brpc_naming_service_filter_unittest.cpp 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // Licensed to the Apache Software Foundation (ASF) under one
  2. // or more contributor license agreements. See the NOTICE file
  3. // distributed with this work for additional information
  4. // regarding copyright ownership. The ASF licenses this file
  5. // to you under the Apache License, Version 2.0 (the
  6. // "License"); you may not use this file except in compliance
  7. // with the License. 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,
  12. // software distributed under the License is distributed on an
  13. // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14. // KIND, either express or implied. See the License for the
  15. // specific language governing permissions and limitations
  16. // under the License.
  17. #include <stdio.h>
  18. #include <gtest/gtest.h>
  19. #include <vector>
  20. #include "butil/string_printf.h"
  21. #include "butil/files/temp_file.h"
  22. #include "brpc/socket.h"
  23. #include "brpc/channel.h"
  24. #include "brpc/load_balancer.h"
  25. #include "brpc/policy/file_naming_service.h"
  26. class NamingServiceFilterTest : public testing::Test {
  27. protected:
  28. void SetUp() {}
  29. void TearDown() {}
  30. };
  31. class MyNSFilter: public brpc::NamingServiceFilter {
  32. public:
  33. bool Accept(const brpc::ServerNode& node) const {
  34. return node.tag == "enable";
  35. }
  36. };
  37. TEST_F(NamingServiceFilterTest, sanity) {
  38. std::vector<brpc::ServerNode> servers;
  39. const char *address_list[] = {
  40. "10.127.0.1:1234",
  41. "10.128.0.1:1234 enable",
  42. "10.129.0.1:1234",
  43. "localhost:1234",
  44. "baidu.com:1234"
  45. };
  46. butil::TempFile tmp_file;
  47. {
  48. FILE* fp = fopen(tmp_file.fname(), "w");
  49. for (size_t i = 0; i < ARRAY_SIZE(address_list); ++i) {
  50. ASSERT_TRUE(fprintf(fp, "%s\n", address_list[i]));
  51. }
  52. fclose(fp);
  53. }
  54. MyNSFilter ns_filter;
  55. brpc::Channel channel;
  56. brpc::ChannelOptions opt;
  57. opt.ns_filter = &ns_filter;
  58. std::string ns = std::string("file://") + tmp_file.fname();
  59. ASSERT_EQ(0, channel.Init(ns.c_str(), "rr", &opt));
  60. butil::EndPoint ep;
  61. ASSERT_EQ(0, butil::hostname2endpoint("10.128.0.1:1234", &ep));
  62. for (int i = 0; i < 10; ++i) {
  63. brpc::SocketUniquePtr tmp_sock;
  64. brpc::LoadBalancer::SelectIn sel_in = { 0, false, false, 0, NULL };
  65. brpc::LoadBalancer::SelectOut sel_out(&tmp_sock);
  66. ASSERT_EQ(0, channel._lb->SelectServer(sel_in, &sel_out));
  67. ASSERT_EQ(ep, tmp_sock->remote_side());
  68. }
  69. }