test_detail_random_provider.cpp 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. //
  2. // Copyright (c) 2017 James E. King III
  3. //
  4. // Distributed under the Boost Software License, Version 1.0.
  5. // (See accompanying file LICENSE_1_0.txt or copy at
  6. // https://www.boost.org/LICENSE_1_0.txt)
  7. //
  8. // Positive and negative testing for detail::random_provider
  9. //
  10. #include <boost/array.hpp>
  11. #include <boost/cstdint.hpp>
  12. #include <boost/detail/lightweight_test.hpp>
  13. // The mock needs to load first for posix system call redirection to work properly
  14. #include "mock_random.hpp"
  15. #include <boost/uuid/detail/random_provider.hpp>
  16. #include <boost/uuid/uuid.hpp>
  17. #include <boost/uuid/uuid_io.hpp>
  18. #include <limits>
  19. #include <string.h>
  20. int main(int, char*[])
  21. {
  22. #if !defined(BOOST_UUID_TEST_RANDOM_MOCK) // Positive Testing
  23. boost::uuids::detail::random_provider provider;
  24. boost::array<unsigned int, 2> ints;
  25. // test generator()
  26. ints[0] = 0;
  27. ints[1] = 0;
  28. provider.generate(ints.begin(), ints.end());
  29. BOOST_TEST_NE(ints[0], ints[1]);
  30. // test name()
  31. BOOST_TEST_GT(strlen(provider.name()), 4u);
  32. // test get_random_bytes()
  33. char buf1[64];
  34. char buf2[64];
  35. provider.get_random_bytes(buf1, 64);
  36. provider.get_random_bytes(buf2, 64);
  37. BOOST_TEST_NE(0, memcmp(buf1, buf2, 64));
  38. #else // Negative Testing
  39. if (expectations_capable())
  40. {
  41. // Test fail acquiring context if the provider supports it
  42. if (provider_acquires_context())
  43. {
  44. expect_next_call_success(false);
  45. BOOST_TEST_THROWS(boost::uuids::detail::random_provider(),
  46. boost::uuids::entropy_error);
  47. BOOST_TEST(expectations_met());
  48. }
  49. // Test fail acquiring entropy
  50. if (provider_acquires_context())
  51. {
  52. expect_next_call_success(true);
  53. }
  54. expect_next_call_success(false);
  55. // 4 is important for the posix negative test (partial read) to work properly
  56. // as it sees a size of 4, returns 1, causing a 2nd loop to read 3 more bytes...
  57. char buf[4];
  58. BOOST_TEST_THROWS(boost::uuids::detail::random_provider().get_random_bytes(buf, 4),
  59. boost::uuids::entropy_error);
  60. BOOST_TEST(expectations_met());
  61. }
  62. #endif
  63. return boost::report_errors();
  64. }