internal/covsnap/covsnap_test.go
Ref: Size: 1.9 KiB History
package covsnap
import (
"context"
"os"
"syscall"
"testing"
"time"
)
// TestInstall_SignalTriggersWrite verifies that once Install is called with
// GOCOVERDIR set, sending SIGUSR1 to the process invokes the write seam with
// the configured directory.
func TestInstall_SignalTriggersWrite(t *testing.T) {
dir := t.TempDir()
t.Setenv("GOCOVERDIR", dir)
origWrite := write
t.Cleanup(func() { write = origWrite })
calls := make(chan string, 1)
write = func(d string) error {
calls <- d
return nil
}
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel)
// Tear the handler down synchronously when the test ends: without stop the
// SIGUSR1 handler outlives this test, and the next test's signal races this
// test's write seam through the package-level var.
stop := Install(ctx)
t.Cleanup(stop)
if err := syscall.Kill(os.Getpid(), syscall.SIGUSR1); err != nil {
t.Fatalf("failed to send SIGUSR1: %v", err)
}
select {
case got := <-calls:
if got != dir {
t.Fatalf("write called with dir %q, want %q", got, dir)
}
case <-time.After(2 * time.Second):
t.Fatal("timed out waiting for write to be called after SIGUSR1")
}
}
// TestInstall_NoGOCOVERDIR verifies that Install is a no-op when GOCOVERDIR
// is unset: no handler is registered, so sending SIGUSR1 never calls write
// and never panics.
func TestInstall_NoGOCOVERDIR(t *testing.T) {
t.Setenv("GOCOVERDIR", "")
origWrite := write
t.Cleanup(func() { write = origWrite })
calls := make(chan string, 1)
write = func(d string) error {
calls <- d
return nil
}
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel)
stop := Install(ctx)
t.Cleanup(stop)
if err := syscall.Kill(os.Getpid(), syscall.SIGUSR1); err != nil {
t.Fatalf("failed to send SIGUSR1: %v", err)
}
select {
case got := <-calls:
t.Fatalf("write unexpectedly called with dir %q", got)
case <-time.After(200 * time.Millisecond):
// expected: nothing fired
}
}