key_value_iterable_view_test.cc 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // Copyright The OpenTelemetry Authors
  2. // SPDX-License-Identifier: Apache-2.0
  3. #include <gtest/gtest.h>
  4. #include <map>
  5. #include <string>
  6. #include <utility>
  7. #include <vector>
  8. #include "opentelemetry/common/attribute_value.h"
  9. #include "opentelemetry/common/key_value_iterable.h"
  10. #include "opentelemetry/common/key_value_iterable_view.h"
  11. #include "opentelemetry/nostd/function_ref.h"
  12. #include "opentelemetry/nostd/string_view.h"
  13. #include "opentelemetry/nostd/type_traits.h"
  14. using namespace opentelemetry;
  15. static int TakeKeyValues(const common::KeyValueIterable &iterable)
  16. {
  17. std::map<std::string, common::AttributeValue> result;
  18. int count = 0;
  19. iterable.ForEachKeyValue(
  20. [&](nostd::string_view /* key */, common::AttributeValue /* value */) noexcept {
  21. ++count;
  22. return true;
  23. });
  24. return count;
  25. }
  26. template <class T, nostd::enable_if_t<common::detail::is_key_value_iterable<T>::value> * = nullptr>
  27. static int TakeKeyValues(const T &iterable)
  28. {
  29. return TakeKeyValues(common::KeyValueIterableView<T>{iterable});
  30. }
  31. TEST(KeyValueIterableViewTest, is_key_value_iterable)
  32. {
  33. using M1 = std::map<std::string, std::string>;
  34. EXPECT_TRUE(bool{common::detail::is_key_value_iterable<M1>::value});
  35. using M2 = std::map<std::string, int>;
  36. EXPECT_TRUE(bool{common::detail::is_key_value_iterable<M2>::value});
  37. using M3 = std::map<std::string, common::AttributeValue>;
  38. EXPECT_TRUE(bool{common::detail::is_key_value_iterable<M3>::value});
  39. struct A
  40. {};
  41. using M4 = std::map<std::string, A>;
  42. EXPECT_FALSE(bool{common::detail::is_key_value_iterable<M4>::value});
  43. }
  44. TEST(KeyValueIterableViewTest, ForEachKeyValue)
  45. {
  46. std::map<std::string, std::string> m1 = {{"abc", "123"}, {"xyz", "456"}};
  47. EXPECT_EQ(TakeKeyValues(m1), 2);
  48. std::vector<std::pair<std::string, int>> v1 = {{"abc", 123}, {"xyz", 456}};
  49. EXPECT_EQ(TakeKeyValues(v1), 2);
  50. }
  51. TEST(KeyValueIterableViewTest, ForEachKeyValueWithExit)
  52. {
  53. using M = std::map<std::string, std::string>;
  54. M m1 = {{"abc", "123"}, {"xyz", "456"}};
  55. common::KeyValueIterableView<M> iterable{m1};
  56. int count = 0;
  57. auto exit = iterable.ForEachKeyValue(
  58. [&count](nostd::string_view /*key*/, common::AttributeValue /*value*/) noexcept {
  59. ++count;
  60. return false;
  61. });
  62. EXPECT_EQ(count, 1);
  63. EXPECT_FALSE(exit);
  64. }