Implement str_to_addr() and unit test.
[darkstat] / test_addr.c
1 /* darkstat 3
2 * copyright (c) 2011 Emil Mikulic.
3 *
4 * test_addr.c: tests for addr module
5 *
6 * You may use, modify and redistribute this file under the terms of the
7 * GNU General Public License version 2. (see COPYING.GPL)
8 */
9
10 #include "addr.h"
11
12 #include <netdb.h>
13 #include <stdio.h>
14 #include <string.h>
15
16 void test(const char *in, const char *expect_out, int expect_result)
17 {
18 struct addr a;
19 int success, ret;
20 const char *out;
21
22 success = 1;
23 ret = str_to_addr(in, &a);
24
25 if (ret != expect_result)
26 success = 0;
27
28 if (ret == 0)
29 out = addr_to_str(&a);
30 else
31 out = "(error)";
32
33 if (expect_out && (strcmp(out, expect_out) != 0))
34 success = 0;
35
36 printf("%s:", success ? "PASS" : "FAIL");
37
38 printf(" \"%s\" -> \"%s\"", in, out);
39 if (expect_out && (strcmp(out, expect_out) != 0))
40 printf(" (expected \"%s\")", expect_out);
41
42 if (ret != expect_result)
43 printf(" [ret %d, expected %d]", ret, expect_result);
44
45 if (ret != 0)
46 printf(" [err: %s]", gai_strerror(ret));
47
48 printf("\n");
49 }
50
51 int main()
52 {
53 test("0.0.0.0", "0.0.0.0", 0);
54 test("192.168.1.2", "192.168.1.2", 0);
55
56 test("::", "::", 0);
57 test("::0", "::", 0);
58 test("::00", "::", 0);
59 test("::000", "::", 0);
60 test("::0000", "::", 0);
61
62 test("::1", "::1", 0);
63 test("::01", "::1", 0);
64 test("::001", "::1", 0);
65 test("::0001", "::1", 0);
66
67 test("2404:6800:8004::68", "2404:6800:8004::68", 0);
68 test("2404:6800:8004:0000:0000:0000:0000:0068", "2404:6800:8004::68", 0);
69
70 test(".", NULL, EAI_NONAME);
71 test(":", NULL, EAI_NONAME);
72 test("23.75.345.200", NULL, EAI_NONAME);
73
74 return 0;
75 }
76
77 /* vim:set ts=3 sw=3 tw=78 et: */