1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 | // OK TO COPY / ADAPT any/all of this file if you understand (i.e., at your own risk)
//
// This test is nowhere near adequate on its own. It is provided to illustrate how to
// use helper functions to streamline your test code.
//
// This version requires C11.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "json_c11.h"
#include "miniunit.h"
//#include "clog.h" // only if you wish to use log_yellow(…), etc.
typedef struct {
bool is_success;
union {
Element element;
size_t error_idx;
}; // *** ANONYMOUS union (C11) -- Requires update to .bashrc and/or Makefile
} ParseResult;
ParseResult _parse_json(char* s) {
Element element;
char* pos = s;
bool is_success = parse_element(&element, &pos);
if(is_success) {
return (ParseResult) { .is_success = true, .element = element }; // compound literal
}
else {
return (ParseResult) { .is_success = false, .error_idx = pos - s };
}
}
int test_parse_int() {
mu_start();
//──────────────────────────────────────────────────────
ParseResult result = _parse_json("0");
mu_check(result.is_success);
if(result.is_success) {
mu_check(result.element.type == ELEMENT_INT);
mu_check(result.element.as_int == 0);
free_element(result.element); // should do nothing
}
// TODO: Add more int tests
//──────────────────────────────────────────────────────
mu_end();
}
// TODO: Add lots more test functions, including some that check for failure conditions.
void test_print_element() {
// This uses diff testing, not miniunit.h. Your Makefile probably already does both.
// Otherwise (or if you're not using make), this command should work:
// diff <(./test_json) expected.txt && echo "Test passed: diff" || echo "Test failed: diff"
ParseResult result = _parse_json("1");
print_element(result.element);
fputc('\n', stdout);
// Instead of repeating those 3 lines, create a helper that you can call like this:
//
// _parse_then_print_element("1");
// _parse_then_print_element("0");
// …
//
}
int main(int argc, char* argv[]) {
mu_run(test_parse_int);
// TODO: Call all test_▒▒▒(…) functions that you add above.
test_print_element(); // doesn't use miniunit; put expected output in expected.txt
return EXIT_SUCCESS;
}
/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */
|
© Copyright 2019 Alexander J. Quinn This content is protected and may not be shared, uploaded, or distributed.