-
Notifications
You must be signed in to change notification settings - Fork 0
/
test.go
111 lines (87 loc) · 2.24 KB
/
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 test provides tools for testing the library
package test
import (
"bytes"
"encoding/json"
"os"
"path/filepath"
"strings"
"github.com/invopop/gobl"
cfdi "github.com/invopop/gobl.cfdi"
"github.com/invopop/gobl/bill"
)
// NewDocumentFrom creates a CFDI Document from a GOBL file in the `test/data` folder
func NewDocumentFrom(name string) (*cfdi.Document, error) {
env, err := LoadTestEnvelope(name)
if err != nil {
return nil, err
}
return cfdi.NewDocument(env)
}
// LoadTestInvoice returns a GOBL Invoice from a file in the `test/data` folder
func LoadTestInvoice(name string) (*bill.Invoice, error) {
env, err := LoadTestEnvelope(name)
if err != nil {
return nil, err
}
return env.Extract().(*bill.Invoice), nil
}
// LoadTestEnvelope returns a GOBL Envelope from a file in the `test/data` folder
func LoadTestEnvelope(name string) (*gobl.Envelope, error) {
src, _ := os.Open(filepath.Join(GetDataPath(), name))
buf := new(bytes.Buffer)
if _, err := buf.ReadFrom(src); err != nil {
return nil, err
}
env := new(gobl.Envelope)
if err := json.Unmarshal(buf.Bytes(), env); err != nil {
return nil, err
}
if err := env.Calculate(); err != nil {
return nil, err
}
if err := env.Validate(); err != nil {
return nil, err
}
return env, nil
}
// GenerateCFDIFrom returns a CFDI Document from a GOBL Invoice
func GenerateCFDIFrom(inv *bill.Invoice) (*cfdi.Document, error) {
if err := inv.Calculate(); err != nil {
return nil, err
}
env, err := gobl.Envelop(inv)
if err != nil {
return nil, err
}
return cfdi.NewDocument(env)
}
// GetDataPath returns the path to the `test/data` folder
func GetDataPath() string {
return filepath.Join(GetTestPath(), "data")
}
// GetTestPath returns the path to the `test` folder
func GetTestPath() string {
return filepath.Join(getRootFolder(), "test")
}
func getRootFolder() string {
cwd, _ := os.Getwd()
for !isRootFolder(cwd) {
cwd = removeLastEntry(cwd)
}
return cwd
}
func isRootFolder(dir string) bool {
files, _ := os.ReadDir(dir)
for _, file := range files {
if file.Name() == "go.mod" {
return true
}
}
return false
}
func removeLastEntry(dir string) string {
lastEntry := "/" + filepath.Base(dir)
i := strings.LastIndex(dir, lastEntry)
return dir[:i]
}