[ARM] Remove declaration of unimplemented function. NFC.
[llvm-complete.git] / unittests / Support / ErrorTest.cpp
blobc4a9f3e51684aab06ee7a8513b1fd849f32d4186
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 //===----------------------------------------------------------------------===//
9 #include "llvm/Support/Error.h"
10 #include "llvm-c/Error.h"
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>
21 using namespace llvm;
23 namespace {
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.
29 CustomError(int Info) : Info(Info) {}
31 // Get the info attached to this error.
32 int getInfo() const { return Info; }
34 // Log this error to a stream.
35 void log(raw_ostream &OS) const override {
36 OS << "CustomError {" << getInfo() << "}";
39 std::error_code convertToErrorCode() const override {
40 llvm_unreachable("CustomError doesn't support ECError conversion");
43 // Used by ErrorInfo::classID.
44 static char ID;
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.
51 CustomError() : Info(0) {}
53 int Info;
56 char CustomError::ID = 0;
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.
63 CustomSubError(int Info, int ExtraInfo) : ExtraInfo(ExtraInfo) {
64 this->Info = Info;
67 // Get the extra info attached to this error.
68 int getExtraInfo() const { return ExtraInfo; }
70 // Log this error to a stream.
71 void log(raw_ostream &OS) const override {
72 OS << "CustomSubError { " << getInfo() << ", " << getExtraInfo() << "}";
75 std::error_code convertToErrorCode() const override {
76 llvm_unreachable("CustomSubError doesn't support ECError conversion");
79 // Used by ErrorInfo::classID.
80 static char ID;
82 protected:
83 int ExtraInfo;
86 char CustomSubError::ID = 0;
88 static Error handleCustomError(const CustomError &CE) {
89 return Error::success();
92 static void handleCustomErrorVoid(const CustomError &CE) {}
94 static Error handleCustomErrorUP(std::unique_ptr<CustomError> CE) {
95 return Error::success();
98 static void handleCustomErrorUPVoid(std::unique_ptr<CustomError> CE) {}
100 // Test that success values implicitly convert to false, and don't cause crashes
101 // once they've been implicitly converted.
102 TEST(Error, CheckedSuccess) {
103 Error E = Error::success();
104 EXPECT_FALSE(E) << "Unexpected error while testing Error 'Success'";
107 // Test that unchecked success values cause an abort.
108 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
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()";
114 #endif
116 // ErrorAsOutParameter tester.
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;
126 // Test that ErrorAsOutParameter sets the checked flag on construction.
127 TEST(Error, ErrorAsOutParameterChecked) {
128 Error E = Error::success();
129 errAsOutParamHelper(E);
130 (void)!!E;
133 // Test that ErrorAsOutParameter clears the checked flag on destruction.
134 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
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.";
140 #endif
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
146 TEST(Error, UncheckedError) {
147 auto DropUnhandledError = []() {
148 Error E = make_error<CustomError>(42);
149 (void)!E;
151 EXPECT_DEATH(DropUnhandledError(),
152 "Program aborted due to an unhandled Error:")
153 << "Unhandled Error failure value did not cause abort()";
155 #endif
157 // Check 'Error::isA<T>' method handling.
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();
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>());
170 consumeError(std::move(E));
171 consumeError(std::move(F));
172 consumeError(std::move(G));
175 // Check that we can handle a custom error.
176 TEST(Error, HandleCustomError) {
177 int CaughtErrorInfo = 0;
178 handleAllErrors(make_error<CustomError>(42), [&](const CustomError &CE) {
179 CaughtErrorInfo = CE.getInfo();
182 EXPECT_TRUE(CaughtErrorInfo == 42) << "Wrong result from CustomError handler";
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
198 TEST(Error, HandlerTypeDeduction) {
200 handleAllErrors(make_error<CustomError>(42), [](const CustomError &CE) {});
202 handleAllErrors(
203 make_error<CustomError>(42),
204 [](const CustomError &CE) mutable -> Error { return Error::success(); });
206 handleAllErrors(make_error<CustomError>(42),
207 [](const CustomError &CE) mutable {});
209 handleAllErrors(make_error<CustomError>(42),
210 [](CustomError &CE) -> Error { return Error::success(); });
212 handleAllErrors(make_error<CustomError>(42), [](CustomError &CE) {});
214 handleAllErrors(make_error<CustomError>(42),
215 [](CustomError &CE) mutable -> Error { return Error::success(); });
217 handleAllErrors(make_error<CustomError>(42), [](CustomError &CE) mutable {});
219 handleAllErrors(
220 make_error<CustomError>(42),
221 [](std::unique_ptr<CustomError> CE) -> Error { return Error::success(); });
223 handleAllErrors(make_error<CustomError>(42),
224 [](std::unique_ptr<CustomError> CE) {});
226 handleAllErrors(
227 make_error<CustomError>(42),
228 [](std::unique_ptr<CustomError> CE) mutable -> Error { return Error::success(); });
230 handleAllErrors(make_error<CustomError>(42),
231 [](std::unique_ptr<CustomError> CE) mutable {});
233 // Check that named handlers of type 'Error (const Err&)' work.
234 handleAllErrors(make_error<CustomError>(42), handleCustomError);
236 // Check that named handlers of type 'void (const Err&)' work.
237 handleAllErrors(make_error<CustomError>(42), handleCustomErrorVoid);
239 // Check that named handlers of type 'Error (std::unique_ptr<Err>)' work.
240 handleAllErrors(make_error<CustomError>(42), handleCustomErrorUP);
242 // Check that named handlers of type 'Error (std::unique_ptr<Err>)' work.
243 handleAllErrors(make_error<CustomError>(42), handleCustomErrorUPVoid);
246 // Test that we can handle errors with custom base classes.
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();
256 EXPECT_TRUE(CaughtErrorInfo == 42 && CaughtErrorExtraInfo == 7)
257 << "Wrong result from CustomSubError handler";
260 // Check that we trigger only the first handler that applies.
261 TEST(Error, FirstHandlerOnly) {
262 int DummyInfo = 0;
263 int CaughtErrorInfo = 0;
264 int CaughtErrorExtraInfo = 0;
266 handleAllErrors(make_error<CustomSubError>(42, 7),
267 [&](const CustomSubError &SE) {
268 CaughtErrorInfo = SE.getInfo();
269 CaughtErrorExtraInfo = SE.getExtraInfo();
271 [&](const CustomError &CE) { DummyInfo = CE.getInfo(); });
273 EXPECT_TRUE(CaughtErrorInfo == 42 && CaughtErrorExtraInfo == 7 &&
274 DummyInfo == 0)
275 << "Activated the wrong Error handler(s)";
278 // Check that general handlers shadow specific ones.
279 TEST(Error, HandlerShadowing) {
280 int CaughtErrorInfo = 0;
281 int DummyInfo = 0;
282 int DummyExtraInfo = 0;
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();
292 EXPECT_TRUE(CaughtErrorInfo == 42 && DummyInfo == 0 && DummyExtraInfo == 0)
293 << "General Error handler did not shadow specific handler";
296 // Test joinErrors.
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));
304 handleAllErrors(std::move(E),
305 [&](const CustomSubError &SE) {
306 CustomErrorInfo2 = SE.getInfo();
307 CustomErrorExtraInfo = SE.getExtraInfo();
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();
320 EXPECT_TRUE(CustomErrorInfo1 == 7 && CustomErrorInfo2 == 42 &&
321 CustomErrorExtraInfo == 7)
322 << "Failed handling compound Error.";
324 // Test appending a single item to a list.
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();
335 EXPECT_EQ(Sum, 21) << "Failed to correctly append error to error list.";
338 // Test prepending a single item to a list.
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();
349 EXPECT_EQ(Sum, 21) << "Failed to correctly prepend error to error list.";
352 // Test concatenating two error lists.
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();
366 EXPECT_EQ(Sum, 28) << "Failed to correctly concatenate error lists.";
370 // Test that we can consume success values.
371 TEST(Error, ConsumeSuccess) {
372 Error E = Error::success();
373 consumeError(std::move(E));
376 TEST(Error, ConsumeError) {
377 Error E = make_error<CustomError>(7);
378 consumeError(std::move(E));
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
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);
392 EXPECT_DEATH(FailToHandle(),
393 "Failure value returned from cantFail wrapped call")
394 << "Unhandled Error in handleAllErrors call did not cause an "
395 "abort()";
397 #endif
399 // Test that handleAllUnhandledErrors crashes if an error is returned from a
400 // handler.
401 // Test runs in debug mode only.
402 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
403 TEST(Error, FailureFromHandler) {
404 auto ReturnErrorFromHandler = []() {
405 handleAllErrors(make_error<CustomError>(7),
406 [&](std::unique_ptr<CustomSubError> SE) {
407 return Error(std::move(SE));
411 EXPECT_DEATH(ReturnErrorFromHandler(),
412 "Failure value returned from cantFail wrapped call")
413 << " Error returned from handler in handleAllErrors call did not "
414 "cause abort()";
416 #endif
418 // Test that we can return values from handleErrors.
419 TEST(Error, CatchErrorFromHandler) {
420 int ErrorInfo = 0;
422 Error E = handleErrors(
423 make_error<CustomError>(7),
424 [&](std::unique_ptr<CustomError> CE) { return Error(std::move(CE)); });
426 handleAllErrors(std::move(E),
427 [&](const CustomError &CE) { ErrorInfo = CE.getInfo(); });
429 EXPECT_EQ(ErrorInfo, 7)
430 << "Failed to handle Error returned from handleErrors.";
433 TEST(Error, StringError) {
434 std::string Msg;
435 raw_string_ostream S(Msg);
436 logAllUnhandledErrors(
437 make_error<StringError>("foo" + Twine(42), inconvertibleErrorCode()), S);
438 EXPECT_EQ(S.str(), "foo42\n") << "Unexpected StringError log result";
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.";
446 TEST(Error, createStringError) {
447 static const char *Bar = "bar";
448 static const std::error_code EC = errc::invalid_argument;
449 std::string Msg;
450 raw_string_ostream S(Msg);
451 logAllUnhandledErrors(createStringError(EC, "foo%s%d0x%" PRIx8, Bar, 1, 0xff),
453 EXPECT_EQ(S.str(), "foobar10xff\n")
454 << "Unexpected createStringError() log result";
456 S.flush();
457 Msg.clear();
458 logAllUnhandledErrors(createStringError(EC, Bar), S);
459 EXPECT_EQ(S.str(), "bar\n")
460 << "Unexpected createStringError() (overloaded) log result";
462 S.flush();
463 Msg.clear();
464 auto Res = errorToErrorCode(createStringError(EC, "foo%s", Bar));
465 EXPECT_EQ(Res, EC)
466 << "Failed to convert createStringError() result to error_code.";
469 // Test that the ExitOnError utility works as expected.
470 TEST(Error, ExitOnError) {
471 ExitOnError ExitOnErr;
472 ExitOnErr.setBanner("Error in tool:");
473 ExitOnErr.setExitCodeMapper([](const Error &E) {
474 if (E.isA<CustomSubError>())
475 return 2;
476 return 1;
479 // Make sure we don't bail on success.
480 ExitOnErr(Error::success());
481 EXPECT_EQ(ExitOnErr(Expected<int>(7)), 7)
482 << "exitOnError returned an invalid value for Expected";
484 int A = 7;
485 int &B = ExitOnErr(Expected<int&>(A));
486 EXPECT_EQ(&A, &B) << "ExitOnError failed to propagate reference";
488 // Exit tests.
489 EXPECT_EXIT(ExitOnErr(make_error<CustomError>(7)),
490 ::testing::ExitedWithCode(1), "Error in tool:")
491 << "exitOnError returned an unexpected error result";
493 EXPECT_EXIT(ExitOnErr(Expected<int>(make_error<CustomSubError>(0, 0))),
494 ::testing::ExitedWithCode(2), "Error in tool:")
495 << "exitOnError returned an unexpected error result";
498 // Test that the ExitOnError utility works as expected.
499 TEST(Error, CantFailSuccess) {
500 cantFail(Error::success());
502 int X = cantFail(Expected<int>(42));
503 EXPECT_EQ(X, 42) << "Expected value modified by cantFail";
505 int Dummy = 42;
506 int &Y = cantFail(Expected<int&>(Dummy));
507 EXPECT_EQ(&Dummy, &Y) << "Reference mangled by cantFail";
510 // Test that cantFail results in a crash if you pass it a failure value.
511 #if LLVM_ENABLE_ABI_BREAKING_CHECKS && !defined(NDEBUG)
512 TEST(Error, CantFailDeath) {
513 EXPECT_DEATH(
514 cantFail(make_error<StringError>("foo", inconvertibleErrorCode()),
515 "Cantfail call failed"),
516 "Cantfail call failed")
517 << "cantFail(Error) did not cause an abort for failure value";
519 EXPECT_DEATH(
521 auto IEC = inconvertibleErrorCode();
522 int X = cantFail(Expected<int>(make_error<StringError>("foo", IEC)));
523 (void)X;
525 "Failure value returned from cantFail wrapped call")
526 << "cantFail(Expected<int>) did not cause an abort for failure value";
528 #endif
531 // Test Checked Expected<T> in success mode.
532 TEST(Error, CheckedExpectedInSuccessMode) {
533 Expected<int> A = 7;
534 EXPECT_TRUE(!!A) << "Expected with non-error value doesn't convert to 'true'";
535 // Access is safe in second test, since we checked the error in the first.
536 EXPECT_EQ(*A, 7) << "Incorrect Expected non-error value";
539 // Test Expected with reference type.
540 TEST(Error, ExpectedWithReferenceType) {
541 int A = 7;
542 Expected<int&> B = A;
543 // 'Check' B.
544 (void)!!B;
545 int &C = *B;
546 EXPECT_EQ(&A, &C) << "Expected failed to propagate reference";
549 // Test Unchecked Expected<T> in success mode.
550 // We expect this to blow up the same way Error would.
551 // Test runs in debug mode only.
552 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
553 TEST(Error, UncheckedExpectedInSuccessModeDestruction) {
554 EXPECT_DEATH({ Expected<int> A = 7; },
555 "Expected<T> must be checked before access or destruction.")
556 << "Unchecekd Expected<T> success value did not cause an abort().";
558 #endif
560 // Test Unchecked Expected<T> in success mode.
561 // We expect this to blow up the same way Error would.
562 // Test runs in debug mode only.
563 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
564 TEST(Error, UncheckedExpectedInSuccessModeAccess) {
565 EXPECT_DEATH({ Expected<int> A = 7; *A; },
566 "Expected<T> must be checked before access or destruction.")
567 << "Unchecekd Expected<T> success value did not cause an abort().";
569 #endif
571 // Test Unchecked Expected<T> in success mode.
572 // We expect this to blow up the same way Error would.
573 // Test runs in debug mode only.
574 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
575 TEST(Error, UncheckedExpectedInSuccessModeAssignment) {
576 EXPECT_DEATH({ Expected<int> A = 7; A = 7; },
577 "Expected<T> must be checked before access or destruction.")
578 << "Unchecekd Expected<T> success value did not cause an abort().";
580 #endif
582 // Test Expected<T> in failure mode.
583 TEST(Error, ExpectedInFailureMode) {
584 Expected<int> A = make_error<CustomError>(42);
585 EXPECT_FALSE(!!A) << "Expected with error value doesn't convert to 'false'";
586 Error E = A.takeError();
587 EXPECT_TRUE(E.isA<CustomError>()) << "Incorrect Expected error value";
588 consumeError(std::move(E));
591 // Check that an Expected instance with an error value doesn't allow access to
592 // operator*.
593 // Test runs in debug mode only.
594 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
595 TEST(Error, AccessExpectedInFailureMode) {
596 Expected<int> A = make_error<CustomError>(42);
597 EXPECT_DEATH(*A, "Expected<T> must be checked before access or destruction.")
598 << "Incorrect Expected error value";
599 consumeError(A.takeError());
601 #endif
603 // Check that an Expected instance with an error triggers an abort if
604 // unhandled.
605 // Test runs in debug mode only.
606 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
607 TEST(Error, UnhandledExpectedInFailureMode) {
608 EXPECT_DEATH({ Expected<int> A = make_error<CustomError>(42); },
609 "Expected<T> must be checked before access or destruction.")
610 << "Unchecked Expected<T> failure value did not cause an abort()";
612 #endif
614 // Test covariance of Expected.
615 TEST(Error, ExpectedCovariance) {
616 class B {};
617 class D : public B {};
619 Expected<B *> A1(Expected<D *>(nullptr));
620 // Check A1 by converting to bool before assigning to it.
621 (void)!!A1;
622 A1 = Expected<D *>(nullptr);
623 // Check A1 again before destruction.
624 (void)!!A1;
626 Expected<std::unique_ptr<B>> A2(Expected<std::unique_ptr<D>>(nullptr));
627 // Check A2 by converting to bool before assigning to it.
628 (void)!!A2;
629 A2 = Expected<std::unique_ptr<D>>(nullptr);
630 // Check A2 again before destruction.
631 (void)!!A2;
634 // Test that handleExpected just returns success values.
635 TEST(Error, HandleExpectedSuccess) {
636 auto ValOrErr =
637 handleExpected(Expected<int>(42),
638 []() { return Expected<int>(43); });
639 EXPECT_TRUE(!!ValOrErr)
640 << "handleExpected should have returned a success value here";
641 EXPECT_EQ(*ValOrErr, 42)
642 << "handleExpected should have returned the original success value here";
645 enum FooStrategy { Aggressive, Conservative };
647 static Expected<int> foo(FooStrategy S) {
648 if (S == Aggressive)
649 return make_error<CustomError>(7);
650 return 42;
653 // Test that handleExpected invokes the error path if errors are not handled.
654 TEST(Error, HandleExpectedUnhandledError) {
655 // foo(Aggressive) should return a CustomError which should pass through as
656 // there is no handler for CustomError.
657 auto ValOrErr =
658 handleExpected(
659 foo(Aggressive),
660 []() { return foo(Conservative); });
662 EXPECT_FALSE(!!ValOrErr)
663 << "handleExpected should have returned an error here";
664 auto Err = ValOrErr.takeError();
665 EXPECT_TRUE(Err.isA<CustomError>())
666 << "handleExpected should have returned the CustomError generated by "
667 "foo(Aggressive) here";
668 consumeError(std::move(Err));
671 // Test that handleExpected invokes the fallback path if errors are handled.
672 TEST(Error, HandleExpectedHandledError) {
673 // foo(Aggressive) should return a CustomError which should handle triggering
674 // the fallback path.
675 auto ValOrErr =
676 handleExpected(
677 foo(Aggressive),
678 []() { return foo(Conservative); },
679 [](const CustomError&) { /* do nothing */ });
681 EXPECT_TRUE(!!ValOrErr)
682 << "handleExpected should have returned a success value here";
683 EXPECT_EQ(*ValOrErr, 42)
684 << "handleExpected returned the wrong success value";
687 TEST(Error, ErrorCodeConversions) {
688 // Round-trip a success value to check that it converts correctly.
689 EXPECT_EQ(errorToErrorCode(errorCodeToError(std::error_code())),
690 std::error_code())
691 << "std::error_code() should round-trip via Error conversions";
693 // Round-trip an error value to check that it converts correctly.
694 EXPECT_EQ(errorToErrorCode(errorCodeToError(errc::invalid_argument)),
695 errc::invalid_argument)
696 << "std::error_code error value should round-trip via Error "
697 "conversions";
699 // Round-trip a success value through ErrorOr/Expected to check that it
700 // converts correctly.
702 auto Orig = ErrorOr<int>(42);
703 auto RoundTripped =
704 expectedToErrorOr(errorOrToExpected(ErrorOr<int>(42)));
705 EXPECT_EQ(*Orig, *RoundTripped)
706 << "ErrorOr<T> success value should round-trip via Expected<T> "
707 "conversions.";
710 // Round-trip a failure value through ErrorOr/Expected to check that it
711 // converts correctly.
713 auto Orig = ErrorOr<int>(errc::invalid_argument);
714 auto RoundTripped =
715 expectedToErrorOr(
716 errorOrToExpected(ErrorOr<int>(errc::invalid_argument)));
717 EXPECT_EQ(Orig.getError(), RoundTripped.getError())
718 << "ErrorOr<T> failure value should round-trip via Expected<T> "
719 "conversions.";
723 // Test that error messages work.
724 TEST(Error, ErrorMessage) {
725 EXPECT_EQ(toString(Error::success()).compare(""), 0);
727 Error E1 = make_error<CustomError>(0);
728 EXPECT_EQ(toString(std::move(E1)).compare("CustomError {0}"), 0);
730 Error E2 = make_error<CustomError>(0);
731 handleAllErrors(std::move(E2), [](const CustomError &CE) {
732 EXPECT_EQ(CE.message().compare("CustomError {0}"), 0);
735 Error E3 = joinErrors(make_error<CustomError>(0), make_error<CustomError>(1));
736 EXPECT_EQ(toString(std::move(E3))
737 .compare("CustomError {0}\n"
738 "CustomError {1}"),
742 TEST(Error, Stream) {
744 Error OK = Error::success();
745 std::string Buf;
746 llvm::raw_string_ostream S(Buf);
747 S << OK;
748 EXPECT_EQ("success", S.str());
749 consumeError(std::move(OK));
752 Error E1 = make_error<CustomError>(0);
753 std::string Buf;
754 llvm::raw_string_ostream S(Buf);
755 S << E1;
756 EXPECT_EQ("CustomError {0}", S.str());
757 consumeError(std::move(E1));
761 TEST(Error, ErrorMatchers) {
762 EXPECT_THAT_ERROR(Error::success(), Succeeded());
763 EXPECT_NONFATAL_FAILURE(
764 EXPECT_THAT_ERROR(make_error<CustomError>(0), Succeeded()),
765 "Expected: succeeded\n Actual: failed (CustomError {0})");
767 EXPECT_THAT_ERROR(make_error<CustomError>(0), Failed());
768 EXPECT_NONFATAL_FAILURE(EXPECT_THAT_ERROR(Error::success(), Failed()),
769 "Expected: failed\n Actual: succeeded");
771 EXPECT_THAT_ERROR(make_error<CustomError>(0), Failed<CustomError>());
772 EXPECT_NONFATAL_FAILURE(
773 EXPECT_THAT_ERROR(Error::success(), Failed<CustomError>()),
774 "Expected: failed with Error of given type\n Actual: succeeded");
775 EXPECT_NONFATAL_FAILURE(
776 EXPECT_THAT_ERROR(make_error<CustomError>(0), Failed<CustomSubError>()),
777 "Error was not of given type");
778 EXPECT_NONFATAL_FAILURE(
779 EXPECT_THAT_ERROR(
780 joinErrors(make_error<CustomError>(0), make_error<CustomError>(1)),
781 Failed<CustomError>()),
782 "multiple errors");
784 EXPECT_THAT_ERROR(
785 make_error<CustomError>(0),
786 Failed<CustomError>(testing::Property(&CustomError::getInfo, 0)));
787 EXPECT_NONFATAL_FAILURE(
788 EXPECT_THAT_ERROR(
789 make_error<CustomError>(0),
790 Failed<CustomError>(testing::Property(&CustomError::getInfo, 1))),
791 "Expected: failed with Error of given type and the error is an object "
792 "whose given property is equal to 1\n"
793 " Actual: failed (CustomError {0})");
794 EXPECT_THAT_ERROR(make_error<CustomError>(0), Failed<ErrorInfoBase>());
796 EXPECT_THAT_EXPECTED(Expected<int>(0), Succeeded());
797 EXPECT_NONFATAL_FAILURE(
798 EXPECT_THAT_EXPECTED(Expected<int>(make_error<CustomError>(0)),
799 Succeeded()),
800 "Expected: succeeded\n Actual: failed (CustomError {0})");
802 EXPECT_THAT_EXPECTED(Expected<int>(make_error<CustomError>(0)), Failed());
803 EXPECT_NONFATAL_FAILURE(
804 EXPECT_THAT_EXPECTED(Expected<int>(0), Failed()),
805 "Expected: failed\n Actual: succeeded with value 0");
807 EXPECT_THAT_EXPECTED(Expected<int>(0), HasValue(0));
808 EXPECT_NONFATAL_FAILURE(
809 EXPECT_THAT_EXPECTED(Expected<int>(make_error<CustomError>(0)),
810 HasValue(0)),
811 "Expected: succeeded with value (is equal to 0)\n"
812 " Actual: failed (CustomError {0})");
813 EXPECT_NONFATAL_FAILURE(
814 EXPECT_THAT_EXPECTED(Expected<int>(1), HasValue(0)),
815 "Expected: succeeded with value (is equal to 0)\n"
816 " Actual: succeeded with value 1, (isn't equal to 0)");
818 EXPECT_THAT_EXPECTED(Expected<int &>(make_error<CustomError>(0)), Failed());
819 int a = 1;
820 EXPECT_THAT_EXPECTED(Expected<int &>(a), Succeeded());
821 EXPECT_THAT_EXPECTED(Expected<int &>(a), HasValue(testing::Eq(1)));
823 EXPECT_THAT_EXPECTED(Expected<int>(1), HasValue(testing::Gt(0)));
824 EXPECT_NONFATAL_FAILURE(
825 EXPECT_THAT_EXPECTED(Expected<int>(0), HasValue(testing::Gt(1))),
826 "Expected: succeeded with value (is > 1)\n"
827 " Actual: succeeded with value 0, (isn't > 1)");
828 EXPECT_NONFATAL_FAILURE(
829 EXPECT_THAT_EXPECTED(Expected<int>(make_error<CustomError>(0)),
830 HasValue(testing::Gt(1))),
831 "Expected: succeeded with value (is > 1)\n"
832 " Actual: failed (CustomError {0})");
835 TEST(Error, C_API) {
836 EXPECT_THAT_ERROR(unwrap(wrap(Error::success())), Succeeded())
837 << "Failed to round-trip Error success value via C API";
838 EXPECT_THAT_ERROR(unwrap(wrap(make_error<CustomError>(0))),
839 Failed<CustomError>())
840 << "Failed to round-trip Error failure value via C API";
842 auto Err =
843 wrap(make_error<StringError>("test message", inconvertibleErrorCode()));
844 EXPECT_EQ(LLVMGetErrorTypeId(Err), LLVMGetStringErrorTypeId())
845 << "Failed to match error type ids via C API";
846 char *ErrMsg = LLVMGetErrorMessage(Err);
847 EXPECT_STREQ(ErrMsg, "test message")
848 << "Failed to roundtrip StringError error message via C API";
849 LLVMDisposeErrorMessage(ErrMsg);
851 bool GotCSE = false;
852 bool GotCE = false;
853 handleAllErrors(
854 unwrap(wrap(joinErrors(make_error<CustomSubError>(42, 7),
855 make_error<CustomError>(42)))),
856 [&](CustomSubError &CSE) {
857 GotCSE = true;
859 [&](CustomError &CE) {
860 GotCE = true;
862 EXPECT_TRUE(GotCSE) << "Failed to round-trip ErrorList via C API";
863 EXPECT_TRUE(GotCE) << "Failed to round-trip ErrorList via C API";
866 TEST(Error, FileErrorTest) {
867 #if !defined(NDEBUG) && GTEST_HAS_DEATH_TEST
868 EXPECT_DEATH(
870 Error S = Error::success();
871 consumeError(createFileError("file.bin", std::move(S)));
873 "");
874 #endif
875 // Not allowed, would fail at compile-time
876 //consumeError(createFileError("file.bin", ErrorSuccess()));
878 Error E1 = make_error<CustomError>(1);
879 Error FE1 = createFileError("file.bin", std::move(E1));
880 EXPECT_EQ(toString(std::move(FE1)).compare("'file.bin': CustomError {1}"), 0);
882 Error E2 = make_error<CustomError>(2);
883 Error FE2 = createFileError("file.bin", std::move(E2));
884 handleAllErrors(std::move(FE2), [](const FileError &F) {
885 EXPECT_EQ(F.message().compare("'file.bin': CustomError {2}"), 0);
888 Error E3 = make_error<CustomError>(3);
889 Error FE3 = createFileError("file.bin", std::move(E3));
890 auto E31 = handleErrors(std::move(FE3), [](std::unique_ptr<FileError> F) {
891 return F->takeError();
893 handleAllErrors(std::move(E31), [](const CustomError &C) {
894 EXPECT_EQ(C.message().compare("CustomError {3}"), 0);
897 Error FE4 =
898 joinErrors(createFileError("file.bin", make_error<CustomError>(41)),
899 createFileError("file2.bin", make_error<CustomError>(42)));
900 EXPECT_EQ(toString(std::move(FE4))
901 .compare("'file.bin': CustomError {41}\n"
902 "'file2.bin': CustomError {42}"),
906 enum class test_error_code {
907 unspecified = 1,
908 error_1,
909 error_2,
912 } // end anon namespace
914 namespace std {
915 template <>
916 struct is_error_code_enum<test_error_code> : std::true_type {};
917 } // namespace std
919 namespace {
921 const std::error_category &TErrorCategory();
923 inline std::error_code make_error_code(test_error_code E) {
924 return std::error_code(static_cast<int>(E), TErrorCategory());
927 class TestDebugError : public ErrorInfo<TestDebugError, StringError> {
928 public:
929 using ErrorInfo<TestDebugError, StringError >::ErrorInfo; // inherit constructors
930 TestDebugError(const Twine &S) : ErrorInfo(S, test_error_code::unspecified) {}
931 static char ID;
934 class TestErrorCategory : public std::error_category {
935 public:
936 const char *name() const noexcept override { return "error"; }
937 std::string message(int Condition) const override {
938 switch (static_cast<test_error_code>(Condition)) {
939 case test_error_code::unspecified:
940 return "An unknown error has occurred.";
941 case test_error_code::error_1:
942 return "Error 1.";
943 case test_error_code::error_2:
944 return "Error 2.";
946 llvm_unreachable("Unrecognized test_error_code");
950 static llvm::ManagedStatic<TestErrorCategory> TestErrCategory;
951 const std::error_category &TErrorCategory() { return *TestErrCategory; }
953 char TestDebugError::ID;
955 TEST(Error, SubtypeStringErrorTest) {
956 auto E1 = make_error<TestDebugError>(test_error_code::error_1);
957 EXPECT_EQ(toString(std::move(E1)).compare("Error 1."), 0);
959 auto E2 = make_error<TestDebugError>(test_error_code::error_1,
960 "Detailed information");
961 EXPECT_EQ(toString(std::move(E2)).compare("Error 1. Detailed information"),
964 auto E3 = make_error<TestDebugError>(test_error_code::error_2);
965 handleAllErrors(std::move(E3), [](const TestDebugError &F) {
966 EXPECT_EQ(F.message().compare("Error 2."), 0);
969 auto E4 = joinErrors(make_error<TestDebugError>(test_error_code::error_1,
970 "Detailed information"),
971 make_error<TestDebugError>(test_error_code::error_2));
972 EXPECT_EQ(toString(std::move(E4))
973 .compare("Error 1. Detailed information\n"
974 "Error 2."),
978 } // namespace