Passed
Push — main ( 375dae...05b53a )
by Rafael
01:12
created

files.validateRecordFound   B

Complexity

Conditions 6

Size

Total Lines 21
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 15
dl 0
loc 21
rs 8.6666
c 0
b 0
f 0
nop 3
1
package files
2
3
import (
4
	"io/ioutil"
5
	"os"
6
	"testing"
7
)
8
9
func validateLength(t *testing.T, fsr FileSystemRepository, expectedLength uint8) {
10
	fsList, e := fsr.List()
11
	if e != nil {
12
		t.Errorf("Could not get listing: %v", e.Error())
13
	}
14
	if len(fsList) != int(expectedLength) {
15
		t.Errorf("Should have a length of %d but was %d", expectedLength, len(fsList))
16
	}
17
}
18
19
func validateRecordFound(t *testing.T, fsr FileSystemRepository, addresses []string) {
20
	fs, err := fsr.FindByName("My FS")
21
	if err != nil {
22
		t.Errorf("Unable to find record: %v", err.Error())
23
		t.Fail()
24
	}
25
26
	if fs.Description != "This is a description" {
27
		t.Errorf("Invalid description: %v", fs.Description)
28
		t.Fail()
29
	}
30
31
	if len(fs.Addresses) != len(addresses) {
32
		t.Errorf("Invalid addresses: %d", len(fs.Addresses))
33
		t.Fail()
34
	}
35
36
	for i, addr := range fs.Addresses {
37
		if addr != addresses[i] {
38
			t.Errorf("Invalid address: %v", addr)
39
			t.Fail()
40
		}
41
	}
42
}
43
44
func createTestFile(t *testing.T) string {
45
	file, err := ioutil.TempFile("", "file*.repo")
46
	var path string
47
	if err == nil {
48
		path = file.Name()
49
		file.Close()
50
		os.Remove(file.Name())
51
		return path
52
	}
53
	t.Error("Unable to create temp file")
54
	t.Fail()
55
	return path
56
}
57
58
func getRepository(t *testing.T, path string) FileSystemRepository {
59
	fsr, err := GetFileSystemRepositoryFromPath(path)
60
	if err != nil {
61
		t.Errorf("Unable to build file system repository: %v", err.Error())
62
		t.Fail()
63
	}
64
	return fsr
65
}
66
67
func TestFileSystemRepository(t *testing.T) {
68
	path := createTestFile(t)
69
	fsr := getRepository(t, path)
70
71
	validateLength(t, fsr, 0)
72
73
	if b := fsr.Store(FileSystem{
74
		Name:        "My FS",
75
		Description: "This is a description",
76
		Addresses:   []string{"localhost:9000"},
77
	}); b != nil {
78
		t.Errorf("Could not store record: %v", b.Error())
79
	}
80
81
	validateLength(t, fsr, 1)
82
	validateRecordFound(t, fsr, []string{"localhost:9000"})
83
84
	// re-initialize
85
	fsr = getRepository(t, path)
86
	validateLength(t, fsr, 1)
87
	validateRecordFound(t, fsr, []string{"localhost:9000"})
88
89
	fsr.Store(FileSystem{
90
		Name:        "My FS",
91
		Description: "This is a description",
92
		Addresses:   []string{"localhost:9000", "localhost:9001"},
93
	})
94
	validateRecordFound(t, fsr, []string{"localhost:9000", "localhost:9001"})
95
96
	if b := fsr.Remove("My FS"); b != nil {
97
		t.Errorf("Error removing record: %v", b.Error())
98
	}
99
100
	// re-initialize
101
	fsr = getRepository(t, path)
102
	validateLength(t, fsr, 0)
103
}
104