ErrorTest.cpp 20 KB

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