1 //===----- unittests/ErrorTest.cpp - Error.h tests ------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8
9 #include "llvm/Support/Error.h"
10 #include "llvm-c/Error.h"
11
12 #include "llvm/ADT/Twine.h"
13 #include "llvm/Support/Errc.h"
14 #include "llvm/Support/ErrorHandling.h"
15 #include "llvm/Support/ManagedStatic.h"
16 #include "llvm/Testing/Support/Error.h"
17 #include "gtest/gtest-spi.h"
18 #include "gtest/gtest.h"
19 #include <memory>
20
21 using namespace llvm;
22
23 namespace {
24
25 // Custom error class with a default base class and some random 'info' attached.
26 class CustomError : public ErrorInfo<CustomError> {
27 public:
28 // Create an error with some info attached.
CustomError(int Info)29 CustomError(int Info) : Info(Info) {}
30
31 // Get the info attached to this error.
getInfo() const32 int getInfo() const { return Info; }
33
34 // Log this error to a stream.
log(raw_ostream & OS) const35 void log(raw_ostream &OS) const override {
36 OS << "CustomError {" << getInfo() << "}";
37 }
38
convertToErrorCode() const39 std::error_code convertToErrorCode() const override {
40 llvm_unreachable("CustomError doesn't support ECError conversion");
41 }
42
43 // Used by ErrorInfo::classID.
44 static char ID;
45
46 protected:
47 // This error is subclassed below, but we can't use inheriting constructors
48 // yet, so we can't propagate the constructors through ErrorInfo. Instead
49 // we have to have a default constructor and have the subclass initialize all
50 // fields.
CustomError()51 CustomError() : Info(0) {}
52
53 int Info;
54 };
55
56 char CustomError::ID = 0;
57
58 // Custom error class with a custom base class and some additional random
59 // 'info'.
60 class CustomSubError : public ErrorInfo<CustomSubError, CustomError> {
61 public:
62 // Create a sub-error with some info attached.
CustomSubError(int Info,int ExtraInfo)63 CustomSubError(int Info, int ExtraInfo) : ExtraInfo(ExtraInfo) {
64 this->Info = Info;
65 }
66
67 // Get the extra info attached to this error.
getExtraInfo() const68 int getExtraInfo() const { return ExtraInfo; }
69
70 // Log this error to a stream.
log(raw_ostream & OS) const71 void log(raw_ostream &OS) const override {
72 OS << "CustomSubError { " << getInfo() << ", " << getExtraInfo() << "}";
73 }
74
convertToErrorCode() const75 std::error_code convertToErrorCode() const override {
76 llvm_unreachable("CustomSubError doesn't support ECError conversion");
77 }
78
79 // Used by ErrorInfo::classID.
80 static char ID;
81
82 protected:
83 int ExtraInfo;
84 };
85
86 char CustomSubError::ID = 0;
87
handleCustomError(const CustomError & CE)88 static Error handleCustomError(const CustomError &CE) {
89 return Error::success();
90 }
91
handleCustomErrorVoid(const CustomError & CE)92 static void handleCustomErrorVoid(const CustomError &CE) {}
93
handleCustomErrorUP(std::unique_ptr<CustomError> CE)94 static Error handleCustomErrorUP(std::unique_ptr<CustomError> CE) {
95 return Error::success();
96 }
97
handleCustomErrorUPVoid(std::unique_ptr<CustomError> CE)98 static void handleCustomErrorUPVoid(std::unique_ptr<CustomError> CE) {}
99
100 // Test that success values implicitly convert to false, and don't cause crashes
101 // once they've been implicitly converted.
TEST(Error,CheckedSuccess)102 TEST(Error, CheckedSuccess) {
103 Error E = Error::success();
104 EXPECT_FALSE(E) << "Unexpected error while testing Error 'Success'";
105 }
106
107 // Test that unchecked success values cause an abort.
108 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
TEST(Error,UncheckedSuccess)109 TEST(Error, UncheckedSuccess) {
110 EXPECT_DEATH({ Error E = Error::success(); },
111 "Program aborted due to an unhandled Error:")
112 << "Unchecked Error Succes value did not cause abort()";
113 }
114 #endif
115
116 // ErrorAsOutParameter tester.
errAsOutParamHelper(Error & Err)117 void errAsOutParamHelper(Error &Err) {
118 ErrorAsOutParameter ErrAsOutParam(&Err);
119 // Verify that checked flag is raised - assignment should not crash.
120 Err = Error::success();
121 // Raise the checked bit manually - caller should still have to test the
122 // error.
123 (void)!!Err;
124 }
125
126 // Test that ErrorAsOutParameter sets the checked flag on construction.
TEST(Error,ErrorAsOutParameterChecked)127 TEST(Error, ErrorAsOutParameterChecked) {
128 Error E = Error::success();
129 errAsOutParamHelper(E);
130 (void)!!E;
131 }
132
133 // Test that ErrorAsOutParameter clears the checked flag on destruction.
134 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
TEST(Error,ErrorAsOutParameterUnchecked)135 TEST(Error, ErrorAsOutParameterUnchecked) {
136 EXPECT_DEATH({ Error E = Error::success(); errAsOutParamHelper(E); },
137 "Program aborted due to an unhandled Error:")
138 << "ErrorAsOutParameter did not clear the checked flag on destruction.";
139 }
140 #endif
141
142 // Check that we abort on unhandled failure cases. (Force conversion to bool
143 // to make sure that we don't accidentally treat checked errors as handled).
144 // Test runs in debug mode only.
145 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
TEST(Error,UncheckedError)146 TEST(Error, UncheckedError) {
147 auto DropUnhandledError = []() {
148 Error E = make_error<CustomError>(42);
149 (void)!E;
150 };
151 EXPECT_DEATH(DropUnhandledError(),
152 "Program aborted due to an unhandled Error:")
153 << "Unhandled Error failure value did not cause abort()";
154 }
155 #endif
156
157 // Check 'Error::isA<T>' method handling.
TEST(Error,IsAHandling)158 TEST(Error, IsAHandling) {
159 // Check 'isA' handling.
160 Error E = make_error<CustomError>(1);
161 Error F = make_error<CustomSubError>(1, 2);
162 Error G = Error::success();
163
164 EXPECT_TRUE(E.isA<CustomError>());
165 EXPECT_FALSE(E.isA<CustomSubError>());
166 EXPECT_TRUE(F.isA<CustomError>());
167 EXPECT_TRUE(F.isA<CustomSubError>());
168 EXPECT_FALSE(G.isA<CustomError>());
169
170 consumeError(std::move(E));
171 consumeError(std::move(F));
172 consumeError(std::move(G));
173 }
174
175 // Check that we can handle a custom error.
TEST(Error,HandleCustomError)176 TEST(Error, HandleCustomError) {
177 int CaughtErrorInfo = 0;
178 handleAllErrors(make_error<CustomError>(42), [&](const CustomError &CE) {
179 CaughtErrorInfo = CE.getInfo();
180 });
181
182 EXPECT_TRUE(CaughtErrorInfo == 42) << "Wrong result from CustomError handler";
183 }
184
185 // Check that handler type deduction also works for handlers
186 // of the following types:
187 // void (const Err&)
188 // Error (const Err&) mutable
189 // void (const Err&) mutable
190 // Error (Err&)
191 // void (Err&)
192 // Error (Err&) mutable
193 // void (Err&) mutable
194 // Error (unique_ptr<Err>)
195 // void (unique_ptr<Err>)
196 // Error (unique_ptr<Err>) mutable
197 // void (unique_ptr<Err>) mutable
TEST(Error,HandlerTypeDeduction)198 TEST(Error, HandlerTypeDeduction) {
199
200 handleAllErrors(make_error<CustomError>(42), [](const CustomError &CE) {});
201
202 handleAllErrors(
203 make_error<CustomError>(42),
204 [](const CustomError &CE) mutable -> Error { return Error::success(); });
205
206 handleAllErrors(make_error<CustomError>(42),
207 [](const CustomError &CE) mutable {});
208
209 handleAllErrors(make_error<CustomError>(42),
210 [](CustomError &CE) -> Error { return Error::success(); });
211
212 handleAllErrors(make_error<CustomError>(42), [](CustomError &CE) {});
213
214 handleAllErrors(make_error<CustomError>(42),
215 [](CustomError &CE) mutable -> Error { return Error::success(); });
216
217 handleAllErrors(make_error<CustomError>(42), [](CustomError &CE) mutable {});
218
219 handleAllErrors(
220 make_error<CustomError>(42),
221 [](std::unique_ptr<CustomError> CE) -> Error { return Error::success(); });
222
223 handleAllErrors(make_error<CustomError>(42),
224 [](std::unique_ptr<CustomError> CE) {});
225
226 handleAllErrors(
227 make_error<CustomError>(42),
228 [](std::unique_ptr<CustomError> CE) mutable -> Error { return Error::success(); });
229
230 handleAllErrors(make_error<CustomError>(42),
231 [](std::unique_ptr<CustomError> CE) mutable {});
232
233 // Check that named handlers of type 'Error (const Err&)' work.
234 handleAllErrors(make_error<CustomError>(42), handleCustomError);
235
236 // Check that named handlers of type 'void (const Err&)' work.
237 handleAllErrors(make_error<CustomError>(42), handleCustomErrorVoid);
238
239 // Check that named handlers of type 'Error (std::unique_ptr<Err>)' work.
240 handleAllErrors(make_error<CustomError>(42), handleCustomErrorUP);
241
242 // Check that named handlers of type 'Error (std::unique_ptr<Err>)' work.
243 handleAllErrors(make_error<CustomError>(42), handleCustomErrorUPVoid);
244 }
245
246 // Test that we can handle errors with custom base classes.
TEST(Error,HandleCustomErrorWithCustomBaseClass)247 TEST(Error, HandleCustomErrorWithCustomBaseClass) {
248 int CaughtErrorInfo = 0;
249 int CaughtErrorExtraInfo = 0;
250 handleAllErrors(make_error<CustomSubError>(42, 7),
251 [&](const CustomSubError &SE) {
252 CaughtErrorInfo = SE.getInfo();
253 CaughtErrorExtraInfo = SE.getExtraInfo();
254 });
255
256 EXPECT_TRUE(CaughtErrorInfo == 42 && CaughtErrorExtraInfo == 7)
257 << "Wrong result from CustomSubError handler";
258 }
259
260 // Check that we trigger only the first handler that applies.
TEST(Error,FirstHandlerOnly)261 TEST(Error, FirstHandlerOnly) {
262 int DummyInfo = 0;
263 int CaughtErrorInfo = 0;
264 int CaughtErrorExtraInfo = 0;
265
266 handleAllErrors(make_error<CustomSubError>(42, 7),
267 [&](const CustomSubError &SE) {
268 CaughtErrorInfo = SE.getInfo();
269 CaughtErrorExtraInfo = SE.getExtraInfo();
270 },
271 [&](const CustomError &CE) { DummyInfo = CE.getInfo(); });
272
273 EXPECT_TRUE(CaughtErrorInfo == 42 && CaughtErrorExtraInfo == 7 &&
274 DummyInfo == 0)
275 << "Activated the wrong Error handler(s)";
276 }
277
278 // Check that general handlers shadow specific ones.
TEST(Error,HandlerShadowing)279 TEST(Error, HandlerShadowing) {
280 int CaughtErrorInfo = 0;
281 int DummyInfo = 0;
282 int DummyExtraInfo = 0;
283
284 handleAllErrors(
285 make_error<CustomSubError>(42, 7),
286 [&](const CustomError &CE) { CaughtErrorInfo = CE.getInfo(); },
287 [&](const CustomSubError &SE) {
288 DummyInfo = SE.getInfo();
289 DummyExtraInfo = SE.getExtraInfo();
290 });
291
292 EXPECT_TRUE(CaughtErrorInfo == 42 && DummyInfo == 0 && DummyExtraInfo == 0)
293 << "General Error handler did not shadow specific handler";
294 }
295
296 // Test joinErrors.
TEST(Error,CheckJoinErrors)297 TEST(Error, CheckJoinErrors) {
298 int CustomErrorInfo1 = 0;
299 int CustomErrorInfo2 = 0;
300 int CustomErrorExtraInfo = 0;
301 Error E =
302 joinErrors(make_error<CustomError>(7), make_error<CustomSubError>(42, 7));
303
304 handleAllErrors(std::move(E),
305 [&](const CustomSubError &SE) {
306 CustomErrorInfo2 = SE.getInfo();
307 CustomErrorExtraInfo = SE.getExtraInfo();
308 },
309 [&](const CustomError &CE) {
310 // Assert that the CustomError instance above is handled
311 // before the
312 // CustomSubError - joinErrors should preserve error
313 // ordering.
314 EXPECT_EQ(CustomErrorInfo2, 0)
315 << "CustomErrorInfo2 should be 0 here. "
316 "joinErrors failed to preserve ordering.\n";
317 CustomErrorInfo1 = CE.getInfo();
318 });
319
320 EXPECT_TRUE(CustomErrorInfo1 == 7 && CustomErrorInfo2 == 42 &&
321 CustomErrorExtraInfo == 7)
322 << "Failed handling compound Error.";
323
324 // Test appending a single item to a list.
325 {
326 int Sum = 0;
327 handleAllErrors(
328 joinErrors(
329 joinErrors(make_error<CustomError>(7),
330 make_error<CustomError>(7)),
331 make_error<CustomError>(7)),
332 [&](const CustomError &CE) {
333 Sum += CE.getInfo();
334 });
335 EXPECT_EQ(Sum, 21) << "Failed to correctly append error to error list.";
336 }
337
338 // Test prepending a single item to a list.
339 {
340 int Sum = 0;
341 handleAllErrors(
342 joinErrors(
343 make_error<CustomError>(7),
344 joinErrors(make_error<CustomError>(7),
345 make_error<CustomError>(7))),
346 [&](const CustomError &CE) {
347 Sum += CE.getInfo();
348 });
349 EXPECT_EQ(Sum, 21) << "Failed to correctly prepend error to error list.";
350 }
351
352 // Test concatenating two error lists.
353 {
354 int Sum = 0;
355 handleAllErrors(
356 joinErrors(
357 joinErrors(
358 make_error<CustomError>(7),
359 make_error<CustomError>(7)),
360 joinErrors(
361 make_error<CustomError>(7),
362 make_error<CustomError>(7))),
363 [&](const CustomError &CE) {
364 Sum += CE.getInfo();
365 });
366 EXPECT_EQ(Sum, 28) << "Failed to correctly concatenate error lists.";
367 }
368 }
369
370 // Test that we can consume success values.
TEST(Error,ConsumeSuccess)371 TEST(Error, ConsumeSuccess) {
372 Error E = Error::success();
373 consumeError(std::move(E));
374 }
375
TEST(Error,ConsumeError)376 TEST(Error, ConsumeError) {
377 Error E = make_error<CustomError>(7);
378 consumeError(std::move(E));
379 }
380
381 // Test that handleAllUnhandledErrors crashes if an error is not caught.
382 // Test runs in debug mode only.
383 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
TEST(Error,FailureToHandle)384 TEST(Error, FailureToHandle) {
385 auto FailToHandle = []() {
386 handleAllErrors(make_error<CustomError>(7), [&](const CustomSubError &SE) {
387 errs() << "This should never be called";
388 exit(1);
389 });
390 };
391
392 EXPECT_DEATH(FailToHandle(),
393 "Failure value returned from cantFail wrapped call\n"
394 "CustomError \\{7\\}")
395 << "Unhandled Error in handleAllErrors call did not cause an "
396 "abort()";
397 }
398 #endif
399
400 // Test that handleAllUnhandledErrors crashes if an error is returned from a
401 // handler.
402 // Test runs in debug mode only.
403 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
TEST(Error,FailureFromHandler)404 TEST(Error, FailureFromHandler) {
405 auto ReturnErrorFromHandler = []() {
406 handleAllErrors(make_error<CustomError>(7),
407 [&](std::unique_ptr<CustomSubError> SE) {
408 return Error(std::move(SE));
409 });
410 };
411
412 EXPECT_DEATH(ReturnErrorFromHandler(),
413 "Failure value returned from cantFail wrapped call\n"
414 "CustomError \\{7\\}")
415 << " Error returned from handler in handleAllErrors call did not "
416 "cause abort()";
417 }
418 #endif
419
420 // Test that we can return values from handleErrors.
TEST(Error,CatchErrorFromHandler)421 TEST(Error, CatchErrorFromHandler) {
422 int ErrorInfo = 0;
423
424 Error E = handleErrors(
425 make_error<CustomError>(7),
426 [&](std::unique_ptr<CustomError> CE) { return Error(std::move(CE)); });
427
428 handleAllErrors(std::move(E),
429 [&](const CustomError &CE) { ErrorInfo = CE.getInfo(); });
430
431 EXPECT_EQ(ErrorInfo, 7)
432 << "Failed to handle Error returned from handleErrors.";
433 }
434
TEST(Error,StringError)435 TEST(Error, StringError) {
436 std::string Msg;
437 raw_string_ostream S(Msg);
438 logAllUnhandledErrors(
439 make_error<StringError>("foo" + Twine(42), inconvertibleErrorCode()), S);
440 EXPECT_EQ(S.str(), "foo42\n") << "Unexpected StringError log result";
441
442 auto EC =
443 errorToErrorCode(make_error<StringError>("", errc::invalid_argument));
444 EXPECT_EQ(EC, errc::invalid_argument)
445 << "Failed to convert StringError to error_code.";
446 }
447
TEST(Error,createStringError)448 TEST(Error, createStringError) {
449 static const char *Bar = "bar";
450 static const std::error_code EC = errc::invalid_argument;
451 std::string Msg;
452 raw_string_ostream S(Msg);
453 logAllUnhandledErrors(createStringError(EC, "foo%s%d0x%" PRIx8, Bar, 1, 0xff),
454 S);
455 EXPECT_EQ(S.str(), "foobar10xff\n")
456 << "Unexpected createStringError() log result";
457
458 S.flush();
459 Msg.clear();
460 logAllUnhandledErrors(createStringError(EC, Bar), S);
461 EXPECT_EQ(S.str(), "bar\n")
462 << "Unexpected createStringError() (overloaded) log result";
463
464 S.flush();
465 Msg.clear();
466 auto Res = errorToErrorCode(createStringError(EC, "foo%s", Bar));
467 EXPECT_EQ(Res, EC)
468 << "Failed to convert createStringError() result to error_code.";
469 }
470
471 // Test that the ExitOnError utility works as expected.
TEST(Error,ExitOnError)472 TEST(Error, ExitOnError) {
473 ExitOnError ExitOnErr;
474 ExitOnErr.setBanner("Error in tool:");
475 ExitOnErr.setExitCodeMapper([](const Error &E) {
476 if (E.isA<CustomSubError>())
477 return 2;
478 return 1;
479 });
480
481 // Make sure we don't bail on success.
482 ExitOnErr(Error::success());
483 EXPECT_EQ(ExitOnErr(Expected<int>(7)), 7)
484 << "exitOnError returned an invalid value for Expected";
485
486 int A = 7;
487 int &B = ExitOnErr(Expected<int&>(A));
488 EXPECT_EQ(&A, &B) << "ExitOnError failed to propagate reference";
489
490 // Exit tests.
491 EXPECT_EXIT(ExitOnErr(make_error<CustomError>(7)),
492 ::testing::ExitedWithCode(1), "Error in tool:")
493 << "exitOnError returned an unexpected error result";
494
495 EXPECT_EXIT(ExitOnErr(Expected<int>(make_error<CustomSubError>(0, 0))),
496 ::testing::ExitedWithCode(2), "Error in tool:")
497 << "exitOnError returned an unexpected error result";
498 }
499
500 // Test that the ExitOnError utility works as expected.
TEST(Error,CantFailSuccess)501 TEST(Error, CantFailSuccess) {
502 cantFail(Error::success());
503
504 int X = cantFail(Expected<int>(42));
505 EXPECT_EQ(X, 42) << "Expected value modified by cantFail";
506
507 int Dummy = 42;
508 int &Y = cantFail(Expected<int&>(Dummy));
509 EXPECT_EQ(&Dummy, &Y) << "Reference mangled by cantFail";
510 }
511
512 // Test that cantFail results in a crash if you pass it a failure value.
513 #if LLVM_ENABLE_ABI_BREAKING_CHECKS && !defined(NDEBUG)
TEST(Error,CantFailDeath)514 TEST(Error, CantFailDeath) {
515 EXPECT_DEATH(cantFail(make_error<StringError>("Original error message",
516 inconvertibleErrorCode()),
517 "Cantfail call failed"),
518 "Cantfail call failed\n"
519 "Original error message")
520 << "cantFail(Error) did not cause an abort for failure value";
521
522 EXPECT_DEATH(
523 {
524 auto IEC = inconvertibleErrorCode();
525 int X = cantFail(Expected<int>(make_error<StringError>("foo", IEC)));
526 (void)X;
527 },
528 "Failure value returned from cantFail wrapped call")
529 << "cantFail(Expected<int>) did not cause an abort for failure value";
530 }
531 #endif
532
533
534 // Test Checked Expected<T> in success mode.
TEST(Error,CheckedExpectedInSuccessMode)535 TEST(Error, CheckedExpectedInSuccessMode) {
536 Expected<int> A = 7;
537 EXPECT_TRUE(!!A) << "Expected with non-error value doesn't convert to 'true'";
538 // Access is safe in second test, since we checked the error in the first.
539 EXPECT_EQ(*A, 7) << "Incorrect Expected non-error value";
540 }
541
542 // Test Expected with reference type.
TEST(Error,ExpectedWithReferenceType)543 TEST(Error, ExpectedWithReferenceType) {
544 int A = 7;
545 Expected<int&> B = A;
546 // 'Check' B.
547 (void)!!B;
548 int &C = *B;
549 EXPECT_EQ(&A, &C) << "Expected failed to propagate reference";
550 }
551
552 // Test Unchecked Expected<T> in success mode.
553 // We expect this to blow up the same way Error would.
554 // Test runs in debug mode only.
555 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
TEST(Error,UncheckedExpectedInSuccessModeDestruction)556 TEST(Error, UncheckedExpectedInSuccessModeDestruction) {
557 EXPECT_DEATH({ Expected<int> A = 7; },
558 "Expected<T> must be checked before access or destruction.")
559 << "Unchecekd Expected<T> success value did not cause an abort().";
560 }
561 #endif
562
563 // Test Unchecked Expected<T> in success mode.
564 // We expect this to blow up the same way Error would.
565 // Test runs in debug mode only.
566 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
TEST(Error,UncheckedExpectedInSuccessModeAccess)567 TEST(Error, UncheckedExpectedInSuccessModeAccess) {
568 EXPECT_DEATH({ Expected<int> A = 7; *A; },
569 "Expected<T> must be checked before access or destruction.")
570 << "Unchecekd Expected<T> success value did not cause an abort().";
571 }
572 #endif
573
574 // Test Unchecked Expected<T> in success mode.
575 // We expect this to blow up the same way Error would.
576 // Test runs in debug mode only.
577 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
TEST(Error,UncheckedExpectedInSuccessModeAssignment)578 TEST(Error, UncheckedExpectedInSuccessModeAssignment) {
579 EXPECT_DEATH({ Expected<int> A = 7; A = 7; },
580 "Expected<T> must be checked before access or destruction.")
581 << "Unchecekd Expected<T> success value did not cause an abort().";
582 }
583 #endif
584
585 // Test Expected<T> in failure mode.
TEST(Error,ExpectedInFailureMode)586 TEST(Error, ExpectedInFailureMode) {
587 Expected<int> A = make_error<CustomError>(42);
588 EXPECT_FALSE(!!A) << "Expected with error value doesn't convert to 'false'";
589 Error E = A.takeError();
590 EXPECT_TRUE(E.isA<CustomError>()) << "Incorrect Expected error value";
591 consumeError(std::move(E));
592 }
593
594 // Check that an Expected instance with an error value doesn't allow access to
595 // operator*.
596 // Test runs in debug mode only.
597 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
TEST(Error,AccessExpectedInFailureMode)598 TEST(Error, AccessExpectedInFailureMode) {
599 Expected<int> A = make_error<CustomError>(42);
600 EXPECT_DEATH(*A, "Expected<T> must be checked before access or destruction.")
601 << "Incorrect Expected error value";
602 consumeError(A.takeError());
603 }
604 #endif
605
606 // Check that an Expected instance with an error triggers an abort if
607 // unhandled.
608 // Test runs in debug mode only.
609 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
TEST(Error,UnhandledExpectedInFailureMode)610 TEST(Error, UnhandledExpectedInFailureMode) {
611 EXPECT_DEATH({ Expected<int> A = make_error<CustomError>(42); },
612 "Expected<T> must be checked before access or destruction.")
613 << "Unchecked Expected<T> failure value did not cause an abort()";
614 }
615 #endif
616
617 // Test covariance of Expected.
TEST(Error,ExpectedCovariance)618 TEST(Error, ExpectedCovariance) {
619 class B {};
620 class D : public B {};
621
622 Expected<B *> A1(Expected<D *>(nullptr));
623 // Check A1 by converting to bool before assigning to it.
624 (void)!!A1;
625 A1 = Expected<D *>(nullptr);
626 // Check A1 again before destruction.
627 (void)!!A1;
628
629 Expected<std::unique_ptr<B>> A2(Expected<std::unique_ptr<D>>(nullptr));
630 // Check A2 by converting to bool before assigning to it.
631 (void)!!A2;
632 A2 = Expected<std::unique_ptr<D>>(nullptr);
633 // Check A2 again before destruction.
634 (void)!!A2;
635 }
636
637 // Test that handleExpected just returns success values.
TEST(Error,HandleExpectedSuccess)638 TEST(Error, HandleExpectedSuccess) {
639 auto ValOrErr =
640 handleExpected(Expected<int>(42),
641 []() { return Expected<int>(43); });
642 EXPECT_TRUE(!!ValOrErr)
643 << "handleExpected should have returned a success value here";
644 EXPECT_EQ(*ValOrErr, 42)
645 << "handleExpected should have returned the original success value here";
646 }
647
648 enum FooStrategy { Aggressive, Conservative };
649
foo(FooStrategy S)650 static Expected<int> foo(FooStrategy S) {
651 if (S == Aggressive)
652 return make_error<CustomError>(7);
653 return 42;
654 }
655
656 // Test that handleExpected invokes the error path if errors are not handled.
TEST(Error,HandleExpectedUnhandledError)657 TEST(Error, HandleExpectedUnhandledError) {
658 // foo(Aggressive) should return a CustomError which should pass through as
659 // there is no handler for CustomError.
660 auto ValOrErr =
661 handleExpected(
662 foo(Aggressive),
663 []() { return foo(Conservative); });
664
665 EXPECT_FALSE(!!ValOrErr)
666 << "handleExpected should have returned an error here";
667 auto Err = ValOrErr.takeError();
668 EXPECT_TRUE(Err.isA<CustomError>())
669 << "handleExpected should have returned the CustomError generated by "
670 "foo(Aggressive) here";
671 consumeError(std::move(Err));
672 }
673
674 // Test that handleExpected invokes the fallback path if errors are handled.
TEST(Error,HandleExpectedHandledError)675 TEST(Error, HandleExpectedHandledError) {
676 // foo(Aggressive) should return a CustomError which should handle triggering
677 // the fallback path.
678 auto ValOrErr =
679 handleExpected(
680 foo(Aggressive),
681 []() { return foo(Conservative); },
682 [](const CustomError&) { /* do nothing */ });
683
684 EXPECT_TRUE(!!ValOrErr)
685 << "handleExpected should have returned a success value here";
686 EXPECT_EQ(*ValOrErr, 42)
687 << "handleExpected returned the wrong success value";
688 }
689
TEST(Error,ErrorCodeConversions)690 TEST(Error, ErrorCodeConversions) {
691 // Round-trip a success value to check that it converts correctly.
692 EXPECT_EQ(errorToErrorCode(errorCodeToError(std::error_code())),
693 std::error_code())
694 << "std::error_code() should round-trip via Error conversions";
695
696 // Round-trip an error value to check that it converts correctly.
697 EXPECT_EQ(errorToErrorCode(errorCodeToError(errc::invalid_argument)),
698 errc::invalid_argument)
699 << "std::error_code error value should round-trip via Error "
700 "conversions";
701
702 // Round-trip a success value through ErrorOr/Expected to check that it
703 // converts correctly.
704 {
705 auto Orig = ErrorOr<int>(42);
706 auto RoundTripped =
707 expectedToErrorOr(errorOrToExpected(ErrorOr<int>(42)));
708 EXPECT_EQ(*Orig, *RoundTripped)
709 << "ErrorOr<T> success value should round-trip via Expected<T> "
710 "conversions.";
711 }
712
713 // Round-trip a failure value through ErrorOr/Expected to check that it
714 // converts correctly.
715 {
716 auto Orig = ErrorOr<int>(errc::invalid_argument);
717 auto RoundTripped =
718 expectedToErrorOr(
719 errorOrToExpected(ErrorOr<int>(errc::invalid_argument)));
720 EXPECT_EQ(Orig.getError(), RoundTripped.getError())
721 << "ErrorOr<T> failure value should round-trip via Expected<T> "
722 "conversions.";
723 }
724 }
725
726 // Test that error messages work.
TEST(Error,ErrorMessage)727 TEST(Error, ErrorMessage) {
728 EXPECT_EQ(toString(Error::success()).compare(""), 0);
729
730 Error E1 = make_error<CustomError>(0);
731 EXPECT_EQ(toString(std::move(E1)).compare("CustomError {0}"), 0);
732
733 Error E2 = make_error<CustomError>(0);
734 handleAllErrors(std::move(E2), [](const CustomError &CE) {
735 EXPECT_EQ(CE.message().compare("CustomError {0}"), 0);
736 });
737
738 Error E3 = joinErrors(make_error<CustomError>(0), make_error<CustomError>(1));
739 EXPECT_EQ(toString(std::move(E3))
740 .compare("CustomError {0}\n"
741 "CustomError {1}"),
742 0);
743 }
744
TEST(Error,Stream)745 TEST(Error, Stream) {
746 {
747 Error OK = Error::success();
748 std::string Buf;
749 llvm::raw_string_ostream S(Buf);
750 S << OK;
751 EXPECT_EQ("success", S.str());
752 consumeError(std::move(OK));
753 }
754 {
755 Error E1 = make_error<CustomError>(0);
756 std::string Buf;
757 llvm::raw_string_ostream S(Buf);
758 S << E1;
759 EXPECT_EQ("CustomError {0}", S.str());
760 consumeError(std::move(E1));
761 }
762 }
763
TEST(Error,SucceededMatcher)764 TEST(Error, SucceededMatcher) {
765 EXPECT_THAT_ERROR(Error::success(), Succeeded());
766 EXPECT_NONFATAL_FAILURE(
767 EXPECT_THAT_ERROR(make_error<CustomError>(0), Succeeded()),
768 "Expected: succeeded\n Actual: failed (CustomError {0})");
769
770 EXPECT_THAT_EXPECTED(Expected<int>(0), Succeeded());
771 EXPECT_NONFATAL_FAILURE(
772 EXPECT_THAT_EXPECTED(Expected<int>(make_error<CustomError>(0)),
773 Succeeded()),
774 "Expected: succeeded\n Actual: failed (CustomError {0})");
775 int a = 1;
776 EXPECT_THAT_EXPECTED(Expected<int &>(a), Succeeded());
777 }
778
TEST(Error,FailedMatcher)779 TEST(Error, FailedMatcher) {
780 EXPECT_THAT_ERROR(make_error<CustomError>(0), Failed());
781 EXPECT_NONFATAL_FAILURE(EXPECT_THAT_ERROR(Error::success(), Failed()),
782 "Expected: failed\n Actual: succeeded");
783
784 EXPECT_THAT_ERROR(make_error<CustomError>(0), Failed<CustomError>());
785 EXPECT_NONFATAL_FAILURE(
786 EXPECT_THAT_ERROR(Error::success(), Failed<CustomError>()),
787 "Expected: failed with Error of given type\n Actual: succeeded");
788 EXPECT_NONFATAL_FAILURE(
789 EXPECT_THAT_ERROR(make_error<CustomError>(0), Failed<CustomSubError>()),
790 "Error was not of given type");
791 EXPECT_NONFATAL_FAILURE(
792 EXPECT_THAT_ERROR(
793 joinErrors(make_error<CustomError>(0), make_error<CustomError>(1)),
794 Failed<CustomError>()),
795 "multiple errors");
796
797 EXPECT_THAT_ERROR(
798 make_error<CustomError>(0),
799 Failed<CustomError>(testing::Property(&CustomError::getInfo, 0)));
800 EXPECT_NONFATAL_FAILURE(
801 EXPECT_THAT_ERROR(
802 make_error<CustomError>(0),
803 Failed<CustomError>(testing::Property(&CustomError::getInfo, 1))),
804 "Expected: failed with Error of given type and the error is an object "
805 "whose given property is equal to 1\n"
806 " Actual: failed (CustomError {0})");
807 EXPECT_THAT_ERROR(make_error<CustomError>(0), Failed<ErrorInfoBase>());
808
809 EXPECT_THAT_EXPECTED(Expected<int>(make_error<CustomError>(0)), Failed());
810 EXPECT_NONFATAL_FAILURE(
811 EXPECT_THAT_EXPECTED(Expected<int>(0), Failed()),
812 "Expected: failed\n Actual: succeeded with value 0");
813 EXPECT_THAT_EXPECTED(Expected<int &>(make_error<CustomError>(0)), Failed());
814 }
815
TEST(Error,HasValueMatcher)816 TEST(Error, HasValueMatcher) {
817 EXPECT_THAT_EXPECTED(Expected<int>(0), HasValue(0));
818 EXPECT_NONFATAL_FAILURE(
819 EXPECT_THAT_EXPECTED(Expected<int>(make_error<CustomError>(0)),
820 HasValue(0)),
821 "Expected: succeeded with value (is equal to 0)\n"
822 " Actual: failed (CustomError {0})");
823 EXPECT_NONFATAL_FAILURE(
824 EXPECT_THAT_EXPECTED(Expected<int>(1), HasValue(0)),
825 "Expected: succeeded with value (is equal to 0)\n"
826 " Actual: succeeded with value 1, (isn't equal to 0)");
827
828 int a = 1;
829 EXPECT_THAT_EXPECTED(Expected<int &>(a), HasValue(testing::Eq(1)));
830
831 EXPECT_THAT_EXPECTED(Expected<int>(1), HasValue(testing::Gt(0)));
832 EXPECT_NONFATAL_FAILURE(
833 EXPECT_THAT_EXPECTED(Expected<int>(0), HasValue(testing::Gt(1))),
834 "Expected: succeeded with value (is > 1)\n"
835 " Actual: succeeded with value 0, (isn't > 1)");
836 EXPECT_NONFATAL_FAILURE(
837 EXPECT_THAT_EXPECTED(Expected<int>(make_error<CustomError>(0)),
838 HasValue(testing::Gt(1))),
839 "Expected: succeeded with value (is > 1)\n"
840 " Actual: failed (CustomError {0})");
841 }
842
TEST(Error,FailedWithMessageMatcher)843 TEST(Error, FailedWithMessageMatcher) {
844 EXPECT_THAT_EXPECTED(Expected<int>(make_error<CustomError>(0)),
845 FailedWithMessage("CustomError {0}"));
846
847 EXPECT_NONFATAL_FAILURE(
848 EXPECT_THAT_EXPECTED(Expected<int>(make_error<CustomError>(1)),
849 FailedWithMessage("CustomError {0}")),
850 "Expected: failed with Error whose message has 1 element that is equal "
851 "to \"CustomError {0}\"\n"
852 " Actual: failed (CustomError {1})");
853
854 EXPECT_NONFATAL_FAILURE(
855 EXPECT_THAT_EXPECTED(Expected<int>(0),
856 FailedWithMessage("CustomError {0}")),
857 "Expected: failed with Error whose message has 1 element that is equal "
858 "to \"CustomError {0}\"\n"
859 " Actual: succeeded with value 0");
860
861 EXPECT_NONFATAL_FAILURE(
862 EXPECT_THAT_EXPECTED(Expected<int>(make_error<CustomError>(0)),
863 FailedWithMessage("CustomError {0}", "CustomError {0}")),
864 "Expected: failed with Error whose message has 2 elements where\n"
865 "element #0 is equal to \"CustomError {0}\",\n"
866 "element #1 is equal to \"CustomError {0}\"\n"
867 " Actual: failed (CustomError {0}), which has 1 element");
868
869 EXPECT_NONFATAL_FAILURE(
870 EXPECT_THAT_EXPECTED(
871 Expected<int>(joinErrors(make_error<CustomError>(0),
872 make_error<CustomError>(0))),
873 FailedWithMessage("CustomError {0}")),
874 "Expected: failed with Error whose message has 1 element that is equal "
875 "to \"CustomError {0}\"\n"
876 " Actual: failed (CustomError {0}; CustomError {0}), which has 2 elements");
877
878 EXPECT_THAT_ERROR(
879 joinErrors(make_error<CustomError>(0), make_error<CustomError>(0)),
880 FailedWithMessageArray(testing::SizeIs(2)));
881 }
882
TEST(Error,C_API)883 TEST(Error, C_API) {
884 EXPECT_THAT_ERROR(unwrap(wrap(Error::success())), Succeeded())
885 << "Failed to round-trip Error success value via C API";
886 EXPECT_THAT_ERROR(unwrap(wrap(make_error<CustomError>(0))),
887 Failed<CustomError>())
888 << "Failed to round-trip Error failure value via C API";
889
890 auto Err =
891 wrap(make_error<StringError>("test message", inconvertibleErrorCode()));
892 EXPECT_EQ(LLVMGetErrorTypeId(Err), LLVMGetStringErrorTypeId())
893 << "Failed to match error type ids via C API";
894 char *ErrMsg = LLVMGetErrorMessage(Err);
895 EXPECT_STREQ(ErrMsg, "test message")
896 << "Failed to roundtrip StringError error message via C API";
897 LLVMDisposeErrorMessage(ErrMsg);
898
899 bool GotCSE = false;
900 bool GotCE = false;
901 handleAllErrors(
902 unwrap(wrap(joinErrors(make_error<CustomSubError>(42, 7),
903 make_error<CustomError>(42)))),
904 [&](CustomSubError &CSE) {
905 GotCSE = true;
906 },
907 [&](CustomError &CE) {
908 GotCE = true;
909 });
910 EXPECT_TRUE(GotCSE) << "Failed to round-trip ErrorList via C API";
911 EXPECT_TRUE(GotCE) << "Failed to round-trip ErrorList via C API";
912 }
913
TEST(Error,FileErrorTest)914 TEST(Error, FileErrorTest) {
915 #if !defined(NDEBUG) && GTEST_HAS_DEATH_TEST
916 EXPECT_DEATH(
917 {
918 Error S = Error::success();
919 consumeError(createFileError("file.bin", std::move(S)));
920 },
921 "");
922 #endif
923 // Not allowed, would fail at compile-time
924 //consumeError(createFileError("file.bin", ErrorSuccess()));
925
926 Error E1 = make_error<CustomError>(1);
927 Error FE1 = createFileError("file.bin", std::move(E1));
928 EXPECT_EQ(toString(std::move(FE1)).compare("'file.bin': CustomError {1}"), 0);
929
930 Error E2 = make_error<CustomError>(2);
931 Error FE2 = createFileError("file.bin", std::move(E2));
932 handleAllErrors(std::move(FE2), [](const FileError &F) {
933 EXPECT_EQ(F.message().compare("'file.bin': CustomError {2}"), 0);
934 });
935
936 Error E3 = make_error<CustomError>(3);
937 Error FE3 = createFileError("file.bin", std::move(E3));
938 auto E31 = handleErrors(std::move(FE3), [](std::unique_ptr<FileError> F) {
939 return F->takeError();
940 });
941 handleAllErrors(std::move(E31), [](const CustomError &C) {
942 EXPECT_EQ(C.message().compare("CustomError {3}"), 0);
943 });
944
945 Error FE4 =
946 joinErrors(createFileError("file.bin", make_error<CustomError>(41)),
947 createFileError("file2.bin", make_error<CustomError>(42)));
948 EXPECT_EQ(toString(std::move(FE4))
949 .compare("'file.bin': CustomError {41}\n"
950 "'file2.bin': CustomError {42}"),
951 0);
952 }
953
954 enum class test_error_code {
955 unspecified = 1,
956 error_1,
957 error_2,
958 };
959
960 } // end anon namespace
961
962 namespace std {
963 template <>
964 struct is_error_code_enum<test_error_code> : std::true_type {};
965 } // namespace std
966
967 namespace {
968
969 const std::error_category &TErrorCategory();
970
make_error_code(test_error_code E)971 inline std::error_code make_error_code(test_error_code E) {
972 return std::error_code(static_cast<int>(E), TErrorCategory());
973 }
974
975 class TestDebugError : public ErrorInfo<TestDebugError, StringError> {
976 public:
977 using ErrorInfo<TestDebugError, StringError >::ErrorInfo; // inherit constructors
TestDebugError(const Twine & S)978 TestDebugError(const Twine &S) : ErrorInfo(S, test_error_code::unspecified) {}
979 static char ID;
980 };
981
982 class TestErrorCategory : public std::error_category {
983 public:
name() const984 const char *name() const noexcept override { return "error"; }
message(int Condition) const985 std::string message(int Condition) const override {
986 switch (static_cast<test_error_code>(Condition)) {
987 case test_error_code::unspecified:
988 return "An unknown error has occurred.";
989 case test_error_code::error_1:
990 return "Error 1.";
991 case test_error_code::error_2:
992 return "Error 2.";
993 }
994 llvm_unreachable("Unrecognized test_error_code");
995 }
996 };
997
998 static llvm::ManagedStatic<TestErrorCategory> TestErrCategory;
TErrorCategory()999 const std::error_category &TErrorCategory() { return *TestErrCategory; }
1000
1001 char TestDebugError::ID;
1002
TEST(Error,SubtypeStringErrorTest)1003 TEST(Error, SubtypeStringErrorTest) {
1004 auto E1 = make_error<TestDebugError>(test_error_code::error_1);
1005 EXPECT_EQ(toString(std::move(E1)).compare("Error 1."), 0);
1006
1007 auto E2 = make_error<TestDebugError>(test_error_code::error_1,
1008 "Detailed information");
1009 EXPECT_EQ(toString(std::move(E2)).compare("Error 1. Detailed information"),
1010 0);
1011
1012 auto E3 = make_error<TestDebugError>(test_error_code::error_2);
1013 handleAllErrors(std::move(E3), [](const TestDebugError &F) {
1014 EXPECT_EQ(F.message().compare("Error 2."), 0);
1015 });
1016
1017 auto E4 = joinErrors(make_error<TestDebugError>(test_error_code::error_1,
1018 "Detailed information"),
1019 make_error<TestDebugError>(test_error_code::error_2));
1020 EXPECT_EQ(toString(std::move(E4))
1021 .compare("Error 1. Detailed information\n"
1022 "Error 2."),
1023 0);
1024 }
1025
1026 } // namespace
1027