1
0
mirror of https://blitiri.com.ar/repos/chasquid synced 2026-10-28 15:02:28 +00:00
Files
go-chasquid-smtp/internal/localrpc/client_test.go
T
Alberto Bertogli 8b19760f4e 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.
2026-10-03 10:34:35 +01:00

77 lines
1.8 KiB
Go

package localrpc
import (
"bufio"
"errors"
"io/fs"
"net"
"net/textproto"
"path/filepath"
"testing"
)
// NewFakeServer starts a fake server listening on the given path, which
// replies with the given output to every request.
func NewFakeServer(t *testing.T, path, output string) {
t.Helper()
lis, err := net.Listen("unix", path)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { lis.Close() })
go fakeServe(t, lis, output)
}
func fakeServe(t *testing.T, lis net.Listener, output string) {
for {
conn, err := lis.Accept()
if err != nil {
// Listener closed at the end of the test.
return
}
t.Logf("FakeServer %v: accepted ", conn)
name, inS, err := readRequest(
textproto.NewReader(bufio.NewReader(conn)))
t.Logf("FakeServer %v: readRequest: %q %q / %v", conn, name, inS, err)
n, err := conn.Write([]byte(output))
t.Logf("FakeServer %v: writeMessage(%q): %d %v",
conn, output, n, err)
t.Logf("FakeServer %v: closing", conn)
conn.Close()
}
}
func TestBadServer(t *testing.T) {
socketPath := filepath.Join(t.TempDir(), "rpc.sock")
// textproto client expects a numeric code, this should cause ReadCodeLine
// to fail with textproto.ProtocolError.
NewFakeServer(t, socketPath, "xxx")
client := NewClient(socketPath)
_, err := client.Call("Echo")
if err == nil {
t.Fatal("expected error")
}
if _, ok := errors.AsType[textproto.ProtocolError](err); !ok {
t.Errorf("wanted textproto.ProtocolError, got: %v (%T)", err, err)
}
}
func TestBadSocket(t *testing.T) {
c := NewClient("/does/not/exist")
_, err := c.Call("Echo")
opErr, ok := err.(*net.OpError)
if !ok {
t.Fatalf("expected net.OpError, got %q (%T)", err, err)
}
if !errors.Is(err, fs.ErrNotExist) {
t.Errorf("wanted ErrNotExist, got: %q (%T)", opErr.Err, opErr.Err)
}
}