unit-test: Add ovstest
[sliver-openvswitch.git] / tests / ovstest.c
1 /*
2  * Copyright (c) 2014 Nicira, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 /* The mother of all test programs that links with libopevswitch.la */
18
19 #include <config.h>
20 #include <inttypes.h>
21 #include <limits.h>
22 #include <stdlib.h>
23 #include "command-line.h"
24 #include "ovstest.h"
25 #include "util.h"
26
27 static struct command *commands = NULL;
28 static size_t n_commands = 0;
29 static size_t allocated_commands = 0;
30
31 static void
32 add_command(struct command *cmd)
33 {
34     const struct command nil = {NULL, 0, 0, NULL};
35
36     while (n_commands + 1 >= allocated_commands) {
37         commands = x2nrealloc(commands, &allocated_commands,
38                               sizeof *cmd);
39     }
40
41     commands[n_commands] = *cmd;
42     commands[n_commands + 1] = nil;
43     n_commands++;
44 }
45
46 static void
47 list(int argc OVS_UNUSED, char *argv[] OVS_UNUSED)
48 {
49     const struct command *p;
50
51     for(p = commands; p->name != NULL; p++) {
52         printf("%s, %d, %d\n", p->name,p->min_args, p->max_args);
53     }
54 }
55
56 static void
57 add_top_level_commands(void)
58 {
59     struct command help_cmd = {"--help", 0, 0, list};
60
61     add_command(&help_cmd);
62 }
63
64 void
65 ovstest_register(const char *test_name, ovstest_func f,
66                   const struct command *sub_commands)
67 {
68     struct command test_cmd;
69     int max_args = 0;
70
71     if (sub_commands) {
72         const struct command *p;
73
74         for(p = sub_commands; p->name != NULL; p++) {
75             if (p->max_args > max_args) {
76                 max_args = p->max_args;
77             }
78         }
79     }
80     max_args++;  /* adding in the sub program */
81
82     test_cmd.name = test_name;
83     test_cmd.min_args = 1;
84     test_cmd.max_args = max_args;
85     test_cmd.handler = f;
86
87     add_command(&test_cmd);
88 }
89
90 static void
91 cleanup(void)
92 {
93     if (allocated_commands) {
94         free(commands);
95     }
96 }
97
98 int
99 main(int argc, char *argv[])
100 {
101     set_program_name(argv[0]);
102
103     add_top_level_commands();
104     if (argc > 1) {
105         run_command(argc - 1, argv + 1, commands);
106     }
107     cleanup();
108
109     return 0;
110 }