How to use SetArg method of gomock Package

Best Mock code snippet using gomock.SetArg

Run Mock automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

erc20_rpc_test.go

Source: erc20_rpc_test.go Github

copy
1// Copyright 2019, Keychain Foundation Ltd.
2// This file is part of the dipperin-core library.
3//
4// The dipperin-core library is free software: you can redistribute
5// it and/or modify it under the terms of the GNU Lesser General Public License
6// as published by the Free Software Foundation, either version 3 of the
7// License, or (at your option) any later version.
8//
9// The dipperin-core library is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12// GNU Lesser General Public License for more details.
13//
14// You should have received a copy of the GNU Lesser General Public License
15// along with this program.  If not, see <https://www.gnu.org/licenses/>.
16
17package commands
18
19import (
20	"github.com/stretchr/testify/assert"
21	"math/big"
22	"os"
23	"testing"
24
25	"fmt"
26	"github.com/dipperin/dipperin-core/common"
27	"github.com/dipperin/dipperin-core/common/consts"
28	"github.com/dipperin/dipperin-core/common/hexutil"
29	"github.com/golang/mock/gomock"
30	"github.com/urfave/cli"
31)
32
33func Test_buildERC20Token(t *testing.T) {
34	c := buildERC20Token(common.HexToAddress("0x123"), "xxx", "EOS", big.NewInt(123), 9)
35	assert.NotNil(t, c)
36}
37
38func Test_isParamValid(t *testing.T) {
39	assert.True(t, isParamValid([]string{"1"}, 1))
40	assert.False(t, isParamValid([]string{"1", "2"}, 1))
41	assert.False(t, isParamValid([]string{"", "2"}, 2))
42}
43
44func TestRpcCaller_AnnounceERC20(t *testing.T) {
45	ctrl := gomock.NewController(t)
46	defer ctrl.Finish()
47
48	app := getRpcTestApp()
49	app.Action = func(context *cli.Context) {
50		c := &rpcCaller{}
51		c.AnnounceERC20(context)
52	}
53	assert.NoError(t, app.Run([]string{os.Args[0]}))
54
55	app.Action = func(context *cli.Context) {
56		c := &rpcCaller{}
57		c.AnnounceERC20(context)
58
59		context.Set("p", "")
60		c.AnnounceERC20(context)
61
62		context.Set("p", "owner_address,name,symbol,supply,decimal,gasPrice,gasLimit")
63		c.AnnounceERC20(context)
64
65		context.Set("p", fmt.Sprintf("%s,name,symbol,supply,decimal,gasPrice,gasLimit", from))
66		c.AnnounceERC20(context)
67
68		context.Set("p", fmt.Sprintf("%s,name,symbol,supply,%s,gasPrice,gasLimit", from, "20"))
69		c.AnnounceERC20(context)
70
71		context.Set("p", fmt.Sprintf("%s,name,symbol,supply,%s,gasPrice,gasLimit", from, "18"))
72		c.AnnounceERC20(context)
73
74		context.Set("p", fmt.Sprintf("%s,name,symbol,%s,%s,gasPrice,gasLimit", from, "1000", "18"))
75		c.AnnounceERC20(context)
76
77		context.Set("p", fmt.Sprintf("%s,name,symbol,%s,%s,%v,gasLimit", from, "1000", "18", "10wu"))
78		c.AnnounceERC20(context)
79
80		context.Set("p", fmt.Sprintf("%s,name,symbol,%s,%s,%v,%v", from, "1000", "18", "10wu", "100"))
81		client = NewMockRpcClient(ctrl)
82		client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).Return(testErr)
83		c.AnnounceERC20(context)
84
85		client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil)
86		c.AnnounceERC20(context)
87	}
88	assert.NoError(t, app.Run([]string{os.Args[0], "AnnounceERC20"}))
89	client = nil
90}
91
92func TestRpcCaller_ERC20Transfer(t *testing.T) {
93	ctrl := gomock.NewController(t)
94	defer ctrl.Finish()
95
96	app := getRpcTestApp()
97	app.Action = func(context *cli.Context) {
98		c := &rpcCaller{}
99		c.ERC20Transfer(context)
100	}
101	assert.NoError(t, app.Run([]string{os.Args[0]}))
102
103	app.Action = func(context *cli.Context) {
104		c := &rpcCaller{}
105		context.Set("p", "")
106		c.ERC20Transfer(context)
107
108		context.Set("p", "contractAddr,owner,to,amount,gasPrice,gasLimit")
109		c.ERC20Transfer(context)
110
111		context.Set("p", fmt.Sprintf("%s,owner,to,amount,gasPrice,gasLimit", contractAddr))
112		c.ERC20Transfer(context)
113
114		context.Set("p", fmt.Sprintf("%s,%s,to,amount,gasPrice,gasLimit", contractAddr, from))
115		c.ERC20Transfer(context)
116
117		client = NewMockRpcClient(ctrl)
118		client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).SetArg(0, consts.DIPDecimalBits)
119		context.Set("p", fmt.Sprintf("%s,%s,%s,amount,gasPrice,gasLimit", contractAddr, from, to))
120		c.ERC20Transfer(context)
121
122		client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).SetArg(0, consts.DIPDecimalBits)
123		context.Set("p", fmt.Sprintf("%s,%s,%s,%v,gasPrice,gasLimit", contractAddr, from, to, "10"))
124		c.ERC20Transfer(context)
125
126		client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).SetArg(0, consts.DIPDecimalBits)
127		context.Set("p", fmt.Sprintf("%s,%s,%s,%v,%v,gasLimit", contractAddr, from, to, "10", "10wu"))
128		c.ERC20Transfer(context)
129
130		client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).SetArg(0, consts.DIPDecimalBits)
131		client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil)
132		context.Set("p", fmt.Sprintf("%s,%s,%s,%v,%v,%v", contractAddr, from, to, "10", "10wu", "100"))
133		c.ERC20Transfer(context)
134
135		client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).SetArg(0, consts.DIPDecimalBits)
136		client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).Return(testErr)
137		c.ERC20Transfer(context)
138	}
139	assert.NoError(t, app.Run([]string{os.Args[0], "ERC20Transfer"}))
140	client = nil
141}
142
143func TestRpcCaller_ERC20TransferFrom(t *testing.T) {
144	ctrl := gomock.NewController(t)
145	defer ctrl.Finish()
146
147	app := getRpcTestApp()
148	app.Action = func(context *cli.Context) {
149		c := &rpcCaller{}
150		c.ERC20TransferFrom(context)
151	}
152	assert.NoError(t, app.Run([]string{os.Args[0]}))
153
154	app.Action = func(context *cli.Context) {
155		c := &rpcCaller{}
156		context.Set("p", "")
157		c.ERC20TransferFrom(context)
158
159		context.Set("p", "contractAddr,owner,from,to,amount,gasPrice,gasLimit")
160		c.ERC20TransferFrom(context)
161
162		context.Set("p", fmt.Sprintf("%s,owner,from,to,amount,gasPrice,gasLimit", contractAddr))
163		c.ERC20TransferFrom(context)
164
165		context.Set("p", fmt.Sprintf("%s,%s,from,to,amount,gasPrice,gasLimit", contractAddr, from))
166		c.ERC20TransferFrom(context)
167
168		context.Set("p", fmt.Sprintf("%s,%s,%s,to,amount,gasPrice,gasLimit", contractAddr, from, from))
169		c.ERC20TransferFrom(context)
170
171		client = NewMockRpcClient(ctrl)
172		client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).SetArg(0, consts.DIPDecimalBits)
173		context.Set("p", fmt.Sprintf("%s,%s,%s,%s,amount,gasPrice,gasLimit", contractAddr, from, from, to))
174		c.ERC20TransferFrom(context)
175
176		client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).SetArg(0, consts.DIPDecimalBits)
177		context.Set("p", fmt.Sprintf("%s,%s,%s,%s,%s,gasPrice,gasLimit", contractAddr, from, from, to, "10"))
178		c.ERC20TransferFrom(context)
179
180		client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).SetArg(0, consts.DIPDecimalBits)
181		context.Set("p", fmt.Sprintf("%s,%s,%s,%s,%s,%s,gasLimit", contractAddr, from, from, to, "10", "10wu"))
182		c.ERC20TransferFrom(context)
183
184		client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).SetArg(0, consts.DIPDecimalBits)
185		client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).Return(testErr)
186		context.Set("p", fmt.Sprintf("%s,%s,%s,%s,%s,%s,%s", contractAddr, from, from, to, "10", "10wu", "100"))
187		c.ERC20TransferFrom(context)
188
189		client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).SetArg(0, consts.DIPDecimalBits)
190		client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil)
191		c.ERC20TransferFrom(context)
192	}
193	assert.NoError(t, app.Run([]string{os.Args[0], "ERC20TransferFrom"}))
194	client = nil
195}
196
197func TestRpcCaller_ERC20Allowance(t *testing.T) {
198	ctrl := gomock.NewController(t)
199	defer ctrl.Finish()
200
201	app := getRpcTestApp()
202	app.Action = func(context *cli.Context) {
203		c := &rpcCaller{}
204		c.ERC20Allowance(context)
205	}
206	assert.NoError(t, app.Run([]string{os.Args[0]}))
207
208	app.Action = func(context *cli.Context) {
209		c := &rpcCaller{}
210		context.Set("p", "")
211		c.ERC20Allowance(context)
212
213		context.Set("p", "contractAddr,owner,spender")
214		c.ERC20Allowance(context)
215
216		context.Set("p", fmt.Sprintf("%s,owner,spender", contractAddr))
217		c.ERC20Allowance(context)
218
219		context.Set("p", fmt.Sprintf("%s,%s,spender", contractAddr, from))
220		c.ERC20Allowance(context)
221
222		context.Set("p", fmt.Sprintf("%s,%s,%s", contractAddr, from, to))
223		client = NewMockRpcClient(ctrl)
224		client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).Return(testErr)
225		c.ERC20Allowance(context)
226
227		client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).SetArg(0, big.NewInt(1e18))
228		client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).SetArg(0, consts.DIPDecimalBits)
229		client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).SetArg(0, "dip")
230		c.ERC20Allowance(context)
231	}
232	assert.NoError(t, app.Run([]string{os.Args[0], "ERC20Allowance"}))
233	client = nil
234}
235
236func TestRpcCaller_ERC20Approve(t *testing.T) {
237	ctrl := gomock.NewController(t)
238	defer ctrl.Finish()
239
240	app := getRpcTestApp()
241	app.Action = func(context *cli.Context) {
242		c := &rpcCaller{}
243		c.ERC20Approve(context)
244	}
245	assert.NoError(t, app.Run([]string{os.Args[0]}))
246
247	app.Action = func(context *cli.Context) {
248		c := &rpcCaller{}
249		context.Set("p", "")
250		c.ERC20Approve(context)
251
252		context.Set("p", "contractAddr,owner,to,amount,gasPrice,gasLimit")
253		c.ERC20Approve(context)
254
255		context.Set("p", fmt.Sprintf("%s,owner,to,amount,gasPrice,gasLimit", contractAddr))
256		c.ERC20Approve(context)
257
258		context.Set("p", fmt.Sprintf("%s,%s,to,amount,gasPrice,gasLimit", contractAddr, from))
259		c.ERC20Approve(context)
260
261		client = NewMockRpcClient(ctrl)
262		client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).SetArg(0, consts.KUnitDecimalBits)
263		context.Set("p", fmt.Sprintf("%s,%s,%s,amount,gasPrice,gasLimit", contractAddr, from, to))
264		c.ERC20Approve(context)
265
266		client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).SetArg(0, consts.KUnitDecimalBits)
267		client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).Return(testErr)
268		context.Set("p", fmt.Sprintf("%s,%s,%s,%s,gasPrice,gasLimit", contractAddr, from, to, "10"))
269		c.ERC20Approve(context)
270
271		client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).SetArg(0, consts.KUnitDecimalBits)
272		client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).SetArg(0, big.NewInt(10))
273		context.Set("p", fmt.Sprintf("%s,%s,%s,%s,gasPrice,gasLimit", contractAddr, from, to, "10"))
274		c.ERC20Approve(context)
275
276		client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).SetArg(0, consts.KUnitDecimalBits)
277		client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).SetArg(0, big.NewInt(1e5))
278		context.Set("p", fmt.Sprintf("%s,%s,%s,%s,gasPrice,gasLimit", contractAddr, from, to, "10"))
279		c.ERC20Approve(context)
280
281		client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).SetArg(0, consts.KUnitDecimalBits)
282		client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).SetArg(0, big.NewInt(1e5))
283		context.Set("p", fmt.Sprintf("%s,%s,%s,%s,%s,gasLimit", contractAddr, from, to, "10", "1wu"))
284		c.ERC20Approve(context)
285
286		client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).SetArg(0, consts.KUnitDecimalBits)
287		client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).SetArg(0, big.NewInt(1e5))
288		client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil)
289		context.Set("p", fmt.Sprintf("%s,%s,%s,%s,%s,%s", contractAddr, from, to, "10", "1wu", "100"))
290		c.ERC20Approve(context)
291
292		client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).SetArg(0, consts.KUnitDecimalBits)
293		client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).SetArg(0, big.NewInt(1e5))
294		client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).Return(testErr)
295		c.ERC20Approve(context)
296	}
297	assert.NoError(t, app.Run([]string{os.Args[0], "ERC20Approve"}))
298	client = nil
299}
300
301func TestRpcCaller_ERC20TotalSupply(t *testing.T) {
302	ctrl := gomock.NewController(t)
303	defer ctrl.Finish()
304
305	app := getRpcTestApp()
306	app.Action = func(context *cli.Context) {
307		c := &rpcCaller{}
308		c.ERC20TotalSupply(context)
309	}
310	assert.NoError(t, app.Run([]string{os.Args[0]}))
311
312	app.Action = func(context *cli.Context) {
313		c := &rpcCaller{}
314		context.Set("p", "")
315		c.ERC20TotalSupply(context)
316
317		context.Set("p", "contractAddr")
318		c.ERC20TotalSupply(context)
319
320		context.Set("p", contractAddr)
321		client = NewMockRpcClient(ctrl)
322		client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).Return(testErr)
323		c.ERC20TotalSupply(context)
324
325		client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).SetArg(0, big.NewInt(1e18))
326		client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).SetArg(0, consts.DIPDecimalBits)
327		client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).SetArg(0, "dip")
328		c.ERC20TotalSupply(context)
329	}
330	assert.NoError(t, app.Run([]string{os.Args[0], "ERC20TotalSupply"}))
331	client = nil
332}
333
334func TestRpcCaller_ERC20Balance(t *testing.T) {
335	ctrl := gomock.NewController(t)
336	defer ctrl.Finish()
337
338	app := getRpcTestApp()
339	app.Action = func(context *cli.Context) {
340		c := &rpcCaller{}
341		c.ERC20Balance(context)
342	}
343	assert.NoError(t, app.Run([]string{os.Args[0]}))
344
345	app.Action = func(context *cli.Context) {
346		c := &rpcCaller{}
347		context.Set("p", "")
348		c.ERC20Balance(context)
349
350		context.Set("p", "contractAddr,owner")
351		c.ERC20Balance(context)
352
353		context.Set("p", fmt.Sprintf("%s,owner", contractAddr))
354		c.ERC20Balance(context)
355
356		context.Set("p", fmt.Sprintf("%s,%s", contractAddr, from))
357		client = NewMockRpcClient(ctrl)
358		client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).Return(testErr)
359		c.ERC20Balance(context)
360
361		balance := big.NewInt(1e18)
362		client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).SetArg(0, (*hexutil.Big)(balance))
363		client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).SetArg(0, consts.DIPDecimalBits)
364		client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).SetArg(0, "dip")
365		c.ERC20Balance(context)
366	}
367	assert.NoError(t, app.Run([]string{os.Args[0], "ERC20Balance"}))
368	client = nil
369}
370
371func TestRpcCaller_ERC20TokenName(t *testing.T) {
372	ctrl := gomock.NewController(t)
373	defer ctrl.Finish()
374
375	app := getRpcTestApp()
376	app.Action = func(context *cli.Context) {
377		c := &rpcCaller{}
378		c.ERC20TokenName(context)
379	}
380	assert.NoError(t, app.Run([]string{os.Args[0]}))
381
382	app.Action = func(context *cli.Context) {
383		c := &rpcCaller{}
384		context.Set("p", "")
385		c.ERC20TokenName(context)
386
387		context.Set("p", "contractAddr")
388		c.ERC20TokenName(context)
389
390		context.Set("p", contractAddr)
391		client = NewMockRpcClient(ctrl)
392		client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).Return(testErr)
393		c.ERC20TokenName(context)
394
395		client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).SetArg(0, "name")
396		c.ERC20TokenName(context)
397	}
398	assert.NoError(t, app.Run([]string{os.Args[0], "ERC20TokenName"}))
399	client = nil
400}
401
402func TestRpcCaller_ERC20TokenSymbol(t *testing.T) {
403	ctrl := gomock.NewController(t)
404	defer ctrl.Finish()
405
406	app := getRpcTestApp()
407	app.Action = func(context *cli.Context) {
408		c := &rpcCaller{}
409		c.ERC20TokenSymbol(context)
410	}
411	assert.NoError(t, app.Run([]string{os.Args[0]}))
412
413	app.Action = func(context *cli.Context) {
414		c := &rpcCaller{}
415		context.Set("p", "")
416		c.ERC20TokenSymbol(context)
417
418		context.Set("p", "contractAddr")
419		c.ERC20TokenSymbol(context)
420
421		context.Set("p", contractAddr)
422		client = NewMockRpcClient(ctrl)
423		client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).Return(testErr)
424		c.ERC20TokenSymbol(context)
425
426		client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).SetArg(0, "symbol")
427		c.ERC20TokenSymbol(context)
428	}
429	assert.NoError(t, app.Run([]string{os.Args[0], "ERC20TokenSymbol"}))
430	client = nil
431}
432
433func TestRpcCaller_ERC20TokenDecimals(t *testing.T) {
434	ctrl := gomock.NewController(t)
435	defer ctrl.Finish()
436
437	app := getRpcTestApp()
438	app.Action = func(context *cli.Context) {
439		c := &rpcCaller{}
440		c.ERC20TokenDecimals(context)
441	}
442	assert.NoError(t, app.Run([]string{os.Args[0]}))
443
444	app.Action = func(context *cli.Context) {
445		c := &rpcCaller{}
446		context.Set("p", "")
447		c.ERC20TokenDecimals(context)
448
449		context.Set("p", "contractAddr")
450		c.ERC20TokenDecimals(context)
451
452		context.Set("p", contractAddr)
453		client = NewMockRpcClient(ctrl)
454		client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).Return(testErr)
455		c.ERC20TokenDecimals(context)
456
457		client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).SetArg(0, 18)
458		c.ERC20TokenDecimals(context)
459	}
460	assert.NoError(t, app.Run([]string{os.Args[0], "ERC20TokenDecimals"}))
461	client = nil
462}
463
464func TestRpcCaller_ERC20GetInfo(t *testing.T) {
465	ctrl := gomock.NewController(t)
466	defer ctrl.Finish()
467
468	app := getRpcTestApp()
469	app.Action = func(context *cli.Context) {
470		c := &rpcCaller{}
471		c.ERC20GetInfo(context)
472	}
473	assert.NoError(t, app.Run([]string{os.Args[0]}))
474
475	app.Action = func(context *cli.Context) {
476		c := &rpcCaller{}
477		context.Set("p", "")
478		c.ERC20GetInfo(context)
479
480		context.Set("p", "contractAddr")
481		c.ERC20GetInfo(context)
482
483		context.Set("p", contractAddr)
484		client = NewMockRpcClient(ctrl)
485		client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil).MaxTimes(3)
486		c.ERC20GetInfo(context)
487
488		client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).Return(testErr)
489		c.ERC20GetInfo(context)
490
491		mapInterface := make(map[string]interface{})
492		mapInterface["token_total_supply"] = "1000000000000000000"
493		client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).SetArg(0, mapInterface)
494		client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).SetArg(0, consts.DIPDecimalBits)
495		client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).SetArg(0, "dip")
496		c.ERC20GetInfo(context)
497
498		client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).SetArg(0, mapInterface)
499		client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).Return(testErr).MaxTimes(2)
500		c.ERC20GetInfo(context)
501	}
502	assert.NoError(t, app.Run([]string{os.Args[0], "ERC20GetInfo"}))
503	client = nil
504}
505
Full Screen

proposal_strategy_test.go

Source: proposal_strategy_test.go Github

copy
1package contracts
2
3import (
4	"encoding/json"
5	"testing"
6
7	"github.com/golang/mock/gomock"
8	"github.com/meshplus/bitxhub-core/boltvm"
9	"github.com/meshplus/bitxhub-core/boltvm/mock_stub"
10	"github.com/meshplus/bitxhub-core/governance"
11	"github.com/meshplus/bitxhub-kit/log"
12	"github.com/meshplus/bitxhub-model/constant"
13	"github.com/meshplus/bitxhub-model/pb"
14	"github.com/meshplus/bitxhub/internal/repo"
15	"github.com/stretchr/testify/assert"
16)
17
18func TestGovStrategy_UpdateProposalStrategy(t *testing.T) {
19	g, mockStub, strategies, _ := proposalStrategyPrepare(t)
20	mockStub.EXPECT().CurrentCaller().Return(noAdminAddr).Times(1)
21	mockStub.EXPECT().CurrentCaller().Return(adminAddr).AnyTimes()
22	mockStub.EXPECT().CrossInvoke(constant.RoleContractAddr.String(), "IsAnyAvailableAdmin", pb.String(noAdminAddr), pb.String(string(GovernanceAdmin))).Return(boltvm.Success([]byte(FALSE))).AnyTimes()
23	mockStub.EXPECT().CrossInvoke(constant.RoleContractAddr.String(), "IsAnyAvailableAdmin", pb.String(adminAddr), pb.String(string(GovernanceAdmin))).Return(boltvm.Success([]byte(TRUE))).AnyTimes()
24
25	// 0: updating
26	mockStub.EXPECT().GetObject(ProposalStrategyKey(strategies[0].Module), gomock.Any()).SetArg(1, *strategies[7]).Return(true).Times(1)
27	// 0: available
28	mockStub.EXPECT().GetObject(ProposalStrategyKey(strategies[0].Module), gomock.Any()).SetArg(1, *strategies[0]).Return(true).AnyTimes()
29	mockStub.EXPECT().CrossInvoke(constant.RoleContractAddr.Address().String(), "GetRolesByType", pb.String(string(GovernanceAdmin))).Return(boltvm.Error("", "crossinvoke GetRolesByType error")).Times(1)
30	roles := make([]*Role, 0)
31	roles = append(roles, &Role{
32		Status: governance.GovernanceAvailable,
33	})
34	rolesData, err := json.Marshal(roles)
35	assert.Nil(t, err)
36	mockStub.EXPECT().CrossInvoke(constant.RoleContractAddr.Address().String(), "GetRolesByType", pb.String(string(GovernanceAdmin))).Return(boltvm.Success(rolesData)).AnyTimes()
37	mockStub.EXPECT().CrossInvoke(gomock.Eq(constant.GovernanceContractAddr.Address().String()), gomock.Eq("SubmitProposal"),
38		gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(boltvm.Error("", "SubmitProposal error")).Times(1)
39	mockStub.EXPECT().CrossInvoke(gomock.Eq(constant.GovernanceContractAddr.Address().String()), gomock.Eq("SubmitProposal"),
40		gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(boltvm.Success(nil)).AnyTimes()
41	mockStub.EXPECT().CrossInvoke(gomock.Eq(constant.GovernanceContractAddr.Address().String()), gomock.Eq("ZeroPermission"),
42		gomock.Any()).Return(boltvm.Success(nil)).AnyTimes()
43	mockStub.EXPECT().PostEvent(gomock.Any(), gomock.Any()).AnyTimes()
44	mockStub.EXPECT().Get(gomock.Any()).Return(true, nil).AnyTimes()
45	mockStub.EXPECT().Logger().Return(log.NewWithModule("contracts")).AnyTimes()
46	mockStub.EXPECT().Caller().Return(adminAddr).AnyTimes()
47	mockStub.EXPECT().SetObject(gomock.Any(), gomock.Any()).Return().AnyTimes()
48
49	// promission error
50	res := g.UpdateProposalStrategy(strategies[0].Module, string(SimpleMajority), repo.DefaultSimpleMajorityExpression, "123")
51	assert.False(t, res.Ok, string(res.Result))
52
53	// update updating strategy error
54	res = g.UpdateProposalStrategy(strategies[0].Module, string(SimpleMajority), repo.DefaultSimpleMajorityExpression, "123")
55	assert.False(t, res.Ok, string(res.Result))
56
57	// not update error
58	res = g.UpdateProposalStrategy(strategies[0].Module, string(SimpleMajority), "a==t", "123")
59	assert.False(t, res.Ok, string(res.Result))
60
61	// GetRolesByType error
62	res = g.UpdateProposalStrategy(strategies[0].Module, string(ZeroPermission), "", "123")
63	assert.False(t, res.Ok, string(res.Result))
64
65	// illegal strategy info error
66	res = g.UpdateProposalStrategy(strategies[0].Module, "", "", "123")
67	assert.False(t, res.Ok, string(res.Result))
68
69	// submit proposal error
70	res = g.UpdateProposalStrategy(strategies[0].Module, string(SimpleMajority), repo.DefaultSimpleMajorityExpression, "123")
71	assert.False(t, res.Ok, string(res.Result))
72
73	// ok
74	res = g.UpdateProposalStrategy(strategies[0].Module, string(SimpleMajority), repo.DefaultSimpleMajorityExpression, "123")
75	assert.True(t, res.Ok, string(res.Result))
76}
77
78func TestGovStrategy_UpdateAllProposalStrategy(t *testing.T) {
79	g, mockStub, strategies, _ := proposalStrategyPrepare(t)
80
81	mockStub.EXPECT().CurrentCaller().Return(noAdminAddr).Times(1)
82	mockStub.EXPECT().CurrentCaller().Return(adminAddr).AnyTimes()
83	mockStub.EXPECT().CrossInvoke(constant.RoleContractAddr.String(), "IsAnyAvailableAdmin", pb.String(noAdminAddr), pb.String(string(GovernanceAdmin))).Return(boltvm.Success([]byte(FALSE))).AnyTimes()
84	mockStub.EXPECT().CrossInvoke(constant.RoleContractAddr.String(), "IsAnyAvailableAdmin", pb.String(adminAddr), pb.String(string(GovernanceAdmin))).Return(boltvm.Success([]byte(TRUE))).AnyTimes()
85
86	// 0: updating
87	mockStub.EXPECT().GetObject(ProposalStrategyKey(strategies[0].Module), gomock.Any()).SetArg(1, *strategies[7]).Return(true).Times(1)
88	// 0: available
89	mockStub.EXPECT().GetObject(ProposalStrategyKey(strategies[0].Module), gomock.Any()).SetArg(1, *strategies[0]).Return(true).AnyTimes()
90	// 1: available
91	mockStub.EXPECT().GetObject(ProposalStrategyKey(strategies[1].Module), gomock.Any()).SetArg(1, *strategies[1]).Return(true).AnyTimes()
92	// 2: available
93	mockStub.EXPECT().GetObject(ProposalStrategyKey(strategies[2].Module), gomock.Any()).SetArg(1, *strategies[2]).Return(true).AnyTimes()
94	// 3: available
95	mockStub.EXPECT().GetObject(ProposalStrategyKey(strategies[3].Module), gomock.Any()).SetArg(1, *strategies[3]).Return(true).AnyTimes()
96	// 4: available
97	mockStub.EXPECT().GetObject(ProposalStrategyKey(strategies[4].Module), gomock.Any()).SetArg(1, *strategies[4]).Return(true).AnyTimes()
98	// 5: available
99	mockStub.EXPECT().GetObject(ProposalStrategyKey(strategies[5].Module), gomock.Any()).SetArg(1, *strategies[5]).Return(true).AnyTimes()
100	// 6: available
101	mockStub.EXPECT().GetObject(ProposalStrategyKey(strategies[6].Module), gomock.Any()).SetArg(1, *strategies[6]).Return(true).AnyTimes()
102
103	mockStub.EXPECT().CrossInvoke(constant.RoleContractAddr.Address().String(), "GetRolesByType", pb.String(string(GovernanceAdmin))).Return(boltvm.Error("", "crossinvoke GetRolesByType error")).Times(1)
104	roles := make([]*Role, 0)
105	roles = append(roles, &Role{
106		Status: governance.GovernanceAvailable,
107	})
108	rolesData, err := json.Marshal(roles)
109	assert.Nil(t, err)
110	mockStub.EXPECT().CrossInvoke(constant.RoleContractAddr.Address().String(), "GetRolesByType", pb.String(string(GovernanceAdmin))).Return(boltvm.Success(rolesData)).AnyTimes()
111
112	mockStub.EXPECT().CrossInvoke(gomock.Eq(constant.GovernanceContractAddr.Address().String()), gomock.Eq("SubmitProposal"),
113		gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(boltvm.Error("", "SubmitProposal error")).Times(1)
114	mockStub.EXPECT().CrossInvoke(gomock.Eq(constant.GovernanceContractAddr.Address().String()), gomock.Eq("SubmitProposal"),
115		gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(boltvm.Success(nil)).AnyTimes()
116	mockStub.EXPECT().CrossInvoke(gomock.Eq(constant.GovernanceContractAddr.Address().String()), gomock.Eq("ZeroPermission"),
117		gomock.Any()).Return(boltvm.Success(nil)).AnyTimes()
118	mockStub.EXPECT().PostEvent(gomock.Any(), gomock.Any()).AnyTimes()
119	mockStub.EXPECT().Get(gomock.Any()).Return(true, nil).AnyTimes()
120	mockStub.EXPECT().Logger().Return(log.NewWithModule("contracts")).AnyTimes()
121	mockStub.EXPECT().Caller().Return(adminAddr).AnyTimes()
122	mockStub.EXPECT().SetObject(gomock.Any(), gomock.Any()).Return().AnyTimes()
123
124	// promission error
125	res := g.UpdateAllProposalStrategy(string(SimpleMajority), repo.DefaultSimpleMajorityExpression, "123")
126	assert.False(t, res.Ok)
127
128	// update updating strategy error
129	res = g.UpdateAllProposalStrategy(string(SimpleMajority), repo.DefaultSimpleMajorityExpression, "123")
130	assert.False(t, res.Ok)
131
132	// not update error
133	res = g.UpdateAllProposalStrategy(string(SimpleMajority), "a==t", "123")
134	assert.False(t, res.Ok)
135
136	// GetRolesByType error
137	res = g.UpdateAllProposalStrategy(string(ZeroPermission), "", "123")
138	assert.False(t, res.Ok, string(res.Result))
139
140	// illegal strategy info error
141	res = g.UpdateAllProposalStrategy("", repo.DefaultSimpleMajorityExpression, "123")
142	assert.False(t, res.Ok)
143
144	// submit proposal error
145	res = g.UpdateAllProposalStrategy(string(SimpleMajority), repo.DefaultSimpleMajorityExpression, "123")
146	assert.False(t, res.Ok)
147
148	// ok
149	res = g.UpdateAllProposalStrategy(string(SimpleMajority), repo.DefaultSimpleMajorityExpression, "123")
150	assert.True(t, res.Ok)
151}
152
153func TestGovStrategy_UpdateProposalStrategyByRolesChange(t *testing.T) {
154	g, mockStub, strategies, _ := proposalStrategyPrepare(t)
155
156	mockStub.EXPECT().CurrentCaller().Return(noAdminAddr).Times(1)
157	mockStub.EXPECT().CurrentCaller().Return(constant.RoleContractAddr.Address().String()).AnyTimes()
158
159	// 0: updating
160	mockStub.EXPECT().GetObject(ProposalStrategyKey(strategies[0].Module), gomock.Any()).SetArg(1, *strategies[7]).Return(true).AnyTimes()
161	// 1: available
162	mockStub.EXPECT().GetObject(ProposalStrategyKey(strategies[1].Module), gomock.Any()).SetArg(1, *strategies[1]).Return(true).AnyTimes()
163	// 2: available
164	mockStub.EXPECT().GetObject(ProposalStrategyKey(strategies[2].Module), gomock.Any()).SetArg(1, *strategies[2]).Return(true).AnyTimes()
165	// 3: available
166	mockStub.EXPECT().GetObject(ProposalStrategyKey(strategies[3].Module), gomock.Any()).SetArg(1, *strategies[3]).Return(true).AnyTimes()
167	// 4: available
168	mockStub.EXPECT().GetObject(ProposalStrategyKey(strategies[4].Module), gomock.Any()).SetArg(1, *strategies[4]).Return(true).AnyTimes()
169	// 5: available
170	mockStub.EXPECT().GetObject(ProposalStrategyKey(strategies[5].Module), gomock.Any()).SetArg(1, *strategies[5]).Return(true).AnyTimes()
171	// 6: available/a==5
172	mockStub.EXPECT().GetObject(ProposalStrategyKey(strategies[6].Module), gomock.Any()).SetArg(1, *strategies[14]).Return(true).AnyTimes()
173
174	mockStub.EXPECT().Logger().Return(log.NewWithModule("contracts")).AnyTimes()
175	mockStub.EXPECT().SetObject(gomock.Any(), gomock.Any()).Return().AnyTimes()
176
177	// promission error
178	res := g.UpdateProposalStrategyByRolesChange(4)
179	assert.False(t, res.Ok)
180
181	res = g.UpdateProposalStrategyByRolesChange(4)
182	assert.True(t, res.Ok)
183}
184
185func TestGovStrategy_Manage(t *testing.T) {
186	g, mockStub, strategies, _ := proposalStrategyPrepare(t)
187
188	mockStub.EXPECT().CurrentCaller().Return(noAdminAddr).Times(1)
189	mockStub.EXPECT().CurrentCaller().Return(constant.GovernanceContractAddr.Address().String()).AnyTimes()
190
191	// 0: available
192	mockStub.EXPECT().GetObject(ProposalStrategyKey(strategies[0].Module), gomock.Any()).SetArg(1, *strategies[0]).Return(true).Times(2)
193
194	// 0: updating
195	mockStub.EXPECT().GetObject(ProposalStrategyKey(strategies[0].Module), gomock.Any()).SetArg(1, *strategies[7]).Return(true).AnyTimes()
196	// 1: updating
197	mockStub.EXPECT().GetObject(ProposalStrategyKey(strategies[1].Module), gomock.Any()).SetArg(1, *strategies[8]).Return(true).AnyTimes()
198	// 2: updating
199	mockStub.EXPECT().GetObject(ProposalStrategyKey(strategies[2].Module), gomock.Any()).SetArg(1, *strategies[9]).Return(true).AnyTimes()
200	// 3: updating
201	mockStub.EXPECT().GetObject(ProposalStrategyKey(strategies[3].Module), gomock.Any()).SetArg(1, *strategies[10]).Return(true).AnyTimes()
202	// 4: updating
203	mockStub.EXPECT().GetObject(ProposalStrategyKey(strategies[4].Module), gomock.Any()).SetArg(1, *strategies[11]).Return(true).AnyTimes()
204	// 5: updating
205	mockStub.EXPECT().GetObject(ProposalStrategyKey(strategies[5].Module), gomock.Any()).SetArg(1, *strategies[12]).Return(true).AnyTimes()
206	// 6: updating
207	mockStub.EXPECT().GetObject(ProposalStrategyKey(strategies[6].Module), gomock.Any()).SetArg(1, *strategies[13]).Return(true).AnyTimes()
208
209	mockStub.EXPECT().CrossInvoke(constant.RoleContractAddr.Address().String(), "GetRolesByType", pb.String(string(GovernanceAdmin))).Return(boltvm.Error("", "crossinvoke GetRolesByType error")).Times(1)
210	roles := make([]*Role, 0)
211	roles = append(roles, &Role{
212		Status: governance.GovernanceAvailable,
213	})
214	rolesData, err := json.Marshal(roles)
215	assert.Nil(t, err)
216	mockStub.EXPECT().CrossInvoke(constant.RoleContractAddr.Address().String(), "GetRolesByType", pb.String(string(GovernanceAdmin))).Return(boltvm.Success(rolesData)).AnyTimes()
217
218	mockStub.EXPECT().CrossInvoke(gomock.Eq(constant.GovernanceContractAddr.Address().String()), gomock.Eq("ZeroPermission"),
219		gomock.Any()).Return(boltvm.Success(nil)).AnyTimes()
220	mockStub.EXPECT().PostEvent(gomock.Any(), gomock.Any()).AnyTimes()
221	mockStub.EXPECT().Get(gomock.Any()).Return(true, nil).AnyTimes()
222	mockStub.EXPECT().Logger().Return(log.NewWithModule("contracts")).AnyTimes()
223	mockStub.EXPECT().Caller().Return(adminAddr).AnyTimes()
224	mockStub.EXPECT().SetObject(gomock.Any(), gomock.Any()).Return().AnyTimes()
225
226	updateStrategyInfo := map[string]UpdateStrategyInfo{
227		strategies[0].Module: UpdateStrategyInfo{
228			Typ: UpdateInfo{
229				OldInfo: ZeroPermission,
230				NewInfo: SimpleMajority,
231				IsEdit:  true,
232			},
233			Extra: UpdateInfo{
234				OldInfo: "",
235				NewInfo: repo.DefaultSimpleMajorityExpression,
236				IsEdit:  true,
237			},
238		},
239	}
240	extra, err := json.Marshal(updateStrategyInfo)
241	assert.Nil(t, err)
242
243	updateStrategyInfo1 := map[string]UpdateStrategyInfo{
244		strategies[0].Module: UpdateStrategyInfo{
245			Typ: UpdateInfo{
246				OldInfo: ZeroPermission,
247				NewInfo: SimpleMajority,
248				IsEdit:  true,
249			},
250			Extra: UpdateInfo{
251				OldInfo: "",
252				NewInfo: "a==4",
253				IsEdit:  true,
254			},
255		},
256	}
257	extra1, err := json.Marshal(updateStrategyInfo1)
258	assert.Nil(t, err)
259
260	updateAllStrategyInfo := map[string]UpdateStrategyInfo{}
261	for _, mgr := range mgrs {
262		updateAllStrategyInfo[mgr] = UpdateStrategyInfo{
263			Typ: UpdateInfo{
264				OldInfo: SimpleMajority,
265				NewInfo: ZeroPermission,
266				IsEdit:  true,
267			},
268			Extra: UpdateInfo{
269				OldInfo: repo.DefaultSimpleMajorityExpression,
270				NewInfo: "",
271				IsEdit:  true,
272			},
273		}
274	}
275	allExtra, err := json.Marshal(updateAllStrategyInfo)
276	assert.Nil(t, err)
277
278	// promission error
279	res := g.Manage(string(governance.EventUpdate), BallotApprove, string(governance.GovernanceAvailable), strategies[0].Module, extra)
280	assert.False(t, res.Ok)
281
282	// not all mgr change status error
283	res = g.Manage(string(governance.EventUpdate), BallotApprove, string(governance.GovernanceAvailable), strategies[0].Module, extra)
284	assert.False(t, res.Ok)
285
286	// all mgr change status error
287	res = g.Manage(string(governance.EventUpdate), BallotApprove, string(governance.GovernanceAvailable), repo.AllMgr, extra)
288	assert.False(t, res.Ok)
289
290	// GetRolesByType error
291	res = g.Manage(string(governance.EventUpdate), BallotApprove, string(governance.GovernanceAvailable), strategies[0].Module, extra)
292	assert.False(t, res.Ok)
293
294	// update to default
295	res = g.Manage(string(governance.EventUpdate), BallotApprove, string(governance.GovernanceAvailable), strategies[0].Module, extra1)
296	assert.True(t, res.Ok)
297
298	res = g.Manage(string(governance.EventUpdate), BallotApprove, string(governance.GovernanceAvailable), strategies[0].Module, extra)
299	assert.True(t, res.Ok)
300
301	res = g.Manage(string(governance.EventUpdate), BallotApprove, string(governance.GovernanceAvailable), repo.AllMgr, allExtra)
302	assert.True(t, res.Ok)
303}
304
305func TestGovStrategy_GetAllProposalStrategy(t *testing.T) {
306	g, mockStub, strategies, _ := proposalStrategyPrepare(t)
307
308	// 0: not set
309	mockStub.EXPECT().GetObject(ProposalStrategyKey(strategies[0].Module), gomock.Any()).Return(false).Times(1)
310	// 0: available
311	mockStub.EXPECT().GetObject(ProposalStrategyKey(strategies[0].Module), gomock.Any()).SetArg(1, *strategies[0]).Return(true).AnyTimes()
312	// 1: available
313	mockStub.EXPECT().GetObject(ProposalStrategyKey(strategies[1].Module), gomock.Any()).SetArg(1, *strategies[1]).Return(true).AnyTimes()
314	// 2: available
315	mockStub.EXPECT().GetObject(ProposalStrategyKey(strategies[2].Module), gomock.Any()).SetArg(1, *strategies[2]).Return(true).AnyTimes()
316	// 3: available
317	mockStub.EXPECT().GetObject(ProposalStrategyKey(strategies[3].Module), gomock.Any()).SetArg(1, *strategies[3]).Return(true).AnyTimes()
318	// 4: available
319	mockStub.EXPECT().GetObject(ProposalStrategyKey(strategies[4].Module), gomock.Any()).SetArg(1, *strategies[4]).Return(true).AnyTimes()
320	// 5: available
321	mockStub.EXPECT().GetObject(ProposalStrategyKey(strategies[5].Module), gomock.Any()).SetArg(1, *strategies[5]).Return(true).AnyTimes()
322	// 6: available
323	mockStub.EXPECT().GetObject(ProposalStrategyKey(strategies[6].Module), gomock.Any()).SetArg(1, *strategies[6]).Return(true).AnyTimes()
324
325	res := g.GetAllProposalStrategy()
326	assert.True(t, res.Ok)
327
328	res = g.GetAllProposalStrategy()
329	assert.True(t, res.Ok)
330}
331
332func TestGovStrategy_GetProposalStrategy(t *testing.T) {
333	g, mockStub, strategies, _ := proposalStrategyPrepare(t)
334
335	// 0: not set
336	mockStub.EXPECT().GetObject(ProposalStrategyKey(strategies[0].Module), gomock.Any()).Return(false).Times(1)
337	// 0: available
338	mockStub.EXPECT().GetObject(ProposalStrategyKey(strategies[0].Module), gomock.Any()).SetArg(1, *strategies[0]).Return(true).AnyTimes()
339
340	res := g.GetProposalStrategy(strategies[0].Module)
341	assert.True(t, res.Ok)
342
343	res = g.GetProposalStrategy(strategies[0].Module)
344	assert.True(t, res.Ok)
345}
346
347func proposalStrategyPrepare(t *testing.T) (*GovStrategy, *mock_stub.MockStub, []*ProposalStrategy, [][]byte) {
348	mockCtl := gomock.NewController(t)
349	mockStub := mock_stub.NewMockStub(mockCtl)
350	g := &GovStrategy{
351		Stub: mockStub,
352	}
353
354	strategies := make([]*ProposalStrategy, 0)
355	strategiesData := make([][]byte, 0)
356	for i := 0; i < 7; i++ {
357		ps := &ProposalStrategy{
358			Module: mgrs[i],
359			Typ:    SimpleMajority,
360			Status: governance.GovernanceAvailable,
361			Extra:  "a == t",
362		}
363		strategies = append(strategies, ps)
364		data, err := json.Marshal(ps)
365		assert.Nil(t, err)
366		strategiesData = append(strategiesData, data)
367	}
368
369	for i := 0; i < 7; i++ {
370		ps := &ProposalStrategy{
371			Module: mgrs[i],
372			Typ:    ZeroPermission,
373			Status: governance.GovernanceUpdating,
374			Extra:  "",
375		}
376		strategies = append(strategies, ps)
377
378		data, err := json.Marshal(ps)
379		assert.Nil(t, err)
380		strategiesData = append(strategiesData, data)
381	}
382
383	ps := &ProposalStrategy{
384		Module: mgrs[0],
385		Typ:    SimpleMajority,
386		Status: governance.GovernanceAvailable,
387		Extra:  "a==5",
388	}
389	strategies = append(strategies, ps)
390
391	data, err := json.Marshal(ps)
392	assert.Nil(t, err)
393	strategiesData = append(strategiesData, data)
394
395	return g, mockStub, strategies, strategiesData
396}
397
Full Screen

ocmagenthandler_secret_test.go

Source: ocmagenthandler_secret_test.go Github

copy
1package ocmagenthandler
2
3import (
4	"bytes"
5	"context"
6	"fmt"
7	"reflect"
8	"strings"
9
10	"github.com/golang/mock/gomock"
11
12	corev1 "k8s.io/api/core/v1"
13	k8serrs "k8s.io/apimachinery/pkg/api/errors"
14	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
15	"k8s.io/apimachinery/pkg/runtime/schema"
16	"k8s.io/apimachinery/pkg/types"
17	"sigs.k8s.io/controller-runtime/pkg/client"
18
19	ocmagentv1alpha1 "github.com/openshift/ocm-agent-operator/pkg/apis/ocmagent/v1alpha1"
20	oahconst "github.com/openshift/ocm-agent-operator/pkg/consts/ocmagenthandler"
21	testconst "github.com/openshift/ocm-agent-operator/pkg/consts/test/init"
22	"github.com/openshift/ocm-agent-operator/pkg/localmetrics"
23	clientmocks "github.com/openshift/ocm-agent-operator/pkg/util/test/generated/mocks/client"
24
25	"github.com/prometheus/client_golang/prometheus/testutil"
26
27	. "github.com/onsi/ginkgo"
28	. "github.com/onsi/gomega"
29)
30
31var _ = Describe("OCM Agent Access Token Secret Handler", func() {
32
33	const (
34		testAccessTokenValue = "dGhpcyBpcyBhIHRlc3QgdmFsdWU=" // "this is a test value"
35	)
36
37	var (
38		mockClient *clientmocks.MockClient
39		mockCtrl   *gomock.Controller
40
41		testOcmAgent                  ocmagentv1alpha1.OcmAgent
42		testOcmAgentHandler           ocmAgentHandler
43		testOcmAccessTokenSecretValue []byte
44		testClusterPullSecretValue    []byte
45		testPullSecret                corev1.Secret
46	)
47
48	BeforeEach(func() {
49		mockCtrl = gomock.NewController(GinkgoT())
50		mockClient = clientmocks.NewMockClient(mockCtrl)
51		testOcmAgent = testconst.TestOCMAgent
52		testOcmAgentHandler = ocmAgentHandler{
53			Client: mockClient,
54			Scheme: testconst.Scheme,
55			Log:    testconst.Logger,
56			Ctx:    testconst.Context,
57		}
58		testClusterPullSecretValue = []byte(fmt.Sprintf(`{
59			"auths": {
60				"cloud.openshift.com": {
61					"auth": "%s",
62					"email": "[email protected]"
63				}
64			}
65		}`, testAccessTokenValue))
66		testOcmAccessTokenSecretValue = []byte(testAccessTokenValue)
67		pullSecretNamespacedName := oahconst.PullSecretNamespacedName
68		testPullSecret = corev1.Secret{
69			ObjectMeta: metav1.ObjectMeta{
70				Name:      pullSecretNamespacedName.Name,
71				Namespace: pullSecretNamespacedName.Namespace,
72			},
73			Data: map[string][]byte{
74				oahconst.PullSecretKey: testClusterPullSecretValue,
75			},
76		}
77	})
78
79	Context("When building an OCM Agent Access Token Secret", func() {
80		It("Sets a correct name", func() {
81			cm := buildOCMAgentAccessTokenSecret(testOcmAccessTokenSecretValue, testOcmAgent)
82			Expect(cm.Data).Should(HaveKey(oahconst.OCMAgentAccessTokenSecretKey))
83			Expect(bytes.Compare(cm.Data[oahconst.OCMAgentAccessTokenSecretKey], testOcmAccessTokenSecretValue)).To(BeZero())
84			Expect(cm.Name).To(Equal(testOcmAgent.Spec.TokenSecret))
85		})
86	})
87
88	Context("Managing the OCM Agent Secret", func() {
89		var testSecret corev1.Secret
90		var testNamespacedName types.NamespacedName
91		BeforeEach(func() {
92			testNamespacedName = oahconst.BuildNamespacedName(testOcmAgent.Spec.TokenSecret)
93			testSecret = buildOCMAgentAccessTokenSecret(testOcmAccessTokenSecretValue, testOcmAgent)
94		})
95		When("the OCM Agent secret already exists", func() {
96			When("the secret differs from what is expected", func() {
97				BeforeEach(func() {
98					testSecret.Data = map[string][]byte{"fake": []byte("not the right value")}
99				})
100				It("updates the secret", func() {
101					goldenSecret := buildOCMAgentAccessTokenSecret(testOcmAccessTokenSecretValue, testOcmAgent)
102					gomock.InOrder(
103						mockClient.EXPECT().Get(gomock.Any(), oahconst.PullSecretNamespacedName, gomock.Any()).Times(1).SetArg(2, testPullSecret),
104						mockClient.EXPECT().Get(gomock.Any(), testNamespacedName, gomock.Any()).Times(1).SetArg(2, testSecret),
105						mockClient.EXPECT().Update(gomock.Any(), gomock.Any()).Times(1).DoAndReturn(
106							func(ctx context.Context, d *corev1.Secret, opts ...client.UpdateOptions) error {
107								Expect(d.Data).Should(HaveKey(oahconst.OCMAgentAccessTokenSecretKey))
108								Expect(bytes.Compare(d.Data[oahconst.OCMAgentAccessTokenSecretKey], goldenSecret.Data[oahconst.OCMAgentAccessTokenSecretKey])).To(BeZero())
109								return nil
110							}),
111					)
112					err := testOcmAgentHandler.ensureAccessTokenSecret(testOcmAgent)
113					Expect(err).To(BeNil())
114				})
115			})
116			When("the secret matches what is expected", func() {
117				It("does not update the secret", func() {
118					gomock.InOrder(
119						mockClient.EXPECT().Get(gomock.Any(), oahconst.PullSecretNamespacedName, gomock.Any()).Times(1).SetArg(2, testPullSecret),
120						mockClient.EXPECT().Get(gomock.Any(), testNamespacedName, gomock.Any()).Times(1).SetArg(2, testSecret),
121					)
122					err := testOcmAgentHandler.ensureAccessTokenSecret(testOcmAgent)
123					Expect(err).To(BeNil())
124				})
125			})
126		})
127		When("the OCM Agent secret does not already exist", func() {
128			It("creates the secret", func() {
129				notFound := k8serrs.NewNotFound(schema.GroupResource{}, testSecret.Name)
130				gomock.InOrder(
131					mockClient.EXPECT().Get(gomock.Any(), oahconst.PullSecretNamespacedName, gomock.Any()).Times(1).SetArg(2, testPullSecret),
132					mockClient.EXPECT().Get(gomock.Any(), testNamespacedName, gomock.Any()).Times(1).Return(notFound),
133					mockClient.EXPECT().Create(gomock.Any(), gomock.Any()).DoAndReturn(
134						func(ctx context.Context, d *corev1.Secret, opts ...client.CreateOptions) error {
135							Expect(reflect.DeepEqual(d.Data, testSecret.Data)).To(BeTrue())
136							Expect(d.ObjectMeta.OwnerReferences[0].Kind).To(Equal("OcmAgent"))
137							Expect(*d.ObjectMeta.OwnerReferences[0].BlockOwnerDeletion).To(BeTrue())
138							Expect(*d.ObjectMeta.OwnerReferences[0].Controller).To(BeTrue())
139							return nil
140						}),
141				)
142				err := testOcmAgentHandler.ensureAccessTokenSecret(testOcmAgent)
143				Expect(err).To(BeNil())
144			})
145		})
146		When("the access token secret should be removed", func() {
147			When("the secret is already removed", func() {
148				It("does nothing", func() {
149					notFound := k8serrs.NewNotFound(schema.GroupResource{}, testSecret.Name)
150					gomock.InOrder(
151						mockClient.EXPECT().Get(gomock.Any(), gomock.Any(), gomock.Any()).Times(1).Return(notFound),
152					)
153					err := testOcmAgentHandler.ensureAccessTokenSecretDeleted(testOcmAgent)
154					Expect(err).To(BeNil())
155				})
156			})
157			When("the configmap exists on the cluster", func() {
158				It("removes the configmap", func() {
159					gomock.InOrder(
160						mockClient.EXPECT().Get(gomock.Any(), gomock.Any(), gomock.Any()).Times(1).SetArg(2, testSecret),
161						mockClient.EXPECT().Delete(gomock.Any(), &testSecret),
162					)
163					err := testOcmAgentHandler.ensureAccessTokenSecretDeleted(testOcmAgent)
164					Expect(err).To(BeNil())
165				})
166			})
167		})
168		When("the pull secret can't be found", func() {
169			BeforeEach(func() {
170				delete(testPullSecret.Data, oahconst.PullSecretKey)
171			})
172			It("returns an error and sets the metric", func() {
173				gomock.InOrder(
174					mockClient.EXPECT().Get(gomock.Any(), gomock.Any(), gomock.Any()).Times(1).SetArg(2, testSecret),
175				)
176				err := testOcmAgentHandler.ensureAccessTokenSecret(testOcmAgent)
177				Expect(err).NotTo(BeNil())
178				expectedMetric := `
179# HELP ocm_agent_operator_pull_secret_invalid Failed to obtain a valid pull secret
180# TYPE ocm_agent_operator_pull_secret_invalid gauge
181ocm_agent_operator_pull_secret_invalid{ocmagent_name="test-ocm-agent"} 1
182`
183				err = testutil.CollectAndCompare(localmetrics.MetricPullSecretInvalid, strings.NewReader(expectedMetric))
184				Expect(err).To(BeNil())
185			})
186		})
187		When("the pull secret can be found", func() {
188			It("sets the correct metric", func() {
189				gomock.InOrder(
190					mockClient.EXPECT().Get(gomock.Any(), oahconst.PullSecretNamespacedName, gomock.Any()).Times(1).SetArg(2, testPullSecret),
191					mockClient.EXPECT().Get(gomock.Any(), testNamespacedName, gomock.Any()).Times(1).SetArg(2, testSecret),
192				)
193				err := testOcmAgentHandler.ensureAccessTokenSecret(testOcmAgent)
194				Expect(err).To(BeNil())
195				expectedMetric := `
196# HELP ocm_agent_operator_pull_secret_invalid Failed to obtain a valid pull secret
197# TYPE ocm_agent_operator_pull_secret_invalid gauge
198ocm_agent_operator_pull_secret_invalid{ocmagent_name="test-ocm-agent"} 0
199`
200				err = testutil.CollectAndCompare(localmetrics.MetricPullSecretInvalid, strings.NewReader(expectedMetric))
201				Expect(err).To(BeNil())
202			})
203		})
204	})
205})
206
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)