]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/test/test-glob-util.c
tree-wide: drop 'This file is part of systemd' blurb
[thirdparty/systemd.git] / src / test / test-glob-util.c
CommitLineData
53e1b683 1/* SPDX-License-Identifier: LGPL-2.1+ */
6a4f4a0f 2/***
6a4f4a0f 3 Copyright 2010 Lennart Poettering
6a4f4a0f
RC
4***/
5
6#include <fcntl.h>
48d7c648
ZJS
7#include <glob.h>
8#include <sys/stat.h>
6a4f4a0f
RC
9#include <unistd.h>
10
11#include "alloc-util.h"
48d7c648 12#include "dirent-util.h"
6a4f4a0f 13#include "fileio.h"
48d7c648 14#include "fs-util.h"
6a4f4a0f
RC
15#include "glob-util.h"
16#include "macro.h"
48d7c648 17#include "rm-rf.h"
6a4f4a0f
RC
18
19static void test_glob_exists(void) {
20 char name[] = "/tmp/test-glob_exists.XXXXXX";
21 int fd = -1;
22 int r;
23
646853bd 24 fd = mkostemp_safe(name);
6a4f4a0f
RC
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
46dcfbbd 37static void closedir_wrapper(void* v) {
1fe10174
ZJS
38 (void) closedir(v);
39}
40
48d7c648
ZJS
41static 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 = {
46dcfbbd 46 .gl_closedir = closedir_wrapper,
48d7c648
ZJS
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
68static 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
6a4f4a0f
RC
100int main(void) {
101 test_glob_exists();
48d7c648
ZJS
102 test_glob_no_dot();
103 test_safe_glob();
6a4f4a0f
RC
104
105 return 0;
106}