| 1 | package callstest |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "os" |
| 6 | "runtime" |
| 7 | "strings" |
| 8 | "testing" |
| 9 | "time" |
| 10 | |
| 11 | "amadan.net/oficina/calls/internal/calls/keymailtest" |
| 12 | ) |
| 13 | |
| 14 | // TestMain keeps Keymail classification inside the process: every POST |
| 15 | // /signin now classifies its address (auth.go's gateBegin), and without |
| 16 | // this each one would ask the real network whether example.com runs |
| 17 | // Keymail. Every DNS query is answered NXDOMAIN; no fixture is |
| 18 | // registered here, so every address is plain email. |
| 19 | func TestMain(m *testing.M) { |
| 20 | restore, err := keymailtest.Install() |
| 21 | if err != nil { |
| 22 | fmt.Fprintln(os.Stderr, "keymailtest.Install:", err) |
| 23 | os.Exit(1) |
| 24 | } |
| 25 | code := m.Run() |
| 26 | // No test may leave a sign-in mail worker running: every app a test |
| 27 | // builds has its queue closed in cleanup (Runtime.Close, a |
| 28 | // TestHandle's stop, or buildForTest). |
| 29 | if code == 0 { |
| 30 | deadline := time.Now().Add(5 * time.Second) |
| 31 | for mailWorkers() > 0 && time.Now().Before(deadline) { |
| 32 | time.Sleep(10 * time.Millisecond) |
| 33 | } |
| 34 | if n := mailWorkers(); n > 0 { |
| 35 | fmt.Fprintf(os.Stderr, "FAIL: %d sign-in mail queue goroutines still running after the tests\n", n) |
| 36 | code = 1 |
| 37 | } |
| 38 | } |
| 39 | restore() |
| 40 | os.Exit(code) |
| 41 | } |
| 42 | |
| 43 | // mailWorkers counts goroutines running a sign-in mail queue's worker |
| 44 | // or log pump (internal/calls/signin_mail.go). |
| 45 | func mailWorkers() int { |
| 46 | buf := make([]byte, 1<<22) |
| 47 | stacks := string(buf[:runtime.Stack(buf, true)]) |
| 48 | return strings.Count(stacks, "(*mailQueue).run(") + strings.Count(stacks, "(*mailQueue).pump(") |
| 49 | } |
| 50 | |