github.com/gnolang/gno@v0.0.0-20240520182011-228e9d0192ce/examples/gno.land/r/demo/foo20/foo20_test.gno (about) 1 package foo20 2 3 import ( 4 "std" 5 "testing" 6 7 pusers "gno.land/p/demo/users" 8 "gno.land/r/demo/users" 9 ) 10 11 func TestReadOnlyPublicMethods(t *testing.T) { 12 admin := pusers.AddressOrName("g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj") 13 manfred := pusers.AddressOrName("g1u7y667z64x2h7vc6fmpcprgey4ck233jaww9zq") 14 unknown := pusers.AddressOrName("g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5") // valid but never used. 15 16 type test struct { 17 name string 18 balance uint64 19 fn func() uint64 20 } 21 22 // check balances #1. 23 { 24 tests := []test{ 25 {"TotalSupply", 10100000000, func() uint64 { return TotalSupply() }}, 26 {"BalanceOf(admin)", 10000000000, func() uint64 { return BalanceOf(admin) }}, 27 {"BalanceOf(manfred)", 100000000, func() uint64 { return BalanceOf(manfred) }}, 28 {"Allowance(admin, manfred)", 0, func() uint64 { return Allowance(admin, manfred) }}, 29 {"BalanceOf(unknown)", 0, func() uint64 { return BalanceOf(unknown) }}, 30 } 31 for _, tc := range tests { 32 if tc.fn() != tc.balance { 33 t.Errorf("%s: have: %d want: %d", tc.name, tc.fn(), tc.balance) 34 } 35 } 36 } 37 38 // unknown uses the faucet. 39 std.TestSetOrigCaller(users.Resolve(unknown)) 40 Faucet() 41 42 // check balances #2. 43 { 44 tests := []test{ 45 {"TotalSupply", 10110000000, func() uint64 { return TotalSupply() }}, 46 {"BalanceOf(admin)", 10000000000, func() uint64 { return BalanceOf(admin) }}, 47 {"BalanceOf(manfred)", 100000000, func() uint64 { return BalanceOf(manfred) }}, 48 {"Allowance(admin, manfred)", 0, func() uint64 { return Allowance(admin, manfred) }}, 49 {"BalanceOf(unknown)", 10000000, func() uint64 { return BalanceOf(unknown) }}, 50 } 51 for _, tc := range tests { 52 if tc.fn() != tc.balance { 53 t.Errorf("%s: have: %d want: %d", tc.name, tc.fn(), tc.balance) 54 } 55 } 56 } 57 } 58 59 func TestErrConditions(t *testing.T) { 60 admin := std.Address("g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj") 61 empty := std.Address("") 62 63 type test struct { 64 name string 65 msg string 66 fn func() 67 } 68 69 std.TestSetOrigCaller(admin) 70 { 71 tests := []test{ 72 {"Transfer(admin, 1)", "cannot send transfer to self", func() { Transfer(pusers.AddressOrName(admin), 1) }}, 73 {"Approve(empty, 1))", "invalid address", func() { Approve(pusers.AddressOrName(empty), 1) }}, 74 } 75 for _, tc := range tests { 76 shouldPanicWithMsg(t, tc.fn, tc.msg) 77 } 78 } 79 } 80 81 func shouldPanicWithMsg(t *testing.T, f func(), msg string) { 82 defer func() { 83 if r := recover(); r == nil { 84 t.Errorf("The code did not panic") 85 } else { 86 errMsg := error(r).Error() 87 if errMsg != msg { 88 t.Errorf("excepted panic(%v), got(%v)", msg, errMsg) 89 } 90 } 91 }() 92 f() 93 }