ErrorTest.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757
  1. //===----- unittests/ErrorTest.cpp - Error.h tests ------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. #include "llvm/Support/Error.h"
  10. #include "llvm/ADT/Twine.h"
  11. #include "llvm/Support/Errc.h"
  12. #include "llvm/Support/ErrorHandling.h"
  13. #include "llvm/Testing/Support/Error.h"
  14. #include "gtest/gtest-spi.h"
  15. #include "gtest/gtest.h"
  16. #include <memory>
  17. using namespace llvm;
  18. namespace {
  19. // Custom error class with a default base class and some random 'info' attached.
  20. class CustomError : public ErrorInfo<CustomError> {
  21. public:
  22. // Create an error with some info attached.
  23. CustomError(int Info) : Info(Info) {}
  24. // Get the info attached to this error.
  25. int getInfo() const { return Info; }
  26. // Log this error to a stream.
  27. void log(raw_ostream &OS) const override {
  28. OS << "CustomError { " << getInfo() << "}";
  29. }
  30. std::error_code convertToErrorCode() const override {
  31. llvm_unreachable("CustomError doesn't support ECError conversion");
  32. }
  33. // Used by ErrorInfo::classID.
  34. static char ID;
  35. protected:
  36. // This error is subclassed below, but we can't use inheriting constructors
  37. // yet, so we can't propagate the constructors through ErrorInfo. Instead
  38. // we have to have a default constructor and have the subclass initialize all
  39. // fields.
  40. CustomError() : Info(0) {}
  41. int Info;
  42. };
  43. char CustomError::ID = 0;
  44. // Custom error class with a custom base class and some additional random
  45. // 'info'.
  46. class CustomSubError : public ErrorInfo<CustomSubError, CustomError> {
  47. public:
  48. // Create a sub-error with some info attached.
  49. CustomSubError(int Info, int ExtraInfo) : ExtraInfo(ExtraInfo) {
  50. this->Info = Info;
  51. }
  52. // Get the extra info attached to this error.
  53. int getExtraInfo() const { return ExtraInfo; }
  54. // Log this error to a stream.
  55. void log(raw_ostream &OS) const override {
  56. OS << "CustomSubError { " << getInfo() << ", " << getExtraInfo() << "}";
  57. }
  58. std::error_code convertToErrorCode() const override {
  59. llvm_unreachable("CustomSubError doesn't support ECError conversion");
  60. }
  61. // Used by ErrorInfo::classID.
  62. static char ID;
  63. protected:
  64. int ExtraInfo;
  65. };
  66. char CustomSubError::ID = 0;
  67. static Error handleCustomError(const CustomError &CE) {
  68. return Error::success();
  69. }
  70. static void handleCustomErrorVoid(const CustomError &CE) {}
  71. static Error handleCustomErrorUP(std::unique_ptr<CustomError> CE) {
  72. return Error::success();
  73. }
  74. static void handleCustomErrorUPVoid(std::unique_ptr<CustomError> CE) {}
  75. // Test that success values implicitly convert to false, and don't cause crashes
  76. // once they've been implicitly converted.
  77. TEST(Error, CheckedSuccess) {
  78. Error E = Error::success();
  79. EXPECT_FALSE(E) << "Unexpected error while testing Error 'Success'";
  80. }
  81. // Test that unchecked succes values cause an abort.
  82. #if LLVM_ENABLE_ABI_BREAKING_CHECKS
  83. TEST(Error, UncheckedSuccess) {
  84. EXPECT_DEATH({ Error E = Error::success(); },
  85. "Program aborted due to an unhandled Error:")
  86. << "Unchecked Error Succes value did not cause abort()";
  87. }
  88. #endif
  89. // ErrorAsOutParameter tester.
  90. void errAsOutParamHelper(Error &Err) {
  91. ErrorAsOutParameter ErrAsOutParam(&Err);
  92. // Verify that checked flag is raised - assignment should not crash.
  93. Err = Error::success();
  94. // Raise the checked bit manually - caller should still have to test the
  95. // error.
  96. (void)!!Err;
  97. }
  98. // Test that ErrorAsOutParameter sets the checked flag on construction.
  99. TEST(Error, ErrorAsOutParameterChecked) {
  100. Error E = Error::success();
  101. errAsOutParamHelper(E);
  102. (void)!!E;
  103. }
  104. // Test that ErrorAsOutParameter clears the checked flag on destruction.
  105. #if LLVM_ENABLE_ABI_BREAKING_CHECKS
  106. TEST(Error, ErrorAsOutParameterUnchecked) {
  107. EXPECT_DEATH({ Error E = Error::success(); errAsOutParamHelper(E); },
  108. "Program aborted due to an unhandled Error:")
  109. << "ErrorAsOutParameter did not clear the checked flag on destruction.";
  110. }
  111. #endif
  112. // Check that we abort on unhandled failure cases. (Force conversion to bool
  113. // to make sure that we don't accidentally treat checked errors as handled).
  114. // Test runs in debug mode only.
  115. #if LLVM_ENABLE_ABI_BREAKING_CHECKS
  116. TEST(Error, UncheckedError) {
  117. auto DropUnhandledError = []() {
  118. Error E = make_error<CustomError>(42);
  119. (void)!E;
  120. };
  121. EXPECT_DEATH(DropUnhandledError(),
  122. "Program aborted due to an unhandled Error:")
  123. << "Unhandled Error failure value did not cause abort()";
  124. }
  125. #endif
  126. // Check 'Error::isA<T>' method handling.
  127. TEST(Error, IsAHandling) {
  128. // Check 'isA' handling.
  129. Error E = make_error<CustomError>(1);
  130. Error F = make_error<CustomSubError>(1, 2);
  131. Error G = Error::success();
  132. EXPECT_TRUE(E.isA<CustomError>());
  133. EXPECT_FALSE(E.isA<CustomSubError>());
  134. EXPECT_TRUE(F.isA<CustomError>());
  135. EXPECT_TRUE(F.isA<CustomSubError>());
  136. EXPECT_FALSE(G.isA<CustomError>());
  137. consumeError(std::move(E));
  138. consumeError(std::move(F));
  139. consumeError(std::move(G));
  140. }
  141. // Check that we can handle a custom error.
  142. TEST(Error, HandleCustomError) {
  143. int CaughtErrorInfo = 0;
  144. handleAllErrors(make_error<CustomError>(42), [&](const CustomError &CE) {
  145. CaughtErrorInfo = CE.getInfo();
  146. });
  147. EXPECT_TRUE(CaughtErrorInfo == 42) << "Wrong result from CustomError handler";
  148. }
  149. // Check that handler type deduction also works for handlers
  150. // of the following types:
  151. // void (const Err&)
  152. // Error (const Err&) mutable
  153. // void (const Err&) mutable
  154. // Error (Err&)
  155. // void (Err&)
  156. // Error (Err&) mutable
  157. // void (Err&) mutable
  158. // Error (unique_ptr<Err>)
  159. // void (unique_ptr<Err>)
  160. // Error (unique_ptr<Err>) mutable
  161. // void (unique_ptr<Err>) mutable
  162. TEST(Error, HandlerTypeDeduction) {
  163. handleAllErrors(make_error<CustomError>(42), [](const CustomError &CE) {});
  164. handleAllErrors(
  165. make_error<CustomError>(42),
  166. [](const CustomError &CE) mutable -> Error { return Error::success(); });
  167. handleAllErrors(make_error<CustomError>(42),
  168. [](const CustomError &CE) mutable {});
  169. handleAllErrors(make_error<CustomError>(42),
  170. [](CustomError &CE) -> Error { return Error::success(); });
  171. handleAllErrors(make_error<CustomError>(42), [](CustomError &CE) {});
  172. handleAllErrors(make_error<CustomError>(42),
  173. [](CustomError &CE) mutable -> Error { return Error::success(); });
  174. handleAllErrors(make_error<CustomError>(42), [](CustomError &CE) mutable {});
  175. handleAllErrors(
  176. make_error<CustomError>(42),
  177. [](std::unique_ptr<CustomError> CE) -> Error { return Error::success(); });
  178. handleAllErrors(make_error<CustomError>(42),
  179. [](std::unique_ptr<CustomError> CE) {});
  180. handleAllErrors(
  181. make_error<CustomError>(42),
  182. [](std::unique_ptr<CustomError> CE) mutable -> Error { return Error::success(); });
  183. handleAllErrors(make_error<CustomError>(42),
  184. [](std::unique_ptr<CustomError> CE) mutable {});
  185. // Check that named handlers of type 'Error (const Err&)' work.
  186. handleAllErrors(make_error<CustomError>(42), handleCustomError);
  187. // Check that named handlers of type 'void (const Err&)' work.
  188. handleAllErrors(make_error<CustomError>(42), handleCustomErrorVoid);
  189. // Check that named handlers of type 'Error (std::unique_ptr<Err>)' work.
  190. handleAllErrors(make_error<CustomError>(42), handleCustomErrorUP);
  191. // Check that named handlers of type 'Error (std::unique_ptr<Err>)' work.
  192. handleAllErrors(make_error<CustomError>(42), handleCustomErrorUPVoid);
  193. }
  194. // Test that we can handle errors with custom base classes.
  195. TEST(Error, HandleCustomErrorWithCustomBaseClass) {
  196. int CaughtErrorInfo = 0;
  197. int CaughtErrorExtraInfo = 0;
  198. handleAllErrors(make_error<CustomSubError>(42, 7),
  199. [&](const CustomSubError &SE) {
  200. CaughtErrorInfo = SE.getInfo();
  201. CaughtErrorExtraInfo = SE.getExtraInfo();
  202. });
  203. EXPECT_TRUE(CaughtErrorInfo == 42 && CaughtErrorExtraInfo == 7)
  204. << "Wrong result from CustomSubError handler";
  205. }
  206. // Check that we trigger only the first handler that applies.
  207. TEST(Error, FirstHandlerOnly) {
  208. int DummyInfo = 0;
  209. int CaughtErrorInfo = 0;
  210. int CaughtErrorExtraInfo = 0;
  211. handleAllErrors(make_error<CustomSubError>(42, 7),
  212. [&](const CustomSubError &SE) {
  213. CaughtErrorInfo = SE.getInfo();
  214. CaughtErrorExtraInfo = SE.getExtraInfo();
  215. },
  216. [&](const CustomError &CE) { DummyInfo = CE.getInfo(); });
  217. EXPECT_TRUE(CaughtErrorInfo == 42 && CaughtErrorExtraInfo == 7 &&
  218. DummyInfo == 0)
  219. << "Activated the wrong Error handler(s)";
  220. }
  221. // Check that general handlers shadow specific ones.
  222. TEST(Error, HandlerShadowing) {
  223. int CaughtErrorInfo = 0;
  224. int DummyInfo = 0;
  225. int DummyExtraInfo = 0;
  226. handleAllErrors(
  227. make_error<CustomSubError>(42, 7),
  228. [&](const CustomError &CE) { CaughtErrorInfo = CE.getInfo(); },
  229. [&](const CustomSubError &SE) {
  230. DummyInfo = SE.getInfo();
  231. DummyExtraInfo = SE.getExtraInfo();
  232. });
  233. EXPECT_TRUE(CaughtErrorInfo == 42 && DummyInfo == 0 && DummyExtraInfo == 0)
  234. << "General Error handler did not shadow specific handler";
  235. }
  236. // Test joinErrors.
  237. TEST(Error, CheckJoinErrors) {
  238. int CustomErrorInfo1 = 0;
  239. int CustomErrorInfo2 = 0;
  240. int CustomErrorExtraInfo = 0;
  241. Error E =
  242. joinErrors(make_error<CustomError>(7), make_error<CustomSubError>(42, 7));
  243. handleAllErrors(std::move(E),
  244. [&](const CustomSubError &SE) {
  245. CustomErrorInfo2 = SE.getInfo();
  246. CustomErrorExtraInfo = SE.getExtraInfo();
  247. },
  248. [&](const CustomError &CE) {
  249. // Assert that the CustomError instance above is handled
  250. // before the
  251. // CustomSubError - joinErrors should preserve error
  252. // ordering.
  253. EXPECT_EQ(CustomErrorInfo2, 0)
  254. << "CustomErrorInfo2 should be 0 here. "
  255. "joinErrors failed to preserve ordering.\n";
  256. CustomErrorInfo1 = CE.getInfo();
  257. });
  258. EXPECT_TRUE(CustomErrorInfo1 == 7 && CustomErrorInfo2 == 42 &&
  259. CustomErrorExtraInfo == 7)
  260. << "Failed handling compound Error.";
  261. // Test appending a single item to a list.
  262. {
  263. int Sum = 0;
  264. handleAllErrors(
  265. joinErrors(
  266. joinErrors(make_error<CustomError>(7),
  267. make_error<CustomError>(7)),
  268. make_error<CustomError>(7)),
  269. [&](const CustomError &CE) {
  270. Sum += CE.getInfo();
  271. });
  272. EXPECT_EQ(Sum, 21) << "Failed to correctly append error to error list.";
  273. }
  274. // Test prepending a single item to a list.
  275. {
  276. int Sum = 0;
  277. handleAllErrors(
  278. joinErrors(
  279. make_error<CustomError>(7),
  280. joinErrors(make_error<CustomError>(7),
  281. make_error<CustomError>(7))),
  282. [&](const CustomError &CE) {
  283. Sum += CE.getInfo();
  284. });
  285. EXPECT_EQ(Sum, 21) << "Failed to correctly prepend error to error list.";
  286. }
  287. // Test concatenating two error lists.
  288. {
  289. int Sum = 0;
  290. handleAllErrors(
  291. joinErrors(
  292. joinErrors(
  293. make_error<CustomError>(7),
  294. make_error<CustomError>(7)),
  295. joinErrors(
  296. make_error<CustomError>(7),
  297. make_error<CustomError>(7))),
  298. [&](const CustomError &CE) {
  299. Sum += CE.getInfo();
  300. });
  301. EXPECT_EQ(Sum, 28) << "Failed to correctly concatenate error lists.";
  302. }
  303. }
  304. // Test that we can consume success values.
  305. TEST(Error, ConsumeSuccess) {
  306. Error E = Error::success();
  307. consumeError(std::move(E));
  308. }
  309. TEST(Error, ConsumeError) {
  310. Error E = make_error<CustomError>(7);
  311. consumeError(std::move(E));
  312. }
  313. // Test that handleAllUnhandledErrors crashes if an error is not caught.
  314. // Test runs in debug mode only.
  315. #if LLVM_ENABLE_ABI_BREAKING_CHECKS
  316. TEST(Error, FailureToHandle) {
  317. auto FailToHandle = []() {
  318. handleAllErrors(make_error<CustomError>(7), [&](const CustomSubError &SE) {
  319. errs() << "This should never be called";
  320. exit(1);
  321. });
  322. };
  323. EXPECT_DEATH(FailToHandle(),
  324. "Failure value returned from cantFail wrapped call")
  325. << "Unhandled Error in handleAllErrors call did not cause an "
  326. "abort()";
  327. }
  328. #endif
  329. // Test that handleAllUnhandledErrors crashes if an error is returned from a
  330. // handler.
  331. // Test runs in debug mode only.
  332. #if LLVM_ENABLE_ABI_BREAKING_CHECKS
  333. TEST(Error, FailureFromHandler) {
  334. auto ReturnErrorFromHandler = []() {
  335. handleAllErrors(make_error<CustomError>(7),
  336. [&](std::unique_ptr<CustomSubError> SE) {
  337. return Error(std::move(SE));
  338. });
  339. };
  340. EXPECT_DEATH(ReturnErrorFromHandler(),
  341. "Failure value returned from cantFail wrapped call")
  342. << " Error returned from handler in handleAllErrors call did not "
  343. "cause abort()";
  344. }
  345. #endif
  346. // Test that we can return values from handleErrors.
  347. TEST(Error, CatchErrorFromHandler) {
  348. int ErrorInfo = 0;
  349. Error E = handleErrors(
  350. make_error<CustomError>(7),
  351. [&](std::unique_ptr<CustomError> CE) { return Error(std::move(CE)); });
  352. handleAllErrors(std::move(E),
  353. [&](const CustomError &CE) { ErrorInfo = CE.getInfo(); });
  354. EXPECT_EQ(ErrorInfo, 7)
  355. << "Failed to handle Error returned from handleErrors.";
  356. }
  357. TEST(Error, StringError) {
  358. std::string Msg;
  359. raw_string_ostream S(Msg);
  360. logAllUnhandledErrors(make_error<StringError>("foo" + Twine(42),
  361. inconvertibleErrorCode()),
  362. S, "");
  363. EXPECT_EQ(S.str(), "foo42\n") << "Unexpected StringError log result";
  364. auto EC =
  365. errorToErrorCode(make_error<StringError>("", errc::invalid_argument));
  366. EXPECT_EQ(EC, errc::invalid_argument)
  367. << "Failed to convert StringError to error_code.";
  368. }
  369. // Test that the ExitOnError utility works as expected.
  370. TEST(Error, ExitOnError) {
  371. ExitOnError ExitOnErr;
  372. ExitOnErr.setBanner("Error in tool:");
  373. ExitOnErr.setExitCodeMapper([](const Error &E) {
  374. if (E.isA<CustomSubError>())
  375. return 2;
  376. return 1;
  377. });
  378. // Make sure we don't bail on success.
  379. ExitOnErr(Error::success());
  380. EXPECT_EQ(ExitOnErr(Expected<int>(7)), 7)
  381. << "exitOnError returned an invalid value for Expected";
  382. int A = 7;
  383. int &B = ExitOnErr(Expected<int&>(A));
  384. EXPECT_EQ(&A, &B) << "ExitOnError failed to propagate reference";
  385. // Exit tests.
  386. EXPECT_EXIT(ExitOnErr(make_error<CustomError>(7)),
  387. ::testing::ExitedWithCode(1), "Error in tool:")
  388. << "exitOnError returned an unexpected error result";
  389. EXPECT_EXIT(ExitOnErr(Expected<int>(make_error<CustomSubError>(0, 0))),
  390. ::testing::ExitedWithCode(2), "Error in tool:")
  391. << "exitOnError returned an unexpected error result";
  392. }
  393. // Test that the ExitOnError utility works as expected.
  394. TEST(Error, CantFailSuccess) {
  395. cantFail(Error::success());
  396. int X = cantFail(Expected<int>(42));
  397. EXPECT_EQ(X, 42) << "Expected value modified by cantFail";
  398. int Dummy = 42;
  399. int &Y = cantFail(Expected<int&>(Dummy));
  400. EXPECT_EQ(&Dummy, &Y) << "Reference mangled by cantFail";
  401. }
  402. // Test that cantFail results in a crash if you pass it a failure value.
  403. #if LLVM_ENABLE_ABI_BREAKING_CHECKS && !defined(NDEBUG)
  404. TEST(Error, CantFailDeath) {
  405. EXPECT_DEATH(
  406. cantFail(make_error<StringError>("foo", inconvertibleErrorCode()),
  407. "Cantfail call failed"),
  408. "Cantfail call failed")
  409. << "cantFail(Error) did not cause an abort for failure value";
  410. EXPECT_DEATH(
  411. {
  412. auto IEC = inconvertibleErrorCode();
  413. int X = cantFail(Expected<int>(make_error<StringError>("foo", IEC)));
  414. (void)X;
  415. },
  416. "Failure value returned from cantFail wrapped call")
  417. << "cantFail(Expected<int>) did not cause an abort for failure value";
  418. }
  419. #endif
  420. // Test Checked Expected<T> in success mode.
  421. TEST(Error, CheckedExpectedInSuccessMode) {
  422. Expected<int> A = 7;
  423. EXPECT_TRUE(!!A) << "Expected with non-error value doesn't convert to 'true'";
  424. // Access is safe in second test, since we checked the error in the first.
  425. EXPECT_EQ(*A, 7) << "Incorrect Expected non-error value";
  426. }
  427. // Test Expected with reference type.
  428. TEST(Error, ExpectedWithReferenceType) {
  429. int A = 7;
  430. Expected<int&> B = A;
  431. // 'Check' B.
  432. (void)!!B;
  433. int &C = *B;
  434. EXPECT_EQ(&A, &C) << "Expected failed to propagate reference";
  435. }
  436. // Test Unchecked Expected<T> in success mode.
  437. // We expect this to blow up the same way Error would.
  438. // Test runs in debug mode only.
  439. #if LLVM_ENABLE_ABI_BREAKING_CHECKS
  440. TEST(Error, UncheckedExpectedInSuccessModeDestruction) {
  441. EXPECT_DEATH({ Expected<int> A = 7; },
  442. "Expected<T> must be checked before access or destruction.")
  443. << "Unchecekd Expected<T> success value did not cause an abort().";
  444. }
  445. #endif
  446. // Test Unchecked Expected<T> in success mode.
  447. // We expect this to blow up the same way Error would.
  448. // Test runs in debug mode only.
  449. #if LLVM_ENABLE_ABI_BREAKING_CHECKS
  450. TEST(Error, UncheckedExpectedInSuccessModeAccess) {
  451. EXPECT_DEATH({ Expected<int> A = 7; *A; },
  452. "Expected<T> must be checked before access or destruction.")
  453. << "Unchecekd Expected<T> success value did not cause an abort().";
  454. }
  455. #endif
  456. // Test Unchecked Expected<T> in success mode.
  457. // We expect this to blow up the same way Error would.
  458. // Test runs in debug mode only.
  459. #if LLVM_ENABLE_ABI_BREAKING_CHECKS
  460. TEST(Error, UncheckedExpectedInSuccessModeAssignment) {
  461. EXPECT_DEATH({ Expected<int> A = 7; A = 7; },
  462. "Expected<T> must be checked before access or destruction.")
  463. << "Unchecekd Expected<T> success value did not cause an abort().";
  464. }
  465. #endif
  466. // Test Expected<T> in failure mode.
  467. TEST(Error, ExpectedInFailureMode) {
  468. Expected<int> A = make_error<CustomError>(42);
  469. EXPECT_FALSE(!!A) << "Expected with error value doesn't convert to 'false'";
  470. Error E = A.takeError();
  471. EXPECT_TRUE(E.isA<CustomError>()) << "Incorrect Expected error value";
  472. consumeError(std::move(E));
  473. }
  474. // Check that an Expected instance with an error value doesn't allow access to
  475. // operator*.
  476. // Test runs in debug mode only.
  477. #if LLVM_ENABLE_ABI_BREAKING_CHECKS
  478. TEST(Error, AccessExpectedInFailureMode) {
  479. Expected<int> A = make_error<CustomError>(42);
  480. EXPECT_DEATH(*A, "Expected<T> must be checked before access or destruction.")
  481. << "Incorrect Expected error value";
  482. consumeError(A.takeError());
  483. }
  484. #endif
  485. // Check that an Expected instance with an error triggers an abort if
  486. // unhandled.
  487. // Test runs in debug mode only.
  488. #if LLVM_ENABLE_ABI_BREAKING_CHECKS
  489. TEST(Error, UnhandledExpectedInFailureMode) {
  490. EXPECT_DEATH({ Expected<int> A = make_error<CustomError>(42); },
  491. "Expected<T> must be checked before access or destruction.")
  492. << "Unchecked Expected<T> failure value did not cause an abort()";
  493. }
  494. #endif
  495. // Test covariance of Expected.
  496. TEST(Error, ExpectedCovariance) {
  497. class B {};
  498. class D : public B {};
  499. Expected<B *> A1(Expected<D *>(nullptr));
  500. // Check A1 by converting to bool before assigning to it.
  501. (void)!!A1;
  502. A1 = Expected<D *>(nullptr);
  503. // Check A1 again before destruction.
  504. (void)!!A1;
  505. Expected<std::unique_ptr<B>> A2(Expected<std::unique_ptr<D>>(nullptr));
  506. // Check A2 by converting to bool before assigning to it.
  507. (void)!!A2;
  508. A2 = Expected<std::unique_ptr<D>>(nullptr);
  509. // Check A2 again before destruction.
  510. (void)!!A2;
  511. }
  512. // Test that handleExpected just returns success values.
  513. TEST(Error, HandleExpectedSuccess) {
  514. auto ValOrErr =
  515. handleExpected(Expected<int>(42),
  516. []() { return Expected<int>(43); });
  517. EXPECT_TRUE(!!ValOrErr)
  518. << "handleExpected should have returned a success value here";
  519. EXPECT_EQ(*ValOrErr, 42)
  520. << "handleExpected should have returned the original success value here";
  521. }
  522. enum FooStrategy { Aggressive, Conservative };
  523. static Expected<int> foo(FooStrategy S) {
  524. if (S == Aggressive)
  525. return make_error<CustomError>(7);
  526. return 42;
  527. }
  528. // Test that handleExpected invokes the error path if errors are not handled.
  529. TEST(Error, HandleExpectedUnhandledError) {
  530. // foo(Aggressive) should return a CustomError which should pass through as
  531. // there is no handler for CustomError.
  532. auto ValOrErr =
  533. handleExpected(
  534. foo(Aggressive),
  535. []() { return foo(Conservative); });
  536. EXPECT_FALSE(!!ValOrErr)
  537. << "handleExpected should have returned an error here";
  538. auto Err = ValOrErr.takeError();
  539. EXPECT_TRUE(Err.isA<CustomError>())
  540. << "handleExpected should have returned the CustomError generated by "
  541. "foo(Aggressive) here";
  542. consumeError(std::move(Err));
  543. }
  544. // Test that handleExpected invokes the fallback path if errors are handled.
  545. TEST(Error, HandleExpectedHandledError) {
  546. // foo(Aggressive) should return a CustomError which should handle triggering
  547. // the fallback path.
  548. auto ValOrErr =
  549. handleExpected(
  550. foo(Aggressive),
  551. []() { return foo(Conservative); },
  552. [](const CustomError&) { /* do nothing */ });
  553. EXPECT_TRUE(!!ValOrErr)
  554. << "handleExpected should have returned a success value here";
  555. EXPECT_EQ(*ValOrErr, 42)
  556. << "handleExpected returned the wrong success value";
  557. }
  558. TEST(Error, ErrorCodeConversions) {
  559. // Round-trip a success value to check that it converts correctly.
  560. EXPECT_EQ(errorToErrorCode(errorCodeToError(std::error_code())),
  561. std::error_code())
  562. << "std::error_code() should round-trip via Error conversions";
  563. // Round-trip an error value to check that it converts correctly.
  564. EXPECT_EQ(errorToErrorCode(errorCodeToError(errc::invalid_argument)),
  565. errc::invalid_argument)
  566. << "std::error_code error value should round-trip via Error "
  567. "conversions";
  568. // Round-trip a success value through ErrorOr/Expected to check that it
  569. // converts correctly.
  570. {
  571. auto Orig = ErrorOr<int>(42);
  572. auto RoundTripped =
  573. expectedToErrorOr(errorOrToExpected(ErrorOr<int>(42)));
  574. EXPECT_EQ(*Orig, *RoundTripped)
  575. << "ErrorOr<T> success value should round-trip via Expected<T> "
  576. "conversions.";
  577. }
  578. // Round-trip a failure value through ErrorOr/Expected to check that it
  579. // converts correctly.
  580. {
  581. auto Orig = ErrorOr<int>(errc::invalid_argument);
  582. auto RoundTripped =
  583. expectedToErrorOr(
  584. errorOrToExpected(ErrorOr<int>(errc::invalid_argument)));
  585. EXPECT_EQ(Orig.getError(), RoundTripped.getError())
  586. << "ErrorOr<T> failure value should round-trip via Expected<T> "
  587. "conversions.";
  588. }
  589. }
  590. // Test that error messages work.
  591. TEST(Error, ErrorMessage) {
  592. EXPECT_EQ(toString(Error::success()).compare(""), 0);
  593. Error E1 = make_error<CustomError>(0);
  594. EXPECT_EQ(toString(std::move(E1)).compare("CustomError { 0}"), 0);
  595. Error E2 = make_error<CustomError>(0);
  596. handleAllErrors(std::move(E2), [](const CustomError &CE) {
  597. EXPECT_EQ(CE.message().compare("CustomError { 0}"), 0);
  598. });
  599. Error E3 = joinErrors(make_error<CustomError>(0), make_error<CustomError>(1));
  600. EXPECT_EQ(toString(std::move(E3))
  601. .compare("CustomError { 0}\n"
  602. "CustomError { 1}"),
  603. 0);
  604. }
  605. TEST(Error, ErrorMatchers) {
  606. EXPECT_THAT_ERROR(Error::success(), Succeeded());
  607. EXPECT_NONFATAL_FAILURE(
  608. EXPECT_THAT_ERROR(make_error<CustomError>(0), Succeeded()),
  609. "Expected: succeeded\n Actual: failed (CustomError { 0})");
  610. EXPECT_THAT_ERROR(make_error<CustomError>(0), Failed());
  611. EXPECT_NONFATAL_FAILURE(EXPECT_THAT_ERROR(Error::success(), Failed()),
  612. "Expected: failed\n Actual: succeeded");
  613. EXPECT_THAT_EXPECTED(Expected<int>(0), Succeeded());
  614. EXPECT_NONFATAL_FAILURE(
  615. EXPECT_THAT_EXPECTED(Expected<int>(make_error<CustomError>(0)),
  616. Succeeded()),
  617. "Expected: succeeded\n Actual: failed (CustomError { 0})");
  618. EXPECT_THAT_EXPECTED(Expected<int>(make_error<CustomError>(0)), Failed());
  619. EXPECT_NONFATAL_FAILURE(
  620. EXPECT_THAT_EXPECTED(Expected<int>(0), Failed()),
  621. "Expected: failed\n Actual: succeeded with value \"0\"");
  622. EXPECT_THAT_EXPECTED(Expected<int>(0), HasValue(0));
  623. EXPECT_NONFATAL_FAILURE(
  624. EXPECT_THAT_EXPECTED(Expected<int>(make_error<CustomError>(0)),
  625. HasValue(0)),
  626. "Expected: succeeded with value \"0\"\n"
  627. " Actual: failed (CustomError { 0})");
  628. EXPECT_NONFATAL_FAILURE(
  629. EXPECT_THAT_EXPECTED(Expected<int>(1), HasValue(0)),
  630. "Expected: succeeded with value \"0\"\n"
  631. " Actual: succeeded with value \"1\", but \"1\" != \"0\"");
  632. EXPECT_THAT_EXPECTED(Expected<int &>(make_error<CustomError>(0)), Failed());
  633. int a = 1;
  634. EXPECT_THAT_EXPECTED(Expected<int &>(a), Succeeded());
  635. EXPECT_THAT_EXPECTED(Expected<int &>(a), HasValue(1));
  636. }
  637. } // end anon namespace