aboutsummaryrefslogtreecommitdiff
path: root/fileop/fileop_test.go
blob: f2ab864a88d88f3f1461a8efff2dbaec09962ea2 (plain)
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
package fileop

import (
	"fmt"
	"math/rand"
	"os"
	"testing"
	"time"
)

func init() {
	rand.Seed(time.Now().UnixNano())
}

func RandomString(n int) string {
	var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
	s := make([]rune, n)
	for i := range s {
		s[i] = letters[rand.Intn(len(letters))]
	}
	return string(s)
}

func createFolder() (tmp string) {
	tmp = fmt.Sprintf("/tmp/%s", RandomString(10))

	err := os.Mkdir(tmp, 0755)

	if err != nil {
		fmt.Println(err.Error())
	}

	return
}

func appendEmptyFile(path string) (fullPath string) {
	fullPath = fmt.Sprintf("%s/%s", path, RandomString(10))
	os.OpenFile(fullPath, os.O_RDONLY|os.O_CREATE, 0666)

	return
}

func createEmptyFile(path string) {
	os.OpenFile(path, os.O_RDONLY|os.O_CREATE, 0666)
}

func createTmpFile() (fullPath string) {
	path := createFolder()
	fullPath = appendEmptyFile(path)
	return
}

func TestMove(t *testing.T) {
	src := createTmpFile()
	dest := fmt.Sprintf("/tmp/%s", RandomString(10))

	c := Move()

	c <- &MoveCommand{Source: src, Destination: dest}
	close(c)

	if _, err := os.Stat(dest); err != nil {
		t.Errorf("File %s not moved to %s", src, dest)
	}

}

func TestWalk(t *testing.T) {
	fileCount := 1000
	folder := createFolder()
	files := map[string]struct{}{}
	walkedFiles := map[string]struct{}{}

	for i := 0; i < fileCount; i++ {
		files[appendEmptyFile(folder)] = struct{}{}
	}

	c := WalkFolder(folder)
	for file := range c {
		walkedFiles[file] = struct{}{}
	}

	for k := range files {
		_, ok := walkedFiles[k]
		if !ok {
			t.Errorf("File %s was not walked", k)
		}
	}
}

func TestCalculateSHA256(t *testing.T) {
	sh256, _ := CalculateSHA256("test_file.txt")

	if sh256 != "027cc886f9b8c866f932ef8b8da9a32f0857ef8e16ec98dd2797021b34623b88" {
		t.Errorf("Wrong sh256 hash, given %s", sh256)
	}
}