boolean.gno
1.87 Kb ยท 88 lines
1package expect
2
3import (
4 "strconv"
5
6 "gno.land/p/nt/ufmt"
7)
8
9// NewBooleanChecker creates a new checker of boolean values
10func NewBooleanChecker(ctx Context, value bool) BooleanChecker {
11 return BooleanChecker{ctx, value}
12}
13
14// BooleanChecker asserts boolean values.
15type BooleanChecker struct {
16 ctx Context
17 value bool
18}
19
20// Not negates the next called expectation.
21func (c BooleanChecker) Not() BooleanChecker {
22 c.ctx.negated = !c.ctx.negated
23 return c
24}
25
26// ToEqual asserts that current value is equal to an expected value.
27func (c BooleanChecker) ToEqual(v bool) {
28 c.ctx.T().Helper()
29 c.ctx.CheckExpectation(c.value == v, func(ctx Context) string {
30 got := formatBoolean(c.value)
31 if !ctx.IsNegated() {
32 want := formatBoolean(v)
33 return ufmt.Sprintf("Expected values to match\nGot: %s\nWant: %s", got, want)
34 }
35 return ufmt.Sprintf("Expected values to be different\nGot: %s", got)
36 })
37}
38
39// ToBeFalsy asserts that current value is falsy.
40func (c BooleanChecker) ToBeFalsy() {
41 c.ctx.T().Helper()
42 c.ctx.CheckExpectation(!c.value, func(ctx Context) string {
43 if !ctx.IsNegated() {
44 return "Expected value to be falsy"
45 }
46 return "Expected value not to be falsy"
47 })
48}
49
50// ToBeTruthy asserts that current value is truthy.
51func (c BooleanChecker) ToBeTruthy() {
52 c.ctx.T().Helper()
53 c.ctx.CheckExpectation(c.value, func(ctx Context) string {
54 if !ctx.IsNegated() {
55 return "Expected value to be truthy"
56 }
57 return "Expected value not to be truthy"
58 })
59}
60
61func asBoolean(value any) (bool, error) {
62 if value == nil {
63 return false, nil
64 }
65
66 var s string
67 switch v := value.(type) {
68 case bool:
69 return v, nil
70 case string:
71 s = v
72 case []byte:
73 s = string(v)
74 case Stringer:
75 s = v.String()
76 default:
77 return false, ErrIncompatibleType
78 }
79
80 if s != "" {
81 return strconv.ParseBool(s)
82 }
83 return false, nil
84}
85
86func formatBoolean(value bool) string {
87 return strconv.FormatBool(value)
88}