blob: d5d799384f4729b77747eb710564ba0a6636e724 [file] [log] [blame]
Lang Hamesf7f6d3e2016-03-16 01:02:46 +00001//===----- unittests/ErrorTest.cpp - Error.h tests ------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "llvm/Support/Error.h"
Lang Hamesc5e0bbd2016-05-27 01:37:32 +000011
12#include "llvm/ADT/Twine.h"
Lang Hamesf7f6d3e2016-03-16 01:02:46 +000013#include "llvm/Support/Errc.h"
Lang Hamese7aad352016-03-23 23:57:28 +000014#include "llvm/Support/ErrorHandling.h"
Lang Hamesf7f6d3e2016-03-16 01:02:46 +000015#include "gtest/gtest.h"
16#include <memory>
17
18using namespace llvm;
19
20namespace {
21
Lang Hamesf7f6d3e2016-03-16 01:02:46 +000022// Custom error class with a default base class and some random 'info' attached.
23class CustomError : public ErrorInfo<CustomError> {
24public:
25 // Create an error with some info attached.
26 CustomError(int Info) : Info(Info) {}
27
28 // Get the info attached to this error.
29 int getInfo() const { return Info; }
30
31 // Log this error to a stream.
32 void log(raw_ostream &OS) const override {
33 OS << "CustomError { " << getInfo() << "}";
34 }
35
Lang Hamese7aad352016-03-23 23:57:28 +000036 std::error_code convertToErrorCode() const override {
37 llvm_unreachable("CustomError doesn't support ECError conversion");
38 }
39
Reid Klecknera15b76b2016-03-24 23:49:34 +000040 // Used by ErrorInfo::classID.
41 static char ID;
42
Lang Hamesf7f6d3e2016-03-16 01:02:46 +000043protected:
44 // This error is subclassed below, but we can't use inheriting constructors
45 // yet, so we can't propagate the constructors through ErrorInfo. Instead
46 // we have to have a default constructor and have the subclass initialize all
47 // fields.
48 CustomError() : Info(0) {}
49
50 int Info;
51};
52
Reid Klecknera15b76b2016-03-24 23:49:34 +000053char CustomError::ID = 0;
54
Lang Hamesf7f6d3e2016-03-16 01:02:46 +000055// Custom error class with a custom base class and some additional random
56// 'info'.
57class CustomSubError : public ErrorInfo<CustomSubError, CustomError> {
58public:
59 // Create a sub-error with some info attached.
60 CustomSubError(int Info, int ExtraInfo) : ExtraInfo(ExtraInfo) {
61 this->Info = Info;
62 }
63
64 // Get the extra info attached to this error.
65 int getExtraInfo() const { return ExtraInfo; }
66
67 // Log this error to a stream.
68 void log(raw_ostream &OS) const override {
69 OS << "CustomSubError { " << getInfo() << ", " << getExtraInfo() << "}";
70 }
71
Lang Hamese7aad352016-03-23 23:57:28 +000072 std::error_code convertToErrorCode() const override {
73 llvm_unreachable("CustomSubError doesn't support ECError conversion");
74 }
75
Reid Klecknera15b76b2016-03-24 23:49:34 +000076 // Used by ErrorInfo::classID.
77 static char ID;
78
Lang Hamesf7f6d3e2016-03-16 01:02:46 +000079protected:
80 int ExtraInfo;
81};
82
Reid Klecknera15b76b2016-03-24 23:49:34 +000083char CustomSubError::ID = 0;
84
Lang Hamesf7f6d3e2016-03-16 01:02:46 +000085static Error handleCustomError(const CustomError &CE) { return Error(); }
86
87static void handleCustomErrorVoid(const CustomError &CE) {}
88
89static Error handleCustomErrorUP(std::unique_ptr<CustomError> CE) {
90 return Error();
91}
92
93static void handleCustomErrorUPVoid(std::unique_ptr<CustomError> CE) {}
94
Lang Hames01864a22016-03-18 00:12:37 +000095// Test that success values implicitly convert to false, and don't cause crashes
96// once they've been implicitly converted.
97TEST(Error, CheckedSuccess) {
98 Error E;
99 EXPECT_FALSE(E) << "Unexpected error while testing Error 'Success'";
100}
101
102// Test that unchecked succes values cause an abort.
103#ifndef NDEBUG
104TEST(Error, UncheckedSuccess) {
105 EXPECT_DEATH({ Error E; }, "Program aborted due to an unhandled Error:")
106 << "Unchecked Error Succes value did not cause abort()";
107}
108#endif
109
Lang Hamesd1af8fc2016-03-25 23:54:32 +0000110// ErrorAsOutParameter tester.
111void errAsOutParamHelper(Error &Err) {
112 ErrorAsOutParameter ErrAsOutParam(Err);
113 // Verify that checked flag is raised - assignment should not crash.
114 Err = Error::success();
115 // Raise the checked bit manually - caller should still have to test the
116 // error.
117 (void)!!Err;
Lang Hamesd0ac31a2016-03-25 21:56:35 +0000118}
119
Lang Hamesd1af8fc2016-03-25 23:54:32 +0000120// Test that ErrorAsOutParameter sets the checked flag on construction.
121TEST(Error, ErrorAsOutParameterChecked) {
122 Error E;
123 errAsOutParamHelper(E);
124 (void)!!E;
125}
126
127// Test that ErrorAsOutParameter clears the checked flag on destruction.
128#ifndef NDEBUG
129TEST(Error, ErrorAsOutParameterUnchecked) {
130 EXPECT_DEATH({ Error E; errAsOutParamHelper(E); },
131 "Program aborted due to an unhandled Error:")
132 << "ErrorAsOutParameter did not clear the checked flag on destruction.";
133}
134#endif
135
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000136// Check that we abort on unhandled failure cases. (Force conversion to bool
137// to make sure that we don't accidentally treat checked errors as handled).
138// Test runs in debug mode only.
139#ifndef NDEBUG
Lang Hames01864a22016-03-18 00:12:37 +0000140TEST(Error, UncheckedError) {
141 auto DropUnhandledError = []() {
142 Error E = make_error<CustomError>(42);
143 (void)!E;
144 };
145 EXPECT_DEATH(DropUnhandledError(),
146 "Program aborted due to an unhandled Error:")
147 << "Unhandled Error failure value did not cause abort()";
148}
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000149#endif
150
Lang Hames01864a22016-03-18 00:12:37 +0000151// Check 'Error::isA<T>' method handling.
152TEST(Error, IsAHandling) {
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000153 // Check 'isA' handling.
Lang Hames01864a22016-03-18 00:12:37 +0000154 Error E = make_error<CustomError>(1);
155 Error F = make_error<CustomSubError>(1, 2);
156 Error G = Error::success();
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000157
Lang Hames01864a22016-03-18 00:12:37 +0000158 EXPECT_TRUE(E.isA<CustomError>());
159 EXPECT_FALSE(E.isA<CustomSubError>());
160 EXPECT_TRUE(F.isA<CustomError>());
161 EXPECT_TRUE(F.isA<CustomSubError>());
162 EXPECT_FALSE(G.isA<CustomError>());
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000163
Lang Hames01864a22016-03-18 00:12:37 +0000164 consumeError(std::move(E));
165 consumeError(std::move(F));
166 consumeError(std::move(G));
167}
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000168
Lang Hames01864a22016-03-18 00:12:37 +0000169// Check that we can handle a custom error.
170TEST(Error, HandleCustomError) {
171 int CaughtErrorInfo = 0;
172 handleAllErrors(make_error<CustomError>(42), [&](const CustomError &CE) {
173 CaughtErrorInfo = CE.getInfo();
174 });
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000175
Lang Hames01864a22016-03-18 00:12:37 +0000176 EXPECT_TRUE(CaughtErrorInfo == 42) << "Wrong result from CustomError handler";
177}
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000178
Lang Hames01864a22016-03-18 00:12:37 +0000179// Check that handler type deduction also works for handlers
180// of the following types:
181// void (const Err&)
182// Error (const Err&) mutable
183// void (const Err&) mutable
184// Error (Err&)
185// void (Err&)
186// Error (Err&) mutable
187// void (Err&) mutable
188// Error (unique_ptr<Err>)
189// void (unique_ptr<Err>)
190// Error (unique_ptr<Err>) mutable
191// void (unique_ptr<Err>) mutable
192TEST(Error, HandlerTypeDeduction) {
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000193
194 handleAllErrors(make_error<CustomError>(42), [](const CustomError &CE) {});
195
196 handleAllErrors(
197 make_error<CustomError>(42),
198 [](const CustomError &CE) mutable { return Error::success(); });
199
200 handleAllErrors(make_error<CustomError>(42),
201 [](const CustomError &CE) mutable {});
202
203 handleAllErrors(make_error<CustomError>(42),
204 [](CustomError &CE) { return Error::success(); });
205
206 handleAllErrors(make_error<CustomError>(42), [](CustomError &CE) {});
207
208 handleAllErrors(make_error<CustomError>(42),
209 [](CustomError &CE) mutable { return Error::success(); });
210
211 handleAllErrors(make_error<CustomError>(42), [](CustomError &CE) mutable {});
212
213 handleAllErrors(
214 make_error<CustomError>(42),
215 [](std::unique_ptr<CustomError> CE) { return Error::success(); });
216
217 handleAllErrors(make_error<CustomError>(42),
218 [](std::unique_ptr<CustomError> CE) {});
219
220 handleAllErrors(
221 make_error<CustomError>(42),
222 [](std::unique_ptr<CustomError> CE) mutable { return Error::success(); });
223
224 handleAllErrors(make_error<CustomError>(42),
225 [](std::unique_ptr<CustomError> CE) mutable {});
226
227 // Check that named handlers of type 'Error (const Err&)' work.
228 handleAllErrors(make_error<CustomError>(42), handleCustomError);
229
230 // Check that named handlers of type 'void (const Err&)' work.
231 handleAllErrors(make_error<CustomError>(42), handleCustomErrorVoid);
232
233 // Check that named handlers of type 'Error (std::unique_ptr<Err>)' work.
234 handleAllErrors(make_error<CustomError>(42), handleCustomErrorUP);
235
236 // Check that named handlers of type 'Error (std::unique_ptr<Err>)' work.
237 handleAllErrors(make_error<CustomError>(42), handleCustomErrorUPVoid);
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000238}
239
Lang Hames01864a22016-03-18 00:12:37 +0000240// Test that we can handle errors with custom base classes.
241TEST(Error, HandleCustomErrorWithCustomBaseClass) {
242 int CaughtErrorInfo = 0;
243 int CaughtErrorExtraInfo = 0;
244 handleAllErrors(make_error<CustomSubError>(42, 7),
245 [&](const CustomSubError &SE) {
246 CaughtErrorInfo = SE.getInfo();
247 CaughtErrorExtraInfo = SE.getExtraInfo();
248 });
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000249
Lang Hames01864a22016-03-18 00:12:37 +0000250 EXPECT_TRUE(CaughtErrorInfo == 42 && CaughtErrorExtraInfo == 7)
251 << "Wrong result from CustomSubError handler";
252}
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000253
Lang Hames01864a22016-03-18 00:12:37 +0000254// Check that we trigger only the first handler that applies.
255TEST(Error, FirstHandlerOnly) {
256 int DummyInfo = 0;
257 int CaughtErrorInfo = 0;
258 int CaughtErrorExtraInfo = 0;
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000259
Lang Hames01864a22016-03-18 00:12:37 +0000260 handleAllErrors(make_error<CustomSubError>(42, 7),
261 [&](const CustomSubError &SE) {
262 CaughtErrorInfo = SE.getInfo();
263 CaughtErrorExtraInfo = SE.getExtraInfo();
264 },
265 [&](const CustomError &CE) { DummyInfo = CE.getInfo(); });
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000266
Lang Hames01864a22016-03-18 00:12:37 +0000267 EXPECT_TRUE(CaughtErrorInfo == 42 && CaughtErrorExtraInfo == 7 &&
268 DummyInfo == 0)
269 << "Activated the wrong Error handler(s)";
270}
271
272// Check that general handlers shadow specific ones.
273TEST(Error, HandlerShadowing) {
274 int CaughtErrorInfo = 0;
275 int DummyInfo = 0;
276 int DummyExtraInfo = 0;
277
278 handleAllErrors(
279 make_error<CustomSubError>(42, 7),
280 [&](const CustomError &CE) { CaughtErrorInfo = CE.getInfo(); },
281 [&](const CustomSubError &SE) {
282 DummyInfo = SE.getInfo();
283 DummyExtraInfo = SE.getExtraInfo();
284 });
285
NAKAMURA Takumib2cef642016-03-24 15:19:22 +0000286 EXPECT_TRUE(CaughtErrorInfo == 42 && DummyInfo == 0 && DummyExtraInfo == 0)
Lang Hames01864a22016-03-18 00:12:37 +0000287 << "General Error handler did not shadow specific handler";
288}
289
290// Test joinErrors.
291TEST(Error, CheckJoinErrors) {
292 int CustomErrorInfo1 = 0;
293 int CustomErrorInfo2 = 0;
294 int CustomErrorExtraInfo = 0;
295 Error E =
296 joinErrors(make_error<CustomError>(7), make_error<CustomSubError>(42, 7));
297
298 handleAllErrors(std::move(E),
299 [&](const CustomSubError &SE) {
300 CustomErrorInfo2 = SE.getInfo();
301 CustomErrorExtraInfo = SE.getExtraInfo();
302 },
303 [&](const CustomError &CE) {
304 // Assert that the CustomError instance above is handled
305 // before the
306 // CustomSubError - joinErrors should preserve error
307 // ordering.
308 EXPECT_EQ(CustomErrorInfo2, 0)
309 << "CustomErrorInfo2 should be 0 here. "
310 "joinErrors failed to preserve ordering.\n";
311 CustomErrorInfo1 = CE.getInfo();
312 });
313
314 EXPECT_TRUE(CustomErrorInfo1 == 7 && CustomErrorInfo2 == 42 &&
315 CustomErrorExtraInfo == 7)
316 << "Failed handling compound Error.";
317}
318
319// Test that we can consume success values.
320TEST(Error, ConsumeSuccess) {
321 Error E;
322 consumeError(std::move(E));
323}
324
325TEST(Error, ConsumeError) {
326 Error E = make_error<CustomError>(7);
327 consumeError(std::move(E));
328}
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000329
330// Test that handleAllUnhandledErrors crashes if an error is not caught.
331// Test runs in debug mode only.
332#ifndef NDEBUG
Lang Hames01864a22016-03-18 00:12:37 +0000333TEST(Error, FailureToHandle) {
334 auto FailToHandle = []() {
335 handleAllErrors(make_error<CustomError>(7), [&](const CustomSubError &SE) {
336 errs() << "This should never be called";
337 exit(1);
338 });
339 };
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000340
Lang Hames01864a22016-03-18 00:12:37 +0000341 EXPECT_DEATH(FailToHandle(), "Program aborted due to an unhandled Error:")
342 << "Unhandled Error in handleAllErrors call did not cause an "
343 "abort()";
344}
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000345#endif
346
347// Test that handleAllUnhandledErrors crashes if an error is returned from a
348// handler.
349// Test runs in debug mode only.
350#ifndef NDEBUG
Lang Hames01864a22016-03-18 00:12:37 +0000351TEST(Error, FailureFromHandler) {
352 auto ReturnErrorFromHandler = []() {
353 handleAllErrors(make_error<CustomError>(7),
354 [&](std::unique_ptr<CustomSubError> SE) {
355 return Error(std::move(SE));
356 });
357 };
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000358
Lang Hames01864a22016-03-18 00:12:37 +0000359 EXPECT_DEATH(ReturnErrorFromHandler(),
360 "Program aborted due to an unhandled Error:")
361 << " Error returned from handler in handleAllErrors call did not "
362 "cause abort()";
363}
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000364#endif
365
Lang Hames01864a22016-03-18 00:12:37 +0000366// Test that we can return values from handleErrors.
367TEST(Error, CatchErrorFromHandler) {
368 int ErrorInfo = 0;
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000369
Lang Hames01864a22016-03-18 00:12:37 +0000370 Error E = handleErrors(
371 make_error<CustomError>(7),
372 [&](std::unique_ptr<CustomError> CE) { return Error(std::move(CE)); });
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000373
Lang Hames01864a22016-03-18 00:12:37 +0000374 handleAllErrors(std::move(E),
375 [&](const CustomError &CE) { ErrorInfo = CE.getInfo(); });
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000376
Lang Hames01864a22016-03-18 00:12:37 +0000377 EXPECT_EQ(ErrorInfo, 7)
378 << "Failed to handle Error returned from handleErrors.";
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000379}
380
Lang Hamesc5e0bbd2016-05-27 01:37:32 +0000381TEST(Error, StringError) {
382 std::string Msg;
383 raw_string_ostream S(Msg);
384 logAllUnhandledErrors(make_error<StringError>("foo" + Twine(42),
Lang Hamesbd8e9542016-05-27 01:54:25 +0000385 inconvertibleErrorCode()),
Lang Hamesc5e0bbd2016-05-27 01:37:32 +0000386 S, "");
387 EXPECT_EQ(S.str(), "foo42\n") << "Unexpected StringError log result";
388
389 auto EC =
390 errorToErrorCode(make_error<StringError>("", errc::invalid_argument));
391 EXPECT_EQ(EC, errc::invalid_argument)
392 << "Failed to convert StringError to error_code.";
393}
394
Lang Hames01864a22016-03-18 00:12:37 +0000395// Test that the ExitOnError utility works as expected.
396TEST(Error, ExitOnError) {
397 ExitOnError ExitOnErr;
398 ExitOnErr.setBanner("Error in tool:");
399 ExitOnErr.setExitCodeMapper([](const Error &E) {
400 if (E.isA<CustomSubError>())
401 return 2;
402 return 1;
403 });
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000404
Lang Hames01864a22016-03-18 00:12:37 +0000405 // Make sure we don't bail on success.
406 ExitOnErr(Error::success());
407 EXPECT_EQ(ExitOnErr(Expected<int>(7)), 7)
408 << "exitOnError returned an invalid value for Expected";
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000409
Lang Hames285639f2016-04-25 19:21:57 +0000410 int A = 7;
411 int &B = ExitOnErr(Expected<int&>(A));
412 EXPECT_EQ(&A, &B) << "ExitOnError failed to propagate reference";
413
Lang Hames01864a22016-03-18 00:12:37 +0000414 // Exit tests.
415 EXPECT_EXIT(ExitOnErr(make_error<CustomError>(7)),
416 ::testing::ExitedWithCode(1), "Error in tool:")
417 << "exitOnError returned an unexpected error result";
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000418
Lang Hames01864a22016-03-18 00:12:37 +0000419 EXPECT_EXIT(ExitOnErr(Expected<int>(make_error<CustomSubError>(0, 0))),
420 ::testing::ExitedWithCode(2), "Error in tool:")
421 << "exitOnError returned an unexpected error result";
422}
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000423
Lang Hames580ca232016-04-05 19:57:03 +0000424// Test Checked Expected<T> in success mode.
425TEST(Error, CheckedExpectedInSuccessMode) {
Lang Hames01864a22016-03-18 00:12:37 +0000426 Expected<int> A = 7;
427 EXPECT_TRUE(!!A) << "Expected with non-error value doesn't convert to 'true'";
Lang Hames580ca232016-04-05 19:57:03 +0000428 // Access is safe in second test, since we checked the error in the first.
Lang Hames01864a22016-03-18 00:12:37 +0000429 EXPECT_EQ(*A, 7) << "Incorrect Expected non-error value";
430}
431
Lang Hames285639f2016-04-25 19:21:57 +0000432// Test Expected with reference type.
433TEST(Error, ExpectedWithReferenceType) {
434 int A = 7;
435 Expected<int&> B = A;
436 // 'Check' B.
437 (void)!!B;
438 int &C = *B;
439 EXPECT_EQ(&A, &C) << "Expected failed to propagate reference";
440}
441
Lang Hames580ca232016-04-05 19:57:03 +0000442// Test Unchecked Expected<T> in success mode.
443// We expect this to blow up the same way Error would.
444// Test runs in debug mode only.
445#ifndef NDEBUG
446TEST(Error, UncheckedExpectedInSuccessModeDestruction) {
447 EXPECT_DEATH({ Expected<int> A = 7; },
448 "Expected<T> must be checked before access or destruction.")
449 << "Unchecekd Expected<T> success value did not cause an abort().";
450}
451#endif
452
453// Test Unchecked Expected<T> in success mode.
454// We expect this to blow up the same way Error would.
455// Test runs in debug mode only.
456#ifndef NDEBUG
457TEST(Error, UncheckedExpectedInSuccessModeAccess) {
458 EXPECT_DEATH({ Expected<int> A = 7; *A; },
459 "Expected<T> must be checked before access or destruction.")
460 << "Unchecekd Expected<T> success value did not cause an abort().";
461}
462#endif
463
464// Test Unchecked Expected<T> in success mode.
465// We expect this to blow up the same way Error would.
466// Test runs in debug mode only.
467#ifndef NDEBUG
468TEST(Error, UncheckedExpectedInSuccessModeAssignment) {
469 EXPECT_DEATH({ Expected<int> A = 7; A = 7; },
470 "Expected<T> must be checked before access or destruction.")
471 << "Unchecekd Expected<T> success value did not cause an abort().";
472}
473#endif
474
Lang Hames01864a22016-03-18 00:12:37 +0000475// Test Expected<T> in failure mode.
476TEST(Error, ExpectedInFailureMode) {
477 Expected<int> A = make_error<CustomError>(42);
478 EXPECT_FALSE(!!A) << "Expected with error value doesn't convert to 'false'";
479 Error E = A.takeError();
480 EXPECT_TRUE(E.isA<CustomError>()) << "Incorrect Expected error value";
481 consumeError(std::move(E));
482}
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000483
484// Check that an Expected instance with an error value doesn't allow access to
485// operator*.
486// Test runs in debug mode only.
487#ifndef NDEBUG
Lang Hames01864a22016-03-18 00:12:37 +0000488TEST(Error, AccessExpectedInFailureMode) {
489 Expected<int> A = make_error<CustomError>(42);
Lang Hames580ca232016-04-05 19:57:03 +0000490 EXPECT_DEATH(*A, "Expected<T> must be checked before access or destruction.")
Lang Hames01864a22016-03-18 00:12:37 +0000491 << "Incorrect Expected error value";
492 consumeError(A.takeError());
493}
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000494#endif
495
496// Check that an Expected instance with an error triggers an abort if
497// unhandled.
498// Test runs in debug mode only.
499#ifndef NDEBUG
Lang Hames01864a22016-03-18 00:12:37 +0000500TEST(Error, UnhandledExpectedInFailureMode) {
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000501 EXPECT_DEATH({ Expected<int> A = make_error<CustomError>(42); },
Lang Hames580ca232016-04-05 19:57:03 +0000502 "Expected<T> must be checked before access or destruction.")
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000503 << "Unchecked Expected<T> failure value did not cause an abort()";
Lang Hames01864a22016-03-18 00:12:37 +0000504}
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000505#endif
506
Lang Hames01864a22016-03-18 00:12:37 +0000507// Test covariance of Expected.
508TEST(Error, ExpectedCovariance) {
509 class B {};
510 class D : public B {};
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000511
Lang Hames01864a22016-03-18 00:12:37 +0000512 Expected<B *> A1(Expected<D *>(nullptr));
Lang Hames580ca232016-04-05 19:57:03 +0000513 // Check A1 by converting to bool before assigning to it.
514 (void)!!A1;
Lang Hames01864a22016-03-18 00:12:37 +0000515 A1 = Expected<D *>(nullptr);
Lang Hames580ca232016-04-05 19:57:03 +0000516 // Check A1 again before destruction.
517 (void)!!A1;
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000518
Lang Hames01864a22016-03-18 00:12:37 +0000519 Expected<std::unique_ptr<B>> A2(Expected<std::unique_ptr<D>>(nullptr));
Lang Hames580ca232016-04-05 19:57:03 +0000520 // Check A2 by converting to bool before assigning to it.
521 (void)!!A2;
Lang Hames01864a22016-03-18 00:12:37 +0000522 A2 = Expected<std::unique_ptr<D>>(nullptr);
Lang Hames580ca232016-04-05 19:57:03 +0000523 // Check A2 again before destruction.
524 (void)!!A2;
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000525}
526
Lang Hamesd21a5352016-03-24 02:00:10 +0000527TEST(Error, ErrorCodeConversions) {
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000528 // Round-trip a success value to check that it converts correctly.
529 EXPECT_EQ(errorToErrorCode(errorCodeToError(std::error_code())),
530 std::error_code())
531 << "std::error_code() should round-trip via Error conversions";
532
533 // Round-trip an error value to check that it converts correctly.
534 EXPECT_EQ(errorToErrorCode(errorCodeToError(errc::invalid_argument)),
535 errc::invalid_argument)
536 << "std::error_code error value should round-trip via Error "
537 "conversions";
Lang Hamesd21a5352016-03-24 02:00:10 +0000538
539 // Round-trip a success value through ErrorOr/Expected to check that it
540 // converts correctly.
541 {
542 auto Orig = ErrorOr<int>(42);
543 auto RoundTripped =
544 expectedToErrorOr(errorOrToExpected(ErrorOr<int>(42)));
545 EXPECT_EQ(*Orig, *RoundTripped)
546 << "ErrorOr<T> success value should round-trip via Expected<T> "
547 "conversions.";
548 }
549
550 // Round-trip a failure value through ErrorOr/Expected to check that it
551 // converts correctly.
552 {
553 auto Orig = ErrorOr<int>(errc::invalid_argument);
554 auto RoundTripped =
555 expectedToErrorOr(
556 errorOrToExpected(ErrorOr<int>(errc::invalid_argument)));
557 EXPECT_EQ(Orig.getError(), RoundTripped.getError())
558 << "ErrorOr<T> failure value should round-trip via Expected<T> "
559 "conversions.";
560 }
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000561}
562
Vedant Kumar27370a02016-05-03 23:32:31 +0000563// Test that error messages work.
564TEST(Error, ErrorMessage) {
565 EXPECT_EQ(toString(Error::success()).compare(""), 0);
566
567 Error E1 = make_error<CustomError>(0);
568 EXPECT_EQ(toString(std::move(E1)).compare("CustomError { 0}"), 0);
569
570 Error E2 = make_error<CustomError>(0);
571 handleAllErrors(std::move(E2), [](const CustomError &CE) {
572 EXPECT_EQ(CE.message().compare("CustomError { 0}"), 0);
573 });
574
575 Error E3 = joinErrors(make_error<CustomError>(0), make_error<CustomError>(1));
576 EXPECT_EQ(toString(std::move(E3))
577 .compare("CustomError { 0}\n"
578 "CustomError { 1}"),
579 0);
580}
581
Lang Hamesf7f6d3e2016-03-16 01:02:46 +0000582} // end anon namespace