summaryrefslogtreecommitdiff
path: root/src/mongo/unittest/golden_test_base.cpp
blob: 1544fd3a37bb0a20a2d1dc8ebe4acf0e88a1cbba (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
/**
 *    Copyright (C) 2022-present MongoDB, Inc.
 *
 *    This program is free software: you can redistribute it and/or modify
 *    it under the terms of the Server Side Public License, version 1,
 *    as published by MongoDB, Inc.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    Server Side Public License for more details.
 *
 *    You should have received a copy of the Server Side Public License
 *    along with this program. If not, see
 *    <http://www.mongodb.com/licensing/server-side-public-license>.
 *
 *    As a special exception, the copyright holders give permission to link the
 *    code of portions of this program with the OpenSSL library under certain
 *    conditions as described in each individual source file and distribute
 *    linked combinations including the program with the OpenSSL library. You
 *    must comply with the Server Side Public License in all respects for
 *    all of the code used other than as permitted herein. If you modify file(s)
 *    with this exception, you may extend this exception to your version of the
 *    file(s), but you are not obligated to do so. If you do not wish to do so,
 *    delete this exception statement from your version. If you delete this
 *    exception statement from all source files in the program, then also delete
 *    it in the license file.
 */

#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/iostreams/device/file_descriptor.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/stream_buffer.hpp>
#include <boost/program_options.hpp>
#include <fmt/format.h>
#include <fmt/ostream.h>
#include <yaml-cpp/yaml.h>

#include "mongo/base/init.h"
#include "mongo/base/status.h"
#include "mongo/logv2/log.h"
#include "mongo/unittest/golden_test_base.h"
#include "mongo/util/ctype.h"

#define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kTest

namespace mongo::unittest {

namespace fs = ::boost::filesystem;
namespace po = ::boost::program_options;

using namespace fmt::literals;

std::string readFile(const fs::path& path) {
    uassert(6741506, "path must not be a directory", !is_directory(path));
    uassert(6741505, "path must be a regular file", is_regular_file(path));

    std::ostringstream os;
    os << fs::ifstream(path).rdbuf();
    return os.str();
}

void writeFile(const fs::path& path, const std::string& contents) {
    create_directories(path.parent_path());
    fs::ofstream ofs(path);
    ofs << contents;
}

GoldenTestConfig GoldenTestConfig::parseFromBson(const BSONObj& obj) {
    boost::optional<std::string> relativePath;
    for (auto&& elem : obj) {
        if (elem.fieldNameStringData() == "relativePath"_sd) {
            uassert(6741504,
                    "GoldenTestConfig relativePath must be a string",
                    elem.type() == BSONType::String);
            relativePath = elem.String();
        }
    }
    uassert(6741503, "GoldenTestConfig requires a 'relativePath' argument", relativePath);

    return {*relativePath};
}


GoldenTestEnvironment* GoldenTestEnvironment::getInstance() {
    static GoldenTestEnvironment instance;
    return &instance;
}

GoldenTestEnvironment::GoldenTestEnvironment() : _goldenDataRoot(".") {
    // Parse environment variables
    auto opts = GoldenTestOptions::parseEnvironment();

    fs::path outputRoot;
    if (opts.outputRootPattern) {
        fs::path pattern(*opts.outputRootPattern);
        outputRoot = pattern.parent_path() / fs::unique_path(pattern.leaf());
    } else {
        outputRoot = fs::temp_directory_path() / fs::unique_path("out-%%%%-%%%%-%%%%-%%%%");
    }

    _actualOutputRoot = outputRoot / "actual";
    _expectedOutputRoot = outputRoot / "expected";

    if (opts.diffCmd) {
        _diffCmd = *opts.diffCmd;
    } else {
        // Presumably most (all?) platforms we support have git, including git-diff.
        // git-diff also treats missing files as empty, which is convenient.
        _diffCmd = "git diff --no-index \"{{expected}}\" \"{{actual}}\"";
    }
}

std::string GoldenTestEnvironment::diffCmd(const std::string& expectedOutputFile,
                                           const std::string& actualOutputFile) const {
    std::string cmd = _diffCmd;
    auto replace = [&](const std::string& pattern, const std::string& replacement) {
        size_t n = cmd.find(pattern);
        uassert(6741502,
                str::stream() << "diffCmd '" << _diffCmd << "' did not contain '" << pattern << "'",
                n != std::string::npos);
        cmd.replace(n, pattern.size(), replacement);
    };
    replace("{{expected}}", expectedOutputFile);
    replace("{{actual}}", actualOutputFile);
    return cmd;
}

std::string GoldenTestContextBase::toSnakeCase(const std::string& str) {
    std::string result;
    bool lastAlpha = false;
    for (char c : str) {
        if (ctype::isUpper(c)) {
            if (lastAlpha) {
                result += '_';
            }

            result += ctype::toLower(c);
        } else {
            result += c;
        }

        lastAlpha = ctype::isAlpha(c);
    }

    return result;
}

std::string GoldenTestContextBase::sanitizeName(const std::string& str) {
    for (char c : str) {
        bool valid = c == '_' || c == '-' || ctype::isAlnum(c);
        uassert(6741501, "Unsupported character '{}' in name '{}'"_format(c, str), valid);
    }

    return toSnakeCase(str);
}

void GoldenTestContextBase::verifyOutput() {
    std::string actualStr = getOutputString();

    fs::path goldenDataPath = getGoldenDataPath();
    if (!fs::exists(goldenDataPath)) {
        failResultMismatch(
            actualStr, boost::none, "Golden data file doesn't exist: {}"_format(goldenDataPath));
    }

    std::string expectedStr = readFile(goldenDataPath);
    if (actualStr != expectedStr) {
        failResultMismatch(actualStr,
                           expectedStr,
                           "Actual result doesn't match golden data. "
                           "Run 'buildscripts/golden_test.py diff' for more information.");
    }
}

void GoldenTestContextBase::failResultMismatch(const std::string& actualStr,
                                               const boost::optional<std::string>& expectedStr,
                                               const std::string& message) {
    fs::path actualOutputFilePath = getActualOutputPath();
    fs::path expectedOutputFilePath = getExpectedOutputPath();

    writeFile(actualOutputFilePath, actualStr);

    // Write empty expected file even if the expected result was not set.
    // This improves interaction with diff tools that fail or don't show contents if
    // one of the file is missing.
    writeFile(expectedOutputFilePath, expectedStr.get_value_or(""));

    _onError(message, actualStr, expectedStr);
}

fs::path GoldenTestContextBase::getActualOutputPath() const {
    return _env->actualOutputRoot() / _config->relativePath / getTestPath();
}

fs::path GoldenTestContextBase::getExpectedOutputPath() const {
    return _env->expectedOutputRoot() / _config->relativePath / getTestPath();
}

fs::path GoldenTestContextBase::getGoldenDataPath() const {
    return _env->goldenDataRoot() / _config->relativePath / getTestPath();
}

fs::path GoldenTestContextBase::getTestPath() const {
    return _testPath;
}

GoldenTestOptions GoldenTestOptions::parseEnvironment() {
    GoldenTestOptions opts;
    po::options_description desc_env;
    boost::optional<std::string> configPath;
    desc_env.add_options()  //
        ("config_path",
         po::value<std::string>()->notifier([&configPath](auto v) { configPath = v; }));

    po::variables_map vm_env;
    po::store(po::parse_environment(desc_env, "GOLDEN_TEST_"), vm_env);
    po::notify(vm_env);

    if (configPath) {
        std::string configStr = readFile(*configPath);
        YAML::Node configNode = YAML::Load(configStr);

        YAML::Node outputRootPatternNode = configNode["outputRootPattern"];
        if (outputRootPatternNode && outputRootPatternNode.IsScalar()) {
            opts.outputRootPattern = outputRootPatternNode.as<std::string>();
        }

        YAML::Node diffCmdNode = configNode["diffCmd"];
        if (diffCmdNode && diffCmdNode.IsScalar()) {
            opts.diffCmd = diffCmdNode.as<std::string>();
        }
    }

    return opts;
}

}  // namespace mongo::unittest