ifdef.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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 contract compilation on/off.
  6. #include "../detail/oteststream.hpp"
  7. #include <boost/contract/core/config.hpp>
  8. #ifndef BOOST_CONTRACT_NO_CHECKS
  9. #include <boost/contract/check.hpp>
  10. #include <boost/contract/assert.hpp>
  11. #else
  12. #include <boost/contract/core/check_macro.hpp>
  13. #include <boost/contract/core/exception.hpp>
  14. #endif
  15. #include <boost/detail/lightweight_test.hpp>
  16. #include <sstream>
  17. boost::contract::test::detail::oteststream out;
  18. void f(bool check1, bool check2) {
  19. BOOST_CONTRACT_CHECK([&] () -> bool { // Macro already so #ifdef needed.
  20. out << "f::check1" << std::endl;
  21. return check1;
  22. }());
  23. #ifndef BOOST_CONTRACT_NO_CHECKS
  24. boost::contract::check c = [&] {
  25. out << "f::check2" << std::endl;
  26. BOOST_CONTRACT_ASSERT(check2);
  27. };
  28. #endif
  29. out << "f::body" << std::endl;
  30. }
  31. struct err {}; // Global decl so visible in MSVC10 lambdas.
  32. int main() {
  33. std::ostringstream ok;
  34. out.str("");
  35. f(true, true);
  36. ok.str(""); ok
  37. #ifndef BOOST_CONTRACT_NO_CHECKS
  38. << "f::check1" << std::endl
  39. << "f::check2" << std::endl
  40. #endif
  41. << "f::body" << std::endl
  42. ;
  43. BOOST_TEST(out.eq(ok.str()));
  44. boost::contract::set_check_failure([] { throw err(); });
  45. out.str("");
  46. try {
  47. f(false, true);
  48. #ifndef BOOST_CONTRACT_NO_CHECKS
  49. BOOST_TEST(false);
  50. } catch(err const&) {
  51. ok.str("");
  52. ok << "f::check1" << std::endl;
  53. #else
  54. ok.str("");
  55. ok << "f::body" << std::endl;
  56. #endif
  57. BOOST_TEST(out.eq(ok.str()));
  58. } catch(...) { BOOST_TEST(false); }
  59. out.str("");
  60. try {
  61. f(true, false);
  62. #ifndef BOOST_CONTRACT_NO_CHECKS
  63. BOOST_TEST(false);
  64. } catch(err const&) {
  65. ok.str("");
  66. ok << "f::check1" << std::endl;
  67. ok << "f::check2" << std::endl;
  68. #else
  69. ok.str("");
  70. ok << "f::body" << std::endl;
  71. #endif
  72. BOOST_TEST(out.eq(ok.str()));
  73. } catch(...) { BOOST_TEST(false); }
  74. // No need to test `f(false, false)` because same as `f(false, true)`.
  75. return boost::report_errors();
  76. }