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