Repository navigation
Expand file tree
/
Copy pathvalidation_test.go
More file actions
641 lines (564 loc) · 15.7 KB
/
Copy pathvalidation_test.go
File metadata and controls
641 lines (564 loc) · 15.7 KB
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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
package einvoice
import (
"bytes"
"errors"
"os"
"testing"
"time"
"github.com/shopspring/decimal"
"github.com/speedata/einvoice/rules"
)
func TestValidationError_Error(t *testing.T) {
tests := []struct {
name string
violations []SemanticError
want string
}{
{
name: "no violations",
violations: []SemanticError{},
want: "validation failed with no violations",
},
{
name: "single violation",
violations: []SemanticError{
{Rule: rules.BR1, Text: "Invoice number is required"},
},
want: "validation failed: BR-01 - Invoice number is required",
},
{
name: "multiple violations",
violations: []SemanticError{
{Rule: rules.BR1, Text: "Invoice number is required"},
{Rule: rules.BR2, Text: "Invoice date is required"},
{Rule: rules.BR3, Text: "Currency is required"},
},
want: "validation failed with 3 violations (first: BR-01 - Invoice number is required)",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
e := &ValidationError{violations: tt.violations}
if got := e.Error(); got != tt.want {
t.Errorf("Error() = %v, want %v", got, tt.want)
}
})
}
}
func TestValidationError_Violations(t *testing.T) {
t.Run("returns copy of violations", func(t *testing.T) {
original := []SemanticError{
{Rule: rules.BR1, Text: "Test violation"},
}
e := &ValidationError{violations: original}
// Get violations
violations := e.Violations()
// Verify content
if len(violations) != 1 {
t.Errorf("Violations() returned %d violations, want 1", len(violations))
}
if violations[0].Rule.Code != "BR-01" {
t.Errorf("Violations()[0].Rule.Code = %v, want BR-1", violations[0].Rule.Code)
}
// Modify the returned slice - should not affect internal state
violations[0].Rule = rules.BR2
// Verify internal state unchanged
if e.violations[0].Rule.Code != "BR-01" {
t.Errorf("Internal violations were modified, want BR-1, got %v", e.violations[0].Rule.Code)
}
})
t.Run("returns nil for nil violations", func(t *testing.T) {
e := &ValidationError{violations: nil}
violations := e.Violations()
if violations != nil {
t.Errorf("Violations() = %v, want nil", violations)
}
})
t.Run("returns empty slice for empty violations", func(t *testing.T) {
e := &ValidationError{violations: []SemanticError{}}
violations := e.Violations()
if violations == nil {
t.Error("Violations() = nil, want empty slice")
}
if len(violations) != 0 {
t.Errorf("Violations() length = %d, want 0", len(violations))
}
})
}
func TestValidationError_Count(t *testing.T) {
tests := []struct {
name string
violations []SemanticError
want int
}{
{
name: "no violations",
violations: []SemanticError{},
want: 0,
},
{
name: "one violation",
violations: []SemanticError{
{Rule: rules.BR1, Text: "Test"},
},
want: 1,
},
{
name: "multiple violations",
violations: []SemanticError{
{Rule: rules.BR1, Text: "Test 1"},
{Rule: rules.BR2, Text: "Test 2"},
{Rule: rules.BR3, Text: "Test 3"},
},
want: 3,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
e := &ValidationError{violations: tt.violations}
if got := e.Count(); got != tt.want {
t.Errorf("Count() = %v, want %v", got, tt.want)
}
})
}
}
func TestValidationError_HasRule(t *testing.T) {
violations := []SemanticError{
{Rule: rules.BR1, Text: "Test 1"},
{Rule: rules.BRS8, Text: "Test 2"},
{Rule: rules.BRCO10, Text: "Test 3"},
}
e := &ValidationError{violations: violations}
t.Run("HasRule with Rule constants", func(t *testing.T) {
tests := []struct {
name string
rule rules.Rule
want bool
}{
{
name: "rule exists - rules.BR1",
rule: rules.BR1,
want: true,
},
{
name: "rule exists - rules.BRS8",
rule: rules.BRS8,
want: true,
},
{
name: "rule exists - rules.BRCO10",
rule: rules.BRCO10,
want: true,
},
{
name: "rule does not exist",
rule: rules.BR2,
want: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := e.HasRule(tt.rule); got != tt.want {
t.Errorf("HasRule(%v) = %v, want %v", tt.rule.Code, got, tt.want)
}
})
}
})
t.Run("HasRuleCode with string codes", func(t *testing.T) {
tests := []struct {
name string
code string
want bool
}{
{
name: "rule exists - BR-1",
code: "BR-01",
want: true,
},
{
name: "rule exists - BR-S-8",
code: "BR-S-08",
want: true,
},
{
name: "rule exists - BR-CO-10",
code: "BR-CO-10",
want: true,
},
{
name: "rule does not exist",
code: "BR-99",
want: false,
},
{
name: "empty rule",
code: "",
want: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := e.HasRuleCode(tt.code); got != tt.want {
t.Errorf("HasRuleCode(%v) = %v, want %v", tt.code, got, tt.want)
}
})
}
})
}
func TestValidationError_AsError(t *testing.T) {
t.Run("can be used with errors.As", func(t *testing.T) {
originalErr := &ValidationError{
violations: []SemanticError{
{Rule: rules.BR1, Text: "Test violation"},
},
}
var err error = originalErr
var valErr *ValidationError
if !errors.As(err, &valErr) {
t.Error("errors.As failed to extract ValidationError")
}
if valErr.Count() != 1 {
t.Errorf("Count() = %d, want 1", valErr.Count())
}
if !valErr.HasRule(rules.BR1) {
t.Error("HasRule(rules.BR1) = false, want true")
}
if !valErr.HasRuleCode("BR-01") {
t.Error("HasRuleCode(BR-1) = false, want true")
}
})
}
func TestValidationError_Warnings(t *testing.T) {
t.Run("returns copy of warnings", func(t *testing.T) {
original := []SemanticError{
{Rule: rules.BRDE21, Text: "Test warning"},
}
e := &ValidationError{warnings: original}
// Get warnings
warnings := e.Warnings()
// Verify content
if len(warnings) != 1 {
t.Errorf("Warnings() returned %d warnings, want 1", len(warnings))
}
if warnings[0].Rule.Code != "BR-DE-21" {
t.Errorf("Warnings()[0].Rule.Code = %v, want BR-DE-21", warnings[0].Rule.Code)
}
// Modify the returned slice - should not affect internal state
warnings[0].Rule = rules.BR2
// Verify internal state unchanged
if e.warnings[0].Rule.Code != "BR-DE-21" {
t.Errorf("Internal warnings were modified, want BR-DE-21, got %v", e.warnings[0].Rule.Code)
}
})
t.Run("returns nil for nil warnings", func(t *testing.T) {
e := &ValidationError{warnings: nil}
warnings := e.Warnings()
if warnings != nil {
t.Errorf("Warnings() = %v, want nil", warnings)
}
})
t.Run("returns empty slice for empty warnings", func(t *testing.T) {
e := &ValidationError{warnings: []SemanticError{}}
warnings := e.Warnings()
if warnings == nil {
t.Error("Warnings() = nil, want empty slice")
}
if len(warnings) != 0 {
t.Errorf("Warnings() length = %d, want 0", len(warnings))
}
})
}
func TestValidationError_WarningCount(t *testing.T) {
tests := []struct {
name string
warnings []SemanticError
want int
}{
{
name: "no warnings",
warnings: []SemanticError{},
want: 0,
},
{
name: "one warning",
warnings: []SemanticError{
{Rule: rules.BRDE21, Text: "Test"},
},
want: 1,
},
{
name: "multiple warnings",
warnings: []SemanticError{
{Rule: rules.BRDE21, Text: "Test 1"},
{Rule: rules.BRDE17, Text: "Test 2"},
},
want: 2,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
e := &ValidationError{warnings: tt.warnings}
if got := e.WarningCount(); got != tt.want {
t.Errorf("WarningCount() = %v, want %v", got, tt.want)
}
})
}
}
func TestValidationError_HasWarnings(t *testing.T) {
t.Run("returns true when warnings exist", func(t *testing.T) {
e := &ValidationError{warnings: []SemanticError{{Rule: rules.BRDE21, Text: "Test"}}}
if !e.HasWarnings() {
t.Error("HasWarnings() = false, want true")
}
})
t.Run("returns false when no warnings", func(t *testing.T) {
e := &ValidationError{warnings: []SemanticError{}}
if e.HasWarnings() {
t.Error("HasWarnings() = true, want false")
}
})
t.Run("returns false for nil warnings", func(t *testing.T) {
e := &ValidationError{warnings: nil}
if e.HasWarnings() {
t.Error("HasWarnings() = true, want false")
}
})
}
func TestValidationError_BothViolationsAndWarnings(t *testing.T) {
e := &ValidationError{
violations: []SemanticError{
{Rule: rules.BR1, Text: "Error 1"},
{Rule: rules.BR2, Text: "Error 2"},
},
warnings: []SemanticError{
{Rule: rules.BRDE21, Text: "Warning 1"},
},
}
if e.Count() != 2 {
t.Errorf("Count() = %d, want 2", e.Count())
}
if e.WarningCount() != 1 {
t.Errorf("WarningCount() = %d, want 1", e.WarningCount())
}
if !e.HasWarnings() {
t.Error("HasWarnings() = false, want true")
}
if !e.HasRule(rules.BR1) {
t.Error("HasRule(rules.BR1) = false, want true")
}
// Verify Error() message doesn't include warnings count
errMsg := e.Error()
if errMsg != "validation failed with 2 violations (first: BR-01 - Error 1)" {
t.Errorf("Error() = %q, want proper violation-only message", errMsg)
}
}
func TestInvoice_Warnings(t *testing.T) {
t.Run("returns copy of warnings", func(t *testing.T) {
inv := &Invoice{
warnings: []SemanticError{
{Rule: rules.BRDE21, Text: "Test warning"},
},
}
warnings := inv.Warnings()
if len(warnings) != 1 {
t.Errorf("Warnings() returned %d warnings, want 1", len(warnings))
}
// Modify the returned slice
warnings[0].Rule = rules.BR2
// Verify internal state unchanged
if inv.warnings[0].Rule.Code != "BR-DE-21" {
t.Errorf("Internal warnings were modified")
}
})
t.Run("returns nil for nil warnings", func(t *testing.T) {
inv := &Invoice{warnings: nil}
if inv.Warnings() != nil {
t.Error("Warnings() should return nil for nil warnings")
}
})
}
func TestInvoice_HasWarnings(t *testing.T) {
t.Run("returns true when warnings exist", func(t *testing.T) {
inv := &Invoice{warnings: []SemanticError{{Rule: rules.BRDE21, Text: "Test"}}}
if !inv.HasWarnings() {
t.Error("HasWarnings() = false, want true")
}
})
t.Run("returns false when no warnings", func(t *testing.T) {
inv := &Invoice{warnings: []SemanticError{}}
if inv.HasWarnings() {
t.Error("HasWarnings() = true, want false")
}
})
}
func TestValidate_WarningsDoNotFailValidation(t *testing.T) {
// Test that the warning infrastructure doesn't cause validation to fail
// when warnings exist but no violations
inv := createMinimalInvoice()
// Manually add a warning to verify infrastructure
inv.warnings = []SemanticError{
{Rule: rules.BRDE17, Text: "Test warning"},
}
// Run validation - this will clear and re-populate warnings
// Since there are no warning-generating rules currently active,
// we just verify the clearing mechanism works
err := inv.Validate()
// Validation should pass (no violations in minimal invoice)
if err != nil {
t.Errorf("Validate() returned error: %v, want nil", err)
}
// Warnings should be cleared by Validate() since no rules currently generate warnings
// This tests the clearing mechanism
}
func TestValidate_WarningsIncludedInValidationError(t *testing.T) {
// Test that warnings can be included in ValidationError when there are violations
inv := createMinimalInvoice()
// Remove required field to cause a violation
inv.InvoiceNumber = "" // This should trigger BR-02
err := inv.Validate()
// Should have validation error
if err == nil {
t.Fatal("Validate() returned nil, want error")
}
var valErr *ValidationError
if !errors.As(err, &valErr) {
t.Fatal("Error is not a ValidationError")
}
// Check violations exist
if valErr.Count() == 0 {
t.Error("Count() = 0, want at least 1 violation")
}
// WarningCount() should work (may be 0 since no warning rules are active)
_ = valErr.WarningCount()
}
func TestValidate_ClearsWarningsOnRevalidation(t *testing.T) {
// Test that warnings are cleared between validation calls
inv := createMinimalInvoice()
// Manually set warnings
inv.warnings = []SemanticError{
{Rule: rules.BRDE17, Text: "Old warning"},
}
// Validate should clear old warnings
_ = inv.Validate()
// Since no rules currently generate warnings, warnings should be empty
// This tests the clearing mechanism works properly
if len(inv.warnings) > 0 {
hasOldWarning := false
for _, w := range inv.warnings {
if w.Text == "Old warning" {
hasOldWarning = true
break
}
}
if hasOldWarning {
t.Error("Old warnings were not cleared on revalidation")
}
}
}
// createMinimalInvoice creates a minimal invoice for testing
func createMinimalInvoice() *Invoice {
return &Invoice{
GuidelineSpecifiedDocumentContextParameter: SpecEN16931,
InvoiceNumber: "INV-001",
InvoiceTypeCode: 380,
InvoiceCurrencyCode: "EUR",
InvoiceDate: time.Date(2024, 1, 15, 0, 0, 0, 0, time.UTC),
SpecifiedTradePaymentTerms: []SpecifiedTradePaymentTerms{
{DueDate: time.Date(2024, 2, 15, 0, 0, 0, 0, time.UTC)},
},
Seller: Party{
Name: "Seller Company",
PostalAddress: &PostalAddress{
CountryID: "FR",
},
VATaxRegistration: "FR12345678901",
},
Buyer: Party{
Name: "Buyer Company",
PostalAddress: &PostalAddress{
CountryID: "FR",
},
},
InvoiceLines: []InvoiceLine{
{
LineID: "1",
Total: decimal.NewFromInt(100),
BilledQuantity: decimal.NewFromInt(1),
BilledQuantityUnit: "C62",
ItemName: "Test Item",
NetPrice: decimal.NewFromInt(100),
TaxCategoryCode: "S",
TaxRateApplicablePercent: decimal.NewFromInt(19),
},
},
TradeTaxes: []TradeTax{
{
TypeCode: "VAT",
CategoryCode: "S",
BasisAmount: decimal.NewFromInt(100),
Percent: decimal.NewFromInt(19),
CalculatedAmount: decimal.NewFromFloat(19),
},
},
LineTotal: decimal.NewFromInt(100),
TaxBasisTotal: decimal.NewFromInt(100),
TaxTotal: decimal.NewFromFloat(19),
GrandTotal: decimal.NewFromFloat(119),
DuePayableAmount: decimal.NewFromFloat(119),
}
}
// Benchmark tests for validation performance
// BenchmarkValidate benchmarks validation performance across different profile types
func BenchmarkValidate(b *testing.B) {
benchmarks := []struct {
name string
file string
}{
{"EN16931_CII", "testdata/cii/en16931/zugferd_2p3_EN16931_1.xml"},
{"PEPPOL_UBL", "testdata/ubl/invoice/UBL-Invoice-2.1-Example.xml"},
{"Extended_CII", "testdata/cii/extended/zugferd-extended-rechnung.xml"},
}
for _, bm := range benchmarks {
b.Run(bm.name, func(b *testing.B) {
data, err := os.ReadFile(bm.file)
if err != nil {
b.Skipf("File not found: %s", bm.file)
}
inv, err := ParseReader(bytes.NewReader(data))
if err != nil {
b.Fatalf("Failed to parse: %v", err)
}
b.ReportAllocs()
b.ResetTimer()
for b.Loop() {
err := inv.Validate()
_ = err // Validation may or may not return errors
}
})
}
}
// FuzzValidate fuzzes the validation logic to ensure it never panics
func FuzzValidate(f *testing.F) {
// Seed corpus with valid invoices that should validate successfully
seeds := []string{
"testdata/cii/minimum/zugferd-minimum-rechnung.xml",
"testdata/cii/en16931/zugferd_2p3_EN16931_1.xml",
"testdata/ubl/invoice/UBL-Invoice-2.1-Example.xml",
}
for _, seed := range seeds {
data, err := os.ReadFile(seed)
if err == nil {
f.Add(data)
}
}
f.Fuzz(func(t *testing.T, data []byte) {
// Parse the data first (may fail, which is fine)
inv, err := ParseReader(bytes.NewReader(data))
if err != nil {
return // Skip invalid XML
}
// Validation should never panic, even with invalid/malformed data
err = inv.Validate()
_ = err // Validation errors are expected for malformed invoices
})
}