Add pre-commit config Update default consensus with more sources Move IP version spec to Source so that dual-stack sites can be used Add tests for HTTPSource and consensus
92 lines
2.2 KiB
Go
92 lines
2.2 KiB
Go
package externalip_test
|
|
|
|
import (
|
|
"fmt"
|
|
"net"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"testing"
|
|
"time"
|
|
|
|
"git.narnian.us/lordwelch/externalip"
|
|
)
|
|
|
|
func newConcensus(url string) *externalip.Consensus {
|
|
consensus := externalip.NewConsensus(&externalip.ConsensusConfig{
|
|
Timeout: time.Second * 30,
|
|
}, nil)
|
|
|
|
// TLS-protected providers
|
|
_ = consensus.AddVoter(externalip.NewHTTPSource(url, externalip.IPv4), 1)
|
|
_ = consensus.AddVoter(externalip.NewHTTPSource(url, externalip.IPv4), 1)
|
|
_ = consensus.AddVoter(externalip.NewHTTPSource(url, externalip.IPv4), 1)
|
|
|
|
return consensus
|
|
}
|
|
|
|
func newServer(ip1, ip2, ip3 string) *httptest.Server {
|
|
var try = 1
|
|
return httptest.NewServer(http.HandlerFunc(
|
|
func(w http.ResponseWriter, r *http.Request) {
|
|
w.WriteHeader(200)
|
|
switch try {
|
|
case 1:
|
|
fmt.Fprintln(w, ip1)
|
|
case 2:
|
|
fmt.Fprintln(w, ip2)
|
|
case 3:
|
|
fmt.Fprintln(w, ip3)
|
|
try = 1
|
|
}
|
|
try++
|
|
}))
|
|
}
|
|
|
|
func TestConsensus(t *testing.T) {
|
|
server := newServer("127.0.0.1", "127.0.0.1", "127.0.0.2")
|
|
consensus := newConcensus(server.URL)
|
|
if consensus == nil {
|
|
t.Fatal("default consensus should never be nil")
|
|
}
|
|
|
|
ip, err := consensus.ExternalIP(4)
|
|
if err != nil {
|
|
t.Fatal("couldn't get external IP", err)
|
|
}
|
|
if !ip.Equal(net.IPv4(127, 0, 0, 1)) {
|
|
t.Errorf("invalid ip found: expected %s recieved %s", "127.0.0.1", ip)
|
|
}
|
|
}
|
|
|
|
func TestConsensus2(t *testing.T) {
|
|
server := newServer("127.0.0.1", "127.0.0.2", "127.0.0.2")
|
|
consensus := newConcensus(server.URL)
|
|
if consensus == nil {
|
|
t.Fatal("default consensus should never be nil")
|
|
}
|
|
|
|
ip, err := consensus.ExternalIP(4)
|
|
if err != nil {
|
|
t.Fatal("couldn't get external IP", err)
|
|
}
|
|
if !ip.Equal(net.IPv4(127, 0, 0, 2)) {
|
|
t.Errorf("invalid ip found: expected %s recieved %s", "127.0.0.2", ip)
|
|
}
|
|
}
|
|
|
|
func TestConsensus3(t *testing.T) {
|
|
server := newServer("127.0.0.1", "127.0.0.2", "127.0.0.3")
|
|
consensus := newConcensus(server.URL)
|
|
if consensus == nil {
|
|
t.Fatal("default consensus should never be nil")
|
|
}
|
|
|
|
ip, err := consensus.ExternalIP(4)
|
|
if err != nil {
|
|
t.Fatal("couldn't get external IP", err)
|
|
}
|
|
if !ip.Equal(net.IPv4(127, 0, 0, 1)) {
|
|
t.Errorf("invalid ip found: expected %s recieved %s; This will fail on multiple runs it takes whichever request returns first", "127.0.0.1", ip)
|
|
}
|
|
}
|