Skip to content

Commit 85c9d33

Browse files
authored
Merge pull request #34 from devops-kung-fu/unit_tests
refactor: Additional unit tests and refactoring
2 parents 163a8db + 07af5d5 commit 85c9d33

10 files changed

+193
-79
lines changed

.hookz.yaml

+1-1
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@
2525
args: ["-ignoretests", "./..."]
2626
- name: "gocyclo: Check cyclomatic complexities"
2727
exec: gocyclo
28-
args: ["-over", "13", "."]
28+
args: ["-over", "9", "."]
2929
- name: "go: Build (Ensure pulled modules do not break the build)"
3030
exec: go
3131
args: ["build", "-v"]

cmd/update.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ var (
2020
if lib.IsErrorBool(err, "[ERROR]") {
2121
return
2222
}
23-
if lib.IsErrorBool(lib.UpdateExecutables(config), "[ERROR]") {
23+
if lib.IsErrorBool(lib.NewDeps().UpdateExecutables(config), "[ERROR]") {
2424
return
2525
}
2626
color.Style{color.FgLightGreen}.Println("\nDone!")

lib/configreader.go

+25-11
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77
"log"
88
"os"
99
"path/filepath"
10+
"reflect"
1011
"strings"
1112

1213
"github.com/manifoldco/promptui"
@@ -16,7 +17,6 @@ import (
1617
func (f FileSystem) ReadConfig(version string) (config Configuration, err error) {
1718

1819
filename, _ := filepath.Abs(".hookz.yaml")
19-
//yamlFile, readErr := ioutil.ReadFile(filename)
2020
yamlFile, readErr := f.Afero().ReadFile(filename)
2121
if readErr != nil {
2222
config, err = f.promptCreateConfig(version)
@@ -40,6 +40,10 @@ func checkVersion(config Configuration, version string) (err error) {
4040
err = errors.New("no configuration version value found in .hookz.yaml")
4141
return
4242
}
43+
if version == "" {
44+
err = errors.New("a version should not be empty")
45+
return
46+
}
4347
ver := strings.Split(config.Version, ".")
4448
verMatch := strings.Split(version, ".")
4549
if fmt.Sprintf("%v.%v", ver[0], ver[1]) != fmt.Sprintf("%v.%v", verMatch[0], verMatch[1]) {
@@ -49,27 +53,37 @@ func checkVersion(config Configuration, version string) (err error) {
4953
}
5054

5155
func (f FileSystem) promptCreateConfig(version string) (config Configuration, err error) {
52-
fmt.Println("\nHookz was unable to find a .hookz.yaml file. Would you like")
53-
fmt.Println("to create a starter configuration?")
56+
var result string
57+
fsType := reflect.TypeOf(f.fs)
5458

55-
prompt := promptui.Prompt{
56-
Label: "Create starter .hookz.yaml?",
57-
IsConfirm: true,
58-
}
59+
if fsType.String() == "*afero.OsFs" {
60+
var promptErr error
61+
62+
fmt.Println("\nHookz was unable to find a .hookz.yaml file. Would you like")
63+
fmt.Println("to create a starter configuration?")
64+
65+
prompt := promptui.Prompt{
66+
Label: "Create starter .hookz.yaml?",
67+
IsConfirm: true,
68+
}
5969

60-
result, promptErr := prompt.Run()
70+
result, promptErr = prompt.Run()
6171

62-
if promptErr != nil {
63-
goto CONFIG_ERR
72+
if promptErr != nil {
73+
goto CONFIG_ERR
74+
}
75+
} else {
76+
result = "y"
6477
}
6578

6679
if result == "y" {
6780
config, err = f.createConfig(version)
6881
}
6982

83+
return
84+
7085
CONFIG_ERR:
7186
log.Println("[ERROR]: Hookz cannot run without a .hookz.yaml file. Create one and try again")
7287
os.Exit(1)
73-
7488
return
7589
}

lib/configreader_test.go

+17
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,9 @@ func TestDeps_ReadConfig(t *testing.T) {
2323

2424
assert.NoError(t, err, "ReadConfig should not have generated an error")
2525
assert.Equal(t, version, readConfig.Version, "Versions should match")
26+
27+
_, err = f.ReadConfig("")
28+
assert.Error(t, err, "Passing an empty string should cause an error")
2629
}
2730

2831
func TestDeps_checkVersion(t *testing.T) {
@@ -31,4 +34,18 @@ func TestDeps_checkVersion(t *testing.T) {
3134

3235
err = checkVersion(readConfig, version)
3336
assert.NoError(t, err, "Check version should not have generated an error")
37+
38+
err = checkVersion(readConfig, "2.0")
39+
assert.Error(t, err, "Version mismatch not caught")
40+
41+
readConfig.Version = ""
42+
err = checkVersion(readConfig, version)
43+
assert.Error(t, err, "An empty config version should throw an error")
44+
}
45+
46+
func Test_promptCreateConfig(t *testing.T) {
47+
48+
config, err := f.promptCreateConfig(version)
49+
assert.Equal(t, version, config.Version, "Version mismatch")
50+
assert.NoError(t, err, "Expected no error to be thrown")
3451
}

lib/hookdeleter.go

+12-10
Original file line numberDiff line numberDiff line change
@@ -3,38 +3,40 @@ package lib
33

44
import (
55
"fmt"
6-
"regexp"
6+
"os"
77
"strings"
88
)
99

1010
func (f FileSystem) RemoveHooks() (err error) {
11+
12+
path, _ := os.Getwd()
13+
1114
ext := ".hookz"
12-
p := ".git/hooks/"
15+
p := fmt.Sprintf("%s/%s", path, ".git/hooks")
1316

14-
dirFiles, err := f.Afero().ReadDir(p)
15-
if err != nil {
16-
return err
17-
}
17+
dirFiles, _ := f.Afero().ReadDir(p)
1818

1919
for index := range dirFiles {
2020
file := dirFiles[index]
2121

2222
name := file.Name()
23-
fullPath := fmt.Sprintf("%s%s", p, name)
24-
r, err := regexp.MatchString(ext, fullPath)
25-
if err == nil && r {
23+
fullPath := fmt.Sprintf("%s/%s", p, name)
24+
info, _ := f.Afero().Stat(fullPath)
25+
isHookzFile := strings.Contains(info.Name(), ext)
26+
if isHookzFile {
27+
var hookName = fullPath[0 : len(fullPath)-len(ext)]
2628
removeErr := f.fs.Remove(fullPath)
2729
if removeErr != nil {
2830
return removeErr
2931
}
30-
var hookName = fullPath[0 : len(fullPath)-len(ext)]
3132
removeErr = f.fs.Remove(hookName)
3233
if removeErr != nil {
3334
return removeErr
3435
}
3536
parts := strings.Split(hookName, "/")
3637
fmt.Printf(" Deleted %s\n", parts[len(parts)-1])
3738
}
39+
3840
}
3941
fmt.Println("[*] Successfully removed existing hooks!")
4042

lib/hookdeleter_test.go

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
//Package lib Functionality for the Hookz CLI
2+
package lib
3+
4+
import (
5+
"fmt"
6+
"os"
7+
"testing"
8+
9+
"github.com/stretchr/testify/assert"
10+
)
11+
12+
func TestFileSystem_RemoveHooks(t *testing.T) {
13+
path, _ := os.Getwd()
14+
15+
content := "Test Script"
16+
f.CreateScriptFile(content)
17+
18+
p := fmt.Sprintf("%s/%s", path, ".git/hooks")
19+
dirFiles, _ := f.Afero().ReadDir(p)
20+
assert.Equal(t, 2, len(dirFiles), "Incorrect number of created script files")
21+
22+
err := f.RemoveHooks()
23+
assert.NoError(t, err, "RemoveHooks should not have generated an error")
24+
25+
dirFiles, _ = f.Afero().ReadDir(p)
26+
assert.Equal(t, 0, len(dirFiles), "Incorrect number of created script files")
27+
28+
}

lib/hookwriter.go

+44-49
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ package lib
44
import (
55
"fmt"
66
"os"
7-
"path/filepath"
87
"text/template"
98

109
"github.com/segmentio/ksuid"
@@ -34,35 +33,28 @@ func (f FileSystem) CreateFile(name string) (err error) {
3433
func (f FileSystem) CreateScriptFile(content string) (name string, err error) {
3534

3635
k, idErr := ksuid.NewRandom()
37-
name, _ = filepath.Abs(fmt.Sprintf(".git/hooks/%s", k.String()))
36+
name = k.String()
3837
if IsErrorBool(idErr, "ERROR") {
3938
err = idErr
4039
return
4140
}
42-
hookzFile, hookzFileErr := filepath.Abs(fmt.Sprintf(".git/hooks/%s.hookz", k.String()))
43-
if hookzFileErr != nil {
44-
err = hookzFileErr
45-
return
46-
}
41+
path, _ := os.Getwd()
42+
p := fmt.Sprintf("%s/%s", path, ".git/hooks")
43+
44+
hookzFile := fmt.Sprintf("%s/%s.hookz", p, name)
45+
scriptName := fmt.Sprintf("%s/%s", p, name)
46+
4747
err = f.CreateFile(hookzFile)
4848
if err != nil {
4949
return
5050
}
5151

52-
file, err := f.fs.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
52+
err = f.Afero().WriteFile(scriptName, []byte(content), 0644)
5353
if err != nil {
5454
return
5555
}
56-
_, err = file.WriteString(content)
57-
if err != nil {
58-
return
59-
}
60-
61-
defer func() {
62-
err = file.Close()
63-
}()
6456

65-
err = f.fs.Chmod(name, 0777)
57+
err = f.fs.Chmod(scriptName, 0777)
6658
if err != nil {
6759
return
6860
}
@@ -90,38 +82,19 @@ func (f FileSystem) WriteHooks(config Configuration, verbose bool) (err error) {
9082
for _, hook := range config.Hooks {
9183
var commands []command
9284

93-
filename, _ := filepath.Abs(fmt.Sprintf(".git/hooks/%s", hook.Type))
94-
hookzFile, _ := filepath.Abs(fmt.Sprintf(".git/hooks/%s.hookz", hook.Type))
95-
96-
err = f.CreateFile(hookzFile)
97-
if err != nil {
98-
return err
99-
}
100-
101-
var file, err = f.fs.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
102-
if err != nil {
103-
return err
104-
}
105-
106-
defer func() {
107-
err = file.Close()
108-
}()
109-
110-
fmt.Printf("\n[*] Writing %s \n", hook.Type)
111-
11285
for _, action := range hook.Actions {
113-
11486
if action.Exec == nil && action.URL != nil {
115-
filename, _ := DownloadURL(*action.URL)
87+
filename, _ := f.DownloadURL(*action.URL)
11688
action.Exec = &filename
11789
}
118-
11990
if action.Exec == nil && action.Script != nil {
12091
scriptFileName, err := f.CreateScriptFile(*action.Script)
12192
if err != nil {
12293
return err
12394
}
124-
action.Exec = &scriptFileName
95+
path, _ := os.Getwd()
96+
fullScriptFileName := fmt.Sprintf("%s/%s/%s", path, ".git/hooks", scriptFileName)
97+
action.Exec = &fullScriptFileName
12598
}
12699

127100
fmt.Printf(" Adding %s action: %s\n", hook.Type, action.Name)
@@ -135,21 +108,43 @@ func (f FileSystem) WriteHooks(config Configuration, verbose bool) (err error) {
135108
FullCommand: fullCommand,
136109
})
137110
}
138-
139-
t := genTemplate(hook.Type)
140-
err = t.ExecuteTemplate(file, hook.Type, commands)
141-
if err != nil {
142-
return err
143-
}
144-
err = f.fs.Chmod(filename, 0777)
111+
err = f.writeTemplate(commands, hook.Type)
145112
if err != nil {
146-
return err
113+
return
147114
}
148-
fmt.Println("[*] Successfully wrote " + hook.Type)
149115
}
150116
return nil
151117
}
152118

119+
func (f FileSystem) writeTemplate(commands []command, hookType string) (err error) {
120+
path, _ := os.Getwd()
121+
p := fmt.Sprintf("%s/%s", path, ".git/hooks")
122+
123+
hookzFile := fmt.Sprintf("%s/%s.hookz", p, hookType)
124+
err = f.CreateFile(hookzFile)
125+
if err != nil {
126+
return
127+
}
128+
129+
fmt.Printf("\n[*] Writing %s \n", hookType)
130+
filename := fmt.Sprintf("%s/%s", p, hookType)
131+
file, err := f.Afero().Create(filename)
132+
if err != nil {
133+
return err
134+
}
135+
t := genTemplate(hookType)
136+
err = t.ExecuteTemplate(file, hookType, commands)
137+
if err != nil {
138+
return err
139+
}
140+
err = f.fs.Chmod(filename, 0777)
141+
if err != nil {
142+
return err
143+
}
144+
fmt.Println("[*] Successfully wrote " + hookType)
145+
return
146+
}
147+
153148
func genTemplate(hookType string) (t *template.Template) {
154149

155150
content := `#!/bin/bash

lib/hookwriter_test.go

+22
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
package lib
33

44
import (
5+
"fmt"
6+
"os"
57
"path/filepath"
68
"testing"
79

@@ -13,6 +15,11 @@ func TestDeps_CreateScriptFile(t *testing.T) {
1315
filename, err := f.CreateScriptFile(content)
1416
assert.NoError(t, err, "CreateScriptFile should not have generated an error")
1517
assert.NotEmpty(t, filename, "A filename should have been returned")
18+
19+
path, _ := os.Getwd()
20+
fullFileName := fmt.Sprintf("%s/%s/%s", path, ".git/hooks", filename)
21+
contains, _ := f.Afero().FileContainsBytes(fullFileName, []byte(content))
22+
assert.True(t, contains, "Script file should have the phrase `Test Script` in it")
1623
}
1724

1825
func Test_genTemplate(t *testing.T) {
@@ -43,3 +50,18 @@ func Test_WriteHooks(t *testing.T) {
4350
contains, _ := f.Afero().FileContainsBytes(filename, []byte("Hookz"))
4451
assert.True(t, contains, "Generated hook should have the word Hookz in it")
4552
}
53+
54+
func Test_createFile(t *testing.T) {
55+
err := f.CreateFile("test")
56+
assert.NoError(t, err, "Create file should not generate an error")
57+
// assert.FileExists(t, "./test", "A file should have been created")
58+
59+
// err = f.CreateFile("")
60+
// assert.Error(t, err, "A file should have not been created and an error thrown")
61+
62+
}
63+
64+
func Test_writeTemplate(t *testing.T) {
65+
err := f.writeTemplate(nil, "")
66+
assert.Error(t, err, "writeTemplate should throw an error if there is no file created")
67+
}

0 commit comments

Comments
 (0)