1 /*
2  * libdpkg - Debian packaging suite library routines
3  * t-file.c - test file functions
4  *
5  * Copyright © 2018 Guillem Jover <guillem@debian.org>
6  *
7  * This is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  */
20 
21 #include <config.h>
22 #include <compat.h>
23 
24 #include <dpkg/test.h>
25 #include <dpkg/dpkg.h>
26 #include <dpkg/file.h>
27 
28 #include <sys/types.h>
29 
30 #include <errno.h>
31 #include <unistd.h>
32 #include <stdlib.h>
33 #include <stdio.h>
34 
35 static const char ref_data[] =
36 	"this is a test string\n"
37 	"within a test file\n"
38 	"containing multiple lines\n"
39 ;
40 
41 static void
test_file_slurp(void)42 test_file_slurp(void)
43 {
44 	struct varbuf vb = VARBUF_INIT;
45 	struct dpkg_error err = DPKG_ERROR_INIT;
46 	char *test_file;
47 	char *test_dir;
48 	int fd;
49 
50 	test_pass(file_slurp("/nonexistent", &vb, &err) < 0);
51 	test_pass(vb.used == 0);
52 	test_pass(vb.buf == NULL);
53 	test_pass(err.syserrno == ENOENT);
54 	test_error(err);
55 	varbuf_destroy(&vb);
56 
57 	test_dir = test_alloc(strdup("test.XXXXXX"));
58 	test_pass(mkdtemp(test_dir) != NULL);
59 	test_pass(file_slurp(test_dir, &vb, &err) < 0);
60 	test_pass(vb.used == 0);
61 	test_pass(vb.buf == NULL);
62 	test_pass(err.syserrno == 0);
63 	test_error(err);
64 	varbuf_destroy(&vb);
65 	test_pass(rmdir(test_dir) == 0);
66 
67 	test_file = test_alloc(strdup("test.XXXXXX"));
68 	fd = mkstemp(test_file);
69 	test_pass(fd >= 0);
70 
71 	test_pass(file_slurp(test_file, &vb, &err) == 0);
72 	test_pass(vb.used == 0);
73 	test_pass(vb.buf == NULL);
74 	test_pass(err.syserrno == 0);
75 	test_pass(err.type == DPKG_MSG_NONE);
76 	varbuf_destroy(&vb);
77 
78 	test_pass(write(fd, ref_data, strlen(ref_data)) == (ssize_t)strlen(ref_data));
79 	test_pass(lseek(fd, 0, SEEK_SET) == 0);
80 
81 	test_pass(file_slurp(test_file, &vb, &err) == 0);
82 	test_pass(vb.used == strlen(ref_data));
83 	test_mem(vb.buf, ==, ref_data, min(vb.used, strlen(ref_data)));
84 	test_pass(err.syserrno == 0);
85 	test_pass(err.type == DPKG_MSG_NONE);
86 	varbuf_destroy(&vb);
87 
88 	test_pass(unlink(test_file) == 0);
89 }
90 
TEST_ENTRY(test)91 TEST_ENTRY(test)
92 {
93 	test_plan(26);
94 
95 	test_file_slurp();
96 }
97