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