ErrorTest.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978
  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")
  326. << "Unhandled Error in handleAllErrors call did not cause an "
  327. "abort()";
  328. }
  329. #endif
  330. // Test that handleAllUnhandledErrors crashes if an error is returned from a
  331. // handler.
  332. // Test runs in debug mode only.
  333. #if LLVM_ENABLE_ABI_BREAKING_CHECKS
  334. TEST(Error, FailureFromHandler) {
  335. auto ReturnErrorFromHandler = []() {
  336. handleAllErrors(make_error<CustomError>(7),
  337. [&](std::unique_ptr<CustomSubError> SE) {
  338. return Error(std::move(SE));
  339. });
  340. };
  341. EXPECT_DEATH(ReturnErrorFromHandler(),
  342. "Failure value returned from cantFail wrapped call")
  343. << " Error returned from handler in handleAllErrors call did not "
  344. "cause abort()";
  345. }
  346. #endif
  347. // Test that we can return values from handleErrors.
  348. TEST(Error, CatchErrorFromHandler) {
  349. int ErrorInfo = 0;
  350. Error E = handleErrors(
  351. make_error<CustomError>(7),
  352. [&](std::unique_ptr<CustomError> CE) { return Error(std::move(CE)); });
  353. handleAllErrors(std::move(E),
  354. [&](const CustomError &CE) { ErrorInfo = CE.getInfo(); });
  355. EXPECT_EQ(ErrorInfo, 7)
  356. << "Failed to handle Error returned from handleErrors.";
  357. }
  358. TEST(Error, StringError) {
  359. std::string Msg;
  360. raw_string_ostream S(Msg);
  361. logAllUnhandledErrors(
  362. make_error<StringError>("foo" + Twine(42), inconvertibleErrorCode()), 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(Error, createStringError) {
  370. static const char *Bar = "bar";
  371. static const std::error_code EC = errc::invalid_argument;
  372. std::string Msg;
  373. raw_string_ostream S(Msg);
  374. logAllUnhandledErrors(createStringError(EC, "foo%s%d0x%" PRIx8, Bar, 1, 0xff),
  375. S);
  376. EXPECT_EQ(S.str(), "foobar10xff\n")
  377. << "Unexpected createStringError() log result";
  378. S.flush();
  379. Msg.clear();
  380. logAllUnhandledErrors(createStringError(EC, Bar), S);
  381. EXPECT_EQ(S.str(), "bar\n")
  382. << "Unexpected createStringError() (overloaded) log result";
  383. S.flush();
  384. Msg.clear();
  385. auto Res = errorToErrorCode(createStringError(EC, "foo%s", Bar));
  386. EXPECT_EQ(Res, EC)
  387. << "Failed to convert createStringError() result to error_code.";
  388. }
  389. // Test that the ExitOnError utility works as expected.
  390. TEST(Error, ExitOnError) {
  391. ExitOnError ExitOnErr;
  392. ExitOnErr.setBanner("Error in tool:");
  393. ExitOnErr.setExitCodeMapper([](const Error &E) {
  394. if (E.isA<CustomSubError>())
  395. return 2;
  396. return 1;
  397. });
  398. // Make sure we don't bail on success.
  399. ExitOnErr(Error::success());
  400. EXPECT_EQ(ExitOnErr(Expected<int>(7)), 7)
  401. << "exitOnError returned an invalid value for Expected";
  402. int A = 7;
  403. int &B = ExitOnErr(Expected<int&>(A));
  404. EXPECT_EQ(&A, &B) << "ExitOnError failed to propagate reference";
  405. // Exit tests.
  406. EXPECT_EXIT(ExitOnErr(make_error<CustomError>(7)),
  407. ::testing::ExitedWithCode(1), "Error in tool:")
  408. << "exitOnError returned an unexpected error result";
  409. EXPECT_EXIT(ExitOnErr(Expected<int>(make_error<CustomSubError>(0, 0))),
  410. ::testing::ExitedWithCode(2), "Error in tool:")
  411. << "exitOnError returned an unexpected error result";
  412. }
  413. // Test that the ExitOnError utility works as expected.
  414. TEST(Error, CantFailSuccess) {
  415. cantFail(Error::success());
  416. int X = cantFail(Expected<int>(42));
  417. EXPECT_EQ(X, 42) << "Expected value modified by cantFail";
  418. int Dummy = 42;
  419. int &Y = cantFail(Expected<int&>(Dummy));
  420. EXPECT_EQ(&Dummy, &Y) << "Reference mangled by cantFail";
  421. }
  422. // Test that cantFail results in a crash if you pass it a failure value.
  423. #if LLVM_ENABLE_ABI_BREAKING_CHECKS && !defined(NDEBUG)
  424. TEST(Error, CantFailDeath) {
  425. EXPECT_DEATH(
  426. cantFail(make_error<StringError>("foo", inconvertibleErrorCode()),
  427. "Cantfail call failed"),
  428. "Cantfail call failed")
  429. << "cantFail(Error) did not cause an abort for failure value";
  430. EXPECT_DEATH(
  431. {
  432. auto IEC = inconvertibleErrorCode();
  433. int X = cantFail(Expected<int>(make_error<StringError>("foo", IEC)));
  434. (void)X;
  435. },
  436. "Failure value returned from cantFail wrapped call")
  437. << "cantFail(Expected<int>) did not cause an abort for failure value";
  438. }
  439. #endif
  440. // Test Checked Expected<T> in success mode.
  441. TEST(Error, CheckedExpectedInSuccessMode) {
  442. Expected<int> A = 7;
  443. EXPECT_TRUE(!!A) << "Expected with non-error value doesn't convert to 'true'";
  444. // Access is safe in second test, since we checked the error in the first.
  445. EXPECT_EQ(*A, 7) << "Incorrect Expected non-error value";
  446. }
  447. // Test Expected with reference type.
  448. TEST(Error, ExpectedWithReferenceType) {
  449. int A = 7;
  450. Expected<int&> B = A;
  451. // 'Check' B.
  452. (void)!!B;
  453. int &C = *B;
  454. EXPECT_EQ(&A, &C) << "Expected failed to propagate reference";
  455. }
  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, UncheckedExpectedInSuccessModeDestruction) {
  461. EXPECT_DEATH({ Expected<int> 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 Unchecked Expected<T> in success mode.
  467. // We expect this to blow up the same way Error would.
  468. // Test runs in debug mode only.
  469. #if LLVM_ENABLE_ABI_BREAKING_CHECKS
  470. TEST(Error, UncheckedExpectedInSuccessModeAccess) {
  471. EXPECT_DEATH({ Expected<int> A = 7; *A; },
  472. "Expected<T> must be checked before access or destruction.")
  473. << "Unchecekd Expected<T> success value did not cause an abort().";
  474. }
  475. #endif
  476. // Test Unchecked Expected<T> in success mode.
  477. // We expect this to blow up the same way Error would.
  478. // Test runs in debug mode only.
  479. #if LLVM_ENABLE_ABI_BREAKING_CHECKS
  480. TEST(Error, UncheckedExpectedInSuccessModeAssignment) {
  481. EXPECT_DEATH({ Expected<int> A = 7; A = 7; },
  482. "Expected<T> must be checked before access or destruction.")
  483. << "Unchecekd Expected<T> success value did not cause an abort().";
  484. }
  485. #endif
  486. // Test Expected<T> in failure mode.
  487. TEST(Error, ExpectedInFailureMode) {
  488. Expected<int> A = make_error<CustomError>(42);
  489. EXPECT_FALSE(!!A) << "Expected with error value doesn't convert to 'false'";
  490. Error E = A.takeError();
  491. EXPECT_TRUE(E.isA<CustomError>()) << "Incorrect Expected error value";
  492. consumeError(std::move(E));
  493. }
  494. // Check that an Expected instance with an error value doesn't allow access to
  495. // operator*.
  496. // Test runs in debug mode only.
  497. #if LLVM_ENABLE_ABI_BREAKING_CHECKS
  498. TEST(Error, AccessExpectedInFailureMode) {
  499. Expected<int> A = make_error<CustomError>(42);
  500. EXPECT_DEATH(*A, "Expected<T> must be checked before access or destruction.")
  501. << "Incorrect Expected error value";
  502. consumeError(A.takeError());
  503. }
  504. #endif
  505. // Check that an Expected instance with an error triggers an abort if
  506. // unhandled.
  507. // Test runs in debug mode only.
  508. #if LLVM_ENABLE_ABI_BREAKING_CHECKS
  509. TEST(Error, UnhandledExpectedInFailureMode) {
  510. EXPECT_DEATH({ Expected<int> A = make_error<CustomError>(42); },
  511. "Expected<T> must be checked before access or destruction.")
  512. << "Unchecked Expected<T> failure value did not cause an abort()";
  513. }
  514. #endif
  515. // Test covariance of Expected.
  516. TEST(Error, ExpectedCovariance) {
  517. class B {};
  518. class D : public B {};
  519. Expected<B *> A1(Expected<D *>(nullptr));
  520. // Check A1 by converting to bool before assigning to it.
  521. (void)!!A1;
  522. A1 = Expected<D *>(nullptr);
  523. // Check A1 again before destruction.
  524. (void)!!A1;
  525. Expected<std::unique_ptr<B>> A2(Expected<std::unique_ptr<D>>(nullptr));
  526. // Check A2 by converting to bool before assigning to it.
  527. (void)!!A2;
  528. A2 = Expected<std::unique_ptr<D>>(nullptr);
  529. // Check A2 again before destruction.
  530. (void)!!A2;
  531. }
  532. // Test that handleExpected just returns success values.
  533. TEST(Error, HandleExpectedSuccess) {
  534. auto ValOrErr =
  535. handleExpected(Expected<int>(42),
  536. []() { return Expected<int>(43); });
  537. EXPECT_TRUE(!!ValOrErr)
  538. << "handleExpected should have returned a success value here";
  539. EXPECT_EQ(*ValOrErr, 42)
  540. << "handleExpected should have returned the original success value here";
  541. }
  542. enum FooStrategy { Aggressive, Conservative };
  543. static Expected<int> foo(FooStrategy S) {
  544. if (S == Aggressive)
  545. return make_error<CustomError>(7);
  546. return 42;
  547. }
  548. // Test that handleExpected invokes the error path if errors are not handled.
  549. TEST(Error, HandleExpectedUnhandledError) {
  550. // foo(Aggressive) should return a CustomError which should pass through as
  551. // there is no handler for CustomError.
  552. auto ValOrErr =
  553. handleExpected(
  554. foo(Aggressive),
  555. []() { return foo(Conservative); });
  556. EXPECT_FALSE(!!ValOrErr)
  557. << "handleExpected should have returned an error here";
  558. auto Err = ValOrErr.takeError();
  559. EXPECT_TRUE(Err.isA<CustomError>())
  560. << "handleExpected should have returned the CustomError generated by "
  561. "foo(Aggressive) here";
  562. consumeError(std::move(Err));
  563. }
  564. // Test that handleExpected invokes the fallback path if errors are handled.
  565. TEST(Error, HandleExpectedHandledError) {
  566. // foo(Aggressive) should return a CustomError which should handle triggering
  567. // the fallback path.
  568. auto ValOrErr =
  569. handleExpected(
  570. foo(Aggressive),
  571. []() { return foo(Conservative); },
  572. [](const CustomError&) { /* do nothing */ });
  573. EXPECT_TRUE(!!ValOrErr)
  574. << "handleExpected should have returned a success value here";
  575. EXPECT_EQ(*ValOrErr, 42)
  576. << "handleExpected returned the wrong success value";
  577. }
  578. TEST(Error, ErrorCodeConversions) {
  579. // Round-trip a success value to check that it converts correctly.
  580. EXPECT_EQ(errorToErrorCode(errorCodeToError(std::error_code())),
  581. std::error_code())
  582. << "std::error_code() should round-trip via Error conversions";
  583. // Round-trip an error value to check that it converts correctly.
  584. EXPECT_EQ(errorToErrorCode(errorCodeToError(errc::invalid_argument)),
  585. errc::invalid_argument)
  586. << "std::error_code error value should round-trip via Error "
  587. "conversions";
  588. // Round-trip a success value through ErrorOr/Expected to check that it
  589. // converts correctly.
  590. {
  591. auto Orig = ErrorOr<int>(42);
  592. auto RoundTripped =
  593. expectedToErrorOr(errorOrToExpected(ErrorOr<int>(42)));
  594. EXPECT_EQ(*Orig, *RoundTripped)
  595. << "ErrorOr<T> success value should round-trip via Expected<T> "
  596. "conversions.";
  597. }
  598. // Round-trip a failure value through ErrorOr/Expected to check that it
  599. // converts correctly.
  600. {
  601. auto Orig = ErrorOr<int>(errc::invalid_argument);
  602. auto RoundTripped =
  603. expectedToErrorOr(
  604. errorOrToExpected(ErrorOr<int>(errc::invalid_argument)));
  605. EXPECT_EQ(Orig.getError(), RoundTripped.getError())
  606. << "ErrorOr<T> failure value should round-trip via Expected<T> "
  607. "conversions.";
  608. }
  609. }
  610. // Test that error messages work.
  611. TEST(Error, ErrorMessage) {
  612. EXPECT_EQ(toString(Error::success()).compare(""), 0);
  613. Error E1 = make_error<CustomError>(0);
  614. EXPECT_EQ(toString(std::move(E1)).compare("CustomError {0}"), 0);
  615. Error E2 = make_error<CustomError>(0);
  616. handleAllErrors(std::move(E2), [](const CustomError &CE) {
  617. EXPECT_EQ(CE.message().compare("CustomError {0}"), 0);
  618. });
  619. Error E3 = joinErrors(make_error<CustomError>(0), make_error<CustomError>(1));
  620. EXPECT_EQ(toString(std::move(E3))
  621. .compare("CustomError {0}\n"
  622. "CustomError {1}"),
  623. 0);
  624. }
  625. TEST(Error, Stream) {
  626. {
  627. Error OK = Error::success();
  628. std::string Buf;
  629. llvm::raw_string_ostream S(Buf);
  630. S << OK;
  631. EXPECT_EQ("success", S.str());
  632. consumeError(std::move(OK));
  633. }
  634. {
  635. Error E1 = make_error<CustomError>(0);
  636. std::string Buf;
  637. llvm::raw_string_ostream S(Buf);
  638. S << E1;
  639. EXPECT_EQ("CustomError {0}", S.str());
  640. consumeError(std::move(E1));
  641. }
  642. }
  643. TEST(Error, ErrorMatchers) {
  644. EXPECT_THAT_ERROR(Error::success(), Succeeded());
  645. EXPECT_NONFATAL_FAILURE(
  646. EXPECT_THAT_ERROR(make_error<CustomError>(0), Succeeded()),
  647. "Expected: succeeded\n Actual: failed (CustomError {0})");
  648. EXPECT_THAT_ERROR(make_error<CustomError>(0), Failed());
  649. EXPECT_NONFATAL_FAILURE(EXPECT_THAT_ERROR(Error::success(), Failed()),
  650. "Expected: failed\n Actual: succeeded");
  651. EXPECT_THAT_ERROR(make_error<CustomError>(0), Failed<CustomError>());
  652. EXPECT_NONFATAL_FAILURE(
  653. EXPECT_THAT_ERROR(Error::success(), Failed<CustomError>()),
  654. "Expected: failed with Error of given type\n Actual: succeeded");
  655. EXPECT_NONFATAL_FAILURE(
  656. EXPECT_THAT_ERROR(make_error<CustomError>(0), Failed<CustomSubError>()),
  657. "Error was not of given type");
  658. EXPECT_NONFATAL_FAILURE(
  659. EXPECT_THAT_ERROR(
  660. joinErrors(make_error<CustomError>(0), make_error<CustomError>(1)),
  661. Failed<CustomError>()),
  662. "multiple errors");
  663. EXPECT_THAT_ERROR(
  664. make_error<CustomError>(0),
  665. Failed<CustomError>(testing::Property(&CustomError::getInfo, 0)));
  666. EXPECT_NONFATAL_FAILURE(
  667. EXPECT_THAT_ERROR(
  668. make_error<CustomError>(0),
  669. Failed<CustomError>(testing::Property(&CustomError::getInfo, 1))),
  670. "Expected: failed with Error of given type and the error is an object "
  671. "whose given property is equal to 1\n"
  672. " Actual: failed (CustomError {0})");
  673. EXPECT_THAT_ERROR(make_error<CustomError>(0), Failed<ErrorInfoBase>());
  674. EXPECT_THAT_EXPECTED(Expected<int>(0), Succeeded());
  675. EXPECT_NONFATAL_FAILURE(
  676. EXPECT_THAT_EXPECTED(Expected<int>(make_error<CustomError>(0)),
  677. Succeeded()),
  678. "Expected: succeeded\n Actual: failed (CustomError {0})");
  679. EXPECT_THAT_EXPECTED(Expected<int>(make_error<CustomError>(0)), Failed());
  680. EXPECT_NONFATAL_FAILURE(
  681. EXPECT_THAT_EXPECTED(Expected<int>(0), Failed()),
  682. "Expected: failed\n Actual: succeeded with value 0");
  683. EXPECT_THAT_EXPECTED(Expected<int>(0), HasValue(0));
  684. EXPECT_NONFATAL_FAILURE(
  685. EXPECT_THAT_EXPECTED(Expected<int>(make_error<CustomError>(0)),
  686. HasValue(0)),
  687. "Expected: succeeded with value (is equal to 0)\n"
  688. " Actual: failed (CustomError {0})");
  689. EXPECT_NONFATAL_FAILURE(
  690. EXPECT_THAT_EXPECTED(Expected<int>(1), HasValue(0)),
  691. "Expected: succeeded with value (is equal to 0)\n"
  692. " Actual: succeeded with value 1, (isn't equal to 0)");
  693. EXPECT_THAT_EXPECTED(Expected<int &>(make_error<CustomError>(0)), Failed());
  694. int a = 1;
  695. EXPECT_THAT_EXPECTED(Expected<int &>(a), Succeeded());
  696. EXPECT_THAT_EXPECTED(Expected<int &>(a), HasValue(testing::Eq(1)));
  697. EXPECT_THAT_EXPECTED(Expected<int>(1), HasValue(testing::Gt(0)));
  698. EXPECT_NONFATAL_FAILURE(
  699. EXPECT_THAT_EXPECTED(Expected<int>(0), HasValue(testing::Gt(1))),
  700. "Expected: succeeded with value (is > 1)\n"
  701. " Actual: succeeded with value 0, (isn't > 1)");
  702. EXPECT_NONFATAL_FAILURE(
  703. EXPECT_THAT_EXPECTED(Expected<int>(make_error<CustomError>(0)),
  704. HasValue(testing::Gt(1))),
  705. "Expected: succeeded with value (is > 1)\n"
  706. " Actual: failed (CustomError {0})");
  707. }
  708. TEST(Error, C_API) {
  709. EXPECT_THAT_ERROR(unwrap(wrap(Error::success())), Succeeded())
  710. << "Failed to round-trip Error success value via C API";
  711. EXPECT_THAT_ERROR(unwrap(wrap(make_error<CustomError>(0))),
  712. Failed<CustomError>())
  713. << "Failed to round-trip Error failure value via C API";
  714. auto Err =
  715. wrap(make_error<StringError>("test message", inconvertibleErrorCode()));
  716. EXPECT_EQ(LLVMGetErrorTypeId(Err), LLVMGetStringErrorTypeId())
  717. << "Failed to match error type ids via C API";
  718. char *ErrMsg = LLVMGetErrorMessage(Err);
  719. EXPECT_STREQ(ErrMsg, "test message")
  720. << "Failed to roundtrip StringError error message via C API";
  721. LLVMDisposeErrorMessage(ErrMsg);
  722. bool GotCSE = false;
  723. bool GotCE = false;
  724. handleAllErrors(
  725. unwrap(wrap(joinErrors(make_error<CustomSubError>(42, 7),
  726. make_error<CustomError>(42)))),
  727. [&](CustomSubError &CSE) {
  728. GotCSE = true;
  729. },
  730. [&](CustomError &CE) {
  731. GotCE = true;
  732. });
  733. EXPECT_TRUE(GotCSE) << "Failed to round-trip ErrorList via C API";
  734. EXPECT_TRUE(GotCE) << "Failed to round-trip ErrorList via C API";
  735. }
  736. TEST(Error, FileErrorTest) {
  737. #if !defined(NDEBUG) && GTEST_HAS_DEATH_TEST
  738. EXPECT_DEATH(
  739. {
  740. Error S = Error::success();
  741. consumeError(createFileError("file.bin", std::move(S)));
  742. },
  743. "");
  744. #endif
  745. // Not allowed, would fail at compile-time
  746. //consumeError(createFileError("file.bin", ErrorSuccess()));
  747. Error E1 = make_error<CustomError>(1);
  748. Error FE1 = createFileError("file.bin", std::move(E1));
  749. EXPECT_EQ(toString(std::move(FE1)).compare("'file.bin': CustomError {1}"), 0);
  750. Error E2 = make_error<CustomError>(2);
  751. Error FE2 = createFileError("file.bin", std::move(E2));
  752. handleAllErrors(std::move(FE2), [](const FileError &F) {
  753. EXPECT_EQ(F.message().compare("'file.bin': CustomError {2}"), 0);
  754. });
  755. Error E3 = make_error<CustomError>(3);
  756. Error FE3 = createFileError("file.bin", std::move(E3));
  757. auto E31 = handleErrors(std::move(FE3), [](std::unique_ptr<FileError> F) {
  758. return F->takeError();
  759. });
  760. handleAllErrors(std::move(E31), [](const CustomError &C) {
  761. EXPECT_EQ(C.message().compare("CustomError {3}"), 0);
  762. });
  763. Error FE4 =
  764. joinErrors(createFileError("file.bin", make_error<CustomError>(41)),
  765. createFileError("file2.bin", make_error<CustomError>(42)));
  766. EXPECT_EQ(toString(std::move(FE4))
  767. .compare("'file.bin': CustomError {41}\n"
  768. "'file2.bin': CustomError {42}"),
  769. 0);
  770. }
  771. enum class test_error_code {
  772. unspecified = 1,
  773. error_1,
  774. error_2,
  775. };
  776. } // end anon namespace
  777. namespace std {
  778. template <>
  779. struct is_error_code_enum<test_error_code> : std::true_type {};
  780. } // namespace std
  781. namespace {
  782. const std::error_category &TErrorCategory();
  783. inline std::error_code make_error_code(test_error_code E) {
  784. return std::error_code(static_cast<int>(E), TErrorCategory());
  785. }
  786. class TestDebugError : public ErrorInfo<TestDebugError, StringError> {
  787. public:
  788. using ErrorInfo<TestDebugError, StringError >::ErrorInfo; // inherit constructors
  789. TestDebugError(const Twine &S) : ErrorInfo(S, test_error_code::unspecified) {}
  790. static char ID;
  791. };
  792. class TestErrorCategory : public std::error_category {
  793. public:
  794. const char *name() const noexcept override { return "error"; }
  795. std::string message(int Condition) const override {
  796. switch (static_cast<test_error_code>(Condition)) {
  797. case test_error_code::unspecified:
  798. return "An unknown error has occurred.";
  799. case test_error_code::error_1:
  800. return "Error 1.";
  801. case test_error_code::error_2:
  802. return "Error 2.";
  803. }
  804. llvm_unreachable("Unrecognized test_error_code");
  805. }
  806. };
  807. static llvm::ManagedStatic<TestErrorCategory> TestErrCategory;
  808. const std::error_category &TErrorCategory() { return *TestErrCategory; }
  809. char TestDebugError::ID;
  810. TEST(Error, SubtypeStringErrorTest) {
  811. auto E1 = make_error<TestDebugError>(test_error_code::error_1);
  812. EXPECT_EQ(toString(std::move(E1)).compare("Error 1."), 0);
  813. auto E2 = make_error<TestDebugError>(test_error_code::error_1,
  814. "Detailed information");
  815. EXPECT_EQ(toString(std::move(E2)).compare("Error 1. Detailed information"),
  816. 0);
  817. auto E3 = make_error<TestDebugError>(test_error_code::error_2);
  818. handleAllErrors(std::move(E3), [](const TestDebugError &F) {
  819. EXPECT_EQ(F.message().compare("Error 2."), 0);
  820. });
  821. auto E4 = joinErrors(make_error<TestDebugError>(test_error_code::error_1,
  822. "Detailed information"),
  823. make_error<TestDebugError>(test_error_code::error_2));
  824. EXPECT_EQ(toString(std::move(E4))
  825. .compare("Error 1. Detailed information\n"
  826. "Error 2."),
  827. 0);
  828. }
  829. } // namespace