// // scope_guard_tc.h // scope_guard // // Created by Sam Jaffe on 1/10/17. // #include #include #include "xcode_gtest_helper.h" using testing::NotNull; using testing::IsNull; using ptr = std::shared_ptr; ptr make( int i ) { return std::make_shared(i); } #if __cplusplus > 201402L struct example { ~example() { scope(success) { ++(*_p); }; } ptr _p; }; #endif TEST(Scope, ExitCallsFunction) { ptr p = make( 5 ); { scope(exit) { p.reset(); }; EXPECT_THAT(p, NotNull()); } EXPECT_THAT(p, IsNull()); } #if __cplusplus > 201402L TEST(ScopeFailure, NoOpOnNoexcept) { ptr p = make( 5 ); try { scope(failure) { p.reset(); }; } catch (...) { } EXPECT_THAT(p, NotNull()); } TEST(ScopeFailure, RunsOnException) { ptr p = make( 5 ); try { scope(failure) { p.reset(); }; throw 5; } catch (...) { } EXPECT_THAT(p, IsNull()); } TEST(ScopeSuccess, RunsOnNoexcept) { ptr p = make( 5 ); try { scope(success) { p.reset(); }; } catch (...) { } EXPECT_THAT(p, IsNull()); } TEST(ScopeSuccess, NoOpOnException) { ptr p = make( 5 ); try { scope(success) { p.reset(); }; throw 5; } catch (...) { } EXPECT_THAT(p, NotNull()); } TEST(Scope, CanLayer) { ptr p = make( 5 ); ptr r = p; try { scope(failure) { p.reset(); }; example ex { r }; throw 5; } catch (...) { } EXPECT_THAT(p, IsNull()); EXPECT_EQ(*r, 6); } #endif