filelock_test.go 1000 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. // License: GPLv3 Copyright: 2024, Kovid Goyal, <kovid at kovidgoyal.net>
  2. package utils
  3. import (
  4. "fmt"
  5. "os"
  6. "os/exec"
  7. "testing"
  8. )
  9. var _ = fmt.Print
  10. func TestFileLock(t *testing.T) {
  11. tdir := t.TempDir()
  12. file_descriptor, err := os.Open(tdir)
  13. if err != nil {
  14. t.Fatalf("Initial open of %s failed with error: %s", tdir, err)
  15. }
  16. if err = LockFileExclusive(file_descriptor); err != nil {
  17. file_descriptor.Close()
  18. t.Fatalf("Initial lock of %s failed with error: %s", tdir, err)
  19. }
  20. defer func() {
  21. _ = UnlockFile(file_descriptor)
  22. file_descriptor.Close()
  23. }()
  24. cmd := exec.Command(KittyExe(), "+runpy", `
  25. import sys, os, fcntl
  26. fd = os.open(sys.argv[-1], os.O_RDONLY)
  27. try:
  28. fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
  29. except BlockingIOError:
  30. sys.exit(0)
  31. else:
  32. print("Lock unexpectedly succeeded", flush=True)
  33. sys.exit(1)
  34. `, tdir)
  35. if output, err := cmd.CombinedOutput(); err != nil {
  36. t.Fatalf("Lock test process failed with error: %s and output:\n%s", err, string(output))
  37. }
  38. }