From 4b89aae21f3d0829f4659e977e4293dc51773081 Mon Sep 17 00:00:00 2001 From: Orestis <orestis.malaspinas@pm.me> Date: Sun, 14 Mar 2021 23:17:07 +0100 Subject: [PATCH] started munit stuff --- slides/munit.md | 127 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 127 insertions(+) create mode 100644 slides/munit.md diff --git a/slides/munit.md b/slides/munit.md new file mode 100644 index 0000000..44b39dd --- /dev/null +++ b/slides/munit.md @@ -0,0 +1,127 @@ +--- +title: Framework de tests +date: 2021-03-17 +--- + +# Tests manuels (2/2) + +## Instructions conditionnelles + +Utilisation *d'instruction conditionnelles* pour les tests unitaires: + +```C +void test_add() { // test some add function + if (add(1, -2) != -1) { + printf("Error. Expected %d, Actual %d.\n", + -1, add(1, -2)); + exit(-1); + } +} +int main() { + test_add(); +} +``` + +```bash +$ ./tests +Error. Expected 1, Actual -2. +``` + +**Erreurs détaillées** mais *long à écrire* et *pas généralisable*. + +# Tests manuels (2/2) + +## Assertions + +Utilisation des *assertions* pour les tests unitaires: + +```C +void test_add() { // test some add function + assert(add(1, -2) == -1); +} + +int main() { + test_add(); +} +``` + +Exécution: + +```bash +$ ./tests +tests.c:6: your_function: + Assertion `add(1, -2) == -1' failed. +``` + +*Simple à écrire* et *généralisable* mais **pas détaillé**. + +# Frameworks de tests + +Grand nombre de frameworks: + +* CUnit, <https://sourceforge.net/projects/cunit/> +* Unity, <https://github.com/ThrowTheSwitch/Unity> +* Criterion, <https://github.com/Snaipe/Criterion/> + +Ici on utilisera: + +* $\mu$nit, <https://nemequ.github.io/munit/>, <https://github.com/nemequ/munit> + * Simple à installer, + * Simple à utiliser, + * Erreurs détaillées et général. + +# Petit tuto $\mu$nit + +Structure possible de tests: + +~~~{.mermaid format=png} +graph TD; + lib.h --> lib.o + lib.h --> tests.o + lib.c --> lib.o + tests.c --> tests.o + tests.o --> tests + lib.o --> tests + munit/munit.h --> tests.o + munit/munit.h --> munit.o + munit/munit.c --> munit.o + munit.o --> tests +~~~ + +*Exercice:* Écrire un `Makefile` avec une cible `tests` qui compile et exécute les tests. + +# Utilisation simple + +## Fichier `tests.c` + +```C +#include "munit/munit.h" // inclusion du header munit.h + +int main() { + // Le code vient ici +} +``` + +Mais que mettre dans le code? + +# Les tests les plus simples possibles + +Une grande collection de macros + +```C +#include "munit/munit.h" // inclusion du header munit.h + +int main() { + munit_assert_int(add(1, -2), ==, -1); +} +``` + +```bash +$ ./tests +ERROR> tests.c:5: assertion failed: + add(1, -2) == -1 (-2 == -1) +``` + +Les `munit_assert_TYPE()`{.C} existent en plusieurs saveurs (`char`{.C}, `float`{.C}, ...). + + -- GitLab