// Copyright 2024 Matthew Rich . All rights reserved. package fan import ( "github.com/stretchr/testify/assert" "testing" "bytes" "archive/tar" "decl/internal/data" "decl/internal/folio" "decl/internal/resource" "path/filepath" "strings" "io" "fmt" "log/slog" ) var tarArchiveBuffer bytes.Buffer func TarArchive() (err error) { tw := tar.NewWriter(&tarArchiveBuffer) defer tw.Close() fileContent := "test file content" if err = tw.WriteHeader(&tar.Header{ Name: "testfile", Mode: 0600, Size: int64(len(fileContent)), }); err == nil { _, err = tw.Write([]byte(fileContent)) } return } func TestNewTar(t *testing.T) { a := NewTar() assert.NotNil(t, a) } func TestExtractFiles(t *testing.T) { a := NewTar() assert.NotNil(t, a) e := TarArchive() assert.Nil(t, e) assert.Greater(t, tarArchiveBuffer.Len(), 0) d := folio.NewDeclaration() d.ResourceTypes = folio.DocumentRegistry.ResourceTypes slog.Info("TestExtractFiles", "resourcetypes", folio.DocumentRegistry.ResourceTypes, "declarationtypes", d.ResourceTypes, "resource.ResourceTypes", resource.ResourceTypes) d.Type = "file" assert.Nil(t, d.NewResource(nil)) var sourceResource data.FileResource = d.Attributes.(data.FileResource) assert.Nil(t, sourceResource.SetContent(&tarArchiveBuffer)) exDoc, err := a.Extract(d.Attributes, nil) assert.Nil(t, err) assert.NotNil(t, exDoc) document := exDoc.(*folio.Document) assert.Greater(t, document.Len(), 0) assert.Equal(t, folio.TypeName("file"), document.ResourceDeclarations[0].Type) f := document.ResourceDeclarations[0].Resource().(data.FileResource) assert.Equal(t, "testfile", f.FilePath()) } func TestEmitFiles(t *testing.T) { expected := "some test data" a := NewTar() assert.NotNil(t, a) a.Uri = folio.URI(fmt.Sprintf("file://%s", filepath.Join(TempDir, "testemitfiles.tar"))) doc := folio.DocumentRegistry.NewDocument("") uri := fmt.Sprintf("file://%s", filepath.Join(TempDir, "foo.txt")) res, resErr := doc.NewResource(uri) assert.Nil(t, resErr) assert.NotNil(t, res) assert.Equal(t, res, doc.GetResource(uri).Resource()) f := doc.GetResource(uri).Attributes.(data.FileResource) assert.Nil(t, f.SetContent(strings.NewReader(expected))) target, emitErr := a.Emit(doc, nil) assert.Nil(t, emitErr) assert.Equal(t, folio.URI(fmt.Sprintf("file://%s", target.(data.FileResource).FilePath())), a.Uri) tarArchiveBuffer.Reset() _, contentErr := target.(data.FileResource).GetContent(&tarArchiveBuffer) assert.Nil(t, contentErr) tr := tar.NewReader(&tarArchiveBuffer) hdr, err := tr.Next() assert.NotEqual(t, io.EOF, err) assert.NotNil(t, hdr) assert.Equal(t, f.FilePath(), hdr.Name) data, err := io.ReadAll(tr) assert.Nil(t, err) assert.Equal(t, expected, string(data)) }