1import smartpy as sp
2
3
4@sp.module
5def main():
6 class MyContract(sp.Contract):
7 def __init__(self):
8 self.data.x = 0
9 self.data.y = sp.record(a=1, b="test")
10 self.data.z = sp.cast(None, sp.option[sp.nat])
11
12 @sp.entrypoint
13 def set_x(self, x):
14 self.data.x = x
15
16
17if "templates" not in __name__:
18
19 @sp.add_test()
20 def test():
21 sc = sp.test_scenario("MyContract", main)
22 c1 = main.MyContract()
23 c1.data.x = 5
24 c1.data.x = 6
25 c1.data.y = sp.record(a=2, b="test2")
26 # c1.data = sp.record(x=c1.data.x, y=c1.data.y, z=sp.Some(1))
27
28 def assert_set_x_fails(field, value, detail):
29 try:
30 setattr(c1.data, field, value)
31 except:
32 pass
33 else:
34 # Don't raise error if the scenario failed earlier.
35 # Needed for mockup.
36 if sc.failed:
37 return
38 raise AssertionError(
39 f"`c1.data.{field} = {value}` should fail {detail}"
40 )
41
42 assert_set_x_fails("x", "", "due to type inconsistency: sp.string to a sp.int")
43 assert_set_x_fails("a", 0, "because field 'a' doesn't exist")
44 sc += c1
45 assert_set_x_fails("x", 0, "after origination")
46
47 sc.verify(c1.data.x == 6)
48 sc.verify(c1.data.y.a == 2)
49 # sc.verify(c1.data.z == sp.Some(1))
50 c1.set_x(42)
51
52 c2 = main.MyContract()
53 c2.data.x = c1.data.x
54 sc += c2
55 sc.verify(c2.data.x == c1.data.x)