OptionalCoroutinesTest.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. /*
  2. * Copyright 2017-present Facebook, Inc.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include <folly/Optional.h>
  17. #include <folly/Portability.h>
  18. #include <folly/ScopeGuard.h>
  19. #include <folly/portability/GTest.h>
  20. #if FOLLY_HAS_COROUTINES
  21. using folly::Optional;
  22. Optional<int> f1() {
  23. return 7;
  24. }
  25. Optional<double> f2(int x) {
  26. return 2.0 * x;
  27. }
  28. // move-only type
  29. Optional<std::unique_ptr<int>> f3(int x, double y) {
  30. return std::make_unique<int>((int)(x + y));
  31. }
  32. TEST(Optional, CoroutineSuccess) {
  33. auto r0 = []() -> Optional<int> {
  34. auto x = co_await f1();
  35. EXPECT_EQ(7, x);
  36. auto y = co_await f2(x);
  37. EXPECT_EQ(2.0 * 7, y);
  38. auto z = co_await f3(x, y);
  39. EXPECT_EQ((int)(2.0 * 7 + 7), *z);
  40. co_return* z;
  41. }();
  42. EXPECT_TRUE(r0.hasValue());
  43. EXPECT_EQ(21, *r0);
  44. }
  45. Optional<int> f4(int, double) {
  46. return folly::none;
  47. }
  48. TEST(Optional, CoroutineFailure) {
  49. auto r1 = []() -> Optional<int> {
  50. auto x = co_await f1();
  51. auto y = co_await f2(x);
  52. auto z = co_await f4(x, y);
  53. ADD_FAILURE();
  54. co_return z;
  55. }();
  56. EXPECT_TRUE(!r1.hasValue());
  57. }
  58. Optional<int> throws() {
  59. throw 42;
  60. }
  61. TEST(Optional, CoroutineException) {
  62. try {
  63. auto r2 = []() -> Optional<int> {
  64. auto x = co_await throws();
  65. ADD_FAILURE();
  66. co_return x;
  67. }();
  68. (void)r2;
  69. ADD_FAILURE();
  70. } catch (/* nolint */ int i) {
  71. EXPECT_EQ(42, i);
  72. } catch (...) {
  73. ADD_FAILURE();
  74. }
  75. }
  76. // this test makes sure that the coroutine is destroyed properly
  77. TEST(Optional, CoroutineCleanedUp) {
  78. int count_dest = 0;
  79. auto r = [&]() -> Optional<int> {
  80. SCOPE_EXIT {
  81. ++count_dest;
  82. };
  83. auto x = co_await folly::Optional<int>();
  84. ADD_FAILURE() << "Should not be resuming";
  85. co_return x;
  86. }();
  87. EXPECT_FALSE(r.hasValue());
  88. EXPECT_EQ(1, count_dest);
  89. }
  90. #endif