1// Copyright 2015 The etcd Authors
2//
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//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package rafthttp
16
17import (
18	"net/url"
19	"testing"
20
21	"go.etcd.io/etcd/pkg/testutil"
22)
23
24// TestURLPickerPickTwice tests that pick returns a possible url,
25// and always returns the same one.
26func TestURLPickerPickTwice(t *testing.T) {
27	picker := mustNewURLPicker(t, []string{"http://127.0.0.1:2380", "http://127.0.0.1:7001"})
28
29	u := picker.pick()
30	urlmap := map[url.URL]bool{
31		{Scheme: "http", Host: "127.0.0.1:2380"}: true,
32		{Scheme: "http", Host: "127.0.0.1:7001"}: true,
33	}
34	if !urlmap[u] {
35		t.Errorf("url picked = %+v, want a possible url in %+v", u, urlmap)
36	}
37
38	// pick out the same url when calling pick again
39	uu := picker.pick()
40	if u != uu {
41		t.Errorf("url picked = %+v, want %+v", uu, u)
42	}
43}
44
45func TestURLPickerUpdate(t *testing.T) {
46	picker := mustNewURLPicker(t, []string{"http://127.0.0.1:2380", "http://127.0.0.1:7001"})
47	picker.update(testutil.MustNewURLs(t, []string{"http://localhost:2380", "http://localhost:7001"}))
48
49	u := picker.pick()
50	urlmap := map[url.URL]bool{
51		{Scheme: "http", Host: "localhost:2380"}: true,
52		{Scheme: "http", Host: "localhost:7001"}: true,
53	}
54	if !urlmap[u] {
55		t.Errorf("url picked = %+v, want a possible url in %+v", u, urlmap)
56	}
57}
58
59func TestURLPickerUnreachable(t *testing.T) {
60	picker := mustNewURLPicker(t, []string{"http://127.0.0.1:2380", "http://127.0.0.1:7001"})
61	u := picker.pick()
62	picker.unreachable(u)
63
64	uu := picker.pick()
65	if u == uu {
66		t.Errorf("url picked = %+v, want other possible urls", uu)
67	}
68}
69
70func mustNewURLPicker(t *testing.T, us []string) *urlPicker {
71	urls := testutil.MustNewURLs(t, us)
72	return newURLPicker(urls)
73}
74