xref: /aosp_15_r20/external/starlark-go/starlarktest/assert.star (revision 4947cdc739c985f6d86941e22894f5cefe7c9e9a)
1*4947cdc7SCole Faust# Predeclared built-ins for this module:
2*4947cdc7SCole Faust#
3*4947cdc7SCole Faust# error(msg): report an error in Go's test framework without halting execution.
4*4947cdc7SCole Faust#  This is distinct from the built-in fail function, which halts execution.
5*4947cdc7SCole Faust# catch(f): evaluate f() and returns its evaluation error message, if any
6*4947cdc7SCole Faust# matches(str, pattern): report whether str matches regular expression pattern.
7*4947cdc7SCole Faust# module(**kwargs): a constructor for a module.
8*4947cdc7SCole Faust# _freeze(x): freeze the value x and everything reachable from it.
9*4947cdc7SCole Faust#
10*4947cdc7SCole Faust# Clients may use these functions to define their own testing abstractions.
11*4947cdc7SCole Faust
12*4947cdc7SCole Faustdef _eq(x, y):
13*4947cdc7SCole Faust    if x != y:
14*4947cdc7SCole Faust        error("%r != %r" % (x, y))
15*4947cdc7SCole Faust
16*4947cdc7SCole Faustdef _ne(x, y):
17*4947cdc7SCole Faust    if x == y:
18*4947cdc7SCole Faust        error("%r == %r" % (x, y))
19*4947cdc7SCole Faust
20*4947cdc7SCole Faustdef _true(cond, msg = "assertion failed"):
21*4947cdc7SCole Faust    if not cond:
22*4947cdc7SCole Faust        error(msg)
23*4947cdc7SCole Faust
24*4947cdc7SCole Faustdef _lt(x, y):
25*4947cdc7SCole Faust    if not (x < y):
26*4947cdc7SCole Faust        error("%s is not less than %s" % (x, y))
27*4947cdc7SCole Faust
28*4947cdc7SCole Faustdef _contains(x, y):
29*4947cdc7SCole Faust    if y not in x:
30*4947cdc7SCole Faust        error("%s does not contain %s" % (x, y))
31*4947cdc7SCole Faust
32*4947cdc7SCole Faustdef _fails(f, pattern):
33*4947cdc7SCole Faust    "assert_fails asserts that evaluation of f() fails with the specified error."
34*4947cdc7SCole Faust    msg = catch(f)
35*4947cdc7SCole Faust    if msg == None:
36*4947cdc7SCole Faust        error("evaluation succeeded unexpectedly (want error matching %r)" % pattern)
37*4947cdc7SCole Faust    elif not matches(pattern, msg):
38*4947cdc7SCole Faust        error("regular expression (%s) did not match error (%s)" % (pattern, msg))
39*4947cdc7SCole Faust
40*4947cdc7SCole Faustfreeze = _freeze  # an exported global whose value is the built-in freeze function
41*4947cdc7SCole Faust
42*4947cdc7SCole Faustassert = module(
43*4947cdc7SCole Faust    "assert",
44*4947cdc7SCole Faust    fail = error,
45*4947cdc7SCole Faust    eq = _eq,
46*4947cdc7SCole Faust    ne = _ne,
47*4947cdc7SCole Faust    true = _true,
48*4947cdc7SCole Faust    lt = _lt,
49*4947cdc7SCole Faust    contains = _contains,
50*4947cdc7SCole Faust    fails = _fails,
51*4947cdc7SCole Faust)
52