Passed
Push — main ( 4607a7...816519 )
by Igor
03:21 queued 01:30
created

validationtest.AssertIsViolation   A

Complexity

Conditions 3

Size

Total Lines 13
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 10
dl 0
loc 13
c 0
b 0
f 0
rs 9.9
nop 3
1
// Copyright 2021 Igor Lazarev. All rights reserved.
2
// Use of this source code is governed by a MIT-style
3
// license that can be found in the LICENSE file.
4
5
// Package validationtest contains helper functions for testing purposes.
6
package validationtest
7
8
import (
9
	"testing"
10
11
	"github.com/muonsoft/validation"
12
)
13
14
type AssertViolationFunc func(t *testing.T, violation validation.Violation) bool
15
16
type AssertViolationListFunc func(t *testing.T, violations []validation.Violation) bool
17
18
func AssertIsViolation(t *testing.T, err error, assert AssertViolationFunc) bool {
19
	t.Helper()
20
	if err == nil {
21
		t.Errorf("err is nil, but expected to be a Violation")
22
		return false
23
	}
24
	violation, is := validation.UnwrapViolation(err)
25
	if !is {
26
		t.Errorf("failed asserting that error '%s' is Violation", err)
27
		return false
28
	}
29
30
	return assert(t, violation)
31
}
32
33
func AssertIsViolationList(t *testing.T, err error, assert AssertViolationListFunc) bool {
34
	t.Helper()
35
	if err == nil {
36
		t.Errorf("err is nil, but expected to be a ViolationList")
37
		return false
38
	}
39
	violations, is := validation.UnwrapViolationList(err)
40
	if !is {
41
		t.Errorf("failed asserting that error '%s' is ViolationList", err)
42
		return false
43
	}
44
45
	return assert(t, violations.AsSlice())
46
}
47
48
func AssertOneViolationInList(t *testing.T, err error, assert AssertViolationFunc) bool {
49
	t.Helper()
50
	return AssertIsViolationList(t, err, func(t *testing.T, violations []validation.Violation) bool {
51
		t.Helper()
52
		if len(violations) != 1 {
53
			t.Errorf("failed asserting that violations list contains exactly one violation, actual count is %d", len(violations))
54
			return false
55
		}
56
		return assert(t, violations[0])
57
	})
58
}
59