ErrorTest.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981
  1. //===----- unittests/ErrorTest.cpp - Error.h tests ------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. #include "llvm/Support/Error.h"
  9. #include "llvm-c/Error.h"
  10. #include "llvm/ADT/Twine.h"
  11. #include "llvm/Support/Errc.h"
  12. #include "llvm/Support/ErrorHandling.h"
  13. #include "llvm/Support/ManagedStatic.h"
  14. #include "llvm/Testing/Support/Error.h"
  15. #include "gtest/gtest-spi.h"
  16. #include "gtest/gtest.h"
  17. #include <memory>
  18. using namespace llvm;
  19. namespace {
  20. // Custom error class with a default base class and some random 'info' attached.
  21. class CustomError : public ErrorInfo<CustomError> {
  22. public:
  23. // Create an error with some info attached.
  24. CustomError(int Info) : Info(Info) {}
  25. // Get the info attached to this error.
  26. int getInfo() const { return Info; }
  27. // Log this error to a stream.
  28. void log(raw_ostream &OS) const override {
  29. OS << "CustomError {" << getInfo() << "}";
  30. }
  31. std::error_code convertToErrorCode() const override {
  32. llvm_unreachable("CustomError doesn't support ECError conversion");
  33. }
  34. // Used by ErrorInfo::classID.
  35. static char ID;
  36. protected:
  37. // This error is subclassed below, but we can't use inheriting constructors
  38. // yet, so we can't propagate the constructors through ErrorInfo. Instead
  39. // we have to have a default constructor and have the subclass initialize all
  40. // fields.
  41. CustomError() : Info(0) {}
  42. int Info;
  43. };
  44. char CustomError::ID = 0;
  45. // Custom error class with a custom base class and some additional random
  46. // 'info'.
  47. class CustomSubError : public ErrorInfo<CustomSubError, CustomError> {
  48. public:
  49. // Create a sub-error with some info attached.
  50. CustomSubError(int Info, int ExtraInfo) : ExtraInfo(ExtraInfo) {
  51. this->Info = Info;
  52. }
  53. // Get the extra info attached to this error.
  54. int getExtraInfo() const { return ExtraInfo; }
  55. // Log this error to a stream.
  56. void log(raw_ostream &OS) const override {
  57. OS << "CustomSubError { " << getInfo() << ", " << getExtraInfo() << "}";
  58. }
  59. std::error_code convertToErrorCode() const override {
  60. llvm_unreachable("CustomSubError doesn't support ECError conversion");
  61. }
  62. // Used by ErrorInfo::classID.
  63. static char ID;
  64. protected:
  65. int ExtraInfo;
  66. };
  67. char CustomSubError::ID = 0;
  68. static Error handleCustomError(const CustomError &CE) {
  69. return Error::success();
  70. }
  71. static void handleCustomErrorVoid(const CustomError &CE) {}
  72. static Error handleCustomErrorUP(std::unique_ptr<CustomError> CE) {
  73. return Error::success();
  74. }
  75. static void handleCustomErrorUPVoid(std::unique_ptr<CustomError> CE) {}
  76. // Test that success values implicitly convert to false, and don't cause crashes
  77. // once they've been implicitly converted.
  78. TEST(Error, CheckedSuccess) {
  79. Error E = Error::success();
  80. EXPECT_FALSE(E) << "Unexpected error while testing Error 'Success'";
  81. }
  82. // Test that unchecked success values cause an abort.
  83. #if LLVM_ENABLE_ABI_BREAKING_CHECKS
  84. TEST(Error, UncheckedSuccess) {
  85. EXPECT_DEATH({ Error E = Error::success(); },
  86. "Program aborted due to an unhandled Error:")
  87. << "Unchecked Error Succes value did not cause abort()";
  88. }
  89. #endif
  90. // ErrorAsOutParameter tester.
  91. void errAsOutParamHelper(Error &Err) {
  92. ErrorAsOutParameter ErrAsOutParam(&Err);
  93. // Verify that checked flag is raised - assignment should not crash.
  94. Err = Error::success();
  95. // Raise the checked bit manually - caller should still have to test the
  96. // error.
  97. (void)!!Err;
  98. }
  99. // Test that ErrorAsOutParameter sets the checked flag on construction.
  100. TEST(Error, ErrorAsOutParameterChecked) {
  101. Error E = Error::success();
  102. errAsOutParamHelper(E);
  103. (void)!!E;
  104. }
  105. // Test that ErrorAsOutParameter clears the checked flag on destruction.
  106. #if LLVM_ENABLE_ABI_BREAKING_CHECKS
  107. TEST(Error, ErrorAsOutParameterUnchecked) {
  108. EXPECT_DEATH({ Error E = Error::success(); errAsOutParamHelper(E); },
  109. "Program aborted due to an unhandled Error:")
  110. << "ErrorAsOutParameter did not clear the checked flag on destruction.";
  111. }
  112. #endif
  113. // Check that we abort on unhandled failure cases. (Force conversion to bool
  114. // to make sure that we don't accidentally treat checked errors as handled).
  115. // Test runs in debug mode only.
  116. #if LLVM_ENABLE_ABI_BREAKING_CHECKS
  117. TEST(Error, UncheckedError) {
  118. auto DropUnhandledError = []() {
  119. Error E = make_error<CustomError>(42);
  120. (void)!E;
  121. };
  122. EXPECT_DEATH(DropUnhandledError(),
  123. "Program aborted due to an unhandled Error:")
  124. << "Unhandled Error failure value did not cause abort()";
  125. }
  126. #endif
  127. // Check 'Error::isA<T>' method handling.
  128. TEST(Error, IsAHandling) {
  129. // Check 'isA' handling.
  130. Error E = make_error<CustomError>(1);
  131. Error F = make_error<CustomSubError>(1, 2);
  132. Error G = Error::success();
  133. EXPECT_TRUE(E.isA<CustomError>());
  134. EXPECT_FALSE(E.isA<CustomSubError>());
  135. EXPECT_TRUE(F.isA<CustomError>());
  136. EXPECT_TRUE(F.isA<CustomSubError>());
  137. EXPECT_FALSE(G.isA<CustomError>());
  138. consumeError(std::move(E));
  139. consumeError(std::move(F));
  140. consumeError(std::move(G));
  141. }
  142. // Check that we can handle a custom error.
  143. TEST(Error, HandleCustomError) {
  144. int CaughtErrorInfo = 0;
  145. handleAllErrors(make_error<CustomError>(42), [&](const CustomError &CE) {
  146. CaughtErrorInfo = CE.getInfo();
  147. });
  148. EXPECT_TRUE(CaughtErrorInfo == 42) << "Wrong result from CustomError handler";
  149. }
  150. // Check that handler type deduction also works for handlers
  151. // of the following types:
  152. // void (const Err&)
  153. // Error (const Err&) mutable
  154. // void (const Err&) mutable
  155. // Error (Err&)
  156. // void (Err&)
  157. // Error (Err&) mutable
  158. // void (Err&) mutable
  159. // Error (unique_ptr<Err>)
  160. // void (unique_ptr<Err>)
  161. // Error (unique_ptr<Err>) mutable
  162. // void (unique_ptr<Err>) mutable
  163. TEST(Error, HandlerTypeDeduction) {
  164. handleAllErrors(make_error<CustomError>(42), [](const CustomError &CE) {});
  165. handleAllErrors(
  166. make_error<CustomError>(42),
  167. [](const CustomError &CE) mutable -> Error { return Error::success(); });
  168. handleAllErrors(make_error<CustomError>(42),
  169. [](const CustomError &CE) mutable {});
  170. handleAllErrors(make_error<CustomError>(42),
  171. [](CustomError &CE) -> Error { return Error::success(); });
  172. handleAllErrors(make_error<CustomError>(42), [](CustomError &CE) {});
  173. handleAllErrors(make_error<CustomError>(42),
  174. [](CustomError &CE) mutable -> Error { return Error::success(); });
  175. handleAllErrors(make_error<CustomError>(42), [](CustomError &CE) mutable {});
  176. handleAllErrors(
  177. make_error<CustomError>(42),
  178. [](std::unique_ptr<CustomError> CE) -> Error { return Error::success(); });
  179. handleAllErrors(make_error<CustomError>(42),
  180. [](std::unique_ptr<CustomError> CE) {});
  181. handleAllErrors(
  182. make_error<CustomError>(42),
  183. [](std::unique_ptr<CustomError> CE) mutable -> Error { return Error::success(); });
  184. handleAllErrors(make_error<CustomError>(42),
  185. [](std::unique_ptr<CustomError> CE) mutable {});
  186. // Check that named handlers of type 'Error (const Err&)' work.
  187. handleAllErrors(make_error<CustomError>(42), handleCustomError);
  188. // Check that named handlers of type 'void (const Err&)' work.
  189. handleAllErrors(make_error<CustomError>(42), handleCustomErrorVoid);
  190. // Check that named handlers of type 'Error (std::unique_ptr<Err>)' work.
  191. handleAllErrors(make_error<CustomError>(42), handleCustomErrorUP);
  192. // Check that named handlers of type 'Error (std::unique_ptr<Err>)' work.
  193. handleAllErrors(make_error<CustomError>(42), handleCustomErrorUPVoid);
  194. }
  195. // Test that we can handle errors with custom base classes.
  196. TEST(Error, HandleCustomErrorWithCustomBaseClass) {
  197. int CaughtErrorInfo = 0;
  198. int CaughtErrorExtraInfo = 0;
  199. handleAllErrors(make_error<CustomSubError>(42, 7),
  200. [&](const CustomSubError &SE) {
  201. CaughtErrorInfo = SE.getInfo();
  202. CaughtErrorExtraInfo = SE.getExtraInfo();
  203. });
  204. EXPECT_TRUE(CaughtErrorInfo == 42 && CaughtErrorExtraInfo == 7)
  205. << "Wrong result from CustomSubError handler";
  206. }
  207. // Check that we trigger only the first handler that applies.
  208. TEST(Error, FirstHandlerOnly) {
  209. int DummyInfo = 0;
  210. int CaughtErrorInfo = 0;
  211. int CaughtErrorExtraInfo = 0;
  212. handleAllErrors(make_error<CustomSubError>(42, 7),
  213. [&](const CustomSubError &SE) {
  214. CaughtErrorInfo = SE.getInfo();
  215. CaughtErrorExtraInfo = SE.getExtraInfo();
  216. },
  217. [&](const CustomError &CE) { DummyInfo = CE.getInfo(); });
  218. EXPECT_TRUE(CaughtErrorInfo == 42 && CaughtErrorExtraInfo == 7 &&
  219. DummyInfo == 0)
  220. << "Activated the wrong Error handler(s)";
  221. }
  222. // Check that general handlers shadow specific ones.
  223. TEST(Error, HandlerShadowing) {
  224. int CaughtErrorInfo = 0;
  225. int DummyInfo = 0;
  226. int DummyExtraInfo = 0;
  227. handleAllErrors(
  228. make_error<CustomSubError>(42, 7),
  229. [&](const CustomError &CE) { CaughtErrorInfo = CE.getInfo(); },
  230. [&](const CustomSubError &SE) {
  231. DummyInfo = SE.getInfo();
  232. DummyExtraInfo = SE.getExtraInfo();
  233. });
  234. EXPECT_TRUE(CaughtErrorInfo == 42 && DummyInfo == 0 && DummyExtraInfo == 0)
  235. << "General Error handler did not shadow specific handler";
  236. }
  237. // Test joinErrors.
  238. TEST(Error, CheckJoinErrors) {
  239. int CustomErrorInfo1 = 0;
  240. int CustomErrorInfo2 = 0;
  241. int CustomErrorExtraInfo = 0;
  242. Error E =
  243. joinErrors(make_error<CustomError>(7), make_error<CustomSubError>(42, 7));
  244. handleAllErrors(std::move(E),
  245. [&](const CustomSubError &SE) {
  246. CustomErrorInfo2 = SE.getInfo();
  247. CustomErrorExtraInfo = SE.getExtraInfo();
  248. },
  249. [&](const CustomError &CE) {
  250. // Assert that the CustomError instance above is handled
  251. // before the
  252. // CustomSubError - joinErrors should preserve error
  253. // ordering.
  254. EXPECT_EQ(CustomErrorInfo2, 0)
  255. << "CustomErrorInfo2 should be 0 here. "
  256. "joinErrors failed to preserve ordering.\n";
  257. CustomErrorInfo1 = CE.getInfo();
  258. });
  259. EXPECT_TRUE(CustomErrorInfo1 == 7 && CustomErrorInfo2 == 42 &&
  260. CustomErrorExtraInfo == 7)
  261. << "Failed handling compound Error.";
  262. // Test appending a single item to a list.
  263. {
  264. int Sum = 0;
  265. handleAllErrors(
  266. joinErrors(
  267. joinErrors(make_error<CustomError>(7),
  268. make_error<CustomError>(7)),
  269. make_error<CustomError>(7)),
  270. [&](const CustomError &CE) {
  271. Sum += CE.getInfo();
  272. });
  273. EXPECT_EQ(Sum, 21) << "Failed to correctly append error to error list.";
  274. }
  275. // Test prepending a single item to a list.
  276. {
  277. int Sum = 0;
  278. handleAllErrors(
  279. joinErrors(
  280. make_error<CustomError>(7),
  281. joinErrors(make_error<CustomError>(7),
  282. make_error<CustomError>(7))),
  283. [&](const CustomError &CE) {
  284. Sum += CE.getInfo();
  285. });
  286. EXPECT_EQ(Sum, 21) << "Failed to correctly prepend error to error list.";
  287. }
  288. // Test concatenating two error lists.
  289. {
  290. int Sum = 0;
  291. handleAllErrors(
  292. joinErrors(
  293. joinErrors(
  294. make_error<CustomError>(7),
  295. make_error<CustomError>(7)),
  296. joinErrors(
  297. make_error<CustomError>(7),
  298. make_error<CustomError>(7))),
  299. [&](const CustomError &CE) {
  300. Sum += CE.getInfo();
  301. });
  302. EXPECT_EQ(Sum, 28) << "Failed to correctly concatenate error lists.";
  303. }
  304. }
  305. // Test that we can consume success values.
  306. TEST(Error, ConsumeSuccess) {
  307. Error E = Error::success();
  308. consumeError(std::move(E));
  309. }
  310. TEST(Error, ConsumeError) {
  311. Error E = make_error<CustomError>(7);
  312. consumeError(std::move(E));
  313. }
  314. // Test that handleAllUnhandledErrors crashes if an error is not caught.
  315. // Test runs in debug mode only.
  316. #if LLVM_ENABLE_ABI_BREAKING_CHECKS
  317. TEST(Error, FailureToHandle) {
  318. auto FailToHandle = []() {
  319. handleAllErrors(make_error<CustomError>(7), [&](const CustomSubError &SE) {
  320. errs() << "This should never be called";
  321. exit(1);
  322. });
  323. };
  324. EXPECT_DEATH(FailToHandle(),
  325. "Failure value returned from cantFail wrapped call\n"
  326. "CustomError \\{7\\}")
  327. << "Unhandled Error in handleAllErrors call did not cause an "
  328. "abort()";
  329. }
  330. #endif
  331. // Test that handleAllUnhandledErrors crashes if an error is returned from a
  332. // handler.
  333. // Test runs in debug mode only.
  334. #if LLVM_ENABLE_ABI_BREAKING_CHECKS
  335. TEST(Error, FailureFromHandler) {
  336. auto ReturnErrorFromHandler = []() {
  337. handleAllErrors(make_error<CustomError>(7),
  338. [&](std::unique_ptr<CustomSubError> SE) {
  339. return Error(std::move(SE));
  340. });
  341. };
  342. EXPECT_DEATH(ReturnErrorFromHandler(),
  343. "Failure value returned from cantFail wrapped call\n"
  344. "CustomError \\{7\\}")
  345. << " Error returned from handler in handleAllErrors call did not "
  346. "cause abort()";
  347. }
  348. #endif
  349. // Test that we can return values from handleErrors.
  350. TEST(Error, CatchErrorFromHandler) {
  351. int ErrorInfo = 0;
  352. Error E = handleErrors(
  353. make_error<CustomError>(7),
  354. [&](std::unique_ptr<CustomError> CE) { return Error(std::move(CE)); });
  355. handleAllErrors(std::move(E),
  356. [&](const CustomError &CE) { ErrorInfo = CE.getInfo(); });
  357. EXPECT_EQ(ErrorInfo, 7)
  358. << "Failed to handle Error returned from handleErrors.";
  359. }
  360. TEST(Error, StringError) {
  361. std::string Msg;
  362. raw_string_ostream S(Msg);
  363. logAllUnhandledErrors(
  364. make_error<StringError>("foo" + Twine(42), inconvertibleErrorCode()), S);
  365. EXPECT_EQ(S.str(), "foo42\n") << "Unexpected StringError log result";
  366. auto EC =
  367. errorToErrorCode(make_error<StringError>("", errc::invalid_argument));
  368. EXPECT_EQ(EC, errc::invalid_argument)
  369. << "Failed to convert StringError to error_code.";
  370. }
  371. TEST(Error, createStringError) {
  372. static const char *Bar = "bar";
  373. static const std::error_code EC = errc::invalid_argument;
  374. std::string Msg;
  375. raw_string_ostream S(Msg);
  376. logAllUnhandledErrors(createStringError(EC, "foo%s%d0x%" PRIx8, Bar, 1, 0xff),
  377. S);
  378. EXPECT_EQ(S.str(), "foobar10xff\n")
  379. << "Unexpected createStringError() log result";
  380. S.flush();
  381. Msg.clear();
  382. logAllUnhandledErrors(createStringError(EC, Bar), S);
  383. EXPECT_EQ(S.str(), "bar\n")
  384. << "Unexpected createStringError() (overloaded) log result";
  385. S.flush();
  386. Msg.clear();
  387. auto Res = errorToErrorCode(createStringError(EC, "foo%s", Bar));
  388. EXPECT_EQ(Res, EC)
  389. << "Failed to convert createStringError() result to error_code.";
  390. }
  391. // Test that the ExitOnError utility works as expected.
  392. TEST(Error, ExitOnError) {
  393. ExitOnError ExitOnErr;
  394. ExitOnErr.setBanner("Error in tool:");
  395. ExitOnErr.setExitCodeMapper([](const Error &E) {
  396. if (E.isA<CustomSubError>())
  397. return 2;
  398. return 1;
  399. });
  400. // Make sure we don't bail on success.
  401. ExitOnErr(Error::success());
  402. EXPECT_EQ(ExitOnErr(Expected<int>(7)), 7)
  403. << "exitOnError returned an invalid value for Expected";
  404. int A = 7;
  405. int &B = ExitOnErr(Expected<int&>(A));
  406. EXPECT_EQ(&A, &B) << "ExitOnError failed to propagate reference";
  407. // Exit tests.
  408. EXPECT_EXIT(ExitOnErr(make_error<CustomError>(7)),
  409. ::testing::ExitedWithCode(1), "Error in tool:")
  410. << "exitOnError returned an unexpected error result";
  411. EXPECT_EXIT(ExitOnErr(Expected<int>(make_error<CustomSubError>(0, 0))),
  412. ::testing::ExitedWithCode(2), "Error in tool:")
  413. << "exitOnError returned an unexpected error result";
  414. }
  415. // Test that the ExitOnError utility works as expected.
  416. TEST(Error, CantFailSuccess) {
  417. cantFail(Error::success());
  418. int X = cantFail(Expected<int>(42));
  419. EXPECT_EQ(X, 42) << "Expected value modified by cantFail";
  420. int Dummy = 42;
  421. int &Y = cantFail(Expected<int&>(Dummy));
  422. EXPECT_EQ(&Dummy, &Y) << "Reference mangled by cantFail";
  423. }
  424. // Test that cantFail results in a crash if you pass it a failure value.
  425. #if LLVM_ENABLE_ABI_BREAKING_CHECKS && !defined(NDEBUG)
  426. TEST(Error, CantFailDeath) {
  427. EXPECT_DEATH(cantFail(make_error<StringError>("Original error message",
  428. inconvertibleErrorCode()),
  429. "Cantfail call failed"),
  430. "Cantfail call failed\n"
  431. "Original error message")
  432. << "cantFail(Error) did not cause an abort for failure value";
  433. EXPECT_DEATH(
  434. {
  435. auto IEC = inconvertibleErrorCode();
  436. int X = cantFail(Expected<int>(make_error<StringError>("foo", IEC)));
  437. (void)X;
  438. },
  439. "Failure value returned from cantFail wrapped call")
  440. << "cantFail(Expected<int>) did not cause an abort for failure value";
  441. }
  442. #endif
  443. // Test Checked Expected<T> in success mode.
  444. TEST(Error, CheckedExpectedInSuccessMode) {
  445. Expected<int> A = 7;
  446. EXPECT_TRUE(!!A) << "Expected with non-error value doesn't convert to 'true'";
  447. // Access is safe in second test, since we checked the error in the first.
  448. EXPECT_EQ(*A, 7) << "Incorrect Expected non-error value";
  449. }
  450. // Test Expected with reference type.
  451. TEST(Error, ExpectedWithReferenceType) {
  452. int A = 7;
  453. Expected<int&> B = A;
  454. // 'Check' B.
  455. (void)!!B;
  456. int &C = *B;
  457. EXPECT_EQ(&A, &C) << "Expected failed to propagate reference";
  458. }
  459. // Test Unchecked Expected<T> in success mode.
  460. // We expect this to blow up the same way Error would.
  461. // Test runs in debug mode only.
  462. #if LLVM_ENABLE_ABI_BREAKING_CHECKS
  463. TEST(Error, UncheckedExpectedInSuccessModeDestruction) {
  464. EXPECT_DEATH({ Expected<int> A = 7; },
  465. "Expected<T> must be checked before access or destruction.")
  466. << "Unchecekd Expected<T> success value did not cause an abort().";
  467. }
  468. #endif
  469. // Test Unchecked Expected<T> in success mode.
  470. // We expect this to blow up the same way Error would.
  471. // Test runs in debug mode only.
  472. #if LLVM_ENABLE_ABI_BREAKING_CHECKS
  473. TEST(Error, UncheckedExpectedInSuccessModeAccess) {
  474. EXPECT_DEATH({ Expected<int> A = 7; *A; },
  475. "Expected<T> must be checked before access or destruction.")
  476. << "Unchecekd Expected<T> success value did not cause an abort().";
  477. }
  478. #endif
  479. // Test Unchecked Expected<T> in success mode.
  480. // We expect this to blow up the same way Error would.
  481. // Test runs in debug mode only.
  482. #if LLVM_ENABLE_ABI_BREAKING_CHECKS
  483. TEST(Error, UncheckedExpectedInSuccessModeAssignment) {
  484. EXPECT_DEATH({ Expected<int> A = 7; A = 7; },
  485. "Expected<T> must be checked before access or destruction.")
  486. << "Unchecekd Expected<T> success value did not cause an abort().";
  487. }
  488. #endif
  489. // Test Expected<T> in failure mode.
  490. TEST(Error, ExpectedInFailureMode) {
  491. Expected<int> A = make_error<CustomError>(42);
  492. EXPECT_FALSE(!!A) << "Expected with error value doesn't convert to 'false'";
  493. Error E = A.takeError();
  494. EXPECT_TRUE(E.isA<CustomError>()) << "Incorrect Expected error value";
  495. consumeError(std::move(E));
  496. }
  497. // Check that an Expected instance with an error value doesn't allow access to
  498. // operator*.
  499. // Test runs in debug mode only.
  500. #if LLVM_ENABLE_ABI_BREAKING_CHECKS
  501. TEST(Error, AccessExpectedInFailureMode) {
  502. Expected<int> A = make_error<CustomError>(42);
  503. EXPECT_DEATH(*A, "Expected<T> must be checked before access or destruction.")
  504. << "Incorrect Expected error value";
  505. consumeError(A.takeError());
  506. }
  507. #endif
  508. // Check that an Expected instance with an error triggers an abort if
  509. // unhandled.
  510. // Test runs in debug mode only.
  511. #if LLVM_ENABLE_ABI_BREAKING_CHECKS
  512. TEST(Error, UnhandledExpectedInFailureMode) {
  513. EXPECT_DEATH({ Expected<int> A = make_error<CustomError>(42); },
  514. "Expected<T> must be checked before access or destruction.")
  515. << "Unchecked Expected<T> failure value did not cause an abort()";
  516. }
  517. #endif
  518. // Test covariance of Expected.
  519. TEST(Error, ExpectedCovariance) {
  520. class B {};
  521. class D : public B {};
  522. Expected<B *> A1(Expected<D *>(nullptr));
  523. // Check A1 by converting to bool before assigning to it.
  524. (void)!!A1;
  525. A1 = Expected<D *>(nullptr);
  526. // Check A1 again before destruction.
  527. (void)!!A1;
  528. Expected<std::unique_ptr<B>> A2(Expected<std::unique_ptr<D>>(nullptr));
  529. // Check A2 by converting to bool before assigning to it.
  530. (void)!!A2;
  531. A2 = Expected<std::unique_ptr<D>>(nullptr);
  532. // Check A2 again before destruction.
  533. (void)!!A2;
  534. }
  535. // Test that handleExpected just returns success values.
  536. TEST(Error, HandleExpectedSuccess) {
  537. auto ValOrErr =
  538. handleExpected(Expected<int>(42),
  539. []() { return Expected<int>(43); });
  540. EXPECT_TRUE(!!ValOrErr)
  541. << "handleExpected should have returned a success value here";
  542. EXPECT_EQ(*ValOrErr, 42)
  543. << "handleExpected should have returned the original success value here";
  544. }
  545. enum FooStrategy { Aggressive, Conservative };
  546. static Expected<int> foo(FooStrategy S) {
  547. if (S == Aggressive)
  548. return make_error<CustomError>(7);
  549. return 42;
  550. }
  551. // Test that handleExpected invokes the error path if errors are not handled.
  552. TEST(Error, HandleExpectedUnhandledError) {
  553. // foo(Aggressive) should return a CustomError which should pass through as
  554. // there is no handler for CustomError.
  555. auto ValOrErr =
  556. handleExpected(
  557. foo(Aggressive),
  558. []() { return foo(Conservative); });
  559. EXPECT_FALSE(!!ValOrErr)
  560. << "handleExpected should have returned an error here";
  561. auto Err = ValOrErr.takeError();
  562. EXPECT_TRUE(Err.isA<CustomError>())
  563. << "handleExpected should have returned the CustomError generated by "
  564. "foo(Aggressive) here";
  565. consumeError(std::move(Err));
  566. }
  567. // Test that handleExpected invokes the fallback path if errors are handled.
  568. TEST(Error, HandleExpectedHandledError) {
  569. // foo(Aggressive) should return a CustomError which should handle triggering
  570. // the fallback path.
  571. auto ValOrErr =
  572. handleExpected(
  573. foo(Aggressive),
  574. []() { return foo(Conservative); },
  575. [](const CustomError&) { /* do nothing */ });
  576. EXPECT_TRUE(!!ValOrErr)
  577. << "handleExpected should have returned a success value here";
  578. EXPECT_EQ(*ValOrErr, 42)
  579. << "handleExpected returned the wrong success value";
  580. }
  581. TEST(Error, ErrorCodeConversions) {
  582. // Round-trip a success value to check that it converts correctly.
  583. EXPECT_EQ(errorToErrorCode(errorCodeToError(std::error_code())),
  584. std::error_code())
  585. << "std::error_code() should round-trip via Error conversions";
  586. // Round-trip an error value to check that it converts correctly.
  587. EXPECT_EQ(errorToErrorCode(errorCodeToError(errc::invalid_argument)),
  588. errc::invalid_argument)
  589. << "std::error_code error value should round-trip via Error "
  590. "conversions";
  591. // Round-trip a success value through ErrorOr/Expected to check that it
  592. // converts correctly.
  593. {
  594. auto Orig = ErrorOr<int>(42);
  595. auto RoundTripped =
  596. expectedToErrorOr(errorOrToExpected(ErrorOr<int>(42)));
  597. EXPECT_EQ(*Orig, *RoundTripped)
  598. << "ErrorOr<T> success value should round-trip via Expected<T> "
  599. "conversions.";
  600. }
  601. // Round-trip a failure value through ErrorOr/Expected to check that it
  602. // converts correctly.
  603. {
  604. auto Orig = ErrorOr<int>(errc::invalid_argument);
  605. auto RoundTripped =
  606. expectedToErrorOr(
  607. errorOrToExpected(ErrorOr<int>(errc::invalid_argument)));
  608. EXPECT_EQ(Orig.getError(), RoundTripped.getError())
  609. << "ErrorOr<T> failure value should round-trip via Expected<T> "
  610. "conversions.";
  611. }
  612. }
  613. // Test that error messages work.
  614. TEST(Error, ErrorMessage) {
  615. EXPECT_EQ(toString(Error::success()).compare(""), 0);
  616. Error E1 = make_error<CustomError>(0);
  617. EXPECT_EQ(toString(std::move(E1)).compare("CustomError {0}"), 0);
  618. Error E2 = make_error<CustomError>(0);
  619. handleAllErrors(std::move(E2), [](const CustomError &CE) {
  620. EXPECT_EQ(CE.message().compare("CustomError {0}"), 0);
  621. });
  622. Error E3 = joinErrors(make_error<CustomError>(0), make_error<CustomError>(1));
  623. EXPECT_EQ(toString(std::move(E3))
  624. .compare("CustomError {0}\n"
  625. "CustomError {1}"),
  626. 0);
  627. }
  628. TEST(Error, Stream) {
  629. {
  630. Error OK = Error::success();
  631. std::string Buf;
  632. llvm::raw_string_ostream S(Buf);
  633. S << OK;
  634. EXPECT_EQ("success", S.str());
  635. consumeError(std::move(OK));
  636. }
  637. {
  638. Error E1 = make_error<CustomError>(0);
  639. std::string Buf;
  640. llvm::raw_string_ostream S(Buf);
  641. S << E1;
  642. EXPECT_EQ("CustomError {0}", S.str());
  643. consumeError(std::move(E1));
  644. }
  645. }
  646. TEST(Error, ErrorMatchers) {
  647. EXPECT_THAT_ERROR(Error::success(), Succeeded());
  648. EXPECT_NONFATAL_FAILURE(
  649. EXPECT_THAT_ERROR(make_error<CustomError>(0), Succeeded()),
  650. "Expected: succeeded\n Actual: failed (CustomError {0})");
  651. EXPECT_THAT_ERROR(make_error<CustomError>(0), Failed());
  652. EXPECT_NONFATAL_FAILURE(EXPECT_THAT_ERROR(Error::success(), Failed()),
  653. "Expected: failed\n Actual: succeeded");
  654. EXPECT_THAT_ERROR(make_error<CustomError>(0), Failed<CustomError>());
  655. EXPECT_NONFATAL_FAILURE(
  656. EXPECT_THAT_ERROR(Error::success(), Failed<CustomError>()),
  657. "Expected: failed with Error of given type\n Actual: succeeded");
  658. EXPECT_NONFATAL_FAILURE(
  659. EXPECT_THAT_ERROR(make_error<CustomError>(0), Failed<CustomSubError>()),
  660. "Error was not of given type");
  661. EXPECT_NONFATAL_FAILURE(
  662. EXPECT_THAT_ERROR(
  663. joinErrors(make_error<CustomError>(0), make_error<CustomError>(1)),
  664. Failed<CustomError>()),
  665. "multiple errors");
  666. EXPECT_THAT_ERROR(
  667. make_error<CustomError>(0),
  668. Failed<CustomError>(testing::Property(&CustomError::getInfo, 0)));
  669. EXPECT_NONFATAL_FAILURE(
  670. EXPECT_THAT_ERROR(
  671. make_error<CustomError>(0),
  672. Failed<CustomError>(testing::Property(&CustomError::getInfo, 1))),
  673. "Expected: failed with Error of given type and the error is an object "
  674. "whose given property is equal to 1\n"
  675. " Actual: failed (CustomError {0})");
  676. EXPECT_THAT_ERROR(make_error<CustomError>(0), Failed<ErrorInfoBase>());
  677. EXPECT_THAT_EXPECTED(Expected<int>(0), Succeeded());
  678. EXPECT_NONFATAL_FAILURE(
  679. EXPECT_THAT_EXPECTED(Expected<int>(make_error<CustomError>(0)),
  680. Succeeded()),
  681. "Expected: succeeded\n Actual: failed (CustomError {0})");
  682. EXPECT_THAT_EXPECTED(Expected<int>(make_error<CustomError>(0)), Failed());
  683. EXPECT_NONFATAL_FAILURE(
  684. EXPECT_THAT_EXPECTED(Expected<int>(0), Failed()),
  685. "Expected: failed\n Actual: succeeded with value 0");
  686. EXPECT_THAT_EXPECTED(Expected<int>(0), HasValue(0));
  687. EXPECT_NONFATAL_FAILURE(
  688. EXPECT_THAT_EXPECTED(Expected<int>(make_error<CustomError>(0)),
  689. HasValue(0)),
  690. "Expected: succeeded with value (is equal to 0)\n"
  691. " Actual: failed (CustomError {0})");
  692. EXPECT_NONFATAL_FAILURE(
  693. EXPECT_THAT_EXPECTED(Expected<int>(1), HasValue(0)),
  694. "Expected: succeeded with value (is equal to 0)\n"
  695. " Actual: succeeded with value 1, (isn't equal to 0)");
  696. EXPECT_THAT_EXPECTED(Expected<int &>(make_error<CustomError>(0)), Failed());
  697. int a = 1;
  698. EXPECT_THAT_EXPECTED(Expected<int &>(a), Succeeded());
  699. EXPECT_THAT_EXPECTED(Expected<int &>(a), HasValue(testing::Eq(1)));
  700. EXPECT_THAT_EXPECTED(Expected<int>(1), HasValue(testing::Gt(0)));
  701. EXPECT_NONFATAL_FAILURE(
  702. EXPECT_THAT_EXPECTED(Expected<int>(0), HasValue(testing::Gt(1))),
  703. "Expected: succeeded with value (is > 1)\n"
  704. " Actual: succeeded with value 0, (isn't > 1)");
  705. EXPECT_NONFATAL_FAILURE(
  706. EXPECT_THAT_EXPECTED(Expected<int>(make_error<CustomError>(0)),
  707. HasValue(testing::Gt(1))),
  708. "Expected: succeeded with value (is > 1)\n"
  709. " Actual: failed (CustomError {0})");
  710. }
  711. TEST(Error, C_API) {
  712. EXPECT_THAT_ERROR(unwrap(wrap(Error::success())), Succeeded())
  713. << "Failed to round-trip Error success value via C API";
  714. EXPECT_THAT_ERROR(unwrap(wrap(make_error<CustomError>(0))),
  715. Failed<CustomError>())
  716. << "Failed to round-trip Error failure value via C API";
  717. auto Err =
  718. wrap(make_error<StringError>("test message", inconvertibleErrorCode()));
  719. EXPECT_EQ(LLVMGetErrorTypeId(Err), LLVMGetStringErrorTypeId())
  720. << "Failed to match error type ids via C API";
  721. char *ErrMsg = LLVMGetErrorMessage(Err);
  722. EXPECT_STREQ(ErrMsg, "test message")
  723. << "Failed to roundtrip StringError error message via C API";
  724. LLVMDisposeErrorMessage(ErrMsg);
  725. bool GotCSE = false;
  726. bool GotCE = false;
  727. handleAllErrors(
  728. unwrap(wrap(joinErrors(make_error<CustomSubError>(42, 7),
  729. make_error<CustomError>(42)))),
  730. [&](CustomSubError &CSE) {
  731. GotCSE = true;
  732. },
  733. [&](CustomError &CE) {
  734. GotCE = true;
  735. });
  736. EXPECT_TRUE(GotCSE) << "Failed to round-trip ErrorList via C API";
  737. EXPECT_TRUE(GotCE) << "Failed to round-trip ErrorList via C API";
  738. }
  739. TEST(Error, FileErrorTest) {
  740. #if !defined(NDEBUG) && GTEST_HAS_DEATH_TEST
  741. EXPECT_DEATH(
  742. {
  743. Error S = Error::success();
  744. consumeError(createFileError("file.bin", std::move(S)));
  745. },
  746. "");
  747. #endif
  748. // Not allowed, would fail at compile-time
  749. //consumeError(createFileError("file.bin", ErrorSuccess()));
  750. Error E1 = make_error<CustomError>(1);
  751. Error FE1 = createFileError("file.bin", std::move(E1));
  752. EXPECT_EQ(toString(std::move(FE1)).compare("'file.bin': CustomError {1}"), 0);
  753. Error E2 = make_error<CustomError>(2);
  754. Error FE2 = createFileError("file.bin", std::move(E2));
  755. handleAllErrors(std::move(FE2), [](const FileError &F) {
  756. EXPECT_EQ(F.message().compare("'file.bin': CustomError {2}"), 0);
  757. });
  758. Error E3 = make_error<CustomError>(3);
  759. Error FE3 = createFileError("file.bin", std::move(E3));
  760. auto E31 = handleErrors(std::move(FE3), [](std::unique_ptr<FileError> F) {
  761. return F->takeError();
  762. });
  763. handleAllErrors(std::move(E31), [](const CustomError &C) {
  764. EXPECT_EQ(C.message().compare("CustomError {3}"), 0);
  765. });
  766. Error FE4 =
  767. joinErrors(createFileError("file.bin", make_error<CustomError>(41)),
  768. createFileError("file2.bin", make_error<CustomError>(42)));
  769. EXPECT_EQ(toString(std::move(FE4))
  770. .compare("'file.bin': CustomError {41}\n"
  771. "'file2.bin': CustomError {42}"),
  772. 0);
  773. }
  774. enum class test_error_code {
  775. unspecified = 1,
  776. error_1,
  777. error_2,
  778. };
  779. } // end anon namespace
  780. namespace std {
  781. template <>
  782. struct is_error_code_enum<test_error_code> : std::true_type {};
  783. } // namespace std
  784. namespace {
  785. const std::error_category &TErrorCategory();
  786. inline std::error_code make_error_code(test_error_code E) {
  787. return std::error_code(static_cast<int>(E), TErrorCategory());
  788. }
  789. class TestDebugError : public ErrorInfo<TestDebugError, StringError> {
  790. public:
  791. using ErrorInfo<TestDebugError, StringError >::ErrorInfo; // inherit constructors
  792. TestDebugError(const Twine &S) : ErrorInfo(S, test_error_code::unspecified) {}
  793. static char ID;
  794. };
  795. class TestErrorCategory : public std::error_category {
  796. public:
  797. const char *name() const noexcept override { return "error"; }
  798. std::string message(int Condition) const override {
  799. switch (static_cast<test_error_code>(Condition)) {
  800. case test_error_code::unspecified:
  801. return "An unknown error has occurred.";
  802. case test_error_code::error_1:
  803. return "Error 1.";
  804. case test_error_code::error_2:
  805. return "Error 2.";
  806. }
  807. llvm_unreachable("Unrecognized test_error_code");
  808. }
  809. };
  810. static llvm::ManagedStatic<TestErrorCategory> TestErrCategory;
  811. const std::error_category &TErrorCategory() { return *TestErrCategory; }
  812. char TestDebugError::ID;
  813. TEST(Error, SubtypeStringErrorTest) {
  814. auto E1 = make_error<TestDebugError>(test_error_code::error_1);
  815. EXPECT_EQ(toString(std::move(E1)).compare("Error 1."), 0);
  816. auto E2 = make_error<TestDebugError>(test_error_code::error_1,
  817. "Detailed information");
  818. EXPECT_EQ(toString(std::move(E2)).compare("Error 1. Detailed information"),
  819. 0);
  820. auto E3 = make_error<TestDebugError>(test_error_code::error_2);
  821. handleAllErrors(std::move(E3), [](const TestDebugError &F) {
  822. EXPECT_EQ(F.message().compare("Error 2."), 0);
  823. });
  824. auto E4 = joinErrors(make_error<TestDebugError>(test_error_code::error_1,
  825. "Detailed information"),
  826. make_error<TestDebugError>(test_error_code::error_2));
  827. EXPECT_EQ(toString(std::move(E4))
  828. .compare("Error 1. Detailed information\n"
  829. "Error 2."),
  830. 0);
  831. }
  832. } // namespace