blob: 2f9ce2d5646dd3d4b29fb35b17d4ba6c8c07438d [file] [log] [blame]
Lang Hamesf7f6d3e2016-03-16 01:02:46 +00001//===----- unittests/ErrorTest.cpp - Error.h tests ------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "llvm/Support/Error.h"
Lang Hamesc5e0bbd2016-05-27 01:37:32 +000011
12#include "llvm/ADT/Twine.h"
Lang Hamesf7f6d3e2016-03-16 01:02:46 +000013#include "llvm/Support/Errc.h"
Lang Hamese7aad352016-03-23 23:57:28 +000014#include "llvm/Support/ErrorHandling.h"
Pavel Labathe8354fe2017-12-07 10:54:23 +000015#include "llvm/Testing/Support/Error.h"
16#include "gtest/gtest-spi.h"
Lang Hamesf7f6d3e2016-03-16 01:02:46 +000017#include "gtest/gtest.h"
18#include <memory>
19
20using namespace llvm;
21
22namespace {
23
Lang Hamesf7f6d3e2016-03-16 01:02:46 +000024// Custom error class with a default base class and some random 'info' attached.
25class CustomError : public ErrorInfo<CustomError> {
26public:
27 // Create an error with some info attached.
28 CustomError(int Info) : Info(Info) {}
29
30 // Get the info attached to this error.
31 int getInfo() const { return Info; }
32
33 // Log this error to a stream.
34 void log(raw_ostream &OS) const override {
Sam McCall8ca99102018-07-06 05:45:45 +000035 OS << "CustomError {" << getInfo() << "}";
Lang Hamesf7f6d3e2016-03-16 01:02:46 +000036 }
37
Lang Hamese7aad352016-03-23 23:57:28 +000038 std::error_code convertToErrorCode() const override {
39 llvm_unreachable("CustomError doesn't support ECError conversion");
40 }
41
Reid Klecknera15b76b2016-03-24 23:49:34 +000042 // Used by ErrorInfo::classID.
43 static char ID;
44
Lang Hamesf7f6d3e2016-03-16 01:02:46 +000045protected:
46 // This error is subclassed below, but we can't use inheriting constructors
47 // yet, so we can't propagate the constructors through ErrorInfo. Instead
48 // we have to have a default constructor and have the subclass initialize all
49 // fields.
50 CustomError() : Info(0) {}
51
52 int Info;
53};
54
Reid Klecknera15b76b2016-03-24 23:49:34 +000055char CustomError::ID = 0;
56
Lang Hamesf7f6d3e2016-03-16 01:02:46 +000057// Custom error class with a custom base class and some additional random
58// 'info'.
59class CustomSubError : public ErrorInfo<CustomSubError, CustomError> {
60public:
61 // Create a sub-error with some info attached.
62 CustomSubError(int Info, int ExtraInfo) : ExtraInfo(ExtraInfo) {
63 this->Info = Info;
64 }
65
66 // Get the extra info attached to this error.
67 int getExtraInfo() const { return ExtraInfo; }
68
69 // Log this error to a stream.
70 void log(raw_ostream &OS) const override {
71 OS << "CustomSubError { " << getInfo() << ", " << getExtraInfo() << "}";
72 }
73
Lang Hamese7aad352016-03-23 23:57:28 +000074 std::error_code convertToErrorCode() const override {
75 llvm_unreachable("CustomSubError doesn't support ECError conversion");
76 }
77
Reid Klecknera15b76b2016-03-24 23:49:34 +000078 // Used by ErrorInfo::classID.
79 static char ID;
80
Lang Hamesf7f6d3e2016-03-16 01:02:46 +000081protected:
82 int ExtraInfo;
83};
84
Reid Klecknera15b76b2016-03-24 23:49:34 +000085char CustomSubError::ID = 0;
86
Mehdi Amini41af4302016-11-11 04:28:40 +000087static Error handleCustomError(const CustomError &CE) {
88 return Error::success();
89}
Lang Hamesf7f6d3e2016-03-16 01:02:46 +000090
91static void handleCustomErrorVoid(const CustomError &CE) {}
92
93static Error handleCustomErrorUP(std::unique_ptr<CustomError> CE) {
Mehdi Amini41af4302016-11-11 04:28:40 +000094 return Error::success();
Lang Hamesf7f6d3e2016-03-16 01:02:46 +000095}
96
97static void handleCustomErrorUPVoid(std::unique_ptr<CustomError> CE) {}
98
Lang Hames01864a22016-03-18 00:12:37 +000099// Test that success values implicitly convert to false, and don't cause crashes
100// once they've been implicitly converted.
101TEST(Error, CheckedSuccess) {
Mehdi Aminic1edf562016-11-11 04:29:25 +0000102 Error E = Error::success();
Lang Hames01864a22016-03-18 00:12:37 +0000103 EXPECT_FALSE(E) << "Unexpected error while testing Error 'Success'";
104}
105
106// Test that unchecked succes values cause an abort.
Mehdi Aminicb79c072016-11-30 19:08:41 +0000107#if LLVM_ENABLE_ABI_BREAKING_CHECKS
Lang Hames01864a22016-03-18 00:12:37 +0000108TEST(Error, UncheckedSuccess) {
Mehdi Aminic1edf562016-11-11 04:29:25 +0000109 EXPECT_DEATH({ Error E = Error::success(); },
110 "Program aborted due to an unhandled Error:")
Lang Hames01864a22016-03-18 00:12:37 +0000111 << "Unchecked Error Succes value did not cause abort()";
112}
113#endif
114
Lang Hamesd1af8fc2016-03-25 23:54:32 +0000115// ErrorAsOutParameter tester.
116void errAsOutParamHelper(Error &Err) {
Lang Hames5e51a2e2016-07-22 16:11:25 +0000117 ErrorAsOutParameter ErrAsOutParam(&Err);
Lang Hamesd1af8fc2016-03-25 23:54:32 +0000118 // Verify that checked flag is raised - assignment should not crash.
119 Err = Error::success();
120 // Raise the checked bit manually - caller should still have to test the
121 // error.
122 (void)!!Err;
Lang Hamesd0ac31a2016-03-25 21:56:35 +0000123}
124
Lang Hamesd1af8fc2016-03-25 23:54:32 +0000125// Test that ErrorAsOutParameter sets the checked flag on construction.
126TEST(Error, ErrorAsOutParameterChecked) {
Mehdi Aminic1edf562016-11-11 04:29:25 +0000127 Error E = Error::success();
Lang Hamesd1af8fc2016-03-25 23:54:32 +0000128 errAsOutParamHelper(E);
129 (void)!!E;
130}
131
132// Test that ErrorAsOutParameter clears the checked flag on destruction.
Mehdi Aminicb79c072016-11-30 19:08:41 +0000133#if LLVM_ENABLE_ABI_BREAKING_CHECKS
Lang Hamesd1af8fc2016-03-25 23:54:32 +0000134TEST(Error, ErrorAsOutParameterUnchecked) {
Mehdi Aminic1edf562016-11-11 04:29:25 +0000135 EXPECT_DEATH({ Error E = Error::success(); errAsOutParamHelper(E); },
Lang Hamesd1af8fc2016-03-25 23:54:32 +0000136 "Program aborted due to an unhandled Error:")
137 << "ErrorAsOutParameter did not clear the checked flag on destruction.";
138}
139#endif
140
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000141// Check that we abort on unhandled failure cases. (Force conversion to bool
142// to make sure that we don't accidentally treat checked errors as handled).
143// Test runs in debug mode only.
Mehdi Aminicb79c072016-11-30 19:08:41 +0000144#if LLVM_ENABLE_ABI_BREAKING_CHECKS
Lang Hames01864a22016-03-18 00:12:37 +0000145TEST(Error, UncheckedError) {
146 auto DropUnhandledError = []() {
147 Error E = make_error<CustomError>(42);
148 (void)!E;
149 };
150 EXPECT_DEATH(DropUnhandledError(),
151 "Program aborted due to an unhandled Error:")
152 << "Unhandled Error failure value did not cause abort()";
153}
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000154#endif
155
Lang Hames01864a22016-03-18 00:12:37 +0000156// Check 'Error::isA<T>' method handling.
157TEST(Error, IsAHandling) {
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000158 // Check 'isA' handling.
Lang Hames01864a22016-03-18 00:12:37 +0000159 Error E = make_error<CustomError>(1);
160 Error F = make_error<CustomSubError>(1, 2);
161 Error G = Error::success();
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000162
Lang Hames01864a22016-03-18 00:12:37 +0000163 EXPECT_TRUE(E.isA<CustomError>());
164 EXPECT_FALSE(E.isA<CustomSubError>());
165 EXPECT_TRUE(F.isA<CustomError>());
166 EXPECT_TRUE(F.isA<CustomSubError>());
167 EXPECT_FALSE(G.isA<CustomError>());
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000168
Lang Hames01864a22016-03-18 00:12:37 +0000169 consumeError(std::move(E));
170 consumeError(std::move(F));
171 consumeError(std::move(G));
172}
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000173
Lang Hames01864a22016-03-18 00:12:37 +0000174// Check that we can handle a custom error.
175TEST(Error, HandleCustomError) {
176 int CaughtErrorInfo = 0;
177 handleAllErrors(make_error<CustomError>(42), [&](const CustomError &CE) {
178 CaughtErrorInfo = CE.getInfo();
179 });
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000180
Lang Hames01864a22016-03-18 00:12:37 +0000181 EXPECT_TRUE(CaughtErrorInfo == 42) << "Wrong result from CustomError handler";
182}
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000183
Lang Hames01864a22016-03-18 00:12:37 +0000184// Check that handler type deduction also works for handlers
185// of the following types:
186// void (const Err&)
187// Error (const Err&) mutable
188// void (const Err&) mutable
189// Error (Err&)
190// void (Err&)
191// Error (Err&) mutable
192// void (Err&) mutable
193// Error (unique_ptr<Err>)
194// void (unique_ptr<Err>)
195// Error (unique_ptr<Err>) mutable
196// void (unique_ptr<Err>) mutable
197TEST(Error, HandlerTypeDeduction) {
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000198
199 handleAllErrors(make_error<CustomError>(42), [](const CustomError &CE) {});
200
201 handleAllErrors(
202 make_error<CustomError>(42),
Mehdi Aminic1edf562016-11-11 04:29:25 +0000203 [](const CustomError &CE) mutable -> Error { return Error::success(); });
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000204
205 handleAllErrors(make_error<CustomError>(42),
206 [](const CustomError &CE) mutable {});
207
208 handleAllErrors(make_error<CustomError>(42),
Mehdi Aminic1edf562016-11-11 04:29:25 +0000209 [](CustomError &CE) -> Error { return Error::success(); });
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000210
211 handleAllErrors(make_error<CustomError>(42), [](CustomError &CE) {});
212
213 handleAllErrors(make_error<CustomError>(42),
Mehdi Aminic1edf562016-11-11 04:29:25 +0000214 [](CustomError &CE) mutable -> Error { return Error::success(); });
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000215
216 handleAllErrors(make_error<CustomError>(42), [](CustomError &CE) mutable {});
217
218 handleAllErrors(
219 make_error<CustomError>(42),
Mehdi Aminic1edf562016-11-11 04:29:25 +0000220 [](std::unique_ptr<CustomError> CE) -> Error { return Error::success(); });
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000221
222 handleAllErrors(make_error<CustomError>(42),
223 [](std::unique_ptr<CustomError> CE) {});
224
225 handleAllErrors(
226 make_error<CustomError>(42),
Mehdi Aminic1edf562016-11-11 04:29:25 +0000227 [](std::unique_ptr<CustomError> CE) mutable -> Error { return Error::success(); });
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000228
229 handleAllErrors(make_error<CustomError>(42),
230 [](std::unique_ptr<CustomError> CE) mutable {});
231
232 // Check that named handlers of type 'Error (const Err&)' work.
233 handleAllErrors(make_error<CustomError>(42), handleCustomError);
234
235 // Check that named handlers of type 'void (const Err&)' work.
236 handleAllErrors(make_error<CustomError>(42), handleCustomErrorVoid);
237
238 // Check that named handlers of type 'Error (std::unique_ptr<Err>)' work.
239 handleAllErrors(make_error<CustomError>(42), handleCustomErrorUP);
240
241 // Check that named handlers of type 'Error (std::unique_ptr<Err>)' work.
242 handleAllErrors(make_error<CustomError>(42), handleCustomErrorUPVoid);
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000243}
244
Lang Hames01864a22016-03-18 00:12:37 +0000245// Test that we can handle errors with custom base classes.
246TEST(Error, HandleCustomErrorWithCustomBaseClass) {
247 int CaughtErrorInfo = 0;
248 int CaughtErrorExtraInfo = 0;
249 handleAllErrors(make_error<CustomSubError>(42, 7),
250 [&](const CustomSubError &SE) {
251 CaughtErrorInfo = SE.getInfo();
252 CaughtErrorExtraInfo = SE.getExtraInfo();
253 });
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000254
Lang Hames01864a22016-03-18 00:12:37 +0000255 EXPECT_TRUE(CaughtErrorInfo == 42 && CaughtErrorExtraInfo == 7)
256 << "Wrong result from CustomSubError handler";
257}
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000258
Lang Hames01864a22016-03-18 00:12:37 +0000259// Check that we trigger only the first handler that applies.
260TEST(Error, FirstHandlerOnly) {
261 int DummyInfo = 0;
262 int CaughtErrorInfo = 0;
263 int CaughtErrorExtraInfo = 0;
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000264
Lang Hames01864a22016-03-18 00:12:37 +0000265 handleAllErrors(make_error<CustomSubError>(42, 7),
266 [&](const CustomSubError &SE) {
267 CaughtErrorInfo = SE.getInfo();
268 CaughtErrorExtraInfo = SE.getExtraInfo();
269 },
270 [&](const CustomError &CE) { DummyInfo = CE.getInfo(); });
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000271
Lang Hames01864a22016-03-18 00:12:37 +0000272 EXPECT_TRUE(CaughtErrorInfo == 42 && CaughtErrorExtraInfo == 7 &&
273 DummyInfo == 0)
274 << "Activated the wrong Error handler(s)";
275}
276
277// Check that general handlers shadow specific ones.
278TEST(Error, HandlerShadowing) {
279 int CaughtErrorInfo = 0;
280 int DummyInfo = 0;
281 int DummyExtraInfo = 0;
282
283 handleAllErrors(
284 make_error<CustomSubError>(42, 7),
285 [&](const CustomError &CE) { CaughtErrorInfo = CE.getInfo(); },
286 [&](const CustomSubError &SE) {
287 DummyInfo = SE.getInfo();
288 DummyExtraInfo = SE.getExtraInfo();
289 });
290
NAKAMURA Takumib2cef642016-03-24 15:19:22 +0000291 EXPECT_TRUE(CaughtErrorInfo == 42 && DummyInfo == 0 && DummyExtraInfo == 0)
Lang Hames01864a22016-03-18 00:12:37 +0000292 << "General Error handler did not shadow specific handler";
293}
294
295// Test joinErrors.
296TEST(Error, CheckJoinErrors) {
297 int CustomErrorInfo1 = 0;
298 int CustomErrorInfo2 = 0;
299 int CustomErrorExtraInfo = 0;
300 Error E =
301 joinErrors(make_error<CustomError>(7), make_error<CustomSubError>(42, 7));
302
303 handleAllErrors(std::move(E),
304 [&](const CustomSubError &SE) {
305 CustomErrorInfo2 = SE.getInfo();
306 CustomErrorExtraInfo = SE.getExtraInfo();
307 },
308 [&](const CustomError &CE) {
309 // Assert that the CustomError instance above is handled
310 // before the
311 // CustomSubError - joinErrors should preserve error
312 // ordering.
313 EXPECT_EQ(CustomErrorInfo2, 0)
314 << "CustomErrorInfo2 should be 0 here. "
315 "joinErrors failed to preserve ordering.\n";
316 CustomErrorInfo1 = CE.getInfo();
317 });
318
319 EXPECT_TRUE(CustomErrorInfo1 == 7 && CustomErrorInfo2 == 42 &&
320 CustomErrorExtraInfo == 7)
321 << "Failed handling compound Error.";
Lang Hames759b30e2016-06-30 17:43:06 +0000322
323 // Test appending a single item to a list.
324 {
325 int Sum = 0;
326 handleAllErrors(
327 joinErrors(
328 joinErrors(make_error<CustomError>(7),
329 make_error<CustomError>(7)),
330 make_error<CustomError>(7)),
331 [&](const CustomError &CE) {
332 Sum += CE.getInfo();
333 });
334 EXPECT_EQ(Sum, 21) << "Failed to correctly append error to error list.";
335 }
336
337 // Test prepending a single item to a list.
338 {
339 int Sum = 0;
340 handleAllErrors(
341 joinErrors(
342 make_error<CustomError>(7),
343 joinErrors(make_error<CustomError>(7),
344 make_error<CustomError>(7))),
345 [&](const CustomError &CE) {
346 Sum += CE.getInfo();
347 });
348 EXPECT_EQ(Sum, 21) << "Failed to correctly prepend error to error list.";
349 }
350
351 // Test concatenating two error lists.
352 {
353 int Sum = 0;
354 handleAllErrors(
355 joinErrors(
356 joinErrors(
357 make_error<CustomError>(7),
358 make_error<CustomError>(7)),
359 joinErrors(
360 make_error<CustomError>(7),
361 make_error<CustomError>(7))),
362 [&](const CustomError &CE) {
363 Sum += CE.getInfo();
364 });
Hiroshi Inoue0ca79dc2017-07-11 06:04:59 +0000365 EXPECT_EQ(Sum, 28) << "Failed to correctly concatenate error lists.";
Lang Hames759b30e2016-06-30 17:43:06 +0000366 }
Lang Hames01864a22016-03-18 00:12:37 +0000367}
368
369// Test that we can consume success values.
370TEST(Error, ConsumeSuccess) {
Mehdi Aminic1edf562016-11-11 04:29:25 +0000371 Error E = Error::success();
Lang Hames01864a22016-03-18 00:12:37 +0000372 consumeError(std::move(E));
373}
374
375TEST(Error, ConsumeError) {
376 Error E = make_error<CustomError>(7);
377 consumeError(std::move(E));
378}
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000379
380// Test that handleAllUnhandledErrors crashes if an error is not caught.
381// Test runs in debug mode only.
Mehdi Aminicb79c072016-11-30 19:08:41 +0000382#if LLVM_ENABLE_ABI_BREAKING_CHECKS
Lang Hames01864a22016-03-18 00:12:37 +0000383TEST(Error, FailureToHandle) {
384 auto FailToHandle = []() {
385 handleAllErrors(make_error<CustomError>(7), [&](const CustomSubError &SE) {
386 errs() << "This should never be called";
387 exit(1);
388 });
389 };
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000390
Lang Hames7febf2b2017-08-24 05:35:27 +0000391 EXPECT_DEATH(FailToHandle(),
392 "Failure value returned from cantFail wrapped call")
Lang Hames01864a22016-03-18 00:12:37 +0000393 << "Unhandled Error in handleAllErrors call did not cause an "
394 "abort()";
395}
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000396#endif
397
398// Test that handleAllUnhandledErrors crashes if an error is returned from a
399// handler.
400// Test runs in debug mode only.
Mehdi Aminicb79c072016-11-30 19:08:41 +0000401#if LLVM_ENABLE_ABI_BREAKING_CHECKS
Lang Hames01864a22016-03-18 00:12:37 +0000402TEST(Error, FailureFromHandler) {
403 auto ReturnErrorFromHandler = []() {
404 handleAllErrors(make_error<CustomError>(7),
405 [&](std::unique_ptr<CustomSubError> SE) {
406 return Error(std::move(SE));
407 });
408 };
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000409
Lang Hames01864a22016-03-18 00:12:37 +0000410 EXPECT_DEATH(ReturnErrorFromHandler(),
Lang Hames7febf2b2017-08-24 05:35:27 +0000411 "Failure value returned from cantFail wrapped call")
Lang Hames01864a22016-03-18 00:12:37 +0000412 << " Error returned from handler in handleAllErrors call did not "
413 "cause abort()";
414}
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000415#endif
416
Lang Hames01864a22016-03-18 00:12:37 +0000417// Test that we can return values from handleErrors.
418TEST(Error, CatchErrorFromHandler) {
419 int ErrorInfo = 0;
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000420
Lang Hames01864a22016-03-18 00:12:37 +0000421 Error E = handleErrors(
422 make_error<CustomError>(7),
423 [&](std::unique_ptr<CustomError> CE) { return Error(std::move(CE)); });
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000424
Lang Hames01864a22016-03-18 00:12:37 +0000425 handleAllErrors(std::move(E),
426 [&](const CustomError &CE) { ErrorInfo = CE.getInfo(); });
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000427
Lang Hames01864a22016-03-18 00:12:37 +0000428 EXPECT_EQ(ErrorInfo, 7)
429 << "Failed to handle Error returned from handleErrors.";
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000430}
431
Lang Hamesc5e0bbd2016-05-27 01:37:32 +0000432TEST(Error, StringError) {
433 std::string Msg;
434 raw_string_ostream S(Msg);
435 logAllUnhandledErrors(make_error<StringError>("foo" + Twine(42),
Lang Hamesbd8e9542016-05-27 01:54:25 +0000436 inconvertibleErrorCode()),
Lang Hamesc5e0bbd2016-05-27 01:37:32 +0000437 S, "");
438 EXPECT_EQ(S.str(), "foo42\n") << "Unexpected StringError log result";
439
440 auto EC =
441 errorToErrorCode(make_error<StringError>("", errc::invalid_argument));
442 EXPECT_EQ(EC, errc::invalid_argument)
443 << "Failed to convert StringError to error_code.";
444}
445
Lang Hames01864a22016-03-18 00:12:37 +0000446// Test that the ExitOnError utility works as expected.
447TEST(Error, ExitOnError) {
448 ExitOnError ExitOnErr;
449 ExitOnErr.setBanner("Error in tool:");
450 ExitOnErr.setExitCodeMapper([](const Error &E) {
451 if (E.isA<CustomSubError>())
452 return 2;
453 return 1;
454 });
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000455
Lang Hames01864a22016-03-18 00:12:37 +0000456 // Make sure we don't bail on success.
457 ExitOnErr(Error::success());
458 EXPECT_EQ(ExitOnErr(Expected<int>(7)), 7)
459 << "exitOnError returned an invalid value for Expected";
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000460
Lang Hames285639f2016-04-25 19:21:57 +0000461 int A = 7;
462 int &B = ExitOnErr(Expected<int&>(A));
463 EXPECT_EQ(&A, &B) << "ExitOnError failed to propagate reference";
464
Lang Hames01864a22016-03-18 00:12:37 +0000465 // Exit tests.
466 EXPECT_EXIT(ExitOnErr(make_error<CustomError>(7)),
467 ::testing::ExitedWithCode(1), "Error in tool:")
468 << "exitOnError returned an unexpected error result";
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000469
Lang Hames01864a22016-03-18 00:12:37 +0000470 EXPECT_EXIT(ExitOnErr(Expected<int>(make_error<CustomSubError>(0, 0))),
471 ::testing::ExitedWithCode(2), "Error in tool:")
472 << "exitOnError returned an unexpected error result";
473}
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000474
Lang Hamesfd4de912017-02-27 21:09:47 +0000475// Test that the ExitOnError utility works as expected.
476TEST(Error, CantFailSuccess) {
477 cantFail(Error::success());
478
479 int X = cantFail(Expected<int>(42));
480 EXPECT_EQ(X, 42) << "Expected value modified by cantFail";
Lang Hamescd227532017-06-20 22:18:02 +0000481
482 int Dummy = 42;
483 int &Y = cantFail(Expected<int&>(Dummy));
484 EXPECT_EQ(&Dummy, &Y) << "Reference mangled by cantFail";
Lang Hamesfd4de912017-02-27 21:09:47 +0000485}
486
487// Test that cantFail results in a crash if you pass it a failure value.
Stephen Hinescc14a382017-08-25 00:48:21 +0000488#if LLVM_ENABLE_ABI_BREAKING_CHECKS && !defined(NDEBUG)
Lang Hamesfd4de912017-02-27 21:09:47 +0000489TEST(Error, CantFailDeath) {
490 EXPECT_DEATH(
Lang Hames3025e482017-08-29 23:29:09 +0000491 cantFail(make_error<StringError>("foo", inconvertibleErrorCode()),
492 "Cantfail call failed"),
493 "Cantfail call failed")
Lang Hamesfd4de912017-02-27 21:09:47 +0000494 << "cantFail(Error) did not cause an abort for failure value";
495
496 EXPECT_DEATH(
497 {
498 auto IEC = inconvertibleErrorCode();
499 int X = cantFail(Expected<int>(make_error<StringError>("foo", IEC)));
500 (void)X;
501 },
502 "Failure value returned from cantFail wrapped call")
503 << "cantFail(Expected<int>) did not cause an abort for failure value";
504}
505#endif
506
507
Lang Hames580ca232016-04-05 19:57:03 +0000508// Test Checked Expected<T> in success mode.
509TEST(Error, CheckedExpectedInSuccessMode) {
Lang Hames01864a22016-03-18 00:12:37 +0000510 Expected<int> A = 7;
511 EXPECT_TRUE(!!A) << "Expected with non-error value doesn't convert to 'true'";
Lang Hames580ca232016-04-05 19:57:03 +0000512 // Access is safe in second test, since we checked the error in the first.
Lang Hames01864a22016-03-18 00:12:37 +0000513 EXPECT_EQ(*A, 7) << "Incorrect Expected non-error value";
514}
515
Lang Hames285639f2016-04-25 19:21:57 +0000516// Test Expected with reference type.
517TEST(Error, ExpectedWithReferenceType) {
518 int A = 7;
519 Expected<int&> B = A;
520 // 'Check' B.
521 (void)!!B;
522 int &C = *B;
523 EXPECT_EQ(&A, &C) << "Expected failed to propagate reference";
524}
525
Lang Hames580ca232016-04-05 19:57:03 +0000526// Test Unchecked Expected<T> in success mode.
527// We expect this to blow up the same way Error would.
528// Test runs in debug mode only.
Mehdi Aminicb79c072016-11-30 19:08:41 +0000529#if LLVM_ENABLE_ABI_BREAKING_CHECKS
Lang Hames580ca232016-04-05 19:57:03 +0000530TEST(Error, UncheckedExpectedInSuccessModeDestruction) {
531 EXPECT_DEATH({ Expected<int> A = 7; },
532 "Expected<T> must be checked before access or destruction.")
533 << "Unchecekd Expected<T> success value did not cause an abort().";
534}
535#endif
536
537// Test Unchecked Expected<T> in success mode.
538// We expect this to blow up the same way Error would.
539// Test runs in debug mode only.
Mehdi Aminicb79c072016-11-30 19:08:41 +0000540#if LLVM_ENABLE_ABI_BREAKING_CHECKS
Lang Hames580ca232016-04-05 19:57:03 +0000541TEST(Error, UncheckedExpectedInSuccessModeAccess) {
542 EXPECT_DEATH({ Expected<int> A = 7; *A; },
543 "Expected<T> must be checked before access or destruction.")
544 << "Unchecekd Expected<T> success value did not cause an abort().";
545}
546#endif
547
548// Test Unchecked Expected<T> in success mode.
549// We expect this to blow up the same way Error would.
550// Test runs in debug mode only.
Mehdi Aminicb79c072016-11-30 19:08:41 +0000551#if LLVM_ENABLE_ABI_BREAKING_CHECKS
Lang Hames580ca232016-04-05 19:57:03 +0000552TEST(Error, UncheckedExpectedInSuccessModeAssignment) {
553 EXPECT_DEATH({ Expected<int> A = 7; A = 7; },
554 "Expected<T> must be checked before access or destruction.")
555 << "Unchecekd Expected<T> success value did not cause an abort().";
556}
557#endif
558
Lang Hames01864a22016-03-18 00:12:37 +0000559// Test Expected<T> in failure mode.
560TEST(Error, ExpectedInFailureMode) {
561 Expected<int> A = make_error<CustomError>(42);
562 EXPECT_FALSE(!!A) << "Expected with error value doesn't convert to 'false'";
563 Error E = A.takeError();
564 EXPECT_TRUE(E.isA<CustomError>()) << "Incorrect Expected error value";
565 consumeError(std::move(E));
566}
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000567
568// Check that an Expected instance with an error value doesn't allow access to
569// operator*.
570// Test runs in debug mode only.
Mehdi Aminicb79c072016-11-30 19:08:41 +0000571#if LLVM_ENABLE_ABI_BREAKING_CHECKS
Lang Hames01864a22016-03-18 00:12:37 +0000572TEST(Error, AccessExpectedInFailureMode) {
573 Expected<int> A = make_error<CustomError>(42);
Lang Hames580ca232016-04-05 19:57:03 +0000574 EXPECT_DEATH(*A, "Expected<T> must be checked before access or destruction.")
Lang Hames01864a22016-03-18 00:12:37 +0000575 << "Incorrect Expected error value";
576 consumeError(A.takeError());
577}
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000578#endif
579
580// Check that an Expected instance with an error triggers an abort if
581// unhandled.
582// Test runs in debug mode only.
Mehdi Aminicb79c072016-11-30 19:08:41 +0000583#if LLVM_ENABLE_ABI_BREAKING_CHECKS
Lang Hames01864a22016-03-18 00:12:37 +0000584TEST(Error, UnhandledExpectedInFailureMode) {
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000585 EXPECT_DEATH({ Expected<int> A = make_error<CustomError>(42); },
Lang Hames580ca232016-04-05 19:57:03 +0000586 "Expected<T> must be checked before access or destruction.")
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000587 << "Unchecked Expected<T> failure value did not cause an abort()";
Lang Hames01864a22016-03-18 00:12:37 +0000588}
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000589#endif
590
Lang Hames01864a22016-03-18 00:12:37 +0000591// Test covariance of Expected.
592TEST(Error, ExpectedCovariance) {
593 class B {};
594 class D : public B {};
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000595
Lang Hames01864a22016-03-18 00:12:37 +0000596 Expected<B *> A1(Expected<D *>(nullptr));
Lang Hames580ca232016-04-05 19:57:03 +0000597 // Check A1 by converting to bool before assigning to it.
598 (void)!!A1;
Lang Hames01864a22016-03-18 00:12:37 +0000599 A1 = Expected<D *>(nullptr);
Lang Hames580ca232016-04-05 19:57:03 +0000600 // Check A1 again before destruction.
601 (void)!!A1;
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000602
Lang Hames01864a22016-03-18 00:12:37 +0000603 Expected<std::unique_ptr<B>> A2(Expected<std::unique_ptr<D>>(nullptr));
Lang Hames580ca232016-04-05 19:57:03 +0000604 // Check A2 by converting to bool before assigning to it.
605 (void)!!A2;
Lang Hames01864a22016-03-18 00:12:37 +0000606 A2 = Expected<std::unique_ptr<D>>(nullptr);
Lang Hames580ca232016-04-05 19:57:03 +0000607 // Check A2 again before destruction.
608 (void)!!A2;
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000609}
610
Lang Hames5d06c232017-08-28 03:36:46 +0000611// Test that handleExpected just returns success values.
612TEST(Error, HandleExpectedSuccess) {
613 auto ValOrErr =
614 handleExpected(Expected<int>(42),
615 []() { return Expected<int>(43); });
616 EXPECT_TRUE(!!ValOrErr)
617 << "handleExpected should have returned a success value here";
618 EXPECT_EQ(*ValOrErr, 42)
619 << "handleExpected should have returned the original success value here";
620}
621
622enum FooStrategy { Aggressive, Conservative };
623
624static Expected<int> foo(FooStrategy S) {
625 if (S == Aggressive)
626 return make_error<CustomError>(7);
627 return 42;
628}
629
630// Test that handleExpected invokes the error path if errors are not handled.
631TEST(Error, HandleExpectedUnhandledError) {
632 // foo(Aggressive) should return a CustomError which should pass through as
633 // there is no handler for CustomError.
634 auto ValOrErr =
635 handleExpected(
636 foo(Aggressive),
637 []() { return foo(Conservative); });
638
639 EXPECT_FALSE(!!ValOrErr)
640 << "handleExpected should have returned an error here";
641 auto Err = ValOrErr.takeError();
642 EXPECT_TRUE(Err.isA<CustomError>())
643 << "handleExpected should have returned the CustomError generated by "
644 "foo(Aggressive) here";
645 consumeError(std::move(Err));
646}
647
648// Test that handleExpected invokes the fallback path if errors are handled.
649TEST(Error, HandleExpectedHandledError) {
650 // foo(Aggressive) should return a CustomError which should handle triggering
651 // the fallback path.
652 auto ValOrErr =
653 handleExpected(
654 foo(Aggressive),
655 []() { return foo(Conservative); },
656 [](const CustomError&) { /* do nothing */ });
657
658 EXPECT_TRUE(!!ValOrErr)
659 << "handleExpected should have returned a success value here";
660 EXPECT_EQ(*ValOrErr, 42)
661 << "handleExpected returned the wrong success value";
662}
663
Lang Hamesd21a5352016-03-24 02:00:10 +0000664TEST(Error, ErrorCodeConversions) {
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000665 // Round-trip a success value to check that it converts correctly.
666 EXPECT_EQ(errorToErrorCode(errorCodeToError(std::error_code())),
667 std::error_code())
668 << "std::error_code() should round-trip via Error conversions";
669
670 // Round-trip an error value to check that it converts correctly.
671 EXPECT_EQ(errorToErrorCode(errorCodeToError(errc::invalid_argument)),
672 errc::invalid_argument)
673 << "std::error_code error value should round-trip via Error "
674 "conversions";
Lang Hamesd21a5352016-03-24 02:00:10 +0000675
676 // Round-trip a success value through ErrorOr/Expected to check that it
677 // converts correctly.
678 {
679 auto Orig = ErrorOr<int>(42);
680 auto RoundTripped =
681 expectedToErrorOr(errorOrToExpected(ErrorOr<int>(42)));
682 EXPECT_EQ(*Orig, *RoundTripped)
683 << "ErrorOr<T> success value should round-trip via Expected<T> "
684 "conversions.";
685 }
686
687 // Round-trip a failure value through ErrorOr/Expected to check that it
688 // converts correctly.
689 {
690 auto Orig = ErrorOr<int>(errc::invalid_argument);
691 auto RoundTripped =
692 expectedToErrorOr(
693 errorOrToExpected(ErrorOr<int>(errc::invalid_argument)));
694 EXPECT_EQ(Orig.getError(), RoundTripped.getError())
695 << "ErrorOr<T> failure value should round-trip via Expected<T> "
696 "conversions.";
697 }
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000698}
699
Vedant Kumar27370a02016-05-03 23:32:31 +0000700// Test that error messages work.
701TEST(Error, ErrorMessage) {
702 EXPECT_EQ(toString(Error::success()).compare(""), 0);
703
704 Error E1 = make_error<CustomError>(0);
Sam McCall8ca99102018-07-06 05:45:45 +0000705 EXPECT_EQ(toString(std::move(E1)).compare("CustomError {0}"), 0);
Vedant Kumar27370a02016-05-03 23:32:31 +0000706
707 Error E2 = make_error<CustomError>(0);
708 handleAllErrors(std::move(E2), [](const CustomError &CE) {
Sam McCall8ca99102018-07-06 05:45:45 +0000709 EXPECT_EQ(CE.message().compare("CustomError {0}"), 0);
Vedant Kumar27370a02016-05-03 23:32:31 +0000710 });
711
712 Error E3 = joinErrors(make_error<CustomError>(0), make_error<CustomError>(1));
713 EXPECT_EQ(toString(std::move(E3))
Sam McCall8ca99102018-07-06 05:45:45 +0000714 .compare("CustomError {0}\n"
715 "CustomError {1}"),
Vedant Kumar27370a02016-05-03 23:32:31 +0000716 0);
717}
718
Sam McCall8ca99102018-07-06 05:45:45 +0000719TEST(Error, Stream) {
720 {
721 Error OK = Error::success();
722 std::string Buf;
723 llvm::raw_string_ostream S(Buf);
724 S << OK;
725 EXPECT_EQ("success", S.str());
726 consumeError(std::move(OK));
727 }
728 {
729 Error E1 = make_error<CustomError>(0);
730 std::string Buf;
731 llvm::raw_string_ostream S(Buf);
732 S << E1;
733 EXPECT_EQ("CustomError {0}", S.str());
734 consumeError(std::move(E1));
735 }
736}
737
Pavel Labathe8354fe2017-12-07 10:54:23 +0000738TEST(Error, ErrorMatchers) {
739 EXPECT_THAT_ERROR(Error::success(), Succeeded());
740 EXPECT_NONFATAL_FAILURE(
741 EXPECT_THAT_ERROR(make_error<CustomError>(0), Succeeded()),
Sam McCall8ca99102018-07-06 05:45:45 +0000742 "Expected: succeeded\n Actual: failed (CustomError {0})");
Pavel Labathe8354fe2017-12-07 10:54:23 +0000743
744 EXPECT_THAT_ERROR(make_error<CustomError>(0), Failed());
745 EXPECT_NONFATAL_FAILURE(EXPECT_THAT_ERROR(Error::success(), Failed()),
746 "Expected: failed\n Actual: succeeded");
747
Pavel Labath510725c2018-04-05 14:32:10 +0000748 EXPECT_THAT_ERROR(make_error<CustomError>(0), Failed<CustomError>());
749 EXPECT_NONFATAL_FAILURE(
750 EXPECT_THAT_ERROR(Error::success(), Failed<CustomError>()),
751 "Expected: failed with Error of given type\n Actual: succeeded");
752 EXPECT_NONFATAL_FAILURE(
753 EXPECT_THAT_ERROR(make_error<CustomError>(0), Failed<CustomSubError>()),
754 "Error was not of given type");
755 EXPECT_NONFATAL_FAILURE(
756 EXPECT_THAT_ERROR(
757 joinErrors(make_error<CustomError>(0), make_error<CustomError>(1)),
758 Failed<CustomError>()),
759 "multiple errors");
760
761 EXPECT_THAT_ERROR(
762 make_error<CustomError>(0),
763 Failed<CustomError>(testing::Property(&CustomError::getInfo, 0)));
764 EXPECT_NONFATAL_FAILURE(
765 EXPECT_THAT_ERROR(
766 make_error<CustomError>(0),
767 Failed<CustomError>(testing::Property(&CustomError::getInfo, 1))),
768 "Expected: failed with Error of given type and the error is an object "
769 "whose given property is equal to 1\n"
Sam McCall8ca99102018-07-06 05:45:45 +0000770 " Actual: failed (CustomError {0})");
Pavel Labath397e1502018-04-10 14:11:53 +0000771 EXPECT_THAT_ERROR(make_error<CustomError>(0), Failed<ErrorInfoBase>());
Pavel Labath510725c2018-04-05 14:32:10 +0000772
Pavel Labathe8354fe2017-12-07 10:54:23 +0000773 EXPECT_THAT_EXPECTED(Expected<int>(0), Succeeded());
774 EXPECT_NONFATAL_FAILURE(
775 EXPECT_THAT_EXPECTED(Expected<int>(make_error<CustomError>(0)),
776 Succeeded()),
Sam McCall8ca99102018-07-06 05:45:45 +0000777 "Expected: succeeded\n Actual: failed (CustomError {0})");
Pavel Labathe8354fe2017-12-07 10:54:23 +0000778
779 EXPECT_THAT_EXPECTED(Expected<int>(make_error<CustomError>(0)), Failed());
780 EXPECT_NONFATAL_FAILURE(
781 EXPECT_THAT_EXPECTED(Expected<int>(0), Failed()),
Pavel Labath56c2d992017-12-13 10:00:38 +0000782 "Expected: failed\n Actual: succeeded with value 0");
Pavel Labathe8354fe2017-12-07 10:54:23 +0000783
784 EXPECT_THAT_EXPECTED(Expected<int>(0), HasValue(0));
785 EXPECT_NONFATAL_FAILURE(
786 EXPECT_THAT_EXPECTED(Expected<int>(make_error<CustomError>(0)),
787 HasValue(0)),
Pavel Labath56c2d992017-12-13 10:00:38 +0000788 "Expected: succeeded with value (is equal to 0)\n"
Sam McCall8ca99102018-07-06 05:45:45 +0000789 " Actual: failed (CustomError {0})");
Pavel Labathe8354fe2017-12-07 10:54:23 +0000790 EXPECT_NONFATAL_FAILURE(
791 EXPECT_THAT_EXPECTED(Expected<int>(1), HasValue(0)),
Pavel Labath56c2d992017-12-13 10:00:38 +0000792 "Expected: succeeded with value (is equal to 0)\n"
793 " Actual: succeeded with value 1, (isn't equal to 0)");
Pavel Labathe8354fe2017-12-07 10:54:23 +0000794
795 EXPECT_THAT_EXPECTED(Expected<int &>(make_error<CustomError>(0)), Failed());
796 int a = 1;
797 EXPECT_THAT_EXPECTED(Expected<int &>(a), Succeeded());
Pavel Labath56c2d992017-12-13 10:00:38 +0000798 EXPECT_THAT_EXPECTED(Expected<int &>(a), HasValue(testing::Eq(1)));
799
800 EXPECT_THAT_EXPECTED(Expected<int>(1), HasValue(testing::Gt(0)));
801 EXPECT_NONFATAL_FAILURE(
802 EXPECT_THAT_EXPECTED(Expected<int>(0), HasValue(testing::Gt(1))),
803 "Expected: succeeded with value (is > 1)\n"
804 " Actual: succeeded with value 0, (isn't > 1)");
805 EXPECT_NONFATAL_FAILURE(
806 EXPECT_THAT_EXPECTED(Expected<int>(make_error<CustomError>(0)),
807 HasValue(testing::Gt(1))),
808 "Expected: succeeded with value (is > 1)\n"
Sam McCall8ca99102018-07-06 05:45:45 +0000809 " Actual: failed (CustomError {0})");
Pavel Labathe8354fe2017-12-07 10:54:23 +0000810}
811
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000812} // end anon namespace