-
Notifications
You must be signed in to change notification settings - Fork 101
Expand file tree
/
Copy pathtestErrorHandling.cpp
More file actions
464 lines (410 loc) · 15.4 KB
/
testErrorHandling.cpp
File metadata and controls
464 lines (410 loc) · 15.4 KB
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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
/*
* ------------------------------------------------------------------------------------------------------------
* SPDX-License-Identifier: LGPL-2.1-only
*
* Copyright (c) 2016-2024 Lawrence Livermore National Security LLC
* Copyright (c) 2018-2024 TotalEnergies
* Copyright (c) 2018-2024 The Board of Trustees of the Leland Stanford Junior University
* Copyright (c) 2023-2024 Chevron
* Copyright (c) 2019- GEOS/GEOSX Contributors
* All rights reserved
*
* See top level LICENSE, COPYRIGHT, CONTRIBUTORS, NOTICE, and ACKNOWLEDGEMENTS files for details.
* ------------------------------------------------------------------------------------------------------------
*/
// forcefully enable asserts macros for this unit test
#include "LvArray/src/system.hpp"
#include "common/logger/ExternalErrorHandler.hpp"
#include "gtest/gtest.h"
#define GEOS_ASSERT_ENABLED
#include "common/logger/ErrorHandling.hpp"
#include "common/logger/Logger.hpp"
#include "dataRepository/DataContext.hpp"
#include "common/initializeEnvironment.hpp"
#include <gtest/gtest.h>
#include <csignal>
#include <filesystem>
#include <signal.h>
using namespace geos;
using namespace dataRepository;
namespace fs = std::filesystem;
// redeging logger instance to test macros with a local instance (to prevent any side effect)
#undef GEOS_GLOBAL_LOGGER
#define GEOS_GLOBAL_LOGGER testErrorLogger
// declare a constant which value is the source file line (to predict the error file output).
#define GET_LINE( lineVar ) static size_t constexpr lineVar = __LINE__
// various dummy test values and contexts
double testMinPrecision = 1e-6;
double testMaxPrecision = 1e-3;
int testValue = 5;
DataFileContext const context = DataFileContext( "Base Test Class", "/path/to/file.xml", 23 );
DataFileContext const additionalContext = DataFileContext( "Additional Test Class", "/path/to/file.xml", 32 );
DataFileContext const importantAdditionalContext = DataFileContext( "Important Additional Test Class", "/path/to/file.xml", 64 );
/**
* @brief begin a test with a local logger
* @param errorLogger local error logger instance
* @param filename output error filename
*/
void beginLocalLoggerTest( ErrorLogger & errorLogger, string_view filename )
{
errorLogger.enableFileOutput( true );
errorLogger.setOutputFilename( filename );
errorLogger.createFile();
}
/**
* @brief end the local logger test by reading the logger file output, comparing it to a reference, and removing it.
* @param errorLogger local error logger instance
* @param expectedFileBits reference file parts that must be in the logger file output
*/
void endLocalLoggerTest( ErrorLogger & errorLogger,
std::vector< string > expectedFileBits )
{
auto const readFile = [] ( string_view filename ) {
if( !fs::exists( filename ))
throw std::runtime_error( "File not found: " + std::string( filename ) );
std::ifstream file{ std::string( filename ) };
if( !file.is_open())
throw std::runtime_error( "Failed to open file: " + std::string( filename ) );
std::stringstream buffer;
std::string line;
while( std::getline( file, line ))
buffer << line << '\n';
return buffer.str();
};
string_view filename = errorLogger.getOutputFilename();
string fileContent = readFile( filename );
bool testFailed = false;
for( size_t i = 0; i < expectedFileBits.size(); ++i )
{
bool const foundFileBit = fileContent.find( expectedFileBits[i] ) != string::npos;
EXPECT_TRUE( foundFileBit ) << "Expected bit not found (no." << i << "):\n"
<< "-----------------------\n"
<< expectedFileBits[i] << '\n'
<< "-----------------------\n";
testFailed |= !foundFileBit;
}
EXPECT_FALSE( testFailed ) << "Generated error file content:\n"
<< "-----------------------\n"
<< fileContent << '\n'
<< "-----------------------\n";
if( fs::exists( filename ) )
fs::remove( filename );
}
TEST( ErrorHandling, testYamlFileWarningOutput )
{
ErrorLogger testErrorLogger;
beginLocalLoggerTest( testErrorLogger, "warningTestOutput.yaml" );
GET_LINE( line1 ); GEOS_WARNING( "Conflicting pressure boundary conditions" );
GET_LINE( line2 ); GEOS_WARNING_IF_GT_MSG( testValue, testMaxPrecision, "Pressure value is too high." );
string const warningMsg = GEOS_FMT( "{}: option should be between {} and {}. A value of {} will be used.",
context.toString(), testMinPrecision, testMaxPrecision, testMinPrecision );
GET_LINE( line3 ); GEOS_WARNING_IF( testValue == 5, warningMsg, context, additionalContext );
endLocalLoggerTest( testErrorLogger, {
R"(errors:)",
GEOS_FMT(
R"(- type: Warning
rank: 0
message: >-
Conflicting pressure boundary conditions
sourceLocation:
file: {}
line: {})",
__FILE__, line1 ),
GEOS_FMT(
R"(- type: Warning
rank: 0
message: >-
Pressure value is too high.
cause: >-
Expected: testValue <= testMaxPrecision
* testValue = 5
* testMaxPrecision = 0.001
sourceLocation:
file: {}
line: {})",
__FILE__, line2 ),
GEOS_FMT(
R"(- type: Warning
rank: 0
message: >-
Base Test Class (file.xml, l.23): option should be between 1e-06 and 0.001. A value of 1e-06 will be used.
contexts:
- priority: 0
description: Base Test Class (file.xml, l.23)
inputFile: /path/to/file.xml
inputLine: 23
- priority: 0
description: Additional Test Class (file.xml, l.32)
inputFile: /path/to/file.xml
inputLine: 32
cause: >-
Warning cause: testValue == 5
sourceLocation:
file: {}
line: {})",
__FILE__, line3 ),
} );
}
TEST( ErrorHandling, testYamlFileExceptionOutput )
{
ErrorLogger testErrorLogger;
string const file = "exceptionTestOutput.yaml";
beginLocalLoggerTest( testErrorLogger, file );
size_t line1;
// Stacked exception test (contexts must appear sorted by priority)
try
{
line1 = __LINE__; GEOS_THROW_IF( testValue == 5, "Empty Group", geos::DomainError, context.getContextInfo().setPriority( 3 ) );
}
catch( geos::DomainError const & ex )
{
string const errorMsg = "Table input error.\n";
testErrorLogger.modifyCurrentExceptionMessage()
.addToMsg( errorMsg )
.addContextInfo( additionalContext.getContextInfo() )
.addContextInfo( importantAdditionalContext.getContextInfo().setPriority( 2 ) );
string const whatExpected = GEOS_FMT( "***** Exception\n"
"***** LOCATION: {}:{}\n"
"***** Error cause: testValue == 5\n"
"***** Rank 0\n"
"***** Message from {}:\n"
"Empty Group",
testErrorLogger.getCurrentExceptionMsg().m_file, line1,
testErrorLogger.getCurrentExceptionMsg().m_contextsInfo.front().m_formattedContext );
GEOS_ERROR_IF_EQ_MSG( string( ex.what()).find( whatExpected ), string::npos,
GEOS_FMT( "The error message was not containing the expected sequence.\n"
" Error message :\n{}"
" expected sequence :\n{}",
ex.what(),
whatExpected ) );
}
testErrorLogger.flushCurrentExceptionMessage();
endLocalLoggerTest( testErrorLogger, {
R"(errors:)",
GEOS_FMT(
R"(- type: Exception
rank: 0
message: >-
Table input error.
Empty Group
contexts:
- priority: 3
description: Base Test Class (file.xml, l.23)
inputFile: /path/to/file.xml
inputLine: 23
- priority: 2
description: Important Additional Test Class (file.xml, l.64)
inputFile: /path/to/file.xml
inputLine: 64
- priority: 0
description: Additional Test Class (file.xml, l.32)
inputFile: /path/to/file.xml
inputLine: 32
cause: >-
Error cause: testValue == 5
sourceLocation:
file: {}
line: {}
sourceCallStack:)",
__FILE__, line1 ),
"- frame0: ",
"- frame1: ",
"- frame2: "
} );
}
TEST( ErrorHandling, testYamlFileErrorOutput )
{
ErrorLogger testErrorLogger;
beginLocalLoggerTest( testErrorLogger, "errorTestOutput.yaml" );
EXPECT_EXIT( GEOS_ERROR_IF_GT_MSG( testValue, testMaxPrecision,
GEOS_FMT( "{}: option should be lower than {}.",
context.toString(), testMaxPrecision ),
context,
additionalContext,
importantAdditionalContext.getContextInfo().setPriority( 2 ) ),
::testing::ExitedWithCode( 1 ),
".*" );
endLocalLoggerTest( testErrorLogger, {
R"(errors:)",
// we won't test the line index for this test as it cannot be a one-liner.
R"(- type: Error
rank: 0
message: >-
Base Test Class (file.xml, l.23): option should be lower than 0.001.
contexts:
- priority: 2
description: Important Additional Test Class (file.xml, l.64)
inputFile: /path/to/file.xml
inputLine: 64
- priority: 0
description: Base Test Class (file.xml, l.23)
inputFile: /path/to/file.xml
inputLine: 23
- priority: 0
description: Additional Test Class (file.xml, l.32)
inputFile: /path/to/file.xml
inputLine: 32
cause: >-
Expected: testValue <= testMaxPrecision
* testValue = 5
* testMaxPrecision = 0.001
sourceLocation:)",
" file: ",
" line: ",
"sourceCallStack:",
"- frame0: ",
"- frame1: ",
"- frame2: "
} );
}
TEST( ErrorHandling, testLogFileExceptionOutput )
{
ErrorLogger testErrorLogger;
size_t line1;
// test that the first context with default priority comes after the most important one, but before
// a second context with default priotity
try
{
line1 = __LINE__; GEOS_THROW_IF( testValue == 5, "Empty Group", geos::DomainError, context );
}
catch( geos::DomainError const & ex )
{
string const errorMsg = "Table input error.\n";
testErrorLogger.modifyCurrentExceptionMessage()
.addToMsg( errorMsg )
.addContextInfo( additionalContext.getContextInfo() )
.addContextInfo( importantAdditionalContext.getContextInfo().setPriority( 2 ));
string const streamExpected = GEOS_FMT(
"***** Exception\n"
"***** LOCATION: {}:{}\n"
"***** {}\n"
"***** Rank 0\n"
"***** Message from {}:\n"
"{}\n"
"***** Additional contexts:\n"
"***** - {}\n"
"***** - {}\n",
testErrorLogger.getCurrentExceptionMsg().m_file, line1,
testErrorLogger.getCurrentExceptionMsg().m_cause,
importantAdditionalContext.toString(),
testErrorLogger.getCurrentExceptionMsg().m_msg,
context.toString(),
additionalContext.toString(),
testErrorLogger.getCurrentExceptionMsg().m_sourceCallStack );
std::ostringstream oss;
ErrorLogger::formatMsgForLog( testErrorLogger.getCurrentExceptionMsg(), oss );
GEOS_ERROR_IF_EQ_MSG( oss.str().find( streamExpected ), string::npos,
GEOS_FMT( "The error message was not containing the expected sequence.\n"
"The error message was not containing the expected sequence.\n"
" Error message :\n{}"
" expected sequence :\n{}",
oss.str(),
streamExpected ) );
}
}
TEST( ErrorHandling, testStdException )
{
ErrorLogger testErrorLogger;
try
{
throw std::invalid_argument( "received negative value" );
}
catch( std::exception & e )
{
testErrorLogger.initCurrentExceptionMessage( MsgType::Exception, e.what(),
::geos::logger::internal::g_rank )
.addCallStackInfo( LvArray::system::stackTrace( true ) );
std::ostringstream oss;
ErrorLogger::formatMsgForLog( testErrorLogger.getCurrentExceptionMsg(), oss );
string const streamExpected = GEOS_FMT(
"***** Exception\n"
"***** Rank 0\n"
"***** Message :\n"
"{}\n",
testErrorLogger.getCurrentExceptionMsg().m_msg );
GEOS_ERROR_IF_EQ_MSG( oss.str().find( streamExpected ), string::npos,
GEOS_FMT( "The error message was not containing the expected sequence.\n"
"The error message was not containing the expected sequence.\n"
" Error message :\n{}"
" expected sequence :\n{}",
oss.str(),
streamExpected ) );
}
}
TEST( ErrorHandling, testYamlFileAssertOutput )
{
ErrorLogger testErrorLogger;
beginLocalLoggerTest( testErrorLogger, "assertTestOutput.yaml" );
EXPECT_EXIT( GEOS_ASSERT_MSG( testValue > testMinPrecision && testValue < testMaxPrecision,
GEOS_FMT( "{}: value should be between {} and {}, but is {}.",
context.toString(), testMinPrecision, testMaxPrecision, testValue ),
context,
additionalContext ),
::testing::ExitedWithCode( 1 ),
".*" );
endLocalLoggerTest( testErrorLogger, {
R"(errors:)",
// we won't test the line index for this test as it cannot be a one-liner.
R"(- type: Error
rank: 0
message: >-
Base Test Class (file.xml, l.23): value should be between 1e-06 and 0.001, but is 5.
contexts:
- priority: 0
description: Base Test Class (file.xml, l.23)
inputFile: /path/to/file.xml
inputLine: 23
- priority: 0
description: Additional Test Class (file.xml, l.32)
inputFile: /path/to/file.xml
inputLine: 32
cause: >-
Expected: testValue > testMinPrecision && testValue < testMaxPrecision
sourceLocation:)",
" file: ",
" line: ",
"sourceCallStack:",
"- frame0: ",
"- frame1: ",
"- frame2: "
} );
}
TEST( ErrorHandling, VerifySignalHandlerLogs )
{
ErrorLogger testErrorLogger;
beginLocalLoggerTest( testErrorLogger, "errors.yaml" );
setupLogger();
bool signalHappened = false;
LvArray::system::setErrorHandler( [&]()
{
endLocalLoggerTest( testErrorLogger, {
R"(- type: ExternalError
rank: 0
message: >-
Signal encountered (no. 2): Interrupt
contexts:
- priority: 0
description: Signal (detected from Signal Handler)
detectionLocation: Signal handler
signal: 2
sourceCallStack:)",
"- frame0: ",
"- frame1: ",
"- frame2: "
} );
signalHappened = true;
} );
ErrorLogger::global().enableFileOutput( true );
std::raise( SIGINT );
EXPECT_TRUE( signalHappened );
setupLogger();
}
int main( int ac, char * av[] )
{
::testing::GTEST_FLAG( death_test_style ) = "threadsafe";
::testing::InitGoogleTest( &ac, av );
geos::setupEnvironment( ac, av );
int const result = RUN_ALL_TESTS();
geos::cleanupEnvironment( );
return result;
}