package io import ( "io/fs" "log" "os" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) var ( testWriterPath = "testPath" testWriterPathError = "test Path, @:ººººº\\/.Ç*⁺´+" testFileContent = []byte("test data") testFileName = "test-file.txt" workingDir = "" ) func deleteAllDirs() error { return os.RemoveAll(testWriterPath) } func init() { err := deleteAllDirs() if err != nil { log.Fatalln("deleteAllDirs: ", err) } workingDir, err = os.Getwd() if err != nil { log.Fatalln("os.Getwd: ", err) } } func Test_newWriter(t *testing.T) { w := newWriter(testWriterPath) require.NotNil(t, w) } func TestNewWriter(t *testing.T) { w := NewWriter(testWriterPath) require.NotNil(t, w) } func Test_writer_WriteFile(t *testing.T) { err := deleteAllDirs() require.NoError(t, err) defer func(t *testing.T) { err := deleteAllDirs() require.NoError(t, err) }(t) w := newWriter(testWriterPath) wgot, err := w.WriteFile(testFileName, testFileContent) require.NoError(t, err) btsReaded, err := os.ReadFile(wgot) require.NoError(t, err) require.NotEmpty(t, btsReaded) require.Equal(t, string(btsReaded), string(testFileContent)) } func Test_writer_WriteFileError(t *testing.T) { err := deleteAllDirs() require.NoError(t, err) defer func(t *testing.T) { err := deleteAllDirs() require.NoError(t, err) }(t) w := newWriter("") _, err = w.WriteFile(testFileName, testFileContent) assert.Error(t, err) w = newWriter(testWriterPath) _, err = w.WriteFile("", testFileContent) require.Error(t, err) err = os.MkdirAll(testWriterPath, fs.ModeDir) require.NoError(t, err, "mkdir should not throw error") err = os.MkdirAll(testWriterPath+"/"+testFileName, fs.ModeDir) require.NoError(t, err) _, err = w.WriteFile(testFileName, nil) assert.Error(t, err) w = newWriter(testWriterPathError) _, err = w.WriteFile(testFileName, testFileContent) require.Error(t, err) }