Read-only mirrors. Development, issues and pull requests are on GitHub.

summaryrefslogtreecommitdiffhomepage
path: root/tests/Progmasoft/Runner.tests.cpp
blob: 66586f7733ad159ec00f3183866c59c4e9df183f (plain)
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
// Copyright (c) 2026 Progmasoft.
// SPDX-License-Identifier: MPL-2.0 WITH AdditionRef-Progmasoft-Exception-2.0

// Starts the runner fixture and checks what the runner made of its tests.

#include "RunnerFixtureClient.hpp"

#include <Progmasoft/Runner/Files.hpp>
#include <Progmasoft/Runner/Json.hpp>
#include <Progmasoft/Runner/Process.hpp>

#include <Progmasoft/Catch3/TestMacros.hpp>
#include <Progmasoft/Catch3/Matchers/String.hpp>

#include <chrono>
#include <cstdlib>
#include <filesystem>
#include <set>
#include <string>
#include <vector>

namespace
{
    namespace Runner = Progmasoft::Catch3::Runner;
    using Catch::Matchers::ContainsSubstring;
    using FixtureClient::ExitCode;
    using FixtureClient::Fixture;
    using FixtureClient::RunFixture;
    using FixtureClient::Scratch;
} // namespace

TEST_CASE("Passing and failing tests get their verdicts", "[progmasoft][runner]")
{
    const Scratch scratch;
    const auto run = RunFixture(scratch, {"--no-history", "[pass],[fail]"});
    INFO(run.output);
    CHECK(ExitCode(run) == 42);
    CHECK(run.report["format"].AsString() == "catch3-run");
    CHECK(run.Test("fixture passes")["outcome"].AsString() == "passed");

    const auto &fails = run.Test("fixture fails");
    CHECK(fails["outcome"].AsString() == "failed");
    CHECK(fails["category"].AsString() == "assertion");
    CHECK_FALSE(fails["flaky"].AsBoolean());
    // A failure in a shared process is tried once more alone.
    CHECK(fails["attempts"].Items().size() == 2);
    const auto &assertion = fails["attempts"].Items().front()["assertions"].Items().front();
    CHECK(assertion["expansion"].AsString() == "2 == 3");
    CHECK(assertion["sections"].Items().front().AsString() == "in a section");

    CHECK(run.Test("fixture throws")["category"].AsString() ==
          "unexpected-exception");

    const auto &prints = run.Test("fixture prints");
    CHECK(prints["outcome"].AsString() == "passed");
    CHECK_THAT(prints["attempts"].Items().front()["standardOutput"].AsString(),
               ContainsSubstring("said through std::cout"));
    CHECK_THAT(run.output, ContainsSubstring("FAIL fixture fails"));
}

TEST_CASE("A crashing test does not take the run with it", "[progmasoft][runner]")
{
    const Scratch scratch;
    const auto run =
        RunFixture(scratch, {"--no-history", "[crash],[pass]", "--jobs=1"});
    INFO(run.output);
    CHECK(ExitCode(run) == 42);
    const auto &crash = run.Test("fixture crashes");
    CHECK(crash["outcome"].AsString() == "crashed");
    CHECK(crash["category"].AsString() == "crash");
    CHECK_THAT(run.Analysis("fixture crashes"),
               ContainsSubstring("in section deep down"));
    // The worker that crashed is replaced; the other tests still ran.
    CHECK(run.Test("fixture passes")["outcome"].AsString() == "passed");
    CHECK(run.Test("fixture prints")["outcome"].AsString() == "passed");
}

TEST_CASE("A hanging test is stopped at its time limit", "[progmasoft][runner]")
{
    const Scratch scratch;
    const auto run =
        RunFixture(scratch, {"--no-history", "--retries=off", "[hang]"});
    INFO(run.output);
    CHECK(ExitCode(run) == 42);
    const auto &hang = run.Test("fixture hangs");
    CHECK(hang["outcome"].AsString() == "timed-out");
    CHECK(hang["category"].AsString() == "timeout");
    CHECK_THAT(hang["attempts"].Items().front()["lastLocation"].AsString(),
               ContainsSubstring("RunnerFixture.cpp"));
    // Well below the 60 s the test sleeps; a slow, busy disk can stretch
    // the runner's own start-up and Git query to half a minute.
    CHECK(run.wall < std::chrono::seconds(50));
}

TEST_CASE("A test that passes on a retry is flaky", "[progmasoft][runner]")
{
    const Scratch scratch;
    const auto run = RunFixture(scratch, {"--no-history", "[flaky]"});
    INFO(run.output);
    CHECK(ExitCode(run) == 0);
    const auto &flaky = run.Test("fixture is flaky");
    CHECK(flaky["outcome"].AsString() == "passed");
    CHECK(flaky["flaky"].AsBoolean());
    CHECK(flaky["attempts"].Items().size() == 2);
    CHECK_THAT(run.output, ContainsSubstring("FLAKY fixture is flaky"));
}

TEST_CASE("The test that leaves state behind is found", "[progmasoft][runner]")
{
    const Scratch scratch;
    const auto run = RunFixture(
        scratch, {"--no-history", "--jobs=1", "--order=declared", "[order]"});
    INFO(run.output);
    CHECK(ExitCode(run) == 42);
    const auto &victim = run.Test("fixture victim");
    CHECK(victim["outcome"].AsString() == "failed");
    CHECK_FALSE(victim["flaky"].AsBoolean());
    CHECK_THAT(run.Analysis("fixture victim"),
               ContainsSubstring("it fails after 'fixture polluter'"));
}

TEST_CASE("A test whose dependency fails is blocked", "[progmasoft][runner]")
{
    const Scratch scratch;
    const auto run = RunFixture(scratch, {"--no-history", "fixture dependent"});
    INFO(run.output);
    CHECK(ExitCode(run) == 42);
    const auto &base = run.Test("fixture base");
    CHECK(base["selectionReason"].AsString() ==
          "needed by 'fixture dependent'");
    const auto &dependent = run.Test("fixture dependent");
    CHECK(dependent["outcome"].AsString() == "blocked");
    CHECK(dependent["attempts"].Items().empty());
    CHECK_THAT(run.Analysis("fixture dependent"),
               ContainsSubstring("depends on 'fixture base', which failed"));
}

TEST_CASE("Every test gets a temporary directory of its own",
          "[progmasoft][runner]")
{
    const Scratch scratch;
    const auto passing = RunFixture(scratch, {"--no-history", "[temp]"});
    INFO(passing.output);
    CHECK(ExitCode(passing) == 0);

    const auto failing = RunFixture(scratch,
                                    {"--no-history", "--retries=off", "[temp]"},
                                    {{"CATCH3_FIXTURE_FAIL_TEMP", "1"}});
    INFO(failing.output);
    CHECK(ExitCode(failing) == 42);
    const std::string kept =
        failing.Test("fixture temporary directory")["attempts"]
            .Items()
            .front()["temporaryDirectory"]
            .AsString();
    REQUIRE_FALSE(kept.empty());
    CHECK(std::filesystem::exists(std::filesystem::path{kept} / "scratch.txt"));
    std::error_code error;
    std::filesystem::remove_all(kept, error);
}

TEST_CASE("Tests run in parallel workers", "[progmasoft][runner]")
{
    const Scratch scratch;
    const auto run = RunFixture(scratch, {"--no-history", "--jobs=4", "[slow]"});
    INFO(run.output);
    CHECK(ExitCode(run) == 0);
    std::set<std::int64_t> workers;
    for (const auto &test : run.report["tests"].Items())
    {
        workers.insert(test["attempts"].Items().front()["worker"].AsInteger());
    }
    CHECK(workers.size() >= 2);
    CHECK(run.report["summary"]["testMicroseconds"].AsInteger() >
          run.report["wallMicroseconds"].AsInteger() / 2);
}

TEST_CASE("Shards split the tests without overlap", "[progmasoft][runner]")
{
    const Scratch scratch;
    std::multiset<std::string> seen;
    for (const char *shard : {"--shard=0/2", "--shard=1/2"})
    {
        const auto run = RunFixture(
            scratch, {"--no-history", "--allow-no-tests", shard, "[slow],[pass]"});
        INFO(run.output);
        CHECK(ExitCode(run) == 0);
        for (const auto &test : run.report["tests"].Items())
        {
            seen.insert(test["name"].AsString());
        }
    }
    CHECK(seen.size() == 6);
    CHECK(std::set<std::string>(seen.begin(), seen.end()).size() == 6);
}

TEST_CASE("History drives quarantine, incremental runs and replay",
          "[progmasoft][runner]")
{
    const Scratch scratch;
    const std::string history = "--history=" + (scratch.Path() / "history").string();

    // Flaky twice in a row: into quarantine.
    for (int run = 0; run < 2; ++run)
    {
        const auto result = RunFixture(scratch, {history, "[alternate]"});
        INFO(result.output);
        CHECK(result.Test("fixture alternates")["flaky"].AsBoolean());
    }
    const auto quarantined = RunFixture(scratch, {history, "[alternate]"});
    INFO(quarantined.output);
    CHECK(quarantined.Test("fixture alternates")["quarantined"].AsBoolean());

    // Passed with the same binary: kept as up to date.
    const auto first = RunFixture(scratch, {history, "--incremental", "[pass]"});
    CHECK(ExitCode(first) == 0);
    const auto second = RunFixture(scratch, {history, "--incremental", "[pass]"});
    INFO(second.output);
    CHECK(ExitCode(second) == 0);
    CHECK(second.Test("fixture passes")["outcome"].AsString() == "up-to-date");

    // Without the search for its cause, a failure that does not repeat
    // alone counts as flaky; the replay runs it in the order it happened,
    // where it fails again, and the search finds the cause.
    const auto failed = RunFixture(
        scratch, {history, "--jobs=1", "--order=declared", "--no-bisect", "[order]"});
    CHECK(ExitCode(failed) == 0);
    CHECK(failed.Test("fixture victim")["flaky"].AsBoolean());
    const auto replay = RunFixture(scratch, {history, "--replay"});
    INFO(replay.output);
    CHECK(ExitCode(replay) == 42);
    CHECK(replay.Test("fixture victim")["outcome"].AsString() == "failed");

    // Analytics read the same history.
    Runner::ChildOptions analytics;
    analytics.arguments = {Fixture(), history, "--analytics=json"};
    auto printed = Runner::RunAndCapture(analytics);
    REQUIRE(printed);
    auto json = Runner::ParseJson(printed->output);
    REQUIRE(json);
    CHECK((*json)["format"].AsString() == "catch3-analytics");
    CHECK((*json)["runs"].AsInteger() >= 6);
}

TEST_CASE("The discovery protocol lists tests with their runner tags",
          "[progmasoft][runner]")
{
    Runner::ChildOptions options;
    options.arguments = {Fixture(), "--list=json", "[deps],[hang]"};
    auto listed = Runner::RunAndCapture(options);
    REQUIRE(listed);
    INFO(listed->output);
    auto json = Runner::ParseJson(listed->output);
    REQUIRE(json);
    CHECK((*json)["format"].AsString() == "catch3-tests");
    CHECK((*json)["version"].AsInteger() == 1);
    REQUIRE((*json)["tests"].Items().size() == 3);
    bool sawDependency = false;
    bool sawTimeout = false;
    for (const auto &test : (*json)["tests"].Items())
    {
        CHECK_THAT(test["file"].AsString(), ContainsSubstring("RunnerFixture.cpp"));
        CHECK(test["line"].AsInteger() > 0);
        sawDependency = sawDependency || (!test["dependsOn"].Items().empty() &&
                                          test["dependsOn"].Items().front().AsString() ==
                                              "fixture base");
        sawTimeout =
            sawTimeout || test["timeoutSeconds"].AsNumber() > 0.5;
    }
    CHECK(sawDependency);
    CHECK(sawTimeout);
}

TEST_CASE("JUnit and trace outputs are written", "[progmasoft][runner]")
{
    const Scratch scratch;
    const auto junit = scratch.Path() / "junit.xml";
    const auto trace = scratch.Path() / "trace.json";
    const auto run = RunFixture(scratch,
                                {"--no-history",
                                 "[pass],[skip]",
                                 "--junit=" + junit.string(),
                                 "--trace=" + trace.string()});
    INFO(run.output);
    CHECK(ExitCode(run) == 0);
    auto xml = Runner::ReadFile(junit);
    REQUIRE(xml);
    CHECK_THAT(*xml, ContainsSubstring("<skipped message=\"skipped\" />"));
    auto traceText = Runner::ReadFile(trace);
    REQUIRE(traceText);
    auto traceJson = Runner::ParseJson(*traceText);
    REQUIRE(traceJson);
    CHECK((*traceJson)["traceEvents"].Items().size() >= 3);
}

TEST_CASE("A child does not inherit the secrets of the runner",
          "[progmasoft][runner]")
{
    CHECK(Runner::IsSecretVariable("GITHUB_TOKEN"));
    CHECK(Runner::IsSecretVariable("aws_secret_access_key"));
    CHECK(Runner::IsSecretVariable("DB_PASSWORD"));
    CHECK(Runner::IsSecretVariable("NPM_ApiKey"));
    CHECK_FALSE(Runner::IsSecretVariable("PATH"));
    CHECK_FALSE(Runner::IsSecretVariable("XAUTHORITY"));

    Runner::ChildOptions options;
#if defined(_WIN32)
    REQUIRE(_putenv_s("CATCH3_TEST_TOKEN", "withheld") == 0);
    REQUIRE(_putenv_s("CATCH3_TEST_PLAIN", "kept") == 0);
    options.arguments = { "cmd.exe", "/d", "/c", "set" };
#else
    REQUIRE(setenv("CATCH3_TEST_TOKEN", "withheld", 1) == 0);
    REQUIRE(setenv("CATCH3_TEST_PLAIN", "kept", 1) == 0);
    options.arguments = { "env" };
#endif
    options.searchPath = true;
    auto printed = Runner::RunAndCapture(options);
    REQUIRE(printed);
    CHECK(printed->output.find("CATCH3_TEST_TOKEN") == std::string::npos);
    CHECK_THAT(printed->output, ContainsSubstring("CATCH3_TEST_PLAIN=kept"));

    options.keptEnvironment = { "CATCH3_TEST_TOKEN" };
    printed = Runner::RunAndCapture(options);
    REQUIRE(printed);
    CHECK_THAT(printed->output,
               ContainsSubstring("CATCH3_TEST_TOKEN=withheld"));
#if defined(_WIN32)
    CHECK(_putenv_s("CATCH3_TEST_TOKEN", "") == 0);
    CHECK(_putenv_s("CATCH3_TEST_PLAIN", "") == 0);
#else
    CHECK(unsetenv("CATCH3_TEST_TOKEN") == 0);
    CHECK(unsetenv("CATCH3_TEST_PLAIN") == 0);
#endif
}