]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/test/test-clock.c
tree-wide: drop 'This file is part of systemd' blurb
[thirdparty/systemd.git] / src / test / test-clock.c
CommitLineData
53e1b683 1/* SPDX-License-Identifier: LGPL-2.1+ */
6369641d 2/***
6369641d 3 Copyright (C) 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
MP
11#include "fileio.h"
12#include "log.h"
fe4f8fd1 13#include "macro.h"
6369641d
MP
14
15static void test_clock_is_localtime(void) {
16 char adjtime[] = "/tmp/test-adjtime.XXXXXX";
07edd3b9
MP
17 int fd = -1;
18 _cleanup_fclose_ FILE* f = NULL;
6369641d 19
fe4f8fd1 20 static const struct scenario {
6369641d
MP
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},
35f7216f
MP
31 /* empty value -> defaults to UTC */
32 {"0.0 0 0\n0\n", 0},
6369641d
MP
33 /* unknown value -> defaults to UTC */
34 {"0.0 0 0\n0\nFOO\n", 0},
35f7216f
MP
35 /* no third line */
36 {"0.0 0 0", 0},
37 {"0.0 0 0\n", 0},
38 {"0.0 0 0\n0", 0},
6369641d
MP
39 };
40
41 /* without an adjtime file we default to UTC */
42 assert_se(clock_is_localtime("/nonexisting/adjtime") == 0);
43
646853bd 44 fd = mkostemp_safe(adjtime);
d69d951b 45 assert_se(fd >= 0);
6369641d
MP
46 log_info("adjtime test file: %s", adjtime);
47 f = fdopen(fd, "w");
d69d951b 48 assert_se(f);
6369641d
MP
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);
b1837133 55 assert_se(write_string_stream(f, scenarios[i].contents, WRITE_STRING_FILE_AVOID_NEWLINE) == 0);
6369641d
MP
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 */
63static 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);
35f7216f
MP
69 /* if /etc/adjtime exists we expect some answer, no error or
70 * crash */
4c701096 71 assert_se(IN_SET(r, 0, 1));
6369641d
MP
72 } else
73 /* default is UTC if there is no /etc/adjtime */
d69d951b 74 assert_se(r == 0);
6369641d
MP
75}
76
77int main(int argc, char *argv[]) {
78 test_clock_is_localtime();
79 test_clock_is_localtime_system();
80
81 return 0;
82}