tests_test.gno
1.97 Kb ยท 65 lines
1package tests_test
2
3import (
4 "std"
5 "testing"
6
7 "gno.land/p/demo/testutils"
8 "gno.land/r/demo/tests"
9)
10
11func TestAssertOriginCall(t *testing.T) {
12 // CallAssertOriginCall(): no panic
13 caller := testutils.TestAddress("caller")
14 testing.SetRealm(std.NewUserRealm(caller))
15 tests.CallAssertOriginCall()
16 if !tests.CallIsOriginCall() {
17 t.Errorf("expected IsOriginCall=true but got false")
18 }
19
20 testing.SetRealm(std.NewCodeRealm("gno.land/r/demo/tests"))
21 // CallAssertOriginCall() from a block: panic
22 expectedReason := "invalid non-origin call"
23 func() {
24 defer func() {
25 r := recover()
26 if r == nil || r.(string) != expectedReason {
27 t.Errorf("expected panic with '%v', got '%v'", expectedReason, r)
28 }
29 }()
30 // if called inside a function literal, this is no longer an origin call
31 // because there's one additional frame (the function literal block).
32 if tests.CallIsOriginCall() {
33 t.Errorf("expected IsOriginCall=false but got true")
34 }
35 tests.CallAssertOriginCall()
36 }()
37
38 // CallSubtestsAssertOriginCall(): panic
39 defer func() {
40 r := recover()
41 if r == nil || r.(string) != expectedReason {
42 t.Errorf("expected panic with '%v', got '%v'", expectedReason, r)
43 }
44 }()
45 if tests.CallSubtestsIsOriginCall() {
46 t.Errorf("expected IsOriginCall=false but got true")
47 }
48 tests.CallSubtestsAssertOriginCall()
49}
50
51func TestPreviousRealm(t *testing.T) {
52 var (
53 firstRealm = std.DerivePkgAddr("gno.land/r/demo/tests_test")
54 rTestsAddr = std.DerivePkgAddr("gno.land/r/demo/tests")
55 )
56 // When only one realm in the frames, PreviousRealm returns the same realm
57 if addr := tests.GetPreviousRealm().Address(); addr != firstRealm {
58 println(tests.GetPreviousRealm())
59 t.Errorf("want GetPreviousRealm().Address==%s, got %s", firstRealm, addr)
60 }
61 // When 2 or more realms in the frames, PreviousRealm returns the second to last
62 if addr := tests.GetRSubtestsPreviousRealm().Address(); addr != rTestsAddr {
63 t.Errorf("want GetRSubtestsPreviousRealm().Address==%s, got %s", rTestsAddr, addr)
64 }
65}