debian-mirror-gitlab/workhorse/internal/zipartifacts/metadata_test.go

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

100 lines
2.2 KiB
Go
Raw Normal View History

2023-03-17 16:20:25 +05:30
package zipartifacts
2021-02-22 17:27:13 +05:30
import (
"bytes"
"compress/gzip"
"context"
"fmt"
"io"
"os"
"testing"
"github.com/stretchr/testify/require"
2022-01-26 12:08:38 +05:30
zip "gitlab.com/gitlab-org/golang-archive-zip"
2021-02-22 17:27:13 +05:30
)
func generateTestArchive(w io.Writer) error {
archive := zip.NewWriter(w)
// non-POSIX paths are here just to test if we never enter infinite loop
files := []string{"file1", "some/file/dir/", "some/file/dir/file2", "../../test12/test",
"/usr/bin/test", `c:\windows\win32.exe`, `c:/windows/win.dll`, "./f/asd", "/"}
for _, file := range files {
archiveFile, err := archive.Create(file)
if err != nil {
return err
}
fmt.Fprint(archiveFile, file)
}
return archive.Close()
}
func validateMetadata(r io.Reader) error {
gz, err := gzip.NewReader(r)
if err != nil {
return err
}
2022-07-23 23:45:48 +05:30
meta, err := io.ReadAll(gz)
2021-02-22 17:27:13 +05:30
if err != nil {
return err
}
paths := []string{"file1", "some/", "some/file/", "some/file/dir/", "some/file/dir/file2"}
for _, path := range paths {
if !bytes.Contains(meta, []byte(path+"\x00")) {
return fmt.Errorf(fmt.Sprintf("zipartifacts: metadata for path %q not found", path))
}
}
return nil
}
func TestGenerateZipMetadataFromFile(t *testing.T) {
var metaBuffer bytes.Buffer
2022-07-23 23:45:48 +05:30
f, err := os.CreateTemp("", "workhorse-metadata.zip-")
2021-02-22 17:27:13 +05:30
if f != nil {
defer os.Remove(f.Name())
}
require.NoError(t, err)
defer f.Close()
err = generateTestArchive(f)
require.NoError(t, err)
f.Close()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
2023-03-17 16:20:25 +05:30
archive, err := OpenArchive(ctx, f.Name())
2021-02-22 17:27:13 +05:30
require.NoError(t, err, "zipartifacts: OpenArchive failed")
2023-03-17 16:20:25 +05:30
err = GenerateZipMetadata(&metaBuffer, archive)
2021-02-22 17:27:13 +05:30
require.NoError(t, err, "zipartifacts: GenerateZipMetadata failed")
err = validateMetadata(&metaBuffer)
require.NoError(t, err)
}
func TestErrNotAZip(t *testing.T) {
2022-07-23 23:45:48 +05:30
f, err := os.CreateTemp("", "workhorse-metadata.zip-")
2021-02-22 17:27:13 +05:30
if f != nil {
defer os.Remove(f.Name())
}
require.NoError(t, err)
defer f.Close()
_, err = fmt.Fprint(f, "Not a zip file")
require.NoError(t, err)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
2023-03-17 16:20:25 +05:30
_, err = OpenArchive(ctx, f.Name())
require.Equal(t, ErrorCode[CodeNotZip], err, "OpenArchive requires a zip file")
2021-02-22 17:27:13 +05:30
}