match_test.cc 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // Copyright 2021 gRPC authors.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #include "src/core/lib/gprpp/match.h"
  15. #include <gtest/gtest.h>
  16. namespace grpc_core {
  17. namespace testing {
  18. TEST(MatchTest, Test) {
  19. EXPECT_EQ(Match(
  20. absl::variant<int, double>(1.9), [](int) -> int { abort(); },
  21. [](double x) -> int {
  22. EXPECT_EQ(x, 1.9);
  23. return 42;
  24. }),
  25. 42);
  26. EXPECT_EQ(Match(
  27. absl::variant<int, double>(3),
  28. [](int x) -> int {
  29. EXPECT_EQ(x, 3);
  30. return 42;
  31. },
  32. [](double) -> int { abort(); }),
  33. 42);
  34. }
  35. TEST(MatchTest, TestVoidReturn) {
  36. bool triggered = false;
  37. Match(
  38. absl::variant<int, double>(1.9), [](int) { abort(); },
  39. [&triggered](double x) {
  40. EXPECT_EQ(x, 1.9);
  41. triggered = true;
  42. });
  43. EXPECT_TRUE(triggered);
  44. }
  45. TEST(MatchTest, TestMutable) {
  46. absl::variant<int, double> v = 1.9;
  47. MatchMutable(
  48. &v, [](int*) { abort(); }, [](double* x) { *x = 0.0; });
  49. EXPECT_EQ(v, (absl::variant<int, double>(0.0)));
  50. }
  51. TEST(MatchTest, TestMutableWithReturn) {
  52. absl::variant<int, double> v = 1.9;
  53. EXPECT_EQ(MatchMutable(
  54. &v, [](int*) -> int { abort(); },
  55. [](double* x) -> int {
  56. *x = 0.0;
  57. return 1;
  58. }),
  59. 1);
  60. EXPECT_EQ(v, (absl::variant<int, double>(0.0)));
  61. }
  62. } // namespace testing
  63. } // namespace grpc_core
  64. int main(int argc, char** argv) {
  65. ::testing::InitGoogleTest(&argc, argv);
  66. return RUN_ALL_TESTS();
  67. }