Line data Source code
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 1 : static void test_clock_is_localtime(void) {
18 1 : _cleanup_(unlink_tempfilep) char adjtime[] = "/tmp/test-adjtime.XXXXXX";
19 1 : _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 1 : assert_se(clock_is_localtime("/nonexisting/adjtime") == 0);
44 :
45 1 : assert_se(fmkostemp_safe(adjtime, "w", &f) == 0);
46 1 : log_info("adjtime test file: %s", adjtime);
47 :
48 10 : for (size_t i = 0; i < ELEMENTSOF(scenarios); ++i) {
49 9 : log_info("scenario #%zu:, expected result %i", i, scenarios[i].expected_result);
50 9 : log_info("%s", scenarios[i].contents);
51 9 : rewind(f);
52 9 : ftruncate(fileno(f), 0);
53 9 : assert_se(write_string_stream(f, scenarios[i].contents, WRITE_STRING_FILE_AVOID_NEWLINE) == 0);
54 9 : assert_se(clock_is_localtime(adjtime) == scenarios[i].expected_result);
55 : }
56 1 : }
57 :
58 : /* Test with the real /etc/adjtime */
59 1 : static void test_clock_is_localtime_system(void) {
60 : int r;
61 1 : r = clock_is_localtime(NULL);
62 :
63 1 : if (access("/etc/adjtime", F_OK) == 0) {
64 1 : log_info("/etc/adjtime exists, clock_is_localtime() == %i", r);
65 : /* if /etc/adjtime exists we expect some answer, no error or
66 : * crash */
67 1 : assert_se(IN_SET(r, 0, 1));
68 : } else
69 : /* default is UTC if there is no /etc/adjtime */
70 0 : assert_se(r == 0);
71 1 : }
72 :
73 1 : int main(int argc, char *argv[]) {
74 1 : test_clock_is_localtime();
75 1 : test_clock_is_localtime_system();
76 :
77 1 : return 0;
78 : }
|