1f7f6d3e9SLang Hames //===----- unittests/ErrorTest.cpp - Error.h tests ------------------------===//
2f7f6d3e9SLang Hames //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6f7f6d3e9SLang Hames //
7f7f6d3e9SLang Hames //===----------------------------------------------------------------------===//
8f7f6d3e9SLang Hames
9f7f6d3e9SLang Hames #include "llvm/Support/Error.h"
1000fb14daSLang Hames #include "llvm-c/Error.h"
11c5e0bbd7SLang Hames
12c5e0bbd7SLang Hames #include "llvm/ADT/Twine.h"
13f7f6d3e9SLang Hames #include "llvm/Support/Errc.h"
14e7aad357SLang Hames #include "llvm/Support/ErrorHandling.h"
15e8354fe6SPavel Labath #include "llvm/Testing/Support/Error.h"
16e8354fe6SPavel Labath #include "gtest/gtest-spi.h"
17f7f6d3e9SLang Hames #include "gtest/gtest.h"
18f7f6d3e9SLang Hames #include <memory>
19f7f6d3e9SLang Hames
20f7f6d3e9SLang Hames using namespace llvm;
21f7f6d3e9SLang Hames
22f7f6d3e9SLang Hames namespace {
23f7f6d3e9SLang Hames
24f7f6d3e9SLang Hames // Custom error class with a default base class and some random 'info' attached.
25f7f6d3e9SLang Hames class CustomError : public ErrorInfo<CustomError> {
26f7f6d3e9SLang Hames public:
27f7f6d3e9SLang Hames // Create an error with some info attached.
CustomError(int Info)28f7f6d3e9SLang Hames CustomError(int Info) : Info(Info) {}
29f7f6d3e9SLang Hames
30f7f6d3e9SLang Hames // Get the info attached to this error.
getInfo() const31f7f6d3e9SLang Hames int getInfo() const { return Info; }
32f7f6d3e9SLang Hames
33f7f6d3e9SLang Hames // Log this error to a stream.
log(raw_ostream & OS) const34f7f6d3e9SLang Hames void log(raw_ostream &OS) const override {
35f7f6d3e9SLang Hames OS << "CustomError {" << getInfo() << "}";
36f7f6d3e9SLang Hames }
37f7f6d3e9SLang Hames
convertToErrorCode() const38e7aad357SLang Hames std::error_code convertToErrorCode() const override {
39e7aad357SLang Hames llvm_unreachable("CustomError doesn't support ECError conversion");
40e7aad357SLang Hames }
41e7aad357SLang Hames
42a15b76b3SReid Kleckner // Used by ErrorInfo::classID.
43a15b76b3SReid Kleckner static char ID;
44a15b76b3SReid Kleckner
45f7f6d3e9SLang Hames protected:
46f7f6d3e9SLang Hames // This error is subclassed below, but we can't use inheriting constructors
47f7f6d3e9SLang Hames // yet, so we can't propagate the constructors through ErrorInfo. Instead
48f7f6d3e9SLang Hames // we have to have a default constructor and have the subclass initialize all
49f7f6d3e9SLang Hames // fields.
CustomError()50f7f6d3e9SLang Hames CustomError() : Info(0) {}
51f7f6d3e9SLang Hames
52f7f6d3e9SLang Hames int Info;
53f7f6d3e9SLang Hames };
54f7f6d3e9SLang Hames
55a15b76b3SReid Kleckner char CustomError::ID = 0;
56a15b76b3SReid Kleckner
57f7f6d3e9SLang Hames // Custom error class with a custom base class and some additional random
58f7f6d3e9SLang Hames // 'info'.
59f7f6d3e9SLang Hames class CustomSubError : public ErrorInfo<CustomSubError, CustomError> {
60f7f6d3e9SLang Hames public:
61f7f6d3e9SLang Hames // Create a sub-error with some info attached.
CustomSubError(int Info,int ExtraInfo)62f7f6d3e9SLang Hames CustomSubError(int Info, int ExtraInfo) : ExtraInfo(ExtraInfo) {
63f7f6d3e9SLang Hames this->Info = Info;
64f7f6d3e9SLang Hames }
65f7f6d3e9SLang Hames
66f7f6d3e9SLang Hames // Get the extra info attached to this error.
getExtraInfo() const67f7f6d3e9SLang Hames int getExtraInfo() const { return ExtraInfo; }
68f7f6d3e9SLang Hames
69f7f6d3e9SLang Hames // Log this error to a stream.
log(raw_ostream & OS) const70f7f6d3e9SLang Hames void log(raw_ostream &OS) const override {
71f7f6d3e9SLang Hames OS << "CustomSubError { " << getInfo() << ", " << getExtraInfo() << "}";
72f7f6d3e9SLang Hames }
73f7f6d3e9SLang Hames
convertToErrorCode() const74e7aad357SLang Hames std::error_code convertToErrorCode() const override {
75e7aad357SLang Hames llvm_unreachable("CustomSubError doesn't support ECError conversion");
76e7aad357SLang Hames }
77e7aad357SLang Hames
78a15b76b3SReid Kleckner // Used by ErrorInfo::classID.
79a15b76b3SReid Kleckner static char ID;
80a15b76b3SReid Kleckner
81f7f6d3e9SLang Hames protected:
82f7f6d3e9SLang Hames int ExtraInfo;
83f7f6d3e9SLang Hames };
84f7f6d3e9SLang Hames
85a15b76b3SReid Kleckner char CustomSubError::ID = 0;
86a15b76b3SReid Kleckner
handleCustomError(const CustomError & CE)8741af4309SMehdi Amini static Error handleCustomError(const CustomError &CE) {
8841af4309SMehdi Amini return Error::success();
8941af4309SMehdi Amini }
90f7f6d3e9SLang Hames
handleCustomErrorVoid(const CustomError & CE)91f7f6d3e9SLang Hames static void handleCustomErrorVoid(const CustomError &CE) {}
92f7f6d3e9SLang Hames
handleCustomErrorUP(std::unique_ptr<CustomError> CE)93f7f6d3e9SLang Hames static Error handleCustomErrorUP(std::unique_ptr<CustomError> CE) {
9441af4309SMehdi Amini return Error::success();
95f7f6d3e9SLang Hames }
96f7f6d3e9SLang Hames
handleCustomErrorUPVoid(std::unique_ptr<CustomError> CE)97f7f6d3e9SLang Hames static void handleCustomErrorUPVoid(std::unique_ptr<CustomError> CE) {}
98f7f6d3e9SLang Hames
9901864a2dSLang Hames // Test that success values implicitly convert to false, and don't cause crashes
10001864a2dSLang Hames // once they've been implicitly converted.
TEST(Error,CheckedSuccess)10101864a2dSLang Hames TEST(Error, CheckedSuccess) {
102c1edf566SMehdi Amini Error E = Error::success();
10301864a2dSLang Hames EXPECT_FALSE(E) << "Unexpected error while testing Error 'Success'";
10401864a2dSLang Hames }
10501864a2dSLang Hames
106e11f2217SAlexandre Ganea // Test that unchecked success values cause an abort.
107cb79c079SMehdi Amini #if LLVM_ENABLE_ABI_BREAKING_CHECKS
TEST(Error,UncheckedSuccess)10801864a2dSLang Hames TEST(Error, UncheckedSuccess) {
109c1edf566SMehdi Amini EXPECT_DEATH({ Error E = Error::success(); },
110c1edf566SMehdi Amini "Program aborted due to an unhandled Error:")
11101864a2dSLang Hames << "Unchecked Error Succes value did not cause abort()";
11201864a2dSLang Hames }
11301864a2dSLang Hames #endif
11401864a2dSLang Hames
115d1af8fceSLang Hames // ErrorAsOutParameter tester.
errAsOutParamHelper(Error & Err)116d1af8fceSLang Hames void errAsOutParamHelper(Error &Err) {
1175e51a2e3SLang Hames ErrorAsOutParameter ErrAsOutParam(&Err);
118d1af8fceSLang Hames // Verify that checked flag is raised - assignment should not crash.
119d1af8fceSLang Hames Err = Error::success();
120d1af8fceSLang Hames // Raise the checked bit manually - caller should still have to test the
121d1af8fceSLang Hames // error.
122d1af8fceSLang Hames (void)!!Err;
123d0ac31a7SLang Hames }
124d0ac31a7SLang Hames
125d1af8fceSLang Hames // Test that ErrorAsOutParameter sets the checked flag on construction.
TEST(Error,ErrorAsOutParameterChecked)126d1af8fceSLang Hames TEST(Error, ErrorAsOutParameterChecked) {
127c1edf566SMehdi Amini Error E = Error::success();
128d1af8fceSLang Hames errAsOutParamHelper(E);
129d1af8fceSLang Hames (void)!!E;
130d1af8fceSLang Hames }
131d1af8fceSLang Hames
132d1af8fceSLang Hames // Test that ErrorAsOutParameter clears the checked flag on destruction.
133cb79c079SMehdi Amini #if LLVM_ENABLE_ABI_BREAKING_CHECKS
TEST(Error,ErrorAsOutParameterUnchecked)134d1af8fceSLang Hames TEST(Error, ErrorAsOutParameterUnchecked) {
135c1edf566SMehdi Amini EXPECT_DEATH({ Error E = Error::success(); errAsOutParamHelper(E); },
136d1af8fceSLang Hames "Program aborted due to an unhandled Error:")
137d1af8fceSLang Hames << "ErrorAsOutParameter did not clear the checked flag on destruction.";
138d1af8fceSLang Hames }
139d1af8fceSLang Hames #endif
140d1af8fceSLang Hames
141f7f6d3e9SLang Hames // Check that we abort on unhandled failure cases. (Force conversion to bool
142f7f6d3e9SLang Hames // to make sure that we don't accidentally treat checked errors as handled).
143f7f6d3e9SLang Hames // Test runs in debug mode only.
144cb79c079SMehdi Amini #if LLVM_ENABLE_ABI_BREAKING_CHECKS
TEST(Error,UncheckedError)14501864a2dSLang Hames TEST(Error, UncheckedError) {
146f7f6d3e9SLang Hames auto DropUnhandledError = []() {
147f7f6d3e9SLang Hames Error E = make_error<CustomError>(42);
148f7f6d3e9SLang Hames (void)!E;
149f7f6d3e9SLang Hames };
150f7f6d3e9SLang Hames EXPECT_DEATH(DropUnhandledError(),
151f7f6d3e9SLang Hames "Program aborted due to an unhandled Error:")
152f7f6d3e9SLang Hames << "Unhandled Error failure value did not cause abort()";
153f7f6d3e9SLang Hames }
154f7f6d3e9SLang Hames #endif
155f7f6d3e9SLang Hames
15601864a2dSLang Hames // Check 'Error::isA<T>' method handling.
TEST(Error,IsAHandling)15701864a2dSLang Hames TEST(Error, IsAHandling) {
158f7f6d3e9SLang Hames // Check 'isA' handling.
159f7f6d3e9SLang Hames Error E = make_error<CustomError>(1);
160f7f6d3e9SLang Hames Error F = make_error<CustomSubError>(1, 2);
16101a3cf4dSLang Hames Error G = Error::success();
162f7f6d3e9SLang Hames
163f7f6d3e9SLang Hames EXPECT_TRUE(E.isA<CustomError>());
164f7f6d3e9SLang Hames EXPECT_FALSE(E.isA<CustomSubError>());
165f7f6d3e9SLang Hames EXPECT_TRUE(F.isA<CustomError>());
166f7f6d3e9SLang Hames EXPECT_TRUE(F.isA<CustomSubError>());
16701a3cf4dSLang Hames EXPECT_FALSE(G.isA<CustomError>());
168f7f6d3e9SLang Hames
169f7f6d3e9SLang Hames consumeError(std::move(E));
170f7f6d3e9SLang Hames consumeError(std::move(F));
17101a3cf4dSLang Hames consumeError(std::move(G));
172f7f6d3e9SLang Hames }
173f7f6d3e9SLang Hames
174f7f6d3e9SLang Hames // Check that we can handle a custom error.
TEST(Error,HandleCustomError)17501864a2dSLang Hames TEST(Error, HandleCustomError) {
176f7f6d3e9SLang Hames int CaughtErrorInfo = 0;
177f7f6d3e9SLang Hames handleAllErrors(make_error<CustomError>(42), [&](const CustomError &CE) {
178f7f6d3e9SLang Hames CaughtErrorInfo = CE.getInfo();
179f7f6d3e9SLang Hames });
180f7f6d3e9SLang Hames
18138ac4093SArchibald Elliott EXPECT_EQ(CaughtErrorInfo, 42) << "Wrong result from CustomError handler";
182f7f6d3e9SLang Hames }
183f7f6d3e9SLang Hames
184f7f6d3e9SLang Hames // Check that handler type deduction also works for handlers
185f7f6d3e9SLang Hames // of the following types:
186f7f6d3e9SLang Hames // void (const Err&)
187f7f6d3e9SLang Hames // Error (const Err&) mutable
188f7f6d3e9SLang Hames // void (const Err&) mutable
189f7f6d3e9SLang Hames // Error (Err&)
190f7f6d3e9SLang Hames // void (Err&)
191f7f6d3e9SLang Hames // Error (Err&) mutable
192f7f6d3e9SLang Hames // void (Err&) mutable
193f7f6d3e9SLang Hames // Error (unique_ptr<Err>)
194f7f6d3e9SLang Hames // void (unique_ptr<Err>)
195f7f6d3e9SLang Hames // Error (unique_ptr<Err>) mutable
196f7f6d3e9SLang Hames // void (unique_ptr<Err>) mutable
TEST(Error,HandlerTypeDeduction)19701864a2dSLang Hames TEST(Error, HandlerTypeDeduction) {
198f7f6d3e9SLang Hames
199f7f6d3e9SLang Hames handleAllErrors(make_error<CustomError>(42), [](const CustomError &CE) {});
200f7f6d3e9SLang Hames
201f7f6d3e9SLang Hames handleAllErrors(
202f7f6d3e9SLang Hames make_error<CustomError>(42),
203c1edf566SMehdi Amini [](const CustomError &CE) mutable -> Error { return Error::success(); });
204f7f6d3e9SLang Hames
205f7f6d3e9SLang Hames handleAllErrors(make_error<CustomError>(42),
206f7f6d3e9SLang Hames [](const CustomError &CE) mutable {});
207f7f6d3e9SLang Hames
208f7f6d3e9SLang Hames handleAllErrors(make_error<CustomError>(42),
209c1edf566SMehdi Amini [](CustomError &CE) -> Error { return Error::success(); });
210f7f6d3e9SLang Hames
211f7f6d3e9SLang Hames handleAllErrors(make_error<CustomError>(42), [](CustomError &CE) {});
212f7f6d3e9SLang Hames
213f7f6d3e9SLang Hames handleAllErrors(make_error<CustomError>(42),
214c1edf566SMehdi Amini [](CustomError &CE) mutable -> Error { return Error::success(); });
215f7f6d3e9SLang Hames
216f7f6d3e9SLang Hames handleAllErrors(make_error<CustomError>(42), [](CustomError &CE) mutable {});
217f7f6d3e9SLang Hames
218f7f6d3e9SLang Hames handleAllErrors(
219f7f6d3e9SLang Hames make_error<CustomError>(42),
220c1edf566SMehdi Amini [](std::unique_ptr<CustomError> CE) -> Error { return Error::success(); });
221f7f6d3e9SLang Hames
222f7f6d3e9SLang Hames handleAllErrors(make_error<CustomError>(42),
223f7f6d3e9SLang Hames [](std::unique_ptr<CustomError> CE) {});
224f7f6d3e9SLang Hames
225f7f6d3e9SLang Hames handleAllErrors(
226f7f6d3e9SLang Hames make_error<CustomError>(42),
227c1edf566SMehdi Amini [](std::unique_ptr<CustomError> CE) mutable -> Error { return Error::success(); });
228f7f6d3e9SLang Hames
229f7f6d3e9SLang Hames handleAllErrors(make_error<CustomError>(42),
230f7f6d3e9SLang Hames [](std::unique_ptr<CustomError> CE) mutable {});
231f7f6d3e9SLang Hames
232f7f6d3e9SLang Hames // Check that named handlers of type 'Error (const Err&)' work.
233f7f6d3e9SLang Hames handleAllErrors(make_error<CustomError>(42), handleCustomError);
234f7f6d3e9SLang Hames
235f7f6d3e9SLang Hames // Check that named handlers of type 'void (const Err&)' work.
236f7f6d3e9SLang Hames handleAllErrors(make_error<CustomError>(42), handleCustomErrorVoid);
237f7f6d3e9SLang Hames
238f7f6d3e9SLang Hames // Check that named handlers of type 'Error (std::unique_ptr<Err>)' work.
239f7f6d3e9SLang Hames handleAllErrors(make_error<CustomError>(42), handleCustomErrorUP);
240f7f6d3e9SLang Hames
241f7f6d3e9SLang Hames // Check that named handlers of type 'Error (std::unique_ptr<Err>)' work.
242f7f6d3e9SLang Hames handleAllErrors(make_error<CustomError>(42), handleCustomErrorUPVoid);
24301864a2dSLang Hames }
244f7f6d3e9SLang Hames
24501864a2dSLang Hames // Test that we can handle errors with custom base classes.
TEST(Error,HandleCustomErrorWithCustomBaseClass)24601864a2dSLang Hames TEST(Error, HandleCustomErrorWithCustomBaseClass) {
247f7f6d3e9SLang Hames int CaughtErrorInfo = 0;
248f7f6d3e9SLang Hames int CaughtErrorExtraInfo = 0;
249f7f6d3e9SLang Hames handleAllErrors(make_error<CustomSubError>(42, 7),
250f7f6d3e9SLang Hames [&](const CustomSubError &SE) {
251f7f6d3e9SLang Hames CaughtErrorInfo = SE.getInfo();
252f7f6d3e9SLang Hames CaughtErrorExtraInfo = SE.getExtraInfo();
253f7f6d3e9SLang Hames });
254f7f6d3e9SLang Hames
25538ac4093SArchibald Elliott EXPECT_EQ(CaughtErrorInfo, 42) << "Wrong result from CustomSubError handler";
25638ac4093SArchibald Elliott EXPECT_EQ(CaughtErrorExtraInfo, 7)
257f7f6d3e9SLang Hames << "Wrong result from CustomSubError handler";
258f7f6d3e9SLang Hames }
259f7f6d3e9SLang Hames
260f7f6d3e9SLang Hames // Check that we trigger only the first handler that applies.
TEST(Error,FirstHandlerOnly)26101864a2dSLang Hames TEST(Error, FirstHandlerOnly) {
262f7f6d3e9SLang Hames int DummyInfo = 0;
263f7f6d3e9SLang Hames int CaughtErrorInfo = 0;
264f7f6d3e9SLang Hames int CaughtErrorExtraInfo = 0;
265f7f6d3e9SLang Hames
266f7f6d3e9SLang Hames handleAllErrors(make_error<CustomSubError>(42, 7),
267f7f6d3e9SLang Hames [&](const CustomSubError &SE) {
268f7f6d3e9SLang Hames CaughtErrorInfo = SE.getInfo();
269f7f6d3e9SLang Hames CaughtErrorExtraInfo = SE.getExtraInfo();
270f7f6d3e9SLang Hames },
271f7f6d3e9SLang Hames [&](const CustomError &CE) { DummyInfo = CE.getInfo(); });
272f7f6d3e9SLang Hames
27338ac4093SArchibald Elliott EXPECT_EQ(CaughtErrorInfo, 42) << "Activated the wrong Error handler(s)";
27438ac4093SArchibald Elliott EXPECT_EQ(CaughtErrorExtraInfo, 7) << "Activated the wrong Error handler(s)";
27538ac4093SArchibald Elliott EXPECT_EQ(DummyInfo, 0) << "Activated the wrong Error handler(s)";
276f7f6d3e9SLang Hames }
277f7f6d3e9SLang Hames
278f7f6d3e9SLang Hames // Check that general handlers shadow specific ones.
TEST(Error,HandlerShadowing)27901864a2dSLang Hames TEST(Error, HandlerShadowing) {
280f7f6d3e9SLang Hames int CaughtErrorInfo = 0;
281f7f6d3e9SLang Hames int DummyInfo = 0;
282f7f6d3e9SLang Hames int DummyExtraInfo = 0;
283f7f6d3e9SLang Hames
284f7f6d3e9SLang Hames handleAllErrors(
285f7f6d3e9SLang Hames make_error<CustomSubError>(42, 7),
286f7f6d3e9SLang Hames [&](const CustomError &CE) { CaughtErrorInfo = CE.getInfo(); },
287f7f6d3e9SLang Hames [&](const CustomSubError &SE) {
288f7f6d3e9SLang Hames DummyInfo = SE.getInfo();
289f7f6d3e9SLang Hames DummyExtraInfo = SE.getExtraInfo();
290f7f6d3e9SLang Hames });
291f7f6d3e9SLang Hames
29238ac4093SArchibald Elliott EXPECT_EQ(CaughtErrorInfo, 42)
29338ac4093SArchibald Elliott << "General Error handler did not shadow specific handler";
29438ac4093SArchibald Elliott EXPECT_EQ(DummyInfo, 0)
29538ac4093SArchibald Elliott << "General Error handler did not shadow specific handler";
29638ac4093SArchibald Elliott EXPECT_EQ(DummyExtraInfo, 0)
297f7f6d3e9SLang Hames << "General Error handler did not shadow specific handler";
298f7f6d3e9SLang Hames }
299f7f6d3e9SLang Hames
30001864a2dSLang Hames // Test joinErrors.
TEST(Error,CheckJoinErrors)30101864a2dSLang Hames TEST(Error, CheckJoinErrors) {
302f7f6d3e9SLang Hames int CustomErrorInfo1 = 0;
303f7f6d3e9SLang Hames int CustomErrorInfo2 = 0;
304f7f6d3e9SLang Hames int CustomErrorExtraInfo = 0;
30501864a2dSLang Hames Error E =
30601864a2dSLang Hames joinErrors(make_error<CustomError>(7), make_error<CustomSubError>(42, 7));
307f7f6d3e9SLang Hames
308f7f6d3e9SLang Hames handleAllErrors(std::move(E),
309f7f6d3e9SLang Hames [&](const CustomSubError &SE) {
310f7f6d3e9SLang Hames CustomErrorInfo2 = SE.getInfo();
311f7f6d3e9SLang Hames CustomErrorExtraInfo = SE.getExtraInfo();
312f7f6d3e9SLang Hames },
313f7f6d3e9SLang Hames [&](const CustomError &CE) {
314f7f6d3e9SLang Hames // Assert that the CustomError instance above is handled
315f7f6d3e9SLang Hames // before the
316f7f6d3e9SLang Hames // CustomSubError - joinErrors should preserve error
317f7f6d3e9SLang Hames // ordering.
318f7f6d3e9SLang Hames EXPECT_EQ(CustomErrorInfo2, 0)
319f7f6d3e9SLang Hames << "CustomErrorInfo2 should be 0 here. "
320f7f6d3e9SLang Hames "joinErrors failed to preserve ordering.\n";
321f7f6d3e9SLang Hames CustomErrorInfo1 = CE.getInfo();
322f7f6d3e9SLang Hames });
323f7f6d3e9SLang Hames
32438ac4093SArchibald Elliott EXPECT_EQ(CustomErrorInfo1, 7) << "Failed handling compound Error.";
32538ac4093SArchibald Elliott EXPECT_EQ(CustomErrorInfo2, 42) << "Failed handling compound Error.";
32638ac4093SArchibald Elliott EXPECT_EQ(CustomErrorExtraInfo, 7) << "Failed handling compound Error.";
327759b30edSLang Hames
328759b30edSLang Hames // Test appending a single item to a list.
329759b30edSLang Hames {
330759b30edSLang Hames int Sum = 0;
331759b30edSLang Hames handleAllErrors(
332759b30edSLang Hames joinErrors(
333759b30edSLang Hames joinErrors(make_error<CustomError>(7),
334759b30edSLang Hames make_error<CustomError>(7)),
335759b30edSLang Hames make_error<CustomError>(7)),
336759b30edSLang Hames [&](const CustomError &CE) {
337759b30edSLang Hames Sum += CE.getInfo();
338759b30edSLang Hames });
339759b30edSLang Hames EXPECT_EQ(Sum, 21) << "Failed to correctly append error to error list.";
340759b30edSLang Hames }
341759b30edSLang Hames
342759b30edSLang Hames // Test prepending a single item to a list.
343759b30edSLang Hames {
344759b30edSLang Hames int Sum = 0;
345759b30edSLang Hames handleAllErrors(
346759b30edSLang Hames joinErrors(
347759b30edSLang Hames make_error<CustomError>(7),
348759b30edSLang Hames joinErrors(make_error<CustomError>(7),
349759b30edSLang Hames make_error<CustomError>(7))),
350759b30edSLang Hames [&](const CustomError &CE) {
351759b30edSLang Hames Sum += CE.getInfo();
352759b30edSLang Hames });
353759b30edSLang Hames EXPECT_EQ(Sum, 21) << "Failed to correctly prepend error to error list.";
354759b30edSLang Hames }
355759b30edSLang Hames
356759b30edSLang Hames // Test concatenating two error lists.
357759b30edSLang Hames {
358759b30edSLang Hames int Sum = 0;
359759b30edSLang Hames handleAllErrors(
360759b30edSLang Hames joinErrors(
361759b30edSLang Hames joinErrors(
362759b30edSLang Hames make_error<CustomError>(7),
363759b30edSLang Hames make_error<CustomError>(7)),
364759b30edSLang Hames joinErrors(
365759b30edSLang Hames make_error<CustomError>(7),
366759b30edSLang Hames make_error<CustomError>(7))),
367759b30edSLang Hames [&](const CustomError &CE) {
368759b30edSLang Hames Sum += CE.getInfo();
369759b30edSLang Hames });
3700ca79dcfSHiroshi Inoue EXPECT_EQ(Sum, 28) << "Failed to correctly concatenate error lists.";
371759b30edSLang Hames }
372f7f6d3e9SLang Hames }
373f7f6d3e9SLang Hames
37401864a2dSLang Hames // Test that we can consume success values.
TEST(Error,ConsumeSuccess)37501864a2dSLang Hames TEST(Error, ConsumeSuccess) {
376c1edf566SMehdi Amini Error E = Error::success();
377f7f6d3e9SLang Hames consumeError(std::move(E));
378f7f6d3e9SLang Hames }
37901864a2dSLang Hames
TEST(Error,ConsumeError)38001864a2dSLang Hames TEST(Error, ConsumeError) {
381f7f6d3e9SLang Hames Error E = make_error<CustomError>(7);
382f7f6d3e9SLang Hames consumeError(std::move(E));
383f7f6d3e9SLang Hames }
384f7f6d3e9SLang Hames
385f7f6d3e9SLang Hames // Test that handleAllUnhandledErrors crashes if an error is not caught.
386f7f6d3e9SLang Hames // Test runs in debug mode only.
387cb79c079SMehdi Amini #if LLVM_ENABLE_ABI_BREAKING_CHECKS
TEST(Error,FailureToHandle)38801864a2dSLang Hames TEST(Error, FailureToHandle) {
389f7f6d3e9SLang Hames auto FailToHandle = []() {
39001864a2dSLang Hames handleAllErrors(make_error<CustomError>(7), [&](const CustomSubError &SE) {
391f7f6d3e9SLang Hames errs() << "This should never be called";
392f7f6d3e9SLang Hames exit(1);
393f7f6d3e9SLang Hames });
394f7f6d3e9SLang Hames };
395f7f6d3e9SLang Hames
3967febf2baSLang Hames EXPECT_DEATH(FailToHandle(),
397ecb310b3SDon Hinton "Failure value returned from cantFail wrapped call\n"
398ecb310b3SDon Hinton "CustomError \\{7\\}")
399f7f6d3e9SLang Hames << "Unhandled Error in handleAllErrors call did not cause an "
400f7f6d3e9SLang Hames "abort()";
401f7f6d3e9SLang Hames }
402f7f6d3e9SLang Hames #endif
403f7f6d3e9SLang Hames
404f7f6d3e9SLang Hames // Test that handleAllUnhandledErrors crashes if an error is returned from a
405f7f6d3e9SLang Hames // handler.
406f7f6d3e9SLang Hames // Test runs in debug mode only.
407cb79c079SMehdi Amini #if LLVM_ENABLE_ABI_BREAKING_CHECKS
TEST(Error,FailureFromHandler)40801864a2dSLang Hames TEST(Error, FailureFromHandler) {
409f7f6d3e9SLang Hames auto ReturnErrorFromHandler = []() {
410f7f6d3e9SLang Hames handleAllErrors(make_error<CustomError>(7),
411f7f6d3e9SLang Hames [&](std::unique_ptr<CustomSubError> SE) {
412f7f6d3e9SLang Hames return Error(std::move(SE));
413f7f6d3e9SLang Hames });
414f7f6d3e9SLang Hames };
415f7f6d3e9SLang Hames
416f7f6d3e9SLang Hames EXPECT_DEATH(ReturnErrorFromHandler(),
417ecb310b3SDon Hinton "Failure value returned from cantFail wrapped call\n"
418ecb310b3SDon Hinton "CustomError \\{7\\}")
419f7f6d3e9SLang Hames << " Error returned from handler in handleAllErrors call did not "
420f7f6d3e9SLang Hames "cause abort()";
421f7f6d3e9SLang Hames }
422f7f6d3e9SLang Hames #endif
423f7f6d3e9SLang Hames
424f7f6d3e9SLang Hames // Test that we can return values from handleErrors.
TEST(Error,CatchErrorFromHandler)42501864a2dSLang Hames TEST(Error, CatchErrorFromHandler) {
426f7f6d3e9SLang Hames int ErrorInfo = 0;
427f7f6d3e9SLang Hames
428f7f6d3e9SLang Hames Error E = handleErrors(
429f7f6d3e9SLang Hames make_error<CustomError>(7),
430f7f6d3e9SLang Hames [&](std::unique_ptr<CustomError> CE) { return Error(std::move(CE)); });
431f7f6d3e9SLang Hames
432f7f6d3e9SLang Hames handleAllErrors(std::move(E),
433f7f6d3e9SLang Hames [&](const CustomError &CE) { ErrorInfo = CE.getInfo(); });
434f7f6d3e9SLang Hames
435f7f6d3e9SLang Hames EXPECT_EQ(ErrorInfo, 7)
436f7f6d3e9SLang Hames << "Failed to handle Error returned from handleErrors.";
437f7f6d3e9SLang Hames }
4386935c2d3SLang Hames
TEST(Error,StringError)439c5e0bbd7SLang Hames TEST(Error, StringError) {
440c5e0bbd7SLang Hames std::string Msg;
441c5e0bbd7SLang Hames raw_string_ostream S(Msg);
44245eb84f3SJonas Devlieghere logAllUnhandledErrors(
44345eb84f3SJonas Devlieghere make_error<StringError>("foo" + Twine(42), inconvertibleErrorCode()), S);
444c5e0bbd7SLang Hames EXPECT_EQ(S.str(), "foo42\n") << "Unexpected StringError log result";
445c5e0bbd7SLang Hames
446c5e0bbd7SLang Hames auto EC =
447c5e0bbd7SLang Hames errorToErrorCode(make_error<StringError>("", errc::invalid_argument));
448c5e0bbd7SLang Hames EXPECT_EQ(EC, errc::invalid_argument)
449c5e0bbd7SLang Hames << "Failed to convert StringError to error_code.";
450c5e0bbd7SLang Hames }
451c5e0bbd7SLang Hames
TEST(Error,createStringError)452e58e9907SVictor Leschuk TEST(Error, createStringError) {
453e58e9907SVictor Leschuk static const char *Bar = "bar";
454e58e9907SVictor Leschuk static const std::error_code EC = errc::invalid_argument;
455e58e9907SVictor Leschuk std::string Msg;
456e58e9907SVictor Leschuk raw_string_ostream S(Msg);
457e58e9907SVictor Leschuk logAllUnhandledErrors(createStringError(EC, "foo%s%d0x%" PRIx8, Bar, 1, 0xff),
45845eb84f3SJonas Devlieghere S);
459e58e9907SVictor Leschuk EXPECT_EQ(S.str(), "foobar10xff\n")
460e58e9907SVictor Leschuk << "Unexpected createStringError() log result";
461e58e9907SVictor Leschuk
462e58e9907SVictor Leschuk S.flush();
463e58e9907SVictor Leschuk Msg.clear();
46445eb84f3SJonas Devlieghere logAllUnhandledErrors(createStringError(EC, Bar), S);
465e58e9907SVictor Leschuk EXPECT_EQ(S.str(), "bar\n")
466e58e9907SVictor Leschuk << "Unexpected createStringError() (overloaded) log result";
467e58e9907SVictor Leschuk
468e58e9907SVictor Leschuk S.flush();
469e58e9907SVictor Leschuk Msg.clear();
470e58e9907SVictor Leschuk auto Res = errorToErrorCode(createStringError(EC, "foo%s", Bar));
471e58e9907SVictor Leschuk EXPECT_EQ(Res, EC)
472e58e9907SVictor Leschuk << "Failed to convert createStringError() result to error_code.";
473e58e9907SVictor Leschuk }
474e58e9907SVictor Leschuk
47501864a2dSLang Hames // Test that the ExitOnError utility works as expected.
TEST(ErrorDeathTest,ExitOnError)476c32f8f34SYuanfang Chen TEST(ErrorDeathTest, ExitOnError) {
4776935c2d3SLang Hames ExitOnError ExitOnErr;
4786935c2d3SLang Hames ExitOnErr.setBanner("Error in tool:");
47901864a2dSLang Hames ExitOnErr.setExitCodeMapper([](const Error &E) {
4806935c2d3SLang Hames if (E.isA<CustomSubError>())
4816935c2d3SLang Hames return 2;
4826935c2d3SLang Hames return 1;
4836935c2d3SLang Hames });
4846935c2d3SLang Hames
4856935c2d3SLang Hames // Make sure we don't bail on success.
4866935c2d3SLang Hames ExitOnErr(Error::success());
4876935c2d3SLang Hames EXPECT_EQ(ExitOnErr(Expected<int>(7)), 7)
4886935c2d3SLang Hames << "exitOnError returned an invalid value for Expected";
4896935c2d3SLang Hames
490285639f8SLang Hames int A = 7;
491285639f8SLang Hames int &B = ExitOnErr(Expected<int&>(A));
492285639f8SLang Hames EXPECT_EQ(&A, &B) << "ExitOnError failed to propagate reference";
493285639f8SLang Hames
4946935c2d3SLang Hames // Exit tests.
4956935c2d3SLang Hames EXPECT_EXIT(ExitOnErr(make_error<CustomError>(7)),
4966935c2d3SLang Hames ::testing::ExitedWithCode(1), "Error in tool:")
4976935c2d3SLang Hames << "exitOnError returned an unexpected error result";
4986935c2d3SLang Hames
4996935c2d3SLang Hames EXPECT_EXIT(ExitOnErr(Expected<int>(make_error<CustomSubError>(0, 0))),
5006935c2d3SLang Hames ::testing::ExitedWithCode(2), "Error in tool:")
5016935c2d3SLang Hames << "exitOnError returned an unexpected error result";
5026935c2d3SLang Hames }
503f7f6d3e9SLang Hames
504fd4de910SLang Hames // Test that the ExitOnError utility works as expected.
TEST(Error,CantFailSuccess)505fd4de910SLang Hames TEST(Error, CantFailSuccess) {
506fd4de910SLang Hames cantFail(Error::success());
507fd4de910SLang Hames
508fd4de910SLang Hames int X = cantFail(Expected<int>(42));
509fd4de910SLang Hames EXPECT_EQ(X, 42) << "Expected value modified by cantFail";
510cd227536SLang Hames
511cd227536SLang Hames int Dummy = 42;
512cd227536SLang Hames int &Y = cantFail(Expected<int&>(Dummy));
513cd227536SLang Hames EXPECT_EQ(&Dummy, &Y) << "Reference mangled by cantFail";
514fd4de910SLang Hames }
515fd4de910SLang Hames
516fd4de910SLang Hames // Test that cantFail results in a crash if you pass it a failure value.
517cc14a386SStephen Hines #if LLVM_ENABLE_ABI_BREAKING_CHECKS && !defined(NDEBUG)
TEST(Error,CantFailDeath)518fd4de910SLang Hames TEST(Error, CantFailDeath) {
519ecb310b3SDon Hinton EXPECT_DEATH(cantFail(make_error<StringError>("Original error message",
520ecb310b3SDon Hinton inconvertibleErrorCode()),
5213025e48aSLang Hames "Cantfail call failed"),
522ecb310b3SDon Hinton "Cantfail call failed\n"
523ecb310b3SDon Hinton "Original error message")
524fd4de910SLang Hames << "cantFail(Error) did not cause an abort for failure value";
525fd4de910SLang Hames
526fd4de910SLang Hames EXPECT_DEATH(
527fd4de910SLang Hames {
528fd4de910SLang Hames auto IEC = inconvertibleErrorCode();
529fd4de910SLang Hames int X = cantFail(Expected<int>(make_error<StringError>("foo", IEC)));
530fd4de910SLang Hames (void)X;
531fd4de910SLang Hames },
532fd4de910SLang Hames "Failure value returned from cantFail wrapped call")
533fd4de910SLang Hames << "cantFail(Expected<int>) did not cause an abort for failure value";
534fd4de910SLang Hames }
535fd4de910SLang Hames #endif
536fd4de910SLang Hames
537fd4de910SLang Hames
538580ca237SLang Hames // Test Checked Expected<T> in success mode.
TEST(Error,CheckedExpectedInSuccessMode)539580ca237SLang Hames TEST(Error, CheckedExpectedInSuccessMode) {
540f7f6d3e9SLang Hames Expected<int> A = 7;
54101864a2dSLang Hames EXPECT_TRUE(!!A) << "Expected with non-error value doesn't convert to 'true'";
542580ca237SLang Hames // Access is safe in second test, since we checked the error in the first.
543f7f6d3e9SLang Hames EXPECT_EQ(*A, 7) << "Incorrect Expected non-error value";
544f7f6d3e9SLang Hames }
545f7f6d3e9SLang Hames
546285639f8SLang Hames // Test Expected with reference type.
TEST(Error,ExpectedWithReferenceType)547285639f8SLang Hames TEST(Error, ExpectedWithReferenceType) {
548285639f8SLang Hames int A = 7;
549285639f8SLang Hames Expected<int&> B = A;
550285639f8SLang Hames // 'Check' B.
551285639f8SLang Hames (void)!!B;
552285639f8SLang Hames int &C = *B;
553285639f8SLang Hames EXPECT_EQ(&A, &C) << "Expected failed to propagate reference";
554285639f8SLang Hames }
555285639f8SLang Hames
556580ca237SLang Hames // Test Unchecked Expected<T> in success mode.
557580ca237SLang Hames // We expect this to blow up the same way Error would.
558580ca237SLang Hames // Test runs in debug mode only.
559cb79c079SMehdi Amini #if LLVM_ENABLE_ABI_BREAKING_CHECKS
TEST(Error,UncheckedExpectedInSuccessModeDestruction)560580ca237SLang Hames TEST(Error, UncheckedExpectedInSuccessModeDestruction) {
561580ca237SLang Hames EXPECT_DEATH({ Expected<int> A = 7; },
562580ca237SLang Hames "Expected<T> must be checked before access or destruction.")
5637445f1e4Sxndcn << "Unchecked Expected<T> success value did not cause an abort().";
564580ca237SLang Hames }
565580ca237SLang Hames #endif
566580ca237SLang Hames
567580ca237SLang Hames // Test Unchecked Expected<T> in success mode.
568580ca237SLang Hames // We expect this to blow up the same way Error would.
569580ca237SLang Hames // Test runs in debug mode only.
570cb79c079SMehdi Amini #if LLVM_ENABLE_ABI_BREAKING_CHECKS
TEST(Error,UncheckedExpectedInSuccessModeAccess)571580ca237SLang Hames TEST(Error, UncheckedExpectedInSuccessModeAccess) {
5727445f1e4Sxndcn EXPECT_DEATH(
5737445f1e4Sxndcn {
5747445f1e4Sxndcn const Expected<int> A = 7;
5757445f1e4Sxndcn *A;
5767445f1e4Sxndcn },
577580ca237SLang Hames "Expected<T> must be checked before access or destruction.")
5787445f1e4Sxndcn << "Unchecked Expected<T> success value did not cause an abort().";
579580ca237SLang Hames }
580580ca237SLang Hames #endif
581580ca237SLang Hames
582580ca237SLang Hames // Test Unchecked Expected<T> in success mode.
583580ca237SLang Hames // We expect this to blow up the same way Error would.
584580ca237SLang Hames // Test runs in debug mode only.
585cb79c079SMehdi Amini #if LLVM_ENABLE_ABI_BREAKING_CHECKS
TEST(Error,UncheckedExpectedInSuccessModeAssignment)586580ca237SLang Hames TEST(Error, UncheckedExpectedInSuccessModeAssignment) {
5877445f1e4Sxndcn EXPECT_DEATH(
5887445f1e4Sxndcn {
5897445f1e4Sxndcn Expected<int> A = 7;
5907445f1e4Sxndcn A = 7;
5917445f1e4Sxndcn },
592580ca237SLang Hames "Expected<T> must be checked before access or destruction.")
5937445f1e4Sxndcn << "Unchecked Expected<T> success value did not cause an abort().";
594580ca237SLang Hames }
595580ca237SLang Hames #endif
596580ca237SLang Hames
59701864a2dSLang Hames // Test Expected<T> in failure mode.
TEST(Error,ExpectedInFailureMode)59801864a2dSLang Hames TEST(Error, ExpectedInFailureMode) {
599f7f6d3e9SLang Hames Expected<int> A = make_error<CustomError>(42);
600f7f6d3e9SLang Hames EXPECT_FALSE(!!A) << "Expected with error value doesn't convert to 'false'";
601f7f6d3e9SLang Hames Error E = A.takeError();
602f7f6d3e9SLang Hames EXPECT_TRUE(E.isA<CustomError>()) << "Incorrect Expected error value";
603f7f6d3e9SLang Hames consumeError(std::move(E));
604f7f6d3e9SLang Hames }
605f7f6d3e9SLang Hames
606f7f6d3e9SLang Hames // Check that an Expected instance with an error value doesn't allow access to
607f7f6d3e9SLang Hames // operator*.
608f7f6d3e9SLang Hames // Test runs in debug mode only.
609cb79c079SMehdi Amini #if LLVM_ENABLE_ABI_BREAKING_CHECKS
TEST(Error,AccessExpectedInFailureMode)61001864a2dSLang Hames TEST(Error, AccessExpectedInFailureMode) {
611f7f6d3e9SLang Hames Expected<int> A = make_error<CustomError>(42);
612580ca237SLang Hames EXPECT_DEATH(*A, "Expected<T> must be checked before access or destruction.")
613f7f6d3e9SLang Hames << "Incorrect Expected error value";
614f7f6d3e9SLang Hames consumeError(A.takeError());
615f7f6d3e9SLang Hames }
616f7f6d3e9SLang Hames #endif
617f7f6d3e9SLang Hames
618f7f6d3e9SLang Hames // Check that an Expected instance with an error triggers an abort if
619f7f6d3e9SLang Hames // unhandled.
620f7f6d3e9SLang Hames // Test runs in debug mode only.
621cb79c079SMehdi Amini #if LLVM_ENABLE_ABI_BREAKING_CHECKS
TEST(Error,UnhandledExpectedInFailureMode)62201864a2dSLang Hames TEST(Error, UnhandledExpectedInFailureMode) {
623f7f6d3e9SLang Hames EXPECT_DEATH({ Expected<int> A = make_error<CustomError>(42); },
624580ca237SLang Hames "Expected<T> must be checked before access or destruction.")
625f7f6d3e9SLang Hames << "Unchecked Expected<T> failure value did not cause an abort()";
62601864a2dSLang Hames }
627f7f6d3e9SLang Hames #endif
628f7f6d3e9SLang Hames
629f7f6d3e9SLang Hames // Test covariance of Expected.
TEST(Error,ExpectedCovariance)63001864a2dSLang Hames TEST(Error, ExpectedCovariance) {
631f7f6d3e9SLang Hames class B {};
632f7f6d3e9SLang Hames class D : public B {};
633f7f6d3e9SLang Hames
634f7f6d3e9SLang Hames Expected<B *> A1(Expected<D *>(nullptr));
635580ca237SLang Hames // Check A1 by converting to bool before assigning to it.
636580ca237SLang Hames (void)!!A1;
637f7f6d3e9SLang Hames A1 = Expected<D *>(nullptr);
638580ca237SLang Hames // Check A1 again before destruction.
639580ca237SLang Hames (void)!!A1;
640f7f6d3e9SLang Hames
641f7f6d3e9SLang Hames Expected<std::unique_ptr<B>> A2(Expected<std::unique_ptr<D>>(nullptr));
642580ca237SLang Hames // Check A2 by converting to bool before assigning to it.
643580ca237SLang Hames (void)!!A2;
644f7f6d3e9SLang Hames A2 = Expected<std::unique_ptr<D>>(nullptr);
645580ca237SLang Hames // Check A2 again before destruction.
646580ca237SLang Hames (void)!!A2;
647f7f6d3e9SLang Hames }
648f7f6d3e9SLang Hames
6495d06c23dSLang Hames // Test that handleExpected just returns success values.
TEST(Error,HandleExpectedSuccess)6505d06c23dSLang Hames TEST(Error, HandleExpectedSuccess) {
6515d06c23dSLang Hames auto ValOrErr =
6525d06c23dSLang Hames handleExpected(Expected<int>(42),
6535d06c23dSLang Hames []() { return Expected<int>(43); });
6545d06c23dSLang Hames EXPECT_TRUE(!!ValOrErr)
6555d06c23dSLang Hames << "handleExpected should have returned a success value here";
6565d06c23dSLang Hames EXPECT_EQ(*ValOrErr, 42)
6575d06c23dSLang Hames << "handleExpected should have returned the original success value here";
6585d06c23dSLang Hames }
6595d06c23dSLang Hames
6605d06c23dSLang Hames enum FooStrategy { Aggressive, Conservative };
6615d06c23dSLang Hames
foo(FooStrategy S)6625d06c23dSLang Hames static Expected<int> foo(FooStrategy S) {
6635d06c23dSLang Hames if (S == Aggressive)
6645d06c23dSLang Hames return make_error<CustomError>(7);
6655d06c23dSLang Hames return 42;
6665d06c23dSLang Hames }
6675d06c23dSLang Hames
6685d06c23dSLang Hames // Test that handleExpected invokes the error path if errors are not handled.
TEST(Error,HandleExpectedUnhandledError)6695d06c23dSLang Hames TEST(Error, HandleExpectedUnhandledError) {
6705d06c23dSLang Hames // foo(Aggressive) should return a CustomError which should pass through as
6715d06c23dSLang Hames // there is no handler for CustomError.
6725d06c23dSLang Hames auto ValOrErr =
6735d06c23dSLang Hames handleExpected(
6745d06c23dSLang Hames foo(Aggressive),
6755d06c23dSLang Hames []() { return foo(Conservative); });
6765d06c23dSLang Hames
6775d06c23dSLang Hames EXPECT_FALSE(!!ValOrErr)
6785d06c23dSLang Hames << "handleExpected should have returned an error here";
6795d06c23dSLang Hames auto Err = ValOrErr.takeError();
6805d06c23dSLang Hames EXPECT_TRUE(Err.isA<CustomError>())
6815d06c23dSLang Hames << "handleExpected should have returned the CustomError generated by "
6825d06c23dSLang Hames "foo(Aggressive) here";
6835d06c23dSLang Hames consumeError(std::move(Err));
6845d06c23dSLang Hames }
6855d06c23dSLang Hames
6865d06c23dSLang Hames // Test that handleExpected invokes the fallback path if errors are handled.
TEST(Error,HandleExpectedHandledError)6875d06c23dSLang Hames TEST(Error, HandleExpectedHandledError) {
6885d06c23dSLang Hames // foo(Aggressive) should return a CustomError which should handle triggering
6895d06c23dSLang Hames // the fallback path.
6905d06c23dSLang Hames auto ValOrErr =
6915d06c23dSLang Hames handleExpected(
6925d06c23dSLang Hames foo(Aggressive),
6935d06c23dSLang Hames []() { return foo(Conservative); },
6945d06c23dSLang Hames [](const CustomError&) { /* do nothing */ });
6955d06c23dSLang Hames
6965d06c23dSLang Hames EXPECT_TRUE(!!ValOrErr)
6975d06c23dSLang Hames << "handleExpected should have returned a success value here";
6985d06c23dSLang Hames EXPECT_EQ(*ValOrErr, 42)
6995d06c23dSLang Hames << "handleExpected returned the wrong success value";
7005d06c23dSLang Hames }
7015d06c23dSLang Hames
TEST(Error,ErrorCodeConversions)702d21a535bSLang Hames TEST(Error, ErrorCodeConversions) {
703f7f6d3e9SLang Hames // Round-trip a success value to check that it converts correctly.
704f7f6d3e9SLang Hames EXPECT_EQ(errorToErrorCode(errorCodeToError(std::error_code())),
705f7f6d3e9SLang Hames std::error_code())
706f7f6d3e9SLang Hames << "std::error_code() should round-trip via Error conversions";
707f7f6d3e9SLang Hames
708f7f6d3e9SLang Hames // Round-trip an error value to check that it converts correctly.
709f7f6d3e9SLang Hames EXPECT_EQ(errorToErrorCode(errorCodeToError(errc::invalid_argument)),
710f7f6d3e9SLang Hames errc::invalid_argument)
711f7f6d3e9SLang Hames << "std::error_code error value should round-trip via Error "
712f7f6d3e9SLang Hames "conversions";
713d21a535bSLang Hames
714d21a535bSLang Hames // Round-trip a success value through ErrorOr/Expected to check that it
715d21a535bSLang Hames // converts correctly.
716d21a535bSLang Hames {
717d21a535bSLang Hames auto Orig = ErrorOr<int>(42);
718d21a535bSLang Hames auto RoundTripped =
719d21a535bSLang Hames expectedToErrorOr(errorOrToExpected(ErrorOr<int>(42)));
720d21a535bSLang Hames EXPECT_EQ(*Orig, *RoundTripped)
721d21a535bSLang Hames << "ErrorOr<T> success value should round-trip via Expected<T> "
722d21a535bSLang Hames "conversions.";
723d21a535bSLang Hames }
724d21a535bSLang Hames
725d21a535bSLang Hames // Round-trip a failure value through ErrorOr/Expected to check that it
726d21a535bSLang Hames // converts correctly.
727d21a535bSLang Hames {
728d21a535bSLang Hames auto Orig = ErrorOr<int>(errc::invalid_argument);
729d21a535bSLang Hames auto RoundTripped =
730d21a535bSLang Hames expectedToErrorOr(
731d21a535bSLang Hames errorOrToExpected(ErrorOr<int>(errc::invalid_argument)));
732d21a535bSLang Hames EXPECT_EQ(Orig.getError(), RoundTripped.getError())
733d21a535bSLang Hames << "ErrorOr<T> failure value should round-trip via Expected<T> "
734d21a535bSLang Hames "conversions.";
735d21a535bSLang Hames }
736f7f6d3e9SLang Hames }
737f7f6d3e9SLang Hames
73827370a09SVedant Kumar // Test that error messages work.
TEST(Error,ErrorMessage)73927370a09SVedant Kumar TEST(Error, ErrorMessage) {
740d18083c6SDavid Blaikie EXPECT_EQ(toString(Error::success()), "");
74127370a09SVedant Kumar
74227370a09SVedant Kumar Error E1 = make_error<CustomError>(0);
743d18083c6SDavid Blaikie EXPECT_EQ(toString(std::move(E1)), "CustomError {0}");
74427370a09SVedant Kumar
74527370a09SVedant Kumar Error E2 = make_error<CustomError>(0);
74627370a09SVedant Kumar handleAllErrors(std::move(E2), [](const CustomError &CE) {
747d18083c6SDavid Blaikie EXPECT_EQ(CE.message(), "CustomError {0}");
74827370a09SVedant Kumar });
74927370a09SVedant Kumar
75027370a09SVedant Kumar Error E3 = joinErrors(make_error<CustomError>(0), make_error<CustomError>(1));
751d18083c6SDavid Blaikie EXPECT_EQ(toString(std::move(E3)), "CustomError {0}\n"
752d18083c6SDavid Blaikie "CustomError {1}");
75327370a09SVedant Kumar }
75427370a09SVedant Kumar
TEST(Error,Stream)7558ca99100SSam McCall TEST(Error, Stream) {
7568ca99100SSam McCall {
7578ca99100SSam McCall Error OK = Error::success();
7588ca99100SSam McCall std::string Buf;
7598ca99100SSam McCall llvm::raw_string_ostream S(Buf);
7608ca99100SSam McCall S << OK;
7618ca99100SSam McCall EXPECT_EQ("success", S.str());
7628ca99100SSam McCall consumeError(std::move(OK));
7638ca99100SSam McCall }
7648ca99100SSam McCall {
7658ca99100SSam McCall Error E1 = make_error<CustomError>(0);
7668ca99100SSam McCall std::string Buf;
7678ca99100SSam McCall llvm::raw_string_ostream S(Buf);
7688ca99100SSam McCall S << E1;
7698ca99100SSam McCall EXPECT_EQ("CustomError {0}", S.str());
7708ca99100SSam McCall consumeError(std::move(E1));
7718ca99100SSam McCall }
7728ca99100SSam McCall }
7738ca99100SSam McCall
TEST(Error,SucceededMatcher)7749746b3aeSPavel Labath TEST(Error, SucceededMatcher) {
775e8354fe6SPavel Labath EXPECT_THAT_ERROR(Error::success(), Succeeded());
776e8354fe6SPavel Labath EXPECT_NONFATAL_FAILURE(
777e8354fe6SPavel Labath EXPECT_THAT_ERROR(make_error<CustomError>(0), Succeeded()),
778e8354fe6SPavel Labath "Expected: succeeded\n Actual: failed (CustomError {0})");
779e8354fe6SPavel Labath
7809746b3aeSPavel Labath EXPECT_THAT_EXPECTED(Expected<int>(0), Succeeded());
7819746b3aeSPavel Labath EXPECT_NONFATAL_FAILURE(
7829746b3aeSPavel Labath EXPECT_THAT_EXPECTED(Expected<int>(make_error<CustomError>(0)),
7839746b3aeSPavel Labath Succeeded()),
7849746b3aeSPavel Labath "Expected: succeeded\n Actual: failed (CustomError {0})");
7859746b3aeSPavel Labath int a = 1;
7869746b3aeSPavel Labath EXPECT_THAT_EXPECTED(Expected<int &>(a), Succeeded());
7879746b3aeSPavel Labath }
7889746b3aeSPavel Labath
TEST(Error,FailedMatcher)7899746b3aeSPavel Labath TEST(Error, FailedMatcher) {
790e8354fe6SPavel Labath EXPECT_THAT_ERROR(make_error<CustomError>(0), Failed());
791e8354fe6SPavel Labath EXPECT_NONFATAL_FAILURE(EXPECT_THAT_ERROR(Error::success(), Failed()),
792e8354fe6SPavel Labath "Expected: failed\n Actual: succeeded");
793e8354fe6SPavel Labath
794510725c2SPavel Labath EXPECT_THAT_ERROR(make_error<CustomError>(0), Failed<CustomError>());
795510725c2SPavel Labath EXPECT_NONFATAL_FAILURE(
796510725c2SPavel Labath EXPECT_THAT_ERROR(Error::success(), Failed<CustomError>()),
797510725c2SPavel Labath "Expected: failed with Error of given type\n Actual: succeeded");
798510725c2SPavel Labath EXPECT_NONFATAL_FAILURE(
799510725c2SPavel Labath EXPECT_THAT_ERROR(make_error<CustomError>(0), Failed<CustomSubError>()),
800510725c2SPavel Labath "Error was not of given type");
801510725c2SPavel Labath EXPECT_NONFATAL_FAILURE(
802510725c2SPavel Labath EXPECT_THAT_ERROR(
803510725c2SPavel Labath joinErrors(make_error<CustomError>(0), make_error<CustomError>(1)),
804510725c2SPavel Labath Failed<CustomError>()),
805510725c2SPavel Labath "multiple errors");
806510725c2SPavel Labath
807510725c2SPavel Labath EXPECT_THAT_ERROR(
808510725c2SPavel Labath make_error<CustomError>(0),
809510725c2SPavel Labath Failed<CustomError>(testing::Property(&CustomError::getInfo, 0)));
810510725c2SPavel Labath EXPECT_NONFATAL_FAILURE(
811510725c2SPavel Labath EXPECT_THAT_ERROR(
812510725c2SPavel Labath make_error<CustomError>(0),
813510725c2SPavel Labath Failed<CustomError>(testing::Property(&CustomError::getInfo, 1))),
814510725c2SPavel Labath "Expected: failed with Error of given type and the error is an object "
815510725c2SPavel Labath "whose given property is equal to 1\n"
816510725c2SPavel Labath " Actual: failed (CustomError {0})");
817397e150dSPavel Labath EXPECT_THAT_ERROR(make_error<CustomError>(0), Failed<ErrorInfoBase>());
818510725c2SPavel Labath
819e8354fe6SPavel Labath EXPECT_THAT_EXPECTED(Expected<int>(make_error<CustomError>(0)), Failed());
820e8354fe6SPavel Labath EXPECT_NONFATAL_FAILURE(
821e8354fe6SPavel Labath EXPECT_THAT_EXPECTED(Expected<int>(0), Failed()),
82256c2d999SPavel Labath "Expected: failed\n Actual: succeeded with value 0");
8239746b3aeSPavel Labath EXPECT_THAT_EXPECTED(Expected<int &>(make_error<CustomError>(0)), Failed());
8249746b3aeSPavel Labath }
825e8354fe6SPavel Labath
TEST(Error,HasValueMatcher)8269746b3aeSPavel Labath TEST(Error, HasValueMatcher) {
827e8354fe6SPavel Labath EXPECT_THAT_EXPECTED(Expected<int>(0), HasValue(0));
828e8354fe6SPavel Labath EXPECT_NONFATAL_FAILURE(
829e8354fe6SPavel Labath EXPECT_THAT_EXPECTED(Expected<int>(make_error<CustomError>(0)),
830e8354fe6SPavel Labath HasValue(0)),
83156c2d999SPavel Labath "Expected: succeeded with value (is equal to 0)\n"
832e8354fe6SPavel Labath " Actual: failed (CustomError {0})");
833e8354fe6SPavel Labath EXPECT_NONFATAL_FAILURE(
834e8354fe6SPavel Labath EXPECT_THAT_EXPECTED(Expected<int>(1), HasValue(0)),
83556c2d999SPavel Labath "Expected: succeeded with value (is equal to 0)\n"
83656c2d999SPavel Labath " Actual: succeeded with value 1, (isn't equal to 0)");
837e8354fe6SPavel Labath
838e8354fe6SPavel Labath int a = 1;
83956c2d999SPavel Labath EXPECT_THAT_EXPECTED(Expected<int &>(a), HasValue(testing::Eq(1)));
84056c2d999SPavel Labath
84156c2d999SPavel Labath EXPECT_THAT_EXPECTED(Expected<int>(1), HasValue(testing::Gt(0)));
84256c2d999SPavel Labath EXPECT_NONFATAL_FAILURE(
84356c2d999SPavel Labath EXPECT_THAT_EXPECTED(Expected<int>(0), HasValue(testing::Gt(1))),
84456c2d999SPavel Labath "Expected: succeeded with value (is > 1)\n"
84556c2d999SPavel Labath " Actual: succeeded with value 0, (isn't > 1)");
84656c2d999SPavel Labath EXPECT_NONFATAL_FAILURE(
84756c2d999SPavel Labath EXPECT_THAT_EXPECTED(Expected<int>(make_error<CustomError>(0)),
84856c2d999SPavel Labath HasValue(testing::Gt(1))),
84956c2d999SPavel Labath "Expected: succeeded with value (is > 1)\n"
85056c2d999SPavel Labath " Actual: failed (CustomError {0})");
851e8354fe6SPavel Labath }
852e8354fe6SPavel Labath
TEST(Error,FailedWithMessageMatcher)853b55c58a2SPavel Labath TEST(Error, FailedWithMessageMatcher) {
854b55c58a2SPavel Labath EXPECT_THAT_EXPECTED(Expected<int>(make_error<CustomError>(0)),
855b55c58a2SPavel Labath FailedWithMessage("CustomError {0}"));
856b55c58a2SPavel Labath
857b55c58a2SPavel Labath EXPECT_NONFATAL_FAILURE(
858b55c58a2SPavel Labath EXPECT_THAT_EXPECTED(Expected<int>(make_error<CustomError>(1)),
859b55c58a2SPavel Labath FailedWithMessage("CustomError {0}")),
860b55c58a2SPavel Labath "Expected: failed with Error whose message has 1 element that is equal "
861b55c58a2SPavel Labath "to \"CustomError {0}\"\n"
862b55c58a2SPavel Labath " Actual: failed (CustomError {1})");
863b55c58a2SPavel Labath
864b55c58a2SPavel Labath EXPECT_NONFATAL_FAILURE(
865b55c58a2SPavel Labath EXPECT_THAT_EXPECTED(Expected<int>(0),
866b55c58a2SPavel Labath FailedWithMessage("CustomError {0}")),
867b55c58a2SPavel Labath "Expected: failed with Error whose message has 1 element that is equal "
868b55c58a2SPavel Labath "to \"CustomError {0}\"\n"
869b55c58a2SPavel Labath " Actual: succeeded with value 0");
870b55c58a2SPavel Labath
871b55c58a2SPavel Labath EXPECT_NONFATAL_FAILURE(
872b55c58a2SPavel Labath EXPECT_THAT_EXPECTED(Expected<int>(make_error<CustomError>(0)),
873b55c58a2SPavel Labath FailedWithMessage("CustomError {0}", "CustomError {0}")),
874b55c58a2SPavel Labath "Expected: failed with Error whose message has 2 elements where\n"
875b55c58a2SPavel Labath "element #0 is equal to \"CustomError {0}\",\n"
876b55c58a2SPavel Labath "element #1 is equal to \"CustomError {0}\"\n"
877b55c58a2SPavel Labath " Actual: failed (CustomError {0}), which has 1 element");
878b55c58a2SPavel Labath
879b55c58a2SPavel Labath EXPECT_NONFATAL_FAILURE(
880b55c58a2SPavel Labath EXPECT_THAT_EXPECTED(
881b55c58a2SPavel Labath Expected<int>(joinErrors(make_error<CustomError>(0),
882b55c58a2SPavel Labath make_error<CustomError>(0))),
883b55c58a2SPavel Labath FailedWithMessage("CustomError {0}")),
884b55c58a2SPavel Labath "Expected: failed with Error whose message has 1 element that is equal "
885b55c58a2SPavel Labath "to \"CustomError {0}\"\n"
886b55c58a2SPavel Labath " Actual: failed (CustomError {0}; CustomError {0}), which has 2 elements");
887b55c58a2SPavel Labath
888b55c58a2SPavel Labath EXPECT_THAT_ERROR(
889b55c58a2SPavel Labath joinErrors(make_error<CustomError>(0), make_error<CustomError>(0)),
890b55c58a2SPavel Labath FailedWithMessageArray(testing::SizeIs(2)));
891b55c58a2SPavel Labath }
892b55c58a2SPavel Labath
TEST(Error,C_API)89300fb14daSLang Hames TEST(Error, C_API) {
89400fb14daSLang Hames EXPECT_THAT_ERROR(unwrap(wrap(Error::success())), Succeeded())
89500fb14daSLang Hames << "Failed to round-trip Error success value via C API";
89600fb14daSLang Hames EXPECT_THAT_ERROR(unwrap(wrap(make_error<CustomError>(0))),
89700fb14daSLang Hames Failed<CustomError>())
89800fb14daSLang Hames << "Failed to round-trip Error failure value via C API";
89900fb14daSLang Hames
90000fb14daSLang Hames auto Err =
90100fb14daSLang Hames wrap(make_error<StringError>("test message", inconvertibleErrorCode()));
90200fb14daSLang Hames EXPECT_EQ(LLVMGetErrorTypeId(Err), LLVMGetStringErrorTypeId())
90300fb14daSLang Hames << "Failed to match error type ids via C API";
90400fb14daSLang Hames char *ErrMsg = LLVMGetErrorMessage(Err);
90500fb14daSLang Hames EXPECT_STREQ(ErrMsg, "test message")
90600fb14daSLang Hames << "Failed to roundtrip StringError error message via C API";
90700fb14daSLang Hames LLVMDisposeErrorMessage(ErrMsg);
90800fb14daSLang Hames
90900fb14daSLang Hames bool GotCSE = false;
91000fb14daSLang Hames bool GotCE = false;
91100fb14daSLang Hames handleAllErrors(
91200fb14daSLang Hames unwrap(wrap(joinErrors(make_error<CustomSubError>(42, 7),
91300fb14daSLang Hames make_error<CustomError>(42)))),
91400fb14daSLang Hames [&](CustomSubError &CSE) {
91500fb14daSLang Hames GotCSE = true;
91600fb14daSLang Hames },
91700fb14daSLang Hames [&](CustomError &CE) {
91800fb14daSLang Hames GotCE = true;
91900fb14daSLang Hames });
92000fb14daSLang Hames EXPECT_TRUE(GotCSE) << "Failed to round-trip ErrorList via C API";
92100fb14daSLang Hames EXPECT_TRUE(GotCE) << "Failed to round-trip ErrorList via C API";
92200fb14daSLang Hames }
92300fb14daSLang Hames
TEST(Error,FileErrorTest)924e11f2217SAlexandre Ganea TEST(Error, FileErrorTest) {
925e11f2217SAlexandre Ganea #if !defined(NDEBUG) && GTEST_HAS_DEATH_TEST
926e11f2217SAlexandre Ganea EXPECT_DEATH(
927e11f2217SAlexandre Ganea {
928e11f2217SAlexandre Ganea Error S = Error::success();
929607a7be5SAlexandre Ganea consumeError(createFileError("file.bin", std::move(S)));
930e11f2217SAlexandre Ganea },
931e11f2217SAlexandre Ganea "");
932e11f2217SAlexandre Ganea #endif
93396032447SAlexandre Ganea // Not allowed, would fail at compile-time
93496032447SAlexandre Ganea //consumeError(createFileError("file.bin", ErrorSuccess()));
93596032447SAlexandre Ganea
936e11f2217SAlexandre Ganea Error E1 = make_error<CustomError>(1);
937e11f2217SAlexandre Ganea Error FE1 = createFileError("file.bin", std::move(E1));
938d18083c6SDavid Blaikie EXPECT_EQ(toString(std::move(FE1)), "'file.bin': CustomError {1}");
939e11f2217SAlexandre Ganea
940e11f2217SAlexandre Ganea Error E2 = make_error<CustomError>(2);
941e11f2217SAlexandre Ganea Error FE2 = createFileError("file.bin", std::move(E2));
942e11f2217SAlexandre Ganea handleAllErrors(std::move(FE2), [](const FileError &F) {
943d18083c6SDavid Blaikie EXPECT_EQ(F.message(), "'file.bin': CustomError {2}");
944e11f2217SAlexandre Ganea });
945e11f2217SAlexandre Ganea
946e11f2217SAlexandre Ganea Error E3 = make_error<CustomError>(3);
947e11f2217SAlexandre Ganea Error FE3 = createFileError("file.bin", std::move(E3));
948e11f2217SAlexandre Ganea auto E31 = handleErrors(std::move(FE3), [](std::unique_ptr<FileError> F) {
949e11f2217SAlexandre Ganea return F->takeError();
950e11f2217SAlexandre Ganea });
951e11f2217SAlexandre Ganea handleAllErrors(std::move(E31), [](const CustomError &C) {
952d18083c6SDavid Blaikie EXPECT_EQ(C.message(), "CustomError {3}");
953e11f2217SAlexandre Ganea });
954e11f2217SAlexandre Ganea
955e11f2217SAlexandre Ganea Error FE4 =
956e11f2217SAlexandre Ganea joinErrors(createFileError("file.bin", make_error<CustomError>(41)),
957e11f2217SAlexandre Ganea createFileError("file2.bin", make_error<CustomError>(42)));
958d18083c6SDavid Blaikie EXPECT_EQ(toString(std::move(FE4)), "'file.bin': CustomError {41}\n"
959d18083c6SDavid Blaikie "'file2.bin': CustomError {42}");
9600c502507SDavid Blaikie
961f03689acSDavid Blaikie Error FE5 = createFileError("", make_error<CustomError>(5));
962d18083c6SDavid Blaikie EXPECT_EQ(toString(std::move(FE5)), "'': CustomError {5}");
963f03689acSDavid Blaikie
964f03689acSDavid Blaikie Error FE6 = createFileError("unused", make_error<CustomError>(6));
965f03689acSDavid Blaikie handleAllErrors(std::move(FE6), [](std::unique_ptr<FileError> F) {
966f03689acSDavid Blaikie EXPECT_EQ(F->messageWithoutFileInfo(), "CustomError {6}");
967f03689acSDavid Blaikie });
968e11f2217SAlexandre Ganea }
969e11f2217SAlexandre Ganea
TEST(Error,FileErrorErrorCode)97079c54798SDuncan P. N. Exon Smith TEST(Error, FileErrorErrorCode) {
97179c54798SDuncan P. N. Exon Smith for (std::error_code EC : {
97279c54798SDuncan P. N. Exon Smith make_error_code(std::errc::not_supported),
97379c54798SDuncan P. N. Exon Smith make_error_code(std::errc::invalid_argument),
97479c54798SDuncan P. N. Exon Smith make_error_code(std::errc::no_such_file_or_directory),
97579c54798SDuncan P. N. Exon Smith }) {
97679c54798SDuncan P. N. Exon Smith EXPECT_EQ(EC, errorToErrorCode(
97779c54798SDuncan P. N. Exon Smith createFileError("file.bin", EC)));
97879c54798SDuncan P. N. Exon Smith EXPECT_EQ(EC, errorToErrorCode(
97979c54798SDuncan P. N. Exon Smith createFileError("file.bin", /*Line=*/5, EC)));
98079c54798SDuncan P. N. Exon Smith EXPECT_EQ(EC, errorToErrorCode(
98179c54798SDuncan P. N. Exon Smith createFileError("file.bin", errorCodeToError(EC))));
98279c54798SDuncan P. N. Exon Smith EXPECT_EQ(EC, errorToErrorCode(
98379c54798SDuncan P. N. Exon Smith createFileError("file.bin", /*Line=*/5, errorCodeToError(EC))));
98479c54798SDuncan P. N. Exon Smith }
98579c54798SDuncan P. N. Exon Smith
98679c54798SDuncan P. N. Exon Smith // inconvertibleErrorCode() should be wrapped to avoid a fatal error.
98779c54798SDuncan P. N. Exon Smith EXPECT_EQ(
98879c54798SDuncan P. N. Exon Smith "A file error occurred.",
98979c54798SDuncan P. N. Exon Smith errorToErrorCode(createFileError("file.bin", inconvertibleErrorCode()))
99079c54798SDuncan P. N. Exon Smith .message());
99179c54798SDuncan P. N. Exon Smith EXPECT_EQ(
99279c54798SDuncan P. N. Exon Smith "A file error occurred.",
99379c54798SDuncan P. N. Exon Smith errorToErrorCode(createFileError("file.bin", /*Line=*/5, inconvertibleErrorCode()))
99479c54798SDuncan P. N. Exon Smith .message());
99579c54798SDuncan P. N. Exon Smith }
99679c54798SDuncan P. N. Exon Smith
997e11f2217SAlexandre Ganea enum class test_error_code {
998e11f2217SAlexandre Ganea unspecified = 1,
999e11f2217SAlexandre Ganea error_1,
1000e11f2217SAlexandre Ganea error_2,
1001e11f2217SAlexandre Ganea };
1002e11f2217SAlexandre Ganea
1003f7f6d3e9SLang Hames } // end anon namespace
1004e11f2217SAlexandre Ganea
1005e11f2217SAlexandre Ganea namespace std {
1006e11f2217SAlexandre Ganea template <>
1007e11f2217SAlexandre Ganea struct is_error_code_enum<test_error_code> : std::true_type {};
1008e11f2217SAlexandre Ganea } // namespace std
1009e11f2217SAlexandre Ganea
1010e11f2217SAlexandre Ganea namespace {
1011e11f2217SAlexandre Ganea
1012e11f2217SAlexandre Ganea const std::error_category &TErrorCategory();
1013e11f2217SAlexandre Ganea
make_error_code(test_error_code E)1014e11f2217SAlexandre Ganea inline std::error_code make_error_code(test_error_code E) {
1015e11f2217SAlexandre Ganea return std::error_code(static_cast<int>(E), TErrorCategory());
1016e11f2217SAlexandre Ganea }
1017e11f2217SAlexandre Ganea
1018e11f2217SAlexandre Ganea class TestDebugError : public ErrorInfo<TestDebugError, StringError> {
1019e11f2217SAlexandre Ganea public:
1020e11f2217SAlexandre Ganea using ErrorInfo<TestDebugError, StringError >::ErrorInfo; // inherit constructors
TestDebugError(const Twine & S)1021e11f2217SAlexandre Ganea TestDebugError(const Twine &S) : ErrorInfo(S, test_error_code::unspecified) {}
1022e11f2217SAlexandre Ganea static char ID;
1023e11f2217SAlexandre Ganea };
1024e11f2217SAlexandre Ganea
1025e11f2217SAlexandre Ganea class TestErrorCategory : public std::error_category {
1026e11f2217SAlexandre Ganea public:
name() const10270d802a49SPavel Labath const char *name() const noexcept override { return "error"; }
message(int Condition) const1028e11f2217SAlexandre Ganea std::string message(int Condition) const override {
1029e11f2217SAlexandre Ganea switch (static_cast<test_error_code>(Condition)) {
1030e11f2217SAlexandre Ganea case test_error_code::unspecified:
1031e11f2217SAlexandre Ganea return "An unknown error has occurred.";
1032e11f2217SAlexandre Ganea case test_error_code::error_1:
1033e11f2217SAlexandre Ganea return "Error 1.";
1034e11f2217SAlexandre Ganea case test_error_code::error_2:
1035e11f2217SAlexandre Ganea return "Error 2.";
1036e11f2217SAlexandre Ganea }
1037e11f2217SAlexandre Ganea llvm_unreachable("Unrecognized test_error_code");
1038e11f2217SAlexandre Ganea }
1039e11f2217SAlexandre Ganea };
1040e11f2217SAlexandre Ganea
TErrorCategory()1041*ede60037SNicolai Hähnle const std::error_category &TErrorCategory() {
1042*ede60037SNicolai Hähnle static TestErrorCategory TestErrCategory;
1043*ede60037SNicolai Hähnle return TestErrCategory;
1044*ede60037SNicolai Hähnle }
1045e11f2217SAlexandre Ganea
1046e11f2217SAlexandre Ganea char TestDebugError::ID;
1047e11f2217SAlexandre Ganea
TEST(Error,SubtypeStringErrorTest)1048e11f2217SAlexandre Ganea TEST(Error, SubtypeStringErrorTest) {
1049e11f2217SAlexandre Ganea auto E1 = make_error<TestDebugError>(test_error_code::error_1);
1050d18083c6SDavid Blaikie EXPECT_EQ(toString(std::move(E1)), "Error 1.");
1051e11f2217SAlexandre Ganea
1052e11f2217SAlexandre Ganea auto E2 = make_error<TestDebugError>(test_error_code::error_1,
1053e11f2217SAlexandre Ganea "Detailed information");
1054d18083c6SDavid Blaikie EXPECT_EQ(toString(std::move(E2)), "Error 1. Detailed information");
1055e11f2217SAlexandre Ganea
1056e11f2217SAlexandre Ganea auto E3 = make_error<TestDebugError>(test_error_code::error_2);
1057e11f2217SAlexandre Ganea handleAllErrors(std::move(E3), [](const TestDebugError &F) {
1058d18083c6SDavid Blaikie EXPECT_EQ(F.message(), "Error 2.");
1059e11f2217SAlexandre Ganea });
1060e11f2217SAlexandre Ganea
1061e11f2217SAlexandre Ganea auto E4 = joinErrors(make_error<TestDebugError>(test_error_code::error_1,
1062e11f2217SAlexandre Ganea "Detailed information"),
1063e11f2217SAlexandre Ganea make_error<TestDebugError>(test_error_code::error_2));
1064d18083c6SDavid Blaikie EXPECT_EQ(toString(std::move(E4)), "Error 1. Detailed information\n"
1065d18083c6SDavid Blaikie "Error 2.");
1066e11f2217SAlexandre Ganea }
1067e11f2217SAlexandre Ganea
createAnyError()106827181cadSDuncan P. N. Exon Smith static Error createAnyError() {
106927181cadSDuncan P. N. Exon Smith return errorCodeToError(test_error_code::unspecified);
107027181cadSDuncan P. N. Exon Smith }
107127181cadSDuncan P. N. Exon Smith
107227181cadSDuncan P. N. Exon Smith struct MoveOnlyBox {
107327181cadSDuncan P. N. Exon Smith Optional<int> Box;
107427181cadSDuncan P. N. Exon Smith
MoveOnlyBox__anonad7eff122b11::MoveOnlyBox107527181cadSDuncan P. N. Exon Smith explicit MoveOnlyBox(int I) : Box(I) {}
107627181cadSDuncan P. N. Exon Smith MoveOnlyBox() = default;
107727181cadSDuncan P. N. Exon Smith MoveOnlyBox(MoveOnlyBox &&) = default;
107827181cadSDuncan P. N. Exon Smith MoveOnlyBox &operator=(MoveOnlyBox &&) = default;
107927181cadSDuncan P. N. Exon Smith
108027181cadSDuncan P. N. Exon Smith MoveOnlyBox(const MoveOnlyBox &) = delete;
108127181cadSDuncan P. N. Exon Smith MoveOnlyBox &operator=(const MoveOnlyBox &) = delete;
108227181cadSDuncan P. N. Exon Smith
operator ==__anonad7eff122b11::MoveOnlyBox108327181cadSDuncan P. N. Exon Smith bool operator==(const MoveOnlyBox &RHS) const {
108427181cadSDuncan P. N. Exon Smith if (bool(Box) != bool(RHS.Box))
108527181cadSDuncan P. N. Exon Smith return false;
108627181cadSDuncan P. N. Exon Smith return Box ? *Box == *RHS.Box : false;
108727181cadSDuncan P. N. Exon Smith }
108827181cadSDuncan P. N. Exon Smith };
108927181cadSDuncan P. N. Exon Smith
TEST(Error,moveInto)109027181cadSDuncan P. N. Exon Smith TEST(Error, moveInto) {
109127181cadSDuncan P. N. Exon Smith // Use MoveOnlyBox as the T in Expected<T>.
109227181cadSDuncan P. N. Exon Smith auto make = [](int I) -> Expected<MoveOnlyBox> { return MoveOnlyBox(I); };
109327181cadSDuncan P. N. Exon Smith auto makeFailure = []() -> Expected<MoveOnlyBox> { return createAnyError(); };
109427181cadSDuncan P. N. Exon Smith
109527181cadSDuncan P. N. Exon Smith {
109627181cadSDuncan P. N. Exon Smith MoveOnlyBox V;
109727181cadSDuncan P. N. Exon Smith
109827181cadSDuncan P. N. Exon Smith // Failure with no prior value.
109927181cadSDuncan P. N. Exon Smith EXPECT_THAT_ERROR(makeFailure().moveInto(V), Failed());
110027181cadSDuncan P. N. Exon Smith EXPECT_EQ(None, V.Box);
110127181cadSDuncan P. N. Exon Smith
110227181cadSDuncan P. N. Exon Smith // Success with no prior value.
110327181cadSDuncan P. N. Exon Smith EXPECT_THAT_ERROR(make(5).moveInto(V), Succeeded());
110427181cadSDuncan P. N. Exon Smith EXPECT_EQ(5, V.Box);
110527181cadSDuncan P. N. Exon Smith
110627181cadSDuncan P. N. Exon Smith // Success with an existing value.
110727181cadSDuncan P. N. Exon Smith EXPECT_THAT_ERROR(make(7).moveInto(V), Succeeded());
110827181cadSDuncan P. N. Exon Smith EXPECT_EQ(7, V.Box);
110927181cadSDuncan P. N. Exon Smith
111027181cadSDuncan P. N. Exon Smith // Failure with an existing value. Might be nice to assign a
111127181cadSDuncan P. N. Exon Smith // default-constructed value in this case, but for now it's being left
111227181cadSDuncan P. N. Exon Smith // alone.
111327181cadSDuncan P. N. Exon Smith EXPECT_THAT_ERROR(makeFailure().moveInto(V), Failed());
111427181cadSDuncan P. N. Exon Smith EXPECT_EQ(7, V.Box);
111527181cadSDuncan P. N. Exon Smith }
111627181cadSDuncan P. N. Exon Smith
111727181cadSDuncan P. N. Exon Smith // Check that this works with optionals too.
111827181cadSDuncan P. N. Exon Smith {
111927181cadSDuncan P. N. Exon Smith // Same cases as above.
112027181cadSDuncan P. N. Exon Smith Optional<MoveOnlyBox> MaybeV;
112127181cadSDuncan P. N. Exon Smith EXPECT_THAT_ERROR(makeFailure().moveInto(MaybeV), Failed());
112227181cadSDuncan P. N. Exon Smith EXPECT_EQ(None, MaybeV);
112327181cadSDuncan P. N. Exon Smith
112427181cadSDuncan P. N. Exon Smith EXPECT_THAT_ERROR(make(5).moveInto(MaybeV), Succeeded());
112527181cadSDuncan P. N. Exon Smith EXPECT_EQ(MoveOnlyBox(5), MaybeV);
112627181cadSDuncan P. N. Exon Smith
112727181cadSDuncan P. N. Exon Smith EXPECT_THAT_ERROR(make(7).moveInto(MaybeV), Succeeded());
112827181cadSDuncan P. N. Exon Smith EXPECT_EQ(MoveOnlyBox(7), MaybeV);
112927181cadSDuncan P. N. Exon Smith
113027181cadSDuncan P. N. Exon Smith EXPECT_THAT_ERROR(makeFailure().moveInto(MaybeV), Failed());
113127181cadSDuncan P. N. Exon Smith EXPECT_EQ(MoveOnlyBox(7), MaybeV);
113227181cadSDuncan P. N. Exon Smith }
113327181cadSDuncan P. N. Exon Smith }
113427181cadSDuncan P. N. Exon Smith
1135e11f2217SAlexandre Ganea } // namespace
1136