From f7d0490bb4f111c3b8806823fbad706053e582b5 Mon Sep 17 00:00:00 2001 From: Yusuf Birader Date: Thu, 10 Aug 2023 22:57:08 +0100 Subject: [PATCH] add archive of single non-empty file --- main.go | 7 +++++-- main_test.go | 22 +++++++++++++++++++++- 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/main.go b/main.go index c19ffee..fab8818 100644 --- a/main.go +++ b/main.go @@ -2,6 +2,8 @@ package main import ( "archive/zip" + "fmt" + "io" "os" ) @@ -14,8 +16,9 @@ func NewArchiver(archive *os.File) *Archiver { return &Archiver{Dest: archive, w: zip.NewWriter(archive)} } -func (a *Archiver) Archive() { - a.w.Create("hello.txt") +func (a *Archiver) Archive(r io.Reader) { + writer, _ := a.w.Create("hello.txt") + fmt.Fprint(writer, r) a.w.Close() } diff --git a/main_test.go b/main_test.go index a91f977..4685536 100644 --- a/main_test.go +++ b/main_test.go @@ -2,6 +2,7 @@ package main import ( "archive/zip" + "bytes" "fmt" "os" "testing" @@ -11,11 +12,12 @@ import ( func TestArchive(t *testing.T) { t.Run("archives a single empty file called hello.txt", func(t *testing.T) { + file := bytes.NewBufferString("") archive, cleanup := createTempArchive(t, "testdata/archive.zip") defer cleanup() archiver := NewArchiver(archive) - archiver.Archive() + archiver.Archive(file) archiveReader, err := zip.OpenReader(archive.Name()) assert.NoError(t, err) @@ -24,6 +26,24 @@ func TestArchive(t *testing.T) { assert.Equal(t, 1, len(archiveReader.File)) assert.Equal(t, "hello.txt", archiveReader.File[0].Name) }) + + t.Run("archives a single non-empty file called hello.txt", func(t *testing.T) { + file := bytes.NewBufferString("hello, world!") + archive, cleanup := createTempArchive(t, "testdata/archive.zip") + defer cleanup() + + archiver := NewArchiver(archive) + archiver.Archive(file) + + archiveReader, err := zip.OpenReader(archive.Name()) + assert.NoError(t, err) + defer archiveReader.Close() + + got := archiveReader.File[0].UncompressedSize64 + want := uint64(file.Len()) + + assert.Equal(t, want, got, "expected %s to have size %d but got %d", "hello.txt", want, got) + }) } func createTempArchive(t testing.TB, name string) (*os.File, func()) {