blob: e2b43a76ba3f2d56ee7742ccbadc83691056ff21 [file] [log] [blame]
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001#include "test_assert.h"
2
3#include <assert.h>
4
5#ifdef _MSC_VER
6# include <crtdbg.h>
7# include <windows.h>
8#endif
9
10int testing_fails = 0;
11static TestFailEventListener fail_listener_ = nullptr;
12
13void TestFail(const char *expval, const char *val, const char *exp,
14 const char *file, int line, const char *func) {
Austin Schuh272c6132020-11-14 16:37:52 -080015 TEST_OUTPUT_LINE("EXPECTED: \"%s\"", expval);
16 TEST_OUTPUT_LINE("VALUE: \"%s\"", val);
Austin Schuhe89fa2d2019-08-14 20:24:23 -070017 TEST_OUTPUT_LINE("TEST FAILED: %s:%d, %s in %s", file, line, exp,
18 func ? func : "");
19 testing_fails++;
20
21 // Notify, emulate 'gtest::OnTestPartResult' event handler.
22 if (fail_listener_) (*fail_listener_)(expval, val, exp, file, line, func);
23
24 assert(0); // ignored in Release if NDEBUG defined
25}
26
27void TestEqStr(const char *expval, const char *val, const char *exp,
Austin Schuh272c6132020-11-14 16:37:52 -080028 const char *file, int line, const char *func) {
29 if (strcmp(expval, val) != 0) {
30 TestFail(expval, val, exp, file, line, func);
31 }
Austin Schuhe89fa2d2019-08-14 20:24:23 -070032}
33
34#if defined(FLATBUFFERS_MEMORY_LEAK_TRACKING) && defined(_MSC_VER) && \
35 defined(_DEBUG)
Austin Schuh272c6132020-11-14 16:37:52 -080036# define FLATBUFFERS_MEMORY_LEAK_TRACKING_MSVC
Austin Schuhe89fa2d2019-08-14 20:24:23 -070037#endif
38
39void InitTestEngine(TestFailEventListener listener) {
40 testing_fails = 0;
41 // Disable stdout buffering to prevent information lost on assertion or core
42 // dump.
43 setvbuf(stdout, NULL, _IONBF, 0);
44 setvbuf(stderr, NULL, _IONBF, 0);
45
46 flatbuffers::SetupDefaultCRTReportMode();
47
48 // clang-format off
49
50 #if defined(FLATBUFFERS_MEMORY_LEAK_TRACKING_MSVC)
51 // For more thorough checking:
52 // _CRTDBG_DELAY_FREE_MEM_DF | _CRTDBG_CHECK_ALWAYS_DF
53 auto flags = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
54 _CrtSetDbgFlag(flags | _CRTDBG_ALLOC_MEM_DF);
55 #endif
56 // clang-format on
57
58 fail_listener_ = listener;
59}
60
61int CloseTestEngine(bool force_report) {
62 if (!testing_fails || force_report) {
Austin Schuh272c6132020-11-14 16:37:52 -080063#if defined(FLATBUFFERS_MEMORY_LEAK_TRACKING_MSVC)
64 auto flags = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
65 flags &= ~_CRTDBG_DELAY_FREE_MEM_DF;
66 flags |= _CRTDBG_LEAK_CHECK_DF;
67 _CrtSetDbgFlag(flags);
68#endif
Austin Schuhe89fa2d2019-08-14 20:24:23 -070069 }
70 return (0 != testing_fails);
71}