| 1 | package historywork |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "strings" |
| 7 | "testing" |
| 8 | ) |
| 9 | |
| 10 | func TestReaderBoundsDecoderReadsAndChecksCancellation(t *testing.T) { |
| 11 | ctx, cancel := context.WithCancel(t.Context()) |
| 12 | r := &Reader{Context: ctx, Source: strings.NewReader(strings.Repeat("x", 2*ReadChunk))} |
| 13 | buf := make([]byte, 2*ReadChunk) |
| 14 | if n, err := r.Read(buf); err != nil || n != ReadChunk { |
| 15 | t.Fatalf("read=%d %v", n, err) |
| 16 | } |
| 17 | cancel() |
| 18 | if n, err := r.Read(buf); n != 0 || !errors.Is(err, context.Canceled) { |
| 19 | t.Fatalf("cancelled read=%d %v", n, err) |
| 20 | } |
| 21 | } |
| 22 | |
| 23 | func TestForegroundPausesBackgroundAndReleaseIsIdempotent(t *testing.T) { |
| 24 | var c Coordinator |
| 25 | release, err := c.Foreground(t.Context()) |
| 26 | if err != nil { |
| 27 | t.Fatal(err) |
| 28 | } |
| 29 | ctx, cancel := context.WithCancel(t.Context()) |
| 30 | cancel() |
| 31 | if _, err := c.Background(ctx); !errors.Is(err, context.Canceled) { |
| 32 | t.Fatalf("background admission=%v", err) |
| 33 | } |
| 34 | release() |
| 35 | release() |
| 36 | bg, err := c.Background(t.Context()) |
| 37 | if err != nil { |
| 38 | t.Fatal(err) |
| 39 | } |
| 40 | bg() |
| 41 | bg() |
| 42 | } |
| 43 | |
| 44 | func TestYieldingBackgroundDoesNotTrapPriorityMetadataBehindForeground(t *testing.T) { |
| 45 | var c Coordinator |
| 46 | foreground, err := c.Foreground(t.Context()) |
| 47 | if err != nil { |
| 48 | t.Fatal(err) |
| 49 | } |
| 50 | defer foreground() |
| 51 | if _, err := c.BackgroundSliceYielding(t.Context(), false); !errors.Is(err, ErrForegroundActive) { |
| 52 | t.Fatalf("P2 must yield to its queue, got %v", err) |
| 53 | } |
| 54 | metadata, err := c.BackgroundSliceYielding(t.Context(), true) |
| 55 | if err != nil { |
| 56 | t.Fatal(err) |
| 57 | } |
| 58 | metadata(0) |
| 59 | if got := c.Diagnostics(); got.BackgroundSlices != 1 || got.ForegroundActive != 1 { |
| 60 | t.Fatalf("metadata incorrectly waited for or released execution preparation: %+v", got) |
| 61 | } |
| 62 | } |
| 63 |