var_unittest.cc 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /*
  2. Copyright (c) 2023 Sogou, Inc.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. #include <stdio.h>
  14. #include <sys/types.h>
  15. #include <sys/stat.h>
  16. #include <fcntl.h>
  17. #include <string.h>
  18. #include <string>
  19. #include <mutex>
  20. #include <condition_variable>
  21. #include <chrono>
  22. #include <gtest/gtest.h>
  23. #include "srpc/rpc_var.h"
  24. using namespace srpc;
  25. RPCVar *get_and_reduce(std::string&& var_name)
  26. {
  27. RPCVar *result = NULL;
  28. RPCVarGlobal *global_var = RPCVarGlobal::get_instance();
  29. std::unordered_map<std::string, RPCVar *>::iterator it;
  30. global_var->mutex.lock();
  31. for (RPCVarLocal *local : global_var->local_vars)
  32. {
  33. local->mutex.lock();
  34. it = local->vars.find(var_name);
  35. if (it != local->vars.end())
  36. {
  37. if (result == NULL)
  38. result = it->second->create(true);
  39. else
  40. result->reduce(it->second->get_data(), it->second->get_size());
  41. }
  42. local->mutex.unlock();
  43. }
  44. global_var->mutex.unlock();
  45. return result;
  46. }
  47. TEST(var_unittest, GaugeVar)
  48. {
  49. GaugeVar *req = new GaugeVar("req", "total req");
  50. RPCVarLocal::get_instance()->add("req", req);
  51. RPCVarFactory::gauge("req")->increase();
  52. GaugeVar *gauge = (GaugeVar *)get_and_reduce("req");
  53. EXPECT_EQ(gauge->get(), 1.0);
  54. delete gauge;
  55. }
  56. TEST(var_unittest, TimedGaugeVar)
  57. {
  58. TimedGaugeVar *qps = new TimedGaugeVar("qps", "req per second",
  59. std::chrono::seconds(1), 4);
  60. RPCVarLocal::get_instance()->add("qps", qps);
  61. RPCVarFactory::gauge("qps")->increase();
  62. RPCVarFactory::gauge("qps")->increase();
  63. GaugeVar *gauge = (GaugeVar *)get_and_reduce("qps");
  64. EXPECT_EQ(gauge->get(), 2.0);
  65. delete gauge;
  66. usleep(500000);
  67. RPCVarFactory::gauge("qps")->increase();
  68. gauge = (GaugeVar *)get_and_reduce("qps");
  69. EXPECT_EQ(gauge->get(), 3.0);
  70. delete gauge;
  71. usleep(500000);
  72. gauge = (GaugeVar *)get_and_reduce("qps");
  73. EXPECT_EQ(gauge->get(), 1.0);
  74. delete gauge;
  75. }