typecast_test.cxx 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. //
  2. // typecast_test.cxx
  3. // reflection-test
  4. //
  5. // Created by Sam Jaffe on 7/5/22.
  6. // Copyright © 2022 Sam Jaffe. All rights reserved.
  7. //
  8. #define REFLECTION_TYPE_CAST_IMPLEMENTATION
  9. #include "reflection/typecast.h"
  10. #include "xcode_gtest_helper.h"
  11. using reflection::Object;
  12. using reflection::TypeCast;
  13. using testing::Eq;
  14. using testing::NotNull;
  15. enum class Status { OK, BAD_INPUT, INTERNAL_ERROR };
  16. std::string status_to_string(Status status) {
  17. switch (status) {
  18. case Status::OK:
  19. return "OK";
  20. case Status::BAD_INPUT:
  21. return "BAD";
  22. case Status::INTERNAL_ERROR:
  23. return "ERROR";
  24. }
  25. }
  26. Status status_from_string(std::string const & str) {
  27. if (str == "OK")
  28. return Status::OK;
  29. else if (str == "BAD")
  30. return Status::BAD_INPUT;
  31. else if (str == "ERROR")
  32. return Status::INTERNAL_ERROR;
  33. throw std::invalid_argument(str);
  34. }
  35. namespace reflection {
  36. INSTANTIATE_REFLECTION_TYPECAST(Status);
  37. REFLECTION_TYPE_CAST(Status).bind<int>().bind(&status_from_string,
  38. &status_to_string);
  39. }
  40. TEST(TypeCastTest, CanPerformTypeCoercion) {
  41. Object stat(Status::OK);
  42. EXPECT_THAT(Status(stat), Eq(Status::OK));
  43. EXPECT_THAT(int(stat), Eq(0));
  44. std::string str(stat);
  45. EXPECT_THAT(str, Eq("OK"));
  46. }