1 //===----- unittests/ErrorTest.cpp - Error.h tests ------------------------===//
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
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/Testing/Support/Error.h"
16 #include "gmock/gmock.h"
17 #include "gtest/gtest-spi.h"
18 #include "gtest/gtest.h"
25 // Custom error class with a default base class and some random 'info' attached.
26 class CustomError
: public ErrorInfo
<CustomError
> {
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.
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
51 CustomError() : Info(0) {}
56 char CustomError::ID
= 0;
58 // Custom error class with a custom base class and some additional random
60 class CustomSubError
: public ErrorInfo
<CustomSubError
, CustomError
> {
62 // Create a sub-error with some info attached.
63 CustomSubError(int Info
, int ExtraInfo
) : ExtraInfo(ExtraInfo
) {
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.
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()";
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
126 // Test that ErrorAsOutParameter sets the checked flag on construction.
127 TEST(Error
, ErrorAsOutParameterChecked
) {
128 Error E
= Error::success();
129 errAsOutParamHelper(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.";
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);
151 EXPECT_DEATH(DropUnhandledError(),
152 "Program aborted due to an unhandled Error:")
153 << "Unhandled Error failure value did not cause abort()";
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_EQ(CaughtErrorInfo
, 42) << "Wrong result from CustomError handler";
185 // Check that handler type deduction also works for handlers
186 // of the following types:
188 // Error (const Err&) mutable
189 // void (const Err&) mutable
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
) {});
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 {});
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
) {});
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_EQ(CaughtErrorInfo
, 42) << "Wrong result from CustomSubError handler";
257 EXPECT_EQ(CaughtErrorExtraInfo
, 7)
258 << "Wrong result from CustomSubError handler";
261 // Check that we trigger only the first handler that applies.
262 TEST(Error
, FirstHandlerOnly
) {
264 int CaughtErrorInfo
= 0;
265 int CaughtErrorExtraInfo
= 0;
267 handleAllErrors(make_error
<CustomSubError
>(42, 7),
268 [&](const CustomSubError
&SE
) {
269 CaughtErrorInfo
= SE
.getInfo();
270 CaughtErrorExtraInfo
= SE
.getExtraInfo();
272 [&](const CustomError
&CE
) { DummyInfo
= CE
.getInfo(); });
274 EXPECT_EQ(CaughtErrorInfo
, 42) << "Activated the wrong Error handler(s)";
275 EXPECT_EQ(CaughtErrorExtraInfo
, 7) << "Activated the wrong Error handler(s)";
276 EXPECT_EQ(DummyInfo
, 0) << "Activated the wrong Error handler(s)";
279 // Check that general handlers shadow specific ones.
280 TEST(Error
, HandlerShadowing
) {
281 int CaughtErrorInfo
= 0;
283 int DummyExtraInfo
= 0;
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();
293 EXPECT_EQ(CaughtErrorInfo
, 42)
294 << "General Error handler did not shadow specific handler";
295 EXPECT_EQ(DummyInfo
, 0)
296 << "General Error handler did not shadow specific handler";
297 EXPECT_EQ(DummyExtraInfo
, 0)
298 << "General Error handler did not shadow specific handler";
302 TEST(Error
, CheckJoinErrors
) {
303 int CustomErrorInfo1
= 0;
304 int CustomErrorInfo2
= 0;
305 int CustomErrorExtraInfo
= 0;
307 joinErrors(make_error
<CustomError
>(7), make_error
<CustomSubError
>(42, 7));
309 handleAllErrors(std::move(E
),
310 [&](const CustomSubError
&SE
) {
311 CustomErrorInfo2
= SE
.getInfo();
312 CustomErrorExtraInfo
= SE
.getExtraInfo();
314 [&](const CustomError
&CE
) {
315 // Assert that the CustomError instance above is handled
317 // CustomSubError - joinErrors should preserve error
319 EXPECT_EQ(CustomErrorInfo2
, 0)
320 << "CustomErrorInfo2 should be 0 here. "
321 "joinErrors failed to preserve ordering.\n";
322 CustomErrorInfo1
= CE
.getInfo();
325 EXPECT_EQ(CustomErrorInfo1
, 7) << "Failed handling compound Error.";
326 EXPECT_EQ(CustomErrorInfo2
, 42) << "Failed handling compound Error.";
327 EXPECT_EQ(CustomErrorExtraInfo
, 7) << "Failed handling compound Error.";
329 // Test appending a single item to a list.
334 joinErrors(make_error
<CustomError
>(7),
335 make_error
<CustomError
>(7)),
336 make_error
<CustomError
>(7)),
337 [&](const CustomError
&CE
) {
340 EXPECT_EQ(Sum
, 21) << "Failed to correctly append error to error list.";
343 // Test prepending a single item to a list.
348 make_error
<CustomError
>(7),
349 joinErrors(make_error
<CustomError
>(7),
350 make_error
<CustomError
>(7))),
351 [&](const CustomError
&CE
) {
354 EXPECT_EQ(Sum
, 21) << "Failed to correctly prepend error to error list.";
357 // Test concatenating two error lists.
363 make_error
<CustomError
>(7),
364 make_error
<CustomError
>(7)),
366 make_error
<CustomError
>(7),
367 make_error
<CustomError
>(7))),
368 [&](const CustomError
&CE
) {
371 EXPECT_EQ(Sum
, 28) << "Failed to correctly concatenate error lists.";
375 // Test that we can consume success values.
376 TEST(Error
, ConsumeSuccess
) {
377 Error E
= Error::success();
378 consumeError(std::move(E
));
381 TEST(Error
, ConsumeError
) {
382 Error E
= make_error
<CustomError
>(7);
383 consumeError(std::move(E
));
386 // Test that handleAllUnhandledErrors crashes if an error is not caught.
387 // Test runs in debug mode only.
388 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
389 TEST(Error
, FailureToHandle
) {
390 auto FailToHandle
= []() {
391 handleAllErrors(make_error
<CustomError
>(7), [&](const CustomSubError
&SE
) {
392 errs() << "This should never be called";
397 EXPECT_DEATH(FailToHandle(),
398 "Failure value returned from cantFail wrapped call\n"
399 "CustomError \\{7\\}")
400 << "Unhandled Error in handleAllErrors call did not cause an "
405 // Test that handleAllUnhandledErrors crashes if an error is returned from a
407 // Test runs in debug mode only.
408 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
409 TEST(Error
, FailureFromHandler
) {
410 auto ReturnErrorFromHandler
= []() {
411 handleAllErrors(make_error
<CustomError
>(7),
412 [&](std::unique_ptr
<CustomSubError
> SE
) {
413 return Error(std::move(SE
));
417 EXPECT_DEATH(ReturnErrorFromHandler(),
418 "Failure value returned from cantFail wrapped call\n"
419 "CustomError \\{7\\}")
420 << " Error returned from handler in handleAllErrors call did not "
425 // Test that we can return values from handleErrors.
426 TEST(Error
, CatchErrorFromHandler
) {
429 Error E
= handleErrors(
430 make_error
<CustomError
>(7),
431 [&](std::unique_ptr
<CustomError
> CE
) { return Error(std::move(CE
)); });
433 handleAllErrors(std::move(E
),
434 [&](const CustomError
&CE
) { ErrorInfo
= CE
.getInfo(); });
436 EXPECT_EQ(ErrorInfo
, 7)
437 << "Failed to handle Error returned from handleErrors.";
440 TEST(Error
, StringError
) {
442 raw_string_ostream
S(Msg
);
443 logAllUnhandledErrors(
444 make_error
<StringError
>("foo" + Twine(42), inconvertibleErrorCode()), S
);
445 EXPECT_EQ(S
.str(), "foo42\n") << "Unexpected StringError log result";
448 errorToErrorCode(make_error
<StringError
>("", errc::invalid_argument
));
449 EXPECT_EQ(EC
, errc::invalid_argument
)
450 << "Failed to convert StringError to error_code.";
453 TEST(Error
, createStringError
) {
454 static const char *Bar
= "bar";
455 static const std::error_code EC
= errc::invalid_argument
;
457 raw_string_ostream
S(Msg
);
458 logAllUnhandledErrors(createStringError(EC
, "foo%s%d0x%" PRIx8
, Bar
, 1, 0xff),
460 EXPECT_EQ(S
.str(), "foobar10xff\n")
461 << "Unexpected createStringError() log result";
465 logAllUnhandledErrors(createStringError(EC
, Bar
), S
);
466 EXPECT_EQ(S
.str(), "bar\n")
467 << "Unexpected createStringError() (overloaded) log result";
471 auto Res
= errorToErrorCode(createStringError(EC
, "foo%s", Bar
));
473 << "Failed to convert createStringError() result to error_code.";
476 // Test that the ExitOnError utility works as expected.
477 TEST(ErrorDeathTest
, ExitOnError
) {
478 ExitOnError ExitOnErr
;
479 ExitOnErr
.setBanner("Error in tool:");
480 ExitOnErr
.setExitCodeMapper([](const Error
&E
) {
481 if (E
.isA
<CustomSubError
>())
486 // Make sure we don't bail on success.
487 ExitOnErr(Error::success());
488 EXPECT_EQ(ExitOnErr(Expected
<int>(7)), 7)
489 << "exitOnError returned an invalid value for Expected";
492 int &B
= ExitOnErr(Expected
<int&>(A
));
493 EXPECT_EQ(&A
, &B
) << "ExitOnError failed to propagate reference";
496 EXPECT_EXIT(ExitOnErr(make_error
<CustomError
>(7)),
497 ::testing::ExitedWithCode(1), "Error in tool:")
498 << "exitOnError returned an unexpected error result";
500 EXPECT_EXIT(ExitOnErr(Expected
<int>(make_error
<CustomSubError
>(0, 0))),
501 ::testing::ExitedWithCode(2), "Error in tool:")
502 << "exitOnError returned an unexpected error result";
505 // Test that the ExitOnError utility works as expected.
506 TEST(Error
, CantFailSuccess
) {
507 cantFail(Error::success());
509 int X
= cantFail(Expected
<int>(42));
510 EXPECT_EQ(X
, 42) << "Expected value modified by cantFail";
513 int &Y
= cantFail(Expected
<int&>(Dummy
));
514 EXPECT_EQ(&Dummy
, &Y
) << "Reference mangled by cantFail";
517 // Test that cantFail results in a crash if you pass it a failure value.
518 #if LLVM_ENABLE_ABI_BREAKING_CHECKS && !defined(NDEBUG)
519 TEST(Error
, CantFailDeath
) {
520 EXPECT_DEATH(cantFail(make_error
<StringError
>("Original error message",
521 inconvertibleErrorCode()),
522 "Cantfail call failed"),
523 "Cantfail call failed\n"
524 "Original error message")
525 << "cantFail(Error) did not cause an abort for failure value";
529 auto IEC
= inconvertibleErrorCode();
530 int X
= cantFail(Expected
<int>(make_error
<StringError
>("foo", IEC
)));
533 "Failure value returned from cantFail wrapped call")
534 << "cantFail(Expected<int>) did not cause an abort for failure value";
539 // Test Checked Expected<T> in success mode.
540 TEST(Error
, CheckedExpectedInSuccessMode
) {
542 EXPECT_TRUE(!!A
) << "Expected with non-error value doesn't convert to 'true'";
543 // Access is safe in second test, since we checked the error in the first.
544 EXPECT_EQ(*A
, 7) << "Incorrect Expected non-error value";
547 // Test Expected with reference type.
548 TEST(Error
, ExpectedWithReferenceType
) {
550 Expected
<int&> B
= A
;
554 EXPECT_EQ(&A
, &C
) << "Expected failed to propagate reference";
557 // Test Unchecked Expected<T> in success mode.
558 // We expect this to blow up the same way Error would.
559 // Test runs in debug mode only.
560 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
561 TEST(Error
, UncheckedExpectedInSuccessModeDestruction
) {
562 EXPECT_DEATH({ Expected
<int> A
= 7; },
563 "Expected<T> must be checked before access or destruction.")
564 << "Unchecked Expected<T> success value did not cause an abort().";
568 // Test Unchecked Expected<T> in success mode.
569 // We expect this to blow up the same way Error would.
570 // Test runs in debug mode only.
571 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
572 TEST(Error
, UncheckedExpectedInSuccessModeAccess
) {
575 const Expected
<int> A
= 7;
578 "Expected<T> must be checked before access or destruction.")
579 << "Unchecked Expected<T> success value did not cause an abort().";
583 // Test Unchecked Expected<T> in success mode.
584 // We expect this to blow up the same way Error would.
585 // Test runs in debug mode only.
586 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
587 TEST(Error
, UncheckedExpectedInSuccessModeAssignment
) {
593 "Expected<T> must be checked before access or destruction.")
594 << "Unchecked Expected<T> success value did not cause an abort().";
598 // Test Expected<T> in failure mode.
599 TEST(Error
, ExpectedInFailureMode
) {
600 Expected
<int> A
= make_error
<CustomError
>(42);
601 EXPECT_FALSE(!!A
) << "Expected with error value doesn't convert to 'false'";
602 Error E
= A
.takeError();
603 EXPECT_TRUE(E
.isA
<CustomError
>()) << "Incorrect Expected error value";
604 consumeError(std::move(E
));
607 // Check that an Expected instance with an error value doesn't allow access to
609 // Test runs in debug mode only.
610 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
611 TEST(Error
, AccessExpectedInFailureMode
) {
612 Expected
<int> A
= make_error
<CustomError
>(42);
613 EXPECT_DEATH(*A
, "Expected<T> must be checked before access or destruction.")
614 << "Incorrect Expected error value";
615 consumeError(A
.takeError());
619 // Check that an Expected instance with an error triggers an abort if
621 // Test runs in debug mode only.
622 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
623 TEST(Error
, UnhandledExpectedInFailureMode
) {
624 EXPECT_DEATH({ Expected
<int> A
= make_error
<CustomError
>(42); },
625 "Expected<T> must be checked before access or destruction.")
626 << "Unchecked Expected<T> failure value did not cause an abort()";
630 // Test covariance of Expected.
631 TEST(Error
, ExpectedCovariance
) {
633 class D
: public B
{};
635 Expected
<B
*> A1(Expected
<D
*>(nullptr));
636 // Check A1 by converting to bool before assigning to it.
638 A1
= Expected
<D
*>(nullptr);
639 // Check A1 again before destruction.
642 Expected
<std::unique_ptr
<B
>> A2(Expected
<std::unique_ptr
<D
>>(nullptr));
643 // Check A2 by converting to bool before assigning to it.
645 A2
= Expected
<std::unique_ptr
<D
>>(nullptr);
646 // Check A2 again before destruction.
650 // Test that handleExpected just returns success values.
651 TEST(Error
, HandleExpectedSuccess
) {
653 handleExpected(Expected
<int>(42),
654 []() { return Expected
<int>(43); });
655 EXPECT_TRUE(!!ValOrErr
)
656 << "handleExpected should have returned a success value here";
657 EXPECT_EQ(*ValOrErr
, 42)
658 << "handleExpected should have returned the original success value here";
661 enum FooStrategy
{ Aggressive
, Conservative
};
663 static Expected
<int> foo(FooStrategy S
) {
665 return make_error
<CustomError
>(7);
669 // Test that handleExpected invokes the error path if errors are not handled.
670 TEST(Error
, HandleExpectedUnhandledError
) {
671 // foo(Aggressive) should return a CustomError which should pass through as
672 // there is no handler for CustomError.
676 []() { return foo(Conservative
); });
678 EXPECT_FALSE(!!ValOrErr
)
679 << "handleExpected should have returned an error here";
680 auto Err
= ValOrErr
.takeError();
681 EXPECT_TRUE(Err
.isA
<CustomError
>())
682 << "handleExpected should have returned the CustomError generated by "
683 "foo(Aggressive) here";
684 consumeError(std::move(Err
));
687 // Test that handleExpected invokes the fallback path if errors are handled.
688 TEST(Error
, HandleExpectedHandledError
) {
689 // foo(Aggressive) should return a CustomError which should handle triggering
690 // the fallback path.
694 []() { return foo(Conservative
); },
695 [](const CustomError
&) { /* do nothing */ });
697 EXPECT_TRUE(!!ValOrErr
)
698 << "handleExpected should have returned a success value here";
699 EXPECT_EQ(*ValOrErr
, 42)
700 << "handleExpected returned the wrong success value";
703 TEST(Error
, ErrorCodeConversions
) {
704 // Round-trip a success value to check that it converts correctly.
705 EXPECT_EQ(errorToErrorCode(errorCodeToError(std::error_code())),
707 << "std::error_code() should round-trip via Error conversions";
709 // Round-trip an error value to check that it converts correctly.
710 EXPECT_EQ(errorToErrorCode(errorCodeToError(errc::invalid_argument
)),
711 errc::invalid_argument
)
712 << "std::error_code error value should round-trip via Error "
715 // Round-trip a success value through ErrorOr/Expected to check that it
716 // converts correctly.
718 auto Orig
= ErrorOr
<int>(42);
720 expectedToErrorOr(errorOrToExpected(ErrorOr
<int>(42)));
721 EXPECT_EQ(*Orig
, *RoundTripped
)
722 << "ErrorOr<T> success value should round-trip via Expected<T> "
726 // Round-trip a failure value through ErrorOr/Expected to check that it
727 // converts correctly.
729 auto Orig
= ErrorOr
<int>(errc::invalid_argument
);
732 errorOrToExpected(ErrorOr
<int>(errc::invalid_argument
)));
733 EXPECT_EQ(Orig
.getError(), RoundTripped
.getError())
734 << "ErrorOr<T> failure value should round-trip via Expected<T> "
739 // Test that error messages work.
740 TEST(Error
, ErrorMessage
) {
741 EXPECT_EQ(toString(Error::success()), "");
743 Error E0
= Error::success();
744 EXPECT_EQ(toStringWithoutConsuming(E0
), "");
745 EXPECT_EQ(toString(std::move(E0
)), "");
747 Error E1
= make_error
<CustomError
>(0);
748 EXPECT_EQ(toStringWithoutConsuming(E1
), "CustomError {0}");
749 EXPECT_EQ(toString(std::move(E1
)), "CustomError {0}");
751 Error E2
= make_error
<CustomError
>(0);
752 visitErrors(E2
, [](const ErrorInfoBase
&EI
) {
753 EXPECT_EQ(EI
.message(), "CustomError {0}");
755 handleAllErrors(std::move(E2
), [](const CustomError
&CE
) {
756 EXPECT_EQ(CE
.message(), "CustomError {0}");
759 Error E3
= joinErrors(make_error
<CustomError
>(0), make_error
<CustomError
>(1));
760 EXPECT_EQ(toStringWithoutConsuming(E3
), "CustomError {0}\n"
762 EXPECT_EQ(toString(std::move(E3
)), "CustomError {0}\n"
766 TEST(Error
, Stream
) {
768 Error OK
= Error::success();
770 llvm::raw_string_ostream
S(Buf
);
772 EXPECT_EQ("success", S
.str());
773 consumeError(std::move(OK
));
776 Error E1
= make_error
<CustomError
>(0);
778 llvm::raw_string_ostream
S(Buf
);
780 EXPECT_EQ("CustomError {0}", S
.str());
781 consumeError(std::move(E1
));
785 TEST(Error
, SucceededMatcher
) {
786 EXPECT_THAT_ERROR(Error::success(), Succeeded());
787 EXPECT_NONFATAL_FAILURE(
788 EXPECT_THAT_ERROR(make_error
<CustomError
>(0), Succeeded()),
789 "Expected: succeeded\n Actual: failed (CustomError {0})");
791 EXPECT_THAT_EXPECTED(Expected
<int>(0), Succeeded());
792 EXPECT_NONFATAL_FAILURE(
793 EXPECT_THAT_EXPECTED(Expected
<int>(make_error
<CustomError
>(0)),
795 "Expected: succeeded\n Actual: failed (CustomError {0})");
797 EXPECT_THAT_EXPECTED(Expected
<int &>(a
), Succeeded());
800 TEST(Error
, FailedMatcher
) {
801 EXPECT_THAT_ERROR(make_error
<CustomError
>(0), Failed());
802 EXPECT_NONFATAL_FAILURE(EXPECT_THAT_ERROR(Error::success(), Failed()),
803 "Expected: failed\n Actual: succeeded");
805 EXPECT_THAT_ERROR(make_error
<CustomError
>(0), Failed
<CustomError
>());
806 EXPECT_NONFATAL_FAILURE(
807 EXPECT_THAT_ERROR(Error::success(), Failed
<CustomError
>()),
808 "Expected: failed with Error of given type\n Actual: succeeded");
809 EXPECT_NONFATAL_FAILURE(
810 EXPECT_THAT_ERROR(make_error
<CustomError
>(0), Failed
<CustomSubError
>()),
811 "Error was not of given type");
812 EXPECT_NONFATAL_FAILURE(
814 joinErrors(make_error
<CustomError
>(0), make_error
<CustomError
>(1)),
815 Failed
<CustomError
>()),
819 make_error
<CustomError
>(0),
820 Failed
<CustomError
>(testing::Property(&CustomError::getInfo
, 0)));
821 EXPECT_NONFATAL_FAILURE(
823 make_error
<CustomError
>(0),
824 Failed
<CustomError
>(testing::Property(&CustomError::getInfo
, 1))),
825 "Expected: failed with Error of given type and the error is an object "
826 "whose given property is equal to 1\n"
827 " Actual: failed (CustomError {0})");
828 EXPECT_THAT_ERROR(make_error
<CustomError
>(0), Failed
<ErrorInfoBase
>());
830 EXPECT_THAT_EXPECTED(Expected
<int>(make_error
<CustomError
>(0)), Failed());
831 EXPECT_NONFATAL_FAILURE(
832 EXPECT_THAT_EXPECTED(Expected
<int>(0), Failed()),
833 "Expected: failed\n Actual: succeeded with value 0");
834 EXPECT_THAT_EXPECTED(Expected
<int &>(make_error
<CustomError
>(0)), Failed());
837 TEST(Error
, HasValueMatcher
) {
838 EXPECT_THAT_EXPECTED(Expected
<int>(0), HasValue(0));
839 EXPECT_NONFATAL_FAILURE(
840 EXPECT_THAT_EXPECTED(Expected
<int>(make_error
<CustomError
>(0)),
842 "Expected: succeeded with value (is equal to 0)\n"
843 " Actual: failed (CustomError {0})");
844 EXPECT_NONFATAL_FAILURE(
845 EXPECT_THAT_EXPECTED(Expected
<int>(1), HasValue(0)),
846 "Expected: succeeded with value (is equal to 0)\n"
847 " Actual: succeeded with value 1, (isn't equal to 0)");
850 EXPECT_THAT_EXPECTED(Expected
<int &>(a
), HasValue(testing::Eq(1)));
852 EXPECT_THAT_EXPECTED(Expected
<int>(1), HasValue(testing::Gt(0)));
853 EXPECT_NONFATAL_FAILURE(
854 EXPECT_THAT_EXPECTED(Expected
<int>(0), HasValue(testing::Gt(1))),
855 "Expected: succeeded with value (is > 1)\n"
856 " Actual: succeeded with value 0, (isn't > 1)");
857 EXPECT_NONFATAL_FAILURE(
858 EXPECT_THAT_EXPECTED(Expected
<int>(make_error
<CustomError
>(0)),
859 HasValue(testing::Gt(1))),
860 "Expected: succeeded with value (is > 1)\n"
861 " Actual: failed (CustomError {0})");
864 TEST(Error
, FailedWithMessageMatcher
) {
865 EXPECT_THAT_EXPECTED(Expected
<int>(make_error
<CustomError
>(0)),
866 FailedWithMessage("CustomError {0}"));
868 EXPECT_NONFATAL_FAILURE(
869 EXPECT_THAT_EXPECTED(Expected
<int>(make_error
<CustomError
>(1)),
870 FailedWithMessage("CustomError {0}")),
871 "Expected: failed with Error whose message has 1 element that is equal "
872 "to \"CustomError {0}\"\n"
873 " Actual: failed (CustomError {1})");
875 EXPECT_NONFATAL_FAILURE(
876 EXPECT_THAT_EXPECTED(Expected
<int>(0),
877 FailedWithMessage("CustomError {0}")),
878 "Expected: failed with Error whose message has 1 element that is equal "
879 "to \"CustomError {0}\"\n"
880 " Actual: succeeded with value 0");
882 EXPECT_NONFATAL_FAILURE(
883 EXPECT_THAT_EXPECTED(Expected
<int>(make_error
<CustomError
>(0)),
884 FailedWithMessage("CustomError {0}", "CustomError {0}")),
885 "Expected: failed with Error whose message has 2 elements where\n"
886 "element #0 is equal to \"CustomError {0}\",\n"
887 "element #1 is equal to \"CustomError {0}\"\n"
888 " Actual: failed (CustomError {0}), which has 1 element");
890 EXPECT_NONFATAL_FAILURE(
891 EXPECT_THAT_EXPECTED(
892 Expected
<int>(joinErrors(make_error
<CustomError
>(0),
893 make_error
<CustomError
>(0))),
894 FailedWithMessage("CustomError {0}")),
895 "Expected: failed with Error whose message has 1 element that is equal "
896 "to \"CustomError {0}\"\n"
897 " Actual: failed (CustomError {0}; CustomError {0}), which has 2 elements");
900 joinErrors(make_error
<CustomError
>(0), make_error
<CustomError
>(0)),
901 FailedWithMessageArray(testing::SizeIs(2)));
905 EXPECT_THAT_ERROR(unwrap(wrap(Error::success())), Succeeded())
906 << "Failed to round-trip Error success value via C API";
907 EXPECT_THAT_ERROR(unwrap(wrap(make_error
<CustomError
>(0))),
908 Failed
<CustomError
>())
909 << "Failed to round-trip Error failure value via C API";
912 wrap(make_error
<StringError
>("test message", inconvertibleErrorCode()));
913 EXPECT_EQ(LLVMGetErrorTypeId(Err
), LLVMGetStringErrorTypeId())
914 << "Failed to match error type ids via C API";
915 char *ErrMsg
= LLVMGetErrorMessage(Err
);
916 EXPECT_STREQ(ErrMsg
, "test message")
917 << "Failed to roundtrip StringError error message via C API";
918 LLVMDisposeErrorMessage(ErrMsg
);
923 unwrap(wrap(joinErrors(make_error
<CustomSubError
>(42, 7),
924 make_error
<CustomError
>(42)))),
925 [&](CustomSubError
&CSE
) {
928 [&](CustomError
&CE
) {
931 EXPECT_TRUE(GotCSE
) << "Failed to round-trip ErrorList via C API";
932 EXPECT_TRUE(GotCE
) << "Failed to round-trip ErrorList via C API";
935 TEST(Error
, FileErrorTest
) {
936 #if !defined(NDEBUG) && GTEST_HAS_DEATH_TEST
939 Error S
= Error::success();
940 consumeError(createFileError("file.bin", std::move(S
)));
944 // Not allowed, would fail at compile-time
945 //consumeError(createFileError("file.bin", ErrorSuccess()));
947 Error E1
= make_error
<CustomError
>(1);
948 Error FE1
= createFileError("file.bin", std::move(E1
));
949 EXPECT_EQ(toString(std::move(FE1
)), "'file.bin': CustomError {1}");
951 Error E2
= make_error
<CustomError
>(2);
952 Error FE2
= createFileError("file.bin", std::move(E2
));
953 handleAllErrors(std::move(FE2
), [](const FileError
&F
) {
954 EXPECT_EQ(F
.message(), "'file.bin': CustomError {2}");
957 Error E3
= make_error
<CustomError
>(3);
958 Error FE3
= createFileError("file.bin", std::move(E3
));
959 auto E31
= handleErrors(std::move(FE3
), [](std::unique_ptr
<FileError
> F
) {
960 return F
->takeError();
962 handleAllErrors(std::move(E31
), [](const CustomError
&C
) {
963 EXPECT_EQ(C
.message(), "CustomError {3}");
967 joinErrors(createFileError("file.bin", make_error
<CustomError
>(41)),
968 createFileError("file2.bin", make_error
<CustomError
>(42)));
969 EXPECT_EQ(toString(std::move(FE4
)), "'file.bin': CustomError {41}\n"
970 "'file2.bin': CustomError {42}");
972 Error FE5
= createFileError("", make_error
<CustomError
>(5));
973 EXPECT_EQ(toString(std::move(FE5
)), "'': CustomError {5}");
975 Error FE6
= createFileError("unused", make_error
<CustomError
>(6));
976 handleAllErrors(std::move(FE6
), [](std::unique_ptr
<FileError
> F
) {
977 EXPECT_EQ(F
->messageWithoutFileInfo(), "CustomError {6}");
981 TEST(Error
, FileErrorErrorCode
) {
982 for (std::error_code EC
: {
983 make_error_code(std::errc::not_supported
),
984 make_error_code(std::errc::invalid_argument
),
985 make_error_code(std::errc::no_such_file_or_directory
),
987 EXPECT_EQ(EC
, errorToErrorCode(
988 createFileError("file.bin", EC
)));
989 EXPECT_EQ(EC
, errorToErrorCode(
990 createFileError("file.bin", /*Line=*/5, EC
)));
991 EXPECT_EQ(EC
, errorToErrorCode(
992 createFileError("file.bin", errorCodeToError(EC
))));
993 EXPECT_EQ(EC
, errorToErrorCode(
994 createFileError("file.bin", /*Line=*/5, errorCodeToError(EC
))));
997 // inconvertibleErrorCode() should be wrapped to avoid a fatal error.
999 "A file error occurred.",
1000 errorToErrorCode(createFileError("file.bin", inconvertibleErrorCode()))
1003 "A file error occurred.",
1004 errorToErrorCode(createFileError("file.bin", /*Line=*/5, inconvertibleErrorCode()))
1008 enum class test_error_code
{
1014 } // end anon namespace
1018 struct is_error_code_enum
<test_error_code
> : std::true_type
{};
1023 const std::error_category
&TErrorCategory();
1025 inline std::error_code
make_error_code(test_error_code E
) {
1026 return std::error_code(static_cast<int>(E
), TErrorCategory());
1029 class TestDebugError
: public ErrorInfo
<TestDebugError
, StringError
> {
1031 using ErrorInfo
<TestDebugError
, StringError
>::ErrorInfo
; // inherit constructors
1032 TestDebugError(const Twine
&S
) : ErrorInfo(S
, test_error_code::unspecified
) {}
1036 class TestErrorCategory
: public std::error_category
{
1038 const char *name() const noexcept override
{ return "error"; }
1039 std::string
message(int Condition
) const override
{
1040 switch (static_cast<test_error_code
>(Condition
)) {
1041 case test_error_code::unspecified
:
1042 return "An unknown error has occurred.";
1043 case test_error_code::error_1
:
1045 case test_error_code::error_2
:
1048 llvm_unreachable("Unrecognized test_error_code");
1052 const std::error_category
&TErrorCategory() {
1053 static TestErrorCategory TestErrCategory
;
1054 return TestErrCategory
;
1057 char TestDebugError::ID
;
1059 TEST(Error
, SubtypeStringErrorTest
) {
1060 auto E1
= make_error
<TestDebugError
>(test_error_code::error_1
);
1061 EXPECT_EQ(toString(std::move(E1
)), "Error 1.");
1063 auto E2
= make_error
<TestDebugError
>(test_error_code::error_1
,
1064 "Detailed information");
1065 EXPECT_EQ(toString(std::move(E2
)), "Error 1. Detailed information");
1067 auto E3
= make_error
<TestDebugError
>(test_error_code::error_2
);
1068 handleAllErrors(std::move(E3
), [](const TestDebugError
&F
) {
1069 EXPECT_EQ(F
.message(), "Error 2.");
1072 auto E4
= joinErrors(make_error
<TestDebugError
>(test_error_code::error_1
,
1073 "Detailed information"),
1074 make_error
<TestDebugError
>(test_error_code::error_2
));
1075 EXPECT_EQ(toString(std::move(E4
)), "Error 1. Detailed information\n"
1079 static Error
createAnyError() {
1080 return errorCodeToError(test_error_code::unspecified
);
1083 struct MoveOnlyBox
{
1084 std::optional
<int> Box
;
1086 explicit MoveOnlyBox(int I
) : Box(I
) {}
1087 MoveOnlyBox() = default;
1088 MoveOnlyBox(MoveOnlyBox
&&) = default;
1089 MoveOnlyBox
&operator=(MoveOnlyBox
&&) = default;
1091 MoveOnlyBox(const MoveOnlyBox
&) = delete;
1092 MoveOnlyBox
&operator=(const MoveOnlyBox
&) = delete;
1094 bool operator==(const MoveOnlyBox
&RHS
) const {
1095 if (bool(Box
) != bool(RHS
.Box
))
1097 return Box
? *Box
== *RHS
.Box
: false;
1101 TEST(Error
, moveInto
) {
1102 // Use MoveOnlyBox as the T in Expected<T>.
1103 auto make
= [](int I
) -> Expected
<MoveOnlyBox
> { return MoveOnlyBox(I
); };
1104 auto makeFailure
= []() -> Expected
<MoveOnlyBox
> { return createAnyError(); };
1109 // Failure with no prior value.
1110 EXPECT_THAT_ERROR(makeFailure().moveInto(V
), Failed());
1111 EXPECT_EQ(std::nullopt
, V
.Box
);
1113 // Success with no prior value.
1114 EXPECT_THAT_ERROR(make(5).moveInto(V
), Succeeded());
1115 EXPECT_EQ(5, V
.Box
);
1117 // Success with an existing value.
1118 EXPECT_THAT_ERROR(make(7).moveInto(V
), Succeeded());
1119 EXPECT_EQ(7, V
.Box
);
1121 // Failure with an existing value. Might be nice to assign a
1122 // default-constructed value in this case, but for now it's being left
1124 EXPECT_THAT_ERROR(makeFailure().moveInto(V
), Failed());
1125 EXPECT_EQ(7, V
.Box
);
1128 // Check that this works with optionals too.
1130 // Same cases as above.
1131 std::optional
<MoveOnlyBox
> MaybeV
;
1132 EXPECT_THAT_ERROR(makeFailure().moveInto(MaybeV
), Failed());
1133 EXPECT_EQ(std::nullopt
, MaybeV
);
1135 EXPECT_THAT_ERROR(make(5).moveInto(MaybeV
), Succeeded());
1136 EXPECT_EQ(MoveOnlyBox(5), MaybeV
);
1138 EXPECT_THAT_ERROR(make(7).moveInto(MaybeV
), Succeeded());
1139 EXPECT_EQ(MoveOnlyBox(7), MaybeV
);
1141 EXPECT_THAT_ERROR(makeFailure().moveInto(MaybeV
), Failed());
1142 EXPECT_EQ(MoveOnlyBox(7), MaybeV
);
1146 TEST(Error
, FatalBadAllocErrorHandlersInteraction
) {
1147 auto ErrorHandler
= [](void *Data
, const char *, bool) {};
1148 install_fatal_error_handler(ErrorHandler
, nullptr);
1149 // The following call should not crash; previously, a bug in
1150 // install_bad_alloc_error_handler asserted that no fatal-error handler is
1151 // installed already.
1152 install_bad_alloc_error_handler(ErrorHandler
, nullptr);
1154 // Don't interfere with other tests.
1155 remove_fatal_error_handler();
1156 remove_bad_alloc_error_handler();
1159 TEST(Error
, BadAllocFatalErrorHandlersInteraction
) {
1160 auto ErrorHandler
= [](void *Data
, const char *, bool) {};
1161 install_bad_alloc_error_handler(ErrorHandler
, nullptr);
1162 // The following call should not crash; related to
1163 // FatalBadAllocErrorHandlersInteraction: Ensure that the error does not occur
1164 // in the other direction.
1165 install_fatal_error_handler(ErrorHandler
, nullptr);
1167 // Don't interfere with other tests.
1168 remove_fatal_error_handler();
1169 remove_bad_alloc_error_handler();
1172 TEST(Error
, ForwardToExpected
) {
1173 auto ErrorReturningFct
= [](bool Fail
) {
1174 return Fail
? make_error
<StringError
>(llvm::errc::invalid_argument
,
1178 auto ExpectedReturningFct
= [&](bool Fail
) -> Expected
<int> {
1179 auto Err
= ErrorReturningFct(Fail
);
1184 std::optional
<int> MaybeV
;
1185 EXPECT_THAT_ERROR(ExpectedReturningFct(true).moveInto(MaybeV
), Failed());
1186 EXPECT_THAT_ERROR(ExpectedReturningFct(false).moveInto(MaybeV
), Succeeded());
1187 EXPECT_EQ(*MaybeV
, 42);