throwing_pre.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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 free function .pre().
  6. #include "../detail/oteststream.hpp"
  7. #include <boost/contract/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 err {}; // Global decl so visible in MSVC10 lambdas.
  13. void f() {
  14. boost::contract::check c = boost::contract::function()
  15. .precondition([] {
  16. out << "f::pre" << std::endl;
  17. throw err(); // Test this throws.
  18. })
  19. .old([] { out << "f::old" << std::endl; })
  20. .postcondition([] { out << "f::post" << std::endl; })
  21. .except([] { out << "f::except" << std::endl; })
  22. ;
  23. out << "f::body" << std::endl;
  24. }
  25. int main() {
  26. std::ostringstream ok;
  27. boost::contract::set_precondition_failure(
  28. [] (boost::contract::from) { throw; });
  29. try {
  30. out.str("");
  31. f();
  32. #ifndef BOOST_CONTRACT_NO_PRECONDITIONS
  33. BOOST_TEST(false);
  34. } catch(err const&) {
  35. #endif
  36. ok.str(""); ok
  37. #ifndef BOOST_CONTRACT_NO_PRECONDITIONS
  38. << "f::pre" << std::endl // Test this threw.
  39. #else
  40. #ifndef BOOST_CONTRACT_NO_OLDS
  41. << "f::old" << std::endl
  42. #endif
  43. << "f::body" << std::endl
  44. #ifndef BOOST_CONTRACT_NO_POSTCONDITIONS
  45. << "f::post" << std::endl
  46. #endif
  47. #endif
  48. ;
  49. BOOST_TEST(out.eq(ok.str()));
  50. } catch(...) { BOOST_TEST(false); }
  51. return boost::report_errors();
  52. }