This repository has been archived by the owner on Jul 2, 2024. It is now read-only.
forked from datacontract/datacontract-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain_test.go
90 lines (73 loc) · 2.05 KB
/
main_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
package datacontract
import (
"bytes"
"fmt"
"log"
"math/rand"
"net/http"
"net/http/httptest"
"os"
"testing"
)
var TestResourcesServer = httptest.NewServer(http.FileServer(http.Dir("./test_resources")))
var TmpFolder = "tmp"
func TestMain(m *testing.M) {
// start static file server
defer TestResourcesServer.Close()
// create folder for temporary files
os.Mkdir(TmpFolder, os.ModePerm)
// run test
m.Run()
// delete temporary files
os.RemoveAll(TmpFolder)
}
func CreateTmpFileName() string {
return fmt.Sprintf("tmp/%v.yaml", rand.Int())
}
func RunLogOutputTest[T any](t *testing.T, test LogOutputTest[T], functionName string, function func(buffer *bytes.Buffer) error) {
var buf bytes.Buffer
log.SetFlags(0)
t.Run(test.name, func(t *testing.T) {
if err := function(&buf); (err != nil) != test.wantErr {
t.Errorf("%v() error = %v, wantErr %v", functionName, err, test.wantErr)
}
if buf.String() != test.wantOutput {
t.Errorf(`%v() gotOutput
---
%v
---
wantOutput
---
%v
---`, functionName, buf.String(), test.wantOutput)
}
})
}
type LogOutputTest[T any] struct {
name string
args T
wantErr bool
wantOutput string
}
func RunFileWriteTest[T any](t *testing.T, test FileWriteTest[T], functionName string, originalFileLocation string, function func(tempFileName string) error) {
tmpFile, _ := os.CreateTemp("", functionName)
input, _ := os.ReadFile(originalFileLocation)
os.WriteFile(tmpFile.Name(), input, os.ModePerm)
t.Run(test.name, func(t *testing.T) {
if err := function(tmpFile.Name()); (err != nil) != test.wantErr {
t.Errorf("%v() error = %v, wantErr %v", functionName, err, test.wantErr)
}
generated, _ := os.ReadFile(tmpFile.Name())
expected, _ := os.ReadFile(test.expectedFileLocation)
if string(generated) != string(expected) {
t.Errorf("%v() gotFile = %v, wantFile %v", functionName, string(generated), string(expected))
}
})
tmpFile.Close()
}
type FileWriteTest[T any] struct {
name string
args T
wantErr bool
expectedFileLocation string
}