boolean.gno
1.94 Kb ยท 89 lines
1package expect
2
3import (
4 "strconv"
5
6 "gno.land/p/demo/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 formatBoolean(value bool) string {
62 return strconv.FormatBool(value)
63}
64
65func asBoolean(value any) (bool, error) {
66 if value == nil {
67 return false, nil
68 }
69
70 switch v := value.(type) {
71 case bool:
72 return v, nil
73 case string:
74 if v == "" {
75 return false, nil
76 }
77 return strconv.ParseBool(v)
78 case []byte:
79 return v != nil, nil
80 case Stringer:
81 s := v.String()
82 if s == "" {
83 return false, nil
84 }
85 return strconv.ParseBool(v.String())
86 default:
87 return false, ErrIncompatibleType
88 }
89}