File: utils.cpp

package info (click to toggle)
icinga2 2.15.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 20,032 kB
  • sloc: cpp: 97,877; sql: 3,261; cs: 1,636; yacc: 1,584; sh: 1,009; ansic: 890; lex: 420; python: 80; makefile: 62; javascript: 12
file content (67 lines) | stat: -rw-r--r-- 1,708 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/* Icinga 2 | (c) 2025 Icinga GmbH | GPLv2+ */

#include "utils.hpp"
#include <cstring>
#include <iomanip>
#include <sstream>
#include <boost/test/unit_test.hpp>

tm make_tm(std::string s)
{
    int dst = -1;
    size_t l = strlen("YYYY-MM-DD HH:MM:SS");
    if (s.size() > l) {
        std::string zone = s.substr(l);
        if (zone == " PST") {
            dst = 0;
        } else if (zone == " PDT") {
            dst = 1;
        } else {
            // tests should only use PST/PDT (for now)
            BOOST_CHECK_MESSAGE(false, "invalid or unknown time time: " << zone);
        }
    }

    std::tm t = {};
    std::istringstream stream(s);
    stream >> std::get_time(&t, "%Y-%m-%d %H:%M:%S");
    t.tm_isdst = dst;

    return t;
}

#ifndef _WIN32
const char *GlobalTimezoneFixture::TestTimezoneWithDST = "America/Los_Angeles";
#else /* _WIN32 */
// Tests are using pacific time because Windows only really supports timezones following US DST rules with the TZ
// environment variable. Format is "[Standard TZ][negative UTC offset][DST TZ]".
// https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/tzset?view=msvc-160#remarks
const char *GlobalTimezoneFixture::TestTimezoneWithDST = "PST8PDT";
#endif /* _WIN32 */

GlobalTimezoneFixture::GlobalTimezoneFixture(const char *fixed_tz)
{
    tz = getenv("TZ");
#ifdef _WIN32
    _putenv_s("TZ", fixed_tz == "" ? "UTC" : fixed_tz);
#else
    setenv("TZ", fixed_tz, 1);
#endif
    tzset();
}

GlobalTimezoneFixture::~GlobalTimezoneFixture()
{
#ifdef _WIN32
    if (tz)
        _putenv_s("TZ", tz);
    else
        _putenv_s("TZ", "");
#else
    if (tz)
        setenv("TZ", tz, 1);
    else
        unsetenv("TZ");
#endif
    tzset();
}