starnet/dns_test.go

104 lines
2.6 KiB
Go
Raw Permalink Normal View History

2026-03-08 20:19:40 +08:00
package starnet
import (
"context"
"net"
"testing"
)
func TestRequestCustomIP(t *testing.T) {
customIPs := []string{"1.2.3.4", "5.6.7.8"}
req := NewSimpleRequest("http://example.com", "GET").
SetCustomIP(customIPs)
if len(req.config.DNS.CustomIP) != 2 {
t.Errorf("CustomIP length = %v; want 2", len(req.config.DNS.CustomIP))
}
for i, ip := range req.config.DNS.CustomIP {
if ip != customIPs[i] {
t.Errorf("CustomIP[%d] = %v; want %v", i, ip, customIPs[i])
}
}
}
func TestRequestCustomIPInvalid(t *testing.T) {
req := NewSimpleRequest("http://example.com", "GET").
SetCustomIP([]string{"invalid-ip"})
if req.Err() == nil {
t.Error("Expected error for invalid IP, got nil")
}
}
func TestRequestCustomDNS(t *testing.T) {
dnsServers := []string{"8.8.8.8", "1.1.1.1"}
req := NewSimpleRequest("http://example.com", "GET").
SetCustomDNS(dnsServers)
if len(req.config.DNS.CustomDNS) != 2 {
t.Errorf("CustomDNS length = %v; want 2", len(req.config.DNS.CustomDNS))
}
}
func TestRequestCustomDNSInvalid(t *testing.T) {
req := NewSimpleRequest("http://example.com", "GET").
SetCustomDNS([]string{"invalid-dns"})
if req.Err() == nil {
t.Error("Expected error for invalid DNS, got nil")
}
}
func TestRequestLookupFunc(t *testing.T) {
called := false
lookupFunc := func(ctx context.Context, host string) ([]net.IPAddr, error) {
called = true
return []net.IPAddr{
{IP: net.ParseIP("1.2.3.4")},
}, nil
}
req := NewSimpleRequest("http://example.com", "GET").
SetLookupFunc(lookupFunc)
if req.config.DNS.LookupFunc == nil {
t.Error("LookupFunc not set")
}
// Call the function to verify it works
ips, err := req.config.DNS.LookupFunc(context.Background(), "example.com")
if err != nil {
t.Errorf("LookupFunc error: %v", err)
}
if !called {
t.Error("LookupFunc was not called")
}
if len(ips) != 1 {
t.Errorf("IPs length = %v; want 1", len(ips))
}
}
func TestDNSPriority(t *testing.T) {
// CustomIP should have highest priority
req := NewSimpleRequest("http://example.com", "GET").
SetCustomIP([]string{"1.2.3.4"}).
SetCustomDNS([]string{"8.8.8.8"}).
SetLookupFunc(func(ctx context.Context, host string) ([]net.IPAddr, error) {
return []net.IPAddr{{IP: net.ParseIP("5.6.7.8")}}, nil
})
// CustomIP should be set
if len(req.config.DNS.CustomIP) == 0 {
t.Error("CustomIP should be set")
}
// Others should also be set (but CustomIP takes priority in actual use)
if len(req.config.DNS.CustomDNS) == 0 {
t.Error("CustomDNS should be set")
}
if req.config.DNS.LookupFunc == nil {
t.Error("LookupFunc should be set")
}
}