shm_test.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
  2. package shm
  3. import (
  4. "crypto/rand"
  5. "errors"
  6. "fmt"
  7. "io/fs"
  8. "os"
  9. "reflect"
  10. "testing"
  11. )
  12. var _ = fmt.Print
  13. func TestSHM(t *testing.T) {
  14. data := make([]byte, 13347)
  15. _, _ = rand.Read(data)
  16. mm, err := CreateTemp("test-kitty-shm-", uint64(len(data)))
  17. if err != nil {
  18. t.Fatal(err)
  19. }
  20. copy(mm.Slice(), data)
  21. err = mm.Flush()
  22. if err != nil {
  23. t.Fatalf("Failed to msync() with error: %v", err)
  24. }
  25. err = mm.Close()
  26. if err != nil {
  27. t.Fatalf("Failed to close with error: %v", err)
  28. }
  29. g, err := Open(mm.Name(), uint64(len(data)))
  30. if err != nil {
  31. t.Fatal(err)
  32. }
  33. data2 := g.Slice()
  34. if !reflect.DeepEqual(data, data2) {
  35. t.Fatalf("Could not read back written data: Written data length: %d Read data length: %d", len(data), len(data2))
  36. }
  37. err = g.Close()
  38. if err != nil {
  39. t.Fatalf("Failed to close with error: %v", err)
  40. }
  41. err = g.Unlink()
  42. if err != nil {
  43. t.Fatalf("Failed to unlink with error: %v", err)
  44. }
  45. g, err = Open(mm.Name(), uint64(len(data)))
  46. if err == nil {
  47. t.Fatalf("Unlinking failed could re-open the SHM data. Data equal: %v Data length: %d", reflect.DeepEqual(g.Slice(), data), len(g.Slice()))
  48. }
  49. if mm.IsFileSystemBacked() {
  50. _, err = os.Stat(mm.FileSystemName())
  51. if !errors.Is(err, fs.ErrNotExist) {
  52. t.Fatalf("Unlinking %s did not work", mm.Name())
  53. }
  54. }
  55. }