time_test.cc 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. *
  3. * Copyright 2015 gRPC authors.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. #include <gtest/gtest.h>
  19. #include <grpc/support/time.h>
  20. #include <grpcpp/support/time.h>
  21. #include "test/core/util/test_config.h"
  22. using std::chrono::microseconds;
  23. using std::chrono::system_clock;
  24. namespace grpc {
  25. namespace {
  26. class TimeTest : public ::testing::Test {};
  27. TEST_F(TimeTest, AbsolutePointTest) {
  28. int64_t us = 10000000L;
  29. gpr_timespec ts = gpr_time_from_micros(us, GPR_TIMESPAN);
  30. ts.clock_type = GPR_CLOCK_REALTIME;
  31. system_clock::time_point tp{microseconds(us)};
  32. system_clock::time_point tp_converted = Timespec2Timepoint(ts);
  33. gpr_timespec ts_converted;
  34. Timepoint2Timespec(tp_converted, &ts_converted);
  35. EXPECT_TRUE(ts.tv_sec == ts_converted.tv_sec);
  36. EXPECT_TRUE(ts.tv_nsec == ts_converted.tv_nsec);
  37. system_clock::time_point tp_converted_2 = Timespec2Timepoint(ts_converted);
  38. EXPECT_TRUE(tp == tp_converted);
  39. EXPECT_TRUE(tp == tp_converted_2);
  40. }
  41. // gpr_inf_future is treated specially and mapped to/from time_point::max()
  42. TEST_F(TimeTest, InfFuture) {
  43. EXPECT_EQ(system_clock::time_point::max(),
  44. Timespec2Timepoint(gpr_inf_future(GPR_CLOCK_REALTIME)));
  45. gpr_timespec from_time_point_max;
  46. Timepoint2Timespec(system_clock::time_point::max(), &from_time_point_max);
  47. EXPECT_EQ(
  48. 0, gpr_time_cmp(gpr_inf_future(GPR_CLOCK_REALTIME), from_time_point_max));
  49. // This will cause an overflow
  50. Timepoint2Timespec(
  51. std::chrono::time_point<system_clock, std::chrono::seconds>::max(),
  52. &from_time_point_max);
  53. EXPECT_EQ(
  54. 0, gpr_time_cmp(gpr_inf_future(GPR_CLOCK_REALTIME), from_time_point_max));
  55. }
  56. } // namespace
  57. } // namespace grpc
  58. int main(int argc, char** argv) {
  59. grpc::testing::TestEnvironment env(argc, argv);
  60. ::testing::InitGoogleTest(&argc, argv);
  61. return RUN_ALL_TESTS();
  62. }