Search Apps Documentation Source Content File Folder Download Copy Actions Download

string.gno

2.10 Kb ยท 81 lines
 1package expect
 2
 3import (
 4	"errors"
 5
 6	"gno.land/p/nt/ufmt"
 7)
 8
 9// ErrIncompatibleType indicates that a value can't be casted to a different type.
10var ErrIncompatibleType = errors.New("incompatible type")
11
12// NewStringChecker creates a new checker of string values.
13func NewStringChecker(ctx Context, value string) StringChecker {
14	return StringChecker{ctx, value}
15}
16
17// StringChecker asserts string values.
18type StringChecker struct {
19	ctx   Context
20	value string
21}
22
23// Not negates the next called expectation.
24func (c StringChecker) Not() StringChecker {
25	c.ctx.negated = !c.ctx.negated
26	return c
27}
28
29// ToEqual asserts that current value is equal to an expected value.
30func (c StringChecker) ToEqual(v string) {
31	c.ctx.T().Helper()
32	c.ctx.CheckExpectation(c.value == v, func(ctx Context) string {
33		if !ctx.IsNegated() {
34			return ufmt.Sprintf("Expected values to match\nGot: %s\nWant: %s", c.value, v)
35		}
36		return ufmt.Sprintf("Expected values to be different\nGot: %s", c.value)
37	})
38}
39
40// ToBeEmpty asserts that current value is an empty string.
41func (c StringChecker) ToBeEmpty() {
42	c.ctx.T().Helper()
43	c.ctx.CheckExpectation(c.value == "", func(ctx Context) string {
44		if !ctx.IsNegated() {
45			return ufmt.Sprintf("Expected string to be empty\nGot: %s", c.value)
46		}
47		return ufmt.Sprintf("Unexpected empty string")
48	})
49}
50
51// ToHaveLength asserts that current value has an expected length.
52func (c StringChecker) ToHaveLength(length int) {
53	c.ctx.T().Helper()
54	c.ctx.CheckExpectation(len(c.value) == length, func(ctx Context) string {
55		got := len(c.value)
56		if !ctx.IsNegated() {
57			return ufmt.Sprintf("Expected string length to match\nGot: %d\nWant: %d", got, length)
58		}
59		return ufmt.Sprintf("Expected string lengths to be different\nGot: %d", got)
60	})
61}
62
63// Stringer defines an interface for values that has a String method.
64type Stringer interface {
65	String() string
66}
67
68func asString(value any) (string, error) {
69	switch v := value.(type) {
70	case string:
71		return v, nil
72	case []byte:
73		return string(v), nil
74	case Stringer:
75		return v.String(), nil
76	case address:
77		return v.String(), nil
78	default:
79		return "", ErrIncompatibleType
80	}
81}