You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

97 lines
2.4KB

  1. /*
  2. * Scope Guard
  3. * Copyright (C) 2017 offa
  4. *
  5. * This file is part of Scope Guard.
  6. *
  7. * Scope Guard is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation, either version 3 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * Scope Guard is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with Scope Guard. If not, see <http://www.gnu.org/licenses/>.
  19. */
  20. #include "scope_guard.h"
  21. #include <catch.hpp>
  22. #include <trompeloeil.hpp>
  23. using namespace trompeloeil;
  24. namespace
  25. {
  26. struct CallMock
  27. {
  28. MAKE_MOCK0(deleter, void());
  29. };
  30. CallMock m;
  31. void deleter()
  32. {
  33. m.deleter();
  34. }
  35. }
  36. TEST_CASE("deleter called on destruction", "[ScopeGuard]")
  37. {
  38. REQUIRE_CALL(m, deleter());
  39. auto guard = sr::scope_guard(deleter);
  40. static_cast<void>(guard);
  41. }
  42. TEST_CASE("deleter is not called if released", "[ScopeGuard]")
  43. {
  44. REQUIRE_CALL(m, deleter()).TIMES(0);
  45. auto guard = sr::scope_guard(deleter);
  46. guard.release();
  47. }
  48. TEST_CASE("deleter lambda called on destruction", "[ScopeGuard]")
  49. {
  50. CallMock cm;
  51. REQUIRE_CALL(cm, deleter());
  52. auto guard = sr::scope_guard([&cm] { cm.deleter(); });
  53. static_cast<void>(guard);
  54. }
  55. TEST_CASE("move releases moved-from object", "[ScopeGuard]")
  56. {
  57. REQUIRE_CALL(m, deleter());
  58. auto movedFrom = sr::scope_guard(deleter);
  59. auto guard = std::move(movedFrom);
  60. static_cast<void>(guard);
  61. }
  62. TEST_CASE("move transfers state", "[ScopeGuard]")
  63. {
  64. REQUIRE_CALL(m, deleter());
  65. auto movedFrom = sr::scope_guard(deleter);
  66. auto guard = std::move(movedFrom);
  67. static_cast<void>(guard);
  68. }
  69. TEST_CASE("move transfers state if released", "[ScopeGuard]")
  70. {
  71. REQUIRE_CALL(m, deleter()).TIMES(0);
  72. auto movedFrom = sr::scope_guard(deleter);
  73. movedFrom.release();
  74. auto guard = std::move(movedFrom);
  75. static_cast<void>(guard);
  76. }
  77. TEST_CASE("no exception propagation from deleter", "[ScopeGuard]")
  78. {
  79. REQUIRE_NOTHROW([] {
  80. auto guard = sr::scope_guard([] { throw std::exception{}; });
  81. static_cast<void>(guard);
  82. }());
  83. }