Merge pull request #99 from painless-security/jennifer/count_failed_reqs
[trust_router.git] / mon / tests / test_mon_req_encode.c
1 //
2 // Created by jlr on 4/9/18.
3 //
4
5 #include <talloc.h>
6 #include <jansson.h>
7 #include <assert.h>
8 #include <string.h>
9 #include <glib.h>
10
11 #include <mon_internal.h>
12
13 #define JSON_DUMP_OPTS 0
14
15 static char *show_plain()
16 {
17   MON_REQ *req = mon_req_new(NULL, MON_CMD_SHOW);
18   json_t *req_json = mon_req_encode(req);
19   char *result = json_dumps(req_json, JSON_DUMP_OPTS);
20   assert(req);
21   assert(req_json);
22   assert(result);
23   json_decref(req_json);
24   mon_req_free(req);
25   return result;
26 }
27
28 static char *show_options(const MON_OPT_TYPE *opts)
29 {
30   MON_REQ *req = mon_req_new(NULL, MON_CMD_SHOW);
31   json_t *req_json = NULL;
32   char *result = NULL;
33
34   assert(req);
35
36   while (*opts != OPT_TYPE_UNKNOWN) {
37     assert(MON_SUCCESS == mon_req_add_option(req, *opts));
38     opts++;
39   }
40
41   req_json = mon_req_encode(req);
42   assert(req_json);
43
44   result = json_dumps(req_json, JSON_DUMP_OPTS);
45   assert(result);
46
47   json_decref(req_json);
48   mon_req_free(req);
49   return result;
50 }
51
52 static char *read_file(const char *filename)
53 {
54   FILE *f = fopen(filename, "r");
55   char *s = NULL;
56   size_t nn = 0;
57   ssize_t n = getline(&s, &nn, f);
58   fclose(f);
59
60   if( (n > 0) && (s[n-1] == '\n'))
61     s[n-1] = 0;
62
63   return s;
64 }
65 int main(void)
66 {
67   char *s = NULL;
68   MON_OPT_TYPE opts[10];
69   char *expected = NULL;
70
71   // Test show without options
72   s = show_plain();
73   expected = read_file("req_show_no_options.test");
74   assert(expected);
75   assert(strcmp(expected, s) == 0);
76   free(s);
77   free(expected);
78
79   // Test show with empty options (this mostly tests the test)
80   opts[0] = OPT_TYPE_UNKNOWN;
81   s = show_options(opts);
82   expected = read_file("req_show_no_options.test");
83   assert(expected);
84   assert(strcmp(expected, s) == 0);
85   free(s);
86   free(expected);
87
88   // Test show with many options
89   opts[0] = OPT_TYPE_SHOW_CONFIG_FILES;
90   opts[1] = OPT_TYPE_SHOW_VERSION;
91   opts[2] = OPT_TYPE_SHOW_UPTIME;
92   opts[3] = OPT_TYPE_SHOW_TID_REQS_PROCESSED;
93   opts[4] = OPT_TYPE_SHOW_TID_REQS_PENDING;
94   opts[5] = OPT_TYPE_SHOW_ROUTES;
95   opts[6] = OPT_TYPE_SHOW_COMMUNITIES;
96   opts[7] = OPT_TYPE_UNKNOWN;
97   s = show_options(opts);
98   expected = read_file("req_show_all_options.test");
99   assert(expected);
100   assert(strcmp(expected, s) == 0);
101   free(s);
102   free(expected);
103
104   return 0;
105 }