fork of https://github.com/sourcegraph/zoekt
1package main
2
3import (
4 "os"
5 "path/filepath"
6 "testing"
7)
8
9func TestOwner(t *testing.T) {
10 path := filepath.Join(t.TempDir(), "owner.txt")
11
12 alice := ownerChecker{
13 Path: path,
14 Hostname: "alice",
15 }
16 bob := ownerChecker{
17 Path: path,
18 Hostname: "bob",
19 }
20
21 assertSuccess := func(err error) {
22 t.Helper()
23 if err != nil {
24 t.Fatal(err)
25 }
26 }
27 assertFailed := func(err error) {
28 t.Helper()
29 if err == nil {
30 t.Fatal("expected failure")
31 }
32 }
33
34 assertSuccess(alice.Init()) // empty dir so success
35 assertSuccess(alice.Check()) // alice took ownership above
36 assertSuccess(bob.Init()) // bob is now the owner. Only debug logs about change of ownership.
37 assertFailed(alice.Check()) // alice is not the owner anymore
38 assertSuccess(bob.Check()) // bob is still the owner
39
40 // Test what happens if someone corrupts the file
41 if err := os.WriteFile(path, []byte("!corrupt"), 0o600); err != nil {
42 t.Fatal(err)
43 }
44 assertFailed(alice.Check()) // corrupt so fail
45 assertFailed(bob.Check()) // corrupt so fail
46 assertSuccess(bob.Init()) // bob ovewrites corruption
47 assertSuccess(bob.Check()) // bob is the owner
48 assertFailed(alice.Check()) // alice is not the owner
49}