xref: /openbsd-src/regress/usr.bin/ssh/unittests/utf8/tests.c (revision fb8aa7497fded39583f40e800732f9c046411717)
1 /*	$OpenBSD: tests.c,v 1.2 2016/05/30 12:05:56 schwarze Exp $ */
2 /*
3  * Regress test for the utf8.h *mprintf() API
4  *
5  * Written by Ingo Schwarze <schwarze@openbsd.org> in 2016
6  * and placed in the public domain.
7  */
8 
9 #include <locale.h>
10 #include <string.h>
11 
12 #include "test_helper.h"
13 
14 #include "utf8.h"
15 
16 void	 badarg(void);
17 void	 one(const char *, const char *, int, int, int, const char *);
18 
19 void
20 badarg(void)
21 {
22 	char	 buf[16];
23 	int	 len, width;
24 
25 	width = 1;
26 	TEST_START("utf8_badarg");
27 	len = snmprintf(buf, sizeof(buf), &width, "\377");
28 	ASSERT_INT_EQ(len, -1);
29 	ASSERT_STRING_EQ(buf, "");
30 	ASSERT_INT_EQ(width, 0);
31 	TEST_DONE();
32 }
33 
34 void
35 one(const char *name, const char *mbs, int width,
36     int wantwidth, int wantlen, const char *wants)
37 {
38 	char	 buf[16];
39 	int	*wp;
40 	int	 len;
41 
42 	if (wantlen == -2)
43 		wantlen = strlen(wants);
44 	(void)strlcpy(buf, "utf8_", sizeof(buf));
45 	(void)strlcat(buf, name, sizeof(buf));
46 	TEST_START(buf);
47 	wp = wantwidth == -2 ? NULL : &width;
48 	len = snmprintf(buf, sizeof(buf), wp, "%s", mbs);
49 	ASSERT_INT_EQ(len, wantlen);
50 	ASSERT_STRING_EQ(buf, wants);
51 	ASSERT_INT_EQ(width, wantwidth);
52 	TEST_DONE();
53 }
54 
55 void
56 tests(void)
57 {
58 	char	*loc;
59 
60 	TEST_START("utf8_setlocale");
61 	loc = setlocale(LC_CTYPE, "en_US.UTF-8");
62 	ASSERT_PTR_NE(loc, NULL);
63 	TEST_DONE();
64 
65 	badarg();
66 	one("null", NULL, 8, 6, 6, "(null)");
67 	one("empty", "", 2, 0, 0, "");
68 	one("ascii", "x", -2, -2, -2, "x");
69 	one("newline", "a\nb", -2, -2, -2, "a\nb");
70 	one("cr", "a\rb", -2, -2, -2, "a\rb");
71 	one("tab", "a\tb", -2, -2, -2, "a\tb");
72 	one("esc", "\033x", -2, -2, -2, "\\033x");
73 	one("inv_badbyte", "\377x", -2, -2, -2, "\\377x");
74 	one("inv_nocont", "\341x", -2, -2, -2, "\\341x");
75 	one("inv_nolead", "a\200b", -2, -2, -2, "a\\200b");
76 	one("sz_ascii", "1234567890123456", -2, -2, 16, "123456789012345");
77 	one("sz_esc", "123456789012\033", -2, -2, 16, "123456789012");
78 	one("width_ascii", "123", 2, 2, -1, "12");
79 	one("width_double", "a\343\201\201", 2, 1, -1, "a");
80 	one("double_fit", "a\343\201\201", 3, 3, 4, "a\343\201\201");
81 	one("double_spc", "a\343\201\201", 4, 3, 4, "a\343\201\201");
82 }
83