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