1
0
mirror of https://blitiri.com.ar/repos/chasquid synced 2026-10-29 15:02:30 +00:00

test: Use modern testing features instead of custom helpers

Many of our tests rely on helpers that predate features which are now
available in the standard library.

This patch replaces them with the standard equivalents:

- MustTempDir/RemoveIfOk -> t.ArtifactDir() or t.TempDir() (depending on
  whether it is useful to keep the data on request).
- GetFreePort + waitForServer -> opening the listeners before starting
  the servers. To support this, localrpc.Server gains a Serve method. We
  may re-introduce these in the future if more use cases appear.
- WaitFor and real-time timing checks -> testing/synctest.
- context.Background() -> t.Context().
- Benchmark b.N loops -> b.Loop().
- reflect.DeepEqual -> cmp.Diff, and proto.Equal for protobufs.
This commit is contained in:
Alberto Bertogli
2026-10-03 10:34:35 +01:00
parent 8d763f450d
commit 8b19760f4e
30 changed files with 495 additions and 763 deletions
+9 -69
View File
@@ -11,78 +11,18 @@ import (
"math/big"
"net"
"os"
"strings"
"sync"
"testing"
"time"
)
// MustTempDir creates a temporary directory, or dies trying.
func MustTempDir(t *testing.T) string {
dir, err := os.MkdirTemp("", "testlib_")
if err != nil {
t.Fatal(err)
}
err = os.Chdir(dir)
if err != nil {
t.Fatal(err)
}
t.Logf("test directory: %q", dir)
return dir
}
// RemoveIfOk removes the given directory, but only if we have not failed. We
// want to keep the failed directories for debugging.
func RemoveIfOk(t *testing.T, dir string) {
// Safeguard, to make sure we only remove test directories.
// This should help prevent accidental deletions.
if !strings.Contains(dir, "testlib_") {
panic("invalid/dangerous directory")
}
if !t.Failed() {
os.RemoveAll(dir)
}
}
// Rewrite a file with the given contents.
func Rewrite(t *testing.T, path, contents string) error {
// Safeguard, to make sure we only mess with test files.
if !strings.Contains(path, "testlib_") {
panic("invalid/dangerous path")
}
// Rewrite a file with the given contents, or fail the test.
func Rewrite(t *testing.T, path, contents string) {
t.Helper()
err := os.WriteFile(path, []byte(contents), 0600)
if err != nil {
t.Errorf("failed to rewrite file: %v", err)
t.Fatalf("failed to rewrite file: %v", err)
}
return err
}
// GetFreePort returns a free TCP port. This is hacky and not race-free, but
// it works well enough for testing purposes.
func GetFreePort() string {
l, err := net.Listen("tcp", "localhost:0")
if err != nil {
panic(err)
}
defer l.Close()
return l.Addr().String()
}
// WaitFor f to return true (returns true), or d to pass (returns false).
func WaitFor(f func() bool, d time.Duration) bool {
start := time.Now()
for time.Since(start) < d {
if f() {
return true
}
time.Sleep(20 * time.Millisecond)
}
return false
}
type deliverRequest struct {
@@ -97,27 +37,27 @@ type TestCourier struct {
wg sync.WaitGroup
Requests []*deliverRequest
ReqFor map[string]*deliverRequest
sync.Mutex
mu sync.Mutex
}
// Deliver the given mail (saving it in tc.Requests).
func (tc *TestCourier) Deliver(from string, to string, data []byte) (error, bool) {
defer tc.wg.Done()
dr := &deliverRequest{from, to, data, nil}
tc.Lock()
tc.mu.Lock()
tc.Requests = append(tc.Requests, dr)
tc.ReqFor[to] = dr
tc.Unlock()
tc.mu.Unlock()
return nil, false
}
func (tc *TestCourier) Forward(from string, to string, data []byte, servers []string) (error, bool) {
defer tc.wg.Done()
dr := &deliverRequest{from, to, data, servers}
tc.Lock()
tc.mu.Lock()
tc.Requests = append(tc.Requests, dr)
tc.ReqFor[to] = dr
tc.Unlock()
tc.mu.Unlock()
return nil, false
}
+9 -90
View File
@@ -1,107 +1,26 @@
package testlib
import (
"errors"
"io/fs"
"os"
"testing"
"time"
)
func TestBasic(t *testing.T) {
dir := MustTempDir(t)
if err := os.WriteFile(dir+"/file", nil, 0660); err != nil {
t.Fatalf("could not create file in %s: %v", dir, err)
}
wd, err := os.Getwd()
if err != nil {
t.Fatalf("could not get working directory: %v", err)
}
if wd != dir {
t.Errorf("MustTempDir did not change directory")
t.Errorf(" expected %q, got %q", dir, wd)
}
RemoveIfOk(t, dir)
if _, err := os.Stat(dir); !errors.Is(err, fs.ErrNotExist) {
t.Fatalf("%s existed, should have been deleted: %v", dir, err)
}
}
func TestRemoveCheck(t *testing.T) {
defer func() {
if r := recover(); r != nil {
t.Logf("recovered: %v", r)
} else {
t.Fatalf("check did not panic as expected")
}
}()
RemoveIfOk(t, "/tmp/something")
}
func TestLeaveDirOnError(t *testing.T) {
myt := &testing.T{}
dir := MustTempDir(myt)
myt.Errorf("something bad happened")
RemoveIfOk(myt, dir)
if _, err := os.Stat(dir); errors.Is(err, fs.ErrNotExist) {
t.Fatalf("%s was removed, should have been kept", dir)
}
// Remove the directory for real this time.
RemoveIfOk(t, dir)
}
func TestRewriteSafeguard(t *testing.T) {
myt := &testing.T{}
defer func() {
if r := recover(); r != nil {
t.Logf("recovered: %v", r)
} else {
t.Fatalf("check did not panic as expected")
}
}()
Rewrite(myt, "/something", "test")
}
func TestRewrite(t *testing.T) {
dir := MustTempDir(t)
defer RemoveIfOk(t, dir)
fname := t.TempDir() + "/file"
Rewrite(t, fname, "hola")
Rewrite(t, fname, "chau")
myt := &testing.T{}
Rewrite(myt, dir+"/file", "hola")
if myt.Failed() {
t.Errorf("basic rewrite failed")
data, err := os.ReadFile(fname)
if err != nil {
t.Fatalf("failed to read file: %v", err)
}
}
func TestGetFreePort(t *testing.T) {
p := GetFreePort()
if p == "" {
t.Errorf("failed to get free port")
}
}
func TestWaitFor(t *testing.T) {
ok := WaitFor(func() bool { return true }, 20*time.Millisecond)
if !ok {
t.Errorf("WaitFor(true) timed out")
}
ok = WaitFor(func() bool { return false }, 20*time.Millisecond)
if ok {
t.Errorf("WaitFor(false) worked")
if string(data) != "chau" {
t.Errorf("file content: got %q, expected %q", data, "chau")
}
}
func TestGenerateCert(t *testing.T) {
dir := MustTempDir(t)
defer os.RemoveAll(dir)
conf, err := GenerateCert(dir)
conf, err := GenerateCert(t.TempDir())
if err != nil {
t.Errorf("GenerateCert returned error: %v", err)
}