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