scope_guard.t.h 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. //
  2. // scope_guard_tc.h
  3. // scope_guard
  4. //
  5. // Created by Sam Jaffe on 1/10/17.
  6. //
  7. #pragma once
  8. #include <cxxtest/TestSuite.h>
  9. #include <memory>
  10. #include "scope_guard.hpp"
  11. class scope_guard_TestSuite : public CxxTest::TestSuite {
  12. public:
  13. using ptr = std::shared_ptr<int>;
  14. static ptr make( int i ) { return std::make_shared<int>(i); }
  15. #if __cplusplus > 201402L
  16. struct example {
  17. ~example() {
  18. scope(success) { ++(*_p); };
  19. }
  20. ptr _p;
  21. };
  22. #endif
  23. public:
  24. void test_scope_exit_reset() const {
  25. ptr p = make( 5 );
  26. {
  27. scope(exit) { p.reset(); };
  28. TS_ASSERT( p );
  29. }
  30. TS_ASSERT( ! p );
  31. }
  32. #if __cplusplus > 201402L
  33. void test_scope_failure_no_effect() const {
  34. ptr p = make( 5 );
  35. try {
  36. scope(failure) { p.reset(); };
  37. } catch (...) {
  38. }
  39. TS_ASSERT( p );
  40. }
  41. void test_scope_failure_on_exception() const {
  42. ptr p = make( 5 );
  43. try {
  44. scope(failure) { p.reset(); };
  45. throw 5;
  46. } catch (...) {
  47. }
  48. TS_ASSERT( ! p );
  49. }
  50. void test_scope_success_works() const {
  51. ptr p = make( 5 );
  52. try {
  53. scope(success) { p.reset(); };
  54. } catch (...) {
  55. }
  56. TS_ASSERT( ! p );
  57. }
  58. void test_scope_success_on_exception_no_effect() const {
  59. ptr p = make( 5 );
  60. try {
  61. scope(success) { p.reset(); };
  62. throw 5;
  63. } catch (...) {
  64. }
  65. TS_ASSERT( p );
  66. }
  67. void test_multi_layer_scoping() const {
  68. ptr p = make( 5 );
  69. ptr r = p;
  70. try {
  71. scope(failure) { p.reset(); };
  72. example ex { r };
  73. throw 5;
  74. } catch (...) {
  75. }
  76. TS_ASSERT( ! p );
  77. TS_ASSERT_EQUALS( *r, 6 );
  78. }
  79. #endif
  80. };