| 1 | package filelock |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "path/filepath" |
| 7 | "testing" |
| 8 | "time" |
| 9 | ) |
| 10 | |
| 11 | func TestAcquireHonorsDeadlineAndRecoversAfterRelease(t *testing.T) { |
| 12 | path := filepath.Join(t.TempDir(), "state.lock") |
| 13 | release, err := Acquire(context.Background(), path) |
| 14 | if err != nil { |
| 15 | t.Fatalf("first acquire: %v", err) |
| 16 | } |
| 17 | |
| 18 | ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) |
| 19 | defer cancel() |
| 20 | if _, err := Acquire(ctx, path); !errors.Is(err, context.DeadlineExceeded) { |
| 21 | t.Fatalf("contended acquire error = %v, want deadline exceeded", err) |
| 22 | } |
| 23 | |
| 24 | release() |
| 25 | secondRelease, err := Acquire(context.Background(), path) |
| 26 | if err != nil { |
| 27 | t.Fatalf("acquire after release: %v", err) |
| 28 | } |
| 29 | secondRelease() |
| 30 | } |
| 31 | |
| 32 | func TestLocalRegistryReclaimsReleasedEntries(t *testing.T) { |
| 33 | before := RegistrySizeForTest() |
| 34 | path := filepath.Join(t.TempDir(), "ephemeral.lock") |
| 35 | release, err := Acquire(context.Background(), path) |
| 36 | if err != nil { |
| 37 | t.Fatal(err) |
| 38 | } |
| 39 | if RegistrySizeForTest() <= before { |
| 40 | t.Fatal("registry should grow while lock is held") |
| 41 | } |
| 42 | release() |
| 43 | if got := RegistrySizeForTest(); got != before { |
| 44 | t.Fatalf("registry size after release = %d, want %d (reclaimed)", got, before) |
| 45 | } |
| 46 | |
| 47 | // Re-acquire still works after reclaim. |
| 48 | release2, err := Acquire(context.Background(), path) |
| 49 | if err != nil { |
| 50 | t.Fatal(err) |
| 51 | } |
| 52 | release2() |
| 53 | if got := RegistrySizeForTest(); got != before { |
| 54 | t.Fatalf("registry size after second cycle = %d, want %d", got, before) |
| 55 | } |
| 56 | } |
| 57 |