jx/internal/transport/file_test.go

77 lines
1.7 KiB
Go
Raw Normal View History

2024-07-01 07:16:55 +00:00
// Copyright 2024 Matthew Rich <matthewrich.conf@gmail.com>. All rights reserved.
package transport
import (
"github.com/stretchr/testify/assert"
"testing"
"fmt"
"os"
"io"
2024-07-01 07:16:55 +00:00
"net/url"
"path/filepath"
"compress/gzip"
"strings"
2024-07-01 07:16:55 +00:00
)
var TransportFileTestFile = fmt.Sprintf("%s/foo", TempDir)
func TestNewTransportFileReader(t *testing.T) {
path := fmt.Sprintf("%s/foo", TempDir)
u, e := url.Parse(fmt.Sprintf("file://%s", path))
assert.Nil(t, e)
writeErr := os.WriteFile(path, []byte("test"), 0644)
assert.Nil(t, writeErr)
file, err := NewFile(u)
assert.Nil(t, err)
assert.Equal(t, file.Path(), path)
}
func TestNewTransportFileReaderExtension(t *testing.T) {
u, e := url.Parse(fmt.Sprintf("file://%s.yaml", TransportFileTestFile))
assert.Nil(t, e)
f := &File{
uri: u,
path: filepath.Join(u.Hostname(), u.Path),
2024-07-01 07:16:55 +00:00
}
f.extension()
assert.Equal(t, f.exttype, "yaml")
}
// Use transport to write a compressed file then verify it.
func TestTransportFileGzipWriter(t *testing.T) {
var content strings.Builder
var testValue string = "write a compressed plaintext file"
path := TempDir.FilePath("foo.tgz")
u, e := url.Parse(fmt.Sprintf("file://%s", path))
assert.Nil(t, e)
fw, err := NewFileWriter(u)
assert.Nil(t, err)
assert.Equal(t, "tgz", fw.File.exttype)
assert.True(t, fw.Gzip())
writer := fw.Writer()
2024-10-04 00:11:58 +00:00
n, err := writer.Write([]byte(testValue))
assert.Equal(t, len(testValue), n)
assert.Nil(t, err)
assert.Nil(t, writer.Close())
assert.True(t, TempDir.FileExists("foo.tgz"))
r, openErr := TempDir.Open("foo.tgz")
assert.Nil(t, openErr)
gzipReader, gzipErr := gzip.NewReader(r)
assert.Nil(t, gzipErr)
_, readErr := io.Copy(&content, gzipReader)
assert.Nil(t, readErr)
assert.Equal(t, content.String(), testValue)
}