2
2
mirror of https://github.com/octoleo/restic.git synced 2024-11-27 15:26:37 +00:00
restic/internal/archiver/file_saver_test.go

103 lines
2.2 KiB
Go
Raw Normal View History

package archiver
import (
"context"
"fmt"
"os"
"path/filepath"
"runtime"
"testing"
"github.com/restic/chunker"
"github.com/restic/restic/internal/fs"
"github.com/restic/restic/internal/restic"
"github.com/restic/restic/internal/test"
2022-05-27 17:08:50 +00:00
"golang.org/x/sync/errgroup"
)
func createTestFiles(t testing.TB, num int) (files []string) {
tempdir := test.TempDir(t)
for i := 0; i < num; i++ {
filename := fmt.Sprintf("testfile-%d", i)
err := os.WriteFile(filepath.Join(tempdir, filename), []byte(filename), 0600)
if err != nil {
t.Fatal(err)
}
files = append(files, filepath.Join(tempdir, filename))
}
return files
}
2024-08-27 09:26:52 +00:00
func startFileSaver(ctx context.Context, t testing.TB) (*fileSaver, context.Context, *errgroup.Group) {
2022-05-27 17:08:50 +00:00
wg, ctx := errgroup.WithContext(ctx)
2024-08-27 09:26:52 +00:00
saveBlob := func(ctx context.Context, tpe restic.BlobType, buf *buffer, _ string, cb func(saveBlobResponse)) {
cb(saveBlobResponse{
id: restic.Hash(buf.Data),
length: len(buf.Data),
sizeInRepo: len(buf.Data),
known: false,
})
}
workers := uint(runtime.NumCPU())
pol, err := chunker.RandomPolynomial()
if err != nil {
t.Fatal(err)
}
2024-08-27 09:26:52 +00:00
s := newFileSaver(ctx, wg, saveBlob, pol, workers, workers)
s.NodeFromFileInfo = func(snPath, filename string, fi os.FileInfo, ignoreXattrListError bool) (*restic.Node, error) {
return fs.NodeFromFileInfo(filename, fi, ignoreXattrListError)
}
2022-05-27 17:08:50 +00:00
return s, ctx, wg
}
func TestFileSaver(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
files := createTestFiles(t, 15)
startFn := func() {}
completeReadingFn := func() {}
completeFn := func(*restic.Node, ItemStats) {}
testFs := fs.Local{}
2022-05-27 17:08:50 +00:00
s, ctx, wg := startFileSaver(ctx, t)
2024-08-27 09:26:52 +00:00
var results []futureNode
for _, filename := range files {
f, err := testFs.OpenFile(filename, os.O_RDONLY, 0)
if err != nil {
t.Fatal(err)
}
fi, err := f.Stat()
if err != nil {
t.Fatal(err)
}
ff := s.Save(ctx, filename, filename, f, fi, startFn, completeReadingFn, completeFn)
results = append(results, ff)
}
for _, file := range results {
fnr := file.take(ctx)
if fnr.err != nil {
t.Errorf("unable to save file: %v", fnr.err)
}
}
2022-05-27 17:08:50 +00:00
s.TriggerShutdown()
2022-05-27 17:08:50 +00:00
err := wg.Wait()
if err != nil {
t.Fatal(err)
}
}