]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/test/test-clock.c
e5a3de8a59a65bdf7a7872cad052efdf507a8539
[thirdparty/systemd.git] / src / test / test-clock.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
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 "tmpfile-util.h"
16
17 static void test_clock_is_localtime(void) {
18 _cleanup_(unlink_tempfilep) char adjtime[] = "/tmp/test-adjtime.XXXXXX";
19 _cleanup_fclose_ FILE* f = NULL;
20
21 static const struct scenario {
22 const char* contents;
23 int expected_result;
24 } scenarios[] = {
25 /* adjtime configures UTC */
26 {"0.0 0 0\n0\nUTC\n", 0},
27 /* adjtime configures local time */
28 {"0.0 0 0\n0\nLOCAL\n", 1},
29 /* no final EOL */
30 {"0.0 0 0\n0\nUTC", 0},
31 {"0.0 0 0\n0\nLOCAL", 1},
32 /* empty value -> defaults to UTC */
33 {"0.0 0 0\n0\n", 0},
34 /* unknown value -> defaults to UTC */
35 {"0.0 0 0\n0\nFOO\n", 0},
36 /* no third line */
37 {"0.0 0 0", 0},
38 {"0.0 0 0\n", 0},
39 {"0.0 0 0\n0", 0},
40 };
41
42 /* without an adjtime file we default to UTC */
43 assert_se(clock_is_localtime("/nonexisting/adjtime") == 0);
44
45 assert_se(fmkostemp_safe(adjtime, "w", &f) == 0);
46 log_info("adjtime test file: %s", adjtime);
47
48 for (size_t i = 0; i < ELEMENTSOF(scenarios); ++i) {
49 log_info("scenario #%zu:, expected result %i", i, scenarios[i].expected_result);
50 log_info("%s", scenarios[i].contents);
51 rewind(f);
52 ftruncate(fileno(f), 0);
53 assert_se(write_string_stream(f, scenarios[i].contents, WRITE_STRING_FILE_AVOID_NEWLINE) == 0);
54 assert_se(clock_is_localtime(adjtime) == scenarios[i].expected_result);
55 }
56 }
57
58 /* Test with the real /etc/adjtime */
59 static void test_clock_is_localtime_system(void) {
60 int r;
61 r = clock_is_localtime(NULL);
62
63 if (access("/etc/adjtime", R_OK) == 0) {
64 log_info("/etc/adjtime is readable, clock_is_localtime() == %i", r);
65 /* if /etc/adjtime exists we expect some answer, no error or
66 * crash */
67 assert_se(IN_SET(r, 0, 1));
68 } else
69 /* default is UTC if there is no /etc/adjtime */
70 assert_se(r == 0 || ERRNO_IS_PRIVILEGE(r));
71 }
72
73 int main(int argc, char *argv[]) {
74 test_clock_is_localtime();
75 test_clock_is_localtime_system();
76
77 return 0;
78 }