-
Notifications
You must be signed in to change notification settings - Fork 4
/
file_utils_test.go
111 lines (87 loc) · 2.1 KB
/
file_utils_test.go
1
2
3
4
5
6
7
8
9
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package cryptoengine
import (
"bytes"
"fmt"
"os"
"testing"
)
func TestFileExists(t *testing.T) {
// create key base folder
if err := createBaseKeyFolder(testKeyPath); err != nil {
t.Error(err)
}
if !fileExists(testKeyPath) {
t.Fatalf("%s should have been created", testKeyPath)
}
}
func TestFileUtils(t *testing.T) {
// create key base folder
if err := createBaseKeyFolder(testKeyPath); err != nil {
t.Error(err)
}
filename := "temp.txt"
dataString := "TEST DATA"
data := []byte(dataString)
// write a simple file
err := writeFile(filename, data)
if err != nil {
t.Error(err)
}
// rewrite the same file, it should trigger an error
err = writeFile(filename, data)
if err != os.ErrExist {
t.Errorf("The expected error is: os.ErrExist, instead we've got: %s\n", err)
}
// check if the file exists, it should
if !fileExists(filename) {
t.Fatal("The file should exist!")
}
// read the file back
storedData, err := readFile(filename)
if err != nil {
t.Fatal(err)
}
// read the data back
storedString := string(storedData)
if storedString != dataString {
t.Error("The data in the file is corrupted")
}
// delete the file
if err := deleteFile(filename); err != nil {
t.Fatal(err)
}
// delete the keys folder
if err := removeFolder(testKeyPath); err != nil {
t.Fatal(err)
}
}
func TestKeyFileUtils(t *testing.T) {
// create key base folder
if err := createBaseKeyFolder(testKeyPath); err != nil {
t.Error(err)
}
var key [keySize]byte
var err error
filename := "test_secret.key"
key, err = generateSecretKey()
if err != nil {
t.Fatal(err)
}
if err := writeKey(filename, testKeysFolderPrefixFormat, key[:]); err != nil {
t.Fatal(err)
}
storedKey, err := readKey(filename, testKeysFolderPrefixFormat)
if err != nil {
t.Fatal(err)
}
if bytes.Compare(key[:], storedKey[:]) != 0 {
t.Fatal("The generated random key and the stored one, do not match")
}
if err := deleteFile(fmt.Sprintf(testKeysFolderPrefixFormat, filename)); err != nil {
t.Error(err)
}
// delete the keys folder
if err := removeFolder(testKeyPath); err != nil {
t.Fatal(err)
}
}