Debian Codegraph @

src/test/test-clock.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2 /***
3 Copyright © 2016 Canonical Ltd.
4 ***/
5
6 #include <unistd.h>
7
8 #include "clock-util.h"
9 #include "errno-util.h"
10 #include "fd-util.h"
11 #include "fileio.h"
12 #include "log.h"
13 #include "tests.h"
14 #include "tmpfile-util.h"
15
16 TEST(clock_is_localtime) {
17 _cleanup_(unlink_tempfilep) char adjtime[] = "/tmp/test-adjtime.XXXXXX";
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_FALSE(clock_is_localtime("/nonexisting/adjtime"));
43
44 ASSERT_OK(fmkostemp_safe(adjtime, "w", &f));
45 log_info("adjtime test file: %s", adjtime);
46
47 for (size_t i = 0; i < ELEMENTSOF(scenarios); ++i) {
48 log_info("scenario #%zu:, expected result %i", i, scenarios[i].expected_result);
49 log_info("%s", scenarios[i].contents);
50 rewind(f);
51 ASSERT_OK_ERRNO(ftruncate(fileno(f), 0));
52 ASSERT_OK(write_string_stream(f, scenarios[i].contents, WRITE_STRING_FILE_AVOID_NEWLINE));
53 ASSERT_TRUE(clock_is_localtime(adjtime) == scenarios[i].expected_result);
54 }
55 }
56
57 /* Test with the real /etc/adjtime */
58 TEST(clock_is_localtime_system) {
59 int r;
60 r = clock_is_localtime(NULL);
61
62 if (access("/etc/adjtime", R_OK) == 0) {
63 log_info("/etc/adjtime is readable, clock_is_localtime() == %i", r);
64 /* if /etc/adjtime exists we expect some answer, no error or
65 * crash */
66 ASSERT_TRUE(IN_SET(r, 0, 1));
67 } else
68 /* default is UTC if there is no /etc/adjtime */
69 ASSERT_TRUE(r == 0 || ERRNO_IS_PRIVILEGE(r));
70 }
71
72 DEFINE_TEST_MAIN(LOG_INFO);