File: cppunit_main.cpp.in

package info (click to toggle)
sight 25.1.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 43,252 kB
  • sloc: cpp: 310,629; xml: 17,622; ansic: 9,960; python: 1,379; sh: 144; makefile: 33
file content (322 lines) | stat: -rw-r--r-- 10,044 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
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
/************************************************************************
 *
 * Copyright (C) 2004-2024 IRCAD France
 * Copyright (C) 2012-2020 IHU Strasbourg
 *
 * This file is part of Sight.
 *
 * Sight is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Sight 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
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with Sight. If not, see <https://www.gnu.org/licenses/>.
 *
 ***********************************************************************/

// cspell:ignore NOLINT SEM_NOGPFAULTERRORBOX

#ifdef _WIN32
#include <cstdlib>
#include <windows.h>
#endif

#include <core/log/spy_logger.hpp>
#include <core/runtime/runtime.hpp>

#include <boost/dll/runtime_symbol_info.hpp>

#include <cppunit/BriefTestProgressListener.h>
#include <cppunit/CompilerOutputter.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/TestResult.h>
#include <cppunit/TestResultCollector.h>
#include <cppunit/TestRunner.h>
#include <cppunit/TextTestProgressListener.h>
#include <cppunit/XmlOutputter.h>

#include <filesystem>

struct Options
{
    bool verbose {false};
    bool xmlReport {false};
    bool listTests {false};
    std::string xmlReportFile;
    std::vector<std::string> testsToRun;

    Options() = default;

    //------------------------------------------------------------------------------

    bool parse(const std::vector<char*>& argv)
    {
        if(argv.empty())
        {
            return true;
        }

        const std::string programName(argv[0] != nullptr ? argv[0] : "test_runner");

        auto args    = argv.begin() + 1;
        auto argsEnd = argv.end();
        while(args < argsEnd)
        {
            std::string arg(*args);

            if(arg == "--help" || arg == "-h")
            {
                std::cout
                << "usage : " << programName << " "
                << "[--help|-h] [--verbose|-v] [--xml|-x] [-o FILE] [--list|-l] [test1 ... testN]"
                << std::endl
                << "    -h,--help         Shows this help" << std::endl
                << "    -v,--verbose      Shows each run test name and it status" << std::endl
                << "    -x,--xml          Output results to a xml file" << std::endl
                << "    -o FILE           Specify xml file name" << std::endl
                << "    -l,--list         Lists test names" << std::endl
                << "    test1 ... testN   Test names to run" << std::endl
                << std::endl;
                return false;
            }

            if(arg == "--verbose" || arg == "-v")
            {
                this->verbose = true;
            }
            else if(arg == "--xml" || arg == "-x")
            {
                this->xmlReport = true;
            }
            else if(arg == "-o")
            {
                ++args;
                if(args >= argsEnd)
                {
                    std::cerr << "value for -o is missing" << std::endl;
                    return false;
                }

                this->xmlReportFile = std::string(*args);
            }
            else if(arg == "--list" || arg == "-l")
            {
                this->listTests = true;
            }
            else if(arg == "-B")
            {
                ++args;
                if(args >= argsEnd)
                {
                    std::cerr << "value for -B is missing" << std::endl;
                    return false;
                }

                const std::filesystem::path external_bundle {std::string(*args)};
                if(!std::filesystem::exists(external_bundle) || !std::filesystem::is_directory(external_bundle))
                {
                    std::cerr << "The external module provided in argument is not a consistent directory : "
                    << external_bundle.string() << std::endl;
                    return false;
                }

                sight::core::runtime::add_modules(external_bundle);
            }
            else
            {
                this->testsToRun.push_back(arg);
            }

            ++args;
        }

        return true;
    }
};

//------------------------------------------------------------------------------

void init_log_output()
{
    std::string logFile = "fwTest.log";

    FILE* pFile = fopen(logFile.c_str(), "w");
    if(pFile == nullptr)
    {
        std::error_code err;
        std::filesystem::path sysTmp = std::filesystem::temp_directory_path(err);
        if(err.value() != 0)
        {
            // replace log file appender by stream appender: current dir and temp dir unreachable
            sight::core::log::spy_logger::add_global_console_log();
        }
        else
        {
            // creates fwTest.log in temp directory: current dir unreachable
            sysTmp  = sysTmp / logFile;
            logFile = sysTmp.string();
            sight::core::log::spy_logger::add_global_file_log(logFile);
        }
    }
    else
    {
        // creates fwTest.log in the current directory
        if(fclose(pFile) != 0)
        {
            perror("fclose");
        }

        sight::core::log::spy_logger::add_global_file_log(logFile);
    }
}

//------------------------------------------------------------------------------

void init_runtime()
{
    // This variable is set when configuring this file in the fw_test() CMake macro
    static const std::string moduleName = "@TESTED_MODULE@"; // NOLINT(readability-redundant-string-init)
    if(!moduleName.empty())
    {
        SIGHT_INFO("Automatic loading of module '" + moduleName + "'");
        sight::core::runtime::init();
        const auto lib_location = boost::dll::this_line_location().parent_path().parent_path() / "@TESTED_MODULE_PATH@";
        sight::core::runtime::add_modules(lib_location.string());
        sight::core::runtime::load_module(moduleName);
    }
}

//------------------------------------------------------------------------------

void shutdown_runtime()
{
    // This variable is set when configuring this file in the fw_test() CMake macro
    static const std::string moduleName = "@TESTED_MODULE@"; // NOLINT(readability-redundant-string-init)
    if(!moduleName.empty())
    {
        sight::core::runtime::shutdown();
    }
}

//------------------------------------------------------------------------------

int main(int argc, char* argv[])
{
#ifdef _WIN32
    // This allows to disable debug dialogs on Windows Debug during unit tests.
    // It is especially useful in the CI, where these debug dialogs block the process and causes a
    // timeout, and makes it impossible to find out the problem if physical access isn't possible.
    // The messages are logged in the console instead.
    if(std::getenv("DISABLE_ABORT_DIALOG") != nullptr)
    {
        _set_error_mode(_OUT_TO_STDERR);
        SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX | SEM_NOALIGNMENTFAULTEXCEPT);
        _set_abort_behavior(0, _WRITE_ABORT_MSG);
        _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE);
        _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
        _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE);
        _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR);
    }
#endif

    init_log_output();
    init_runtime();

    Options options;

    const std::string testExecutable = (argc >= 1) ? std::string(argv[0]) : "unknown";
    options.xmlReportFile = testExecutable + "-cppunit-report.xml";

    if(!options.parse(std::vector(argv, argv + argc)))
    {
        return 1;
    }

    CPPUNIT_NS::Test* testSuite = CPPUNIT_NS::TestFactoryRegistry::getRegistry().makeTest();

    if(options.listTests)
    {
        for(int i = 0 ; i < testSuite->getChildTestCount() ; ++i)
        {
            std::cout << testSuite->getChildTestAt(i)->getName() << std::endl;
        }

        return 0;
    }

    // Add the top suite to the test runner
    CPPUNIT_NS::TestRunner runner;
    runner.addTest(testSuite);

    // Create the event manager and test controller
    CPPUNIT_NS::TestResult controller;

    // Add a listener that collects test result
    CPPUNIT_NS::TestResultCollector result;
    controller.addListener(&result);

    // Listener that prints the name of each test before running it.
    CPPUNIT_NS::BriefTestProgressListener BriefProgress;

    // Listener that print dots as test run.
    CPPUNIT_NS::TextTestProgressListener textProgress;

    if(options.verbose)
    {
        controller.addListener(&BriefProgress);
    }
    else
    {
        controller.addListener(&textProgress);
    }

    if(options.testsToRun.empty())
    {
        options.testsToRun.emplace_back();
    }

    for(const std::string& test : options.testsToRun)
    {
        try
        {
            runner.run(controller, test);
        }
        catch(std::exception& e)
        {
            std::cerr << "[" << ((test.empty()) ? "All tests" : test) << "]" << "Error: " << e.what() << std::endl;
            return 1;
        }
        catch(...)
        {
            std::cerr << "[" << ((test.empty()) ? "All tests" : test) << "]" << "Unexpected error. " << std::endl;
            return 1;
        }
    }

    shutdown_runtime();

    // Print test results in a compiler compatible format.
    CPPUNIT_NS::CompilerOutputter outputter(&result, std::cerr);
    outputter.write();

    if(options.xmlReport)
    {
        std::ofstream file(options.xmlReportFile.c_str());
        CPPUNIT_NS::XmlOutputter xml(&result, file);
        xml.write();
        file.close();
    }

    if(result.testFailuresTotal() != 0)
    {
        return 1;
    }

    return 0;
}