tstor/src/host/vfs/archive_test.go
2024-03-28 16:09:42 +03:00

101 lines
2.2 KiB
Go

package vfs_test
import (
"archive/zip"
"bytes"
"context"
"io"
"testing"
"git.kmsign.ru/royalcat/tstor/pkg/ctxio"
"git.kmsign.ru/royalcat/tstor/src/host/vfs"
"github.com/stretchr/testify/require"
)
// TODO
// func TestArchiveFactories(t *testing.T) {
// t.Parallel()
// ctx := context.Background()
// require := require.New(t)
// require.Contains(vfs.ArchiveFactories, ".zip")
// require.Contains(vfs.ArchiveFactories, ".rar")
// require.Contains(vfs.ArchiveFactories, ".7z")
// fs, err := vfs.ArchiveFactories[".zip"](ctx, &vfs.DummyFile{})
// require.NoError(err)
// require.NotNil(fs)
// fs, err = vfs.ArchiveFactories[".rar"](ctx, &vfs.DummyFile{})
// require.NoError(err)
// require.NotNil(fs)
// fs, err = vfs.ArchiveFactories[".7z"](ctx, &vfs.DummyFile{})
// require.NoError(err)
// require.NotNil(fs)
// }
var fileContent []byte = []byte("Hello World")
func TestZipFilesystem(t *testing.T) {
t.Parallel()
require := require.New(t)
zReader, size := createTestZip(require)
ctx := context.Background()
// TODO add single dir collapse test
zfs, err := vfs.NewArchive(ctx, "test", zReader, size, vfs.ZipLoader)
require.NoError(err)
files, err := zfs.ReadDir(ctx, "/path/to/test/file")
require.NoError(err)
require.Len(files, 1)
e := files[0]
require.Equal("1.txt", e.Name())
require.NotNil(e)
out := make([]byte, 11)
f, err := zfs.Open(ctx, "/path/to/test/file/1.txt")
require.NoError(err)
n, err := f.Read(ctx, out)
require.Equal(io.EOF, err)
require.Equal(11, n)
require.Equal(fileContent, out)
}
func createTestZip(require *require.Assertions) (ctxio.ReaderAt, int64) {
buf := bytes.NewBuffer([]byte{})
zWriter := zip.NewWriter(buf)
f1, err := zWriter.Create("path/to/test/file/1.txt")
require.NoError(err)
_, err = f1.Write(fileContent)
require.NoError(err)
err = zWriter.Close()
require.NoError(err)
return newCBR(buf.Bytes()), int64(buf.Len())
}
type closeableByteReader struct {
data *bytes.Reader
}
func newCBR(b []byte) *closeableByteReader {
return &closeableByteReader{
data: bytes.NewReader(b),
}
}
// ReadAt implements ctxio.ReaderAt.
func (c *closeableByteReader) ReadAt(ctx context.Context, p []byte, off int64) (n int, err error) {
return c.data.ReadAt(p, off)
}