oficina / calendar Public

Clone
git clone https://amadan.net/oficina/calendar

Plain git — no account needed to clone.

Download

Download this file

1package calendartest
2
3import (
4 "context"
5 "errors"
6 "fmt"
7 "net"
8 "os"
9 "runtime"
10 "strings"
11 "testing"
12 "time"
13
14 "amadan.net/oficina/calendar/internal/calendar/keymailtest"
15)
16
17// TestMain keeps Keymail classification inside the process: every POST
18// /signin now classifies its address, and without this each one would
19// ask the real network whether example.com runs Keymail. Every DNS
20// query is answered NXDOMAIN; no fixture is registered here, so every
21// address is plain email.
22func TestMain(m *testing.M) {
23 restore, err := keymailtest.Install()
24 if err != nil {
25 fmt.Fprintln(os.Stderr, "keymailtest.Install:", err)
26 os.Exit(1)
27 }
28 code := m.Run()
29 // No test may leave a sign-in mail worker running: every app a test
30 // builds is closed in its cleanup.
31 if code == 0 {
32 deadline := time.Now().Add(5 * time.Second)
33 for mailWorkers() > 0 && time.Now().Before(deadline) {
34 time.Sleep(10 * time.Millisecond)
35 }
36 if n := mailWorkers(); n > 0 {
37 fmt.Fprintf(os.Stderr, "FAIL: %d sign-in mail queue goroutines still running after the tests\n", n)
38 code = 1
39 }
40 }
41 restore()
42 os.Exit(code)
43}
44
45// mailWorkers counts goroutines running a sign-in mail queue's worker
46// or log pump (internal/calendar/signin_mail.go).
47func mailWorkers() int {
48 buf := make([]byte, 1<<22)
49 stacks := string(buf[:runtime.Stack(buf, true)])
50 return strings.Count(stacks, "(*mailQueue).run(") + strings.Count(stacks, "(*mailQueue).pump(")
51}
52
53// TestKeymailDiscoveryStaysInProcess: every unforced POST /signin
54// classifies its address (rastrillo/auth's Keymail discovery), so this
55// package's tests must not ask the real network whether example.com runs
56// Keymail. With keymailtest installed every query is answered NXDOMAIN
57// in-process, so even example.com, which public DNS resolves, must not.
58func TestKeymailDiscoveryStaysInProcess(t *testing.T) {
59 ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
60 defer cancel()
61 addrs, err := net.DefaultResolver.LookupHost(ctx, "example.com")
62 var dnsErr *net.DNSError
63 if !errors.As(err, &dnsErr) || !dnsErr.IsNotFound {
64 t.Fatalf("LookupHost(example.com) = %v, %v; want NXDOMAIN from keymailtest's in-process resolver", addrs, err)
65 }
66}
67