]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/test/test-clock.c
license: LGPL-2.1+ -> LGPL-2.1-or-later
[thirdparty/systemd.git] / src / test / test-clock.c
CommitLineData
db9ecf05 1/* SPDX-License-Identifier: LGPL-2.1-or-later */
6369641d 2/***
810adae9 3 Copyright © 2016 Canonical Ltd.
6369641d
MP
4***/
5
6#include <unistd.h>
7#include <fcntl.h>
8
fe4f8fd1
ZJS
9#include "clock-util.h"
10#include "fd-util.h"
6369641d 11#include "fileio.h"
d8351049 12#include "fs-util.h"
6369641d 13#include "log.h"
fe4f8fd1 14#include "macro.h"
e4de7287 15#include "tmpfile-util.h"
6369641d
MP
16
17static void test_clock_is_localtime(void) {
75e7d50e 18 _cleanup_(unlink_tempfilep) char adjtime[] = "/tmp/test-adjtime.XXXXXX";
07edd3b9 19 _cleanup_fclose_ FILE* f = NULL;
6369641d 20
fe4f8fd1 21 static const struct scenario {
6369641d
MP
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},
35f7216f
MP
32 /* empty value -> defaults to UTC */
33 {"0.0 0 0\n0\n", 0},
6369641d
MP
34 /* unknown value -> defaults to UTC */
35 {"0.0 0 0\n0\nFOO\n", 0},
35f7216f
MP
36 /* no third line */
37 {"0.0 0 0", 0},
38 {"0.0 0 0\n", 0},
39 {"0.0 0 0\n0", 0},
6369641d
MP
40 };
41
42 /* without an adjtime file we default to UTC */
43 assert_se(clock_is_localtime("/nonexisting/adjtime") == 0);
44
d8351049 45 assert_se(fmkostemp_safe(adjtime, "w", &f) == 0);
6369641d 46 log_info("adjtime test file: %s", adjtime);
6369641d
MP
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);
c8f12abc 52 assert_se(ftruncate(fileno(f), 0) == 0);
b1837133 53 assert_se(write_string_stream(f, scenarios[i].contents, WRITE_STRING_FILE_AVOID_NEWLINE) == 0);
6369641d
MP
54 assert_se(clock_is_localtime(adjtime) == scenarios[i].expected_result);
55 }
6369641d
MP
56}
57
58/* Test with the real /etc/adjtime */
59static void test_clock_is_localtime_system(void) {
60 int r;
61 r = clock_is_localtime(NULL);
62
3c14dc61
TM
63 if (access("/etc/adjtime", R_OK) == 0) {
64 log_info("/etc/adjtime is readable, clock_is_localtime() == %i", r);
35f7216f
MP
65 /* if /etc/adjtime exists we expect some answer, no error or
66 * crash */
4c701096 67 assert_se(IN_SET(r, 0, 1));
6369641d
MP
68 } else
69 /* default is UTC if there is no /etc/adjtime */
3c14dc61 70 assert_se(r == 0 || ERRNO_IS_PRIVILEGE(r));
6369641d
MP
71}
72
73int main(int argc, char *argv[]) {
74 test_clock_is_localtime();
75 test_clock_is_localtime_system();
76
77 return 0;
78}