scope_guard.cxx 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. //
  2. // scope_guard_tc.h
  3. // scope_guard
  4. //
  5. // Created by Sam Jaffe on 1/10/17.
  6. //
  7. #include <memory>
  8. #include <scope_guard/scope_guard.hpp>
  9. #include "xcode_gtest_helper.h"
  10. using testing::NotNull;
  11. using testing::IsNull;
  12. using ptr = std::shared_ptr<int>;
  13. ptr make( int i ) { return std::make_shared<int>(i); }
  14. #if __cplusplus > 201402L
  15. struct example {
  16. ~example() {
  17. scope(success) { ++(*_p); };
  18. }
  19. ptr _p;
  20. };
  21. #endif
  22. TEST(Scope, ExitCallsFunction) {
  23. ptr p = make( 5 );
  24. {
  25. scope(exit) { p.reset(); };
  26. EXPECT_THAT(p, NotNull());
  27. }
  28. EXPECT_THAT(p, IsNull());
  29. }
  30. #if __cplusplus > 201402L
  31. TEST(ScopeFailure, NoOpOnNoexcept) {
  32. ptr p = make( 5 );
  33. try {
  34. scope(failure) { p.reset(); };
  35. } catch (...) {
  36. }
  37. EXPECT_THAT(p, NotNull());
  38. }
  39. TEST(ScopeFailure, RunsOnException) {
  40. ptr p = make( 5 );
  41. try {
  42. scope(failure) { p.reset(); };
  43. throw 5;
  44. } catch (...) {
  45. }
  46. EXPECT_THAT(p, IsNull());
  47. }
  48. TEST(ScopeSuccess, RunsOnNoexcept) {
  49. ptr p = make( 5 );
  50. try {
  51. scope(success) { p.reset(); };
  52. } catch (...) {
  53. }
  54. EXPECT_THAT(p, IsNull());
  55. }
  56. TEST(ScopeSuccess, NoOpOnException) {
  57. ptr p = make( 5 );
  58. try {
  59. scope(success) { p.reset(); };
  60. throw 5;
  61. } catch (...) {
  62. }
  63. EXPECT_THAT(p, NotNull());
  64. }
  65. TEST(Scope, CanLayer) {
  66. ptr p = make( 5 );
  67. ptr r = p;
  68. try {
  69. scope(failure) { p.reset(); };
  70. example ex { r };
  71. throw 5;
  72. } catch (...) {
  73. }
  74. EXPECT_THAT(p, IsNull());
  75. EXPECT_EQ(*r, 6);
  76. }
  77. #endif