]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/test/test-clock.c
Merge pull request #32588 from CodethinkLabs/mkosi-selinux
[thirdparty/systemd.git] / src / test / test-clock.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2 /***
3 Copyright © 2016 Canonical Ltd.
4 ***/
5
6 #include <unistd.h>
7 #include <fcntl.h>
8
9 #include "clock-util.h"
10 #include "fd-util.h"
11 #include "fileio.h"
12 #include "fs-util.h"
13 #include "log.h"
14 #include "macro.h"
15 #include "tests.h"
16 #include "tmpfile-util.h"
17
18 TEST(clock_is_localtime) {
19 _cleanup_(unlink_tempfilep) char adjtime[] = "/tmp/test-adjtime.XXXXXX";
20 _cleanup_fclose_ FILE* f = NULL;
21
22 static const struct scenario {
23 const char* contents;
24 int expected_result;
25 } scenarios[] = {
26 /* adjtime configures UTC */
27 {"0.0 0 0\n0\nUTC\n", 0},
28 /* adjtime configures local time */
29 {"0.0 0 0\n0\nLOCAL\n", 1},
30 /* no final EOL */
31 {"0.0 0 0\n0\nUTC", 0},
32 {"0.0 0 0\n0\nLOCAL", 1},
33 /* empty value -> defaults to UTC */
34 {"0.0 0 0\n0\n", 0},
35 /* unknown value -> defaults to UTC */
36 {"0.0 0 0\n0\nFOO\n", 0},
37 /* no third line */
38 {"0.0 0 0", 0},
39 {"0.0 0 0\n", 0},
40 {"0.0 0 0\n0", 0},
41 };
42
43 /* without an adjtime file we default to UTC */
44 assert_se(clock_is_localtime("/nonexisting/adjtime") == 0);
45
46 assert_se(fmkostemp_safe(adjtime, "w", &f) == 0);
47 log_info("adjtime test file: %s", adjtime);
48
49 for (size_t i = 0; i < ELEMENTSOF(scenarios); ++i) {
50 log_info("scenario #%zu:, expected result %i", i, scenarios[i].expected_result);
51 log_info("%s", scenarios[i].contents);
52 rewind(f);
53 assert_se(ftruncate(fileno(f), 0) == 0);
54 assert_se(write_string_stream(f, scenarios[i].contents, WRITE_STRING_FILE_AVOID_NEWLINE) == 0);
55 assert_se(clock_is_localtime(adjtime) == scenarios[i].expected_result);
56 }
57 }
58
59 /* Test with the real /etc/adjtime */
60 TEST(clock_is_localtime_system) {
61 int r;
62 r = clock_is_localtime(NULL);
63
64 if (access("/etc/adjtime", R_OK) == 0) {
65 log_info("/etc/adjtime is readable, clock_is_localtime() == %i", r);
66 /* if /etc/adjtime exists we expect some answer, no error or
67 * crash */
68 assert_se(IN_SET(r, 0, 1));
69 } else
70 /* default is UTC if there is no /etc/adjtime */
71 assert_se(r == 0 || ERRNO_IS_PRIVILEGE(r));
72 }
73
74 DEFINE_TEST_MAIN(LOG_INFO);