common_test.go 1.81 KB
Newer Older
1 2 3 4 5 6 7 8
package common

import (
	"fmt"
	"os"
	"path/filepath"
	"testing"

9
	"github.com/stretchr/testify/assert"
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
)

var path = os.TempDir()
var ffoo = filepath.Join(path, "foo.txt")
var fbar = filepath.Join(path, "bar.txt")
var fbaz = filepath.Join(path, "baz.txt")
var fqux = filepath.Join(path, "qux.txt")

func TestMain(m *testing.M) {

	// Setup

	// Run tests
	code := m.Run()

	// Teardown
	DeleteQuietly(ffoo)
	DeleteQuietly(fbar)
	DeleteQuietly(fbaz)
	DeleteQuietly(fqux)

	os.Exit(code)
}

// Save an array of bytes on the disk
func TestSaveToDisk(t *testing.T) {
	data := make([]byte, 3)
	data[0] = 'f'
	data[1] = 'o'
	data[2] = 'o'
	err := SaveToDisk(data, ffoo)
41
	assert.True(t, err == nil, "An error has been raised")
42

43
	assert.True(t, FileExists(ffoo), "foo.txt should be present")
44 45 46 47 48 49
}

// Save a string on the disk
func TestSaveStringToDisk(t *testing.T) {
	s := "bar"
	err := SaveStringToDisk(s, fbar)
50
	assert.True(t, err == nil, "An error has been raised")
51

52
	assert.True(t, FileExists(fbar), "bar.txt should be present")
53 54 55 56 57 58
}

// DeleteQuietly should never raise an error, even with non-existant file
func TestDeleteQuietly(t *testing.T) {
	s := "baz"
	_ = SaveStringToDisk(s, fbaz)
59
	assert.True(t, FileExists(fbaz), "baz.txt should be present")
60
	DeleteQuietly(fbaz)
61
	assert.True(t, !FileExists(fbaz), "baz.txt should not be present")
62 63 64 65 66 67 68 69 70

	// Assert it does not panic when deleting an inexistant file
	DeleteQuietly("dummy")
}

// Test the reading of a file
func TestReadFile(t *testing.T) {
	s := "qux"
	_ = SaveStringToDisk(s, fqux)
71
	assert.True(t, FileExists(fqux), "qux.txt should be present")
72 73 74 75

	data, err := ReadFile(fqux)
	if err != nil {
		fmt.Println(err.Error())
76
		assert.True(t, err == nil, "An error has been raised while reading the file")
77 78 79 80
	}
	assert.Equal(t, s, fmt.Sprintf("%s", data), "Expected qux, received ", fmt.Sprintf("%s", data))

}