| 1 | package embedfs |
| 2 | |
| 3 | import ( |
| 4 | "embed" |
| 5 | "sync" |
| 6 | "testing" |
| 7 | |
| 8 | "github.com/stretchr/testify/require" |
| 9 | ) |
| 10 | |
| 11 | //go:embed testdata/concurrent.bin |
| 12 | var concurrentFS embed.FS |
| 13 | |
| 14 | // TestFileConcurrentReadAt asserts that concurrent ReadAt calls on a |
| 15 | // shared embedfs file handle are safe under -race and return correct |
| 16 | // per-byte results. embedfs wraps bytes.Reader, which is already |
| 17 | // concurrent-safe for ReadAt; this test pins the billy.File.ReadAt |
| 18 | // contract so future changes to the wrapper cannot regress it. |
| 19 | func TestFileConcurrentReadAt(t *testing.T) { |
| 20 | t.Parallel() |
| 21 | |
| 22 | want, err := concurrentFS.ReadFile("testdata/concurrent.bin") |
| 23 | require.NoError(t, err) |
| 24 | require.Equal(t, 4096, len(want)) |
| 25 | |
| 26 | fs := New(&concurrentFS) |
| 27 | f, err := fs.Open("testdata/concurrent.bin") |
| 28 | require.NoError(t, err) |
| 29 | t.Cleanup(func() { _ = f.Close() }) |
| 30 | |
| 31 | const workers = 8 |
| 32 | const iters = 200 |
| 33 | const bufLen = 64 |
| 34 | |
| 35 | var wg sync.WaitGroup |
| 36 | wg.Add(workers) |
| 37 | for w := range workers { |
| 38 | go func() { |
| 39 | defer wg.Done() |
| 40 | buf := make([]byte, bufLen) |
| 41 | for i := range iters { |
| 42 | off := int64((w*131 + i*257) % (len(want) - bufLen)) |
| 43 | n, err := f.ReadAt(buf, off) |
| 44 | require.NoError(t, err) |
| 45 | require.Equal(t, bufLen, n) |
| 46 | require.Equal(t, want[off:off+int64(n)], buf[:n]) |
| 47 | } |
| 48 | }() |
| 49 | } |
| 50 | wg.Wait() |
| 51 | } |