mirror of
https://git.vectorsigma.ru/public/AdGuardHome.git
synced 2026-08-03 22:19:28 +00:00
Pull request #2450: Update all
Merge in DNS/adguard-home from upd-all to master Squashed commit of the following: commit 72a41e9e2d9b9a5fbf24fa69322f9c4dcf3f5fb7 Author: Eugene Burkov <E.Burkov@AdGuard.COM> Date: Thu Aug 14 19:42:11 2025 +0300 specs: export tests commit aa729009306e492fd8a046b5e84f49be87e2a57f Author: Eugene Burkov <E.Burkov@AdGuard.COM> Date: Thu Aug 14 19:19:54 2025 +0300 all: upd golibs commit 526ce744cfdf167d1e5b763422092e6f450993a6 Author: Eugene Burkov <E.Burkov@AdGuard.COM> Date: Thu Aug 14 17:21:57 2025 +0300 all: upd scripts commit ecc4312764b31e8b84e462321e3690a9b8eebbf6 Author: Eugene Burkov <E.Burkov@AdGuard.COM> Date: Thu Aug 14 17:02:53 2025 +0300 all: upd go & tools
This commit is contained in:
@@ -7,7 +7,8 @@ import (
|
||||
"testing/fstest"
|
||||
|
||||
"github.com/AdguardTeam/golibs/errors"
|
||||
"github.com/AdguardTeam/golibs/testutil/fakefs"
|
||||
"github.com/AdguardTeam/golibs/testutil"
|
||||
"github.com/AdguardTeam/golibs/testutil/fakeio/fakefs"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
@@ -64,7 +65,7 @@ func TestHostsContainer_PathsToPatterns(t *testing.T) {
|
||||
const errStat errors.Error = "bad file"
|
||||
|
||||
badFS := &fakefs.StatFS{
|
||||
OnOpen: func(_ string) (f fs.File, err error) { panic("not implemented") },
|
||||
OnOpen: func(s string) (f fs.File, err error) { panic(testutil.UnexpectedCall(s)) },
|
||||
OnStat: func(name string) (fi fs.FileInfo, err error) {
|
||||
return nil, errStat
|
||||
},
|
||||
|
||||
@@ -68,7 +68,9 @@ func TestNewHostsContainer(t *testing.T) {
|
||||
}
|
||||
|
||||
hc, err := aghnet.NewHostsContainer(testFS, &aghtest.FSWatcher{
|
||||
OnStart: func(_ context.Context) (_ error) { panic("not implemented") },
|
||||
OnStart: func(ctx context.Context) (_ error) {
|
||||
panic(testutil.UnexpectedCall(ctx))
|
||||
},
|
||||
OnEvents: onEvents,
|
||||
OnAdd: onAdd,
|
||||
OnShutdown: func(_ context.Context) (err error) { return nil },
|
||||
@@ -95,10 +97,12 @@ func TestNewHostsContainer(t *testing.T) {
|
||||
t.Run("nil_fs", func(t *testing.T) {
|
||||
require.Panics(t, func() {
|
||||
_, _ = aghnet.NewHostsContainer(nil, &aghtest.FSWatcher{
|
||||
OnStart: func(_ context.Context) (_ error) { panic("not implemented") },
|
||||
OnStart: func(ctx context.Context) (_ error) {
|
||||
panic(testutil.UnexpectedCall(ctx))
|
||||
},
|
||||
// Those shouldn't panic.
|
||||
OnEvents: func() (e <-chan struct{}) { return nil },
|
||||
OnAdd: func(name string) (err error) { return nil },
|
||||
OnAdd: func(_ string) (err error) { return nil },
|
||||
OnShutdown: func(_ context.Context) (err error) { return nil },
|
||||
}, p)
|
||||
})
|
||||
@@ -114,9 +118,9 @@ func TestNewHostsContainer(t *testing.T) {
|
||||
const errOnAdd errors.Error = "error"
|
||||
|
||||
errWatcher := &aghtest.FSWatcher{
|
||||
OnStart: func(_ context.Context) (_ error) { panic("not implemented") },
|
||||
OnEvents: func() (e <-chan struct{}) { panic("not implemented") },
|
||||
OnAdd: func(name string) (err error) { return errOnAdd },
|
||||
OnStart: func(ctx context.Context) (_ error) { panic(testutil.UnexpectedCall(ctx)) },
|
||||
OnEvents: func() (_ <-chan struct{}) { panic(testutil.UnexpectedCall()) },
|
||||
OnAdd: func(_ string) (err error) { return errOnAdd },
|
||||
OnShutdown: func(_ context.Context) (err error) { return nil },
|
||||
}
|
||||
|
||||
@@ -159,7 +163,7 @@ func TestHostsContainer_refresh(t *testing.T) {
|
||||
t.Cleanup(func() { close(eventsCh) })
|
||||
|
||||
w := &aghtest.FSWatcher{
|
||||
OnStart: func(_ context.Context) (_ error) { panic("not implemented") },
|
||||
OnStart: func(ctx context.Context) (_ error) { panic(testutil.UnexpectedCall(ctx)) },
|
||||
OnEvents: func() (e <-chan event) { return eventsCh },
|
||||
OnAdd: func(name string) (err error) {
|
||||
assert.Equal(t, "dir", name)
|
||||
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
|
||||
"github.com/AdguardTeam/golibs/errors"
|
||||
"github.com/AdguardTeam/golibs/testutil"
|
||||
"github.com/AdguardTeam/golibs/testutil/fakefs"
|
||||
"github.com/AdguardTeam/golibs/testutil/fakeio/fakefs"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
@@ -121,7 +121,7 @@ func TestIfaceSetStaticIP(t *testing.T) {
|
||||
},
|
||||
}
|
||||
panicFsys := &fakefs.FS{
|
||||
OnOpen: func(name string) (fs.File, error) { panic("not implemented") },
|
||||
OnOpen: func(name string) (_ fs.File, _ error) { panic(testutil.UnexpectedCall(name)) },
|
||||
}
|
||||
|
||||
testCases := []struct {
|
||||
|
||||
@@ -19,11 +19,11 @@ import (
|
||||
|
||||
// substRootDirFS replaces the aghos.RootDirFS function used throughout the
|
||||
// package with fsys for tests ran under t.
|
||||
func substRootDirFS(t testing.TB, fsys fs.FS) {
|
||||
t.Helper()
|
||||
func substRootDirFS(tb testing.TB, fsys fs.FS) {
|
||||
tb.Helper()
|
||||
|
||||
prev := rootDirFS
|
||||
t.Cleanup(func() { rootDirFS = prev })
|
||||
tb.Cleanup(func() { rootDirFS = prev })
|
||||
rootDirFS = fsys
|
||||
}
|
||||
|
||||
@@ -32,11 +32,11 @@ type RunCmdFunc func(cmd string, args ...string) (code int, out []byte, err erro
|
||||
|
||||
// substShell replaces the the aghos.RunCommand function used throughout the
|
||||
// package with rc for tests ran under t.
|
||||
func substShell(t testing.TB, rc RunCmdFunc) {
|
||||
t.Helper()
|
||||
func substShell(tb testing.TB, rc RunCmdFunc) {
|
||||
tb.Helper()
|
||||
|
||||
prev := aghosRunCommand
|
||||
t.Cleanup(func() { aghosRunCommand = prev })
|
||||
tb.Cleanup(func() { aghosRunCommand = prev })
|
||||
aghosRunCommand = rc
|
||||
}
|
||||
|
||||
@@ -72,11 +72,11 @@ type ifaceAddrsFunc func() (ifaces []net.Addr, err error)
|
||||
|
||||
// substNetInterfaceAddrs replaces the the net.InterfaceAddrs function used
|
||||
// throughout the package with f for tests ran under t.
|
||||
func substNetInterfaceAddrs(t *testing.T, f ifaceAddrsFunc) {
|
||||
t.Helper()
|
||||
func substNetInterfaceAddrs(tb testing.TB, f ifaceAddrsFunc) {
|
||||
tb.Helper()
|
||||
|
||||
prev := netInterfaceAddrs
|
||||
t.Cleanup(func() { netInterfaceAddrs = prev })
|
||||
tb.Cleanup(func() { netInterfaceAddrs = prev })
|
||||
netInterfaceAddrs = f
|
||||
}
|
||||
|
||||
|
||||
@@ -43,14 +43,14 @@ func TestPendingFile(t *testing.T) {
|
||||
|
||||
// newInitialFile is a test helper that returns the path to the file containing
|
||||
// [initialData].
|
||||
func newInitialFile(t *testing.T) (targetPath string) {
|
||||
t.Helper()
|
||||
func newInitialFile(tb testing.TB) (targetPath string) {
|
||||
tb.Helper()
|
||||
|
||||
dir := t.TempDir()
|
||||
dir := tb.TempDir()
|
||||
targetPath = filepath.Join(dir, "target")
|
||||
|
||||
err := os.WriteFile(targetPath, initialData, 0o644)
|
||||
require.NoError(t, err)
|
||||
require.NoError(tb, err)
|
||||
|
||||
return targetPath
|
||||
}
|
||||
|
||||
@@ -34,16 +34,16 @@ func HostToIPs(host string) (ipv4, ipv6 netip.Addr) {
|
||||
|
||||
// StartHTTPServer is a helper that starts the HTTP server, which is configured
|
||||
// to return data on every request, and returns the client and server URL.
|
||||
func StartHTTPServer(t testing.TB, data []byte) (c *http.Client, u *url.URL) {
|
||||
t.Helper()
|
||||
func StartHTTPServer(tb testing.TB, data []byte) (c *http.Client, u *url.URL) {
|
||||
tb.Helper()
|
||||
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = w.Write(data)
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
tb.Cleanup(srv.Close)
|
||||
|
||||
u, err := url.Parse(srv.URL)
|
||||
require.NoError(t, err)
|
||||
require.NoError(tb, err)
|
||||
|
||||
return srv.Client(), u
|
||||
}
|
||||
@@ -55,8 +55,8 @@ const testTimeout = 1 * time.Second
|
||||
|
||||
// StartLocalhostUpstream is a test helper that starts a DNS server on
|
||||
// localhost.
|
||||
func StartLocalhostUpstream(t *testing.T, h dns.Handler) (addr *url.URL) {
|
||||
t.Helper()
|
||||
func StartLocalhostUpstream(tb *testing.T, h dns.Handler) (addr *url.URL) {
|
||||
tb.Helper()
|
||||
|
||||
startCh := make(chan netip.AddrPort)
|
||||
defer close(startCh)
|
||||
@@ -83,12 +83,12 @@ func StartLocalhostUpstream(t *testing.T, h dns.Handler) (addr *url.URL) {
|
||||
Host: addrPort.String(),
|
||||
}
|
||||
|
||||
testutil.CleanupAndRequireSuccess(t, func() (err error) { return <-errCh })
|
||||
testutil.CleanupAndRequireSuccess(t, srv.Shutdown)
|
||||
testutil.CleanupAndRequireSuccess(tb, func() (err error) { return <-errCh })
|
||||
testutil.CleanupAndRequireSuccess(tb, srv.Shutdown)
|
||||
case err := <-errCh:
|
||||
require.NoError(t, err)
|
||||
require.NoError(tb, err)
|
||||
case <-time.After(testTimeout):
|
||||
require.FailNow(t, "timeout exceeded")
|
||||
require.FailNow(tb, "timeout exceeded")
|
||||
}
|
||||
|
||||
return addr
|
||||
|
||||
@@ -2,7 +2,6 @@ package aghtest
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"net/netip"
|
||||
"time"
|
||||
|
||||
@@ -15,14 +14,6 @@ import (
|
||||
"github.com/miekg/dns"
|
||||
)
|
||||
|
||||
// Interface Mocks
|
||||
//
|
||||
// Keep entities in this file in alphabetic order.
|
||||
|
||||
// Module adguard-home
|
||||
|
||||
// Package aghos
|
||||
|
||||
// FSWatcher is a fake [aghos.FSWatcher] implementation for tests.
|
||||
type FSWatcher struct {
|
||||
OnStart func(ctx context.Context) (err error)
|
||||
@@ -54,8 +45,6 @@ func (w *FSWatcher) Add(name string) (err error) {
|
||||
return w.OnAdd(name)
|
||||
}
|
||||
|
||||
// Package nextagh
|
||||
|
||||
// ServiceWithConfig is a fake [nextagh.ServiceWithConfig] implementation for
|
||||
// tests.
|
||||
type ServiceWithConfig[ConfigType any] struct {
|
||||
@@ -85,8 +74,6 @@ func (s *ServiceWithConfig[ConfigType]) Config() (c ConfigType) {
|
||||
return s.OnConfig()
|
||||
}
|
||||
|
||||
// Package client
|
||||
|
||||
// AddressProcessor is a fake [client.AddressProcessor] implementation for
|
||||
// tests.
|
||||
type AddressProcessor struct {
|
||||
@@ -122,20 +109,6 @@ func (p *AddressUpdater) UpdateAddress(
|
||||
p.OnUpdateAddress(ctx, ip, host, info)
|
||||
}
|
||||
|
||||
// Package filtering
|
||||
|
||||
// Resolver is a fake [filtering.Resolver] implementation for tests.
|
||||
type Resolver struct {
|
||||
OnLookupIP func(ctx context.Context, network, host string) (ips []net.IP, err error)
|
||||
}
|
||||
|
||||
// LookupIP implements the [filtering.Resolver] interface for *Resolver.
|
||||
func (r *Resolver) LookupIP(ctx context.Context, network, host string) (ips []net.IP, err error) {
|
||||
return r.OnLookupIP(ctx, network, host)
|
||||
}
|
||||
|
||||
// Package rdns
|
||||
|
||||
// Exchanger is a fake [rdns.Exchanger] implementation for tests.
|
||||
type Exchanger struct {
|
||||
OnExchange func(ip netip.Addr) (host string, ttl time.Duration, err error)
|
||||
@@ -149,10 +122,6 @@ func (e *Exchanger) Exchange(ip netip.Addr) (host string, ttl time.Duration, err
|
||||
return e.OnExchange(ip)
|
||||
}
|
||||
|
||||
// Module dnsproxy
|
||||
|
||||
// Package upstream
|
||||
|
||||
// UpstreamMock is a fake [upstream.Upstream] implementation for tests.
|
||||
//
|
||||
// TODO(a.garipov): Replace with all uses of Upstream with UpstreamMock and
|
||||
|
||||
@@ -3,20 +3,12 @@ package aghtest_test
|
||||
import (
|
||||
"github.com/AdguardTeam/AdGuardHome/internal/aghtest"
|
||||
"github.com/AdguardTeam/AdGuardHome/internal/client"
|
||||
"github.com/AdguardTeam/AdGuardHome/internal/filtering"
|
||||
)
|
||||
|
||||
// Put interface checks that cause import cycles here.
|
||||
|
||||
// type check
|
||||
var _ filtering.Resolver = (*aghtest.Resolver)(nil)
|
||||
|
||||
// type check
|
||||
//
|
||||
// TODO(s.chzhen): It's here to avoid the import cycle. Remove it.
|
||||
var _ client.AddressProcessor = (*aghtest.AddressProcessor)(nil)
|
||||
|
||||
// type check
|
||||
//
|
||||
// TODO(s.chzhen): It's here to avoid the import cycle. Remove it.
|
||||
var _ client.AddressUpdater = (*aghtest.AddressUpdater)(nil)
|
||||
// TODO(s.chzhen): Resolve the import cycles and move it to aghtest.
|
||||
var (
|
||||
_ client.AddressProcessor = (*aghtest.AddressProcessor)(nil)
|
||||
_ client.AddressUpdater = (*aghtest.AddressUpdater)(nil)
|
||||
)
|
||||
|
||||
@@ -220,7 +220,7 @@ func NewErrorUpstream() (u *UpstreamMock) {
|
||||
return &UpstreamMock{
|
||||
OnAddress: func() (addr string) { return "error.upstream.example" },
|
||||
OnExchange: func(_ *dns.Msg) (resp *dns.Msg, err error) {
|
||||
return nil, errors.Error("test upstream error")
|
||||
return nil, ErrUpstream
|
||||
},
|
||||
OnClose: func() (err error) { return nil },
|
||||
}
|
||||
|
||||
@@ -24,12 +24,12 @@ var testdata fs.FS = os.DirFS("./testdata")
|
||||
type RunCmdFunc func(cmd string, args ...string) (code int, out []byte, err error)
|
||||
|
||||
// substShell replaces the the aghos.RunCommand function used throughout the
|
||||
// package with rc for tests ran under t.
|
||||
func substShell(t testing.TB, rc RunCmdFunc) {
|
||||
t.Helper()
|
||||
// package with rc for tests ran under tb.
|
||||
func substShell(tb testing.TB, rc RunCmdFunc) {
|
||||
tb.Helper()
|
||||
|
||||
prev := aghosRunCommand
|
||||
t.Cleanup(func() { aghosRunCommand = prev })
|
||||
tb.Cleanup(func() { aghosRunCommand = prev })
|
||||
aghosRunCommand = rc
|
||||
}
|
||||
|
||||
|
||||
@@ -1208,12 +1208,8 @@ func TestStorage_CustomUpstreamConfig(t *testing.T) {
|
||||
}
|
||||
|
||||
dhcp := &testDHCP{
|
||||
OnLeases: func() (ls []*dhcpsvc.Lease) {
|
||||
panic("not implemented")
|
||||
},
|
||||
OnHostBy: func(ip netip.Addr) (host string) {
|
||||
panic("not implemented")
|
||||
},
|
||||
OnLeases: func() (_ []*dhcpsvc.Lease) { panic(testutil.UnexpectedCall()) },
|
||||
OnHostBy: func(ip netip.Addr) (_ string) { panic(testutil.UnexpectedCall(ip)) },
|
||||
OnMACBy: func(ip netip.Addr) (mac net.HardwareAddr) {
|
||||
return ipToMAC[ip]
|
||||
},
|
||||
|
||||
@@ -242,8 +242,8 @@ func TestUpgradeSchema8to9(t *testing.T) {
|
||||
}
|
||||
|
||||
// assertEqualExcept removes entries from configs and compares them.
|
||||
func assertEqualExcept(t *testing.T, oldConf, newConf yobj, oldKeys, newKeys []string) {
|
||||
t.Helper()
|
||||
func assertEqualExcept(tb testing.TB, oldConf, newConf yobj, oldKeys, newKeys []string) {
|
||||
tb.Helper()
|
||||
|
||||
for _, k := range oldKeys {
|
||||
delete(oldConf, k)
|
||||
@@ -252,7 +252,7 @@ func assertEqualExcept(t *testing.T, oldConf, newConf yobj, oldKeys, newKeys []s
|
||||
delete(newConf, k)
|
||||
}
|
||||
|
||||
assert.Equal(t, oldConf, newConf)
|
||||
assert.Equal(tb, oldConf, newConf)
|
||||
}
|
||||
|
||||
func testDiskConf(schemaVersion int) (diskConf yobj) {
|
||||
|
||||
@@ -54,6 +54,8 @@ func getField[T any](t require.TestingT, obj any, indexes ...any) (val T) {
|
||||
}
|
||||
|
||||
func TestMigrateConfig_Migrate(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
const (
|
||||
inputFileName = "input.yml"
|
||||
outputFileName = "output.yml"
|
||||
@@ -201,6 +203,8 @@ func TestMigrateConfig_Migrate(t *testing.T) {
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
body, err := fs.ReadFile(testdata, path.Join(t.Name(), inputFileName))
|
||||
require.NoError(t, err)
|
||||
|
||||
|
||||
@@ -34,18 +34,18 @@ func defaultResponse() *dhcpStatusResponse {
|
||||
|
||||
// handleLease is the helper function that calls handler with provided static
|
||||
// lease as body and returns modified response recorder.
|
||||
func handleLease(t *testing.T, lease *leaseStatic, handler http.HandlerFunc) (w *httptest.ResponseRecorder) {
|
||||
t.Helper()
|
||||
func handleLease(tb testing.TB, lease *leaseStatic, handler http.HandlerFunc) (w *httptest.ResponseRecorder) {
|
||||
tb.Helper()
|
||||
|
||||
w = httptest.NewRecorder()
|
||||
|
||||
b := &bytes.Buffer{}
|
||||
err := json.NewEncoder(b).Encode(lease)
|
||||
require.NoError(t, err)
|
||||
require.NoError(tb, err)
|
||||
|
||||
var r *http.Request
|
||||
r, err = http.NewRequest(http.MethodPost, "", b)
|
||||
require.NoError(t, err)
|
||||
require.NoError(tb, err)
|
||||
|
||||
handler(w, r)
|
||||
|
||||
|
||||
@@ -44,12 +44,12 @@ func defaultV4ServerConf() (conf *V4ServerConf) {
|
||||
|
||||
// defaultSrv prepares the default DHCPServer to use in tests. The underlying
|
||||
// type of s is *v4Server.
|
||||
func defaultSrv(t *testing.T) (s DHCPServer) {
|
||||
t.Helper()
|
||||
func defaultSrv(tb testing.TB) (s DHCPServer) {
|
||||
tb.Helper()
|
||||
|
||||
var err error
|
||||
s, err = v4Create(defaultV4ServerConf())
|
||||
require.NoError(t, err)
|
||||
require.NoError(tb, err)
|
||||
|
||||
return s
|
||||
}
|
||||
|
||||
@@ -27,16 +27,16 @@ const maxDNS64SynTTL uint32 = 600
|
||||
// newRR is a helper that creates a new dns.RR with the given name, qtype, ttl
|
||||
// and value. It fails the test if the qtype is not supported or the type of
|
||||
// value doesn't match the qtype.
|
||||
func newRR(t *testing.T, name string, qtype uint16, ttl uint32, val any) (rr dns.RR) {
|
||||
t.Helper()
|
||||
func newRR(tb testing.TB, name string, qtype uint16, ttl uint32, val any) (rr dns.RR) {
|
||||
tb.Helper()
|
||||
|
||||
switch qtype {
|
||||
case dns.TypeA:
|
||||
rr = &dns.A{A: testutil.RequireTypeAssert[net.IP](t, val)}
|
||||
rr = &dns.A{A: testutil.RequireTypeAssert[net.IP](tb, val)}
|
||||
case dns.TypeAAAA:
|
||||
rr = &dns.AAAA{AAAA: testutil.RequireTypeAssert[net.IP](t, val)}
|
||||
rr = &dns.AAAA{AAAA: testutil.RequireTypeAssert[net.IP](tb, val)}
|
||||
case dns.TypeCNAME:
|
||||
rr = &dns.CNAME{Target: testutil.RequireTypeAssert[string](t, val)}
|
||||
rr = &dns.CNAME{Target: testutil.RequireTypeAssert[string](tb, val)}
|
||||
case dns.TypeSOA:
|
||||
rr = &dns.SOA{
|
||||
Ns: "ns." + name,
|
||||
@@ -48,9 +48,9 @@ func newRR(t *testing.T, name string, qtype uint16, ttl uint32, val any) (rr dns
|
||||
Minttl: 1,
|
||||
}
|
||||
case dns.TypePTR:
|
||||
rr = &dns.PTR{Ptr: testutil.RequireTypeAssert[string](t, val)}
|
||||
rr = &dns.PTR{Ptr: testutil.RequireTypeAssert[string](tb, val)}
|
||||
default:
|
||||
t.Fatalf("unsupported qtype: %d", qtype)
|
||||
tb.Fatalf("unsupported qtype: %d", qtype)
|
||||
}
|
||||
|
||||
*rr.Header() = dns.RR_Header{
|
||||
@@ -325,7 +325,7 @@ func TestServer_dns64WithDisabledRDNS(t *testing.T) {
|
||||
|
||||
// Shouldn't go to upstream at all.
|
||||
panicHdlr := dns.HandlerFunc(func(w dns.ResponseWriter, m *dns.Msg) {
|
||||
panic("not implemented")
|
||||
panic(testutil.UnexpectedCall(w, m))
|
||||
})
|
||||
upsAddr := aghtest.StartLocalhostUpstream(t, panicHdlr).String()
|
||||
localUpsAddr := aghtest.StartLocalhostUpstream(t, panicHdlr).String()
|
||||
|
||||
@@ -104,13 +104,16 @@ func (c *clientsContainer) ClearUpstreamCache() {
|
||||
c.OnClearUpstreamCache()
|
||||
}
|
||||
|
||||
func startDeferStop(t *testing.T, s *Server) {
|
||||
t.Helper()
|
||||
// startDeferStop starts the server and stops it when the test ends.
|
||||
//
|
||||
// TODO(e.burkov): Replace with [servicetest.RequireRun].
|
||||
func startDeferStop(tb testing.TB, s *Server) {
|
||||
tb.Helper()
|
||||
|
||||
err := s.Start(testutil.ContextWithTimeout(t, testTimeout))
|
||||
require.NoError(t, err)
|
||||
testutil.CleanupAndRequireSuccess(t, func() (err error) {
|
||||
return s.Stop(testutil.ContextWithTimeout(t, testTimeout))
|
||||
err := s.Start(testutil.ContextWithTimeout(tb, testTimeout))
|
||||
require.NoError(tb, err)
|
||||
testutil.CleanupAndRequireSuccess(tb, func() (err error) {
|
||||
return s.Stop(testutil.ContextWithTimeout(tb, testTimeout))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -130,11 +133,11 @@ func emptyFilteringBlockedServices() (bsvc *filtering.BlockedServices) {
|
||||
// *Server for use in tests, given the provided parameters. It also populates
|
||||
// the filtering configuration with default parameters.
|
||||
func createTestServer(
|
||||
t *testing.T,
|
||||
tb testing.TB,
|
||||
filterConf *filtering.Config,
|
||||
forwardConf ServerConfig,
|
||||
) (s *Server) {
|
||||
t.Helper()
|
||||
tb.Helper()
|
||||
|
||||
filterConf.Logger = cmp.Or(filterConf.Logger, testLogger)
|
||||
|
||||
@@ -155,14 +158,14 @@ func createTestServer(
|
||||
}
|
||||
|
||||
f, err := filtering.New(filterConf, filters)
|
||||
require.NoError(t, err)
|
||||
require.NoError(tb, err)
|
||||
|
||||
f.SetEnabled(true)
|
||||
|
||||
dhcp := &testDHCP{
|
||||
OnEnabled: func() (ok bool) { return false },
|
||||
OnHostByIP: func(ip netip.Addr) (host string) { return "" },
|
||||
OnIPByHost: func(host string) (ip netip.Addr) { panic("not implemented") },
|
||||
OnIPByHost: func(host string) (_ netip.Addr) { panic(testutil.UnexpectedCall(host)) },
|
||||
}
|
||||
s, err = NewServer(DNSCreateParams{
|
||||
DHCPServer: dhcp,
|
||||
@@ -170,23 +173,23 @@ func createTestServer(
|
||||
PrivateNets: netutil.SubnetSetFunc(netutil.IsLocallyServed),
|
||||
Logger: testLogger,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.NoError(tb, err)
|
||||
|
||||
err = s.Prepare(testutil.ContextWithTimeout(t, testTimeout), &forwardConf)
|
||||
require.NoError(t, err)
|
||||
err = s.Prepare(testutil.ContextWithTimeout(tb, testTimeout), &forwardConf)
|
||||
require.NoError(tb, err)
|
||||
|
||||
return s
|
||||
}
|
||||
|
||||
func createServerTLSConfig(t *testing.T) (*tls.Config, []byte, []byte) {
|
||||
t.Helper()
|
||||
func createServerTLSConfig(tb testing.TB) (*tls.Config, []byte, []byte) {
|
||||
tb.Helper()
|
||||
|
||||
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||
require.NoErrorf(t, err, "cannot generate RSA key: %s", err)
|
||||
require.NoErrorf(tb, err, "cannot generate RSA key: %s", err)
|
||||
|
||||
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
|
||||
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
|
||||
require.NoErrorf(t, err, "failed to generate serial number: %s", err)
|
||||
require.NoErrorf(tb, err, "failed to generate serial number: %s", err)
|
||||
|
||||
notBefore := time.Now()
|
||||
notAfter := notBefore.Add(5 * 365 * timeutil.Day)
|
||||
@@ -207,13 +210,13 @@ func createServerTLSConfig(t *testing.T) (*tls.Config, []byte, []byte) {
|
||||
template.DNSNames = append(template.DNSNames, tlsServerName)
|
||||
|
||||
derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, publicKey(privateKey), privateKey)
|
||||
require.NoErrorf(t, err, "failed to create certificate: %s", err)
|
||||
require.NoErrorf(tb, err, "failed to create certificate: %s", err)
|
||||
|
||||
certPem := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
|
||||
keyPem := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(privateKey)})
|
||||
|
||||
cert, err := tls.X509KeyPair(certPem, keyPem)
|
||||
require.NoErrorf(t, err, "failed to create certificate: %s", err)
|
||||
require.NoErrorf(tb, err, "failed to create certificate: %s", err)
|
||||
|
||||
return &tls.Config{
|
||||
Certificates: []tls.Certificate{cert},
|
||||
@@ -222,18 +225,18 @@ func createServerTLSConfig(t *testing.T) (*tls.Config, []byte, []byte) {
|
||||
}, certPem, keyPem
|
||||
}
|
||||
|
||||
func createTestTLS(t *testing.T, tlsConf *TLSConfig) (s *Server, certPem []byte) {
|
||||
t.Helper()
|
||||
func createTestTLS(tb testing.TB, tlsConf *TLSConfig) (s *Server, certPem []byte) {
|
||||
tb.Helper()
|
||||
|
||||
var keyPem []byte
|
||||
_, certPem, keyPem = createServerTLSConfig(t)
|
||||
_, certPem, keyPem = createServerTLSConfig(tb)
|
||||
|
||||
cert, err := tls.X509KeyPair(certPem, keyPem)
|
||||
require.NoError(t, err)
|
||||
require.NoError(tb, err)
|
||||
|
||||
tlsConf.Cert = &cert
|
||||
|
||||
s = createTestServer(t, &filtering.Config{
|
||||
s = createTestServer(tb, &filtering.Config{
|
||||
BlockingMode: filtering.BlockingModeDefault,
|
||||
}, ServerConfig{
|
||||
UDPListenAddrs: []*net.UDPAddr{{}},
|
||||
@@ -247,8 +250,8 @@ func createTestTLS(t *testing.T, tlsConf *TLSConfig) (s *Server, certPem []byte)
|
||||
ServePlainDNS: true,
|
||||
})
|
||||
|
||||
err = s.Prepare(testutil.ContextWithTimeout(t, testTimeout), &s.conf)
|
||||
require.NoErrorf(t, err, "failed to prepare server: %s", err)
|
||||
err = s.Prepare(testutil.ContextWithTimeout(tb, testTimeout), &s.conf)
|
||||
require.NoErrorf(tb, err, "failed to prepare server: %s", err)
|
||||
|
||||
return s, certPem
|
||||
}
|
||||
@@ -304,25 +307,27 @@ func newResp(rcode int, req *dns.Msg, ans []dns.RR) (resp *dns.Msg) {
|
||||
return resp
|
||||
}
|
||||
|
||||
func assertGoogleAResponse(t *testing.T, reply *dns.Msg) {
|
||||
assertResponse(t, reply, netip.AddrFrom4([4]byte{8, 8, 8, 8}))
|
||||
func assertGoogleAResponse(tb testing.TB, reply *dns.Msg) {
|
||||
tb.Helper()
|
||||
|
||||
assertResponse(tb, reply, netip.AddrFrom4([4]byte{8, 8, 8, 8}))
|
||||
}
|
||||
|
||||
func assertResponse(t *testing.T, reply *dns.Msg, ip netip.Addr) {
|
||||
t.Helper()
|
||||
func assertResponse(tb testing.TB, reply *dns.Msg, ip netip.Addr) {
|
||||
tb.Helper()
|
||||
|
||||
require.Lenf(t, reply.Answer, 1, "dns server returned reply with wrong number of answers - %d", len(reply.Answer))
|
||||
require.Lenf(tb, reply.Answer, 1, "dns server returned reply with wrong number of answers - %d", len(reply.Answer))
|
||||
|
||||
a, ok := reply.Answer[0].(*dns.A)
|
||||
require.Truef(t, ok, "dns server returned wrong answer type instead of A: %v", reply.Answer[0])
|
||||
assert.Equal(t, net.IP(ip.AsSlice()), a.A)
|
||||
require.Truef(tb, ok, "dns server returned wrong answer type instead of A: %v", reply.Answer[0])
|
||||
assert.Equal(tb, net.IP(ip.AsSlice()), a.A)
|
||||
}
|
||||
|
||||
// sendTestMessagesAsync sends messages in parallel to check for race issues.
|
||||
//
|
||||
//lint:ignore U1000 it's called from the function which is skipped for now.
|
||||
func sendTestMessagesAsync(t *testing.T, conn *dns.Conn) {
|
||||
t.Helper()
|
||||
func sendTestMessagesAsync(tb testing.TB, conn *dns.Conn) {
|
||||
tb.Helper()
|
||||
|
||||
wg := &sync.WaitGroup{}
|
||||
|
||||
@@ -334,29 +339,29 @@ func sendTestMessagesAsync(t *testing.T, conn *dns.Conn) {
|
||||
defer wg.Done()
|
||||
|
||||
err := conn.WriteMsg(msg)
|
||||
require.NoErrorf(t, err, "cannot write message: %s", err)
|
||||
require.NoErrorf(tb, err, "cannot write message: %s", err)
|
||||
|
||||
res, err := conn.ReadMsg()
|
||||
require.NoErrorf(t, err, "cannot read response to message: %s", err)
|
||||
require.NoErrorf(tb, err, "cannot read response to message: %s", err)
|
||||
|
||||
assertGoogleAResponse(t, res)
|
||||
assertGoogleAResponse(tb, res)
|
||||
}()
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
func sendTestMessages(t *testing.T, conn *dns.Conn) {
|
||||
t.Helper()
|
||||
func sendTestMessages(tb testing.TB, conn *dns.Conn) {
|
||||
tb.Helper()
|
||||
|
||||
for i := range testMessagesCount {
|
||||
req := createGoogleATestMessage()
|
||||
err := conn.WriteMsg(req)
|
||||
assert.NoErrorf(t, err, "cannot write message #%d: %s", i, err)
|
||||
assert.NoErrorf(tb, err, "cannot write message #%d: %s", i, err)
|
||||
|
||||
res, err := conn.ReadMsg()
|
||||
assert.NoErrorf(t, err, "cannot read response to message #%d: %s", i, err)
|
||||
assertGoogleAResponse(t, res)
|
||||
assert.NoErrorf(tb, err, "cannot read response to message #%d: %s", i, err)
|
||||
assertGoogleAResponse(tb, res)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1080,8 +1085,8 @@ func TestBlockedCustomIP(t *testing.T) {
|
||||
|
||||
dhcp := &testDHCP{
|
||||
OnEnabled: func() (ok bool) { return false },
|
||||
OnHostByIP: func(_ netip.Addr) (host string) { panic("not implemented") },
|
||||
OnIPByHost: func(_ string) (ip netip.Addr) { panic("not implemented") },
|
||||
OnHostByIP: func(ip netip.Addr) (_ string) { panic(testutil.UnexpectedCall(ip)) },
|
||||
OnIPByHost: func(host string) (_ netip.Addr) { panic(testutil.UnexpectedCall(host)) },
|
||||
}
|
||||
s, err := NewServer(DNSCreateParams{
|
||||
DHCPServer: dhcp,
|
||||
@@ -1256,8 +1261,8 @@ func TestRewrite(t *testing.T) {
|
||||
|
||||
dhcp := &testDHCP{
|
||||
OnEnabled: func() (ok bool) { return false },
|
||||
OnHostByIP: func(ip netip.Addr) (host string) { panic("not implemented") },
|
||||
OnIPByHost: func(host string) (ip netip.Addr) { panic("not implemented") },
|
||||
OnHostByIP: func(ip netip.Addr) (_ string) { panic(testutil.UnexpectedCall(ip)) },
|
||||
OnIPByHost: func(host string) (_ netip.Addr) { panic(testutil.UnexpectedCall(host)) },
|
||||
}
|
||||
s, err := NewServer(DNSCreateParams{
|
||||
DHCPServer: dhcp,
|
||||
@@ -1392,7 +1397,7 @@ func TestPTRResponseFromDHCPLeases(t *testing.T) {
|
||||
DNSFilter: flt,
|
||||
DHCPServer: &testDHCP{
|
||||
OnEnabled: func() (ok bool) { return true },
|
||||
OnIPByHost: func(host string) (ip netip.Addr) { panic("not implemented") },
|
||||
OnIPByHost: func(host string) (_ netip.Addr) { panic(testutil.UnexpectedCall(host)) },
|
||||
OnHostByIP: func(ip netip.Addr) (host string) {
|
||||
return "myhost"
|
||||
},
|
||||
@@ -1449,13 +1454,13 @@ func TestPTRResponseFromHosts(t *testing.T) {
|
||||
|
||||
dhcp := &testDHCP{
|
||||
OnEnabled: func() (ok bool) { return false },
|
||||
OnIPByHost: func(host string) (ip netip.Addr) { panic("not implemented") },
|
||||
OnIPByHost: func(host string) (_ netip.Addr) { panic(testutil.UnexpectedCall(host)) },
|
||||
OnHostByIP: func(ip netip.Addr) (host string) { return "" },
|
||||
}
|
||||
|
||||
var eventsCalledCounter uint32
|
||||
hc, err := aghnet.NewHostsContainer(testFS, &aghtest.FSWatcher{
|
||||
OnStart: func(_ context.Context) (_ error) { panic("not implemented") },
|
||||
OnStart: func(ctx context.Context) (_ error) { panic(testutil.UnexpectedCall(ctx)) },
|
||||
OnEvents: func() (e <-chan struct{}) {
|
||||
assert.Equal(t, uint32(1), atomic.AddUint32(&eventsCalledCounter, 1))
|
||||
|
||||
@@ -1466,7 +1471,7 @@ func TestPTRResponseFromHosts(t *testing.T) {
|
||||
|
||||
return nil
|
||||
},
|
||||
OnShutdown: func(_ context.Context) (err error) { panic("not implemented") },
|
||||
OnShutdown: func(ctx context.Context) (err error) { panic(testutil.UnexpectedCall(ctx)) },
|
||||
}, hostsFilename)
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() {
|
||||
|
||||
@@ -58,8 +58,8 @@ func TestHandleDNSRequest_handleDNSRequest(t *testing.T) {
|
||||
s, err := NewServer(DNSCreateParams{
|
||||
DHCPServer: &testDHCP{
|
||||
OnEnabled: func() (ok bool) { return false },
|
||||
OnHostByIP: func(ip netip.Addr) (host string) { panic("not implemented") },
|
||||
OnIPByHost: func(host string) (ip netip.Addr) { panic("not implemented") },
|
||||
OnHostByIP: func(ip netip.Addr) (_ string) { panic(testutil.UnexpectedCall(ip)) },
|
||||
OnIPByHost: func(host string) (_ netip.Addr) { panic(testutil.UnexpectedCall(host)) },
|
||||
},
|
||||
DNSFilter: f,
|
||||
PrivateNets: netutil.SubnetSetFunc(netutil.IsLocallyServed),
|
||||
|
||||
@@ -44,16 +44,18 @@ func (emptySysResolvers) Addrs() (addrs []netip.AddrPort) {
|
||||
return nil
|
||||
}
|
||||
|
||||
func loadTestData(t *testing.T, casesFileName string, cases any) {
|
||||
t.Helper()
|
||||
// loadTestData loads the test data from the file with the given name into
|
||||
// cases.
|
||||
func loadTestData(tb testing.TB, casesFileName string, cases any) {
|
||||
tb.Helper()
|
||||
|
||||
var f *os.File
|
||||
f, err := os.Open(filepath.Join("testdata", casesFileName))
|
||||
require.NoError(t, err)
|
||||
testutil.CleanupAndRequireSuccess(t, f.Close)
|
||||
require.NoError(tb, err)
|
||||
testutil.CleanupAndRequireSuccess(tb, f.Close)
|
||||
|
||||
err = json.NewDecoder(f).Decode(cases)
|
||||
require.NoError(t, err)
|
||||
require.NoError(tb, err)
|
||||
}
|
||||
|
||||
const (
|
||||
@@ -312,14 +314,17 @@ func TestDNSForwardHTTP_handleSetConfig(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func newLocalUpstreamListener(t *testing.T, port uint16, handler dns.Handler) (real netip.AddrPort) {
|
||||
t.Helper()
|
||||
// newLocalUpstreamListener creates a local upstream listener and returns its
|
||||
// address. The listener is started in a separate goroutine and stopped when
|
||||
// the tb's test is finished.
|
||||
func newLocalUpstreamListener(tb testing.TB, port uint16, h dns.Handler) (real netip.AddrPort) {
|
||||
tb.Helper()
|
||||
|
||||
startCh := make(chan struct{})
|
||||
upsSrv := &dns.Server{
|
||||
Addr: netip.AddrPortFrom(netutil.IPv4Localhost(), port).String(),
|
||||
Net: "tcp",
|
||||
Handler: handler,
|
||||
Handler: h,
|
||||
NotifyStartedFunc: func() { close(startCh) },
|
||||
}
|
||||
go func() {
|
||||
@@ -328,9 +333,9 @@ func newLocalUpstreamListener(t *testing.T, port uint16, handler dns.Handler) (r
|
||||
}()
|
||||
|
||||
<-startCh
|
||||
testutil.CleanupAndRequireSuccess(t, upsSrv.Shutdown)
|
||||
testutil.CleanupAndRequireSuccess(tb, upsSrv.Shutdown)
|
||||
|
||||
return testutil.RequireTypeAssert[*net.TCPAddr](t, upsSrv.Listener.Addr()).AddrPort()
|
||||
return testutil.RequireTypeAssert[*net.TCPAddr](tb, upsSrv.Listener.Addr()).AddrPort()
|
||||
}
|
||||
|
||||
func TestServer_HandleTestUpstreamDNS(t *testing.T) {
|
||||
@@ -364,7 +369,7 @@ func TestServer_HandleTestUpstreamDNS(t *testing.T) {
|
||||
},
|
||||
},
|
||||
&aghtest.FSWatcher{
|
||||
OnStart: func(_ context.Context) (_ error) { panic("not implemented") },
|
||||
OnStart: func(ctx context.Context) (_ error) { panic(testutil.UnexpectedCall(ctx)) },
|
||||
OnEvents: func() (e <-chan struct{}) { return nil },
|
||||
OnAdd: func(_ string) (err error) { return nil },
|
||||
OnShutdown: func(_ context.Context) (err error) { return nil },
|
||||
@@ -469,10 +474,8 @@ func TestServer_HandleTestUpstreamDNS(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
|
||||
require.Contains(t, resp, sleepyUps)
|
||||
require.IsType(t, "", resp[sleepyUps])
|
||||
sleepyRes, _ := resp[sleepyUps].(string)
|
||||
sleepyRes := testutil.RequireTypeAssert[string](t, resp[sleepyUps])
|
||||
|
||||
// TODO(e.burkov): Improve the format of an error in dnsproxy.
|
||||
assert.True(t, strings.HasSuffix(sleepyRes, "i/o timeout"))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -94,7 +94,7 @@ func TestServer_ProcessInitial(t *testing.T) {
|
||||
var gotAddr netip.Addr
|
||||
s.addrProc = &aghtest.AddressProcessor{
|
||||
OnProcess: func(ctx context.Context, ip netip.Addr) { gotAddr = ip },
|
||||
OnClose: func() (err error) { panic("not implemented") },
|
||||
OnClose: func() (_ error) { panic(testutil.UnexpectedCall()) },
|
||||
}
|
||||
|
||||
dctx := &dnsContext{
|
||||
@@ -373,14 +373,14 @@ func TestServer_ProcessDDRQuery(t *testing.T) {
|
||||
}
|
||||
|
||||
// createTestDNSFilter returns the minimum valid DNSFilter.
|
||||
func createTestDNSFilter(t *testing.T) (f *filtering.DNSFilter) {
|
||||
t.Helper()
|
||||
func createTestDNSFilter(tb testing.TB) (f *filtering.DNSFilter) {
|
||||
tb.Helper()
|
||||
|
||||
f, err := filtering.New(&filtering.Config{
|
||||
Logger: testLogger,
|
||||
BlockingMode: filtering.BlockingModeDefault,
|
||||
}, []filtering.Filter{})
|
||||
require.NoError(t, err)
|
||||
require.NoError(tb, err)
|
||||
|
||||
return f
|
||||
}
|
||||
@@ -519,7 +519,7 @@ func TestServer_ProcessDHCPHosts(t *testing.T) {
|
||||
OnIPByHost: func(host string) (ip netip.Addr) {
|
||||
return knownClients[host]
|
||||
},
|
||||
OnHostByIP: func(ip netip.Addr) (host string) { panic("not implemented") },
|
||||
OnHostByIP: func(ip netip.Addr) (_ string) { panic(testutil.UnexpectedCall(ip)) },
|
||||
}
|
||||
|
||||
testCases := []struct {
|
||||
|
||||
@@ -22,17 +22,16 @@ const testTimeout = 5 * time.Second
|
||||
|
||||
// serveHTTPLocally starts a new HTTP server, that handles its index with h. It
|
||||
// also gracefully closes the listener when the test under t finishes.
|
||||
func serveHTTPLocally(t *testing.T, h http.Handler) (urlStr string) {
|
||||
t.Helper()
|
||||
func serveHTTPLocally(tb testing.TB, h http.Handler) (urlStr string) {
|
||||
tb.Helper()
|
||||
|
||||
l, err := net.Listen("tcp", ":0")
|
||||
require.NoError(t, err)
|
||||
require.NoError(tb, err)
|
||||
|
||||
go func() { _ = http.Serve(l, h) }()
|
||||
testutil.CleanupAndRequireSuccess(t, l.Close)
|
||||
testutil.CleanupAndRequireSuccess(tb, l.Close)
|
||||
|
||||
addr := l.Addr()
|
||||
require.IsType(t, (*net.TCPAddr)(nil), addr)
|
||||
addr := testutil.RequireTypeAssert[*net.TCPAddr](tb, l.Addr())
|
||||
|
||||
return (&url.URL{
|
||||
Scheme: urlutil.SchemeHTTP,
|
||||
@@ -42,10 +41,10 @@ func serveHTTPLocally(t *testing.T, h http.Handler) (urlStr string) {
|
||||
|
||||
// serveFiltersLocally is a helper that concurrently listens on a free port to
|
||||
// respond with fltContent.
|
||||
func serveFiltersLocally(t *testing.T, fltContent []byte) (urlStr string) {
|
||||
t.Helper()
|
||||
func serveFiltersLocally(tb testing.TB, fltContent []byte) (urlStr string) {
|
||||
tb.Helper()
|
||||
|
||||
return serveHTTPLocally(t, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
return serveHTTPLocally(tb, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
pt := testutil.PanicT{}
|
||||
|
||||
n, werr := w.Write(fltContent)
|
||||
@@ -57,43 +56,43 @@ func serveFiltersLocally(t *testing.T, fltContent []byte) (urlStr string) {
|
||||
// updateAndAssert loads filter content from its URL and then asserts rules
|
||||
// count.
|
||||
func updateAndAssert(
|
||||
t *testing.T,
|
||||
tb testing.TB,
|
||||
ctx context.Context,
|
||||
dnsFilter *DNSFilter,
|
||||
f *FilterYAML,
|
||||
wantUpd require.BoolAssertionFunc,
|
||||
wantRulesCount int,
|
||||
) {
|
||||
t.Helper()
|
||||
tb.Helper()
|
||||
|
||||
ok, err := dnsFilter.update(f)
|
||||
require.NoError(t, err)
|
||||
wantUpd(t, ok)
|
||||
require.NoError(tb, err)
|
||||
wantUpd(tb, ok)
|
||||
|
||||
assert.Equal(t, wantRulesCount, f.RulesCount)
|
||||
assert.Equal(tb, wantRulesCount, f.RulesCount)
|
||||
|
||||
dir, err := os.ReadDir(filepath.Join(dnsFilter.conf.DataDir, filterDir))
|
||||
require.NoError(t, err)
|
||||
require.FileExists(t, f.Path(dnsFilter.conf.DataDir))
|
||||
require.NoError(tb, err)
|
||||
require.FileExists(tb, f.Path(dnsFilter.conf.DataDir))
|
||||
|
||||
assert.Len(t, dir, 1)
|
||||
assert.Len(tb, dir, 1)
|
||||
|
||||
err = dnsFilter.load(ctx, f)
|
||||
require.NoError(t, err)
|
||||
require.NoError(tb, err)
|
||||
}
|
||||
|
||||
// newDNSFilter returns a new properly initialized DNS filter instance.
|
||||
func newDNSFilter(t *testing.T) (d *DNSFilter) {
|
||||
t.Helper()
|
||||
func newDNSFilter(tb testing.TB) (d *DNSFilter) {
|
||||
tb.Helper()
|
||||
|
||||
dnsFilter, err := New(&Config{
|
||||
Logger: slogutil.NewDiscardLogger(),
|
||||
DataDir: t.TempDir(),
|
||||
DataDir: tb.TempDir(),
|
||||
HTTPClient: &http.Client{
|
||||
Timeout: testTimeout,
|
||||
},
|
||||
}, nil)
|
||||
require.NoError(t, err)
|
||||
require.NoError(tb, err)
|
||||
|
||||
return dnsFilter
|
||||
}
|
||||
|
||||
@@ -63,37 +63,37 @@ func newChecker(host string) Checker {
|
||||
})
|
||||
}
|
||||
|
||||
func (d *DNSFilter) checkMatch(t *testing.T, hostname string, setts *Settings) {
|
||||
t.Helper()
|
||||
func (d *DNSFilter) checkMatch(tb testing.TB, hostname string, setts *Settings) {
|
||||
tb.Helper()
|
||||
|
||||
res, err := d.CheckHost(hostname, dns.TypeA, setts)
|
||||
require.NoErrorf(t, err, "host %q", hostname)
|
||||
require.NoErrorf(tb, err, "host %q", hostname)
|
||||
|
||||
assert.Truef(t, res.IsFiltered, "host %q", hostname)
|
||||
assert.Truef(tb, res.IsFiltered, "host %q", hostname)
|
||||
}
|
||||
|
||||
func (d *DNSFilter) checkMatchIP(t *testing.T, hostname, ip string, qtype uint16, setts *Settings) {
|
||||
t.Helper()
|
||||
func (d *DNSFilter) checkMatchIP(tb testing.TB, hostname, ip string, qtype uint16, setts *Settings) {
|
||||
tb.Helper()
|
||||
|
||||
res, err := d.CheckHost(hostname, qtype, setts)
|
||||
require.NoErrorf(t, err, "host %q", hostname, err)
|
||||
require.NotEmpty(t, res.Rules, "host %q", hostname)
|
||||
require.NoErrorf(tb, err, "host %q", hostname, err)
|
||||
require.NotEmpty(tb, res.Rules, "host %q", hostname)
|
||||
|
||||
assert.Truef(t, res.IsFiltered, "host %q", hostname)
|
||||
assert.Truef(tb, res.IsFiltered, "host %q", hostname)
|
||||
|
||||
r := res.Rules[0]
|
||||
require.NotNilf(t, r.IP, "Expected ip %s to match, actual: %v", ip, r.IP)
|
||||
require.NotNilf(tb, r.IP, "Expected ip %s to match, actual: %v", ip, r.IP)
|
||||
|
||||
assert.Equalf(t, ip, r.IP.String(), "host %q", hostname)
|
||||
assert.Equalf(tb, ip, r.IP.String(), "host %q", hostname)
|
||||
}
|
||||
|
||||
func (d *DNSFilter) checkMatchEmpty(t *testing.T, hostname string, setts *Settings) {
|
||||
t.Helper()
|
||||
func (d *DNSFilter) checkMatchEmpty(tb testing.TB, hostname string, setts *Settings) {
|
||||
tb.Helper()
|
||||
|
||||
res, err := d.CheckHost(hostname, dns.TypeA, setts)
|
||||
require.NoErrorf(t, err, "host %q", hostname)
|
||||
require.NoErrorf(tb, err, "host %q", hostname)
|
||||
|
||||
assert.Falsef(t, res.IsFiltered, "host %q", hostname)
|
||||
assert.Falsef(tb, res.IsFiltered, "host %q", hostname)
|
||||
}
|
||||
|
||||
func TestDNSFilter_CheckHost_hostRules(t *testing.T) {
|
||||
|
||||
@@ -44,7 +44,7 @@ func TestDNSFilter_CheckHost_hostsContainer(t *testing.T) {
|
||||
},
|
||||
}
|
||||
watcher := &aghtest.FSWatcher{
|
||||
OnStart: func(_ context.Context) (_ error) { panic("not implemented") },
|
||||
OnStart: func(ctx context.Context) (_ error) { panic(testutil.UnexpectedCall(ctx)) },
|
||||
OnEvents: func() (e <-chan struct{}) { return nil },
|
||||
OnAdd: func(name string) (err error) { return nil },
|
||||
OnShutdown: func(_ context.Context) (err error) { return nil },
|
||||
|
||||
@@ -75,13 +75,13 @@ func TestIDGenerator_Fix(t *testing.T) {
|
||||
|
||||
// assertUniqueIDs is a test helper that asserts that the IDs of filters are
|
||||
// unique.
|
||||
func assertUniqueIDs(t testing.TB, flts []FilterYAML) {
|
||||
t.Helper()
|
||||
func assertUniqueIDs(tb testing.TB, flts []FilterYAML) {
|
||||
tb.Helper()
|
||||
|
||||
uc := aghalg.UniqChecker[rulelist.URLFilterID]{}
|
||||
for _, f := range flts {
|
||||
uc.Add(f.ID)
|
||||
}
|
||||
|
||||
assert.NoError(t, uc.Validate())
|
||||
assert.NoError(tb, uc.Validate())
|
||||
}
|
||||
|
||||
@@ -209,20 +209,20 @@ func TestDNSFilter_handleRewriteHTTP(t *testing.T) {
|
||||
|
||||
// assertRewritesList checks if rewrites list equals the list received from the
|
||||
// handler by listURL.
|
||||
func assertRewritesList(t *testing.T, handler http.Handler, wantList []*rewriteJSON) {
|
||||
t.Helper()
|
||||
func assertRewritesList(tb testing.TB, handler http.Handler, wantList []*rewriteJSON) {
|
||||
tb.Helper()
|
||||
|
||||
r := httptest.NewRequest(http.MethodGet, listURL, nil)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
handler.ServeHTTP(w, r)
|
||||
require.Equal(t, http.StatusOK, w.Code)
|
||||
require.Equal(tb, http.StatusOK, w.Code)
|
||||
|
||||
var actual []*rewriteJSON
|
||||
err := json.NewDecoder(w.Body).Decode(&actual)
|
||||
require.NoError(t, err)
|
||||
require.NoError(tb, err)
|
||||
|
||||
assert.Equal(t, wantList, actual)
|
||||
assert.Equal(tb, wantList, actual)
|
||||
}
|
||||
|
||||
// rewriteEntriesToLegacyRewrites gets legacy rewrites from json entries.
|
||||
|
||||
@@ -52,8 +52,8 @@ func newURLFilterID() (id rulelist.URLFilterID) {
|
||||
// newFilter is a helper for creating new filters in tests. It does not
|
||||
// register the closing of the filter using t.Cleanup; callers must do that
|
||||
// either directly or by using the filter in an engine.
|
||||
func newFilter(t testing.TB, u *url.URL, name string) (f *rulelist.Filter) {
|
||||
t.Helper()
|
||||
func newFilter(tb testing.TB, u *url.URL, name string) (f *rulelist.Filter) {
|
||||
tb.Helper()
|
||||
|
||||
f, err := rulelist.NewFilter(&rulelist.FilterConfig{
|
||||
URL: u,
|
||||
@@ -62,7 +62,7 @@ func newFilter(t testing.TB, u *url.URL, name string) (f *rulelist.Filter) {
|
||||
URLFilterID: newURLFilterID(),
|
||||
Enabled: true,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.NoError(tb, err)
|
||||
|
||||
return f
|
||||
}
|
||||
@@ -71,24 +71,24 @@ func newFilter(t testing.TB, u *url.URL, name string) (f *rulelist.Filter) {
|
||||
// file and the HTTP-server. It also registers file removal and server stopping
|
||||
// using t.Cleanup.
|
||||
func newFilterLocations(
|
||||
t testing.TB,
|
||||
tb testing.TB,
|
||||
cacheDir string,
|
||||
fileData string,
|
||||
httpData string,
|
||||
) (fileURL, srvURL *url.URL) {
|
||||
t.Helper()
|
||||
tb.Helper()
|
||||
|
||||
f, err := os.CreateTemp(cacheDir, "")
|
||||
require.NoError(t, err)
|
||||
require.NoError(tb, err)
|
||||
|
||||
err = f.Close()
|
||||
require.NoError(t, err)
|
||||
require.NoError(tb, err)
|
||||
|
||||
filePath := f.Name()
|
||||
err = os.WriteFile(filePath, []byte(fileData), 0o644)
|
||||
require.NoError(t, err)
|
||||
require.NoError(tb, err)
|
||||
|
||||
testutil.CleanupAndRequireSuccess(t, func() (err error) {
|
||||
testutil.CleanupAndRequireSuccess(tb, func() (err error) {
|
||||
return os.Remove(filePath)
|
||||
})
|
||||
|
||||
@@ -98,10 +98,10 @@ func newFilterLocations(
|
||||
}
|
||||
|
||||
srv := newStringHTTPServer(httpData)
|
||||
t.Cleanup(srv.Close)
|
||||
tb.Cleanup(srv.Close)
|
||||
|
||||
srvURL, err = url.Parse(srv.URL)
|
||||
require.NoError(t, err)
|
||||
require.NoError(tb, err)
|
||||
|
||||
return fileURL, srvURL
|
||||
}
|
||||
|
||||
@@ -7,7 +7,6 @@ import (
|
||||
"encoding/binary"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"maps"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
@@ -48,20 +47,20 @@ var _ aghuser.SessionStorage = (*testSessionStorage)(nil)
|
||||
// panic.
|
||||
func newTestSessionStorage() (ts *testSessionStorage) {
|
||||
return &testSessionStorage{
|
||||
onNew: func(_ context.Context, u *aghuser.User) (_ *aghuser.Session, _ error) {
|
||||
panic(fmt.Errorf("unexpected call to testSessionStorage.New(%v)", u))
|
||||
onNew: func(ctx context.Context, u *aghuser.User) (_ *aghuser.Session, _ error) {
|
||||
panic(testutil.UnexpectedCall(ctx, u))
|
||||
},
|
||||
onFindByToken: func(
|
||||
_ context.Context,
|
||||
ctx context.Context,
|
||||
t aghuser.SessionToken,
|
||||
) (_ *aghuser.Session, err error) {
|
||||
panic(fmt.Errorf("unexpected call to testSessionStorage.FindByToken(%v)", t))
|
||||
panic(testutil.UnexpectedCall(ctx, t))
|
||||
},
|
||||
onDeleteByToken: func(_ context.Context, t aghuser.SessionToken) (_ error) {
|
||||
panic(fmt.Errorf("unexpected call to testSessionStorage.DeleteByToken(%v)", t))
|
||||
onDeleteByToken: func(ctx context.Context, t aghuser.SessionToken) (_ error) {
|
||||
panic(testutil.UnexpectedCall(ctx, t))
|
||||
},
|
||||
onClose: func() (_ error) {
|
||||
panic("unexpected call to testSessionStorage.Close")
|
||||
panic(testutil.UnexpectedCall())
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -110,17 +109,17 @@ type testUsersDB struct {
|
||||
// newTestUsersDB returns a new *testUsersDB all methods of which panic.
|
||||
func newTestUsersDB() (ts *testUsersDB) {
|
||||
return &testUsersDB{
|
||||
onAll: func(_ context.Context) (_ []*aghuser.User, _ error) {
|
||||
panic("unexpected call to testUsersDB.All")
|
||||
onAll: func(ctx context.Context) (_ []*aghuser.User, _ error) {
|
||||
panic(testutil.UnexpectedCall(ctx))
|
||||
},
|
||||
onByLogin: func(_ context.Context, l aghuser.Login) (_ *aghuser.User, _ error) {
|
||||
panic(fmt.Errorf("unexpected call to testUsersDB.ByLogin(%v)", l))
|
||||
onByLogin: func(ctx context.Context, l aghuser.Login) (_ *aghuser.User, _ error) {
|
||||
panic(testutil.UnexpectedCall(ctx, l))
|
||||
},
|
||||
onByUUID: func(_ context.Context, id aghuser.UserID) (_ *aghuser.User, _ error) {
|
||||
panic(fmt.Errorf("unexpected call to testUsersDB.ByUUID(%v)", id))
|
||||
onByUUID: func(ctx context.Context, id aghuser.UserID) (_ *aghuser.User, _ error) {
|
||||
panic(testutil.UnexpectedCall(ctx, id))
|
||||
},
|
||||
onCreate: func(_ context.Context, u *aghuser.User) (_ error) {
|
||||
panic(fmt.Errorf("unexpected call to testUsersDB.Create(%v)", u))
|
||||
onCreate: func(ctx context.Context, u *aghuser.User) (_ error) {
|
||||
panic(testutil.UnexpectedCall(ctx, u))
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -574,11 +573,11 @@ func TestAuth_ServeHTTP_auth(t *testing.T) {
|
||||
|
||||
// generateAuthCookie is a helper function that logs in with the provided
|
||||
// credentials and returns the resulting authentication cookie.
|
||||
func generateAuthCookie(t *testing.T, mux http.Handler, name, password string) (ac *http.Cookie) {
|
||||
t.Helper()
|
||||
func generateAuthCookie(tb testing.TB, mux http.Handler, name, password string) (ac *http.Cookie) {
|
||||
tb.Helper()
|
||||
|
||||
creds, err := json.Marshal(&loginJSON{Name: name, Password: password})
|
||||
require.NoError(t, err)
|
||||
require.NoError(tb, err)
|
||||
|
||||
r := httptest.NewRequest(http.MethodPost, "/control/login", bytes.NewReader(creds))
|
||||
r.Header.Set(httphdr.ContentType, aghhttp.HdrValApplicationJSON)
|
||||
@@ -594,20 +593,20 @@ func generateAuthCookie(t *testing.T, mux http.Handler, name, password string) (
|
||||
}
|
||||
}
|
||||
|
||||
require.NotNil(t, ac)
|
||||
require.NotNil(tb, ac)
|
||||
|
||||
return ac
|
||||
}
|
||||
|
||||
// assertHandlerStatusCode is a helper function that asserts the response status
|
||||
// code of a HTTP handler.
|
||||
func assertHandlerStatusCode(t *testing.T, h http.Handler, r *http.Request, wantCode int) {
|
||||
t.Helper()
|
||||
func assertHandlerStatusCode(tb testing.TB, h http.Handler, r *http.Request, wantCode int) {
|
||||
tb.Helper()
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
|
||||
assert.Equal(t, wantCode, w.Code)
|
||||
assert.Equal(tb, wantCode, w.Code)
|
||||
}
|
||||
|
||||
func TestAuth_ServeHTTP_logout(t *testing.T) {
|
||||
|
||||
@@ -12,12 +12,12 @@ import (
|
||||
|
||||
// newClientsContainer is a helper that creates a new clients container for
|
||||
// tests.
|
||||
func newClientsContainer(t *testing.T) (c *clientsContainer) {
|
||||
t.Helper()
|
||||
func newClientsContainer(tb testing.TB) (c *clientsContainer) {
|
||||
tb.Helper()
|
||||
|
||||
c = &clientsContainer{}
|
||||
|
||||
ctx := testutil.ContextWithTimeout(t, testTimeout)
|
||||
ctx := testutil.ContextWithTimeout(tb, testTimeout)
|
||||
err := c.Init(
|
||||
ctx,
|
||||
testLogger,
|
||||
@@ -32,7 +32,7 @@ func newClientsContainer(t *testing.T) (c *clientsContainer) {
|
||||
agh.EmptyConfigModifier{},
|
||||
)
|
||||
|
||||
require.NoError(t, err)
|
||||
require.NoError(tb, err)
|
||||
|
||||
return c
|
||||
}
|
||||
|
||||
@@ -39,14 +39,14 @@ func TestLimitRequestBody(t *testing.T) {
|
||||
want: []byte(nil),
|
||||
}}
|
||||
|
||||
makeHandler := func(t *testing.T, err *error) http.HandlerFunc {
|
||||
t.Helper()
|
||||
makeHandler := func(tb testing.TB, err *error) http.HandlerFunc {
|
||||
tb.Helper()
|
||||
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
var b []byte
|
||||
b, *err = io.ReadAll(r.Body)
|
||||
_, werr := w.Write(b)
|
||||
require.NoError(t, werr)
|
||||
require.NoError(tb, werr)
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -15,11 +15,11 @@ import (
|
||||
|
||||
// setupDNSIPs is a helper that sets up the server IP address configuration for
|
||||
// tests and also tears it down in a cleanup function.
|
||||
func setupDNSIPs(t testing.TB) {
|
||||
t.Helper()
|
||||
func setupDNSIPs(tb testing.TB) {
|
||||
tb.Helper()
|
||||
|
||||
prevConfig := config
|
||||
t.Cleanup(func() {
|
||||
tb.Cleanup(func() {
|
||||
config = prevConfig
|
||||
})
|
||||
|
||||
|
||||
@@ -9,26 +9,34 @@ import (
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func testParseOK(t *testing.T, ss ...string) options {
|
||||
t.Helper()
|
||||
// testParseOK is a helper that parses the command-line options and returns the
|
||||
// parsed options.
|
||||
func testParseOK(tb testing.TB, ss ...string) (o options) {
|
||||
tb.Helper()
|
||||
|
||||
o, _, err := parseCmdOpts("", ss)
|
||||
require.NoError(t, err)
|
||||
require.NoError(tb, err)
|
||||
|
||||
return o
|
||||
}
|
||||
|
||||
func testParseErr(t *testing.T, descr string, ss ...string) {
|
||||
t.Helper()
|
||||
// testParseErr is a helper that asserts that parsing the command-line options
|
||||
// fails with error.
|
||||
//
|
||||
// TODO(a.garipov): Search descr within an error.
|
||||
func testParseErr(tb testing.TB, descr string, ss ...string) {
|
||||
tb.Helper()
|
||||
|
||||
_, _, err := parseCmdOpts("", ss)
|
||||
require.Error(t, err)
|
||||
require.Errorf(tb, err, "should have got error: %s", descr)
|
||||
}
|
||||
|
||||
func testParseParamMissing(t *testing.T, param string) {
|
||||
t.Helper()
|
||||
// testParseParamMissing is a helper that asserts that parsing the command-line
|
||||
// options fails with error due to missing parameter.
|
||||
func testParseParamMissing(tb testing.TB, param string) {
|
||||
tb.Helper()
|
||||
|
||||
testParseErr(t, fmt.Sprintf("%s parameter missing", param), param)
|
||||
testParseErr(tb, fmt.Sprintf("%s parameter missing", param), param)
|
||||
}
|
||||
|
||||
func TestParseVerbose(t *testing.T) {
|
||||
|
||||
@@ -17,6 +17,7 @@ import (
|
||||
"github.com/AdguardTeam/AdGuardHome/internal/next/websvc"
|
||||
"github.com/AdguardTeam/dnsproxy/proxy"
|
||||
"github.com/AdguardTeam/golibs/netutil/urlutil"
|
||||
"github.com/AdguardTeam/golibs/testutil"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
@@ -45,7 +46,7 @@ func TestService_HandlePatchSettingsDNS(t *testing.T) {
|
||||
|
||||
return nil
|
||||
},
|
||||
OnShutdown: func(_ context.Context) (err error) { panic("not implemented") },
|
||||
OnShutdown: func(ctx context.Context) (_ error) { panic(testutil.UnexpectedCall(ctx)) },
|
||||
OnConfig: func() (c *dnssvc.Config) { return &dnssvc.Config{} },
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ import (
|
||||
"github.com/AdguardTeam/golibs/netutil/httputil"
|
||||
"github.com/AdguardTeam/golibs/netutil/urlutil"
|
||||
"github.com/AdguardTeam/golibs/testutil"
|
||||
"github.com/AdguardTeam/golibs/testutil/fakefs"
|
||||
"github.com/AdguardTeam/golibs/testutil/fakeio/fakefs"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
@@ -65,13 +65,17 @@ func (m *configManager) UpdateWeb(ctx context.Context, c *websvc.Config) (err er
|
||||
// newConfigManager returns a *configManager all methods of which panic.
|
||||
func newConfigManager() (m *configManager) {
|
||||
return &configManager{
|
||||
onDNS: func() (svc agh.ServiceWithConfig[*dnssvc.Config]) { panic("not implemented") },
|
||||
onWeb: func() (svc agh.ServiceWithConfig[*websvc.Config]) { panic("not implemented") },
|
||||
onUpdateDNS: func(_ context.Context, _ *dnssvc.Config) (err error) {
|
||||
panic("not implemented")
|
||||
onDNS: func() (_ agh.ServiceWithConfig[*dnssvc.Config]) {
|
||||
panic(testutil.UnexpectedCall())
|
||||
},
|
||||
onUpdateWeb: func(_ context.Context, _ *websvc.Config) (err error) {
|
||||
panic("not implemented")
|
||||
onWeb: func() (_ agh.ServiceWithConfig[*websvc.Config]) {
|
||||
panic(testutil.UnexpectedCall())
|
||||
},
|
||||
onUpdateDNS: func(ctx context.Context, c *dnssvc.Config) (_ error) {
|
||||
panic(testutil.UnexpectedCall(ctx, c))
|
||||
},
|
||||
onUpdateWeb: func(ctx context.Context, c *websvc.Config) (_ error) {
|
||||
panic(testutil.UnexpectedCall(ctx, c))
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -80,10 +84,10 @@ func newConfigManager() (m *configManager) {
|
||||
// sole address. It also registers a cleanup procedure, which shuts the
|
||||
// instance down.
|
||||
func newTestServer(
|
||||
t testing.TB,
|
||||
tb testing.TB,
|
||||
confMgr websvc.ConfigManager,
|
||||
) (svc *websvc.Service, addr netip.AddrPort) {
|
||||
t.Helper()
|
||||
tb.Helper()
|
||||
|
||||
c := &websvc.Config{
|
||||
Logger: slogutil.NewDiscardLogger(),
|
||||
@@ -103,17 +107,17 @@ func newTestServer(
|
||||
}
|
||||
|
||||
svc, err := websvc.New(c)
|
||||
require.NoError(t, err)
|
||||
require.NoError(tb, err)
|
||||
|
||||
err = svc.Start(testutil.ContextWithTimeout(t, testTimeout))
|
||||
require.NoError(t, err)
|
||||
testutil.CleanupAndRequireSuccess(t, func() (err error) {
|
||||
return svc.Shutdown(testutil.ContextWithTimeout(t, testTimeout))
|
||||
err = svc.Start(testutil.ContextWithTimeout(tb, testTimeout))
|
||||
require.NoError(tb, err)
|
||||
testutil.CleanupAndRequireSuccess(tb, func() (err error) {
|
||||
return svc.Shutdown(testutil.ContextWithTimeout(tb, testTimeout))
|
||||
})
|
||||
|
||||
c = svc.Config()
|
||||
require.NotNil(t, c)
|
||||
require.Len(t, c.Addresses, 1)
|
||||
require.NotNil(tb, c)
|
||||
require.Len(tb, c.Addresses, 1)
|
||||
|
||||
return svc, c.Addresses[0]
|
||||
}
|
||||
@@ -125,23 +129,23 @@ type jobj map[string]any
|
||||
// the response as well as checks that the status code is correct.
|
||||
//
|
||||
// TODO(a.garipov): Add helpers for other methods.
|
||||
func httpGet(t testing.TB, u *url.URL, wantCode int) (body []byte) {
|
||||
t.Helper()
|
||||
func httpGet(tb testing.TB, u *url.URL, wantCode int) (body []byte) {
|
||||
tb.Helper()
|
||||
|
||||
req, err := http.NewRequest(http.MethodGet, u.String(), nil)
|
||||
require.NoErrorf(t, err, "creating req")
|
||||
require.NoErrorf(tb, err, "creating req")
|
||||
|
||||
httpCli := &http.Client{
|
||||
Timeout: testTimeout,
|
||||
}
|
||||
resp, err := httpCli.Do(req)
|
||||
require.NoErrorf(t, err, "performing req")
|
||||
require.Equal(t, wantCode, resp.StatusCode)
|
||||
require.NoErrorf(tb, err, "performing req")
|
||||
require.Equal(tb, wantCode, resp.StatusCode)
|
||||
|
||||
testutil.CleanupAndRequireSuccess(t, resp.Body.Close)
|
||||
testutil.CleanupAndRequireSuccess(tb, resp.Body.Close)
|
||||
|
||||
body, err = io.ReadAll(resp.Body)
|
||||
require.NoErrorf(t, err, "reading body")
|
||||
require.NoErrorf(tb, err, "reading body")
|
||||
|
||||
return body
|
||||
}
|
||||
@@ -151,26 +155,26 @@ func httpGet(t testing.TB, u *url.URL, wantCode int) (body []byte) {
|
||||
// checks that the status code is correct.
|
||||
//
|
||||
// TODO(a.garipov): Add helpers for other methods.
|
||||
func httpPatch(t testing.TB, u *url.URL, reqBody any, wantCode int) (body []byte) {
|
||||
t.Helper()
|
||||
func httpPatch(tb testing.TB, u *url.URL, reqBody any, wantCode int) (body []byte) {
|
||||
tb.Helper()
|
||||
|
||||
b, err := json.Marshal(reqBody)
|
||||
require.NoErrorf(t, err, "marshaling reqBody")
|
||||
require.NoErrorf(tb, err, "marshaling reqBody")
|
||||
|
||||
req, err := http.NewRequest(http.MethodPatch, u.String(), bytes.NewReader(b))
|
||||
require.NoErrorf(t, err, "creating req")
|
||||
require.NoErrorf(tb, err, "creating req")
|
||||
|
||||
httpCli := &http.Client{
|
||||
Timeout: testTimeout,
|
||||
}
|
||||
resp, err := httpCli.Do(req)
|
||||
require.NoErrorf(t, err, "performing req")
|
||||
require.Equal(t, wantCode, resp.StatusCode)
|
||||
require.NoErrorf(tb, err, "performing req")
|
||||
require.Equal(tb, wantCode, resp.StatusCode)
|
||||
|
||||
testutil.CleanupAndRequireSuccess(t, resp.Body.Close)
|
||||
testutil.CleanupAndRequireSuccess(tb, resp.Body.Close)
|
||||
|
||||
body, err = io.ReadAll(resp.Body)
|
||||
require.NoErrorf(t, err, "reading body")
|
||||
require.NoErrorf(tb, err, "reading body")
|
||||
|
||||
return body
|
||||
}
|
||||
|
||||
@@ -390,20 +390,20 @@ func addEntry(l *queryLog, host string, answerStr, client net.IP) {
|
||||
l.Add(params)
|
||||
}
|
||||
|
||||
func assertLogEntry(t *testing.T, entry *logEntry, host string, answer, client net.IP) {
|
||||
t.Helper()
|
||||
func assertLogEntry(tb testing.TB, entry *logEntry, host string, answer, client net.IP) {
|
||||
tb.Helper()
|
||||
|
||||
require.NotNil(t, entry)
|
||||
require.NotNil(tb, entry)
|
||||
|
||||
assert.Equal(t, host, entry.QHost)
|
||||
assert.Equal(t, client, entry.IP)
|
||||
assert.Equal(t, "A", entry.QType)
|
||||
assert.Equal(t, "IN", entry.QClass)
|
||||
assert.Equal(tb, host, entry.QHost)
|
||||
assert.Equal(tb, client, entry.IP)
|
||||
assert.Equal(tb, "A", entry.QType)
|
||||
assert.Equal(tb, "IN", entry.QClass)
|
||||
|
||||
msg := &dns.Msg{}
|
||||
require.NoError(t, msg.Unpack(entry.Answer))
|
||||
require.Len(t, msg.Answer, 1)
|
||||
require.NoError(tb, msg.Unpack(entry.Answer))
|
||||
require.Len(tb, msg.Answer, 1)
|
||||
|
||||
a := testutil.RequireTypeAssert[*dns.A](t, msg.Answer[0])
|
||||
assert.Equal(t, answer, a.A.To16())
|
||||
a := testutil.RequireTypeAssert[*dns.A](tb, msg.Answer[0])
|
||||
assert.Equal(tb, answer, a.A.To16())
|
||||
}
|
||||
|
||||
@@ -20,17 +20,17 @@ import (
|
||||
|
||||
// prepareTestFile prepares one test query log file with the specified lines
|
||||
// count.
|
||||
func prepareTestFile(t *testing.T, dir string, linesNum int) (name string) {
|
||||
t.Helper()
|
||||
func prepareTestFile(tb testing.TB, dir string, linesNum int) (name string) {
|
||||
tb.Helper()
|
||||
|
||||
f, err := os.CreateTemp(dir, "*.txt")
|
||||
require.NoError(t, err)
|
||||
require.NoError(tb, err)
|
||||
|
||||
// Use defer and not t.Cleanup to make sure that the file is closed
|
||||
// after this function is done.
|
||||
defer func() {
|
||||
derr := f.Close()
|
||||
require.NoError(t, derr)
|
||||
require.NoError(tb, derr)
|
||||
}()
|
||||
|
||||
const ans = `"AAAAAAABAAEAAAAAB2V4YW1wbGUDb3JnAAABAAEHZXhhbXBsZQNvcmcAAAEAAQAAAAAABAECAwQ="`
|
||||
@@ -49,7 +49,7 @@ func prepareTestFile(t *testing.T, dir string, linesNum int) (name string) {
|
||||
line := fmt.Sprintf(format, ip, lineTime.Format(time.RFC3339Nano))
|
||||
|
||||
_, err = f.WriteString(line)
|
||||
require.NoError(t, err)
|
||||
require.NoError(tb, err)
|
||||
}
|
||||
|
||||
return f.Name()
|
||||
@@ -57,18 +57,18 @@ func prepareTestFile(t *testing.T, dir string, linesNum int) (name string) {
|
||||
|
||||
// prepareTestFiles prepares several test query log files, each with the
|
||||
// specified lines count.
|
||||
func prepareTestFiles(t *testing.T, filesNum, linesNum int) []string {
|
||||
t.Helper()
|
||||
func prepareTestFiles(tb testing.TB, filesNum, linesNum int) []string {
|
||||
tb.Helper()
|
||||
|
||||
if filesNum == 0 {
|
||||
return []string{}
|
||||
}
|
||||
|
||||
dir := t.TempDir()
|
||||
dir := tb.TempDir()
|
||||
|
||||
files := make([]string, filesNum)
|
||||
for i := range files {
|
||||
files[filesNum-i-1] = prepareTestFile(t, dir, linesNum)
|
||||
files[filesNum-i-1] = prepareTestFile(tb, dir, linesNum)
|
||||
}
|
||||
|
||||
return files
|
||||
@@ -76,17 +76,17 @@ func prepareTestFiles(t *testing.T, filesNum, linesNum int) []string {
|
||||
|
||||
// newTestQLogFile creates new *qLogFile for tests and registers the required
|
||||
// cleanup functions.
|
||||
func newTestQLogFile(t *testing.T, linesNum int) (file *qLogFile) {
|
||||
t.Helper()
|
||||
func newTestQLogFile(tb testing.TB, linesNum int) (file *qLogFile) {
|
||||
tb.Helper()
|
||||
|
||||
testFile := prepareTestFiles(t, 1, linesNum)[0]
|
||||
testFile := prepareTestFiles(tb, 1, linesNum)[0]
|
||||
|
||||
// Create the new qLogFile instance.
|
||||
file, err := newQLogFile(testFile)
|
||||
require.NoError(t, err)
|
||||
require.NoError(tb, err)
|
||||
|
||||
assert.NotNil(t, file)
|
||||
testutil.CleanupAndRequireSuccess(t, file.Close)
|
||||
assert.NotNil(tb, file)
|
||||
testutil.CleanupAndRequireSuccess(tb, file.Close)
|
||||
|
||||
return file
|
||||
}
|
||||
|
||||
@@ -13,20 +13,20 @@ import (
|
||||
|
||||
// newTestQLogReader creates new *qLogReader for tests and registers the
|
||||
// required cleanup functions.
|
||||
func newTestQLogReader(t *testing.T, filesNum, linesNum int) (reader *qLogReader) {
|
||||
t.Helper()
|
||||
func newTestQLogReader(tb testing.TB, filesNum, linesNum int) (reader *qLogReader) {
|
||||
tb.Helper()
|
||||
|
||||
testFiles := prepareTestFiles(t, filesNum, linesNum)
|
||||
testFiles := prepareTestFiles(tb, filesNum, linesNum)
|
||||
|
||||
logger := slogutil.NewDiscardLogger()
|
||||
ctx := testutil.ContextWithTimeout(t, testTimeout)
|
||||
ctx := testutil.ContextWithTimeout(tb, testTimeout)
|
||||
|
||||
// Create the new qLogReader instance.
|
||||
reader, err := newQLogReader(ctx, logger, testFiles)
|
||||
require.NoError(t, err)
|
||||
require.NoError(tb, err)
|
||||
|
||||
assert.NotNil(t, reader)
|
||||
testutil.CleanupAndRequireSuccess(t, reader.Close)
|
||||
assert.NotNil(tb, reader)
|
||||
testutil.CleanupAndRequireSuccess(tb, reader.Close)
|
||||
|
||||
return reader
|
||||
}
|
||||
|
||||
@@ -26,25 +26,25 @@ import (
|
||||
// constUnitID is the UnitIDGenFunc which always return 0.
|
||||
func constUnitID() (id uint32) { return 0 }
|
||||
|
||||
func assertSuccessAndUnmarshal(t *testing.T, to any, handler http.Handler, req *http.Request) {
|
||||
t.Helper()
|
||||
func assertSuccessAndUnmarshal(tb testing.TB, to any, handler http.Handler, req *http.Request) {
|
||||
tb.Helper()
|
||||
|
||||
require.NotNil(t, handler)
|
||||
require.NotNil(tb, handler)
|
||||
|
||||
rw := httptest.NewRecorder()
|
||||
|
||||
handler.ServeHTTP(rw, req)
|
||||
require.Equal(t, http.StatusOK, rw.Code)
|
||||
require.Equal(tb, http.StatusOK, rw.Code)
|
||||
|
||||
data := rw.Body.Bytes()
|
||||
if to == nil {
|
||||
assert.Empty(t, data)
|
||||
assert.Empty(tb, data)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
err := json.Unmarshal(data, to)
|
||||
require.NoError(t, err)
|
||||
require.NoError(tb, err)
|
||||
}
|
||||
|
||||
func TestStats(t *testing.T) {
|
||||
|
||||
Reference in New Issue
Block a user