]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/test/test-glob-util.c
grypt-util: drop two emacs modelines
[thirdparty/systemd.git] / src / test / test-glob-util.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2 /***
3 Copyright 2010 Lennart Poettering
4 ***/
5
6 #include <fcntl.h>
7 #include <glob.h>
8 #include <sys/stat.h>
9 #include <unistd.h>
10
11 #include "alloc-util.h"
12 #include "dirent-util.h"
13 #include "fileio.h"
14 #include "fs-util.h"
15 #include "glob-util.h"
16 #include "macro.h"
17 #include "rm-rf.h"
18
19 static void test_glob_exists(void) {
20 char name[] = "/tmp/test-glob_exists.XXXXXX";
21 int fd = -1;
22 int r;
23
24 fd = mkostemp_safe(name);
25 assert_se(fd >= 0);
26 close(fd);
27
28 r = glob_exists("/tmp/test-glob_exists*");
29 assert_se(r == 1);
30
31 r = unlink(name);
32 assert_se(r == 0);
33 r = glob_exists("/tmp/test-glob_exists*");
34 assert_se(r == 0);
35 }
36
37 static void closedir_wrapper(void* v) {
38 (void) closedir(v);
39 }
40
41 static void test_glob_no_dot(void) {
42 char template[] = "/tmp/test-glob-util.XXXXXXX";
43 const char *fn;
44
45 _cleanup_globfree_ glob_t g = {
46 .gl_closedir = closedir_wrapper,
47 .gl_readdir = (struct dirent *(*)(void *)) readdir_no_dot,
48 .gl_opendir = (void *(*)(const char *)) opendir,
49 .gl_lstat = lstat,
50 .gl_stat = stat,
51 };
52
53 int r;
54
55 assert_se(mkdtemp(template));
56
57 fn = strjoina(template, "/*");
58 r = glob(fn, GLOB_NOSORT|GLOB_BRACE|GLOB_ALTDIRFUNC, NULL, &g);
59 assert_se(r == GLOB_NOMATCH);
60
61 fn = strjoina(template, "/.*");
62 r = glob(fn, GLOB_NOSORT|GLOB_BRACE|GLOB_ALTDIRFUNC, NULL, &g);
63 assert_se(r == GLOB_NOMATCH);
64
65 (void) rm_rf(template, REMOVE_ROOT|REMOVE_PHYSICAL);
66 }
67
68 static void test_safe_glob(void) {
69 char template[] = "/tmp/test-glob-util.XXXXXXX";
70 const char *fn, *fn2, *fname;
71
72 _cleanup_globfree_ glob_t g = {};
73 int r;
74
75 assert_se(mkdtemp(template));
76
77 fn = strjoina(template, "/*");
78 r = safe_glob(fn, 0, &g);
79 assert_se(r == -ENOENT);
80
81 fn2 = strjoina(template, "/.*");
82 r = safe_glob(fn2, GLOB_NOSORT|GLOB_BRACE, &g);
83 assert_se(r == -ENOENT);
84
85 fname = strjoina(template, "/.foobar");
86 assert_se(touch(fname) == 0);
87
88 r = safe_glob(fn, 0, &g);
89 assert_se(r == -ENOENT);
90
91 r = safe_glob(fn2, GLOB_NOSORT|GLOB_BRACE, &g);
92 assert_se(r == 0);
93 assert_se(g.gl_pathc == 1);
94 assert_se(streq(g.gl_pathv[0], fname));
95 assert_se(g.gl_pathv[1] == NULL);
96
97 (void) rm_rf(template, REMOVE_ROOT|REMOVE_PHYSICAL);
98 }
99
100 int main(void) {
101 test_glob_exists();
102 test_glob_no_dot();
103 test_safe_glob();
104
105 return 0;
106 }