pgsql_exchange_unittest.cc 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Copyright (C) 2016 Internet Systems Consortium, Inc. ("ISC")
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this
  5. // file, You can obtain one at http://mozilla.org/MPL/2.0/.
  6. #include <config.h>
  7. #include <dhcpsrv/pgsql_exchange.h>
  8. #include <boost/lexical_cast.hpp>
  9. #include <gtest/gtest.h>
  10. using namespace isc;
  11. using namespace isc::dhcp;
  12. namespace {
  13. /// @brief Converts a time_t into a string matching our Postgres input format
  14. ///
  15. /// @param time_val Time value to convert
  16. /// @retrun A string containing the converted time
  17. std::string timeToDbString(const time_t time_val) {
  18. struct tm tinfo;
  19. char buffer[20];
  20. localtime_r(&time_val, &tinfo);
  21. strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", &tinfo);
  22. return(std::string(buffer));
  23. }
  24. /// @brief Basic checks on time conversion functions in PgSqlExchange
  25. /// We input timestamps as date/time strings and we output them as
  26. /// an integer string of seconds since the epoch. There is no meangingful
  27. /// way to test them round-trip without Postgres involved.
  28. TEST(PgSqlExchangeTest, convertTimeTest) {
  29. // Get a reference time and time string
  30. time_t ref_time;
  31. time(&ref_time);
  32. std::string ref_time_str(timeToDbString(ref_time));
  33. // Verify convertToDatabaseTime gives us the expected localtime string
  34. std::string time_str = PgSqlExchange::convertToDatabaseTime(ref_time);
  35. EXPECT_EQ(time_str, ref_time_str);
  36. // Verify convertToDatabaseTime with valid_lifetime = 0 gives us the
  37. // expected localtime string
  38. time_str = PgSqlExchange::convertToDatabaseTime(ref_time, 0);
  39. EXPECT_EQ(time_str, ref_time_str);
  40. // Verify we can add time by adding a day.
  41. ref_time_str = timeToDbString(ref_time + (24*3600));
  42. ASSERT_NO_THROW(time_str = PgSqlExchange::convertToDatabaseTime(ref_time,
  43. 24*3600));
  44. EXPECT_EQ(time_str, ref_time_str);
  45. // Verify too large of a value is detected.
  46. ASSERT_THROW(PgSqlExchange::convertToDatabaseTime(DatabaseConnection::
  47. MAX_DB_TIME - 1,
  48. 24*3600),
  49. isc::BadValue);
  50. // Make sure Conversion "from" database time functions
  51. std::string ref_secs_str = boost::lexical_cast<std::string>(ref_time);
  52. time_t from_time = PgSqlExchange::convertFromDatabaseTime(ref_secs_str);
  53. from_time = PgSqlExchange::convertFromDatabaseTime(ref_secs_str);
  54. EXPECT_EQ(ref_time, from_time);
  55. }
  56. }; // namespace