MCPcopy Create free account
hub / github.com/cli/cli / TestTryLock

Function TestTryLock

internal/flock/flock_test.go:15–101  ·  view source on GitHub ↗
(t *testing.T)

Source from the content-addressed store, hash-verified

13)
14
15func TestTryLock(t *testing.T) {
16 tests := []struct {
17 name string
18 setup func(t *testing.T) string // returns lock path
19 wantErr error
20 verify func(t *testing.T, f *os.File)
21 }{
22 {
23 name: "acquires lock and returns writable file handle",
24 setup: func(t *testing.T) string {
25 return filepath.Join(t.TempDir(), "test.lock")
26 },
27 verify: func(t *testing.T, f *os.File) {
28 t.Helper()
29 _, err := f.WriteString("hello")
30 require.NoError(t, err)
31 _, err = f.Seek(0, 0)
32 require.NoError(t, err)
33 buf := make([]byte, 5)
34 n, err := f.Read(buf)
35 assert.NoError(t, err)
36 assert.Equal(t, "hello", string(buf[:n]))
37 },
38 },
39 {
40 name: "creates lock file if it does not exist",
41 setup: func(t *testing.T) string {
42 dir := filepath.Join(t.TempDir(), "subdir")
43 require.NoError(t, os.MkdirAll(dir, 0o755))
44 return filepath.Join(dir, "new.lock")
45 },
46 verify: func(t *testing.T, f *os.File) {
47 t.Helper()
48 _, err := os.Stat(f.Name())
49 assert.NoError(t, err)
50 },
51 },
52 {
53 name: "second lock on same path returns ErrLocked",
54 setup: func(t *testing.T) string {
55 lockPath := filepath.Join(t.TempDir(), "contended.lock")
56 _, unlock, err := flock.TryLock(lockPath)
57 require.NoError(t, err)
58 t.Cleanup(unlock)
59 return lockPath
60 },
61 wantErr: flock.ErrLocked,
62 },
63 {
64 name: "lock succeeds after unlock",
65 setup: func(t *testing.T) string {
66 lockPath := filepath.Join(t.TempDir(), "reuse.lock")
67 _, unlock, err := flock.TryLock(lockPath)
68 require.NoError(t, err)
69 unlock()
70 return lockPath
71 },
72 },

Callers

nothing calls this directly

Calls 10

TryLockFunction · 0.92
JoinMethod · 0.80
EqualMethod · 0.80
MkdirAllMethod · 0.80
setupMethod · 0.80
HelperMethod · 0.65
NameMethod · 0.65
RunMethod · 0.65
verifyMethod · 0.65
ReadMethod · 0.45

Tested by

no test coverage detected