forked from invopop/gobl.cii
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcii_test.go
228 lines (181 loc) · 5.45 KB
/
cii_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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
package cii
import (
"bytes"
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
"github.com/invopop/gobl"
"github.com/invopop/gobl.cii/document"
"github.com/invopop/gobl.cii/internal/ctog"
"github.com/invopop/gobl.cii/internal/gtoc"
"github.com/invopop/gobl/bill"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/lestrrat-go/libxml2"
"github.com/lestrrat-go/libxml2/xsd"
)
const (
xmlPattern = "*.xml"
jsonPattern = "*.json"
)
func TestGtoC(t *testing.T) {
schema, err := loadSchema("schema.xsd")
require.NoError(t, err)
examples, err := getDataGlob(jsonPattern)
require.NoError(t, err)
for _, example := range examples {
inName := filepath.Base(example)
outName := strings.Replace(inName, ".json", ".xml", 1)
t.Run(inName, func(t *testing.T) {
doc, err := newDocumentFrom(inName)
require.NoError(t, err)
data, err := doc.Bytes()
require.NoError(t, err)
err = validateXML(schema, data)
require.NoError(t, err)
output, err := loadOutputFile(outName)
assert.NoError(t, err)
assert.Equal(t, output, data, "Output should match the expected XML. Update with --update flag.")
})
}
}
func TestCtoG(t *testing.T) {
examples, err := getDataGlob("*.xml")
require.NoError(t, err)
for _, example := range examples {
inName := filepath.Base(example)
outName := strings.Replace(inName, ".xml", ".json", 1)
t.Run(inName, func(t *testing.T) {
// Load XML data
xmlData, err := os.ReadFile(example)
require.NoError(t, err)
// Convert CII XML to GOBL
goblEnv, err := ctog.Convert(xmlData)
require.NoError(t, err)
// Extract the invoice from the envelope
invoice, ok := goblEnv.Extract().(*bill.Invoice)
require.True(t, ok, "Document should be an invoice")
// Remove UUID from the invoice
invoice.UUID = ""
// Marshal only the invoice
data, err := json.MarshalIndent(invoice, "", " ")
require.NoError(t, err)
// Load the expected output
output, err := loadOutputFile(outName)
assert.NoError(t, err)
// Parse the expected output to extract the invoice
var expectedEnv gobl.Envelope
err = json.Unmarshal(output, &expectedEnv)
require.NoError(t, err)
expectedInvoice, ok := expectedEnv.Extract().(*bill.Invoice)
require.True(t, ok, "Expected document should be an invoice")
// Remove UUID from the expected invoice
expectedInvoice.UUID = ""
// Marshal the expected invoice
expectedData, err := json.MarshalIndent(expectedInvoice, "", " ")
require.NoError(t, err)
assert.JSONEq(t, string(expectedData), string(data), "Invoice should match the expected JSON. Update with --update flag.")
})
}
}
// newDocumentFrom creates a cii Document from a GOBL file in the `test/data` folder
func newDocumentFrom(name string) (*document.Invoice, error) {
env, err := loadTestEnvelope(name)
if err != nil {
return nil, err
}
return gtoc.Convert(env)
}
// 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(getConversionTypePath(jsonPattern), 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
}
return env, nil
}
func loadSchema(name string) (*xsd.Schema, error) {
return xsd.ParseFromFile(filepath.Join(getSchemaPath(name), name))
}
// validateXML validates a XML document against a XSD Schema
func validateXML(schema *xsd.Schema, data []byte) error {
xmlDoc, err := libxml2.Parse(data)
if err != nil {
return err
}
err = schema.Validate(xmlDoc)
if err != nil {
// Collect all errors into a single error message
errors := err.(xsd.SchemaValidationError).Errors()
var errorMessages []string
for _, e := range errors {
errorMessages = append(errorMessages, e.Error())
}
return fmt.Errorf("validation errors: %s", strings.Join(errorMessages, ",\n ")) // Return all errors as a single error
}
return nil
}
func loadOutputFile(name string) ([]byte, error) {
var pattern string
if strings.HasSuffix(name, ".json") {
pattern = xmlPattern
} else {
pattern = jsonPattern
}
src, _ := os.Open(filepath.Join(getOutPath(pattern), name))
buf := new(bytes.Buffer)
if _, err := buf.ReadFrom(src); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
func getDataGlob(pattern string) ([]string, error) {
return filepath.Glob(filepath.Join(getConversionTypePath(pattern), pattern))
}
func getSchemaPath(pattern string) string {
return filepath.Join(getConversionTypePath(pattern), "schema")
}
func getOutPath(pattern string) string {
return filepath.Join(getConversionTypePath(pattern), "out")
}
func getDataPath() string {
return filepath.Join(getTestPath(), "data")
}
func getConversionTypePath(pattern string) string {
if pattern == xmlPattern {
return filepath.Join(getDataPath(), "ctog")
}
return filepath.Join(getDataPath(), "gtoc")
}
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]
}