static_throwing_pre.cpp 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // Copyright (C) 2008-2018 Lorenzo Caminiti
  2. // Distributed under the Boost Software License, Version 1.0 (see accompanying
  3. // file LICENSE_1_0.txt or a copy at http://www.boost.org/LICENSE_1_0.txt).
  4. // See: http://www.boost.org/doc/libs/release/libs/contract/doc/html/index.html
  5. // Test throw from public static member function .pre().
  6. #include "../detail/oteststream.hpp"
  7. #include <boost/contract/public_function.hpp>
  8. #include <boost/contract/check.hpp>
  9. #include <boost/detail/lightweight_test.hpp>
  10. #include <sstream>
  11. boost::contract::test::detail::oteststream out;
  12. struct a_err {}; // Global decl so visible in MSVC10 lambdas.
  13. struct a {
  14. static void static_invariant() { out << "a::static_inv" << std::endl; }
  15. void invariant() const { out << "a::inv" << std::endl; }
  16. static void f() {
  17. boost::contract::check c = boost::contract::public_function<a>()
  18. .precondition([] {
  19. out << "a::f::pre" << std::endl;
  20. throw a_err(); // Test this throws.
  21. })
  22. .old([] { out << "a::f::old" << std::endl; })
  23. .postcondition([] { out << "a::f::post" << std::endl; })
  24. .except([] { out << "a::f::except" << std::endl; })
  25. ;
  26. out << "a::f::body" << std::endl;
  27. }
  28. };
  29. int main() {
  30. std::ostringstream ok;
  31. boost::contract::set_precondition_failure(
  32. [] (boost::contract::from) { throw; });
  33. try {
  34. out.str("");
  35. a::f();
  36. #ifndef BOOST_CONTRACT_NO_PRECONDITIONS
  37. BOOST_TEST(false);
  38. } catch(a_err const&) {
  39. #endif
  40. ok.str(""); ok
  41. #ifndef BOOST_CONTRACT_NO_ENTRY_INVARIANTS
  42. << "a::static_inv" << std::endl
  43. #endif
  44. #ifndef BOOST_CONTRACT_NO_PRECONDITIONS
  45. << "a::f::pre" << std::endl // Test this threw.
  46. #else
  47. #ifndef BOOST_CONTRACT_NO_OLDS
  48. << "a::f::old" << std::endl
  49. #endif
  50. << "a::f::body" << std::endl
  51. #ifndef BOOST_CONTRACT_NO_EXIT_INVARIANTS
  52. << "a::static_inv" << std::endl
  53. #endif
  54. #ifndef BOOST_CONTRACT_NO_POSTCONDITIONS
  55. << "a::f::post" << std::endl
  56. #endif
  57. #endif
  58. ;
  59. BOOST_TEST(out.eq(ok.str()));
  60. } catch(...) { BOOST_TEST(false); }
  61. return boost::report_errors();
  62. }