3 * Copyright 2015 gRPC authors.
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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
21 #include <grpc/support/alloc.h>
22 #include <grpc/support/log.h>
24 #include "src/core/lib/gprpp/host_port.h"
25 #include "test/core/util/test_config.h"
27 static void join_host_port_expect(const char* host, int port,
28 const char* expected) {
29 std::string actual = grpc_core::JoinHostPort(host, port);
30 GPR_ASSERT(actual == expected);
33 static void test_join_host_port(void) {
34 join_host_port_expect("foo", 101, "foo:101");
35 join_host_port_expect("", 102, ":102");
36 join_host_port_expect("1::2", 103, "[1::2]:103");
37 join_host_port_expect("[::1]", 104, "[::1]:104");
40 /* Garbage in, garbage out. */
41 static void test_join_host_port_garbage(void) {
42 join_host_port_expect("[foo]", 105, "[foo]:105");
43 join_host_port_expect("[::", 106, "[:::106");
44 join_host_port_expect("::]", 107, "[::]]:107");
47 static void split_host_port_expect(const char* name, const char* host,
48 const char* port, bool ret) {
49 std::string actual_host;
50 std::string actual_port;
51 const bool actual_ret =
52 grpc_core::SplitHostPort(name, &actual_host, &actual_port);
53 GPR_ASSERT(actual_ret == ret);
54 GPR_ASSERT(actual_host == (host == nullptr ? "" : host));
55 GPR_ASSERT(actual_port == (port == nullptr ? "" : port));
58 static void test_split_host_port() {
59 split_host_port_expect("", "", nullptr, true);
60 split_host_port_expect("[a:b]", "a:b", nullptr, true);
61 split_host_port_expect("1.2.3.4", "1.2.3.4", nullptr, true);
62 split_host_port_expect("0.0.0.0:", "0.0.0.0", "", true);
63 split_host_port_expect("a:b:c::", "a:b:c::", nullptr, true);
64 split_host_port_expect("[a:b:c::]:", "a:b:c::", "", true);
65 split_host_port_expect("[a:b]:30", "a:b", "30", true);
66 split_host_port_expect("1.2.3.4:30", "1.2.3.4", "30", true);
67 split_host_port_expect(":30", "", "30", true);
70 static void test_split_host_port_invalid() {
71 split_host_port_expect("[a:b", nullptr, nullptr, false);
72 split_host_port_expect("[a:b]30", nullptr, nullptr, false);
75 int main(int argc, char** argv) {
76 grpc::testing::TestEnvironment env(argc, argv);
78 test_join_host_port();
79 test_join_host_port_garbage();
80 test_split_host_port();
81 test_split_host_port_invalid();