Skip to content

Commit

Permalink
Add lockutil test
Browse files Browse the repository at this point in the history
Verify that the lock works for threads in the same process.

TODO:
- Test the lock also for multiple processes

Signed-off-by: Nir Soffer <[email protected]>
  • Loading branch information
nirs committed Oct 13, 2024
1 parent ed34302 commit 86a5f5f
Showing 1 changed file with 56 additions and 0 deletions.
56 changes: 56 additions & 0 deletions pkg/lockutil/lockutil_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package lockutil

import (
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
)

const parallel = 20

func TestWithDirLock(t *testing.T) {
dir := t.TempDir()
log := filepath.Join(dir, "log")

errc := make(chan error, 10)
for i := 0; i < parallel; i++ {
go func() {
err := WithDirLock(dir, func() error {
if _, err := os.Stat(log); err == nil {
return nil
} else if !errors.Is(err, os.ErrNotExist) {
return err
}
logFile, err := os.OpenFile(log, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o640)
if err != nil {
return err
}
defer logFile.Close()
if _, err := fmt.Fprintf(logFile, "writer %d\n", i); err != nil {
return err
}
return logFile.Close()
})
errc <- err
}()
}

for i := 0; i < parallel; i++ {
err := <-errc
if err != nil {
t.Error(err)
}
}

data, err := os.ReadFile(log)
if err != nil {
t.Fatal(err)
}
lines := strings.Split(strings.Trim(string(data), "\n"), "\n")
if len(lines) != 1 {
t.Errorf("Expected one writer, got %v", lines)
}
}

0 comments on commit 86a5f5f

Please sign in to comment.