How to use finish method of gomock Package

Best Mock code snippet using gomock.finish

ut_router_test.go

Source:ut_router_test.go Github

copy

Full Screen

1/*2Copyright 2018 ZTE Corporation. All rights reserved.3Licensed under the Apache License, Version 2.0 (the "License");4you may not use this file except in compliance with the License.5You may obtain a copy of the License at6http://www.apache.org/licenses/LICENSE-2.07Unless required by applicable law or agreed to in writing, software8distributed under the License is distributed on an "AS IS" BASIS,9WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.10See the License for the specific language governing permissions and11limitations under the License.12*/13package test14import (15	"errors"16	"testing"17	"github.com/coreos/etcd/client"18	"github.com/golang/mock/gomock"19	. "github.com/smartystreets/goconvey/convey"20	"github.com/ZTE/Knitter/knitter-manager/iaas"21	"github.com/ZTE/Knitter/knitter-manager/public"22	_ "github.com/ZTE/Knitter/knitter-manager/routers"23	"github.com/ZTE/Knitter/pkg/iaas-accessor"24	"github.com/golang/gostub"25)26func TestCreateRouterErrNotCfgIaaS(t *testing.T) {27	cfgMock := gomock.NewController(t)28	defer cfgMock.Finish()29	mockDB := NewMockDbAccessor(cfgMock)30	common.SetDataBase(mockDB)31	stubs := gostub.StubFunc(&iaas.GetIaaS, nil)32	defer stubs.Reset()33	MockPaasAdminCheck(mockDB)34	cfg := string(`{"router":{"name":"test-create-router"}}`)35	resp := CreateRouter(cfg)36	Convey("TestCreateRouterErrNotCfgIaaS\n", t, func() {37		So(resp.Code, ShouldEqual, 401)38	})39}40func TestCreateRouterErr403(t *testing.T) {41	cfgMock := gomock.NewController(t)42	defer cfgMock.Finish()43	mockDB := NewMockDbAccessor(cfgMock)44	mockIaaS := NewMockIaaS(cfgMock)45	common.SetDataBase(mockDB)46	stubs := gostub.StubFunc(&iaas.GetIaaS, mockIaaS)47	defer stubs.Reset()48	MockPaasAdminCheck(mockDB)49	cfg := string(`{"router":{"name":"test-create-router"}`)50	resp := CreateRouter(cfg)51	Convey("TestCreateNetworkErrNotCfgIaaS\n", t, func() {52		So(resp.Code, ShouldEqual, 403)53	})54}55func TestCreateRouterErr406A(t *testing.T) {56	cfgMock := gomock.NewController(t)57	defer cfgMock.Finish()58	mockDB := NewMockDbAccessor(cfgMock)59	mockIaaS := NewMockIaaS(cfgMock)60	common.SetDataBase(mockDB)61	stubs := gostub.StubFunc(&iaas.GetIaaS, mockIaaS)62	defer stubs.Reset()63	MockPaasAdminCheck(mockDB)64	mockIaaS.EXPECT().CreateRouter(gomock.Any(),65		gomock.Any()).Return("", errors.New("create-router-error"))66	cfg := string(`{"router":{"name":"test-create-router"}}`)67	resp := CreateRouter(cfg)68	Convey("TestCreateRouterErr406A\n", t, func() {69		So(resp.Code, ShouldEqual, 406)70	})71}72func TestCreateRouterErr406B(t *testing.T) {73	cfgMock := gomock.NewController(t)74	defer cfgMock.Finish()75	mockDB := NewMockDbAccessor(cfgMock)76	mockIaaS := NewMockIaaS(cfgMock)77	common.SetDataBase(mockDB)78	stubs := gostub.StubFunc(&iaas.GetIaaS, mockIaaS)79	defer stubs.Reset()80	MockPaasAdminCheck(mockDB)81	mockIaaS.EXPECT().CreateRouter(gomock.Any(),82		gomock.Any()).Return("router-uuid", nil)83	mockIaaS.EXPECT().GetRouter(gomock.Any()).Return(84		nil, errors.New("get-router-error"))85	cfg := string(`{"router":{"name":"test-create-router"}}`)86	resp := CreateRouter(cfg)87	Convey("TestCreateRouterErr406B\n", t, func() {88		So(resp.Code, ShouldEqual, 406)89	})90}91func TestCreateRouterErr406C(t *testing.T) {92	cfgMock := gomock.NewController(t)93	defer cfgMock.Finish()94	mockDB := NewMockDbAccessor(cfgMock)95	mockIaaS := NewMockIaaS(cfgMock)96	common.SetDataBase(mockDB)97	stubs := gostub.StubFunc(&iaas.GetIaaS, mockIaaS)98	defer stubs.Reset()99	MockPaasAdminCheck(mockDB)100	mockIaaS.EXPECT().CreateRouter(gomock.Any(),101		gomock.Any()).Return("router-uuid", nil)102	router := iaasaccessor.Router{Id: "router-uuid"}103	mockIaaS.EXPECT().GetRouter(gomock.Any()).Return(104		&router, nil)105	mockDB.EXPECT().SaveLeaf(gomock.Any(),106		gomock.Any()).Return(errors.New("error"))107	mockIaaS.EXPECT().DeleteRouter(gomock.Any()).Return(nil)108	cfg := string(`{"router":{"name":"test-create-router"}}`)109	resp := CreateRouter(cfg)110	Convey("TestCreateRouterErr406C\n", t, func() {111		So(resp.Code, ShouldEqual, 406)112	})113}114func TestCreateRouterOK(t *testing.T) {115	cfgMock := gomock.NewController(t)116	defer cfgMock.Finish()117	mockDB := NewMockDbAccessor(cfgMock)118	mockIaaS := NewMockIaaS(cfgMock)119	common.SetDataBase(mockDB)120	stubs := gostub.StubFunc(&iaas.GetIaaS, mockIaaS)121	defer stubs.Reset()122	MockPaasAdminCheck(mockDB)123	mockIaaS.EXPECT().CreateRouter(gomock.Any(),124		gomock.Any()).Return("router-uuid", nil)125	router := iaasaccessor.Router{Id: "router-uuid"}126	mockIaaS.EXPECT().GetRouter(gomock.Any()).Return(127		&router, nil)128	mockDB.EXPECT().SaveLeaf(gomock.Any(),129		gomock.Any()).Return(nil)130	cfg := string(`{"router":{"name":"test-create-router"}}`)131	resp := CreateRouter(cfg)132	Convey("TestCreateRouterOK\n", t, func() {133		So(resp.Code, ShouldEqual, 200)134	})135}136func TestDeleteRouterERR401(t *testing.T) {137	cfgMock := gomock.NewController(t)138	defer cfgMock.Finish()139	mockDB := NewMockDbAccessor(cfgMock)140	common.SetDataBase(mockDB)141	stubs := gostub.StubFunc(&iaas.GetIaaS, nil)142	defer stubs.Reset()143	MockPaasAdminCheck(mockDB)144	resp := DeleteRouter("the-uuid-of-router")145	Convey("TestDeleteRouterERR401\n", t, func() {146		So(resp.Code, ShouldEqual, 401)147	})148}149func TestDeleteRouterERR404(t *testing.T) {150	cfgMock := gomock.NewController(t)151	defer cfgMock.Finish()152	mockDB := NewMockDbAccessor(cfgMock)153	mockIaaS := NewMockIaaS(cfgMock)154	common.SetDataBase(mockDB)155	stubs := gostub.StubFunc(&iaas.GetIaaS, mockIaaS)156	defer stubs.Reset()157	MockPaasAdminCheck(mockDB)158	mockDB.EXPECT().ReadLeaf(gomock.Any()).Return(159		"", errors.New("read-router-return-error"))160	resp := DeleteRouter("the-uuid-of-router")161	Convey("TestDeleteRouterERR404\n", t, func() {162		So(resp.Code, ShouldEqual, 404)163	})164}165func TestDeleteRouter404A(t *testing.T) {166	cfgMock := gomock.NewController(t)167	defer cfgMock.Finish()168	mockDB := NewMockDbAccessor(cfgMock)169	mockIaaS := NewMockIaaS(cfgMock)170	common.SetDataBase(mockDB)171	stubs := gostub.StubFunc(&iaas.GetIaaS, mockIaaS)172	defer stubs.Reset()173	MockPaasAdminCheck(mockDB)174	mockDB.EXPECT().ReadLeaf(gomock.Any()).Return(175		"router-uuid", nil)176	mockIaaS.EXPECT().DeleteRouter(gomock.Any()).Return(177		errors.New("error"))178	resp := DeleteRouter("the-uuid-of-router")179	Convey("TestDeleteRouter404A\n", t, func() {180		So(resp.Code, ShouldEqual, 404)181	})182}183func TestDeleteRouter404B(t *testing.T) {184	cfgMock := gomock.NewController(t)185	defer cfgMock.Finish()186	mockDB := NewMockDbAccessor(cfgMock)187	mockIaaS := NewMockIaaS(cfgMock)188	common.SetDataBase(mockDB)189	stubs := gostub.StubFunc(&iaas.GetIaaS, mockIaaS)190	defer stubs.Reset()191	MockPaasAdminCheck(mockDB)192	mockDB.EXPECT().ReadLeaf(gomock.Any()).Return(193		"router-uuid", nil)194	mockIaaS.EXPECT().DeleteRouter(gomock.Any()).Return(nil)195	mockDB.EXPECT().DeleteLeaf(gomock.Any()).Return(196		errors.New("error"))197	resp := DeleteRouter("the-uuid-of-router")198	Convey("TestDeleteRouter404B\n", t, func() {199		So(resp.Code, ShouldEqual, 404)200	})201}202func TestDeleteRouter404C(t *testing.T) {203	cfgMock := gomock.NewController(t)204	defer cfgMock.Finish()205	mockDB := NewMockDbAccessor(cfgMock)206	mockIaaS := NewMockIaaS(cfgMock)207	common.SetDataBase(mockDB)208	stubs := gostub.StubFunc(&iaas.GetIaaS, mockIaaS)209	defer stubs.Reset()210	MockPaasAdminCheck(mockDB)211	mockDB.EXPECT().ReadLeaf(gomock.Any()).Return(212		"router-uuid", nil)213	mockIaaS.EXPECT().DeleteRouter(gomock.Any()).Return(nil)214	mockDB.EXPECT().DeleteLeaf(gomock.Any()).Return(nil)215	mockDB.EXPECT().DeleteDir(gomock.Any()).Return(216		errors.New("error"))217	resp := DeleteRouter("the-uuid-of-router")218	Convey("TestDeleteRouter404C\n", t, func() {219		So(resp.Code, ShouldEqual, 404)220	})221}222func TestDeleteRouterOK(t *testing.T) {223	cfgMock := gomock.NewController(t)224	defer cfgMock.Finish()225	mockDB := NewMockDbAccessor(cfgMock)226	mockIaaS := NewMockIaaS(cfgMock)227	common.SetDataBase(mockDB)228	stubs := gostub.StubFunc(&iaas.GetIaaS, mockIaaS)229	defer stubs.Reset()230	MockPaasAdminCheck(mockDB)231	mockDB.EXPECT().ReadLeaf(gomock.Any()).Return(232		"router-uuid", nil)233	mockIaaS.EXPECT().DeleteRouter(gomock.Any()).Return(nil)234	mockDB.EXPECT().DeleteLeaf(gomock.Any()).Return(nil)235	mockDB.EXPECT().DeleteDir(gomock.Any()).Return(nil)236	resp := DeleteRouter("the-uuid-of-router")237	Convey("TestDeleteRouterOK\n", t, func() {238		So(resp.Code, ShouldEqual, 200)239	})240}241func TestGetRouterERR401(t *testing.T) {242	cfgMock := gomock.NewController(t)243	defer cfgMock.Finish()244	mockDB := NewMockDbAccessor(cfgMock)245	common.SetDataBase(mockDB)246	stubs := gostub.StubFunc(&iaas.GetIaaS, nil)247	defer stubs.Reset()248	MockPaasAdminCheck(mockDB)249	resp := GetRouter("the-uuid-of-router")250	Convey("TestGetRouterERR401\n", t, func() {251		So(resp.Code, ShouldEqual, 401)252	})253}254func TestGetRouterERR404B(t *testing.T) {255	cfgMock := gomock.NewController(t)256	defer cfgMock.Finish()257	mockDB := NewMockDbAccessor(cfgMock)258	mockIaaS := NewMockIaaS(cfgMock)259	common.SetDataBase(mockDB)260	stubs := gostub.StubFunc(&iaas.GetIaaS, mockIaaS)261	defer stubs.Reset()262	MockPaasAdminCheck(mockDB)263	mockDB.EXPECT().ReadLeaf(gomock.Any()).Return(264		"", errors.New("read-router-from-etcd-error"))265	resp := GetRouter("the-uuid-of-router")266	Convey("TestGetRouterERR404B\n", t, func() {267		So(resp.Code, ShouldEqual, 404)268	})269}270func TestGetRouterOK(t *testing.T) {271	cfgMock := gomock.NewController(t)272	defer cfgMock.Finish()273	mockDB := NewMockDbAccessor(cfgMock)274	mockIaaS := NewMockIaaS(cfgMock)275	common.SetDataBase(mockDB)276	stubs := gostub.StubFunc(&iaas.GetIaaS, mockIaaS)277	defer stubs.Reset()278	MockPaasAdminCheck(mockDB)279	router := string(`{280    "router": {281        "name": "router_show",282        "id": "9a4bf247-0cdd-4649-a5aa-4255856d3da2"283    }}`)284	mockDB.EXPECT().ReadLeaf(gomock.Any()).Return(285		router, nil)286	resp := GetRouter("the-uuid-of-router")287	Convey("TestGetRouterOK\n", t, func() {288		So(resp.Code, ShouldEqual, 200)289	})290}291var Config string = `{292		"router":{293			"name":"auto-test-create-router-should-be-delete"294			}295		}`296var errCfg string = `{297		"router":{298			"name":"auto-test-create-router-should-be-delete"299		}`300func TestUpdateRouterERR401(t *testing.T) {301	cfgMock := gomock.NewController(t)302	defer cfgMock.Finish()303	mockDB := NewMockDbAccessor(cfgMock)304	common.SetDataBase(mockDB)305	stubs := gostub.StubFunc(&iaas.GetIaaS, nil)306	defer stubs.Reset()307	MockPaasAdminCheck(mockDB)308	resp := UpdateRouter("the-uuid-of-router", Config)309	Convey("TestGetRouterERR401\n", t, func() {310		So(resp.Code, ShouldEqual, 401)311	})312}313func TestUpdateRouterERR403(t *testing.T) {314	cfgMock := gomock.NewController(t)315	defer cfgMock.Finish()316	mockDB := NewMockDbAccessor(cfgMock)317	mockIaaS := NewMockIaaS(cfgMock)318	common.SetDataBase(mockDB)319	stubs := gostub.StubFunc(&iaas.GetIaaS, mockIaaS)320	defer stubs.Reset()321	MockPaasAdminCheck(mockDB)322	resp := UpdateRouter("the-uuid-of-router", errCfg)323	Convey("TestUpdateRouterERR403\n", t, func() {324		So(resp.Code, ShouldEqual, 403)325	})326}327func TestUpdateRouterERR406A(t *testing.T) {328	cfgMock := gomock.NewController(t)329	defer cfgMock.Finish()330	mockDB := NewMockDbAccessor(cfgMock)331	mockIaaS := NewMockIaaS(cfgMock)332	common.SetDataBase(mockDB)333	stubs := gostub.StubFunc(&iaas.GetIaaS, mockIaaS)334	defer stubs.Reset()335	MockPaasAdminCheck(mockDB)336	mockIaaS.EXPECT().UpdateRouter(gomock.Any(),337		gomock.Any(), gomock.Any()).Return(errors.New("error"))338	resp := UpdateRouter("the-uuid-of-router", Config)339	Convey("TestUpdateRouterERR406A\n", t, func() {340		So(resp.Code, ShouldEqual, 406)341	})342}343func TestUpdateRouterERR406B(t *testing.T) {344	cfgMock := gomock.NewController(t)345	defer cfgMock.Finish()346	mockDB := NewMockDbAccessor(cfgMock)347	mockIaaS := NewMockIaaS(cfgMock)348	common.SetDataBase(mockDB)349	stubs := gostub.StubFunc(&iaas.GetIaaS, mockIaaS)350	defer stubs.Reset()351	MockPaasAdminCheck(mockDB)352	mockIaaS.EXPECT().UpdateRouter(gomock.Any(),353		gomock.Any(), gomock.Any()).Return(nil)354	mockIaaS.EXPECT().GetRouter(gomock.Any()).Return(355		nil, errors.New("error"))356	resp := UpdateRouter("the-uuid-of-router", Config)357	Convey("TestUpdateRouterERR406B\n", t, func() {358		So(resp.Code, ShouldEqual, 406)359	})360}361func TestUpdateRouterERR406C(t *testing.T) {362	cfgMock := gomock.NewController(t)363	defer cfgMock.Finish()364	mockDB := NewMockDbAccessor(cfgMock)365	mockIaaS := NewMockIaaS(cfgMock)366	common.SetDataBase(mockDB)367	stubs := gostub.StubFunc(&iaas.GetIaaS, mockIaaS)368	defer stubs.Reset()369	MockPaasAdminCheck(mockDB)370	createRouter := iaasaccessor.Router{Id: "router-uuid", Name: "name-router"}371	mockIaaS.EXPECT().UpdateRouter(gomock.Any(),372		gomock.Any(), gomock.Any()).Return(nil)373	mockIaaS.EXPECT().GetRouter(gomock.Any()).Return(374		&createRouter, nil)375	mockDB.EXPECT().SaveLeaf(gomock.Any(),376		gomock.Any()).Return(errors.New("error"))377	resp := UpdateRouter("the-uuid-of-router", Config)378	Convey("TestUpdateRouterERR406B\n", t, func() {379		So(resp.Code, ShouldEqual, 406)380	})381}382func TestUpdateRouterOK(t *testing.T) {383	cfgMock := gomock.NewController(t)384	defer cfgMock.Finish()385	mockDB := NewMockDbAccessor(cfgMock)386	mockIaaS := NewMockIaaS(cfgMock)387	common.SetDataBase(mockDB)388	stubs := gostub.StubFunc(&iaas.GetIaaS, mockIaaS)389	defer stubs.Reset()390	MockPaasAdminCheck(mockDB)391	createRouter := iaasaccessor.Router{Id: "router-uuid", Name: "name-router"}392	mockIaaS.EXPECT().UpdateRouter(gomock.Any(),393		gomock.Any(), gomock.Any()).Return(nil)394	mockIaaS.EXPECT().GetRouter(gomock.Any()).Return(395		&createRouter, nil)396	mockDB.EXPECT().SaveLeaf(gomock.Any(),397		gomock.Any()).Return(nil)398	resp := UpdateRouter("the-uuid-of-router", Config)399	Convey("TestUpdateRouterOK\n", t, func() {400		So(resp.Code, ShouldEqual, 200)401	})402}403func TestGetAllRouterERR401(t *testing.T) {404	cfgMock := gomock.NewController(t)405	defer cfgMock.Finish()406	mockDB := NewMockDbAccessor(cfgMock)407	common.SetDataBase(mockDB)408	stubs := gostub.StubFunc(&iaas.GetIaaS, nil)409	defer stubs.Reset()410	MockPaasAdminCheck(mockDB)411	resp := GetAllRouter()412	Convey("TestGetAllRouterERR401\n", t, func() {413		So(resp.Code, ShouldEqual, 401)414	})415}416func TestGetAllRouterOK1(t *testing.T) {417	cfgMock := gomock.NewController(t)418	defer cfgMock.Finish()419	mockDB := NewMockDbAccessor(cfgMock)420	mockIaaS := NewMockIaaS(cfgMock)421	common.SetDataBase(mockDB)422	stubs := gostub.StubFunc(&iaas.GetIaaS, mockIaaS)423	defer stubs.Reset()424	MockPaasAdminCheck(mockDB)425	mockDB.EXPECT().ReadDir(gomock.Any()).Return(nil,426		errors.New("read-dir-error"))427	resp := GetAllRouter()428	Convey("TestGetAllRouterOK1\n", t, func() {429		So(resp.Code, ShouldEqual, 200)430	})431}432func TestGetAllRouterOK2(t *testing.T) {433	cfgMock := gomock.NewController(t)434	defer cfgMock.Finish()435	mockDB := NewMockDbAccessor(cfgMock)436	mockIaaS := NewMockIaaS(cfgMock)437	common.SetDataBase(mockDB)438	stubs := gostub.StubFunc(&iaas.GetIaaS, mockIaaS)439	defer stubs.Reset()440	MockPaasAdminCheck(mockDB)441	mockDB.EXPECT().ReadDir(gomock.Any()).Return(nil, nil)442	resp := GetAllRouter()443	Convey("TestGetAllRouterOK2\n", t, func() {444		So(resp.Code, ShouldEqual, 200)445	})446}447func TestGetAllRouterOK3(t *testing.T) {448	cfgMock := gomock.NewController(t)449	defer cfgMock.Finish()450	mockDB := NewMockDbAccessor(cfgMock)451	mockIaaS := NewMockIaaS(cfgMock)452	common.SetDataBase(mockDB)453	stubs := gostub.StubFunc(&iaas.GetIaaS, mockIaaS)454	defer stubs.Reset()455	MockPaasAdminCheck(mockDB)456	router := string(`{457    "router": {458        "name": "network_show",459        "id": "9a4bf247-0cdd-4649-a5aa-4255856d3da2"460    }}`)461	var list1 []*client.Node462	node := client.Node{Key: "network-uuid", Value: "network-info"}463	list1 = append(list1, &node)464	list1 = append(list1, &node)465	mockDB.EXPECT().ReadDir(gomock.Any()).Return(list1, nil)466	mockDB.EXPECT().ReadLeaf(gomock.Any()).Return(router, nil)467	mockDB.EXPECT().ReadLeaf(gomock.Any()).Return("",468		errors.New("read-leaf-error"))469	resp := GetAllRouter()470	Convey("TestGetAllRouterOK3\n", t, func() {471		So(resp.Code, ShouldEqual, 200)472	})473}474func TestAttachERR401(t *testing.T) {475	cfgMock := gomock.NewController(t)476	defer cfgMock.Finish()477	mockDB := NewMockDbAccessor(cfgMock)478	common.SetDataBase(mockDB)479	stubs := gostub.StubFunc(&iaas.GetIaaS, nil)480	defer stubs.Reset()481	MockPaasAdminCheck(mockDB)482	resp := AttachRouter("uuid-for-routet", "uuid-for-network")483	Convey("TestAttachERR401\n", t, func() {484		So(resp.Code, ShouldEqual, 401)485	})486}487func TestAttachERR403(t *testing.T) {488	cfgMock := gomock.NewController(t)489	defer cfgMock.Finish()490	mockDB := NewMockDbAccessor(cfgMock)491	mockIaaS := NewMockIaaS(cfgMock)492	common.SetDataBase(mockDB)493	stubs := gostub.StubFunc(&iaas.GetIaaS, mockIaaS)494	defer stubs.Reset()495	MockPaasAdminCheck(mockDB)496	resp := AttachRouter403("uuid-for-routet", "uuid-for-network")497	Convey("TestAttachERR403\n", t, func() {498		So(resp.Code, ShouldEqual, 403)499	})500}501func TestAttachERR406A(t *testing.T) {502	cfgMock := gomock.NewController(t)503	defer cfgMock.Finish()504	mockDB := NewMockDbAccessor(cfgMock)505	mockIaaS := NewMockIaaS(cfgMock)506	common.SetDataBase(mockDB)507	stubs := gostub.StubFunc(&iaas.GetIaaS, mockIaaS)508	defer stubs.Reset()509	MockPaasAdminCheck(mockDB)510	mockDB.EXPECT().ReadLeaf(gomock.Any()).Return(511		"", errors.New("error"))512	resp := AttachRouter("uuid-for-routet", "uuid-for-network")513	Convey("TestAttachERR401\n", t, func() {514		So(resp.Code, ShouldEqual, 406)515	})516}517func TestAttachERR406B(t *testing.T) {518	cfgMock := gomock.NewController(t)519	defer cfgMock.Finish()520	mockDB := NewMockDbAccessor(cfgMock)521	mockIaaS := NewMockIaaS(cfgMock)522	common.SetDataBase(mockDB)523	stubs := gostub.StubFunc(&iaas.GetIaaS, mockIaaS)524	defer stubs.Reset()525	MockPaasAdminCheck(mockDB)526	netInfo := string(`{527    "network": {528        "cidr": "123.124.125.0/24",529        "gateway": "123.124.125.1",530        "name": "network_show",531        "network_id": "9a4bf247-0cdd-4649-a5aa-4255856d3da2"532    }}`)533	mockDB.EXPECT().ReadLeaf(gomock.Any()).Return(534		netInfo, nil)535	mockIaaS.EXPECT().AttachNetToRouter(536		gomock.Any(), gomock.Any()).Return("", errors.New("error"))537	resp := AttachRouter("uuid-for-routet", "uuid-for-network")538	Convey("TestAttachERR401\n", t, func() {539		So(resp.Code, ShouldEqual, 406)540	})541}542func TestAttachERR406C(t *testing.T) {543	cfgMock := gomock.NewController(t)544	defer cfgMock.Finish()545	mockDB := NewMockDbAccessor(cfgMock)546	mockIaaS := NewMockIaaS(cfgMock)547	common.SetDataBase(mockDB)548	stubs := gostub.StubFunc(&iaas.GetIaaS, mockIaaS)549	defer stubs.Reset()550	MockPaasAdminCheck(mockDB)551	netInfo := string(`{552    "network": {553        "cidr": "123.124.125.0/24",554        "gateway": "123.124.125.1",555        "name": "network_show",556        "network_id": "9a4bf247-0cdd-4649-a5aa-4255856d3da2"557    }}`)558	mockDB.EXPECT().ReadLeaf(gomock.Any()).Return(559		netInfo, nil)560	mockIaaS.EXPECT().AttachNetToRouter(gomock.Any(),561		gomock.Any()).Return("uuid-for-port", nil)562	mockDB.EXPECT().SaveLeaf(gomock.Any(),563		gomock.Any()).Return(nil)564	mockDB.EXPECT().SaveLeaf(gomock.Any(),565		gomock.Any()).Return(errors.New("error"))566	resp := AttachRouter("uuid-for-routet", "uuid-for-network")567	Convey("TestAttachERR401\n", t, func() {568		So(resp.Code, ShouldEqual, 406)569	})570}571/*572func TestAttachERR406D(t *testing.T) {573	cfgMock := gomock.NewController(t)574	defer cfgMock.Finish()575	mockDB := NewMockDbAccessor(cfgMock)576	mockIaaS := NewMockIaaS(cfgMock)577	common.SetDataBase(mockDB)578	common.SetIaaS(mockIaaS)579	netInfo := string(`{580    "network": {581        "cidr": "123.124.125.0/24",582        "gateway": "123.124.125.1",583        "name": "network_show",584        "network_id": "9a4bf247-0cdd-4649-a5aa-4255856d3da2"585    }}`)586	mockDB.EXPECT().ReadLeaf(gomock.Any()).Return(587		netInfo, nil)588	mockIaaS.EXPECT().AttachNetToRouter(gomock.Any(),589		gomock.Any()).Return("uuid-for-port",nil)590	mockDB.EXPECT().SaveLeaf(gomock.Any(),gomock.Any()).Return(nil)591	mockDB.EXPECT().SaveLeaf(gomock.Any(),gomock.Any()).Return(nil)592	mockDB.EXPECT().SaveLeaf(gomock.Any(),gomock.Any()).Return(593		errors.New("error"))594	resp := AttachRouter("uuid-for-routet","uuid-for-network")595	Convey("TestAttachERR406C\n", t, func() {596		So(resp.Code, ShouldEqual, 406)597	})598}599func TestAttachERR406E(t *testing.T) {600	cfgMock := gomock.NewController(t)601	defer cfgMock.Finish()602	mockDB := NewMockDbAccessor(cfgMock)603	mockIaaS := NewMockIaaS(cfgMock)604	common.SetDataBase(mockDB)605	common.SetIaaS(mockIaaS)606	netInfo := string(`{607    "network": {608        "cidr": "123.124.125.0/24",609        "gateway": "123.124.125.1",610        "name": "network_show",611        "network_id": "9a4bf247-0cdd-4649-a5aa-4255856d3da2"612    }}`)613	mockDB.EXPECT().ReadLeaf(gomock.Any()).Return(614		netInfo, nil)615	mockIaaS.EXPECT().AttachNetToRouter(gomock.Any(),616		gomock.Any()).Return("uuid-for-port",nil)617	mockDB.EXPECT().SaveLeaf(gomock.Any(),gomock.Any()).Return(nil)618	mockDB.EXPECT().SaveLeaf(gomock.Any(),gomock.Any()).Return(nil)619	mockDB.EXPECT().SaveLeaf(gomock.Any(),gomock.Any()).Return(nil)620	mockDB.EXPECT().SaveLeaf(gomock.Any(),gomock.Any()).Return(nil)621	mockDB.EXPECT().SaveLeaf(gomock.Any(),622		gomock.Any()).Return(errors.New("error"))623	resp := AttachRouter("uuid-for-routet","uuid-for-network")624	Convey("TestAttachERR406C\n", t, func() {625		So(resp.Code, ShouldEqual, 406)626	})627}628*/629func TestAttachOK(t *testing.T) {630	cfgMock := gomock.NewController(t)631	defer cfgMock.Finish()632	mockDB := NewMockDbAccessor(cfgMock)633	mockIaaS := NewMockIaaS(cfgMock)634	common.SetDataBase(mockDB)635	stubs := gostub.StubFunc(&iaas.GetIaaS, mockIaaS)636	defer stubs.Reset()637	MockPaasAdminCheck(mockDB)638	netInfo := string(`{639    "network": {640        "cidr": "123.124.125.0/24",641        "gateway": "123.124.125.1",642        "name": "network_show",643        "network_id": "9a4bf247-0cdd-4649-a5aa-4255856d3da2"644    }}`)645	mockDB.EXPECT().ReadLeaf(gomock.Any()).Return(646		netInfo, nil)647	mockIaaS.EXPECT().AttachNetToRouter(gomock.Any(),648		gomock.Any()).Return("uuid-for-port", nil)649	mockDB.EXPECT().SaveLeaf(gomock.Any(),650		gomock.Any()).Return(nil)651	mockDB.EXPECT().SaveLeaf(gomock.Any(),652		gomock.Any()).Return(nil)653	mockDB.EXPECT().SaveLeaf(gomock.Any(),654		gomock.Any()).Return(nil)655	mockDB.EXPECT().SaveLeaf(gomock.Any(),656		gomock.Any()).Return(nil)657	mockDB.EXPECT().SaveLeaf(gomock.Any(),658		gomock.Any()).Return(nil)659	mockDB.EXPECT().SaveLeaf(gomock.Any(),660		gomock.Any()).Return(nil)661	resp := AttachRouter("uuid-for-routet", "uuid-for-network")662	Convey("TestAttachERR406D\n", t, func() {663		So(resp.Code, ShouldEqual, 200)664	})665}666func TestDetachERR401(t *testing.T) {667	cfgMock := gomock.NewController(t)668	defer cfgMock.Finish()669	mockDB := NewMockDbAccessor(cfgMock)670	common.SetDataBase(mockDB)671	stubs := gostub.StubFunc(&iaas.GetIaaS, nil)672	defer stubs.Reset()673	MockPaasAdminCheck(mockDB)674	resp := DetachRouter("uuid-for-routet", "uuid-for-network")675	Convey("TestDetachERR401\n", t, func() {676		So(resp.Code, ShouldEqual, 401)677	})678}679func TestDetachERR403(t *testing.T) {680	cfgMock := gomock.NewController(t)681	defer cfgMock.Finish()682	mockDB := NewMockDbAccessor(cfgMock)683	mockIaaS := NewMockIaaS(cfgMock)684	common.SetDataBase(mockDB)685	stubs := gostub.StubFunc(&iaas.GetIaaS, mockIaaS)686	defer stubs.Reset()687	MockPaasAdminCheck(mockDB)688	resp := DetachRouter403("uuid-for-routet", "uuid-for-network")689	Convey("TestDetachERR403\n", t, func() {690		So(resp.Code, ShouldEqual, 403)691	})692}693func TestDetachERR406A(t *testing.T) {694	cfgMock := gomock.NewController(t)695	defer cfgMock.Finish()696	mockDB := NewMockDbAccessor(cfgMock)697	mockIaaS := NewMockIaaS(cfgMock)698	common.SetDataBase(mockDB)699	stubs := gostub.StubFunc(&iaas.GetIaaS, mockIaaS)700	defer stubs.Reset()701	MockPaasAdminCheck(mockDB)702	mockDB.EXPECT().ReadLeaf(gomock.Any()).Return(703		"", errors.New("error"))704	resp := DetachRouter("uuid-for-routet", "uuid-for-network")705	Convey("TestAttachERR401\n", t, func() {706		So(resp.Code, ShouldEqual, 406)707	})708}709func TestDetachERR406B(t *testing.T) {710	cfgMock := gomock.NewController(t)711	defer cfgMock.Finish()712	mockDB := NewMockDbAccessor(cfgMock)713	mockIaaS := NewMockIaaS(cfgMock)714	common.SetDataBase(mockDB)715	stubs := gostub.StubFunc(&iaas.GetIaaS, mockIaaS)716	defer stubs.Reset()717	MockPaasAdminCheck(mockDB)718	netInfo := string(`{719    "network": {720        "cidr": "123.124.125.0/24",721        "gateway": "123.124.125.1",722        "name": "network_show",723        "network_id": "9a4bf247-0cdd-4649-a5aa-4255856d3da2"724    }}`)725	mockDB.EXPECT().ReadLeaf(gomock.Any()).Return(726		netInfo, nil)727	mockIaaS.EXPECT().DetachNetFromRouter(gomock.Any(),728		gomock.Any()).Return("", errors.New("error"))729	resp := DetachRouter("uuid-for-routet", "uuid-for-network")730	Convey("TestDetachERR406B\n", t, func() {731		So(resp.Code, ShouldEqual, 406)732	})733}734func TestDetachERR406C(t *testing.T) {735	cfgMock := gomock.NewController(t)736	defer cfgMock.Finish()737	mockDB := NewMockDbAccessor(cfgMock)738	mockIaaS := NewMockIaaS(cfgMock)739	common.SetDataBase(mockDB)740	stubs := gostub.StubFunc(&iaas.GetIaaS, mockIaaS)741	defer stubs.Reset()742	netInfo := string(`{743    "network": {744        "cidr": "123.124.125.0/24",745        "gateway": "123.124.125.1",746        "name": "network_show",747        "network_id": "9a4bf247-0cdd-4649-a5aa-4255856d3da2"748    }}`)749	MockPaasAdminCheck(mockDB)750	mockDB.EXPECT().ReadLeaf(gomock.Any()).Return(751		netInfo, nil)752	mockIaaS.EXPECT().DetachNetFromRouter(gomock.Any(),753		gomock.Any()).Return("uuid-for-port", nil)754	mockDB.EXPECT().DeleteLeaf(755		gomock.Any()).Return(errors.New("error"))756	resp := DetachRouter("uuid-for-routet", "uuid-for-network")757	Convey("TestDetachERR406C\n", t, func() {758		So(resp.Code, ShouldEqual, 406)759	})760}761func TestDetachERR406D(t *testing.T) {762	cfgMock := gomock.NewController(t)763	defer cfgMock.Finish()764	mockDB := NewMockDbAccessor(cfgMock)765	mockIaaS := NewMockIaaS(cfgMock)766	common.SetDataBase(mockDB)767	stubs := gostub.StubFunc(&iaas.GetIaaS, mockIaaS)768	defer stubs.Reset()769	netInfo := string(`{770    "network": {771        "cidr": "123.124.125.0/24",772        "gateway": "123.124.125.1",773        "name": "network_show",774        "network_id": "9a4bf247-0cdd-4649-a5aa-4255856d3da2"775    }}`)776	MockPaasAdminCheck(mockDB)777	mockDB.EXPECT().ReadLeaf(gomock.Any()).Return(778		netInfo, nil)779	mockIaaS.EXPECT().DetachNetFromRouter(gomock.Any(),780		gomock.Any()).Return("uuid-for-port", nil)781	mockDB.EXPECT().DeleteLeaf(gomock.Any()).Return(nil)782	mockDB.EXPECT().DeleteLeaf(783		gomock.Any()).Return(errors.New("error"))784	resp := DetachRouter("uuid-for-routet", "uuid-for-network")785	Convey("TestDetachERR406D\n", t, func() {786		So(resp.Code, ShouldEqual, 406)787	})788}789func TestDetachERR406E(t *testing.T) {790	cfgMock := gomock.NewController(t)791	defer cfgMock.Finish()792	mockDB := NewMockDbAccessor(cfgMock)793	mockIaaS := NewMockIaaS(cfgMock)794	common.SetDataBase(mockDB)795	stubs := gostub.StubFunc(&iaas.GetIaaS, mockIaaS)796	defer stubs.Reset()797	netInfo := string(`{798    "network": {799        "cidr": "123.124.125.0/24",800        "gateway": "123.124.125.1",801        "name": "network_show",802        "network_id": "9a4bf247-0cdd-4649-a5aa-4255856d3da2"803    }}`)804	MockPaasAdminCheck(mockDB)805	mockDB.EXPECT().ReadLeaf(gomock.Any()).Return(806		netInfo, nil)807	mockIaaS.EXPECT().DetachNetFromRouter(gomock.Any(),808		gomock.Any()).Return("uuid-for-port", nil)809	mockDB.EXPECT().DeleteLeaf(gomock.Any()).Return(nil)810	mockDB.EXPECT().DeleteLeaf(gomock.Any()).Return(nil)811	mockDB.EXPECT().DeleteDir(gomock.Any()).Return(errors.New("error"))812	resp := DetachRouter("uuid-for-routet", "uuid-for-network")813	Convey("TestDetachERR406D\n", t, func() {814		So(resp.Code, ShouldEqual, 406)815	})816}817func TestDetachOK(t *testing.T) {818	cfgMock := gomock.NewController(t)819	defer cfgMock.Finish()820	mockDB := NewMockDbAccessor(cfgMock)821	mockIaaS := NewMockIaaS(cfgMock)822	common.SetDataBase(mockDB)823	stubs := gostub.StubFunc(&iaas.GetIaaS, mockIaaS)824	defer stubs.Reset()825	netInfo := string(`{826    "network": {827        "cidr": "123.124.125.0/24",828        "gateway": "123.124.125.1",829        "name": "network_show",830        "network_id": "9a4bf247-0cdd-4649-a5aa-4255856d3da2"831    }}`)832	MockPaasAdminCheck(mockDB)833	gomock.InOrder(834		mockDB.EXPECT().ReadLeaf(gomock.Any()).Return(835			netInfo, nil),836		mockIaaS.EXPECT().DetachNetFromRouter(gomock.Any(),837			gomock.Any()).Return("uuid-for-port", nil),838		mockDB.EXPECT().DeleteLeaf(gomock.Any()).Return(nil),839		mockDB.EXPECT().DeleteLeaf(gomock.Any()).Return(nil),840		mockDB.EXPECT().DeleteDir(gomock.Any()).Return(nil),841	)842	resp := DetachRouter("uuid-for-routet", "uuid-for-network")843	Convey("TestDetachERR406E\n", t, func() {844		So(resp.Code, ShouldEqual, 200)845	})846}...

Full Screen

Full Screen

propose_test.go

Source:propose_test.go Github

copy

Full Screen

...78	return validator, m, validatorKey, ctrl.Finish79}80func TestProposeBlock_DoesNotProposeGenesisBlock(t *testing.T) {81	hook := logTest.NewGlobal()82	validator, _, validatorKey, finish := setup(t)83	defer finish()84	pubKey := [48]byte{}85	copy(pubKey[:], validatorKey.PublicKey().Marshal())86	validator.ProposeBlock(context.Background(), 0, pubKey)87	require.LogsContain(t, hook, "Assigned to genesis slot, skipping proposal")88}89func TestProposeBlock_DomainDataFailed(t *testing.T) {90	hook := logTest.NewGlobal()91	validator, m, validatorKey, finish := setup(t)92	defer finish()93	pubKey := [48]byte{}94	copy(pubKey[:], validatorKey.PublicKey().Marshal())95	m.validatorClient.EXPECT().DomainData(96		gomock.Any(), // ctx97		gomock.Any(), // epoch98	).Return(nil /*response*/, errors.New("uh oh"))99	validator.ProposeBlock(context.Background(), 1, pubKey)100	require.LogsContain(t, hook, "Failed to sign randao reveal")101}102func TestProposeBlock_DomainDataIsNil(t *testing.T) {103	hook := logTest.NewGlobal()104	validator, m, validatorKey, finish := setup(t)105	defer finish()106	pubKey := [48]byte{}107	copy(pubKey[:], validatorKey.PublicKey().Marshal())108	m.validatorClient.EXPECT().DomainData(109		gomock.Any(), // ctx110		gomock.Any(), // epoch111	).Return(nil /*response*/, nil)112	validator.ProposeBlock(context.Background(), 1, pubKey)113	require.LogsContain(t, hook, domainDataErr)114}115func TestProposeBlock_RequestBlockFailed(t *testing.T) {116	hook := logTest.NewGlobal()117	validator, m, validatorKey, finish := setup(t)118	defer finish()119	pubKey := [48]byte{}120	copy(pubKey[:], validatorKey.PublicKey().Marshal())121	m.validatorClient.EXPECT().DomainData(122		gomock.Any(), // ctx123		gomock.Any(), // epoch124	).Return(&ethpb.DomainResponse{SignatureDomain: make([]byte, 32)}, nil /*err*/)125	m.validatorClient.EXPECT().GetBlock(126		gomock.Any(), // ctx127		gomock.Any(), // block request128	).Return(nil /*response*/, errors.New("uh oh"))129	validator.ProposeBlock(context.Background(), 1, pubKey)130	require.LogsContain(t, hook, "Failed to request block from beacon node")131}132func TestProposeBlock_ProposeBlockFailed(t *testing.T) {133	hook := logTest.NewGlobal()134	validator, m, validatorKey, finish := setup(t)135	defer finish()136	pubKey := [48]byte{}137	copy(pubKey[:], validatorKey.PublicKey().Marshal())138	m.validatorClient.EXPECT().DomainData(139		gomock.Any(), // ctx140		gomock.Any(), //epoch141	).Return(&ethpb.DomainResponse{SignatureDomain: make([]byte, 32)}, nil /*err*/)142	m.validatorClient.EXPECT().GetBlock(143		gomock.Any(), // ctx144		gomock.Any(),145	).Return(testutil.NewBeaconBlock().Block, nil /*err*/)146	m.validatorClient.EXPECT().DomainData(147		gomock.Any(), // ctx148		gomock.Any(), //epoch149	).Return(&ethpb.DomainResponse{SignatureDomain: make([]byte, 32)}, nil /*err*/)150	m.validatorClient.EXPECT().ProposeBlock(151		gomock.Any(), // ctx152		gomock.AssignableToTypeOf(&ethpb.SignedBeaconBlock{}),153	).Return(nil /*response*/, errors.New("uh oh"))154	validator.ProposeBlock(context.Background(), 1, pubKey)155	require.LogsContain(t, hook, "Failed to propose block")156}157func TestProposeBlock_BlocksDoubleProposal(t *testing.T) {158	hook := logTest.NewGlobal()159	validator, m, validatorKey, finish := setup(t)160	defer finish()161	pubKey := [48]byte{}162	copy(pubKey[:], validatorKey.PublicKey().Marshal())163	m.validatorClient.EXPECT().DomainData(164		gomock.Any(), // ctx165		gomock.Any(), //epoch166	).Times(2).Return(&ethpb.DomainResponse{SignatureDomain: make([]byte, 32)}, nil /*err*/)167	m.validatorClient.EXPECT().GetBlock(168		gomock.Any(), // ctx169		gomock.Any(),170	).Times(2).Return(testutil.NewBeaconBlock().Block, nil /*err*/)171	m.validatorClient.EXPECT().DomainData(172		gomock.Any(), // ctx173		gomock.Any(), //epoch174	).Return(&ethpb.DomainResponse{SignatureDomain: make([]byte, 32)}, nil /*err*/)175	m.validatorClient.EXPECT().ProposeBlock(176		gomock.Any(), // ctx177		gomock.AssignableToTypeOf(&ethpb.SignedBeaconBlock{}),178	).Return(&ethpb.ProposeResponse{BlockRoot: make([]byte, 32)}, nil /*error*/)179	slot := params.BeaconConfig().SlotsPerEpoch*5 + 2180	validator.ProposeBlock(context.Background(), slot, pubKey)181	require.LogsDoNotContain(t, hook, failedPreBlockSignLocalErr)182	validator.ProposeBlock(context.Background(), slot, pubKey)183	require.LogsContain(t, hook, failedPreBlockSignLocalErr)184}185func TestProposeBlock_BlocksDoubleProposal_After54KEpochs(t *testing.T) {186	hook := logTest.NewGlobal()187	validator, m, validatorKey, finish := setup(t)188	defer finish()189	pubKey := [48]byte{}190	copy(pubKey[:], validatorKey.PublicKey().Marshal())191	m.validatorClient.EXPECT().DomainData(192		gomock.Any(), // ctx193		gomock.Any(), //epoch194	).Times(2).Return(&ethpb.DomainResponse{SignatureDomain: make([]byte, 32)}, nil /*err*/)195	m.validatorClient.EXPECT().GetBlock(196		gomock.Any(), // ctx197		gomock.Any(),198	).Times(2).Return(testutil.NewBeaconBlock().Block, nil /*err*/)199	m.validatorClient.EXPECT().DomainData(200		gomock.Any(), // ctx201		gomock.Any(), //epoch202	).Return(&ethpb.DomainResponse{SignatureDomain: make([]byte, 32)}, nil /*err*/)203	m.validatorClient.EXPECT().ProposeBlock(204		gomock.Any(), // ctx205		gomock.AssignableToTypeOf(&ethpb.SignedBeaconBlock{}),206	).Return(&ethpb.ProposeResponse{BlockRoot: make([]byte, 32)}, nil /*error*/)207	farFuture := (params.BeaconConfig().WeakSubjectivityPeriod + 9) * params.BeaconConfig().SlotsPerEpoch208	validator.ProposeBlock(context.Background(), farFuture, pubKey)209	require.LogsDoNotContain(t, hook, failedPreBlockSignLocalErr)210	validator.ProposeBlock(context.Background(), farFuture, pubKey)211	require.LogsContain(t, hook, failedPreBlockSignLocalErr)212}213func TestProposeBlock_AllowsPastProposals(t *testing.T) {214	hook := logTest.NewGlobal()215	validator, m, validatorKey, finish := setup(t)216	defer finish()217	pubKey := [48]byte{}218	copy(pubKey[:], validatorKey.PublicKey().Marshal())219	m.validatorClient.EXPECT().DomainData(220		gomock.Any(), // ctx221		gomock.Any(), //epoch222	).Times(2).Return(&ethpb.DomainResponse{SignatureDomain: make([]byte, 32)}, nil /*err*/)223	farAhead := (params.BeaconConfig().WeakSubjectivityPeriod + 9) * params.BeaconConfig().SlotsPerEpoch224	blk := testutil.NewBeaconBlock()225	blk.Block.Slot = farAhead226	m.validatorClient.EXPECT().GetBlock(227		gomock.Any(), // ctx228		gomock.Any(),229	).Return(blk.Block, nil /*err*/)230	m.validatorClient.EXPECT().DomainData(231		gomock.Any(), // ctx232		gomock.Any(), //epoch233	).Times(2).Return(&ethpb.DomainResponse{SignatureDomain: make([]byte, 32)}, nil /*err*/)234	m.validatorClient.EXPECT().ProposeBlock(235		gomock.Any(), // ctx236		gomock.AssignableToTypeOf(&ethpb.SignedBeaconBlock{}),237	).Times(2).Return(&ethpb.ProposeResponse{BlockRoot: make([]byte, 32)}, nil /*error*/)238	validator.ProposeBlock(context.Background(), farAhead, pubKey)239	require.LogsDoNotContain(t, hook, failedPreBlockSignLocalErr)240	past := (params.BeaconConfig().WeakSubjectivityPeriod - 400) * params.BeaconConfig().SlotsPerEpoch241	blk2 := testutil.NewBeaconBlock()242	blk2.Block.Slot = past243	m.validatorClient.EXPECT().GetBlock(244		gomock.Any(), // ctx245		gomock.Any(),246	).Return(blk2.Block, nil /*err*/)247	validator.ProposeBlock(context.Background(), past, pubKey)248	require.LogsDoNotContain(t, hook, failedPreBlockSignLocalErr)249}250func TestProposeBlock_AllowsSameEpoch(t *testing.T) {251	hook := logTest.NewGlobal()252	validator, m, validatorKey, finish := setup(t)253	defer finish()254	pubKey := [48]byte{}255	copy(pubKey[:], validatorKey.PublicKey().Marshal())256	m.validatorClient.EXPECT().DomainData(257		gomock.Any(), // ctx258		gomock.Any(), //epoch259	).Times(2).Return(&ethpb.DomainResponse{SignatureDomain: make([]byte, 32)}, nil /*err*/)260	farAhead := (params.BeaconConfig().WeakSubjectivityPeriod + 9) * params.BeaconConfig().SlotsPerEpoch261	blk := testutil.NewBeaconBlock()262	blk.Block.Slot = farAhead263	m.validatorClient.EXPECT().GetBlock(264		gomock.Any(), // ctx265		gomock.Any(),266	).Return(blk.Block, nil /*err*/)267	m.validatorClient.EXPECT().DomainData(268		gomock.Any(), // ctx269		gomock.Any(), //epoch270	).Times(2).Return(&ethpb.DomainResponse{SignatureDomain: make([]byte, 32)}, nil /*err*/)271	m.validatorClient.EXPECT().ProposeBlock(272		gomock.Any(), // ctx273		gomock.AssignableToTypeOf(&ethpb.SignedBeaconBlock{}),274	).Times(2).Return(&ethpb.ProposeResponse{BlockRoot: make([]byte, 32)}, nil /*error*/)275	validator.ProposeBlock(context.Background(), farAhead, pubKey)276	require.LogsDoNotContain(t, hook, failedPreBlockSignLocalErr)277	blk2 := testutil.NewBeaconBlock()278	blk2.Block.Slot = farAhead - 4279	m.validatorClient.EXPECT().GetBlock(280		gomock.Any(), // ctx281		gomock.Any(),282	).Return(blk2.Block, nil /*err*/)283	validator.ProposeBlock(context.Background(), farAhead-4, pubKey)284	require.LogsDoNotContain(t, hook, failedPreBlockSignLocalErr)285}286func TestProposeBlock_BroadcastsBlock(t *testing.T) {287	validator, m, validatorKey, finish := setup(t)288	defer finish()289	pubKey := [48]byte{}290	copy(pubKey[:], validatorKey.PublicKey().Marshal())291	m.validatorClient.EXPECT().DomainData(292		gomock.Any(), // ctx293		gomock.Any(), //epoch294	).Return(&ethpb.DomainResponse{SignatureDomain: make([]byte, 32)}, nil /*err*/)295	m.validatorClient.EXPECT().GetBlock(296		gomock.Any(), // ctx297		gomock.Any(),298	).Return(testutil.NewBeaconBlock().Block, nil /*err*/)299	m.validatorClient.EXPECT().DomainData(300		gomock.Any(), // ctx301		gomock.Any(), //epoch302	).Return(&ethpb.DomainResponse{SignatureDomain: make([]byte, 32)}, nil /*err*/)303	m.validatorClient.EXPECT().ProposeBlock(304		gomock.Any(), // ctx305		gomock.AssignableToTypeOf(&ethpb.SignedBeaconBlock{}),306	).Return(&ethpb.ProposeResponse{BlockRoot: make([]byte, 32)}, nil /*error*/)307	validator.ProposeBlock(context.Background(), 1, pubKey)308}309func TestProposeBlock_BroadcastsBlock_WithGraffiti(t *testing.T) {310	validator, m, validatorKey, finish := setup(t)311	defer finish()312	pubKey := [48]byte{}313	copy(pubKey[:], validatorKey.PublicKey().Marshal())314	validator.graffiti = []byte("12345678901234567890123456789012")315	m.validatorClient.EXPECT().DomainData(316		gomock.Any(), // ctx317		gomock.Any(), //epoch318	).Return(&ethpb.DomainResponse{SignatureDomain: make([]byte, 32)}, nil /*err*/)319	blk := testutil.NewBeaconBlock()320	blk.Block.Body.Graffiti = validator.graffiti321	m.validatorClient.EXPECT().GetBlock(322		gomock.Any(), // ctx323		gomock.Any(),324	).Return(blk.Block, nil /*err*/)325	m.validatorClient.EXPECT().DomainData(326		gomock.Any(), // ctx327		gomock.Any(), //epoch328	).Return(&ethpb.DomainResponse{SignatureDomain: make([]byte, 32)}, nil /*err*/)329	var sentBlock *ethpb.SignedBeaconBlock330	m.validatorClient.EXPECT().ProposeBlock(331		gomock.Any(), // ctx332		gomock.AssignableToTypeOf(&ethpb.SignedBeaconBlock{}),333	).DoAndReturn(func(ctx context.Context, block *ethpb.SignedBeaconBlock) (*ethpb.ProposeResponse, error) {334		sentBlock = block335		return &ethpb.ProposeResponse{BlockRoot: make([]byte, 32)}, nil336	})337	validator.ProposeBlock(context.Background(), 1, pubKey)338	assert.Equal(t, string(validator.graffiti), string(sentBlock.Block.Body.Graffiti))339}340func TestProposeExit_ValidatorIndexFailed(t *testing.T) {341	_, m, validatorKey, finish := setup(t)342	defer finish()343	m.validatorClient.EXPECT().ValidatorIndex(344		gomock.Any(),345		gomock.Any(),346	).Return(nil, errors.New("uh oh"))347	err := ProposeExit(348		context.Background(),349		m.validatorClient,350		m.nodeClient,351		m.signExitFunc,352		validatorKey.PublicKey().Marshal(),353	)354	assert.NotNil(t, err)355	assert.ErrorContains(t, "uh oh", err)356	assert.ErrorContains(t, "gRPC call to get validator index failed", err)357}358func TestProposeExit_GetGenesisFailed(t *testing.T) {359	_, m, validatorKey, finish := setup(t)360	defer finish()361	m.validatorClient.EXPECT().362		ValidatorIndex(gomock.Any(), gomock.Any()).363		Return(nil, nil)364	m.nodeClient.EXPECT().365		GetGenesis(gomock.Any(), gomock.Any()).366		Return(nil, errors.New("uh oh"))367	err := ProposeExit(368		context.Background(),369		m.validatorClient,370		m.nodeClient,371		m.signExitFunc,372		validatorKey.PublicKey().Marshal(),373	)374	assert.NotNil(t, err)375	assert.ErrorContains(t, "uh oh", err)376	assert.ErrorContains(t, "gRPC call to get genesis time failed", err)377}378func TestProposeExit_DomainDataFailed(t *testing.T) {379	_, m, validatorKey, finish := setup(t)380	defer finish()381	m.validatorClient.EXPECT().382		ValidatorIndex(gomock.Any(), gomock.Any()).383		Return(&ethpb.ValidatorIndexResponse{Index: 1}, nil)384	// Any time in the past will suffice385	genesisTime := &types.Timestamp{386		Seconds: time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC).Unix(),387	}388	m.nodeClient.EXPECT().389		GetGenesis(gomock.Any(), gomock.Any()).390		Return(&ethpb.Genesis{GenesisTime: genesisTime}, nil)391	m.validatorClient.EXPECT().392		DomainData(gomock.Any(), gomock.Any()).393		Return(nil, errors.New("uh oh"))394	err := ProposeExit(395		context.Background(),396		m.validatorClient,397		m.nodeClient,398		m.signExitFunc,399		validatorKey.PublicKey().Marshal(),400	)401	assert.NotNil(t, err)402	assert.ErrorContains(t, domainDataErr, err)403	assert.ErrorContains(t, "uh oh", err)404	assert.ErrorContains(t, "failed to sign voluntary exit", err)405}406func TestProposeExit_DomainDataIsNil(t *testing.T) {407	_, m, validatorKey, finish := setup(t)408	defer finish()409	m.validatorClient.EXPECT().410		ValidatorIndex(gomock.Any(), gomock.Any()).411		Return(&ethpb.ValidatorIndexResponse{Index: 1}, nil)412	// Any time in the past will suffice413	genesisTime := &types.Timestamp{414		Seconds: time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC).Unix(),415	}416	m.nodeClient.EXPECT().417		GetGenesis(gomock.Any(), gomock.Any()).418		Return(&ethpb.Genesis{GenesisTime: genesisTime}, nil)419	m.validatorClient.EXPECT().420		DomainData(gomock.Any(), gomock.Any()).421		Return(nil, nil)422	err := ProposeExit(423		context.Background(),424		m.validatorClient,425		m.nodeClient,426		m.signExitFunc,427		validatorKey.PublicKey().Marshal(),428	)429	assert.NotNil(t, err)430	assert.ErrorContains(t, domainDataErr, err)431	assert.ErrorContains(t, "failed to sign voluntary exit", err)432}433func TestProposeBlock_ProposeExitFailed(t *testing.T) {434	_, m, validatorKey, finish := setup(t)435	defer finish()436	m.validatorClient.EXPECT().437		ValidatorIndex(gomock.Any(), gomock.Any()).438		Return(&ethpb.ValidatorIndexResponse{Index: 1}, nil)439	// Any time in the past will suffice440	genesisTime := &types.Timestamp{441		Seconds: time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC).Unix(),442	}443	m.nodeClient.EXPECT().444		GetGenesis(gomock.Any(), gomock.Any()).445		Return(&ethpb.Genesis{GenesisTime: genesisTime}, nil)446	m.validatorClient.EXPECT().447		DomainData(gomock.Any(), gomock.Any()).448		Return(&ethpb.DomainResponse{SignatureDomain: make([]byte, 32)}, nil)449	m.validatorClient.EXPECT().450		ProposeExit(gomock.Any(), gomock.AssignableToTypeOf(&ethpb.SignedVoluntaryExit{})).451		Return(nil, errors.New("uh oh"))452	err := ProposeExit(453		context.Background(),454		m.validatorClient,455		m.nodeClient,456		m.signExitFunc,457		validatorKey.PublicKey().Marshal(),458	)459	assert.NotNil(t, err)460	assert.ErrorContains(t, "uh oh", err)461	assert.ErrorContains(t, "failed to propose voluntary exit", err)462}463func TestProposeExit_BroadcastsBlock(t *testing.T) {464	_, m, validatorKey, finish := setup(t)465	defer finish()466	m.validatorClient.EXPECT().467		ValidatorIndex(gomock.Any(), gomock.Any()).468		Return(&ethpb.ValidatorIndexResponse{Index: 1}, nil)469	// Any time in the past will suffice470	genesisTime := &types.Timestamp{471		Seconds: time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC).Unix(),472	}473	m.nodeClient.EXPECT().474		GetGenesis(gomock.Any(), gomock.Any()).475		Return(&ethpb.Genesis{GenesisTime: genesisTime}, nil)476	m.validatorClient.EXPECT().477		DomainData(gomock.Any(), gomock.Any()).478		Return(&ethpb.DomainResponse{SignatureDomain: make([]byte, 32)}, nil)479	m.validatorClient.EXPECT().480		ProposeExit(gomock.Any(), gomock.AssignableToTypeOf(&ethpb.SignedVoluntaryExit{})).481		Return(&ethpb.ProposeExitResponse{}, nil)482	assert.NoError(t, ProposeExit(483		context.Background(),484		m.validatorClient,485		m.nodeClient,486		m.signExitFunc,487		validatorKey.PublicKey().Marshal(),488	))489}490func TestSignBlock(t *testing.T) {491	validator, m, _, finish := setup(t)492	defer finish()493	secretKey, err := bls.SecretKeyFromBytes(bytesutil.PadTo([]byte{1}, 32))494	require.NoError(t, err, "Failed to generate key from bytes")495	publicKey := secretKey.PublicKey()496	proposerDomain := make([]byte, 32)497	m.validatorClient.EXPECT().498		DomainData(gomock.Any(), gomock.Any()).499		Return(&ethpb.DomainResponse{SignatureDomain: proposerDomain}, nil)500	ctx := context.Background()501	blk := testutil.NewBeaconBlock()502	blk.Block.Slot = 1503	blk.Block.ProposerIndex = 100504	var pubKey [48]byte505	copy(pubKey[:], publicKey.Marshal())506	km := &mockKeymanager{...

Full Screen

Full Screen

validator_propose_test.go

Source:validator_propose_test.go Github

copy

Full Screen

...38	return validator, m, ctrl.Finish39}40func TestProposeBlock_DoesNotProposeGenesisBlock(t *testing.T) {41	hook := logTest.NewGlobal()42	validator, _, finish := setup(t)43	defer finish()44	validator.ProposeBlock(context.Background(), params.BeaconConfig().GenesisSlot, hex.EncodeToString(validatorKey.PublicKey.Marshal()))45	testutil.AssertLogsContain(t, hook, "Assigned to genesis slot, skipping proposal")46}47func TestProposeBlock_LogsCanonicalHeadFailure(t *testing.T) {48	hook := logTest.NewGlobal()49	validator, m, finish := setup(t)50	defer finish()51	m.beaconClient.EXPECT().CanonicalHead(52		gomock.Any(), // ctx53		gomock.Eq(&ptypes.Empty{}),54	).Return(nil /*beaconBlock*/, errors.New("something bad happened"))55	validator.ProposeBlock(context.Background(), 55, hex.EncodeToString(validatorKey.PublicKey.Marshal()))56	testutil.AssertLogsContain(t, hook, "something bad happened")57}58func TestProposeBlock_PendingDepositsFailure(t *testing.T) {59	hook := logTest.NewGlobal()60	validator, m, finish := setup(t)61	defer finish()62	m.beaconClient.EXPECT().CanonicalHead(63		gomock.Any(), // ctx64		gomock.Eq(&ptypes.Empty{}),65	).Return(&pbp2p.BeaconBlock{}, nil /*err*/)66	m.beaconClient.EXPECT().PendingDeposits(67		gomock.Any(), // ctx68		gomock.Eq(&ptypes.Empty{}),69	).Return(nil /*response*/, errors.New("something bad happened"))70	validator.ProposeBlock(context.Background(), 55, hex.EncodeToString(validatorKey.PublicKey.Marshal()))71	testutil.AssertLogsContain(t, hook, "something bad happened")72}73func TestProposeBlock_UsePendingDeposits(t *testing.T) {74	validator, m, finish := setup(t)75	defer finish()76	m.beaconClient.EXPECT().CanonicalHead(77		gomock.Any(), // ctx78		gomock.Eq(&ptypes.Empty{}),79	).Return(&pbp2p.BeaconBlock{}, nil /*err*/)80	m.beaconClient.EXPECT().PendingDeposits(81		gomock.Any(), // ctx82		gomock.Eq(&ptypes.Empty{}),83	).Return(&pb.PendingDepositsResponse{84		PendingDeposits: []*pbp2p.Deposit{85			{DepositData: []byte{'D', 'A', 'T', 'A'}},86		},87	}, nil /*err*/)88	m.beaconClient.EXPECT().Eth1Data(89		gomock.Any(), // ctx90		gomock.Eq(&ptypes.Empty{}),91	).Return(&pb.Eth1DataResponse{}, nil /*err*/)92	m.beaconClient.EXPECT().ForkData(93		gomock.Any(), // ctx94		gomock.Eq(&ptypes.Empty{}),95	).Return(&pbp2p.Fork{96		Epoch:           params.BeaconConfig().GenesisEpoch,97		CurrentVersion:  0,98		PreviousVersion: 0,99	}, nil /*err*/)100	m.proposerClient.EXPECT().PendingAttestations(101		gomock.Any(), // ctx102		gomock.AssignableToTypeOf(&pb.PendingAttestationsRequest{}),103	).Return(&pb.PendingAttestationsResponse{PendingAttestations: []*pbp2p.Attestation{}}, nil)104	m.proposerClient.EXPECT().ComputeStateRoot(105		gomock.Any(), // context106		gomock.AssignableToTypeOf(&pbp2p.BeaconBlock{}),107	).Return(&pb.StateRootResponse{108		StateRoot: []byte{'F'},109	}, nil /*err*/)110	var broadcastedBlock *pbp2p.BeaconBlock111	m.proposerClient.EXPECT().ProposeBlock(112		gomock.Any(), // context113		gomock.AssignableToTypeOf(&pbp2p.BeaconBlock{}),114	).Do(func(_ context.Context, blk *pbp2p.BeaconBlock) {115		broadcastedBlock = blk116	}).Return(&pb.ProposeResponse{}, nil /*error*/)117	validator.ProposeBlock(context.Background(), 55, hex.EncodeToString(validatorKey.PublicKey.Marshal()))118	if !bytes.Equal(broadcastedBlock.Body.Deposits[0].DepositData, []byte{'D', 'A', 'T', 'A'}) {119		t.Errorf("Unexpected deposit data: %v", broadcastedBlock.Body.Deposits)120	}121}122func TestProposeBlock_Eth1DataFailure(t *testing.T) {123	hook := logTest.NewGlobal()124	validator, m, finish := setup(t)125	defer finish()126	m.beaconClient.EXPECT().CanonicalHead(127		gomock.Any(), // ctx128		gomock.Eq(&ptypes.Empty{}),129	).Return(&pbp2p.BeaconBlock{}, nil /*err*/)130	m.beaconClient.EXPECT().PendingDeposits(131		gomock.Any(), // ctx132		gomock.Eq(&ptypes.Empty{}),133	).Return(&pb.PendingDepositsResponse{}, nil /*err*/)134	m.beaconClient.EXPECT().Eth1Data(135		gomock.Any(), // ctx136		gomock.Eq(&ptypes.Empty{}),137	).Return(nil /*response*/, errors.New("something bad happened"))138	validator.ProposeBlock(context.Background(), 55, hex.EncodeToString(validatorKey.PublicKey.Marshal()))139	testutil.AssertLogsContain(t, hook, "something bad happened")140}141func TestProposeBlock_UsesEth1Data(t *testing.T) {142	validator, m, finish := setup(t)143	defer finish()144	m.beaconClient.EXPECT().CanonicalHead(145		gomock.Any(), // ctx146		gomock.Eq(&ptypes.Empty{}),147	).Return(&pbp2p.BeaconBlock{}, nil /*err*/)148	m.beaconClient.EXPECT().PendingDeposits(149		gomock.Any(), // ctx150		gomock.Eq(&ptypes.Empty{}),151	).Return(&pb.PendingDepositsResponse{}, nil /*err*/)152	m.beaconClient.EXPECT().Eth1Data(153		gomock.Any(), // ctx154		gomock.Eq(&ptypes.Empty{}),155	).Return(&pb.Eth1DataResponse{156		Eth1Data: &pbp2p.Eth1Data{BlockHash32: []byte{'B', 'L', 'O', 'C', 'K'}},157	}, nil /*err*/)158	m.beaconClient.EXPECT().ForkData(159		gomock.Any(), // ctx160		gomock.Eq(&ptypes.Empty{}),161	).Return(&pbp2p.Fork{162		Epoch:           params.BeaconConfig().GenesisEpoch,163		CurrentVersion:  0,164		PreviousVersion: 0,165	}, nil /*err*/)166	m.proposerClient.EXPECT().PendingAttestations(167		gomock.Any(), // ctx168		gomock.AssignableToTypeOf(&pb.PendingAttestationsRequest{}),169	).Return(&pb.PendingAttestationsResponse{PendingAttestations: []*pbp2p.Attestation{}}, nil)170	m.proposerClient.EXPECT().ComputeStateRoot(171		gomock.Any(), // context172		gomock.AssignableToTypeOf(&pbp2p.BeaconBlock{}),173	).Return(&pb.StateRootResponse{174		StateRoot: []byte{'F'},175	}, nil /*err*/)176	var broadcastedBlock *pbp2p.BeaconBlock177	m.proposerClient.EXPECT().ProposeBlock(178		gomock.Any(), // ctx179		gomock.AssignableToTypeOf(&pbp2p.BeaconBlock{}),180	).Do(func(_ context.Context, blk *pbp2p.BeaconBlock) {181		broadcastedBlock = blk182	}).Return(&pb.ProposeResponse{}, nil /*error*/)183	validator.ProposeBlock(context.Background(), 55, hex.EncodeToString(validatorKey.PublicKey.Marshal()))184	if !bytes.Equal(broadcastedBlock.Eth1Data.BlockHash32, []byte{'B', 'L', 'O', 'C', 'K'}) {185		t.Errorf("Unexpected ETH1 data: %v", broadcastedBlock.Eth1Data)186	}187}188func TestProposeBlock_PendingAttestations_UsesCurrentSlot(t *testing.T) {189	validator, m, finish := setup(t)190	defer finish()191	m.beaconClient.EXPECT().CanonicalHead(192		gomock.Any(), // ctx193		gomock.Eq(&ptypes.Empty{}),194	).Return(&pbp2p.BeaconBlock{}, nil /*err*/)195	m.beaconClient.EXPECT().PendingDeposits(196		gomock.Any(), // ctx197		gomock.Eq(&ptypes.Empty{}),198	).Return(&pb.PendingDepositsResponse{}, nil /*err*/)199	m.beaconClient.EXPECT().Eth1Data(200		gomock.Any(), // ctx201		gomock.Eq(&ptypes.Empty{}),202	).Return(&pb.Eth1DataResponse{203		Eth1Data: &pbp2p.Eth1Data{BlockHash32: []byte{'B', 'L', 'O', 'C', 'K'}},204	}, nil /*err*/)205	m.beaconClient.EXPECT().ForkData(206		gomock.Any(), // ctx207		gomock.Eq(&ptypes.Empty{}),208	).Return(&pbp2p.Fork{209		Epoch:           params.BeaconConfig().GenesisEpoch,210		CurrentVersion:  0,211		PreviousVersion: 0,212	}, nil /*err*/)213	var req *pb.PendingAttestationsRequest214	m.proposerClient.EXPECT().PendingAttestations(215		gomock.Any(), // ctx216		gomock.AssignableToTypeOf(&pb.PendingAttestationsRequest{}),217	).DoAndReturn(func(_ context.Context, r *pb.PendingAttestationsRequest) (*pb.PendingAttestationsResponse, error) {218		req = r219		return &pb.PendingAttestationsResponse{PendingAttestations: []*pbp2p.Attestation{}}, nil220	})221	m.proposerClient.EXPECT().ComputeStateRoot(222		gomock.Any(), // context223		gomock.AssignableToTypeOf(&pbp2p.BeaconBlock{}),224	).Return(&pb.StateRootResponse{225		StateRoot: []byte{'F'},226	}, nil /*err*/)227	m.proposerClient.EXPECT().ProposeBlock(228		gomock.Any(), // context229		gomock.AssignableToTypeOf(&pbp2p.BeaconBlock{}),230	).Return(&pb.ProposeResponse{}, nil /*error*/)231	validator.ProposeBlock(context.Background(), 55, hex.EncodeToString(validatorKey.PublicKey.Marshal()))232	if req.ProposalBlockSlot != 55 {233		t.Errorf(234			"expected request to use the current proposal slot %d, but got %d",235			55,236			req.ProposalBlockSlot,237		)238	}239}240func TestProposeBlock_PendingAttestationsFailure(t *testing.T) {241	hook := logTest.NewGlobal()242	validator, m, finish := setup(t)243	defer finish()244	m.beaconClient.EXPECT().CanonicalHead(245		gomock.Any(), // ctx246		gomock.Eq(&ptypes.Empty{}),247	).Return(&pbp2p.BeaconBlock{}, nil /*err*/)248	m.beaconClient.EXPECT().PendingDeposits(249		gomock.Any(), // ctx250		gomock.Eq(&ptypes.Empty{}),251	).Return(&pb.PendingDepositsResponse{}, nil /*err*/)252	m.beaconClient.EXPECT().Eth1Data(253		gomock.Any(), // ctx254		gomock.Eq(&ptypes.Empty{}),255	).Return(&pb.Eth1DataResponse{256		Eth1Data: &pbp2p.Eth1Data{BlockHash32: []byte{'B', 'L', 'O', 'C', 'K'}},257	}, nil /*err*/)258	m.beaconClient.EXPECT().ForkData(259		gomock.Any(), // ctx260		gomock.Eq(&ptypes.Empty{}),261	).Return(&pbp2p.Fork{262		Epoch:           params.BeaconConfig().GenesisEpoch,263		CurrentVersion:  0,264		PreviousVersion: 0,265	}, nil /*err*/)266	m.proposerClient.EXPECT().PendingAttestations(267		gomock.Any(), // ctx268		gomock.AssignableToTypeOf(&pb.PendingAttestationsRequest{}),269	).Return(nil, errors.New("failed"))270	validator.ProposeBlock(context.Background(), 55, hex.EncodeToString(validatorKey.PublicKey.Marshal()))271	testutil.AssertLogsContain(t, hook, "Failed to fetch pending attestations")272}273func TestProposeBlock_ComputeStateFailure(t *testing.T) {274	hook := logTest.NewGlobal()275	validator, m, finish := setup(t)276	defer finish()277	m.beaconClient.EXPECT().CanonicalHead(278		gomock.Any(), // ctx279		gomock.Eq(&ptypes.Empty{}),280	).Return(&pbp2p.BeaconBlock{}, nil /*err*/)281	m.beaconClient.EXPECT().PendingDeposits(282		gomock.Any(), // ctx283		gomock.Eq(&ptypes.Empty{}),284	).Return(&pb.PendingDepositsResponse{}, nil /*err*/)285	m.beaconClient.EXPECT().Eth1Data(286		gomock.Any(), // ctx287		gomock.Eq(&ptypes.Empty{}),288	).Return(&pb.Eth1DataResponse{}, nil /*err*/)289	m.beaconClient.EXPECT().ForkData(290		gomock.Any(), // ctx291		gomock.Eq(&ptypes.Empty{}),292	).Return(&pbp2p.Fork{293		Epoch:           params.BeaconConfig().GenesisEpoch,294		CurrentVersion:  0,295		PreviousVersion: 0,296	}, nil /*err*/)297	m.proposerClient.EXPECT().PendingAttestations(298		gomock.Any(), // ctx299		gomock.AssignableToTypeOf(&pb.PendingAttestationsRequest{}),300	).Return(&pb.PendingAttestationsResponse{PendingAttestations: []*pbp2p.Attestation{}}, nil)301	m.proposerClient.EXPECT().ComputeStateRoot(302		gomock.Any(), // context303		gomock.AssignableToTypeOf(&pbp2p.BeaconBlock{}),304	).Return(nil /*response*/, errors.New("something bad happened"))305	validator.ProposeBlock(context.Background(), 55, hex.EncodeToString(validatorKey.PublicKey.Marshal()))306	testutil.AssertLogsContain(t, hook, "something bad happened")307}308func TestProposeBlock_UsesComputedState(t *testing.T) {309	validator, m, finish := setup(t)310	defer finish()311	m.beaconClient.EXPECT().CanonicalHead(312		gomock.Any(), // ctx313		gomock.Eq(&ptypes.Empty{}),314	).Return(&pbp2p.BeaconBlock{}, nil /*err*/)315	m.beaconClient.EXPECT().PendingDeposits(316		gomock.Any(), // ctx317		gomock.Eq(&ptypes.Empty{}),318	).Return(&pb.PendingDepositsResponse{}, nil /*err*/)319	m.beaconClient.EXPECT().Eth1Data(320		gomock.Any(), // ctx321		gomock.Eq(&ptypes.Empty{}),322	).Return(&pb.Eth1DataResponse{}, nil /*err*/)323	m.beaconClient.EXPECT().ForkData(324		gomock.Any(), // ctx325		gomock.Eq(&ptypes.Empty{}),326	).Return(&pbp2p.Fork{327		Epoch:           params.BeaconConfig().GenesisEpoch,328		CurrentVersion:  0,329		PreviousVersion: 0,330	}, nil /*err*/)331	m.proposerClient.EXPECT().PendingAttestations(332		gomock.Any(), // ctx333		gomock.AssignableToTypeOf(&pb.PendingAttestationsRequest{}),334	).Return(&pb.PendingAttestationsResponse{PendingAttestations: []*pbp2p.Attestation{}}, nil)335	var broadcastedBlock *pbp2p.BeaconBlock336	m.proposerClient.EXPECT().ProposeBlock(337		gomock.Any(), // ctx338		gomock.AssignableToTypeOf(&pbp2p.BeaconBlock{}),339	).Do(func(_ context.Context, blk *pbp2p.BeaconBlock) {340		broadcastedBlock = blk341	}).Return(&pb.ProposeResponse{}, nil /*error*/)342	computedStateRoot := []byte{'T', 'E', 'S', 'T'}343	m.proposerClient.EXPECT().ComputeStateRoot(344		gomock.Any(), // context345		gomock.AssignableToTypeOf(&pbp2p.BeaconBlock{}),346	).Return(347		&pb.StateRootResponse{348			StateRoot: computedStateRoot,349		},350		nil, // err351	)352	validator.ProposeBlock(context.Background(), 55, hex.EncodeToString(validatorKey.PublicKey.Marshal()))353	if !bytes.Equal(broadcastedBlock.StateRootHash32, computedStateRoot) {354		t.Errorf("Unexpected state root hash. want=%#x got=%#x", computedStateRoot, broadcastedBlock.StateRootHash32)355	}356}357func TestProposeBlock_BroadcastsABlock(t *testing.T) {358	validator, m, finish := setup(t)359	defer finish()360	m.beaconClient.EXPECT().CanonicalHead(361		gomock.Any(), // ctx362		gomock.Eq(&ptypes.Empty{}),363	).Return(&pbp2p.BeaconBlock{}, nil /*err*/)364	m.beaconClient.EXPECT().PendingDeposits(365		gomock.Any(), // ctx366		gomock.Eq(&ptypes.Empty{}),367	).Return(&pb.PendingDepositsResponse{}, nil /*err*/)368	m.beaconClient.EXPECT().Eth1Data(369		gomock.Any(), // ctx370		gomock.Eq(&ptypes.Empty{}),371	).Return(&pb.Eth1DataResponse{}, nil /*err*/)372	m.beaconClient.EXPECT().ForkData(373		gomock.Any(), // ctx...

Full Screen

Full Screen

finish

Using AI Code Generation

copy

Full Screen

1import (2func Test1(t *testing.T) {3	ctrl := gomock.NewController(t)4	defer ctrl.Finish()5	fmt.Println("Test 1 passed")6}7func Test2(t *testing.T) {8	ctrl := gomock.NewController(t)9	fmt.Println("Test 2 passed")10}11--- PASS: Test1 (0.00s)12--- FAIL: Test2 (0.00s)13testing.tRunner.func1(0xc4200b6100)14panic(0x4f2c40, 0x5e4a20)15github.com/golang/mock/gomock.(*Controller).Finish(0xc4200d2000)16main.Test2(0xc4200b6100)17testing.tRunner(0xc4200b6100, 0x52c6f8)18created by testing.(*T).Run19When to use gomock.Finish()?

Full Screen

Full Screen

finish

Using AI Code Generation

copy

Full Screen

1import (2func TestFinish(t *testing.T) {3	ctrl := gomock.NewController(t)4	defer ctrl.Finish()5	fmt.Println("Hello")6}7import (8func TestTimes(t *testing.T) {9	ctrl := gomock.NewController(t)10	defer ctrl.Finish()11	fmt.Println("Hello")12}13import (14func TestCall(t *testing.T) {15	ctrl := gomock.NewController(t)16	defer ctrl.Finish()17	fmt.Println("Hello")18}19import (20func TestTimes(t *testing.T) {21	ctrl := gomock.NewController(t)22	defer ctrl.Finish()23	fmt.Println("Hello")24}25import (26func TestTimes(t *testing.T) {27	ctrl := gomock.NewController(t)28	defer ctrl.Finish()29	fmt.Println("Hello")30}31import (

Full Screen

Full Screen

finish

Using AI Code Generation

copy

Full Screen

1import (2func TestMock(t *testing.T) {3	ctrl := gomock.NewController(t)4	defer ctrl.Finish()5	fmt.Println("Mock test")6}7import (8func TestMock(t *testing.T) {9	ctrl := gomock.NewController(t)10	defer ctrl.Finish()11	fmt.Println("Mock test")12}13import (14func TestMock(t *testing.T) {15	ctrl := gomock.NewController(t)16	defer ctrl.Finish()17	fmt.Println("Mock test")18}19import (20func TestMock(t *testing.T) {21	ctrl := gomock.NewController(t)22	defer ctrl.Finish()23	fmt.Println("Mock test")24}25import (26func TestMock(t *testing.T) {27	ctrl := gomock.NewController(t)28	defer ctrl.Finish()29	fmt.Println("Mock test")30}31import (32func TestMock(t *testing.T) {33	ctrl := gomock.NewController(t)34	defer ctrl.Finish()35	fmt.Println("Mock test")36}37import (38func TestMock(t *testing.T) {39	ctrl := gomock.NewController(t)40	defer ctrl.Finish()41	fmt.Println("Mock test")42}

Full Screen

Full Screen

finish

Using AI Code Generation

copy

Full Screen

1import (2func main() {3	ctrl := gomock.NewController(t)4	defer ctrl.Finish()5	mock := mocks.NewMockInterface(ctrl)6	mock.EXPECT().Method().Return("Hello World")7	fmt.Println(mock.Method())8}9import (10func main() {11	ctrl := gomock.NewController(t)12	defer ctrl.Finish()13	mock := mocks.NewMockInterface(ctrl)14	mock.EXPECT().Method().Return("Hello World")15	fmt.Println(mock.Method())16}17import (18func main() {19	ctrl := gomock.NewController(t)20	defer ctrl.Finish()21	mock := mocks.NewMockInterface(ctrl)22	mock.EXPECT().Method().Return("Hello World")23	fmt.Println(mock.Method())24}25import (26func main() {27	ctrl := gomock.NewController(t)28	defer ctrl.Finish()29	mock := mocks.NewMockInterface(ctrl)30	mock.EXPECT().Method().Return("Hello World")31	fmt.Println(mock.Method())32}33import (34func main() {35	ctrl := gomock.NewController(t)36	defer ctrl.Finish()37	mock := mocks.NewMockInterface(ctrl)38	mock.EXPECT().Method().Return("Hello World")39	fmt.Println(mock.Method())40}41import (42func main() {43	ctrl := gomock.NewController(t)

Full Screen

Full Screen

finish

Using AI Code Generation

copy

Full Screen

1func TestFinish(t *testing.T) {2    ctrl := gomock.NewController(t)3    defer ctrl.Finish()4    mock := NewMockFoo(ctrl)5    mock.EXPECT().Bar().Return("bar")6    mock.Bar()7}8func TestFoo(t *testing.T) {9    ctrl := gomock.NewController(t)10    defer ctrl.Finish()11    mock := NewMockFoo(ctrl)12    mock.EXPECT().Bar().Return("bar")13    Foo(mock)14}15func TestBar(t *testing.T) {16    ctrl := gomock.NewController(t)17    defer ctrl.Finish()18    mock := NewMockFoo(ctrl)19    mock.EXPECT().Bar().Return("bar")20    Bar(mock)21}22func TestBaz(t *testing.T) {23    ctrl := gomock.NewController(t)24    defer ctrl.Finish()25    mock := NewMockFoo(ctrl)26    mock.EXPECT().Bar().Return("bar")27    Baz(mock)28}29func TestFoo(t *testing.T) {30    mock := NewMockFoo(ctrl)31    mock.EXPECT().Bar().Return("bar")32    Foo(mock)33}34func TestBar(t *testing.T) {35    mock := NewMockFoo(ctrl)36    mock.EXPECT().Bar().Return("bar")37    Bar(mock)38}39func TestBaz(t *testing.T) {40    mock := NewMockFoo(ctrl)41    mock.EXPECT().Bar().Return("bar")42    Baz(mock)43}44func TestBaz(t *testing.T) {45    mock := NewMockFoo(ctrl)46    mock.EXPECT().Bar().Return("bar")47    Baz(mock)48}49func TestBaz(t *testing.T) {50    mock := NewMockFoo(ctrl)51    mock.EXPECT().Bar().Return("bar")52    Baz(mock)53}

Full Screen

Full Screen

finish

Using AI Code Generation

copy

Full Screen

1import (2func main() {3	ctrl := gomock.NewController(nil)4	fmt.Println("Hello World")5}6import (7func main() {8	ctrl := gomock.NewController(nil)9	fmt.Println("Hello World")10}11import (12func main() {13	ctrl := gomock.NewController(nil)14	fmt.Println("Hello World")15}16import (17func main() {18	ctrl := gomock.NewController(nil)19	fmt.Println("Hello World")20}21import (22func main() {23	ctrl := gomock.NewController(nil)24	fmt.Println("Hello World")25}26import (27func main() {28	ctrl := gomock.NewController(nil)29	fmt.Println("Hello World")30}31import (32func main() {33	ctrl := gomock.NewController(nil)34	fmt.Println("Hello World")35}

Full Screen

Full Screen

finish

Using AI Code Generation

copy

Full Screen

1func Test1(t *testing.T) {2    ctrl := gomock.NewController(t)3    defer ctrl.Finish()4    mock := mock.NewMockMyInterface(ctrl)5    mock.EXPECT().MyMethod(gomock.Any()).Return("abc")6    actual := MyFunction(mock)7    if actual != "abc" {8        t.Errorf("expected %s, got %s", "abc", actual)9    }10}11func Test2(t *testing.T) {12    ctrl := gomock.NewController(t)13    defer ctrl.Finish()14    mock := mock.NewMockMyInterface(ctrl)15    mock.EXPECT().MyMethod(gomock.Any()).Return("abc")16    actual := MyFunction(mock)17    if actual != "abc" {18        t.Errorf("expected %s, got %s", "abc", actual)19    }20}21func Test3(t *testing.T) {22    ctrl := gomock.NewController(t)23    defer ctrl.Finish()24    mock := mock.NewMockMyInterface(ctrl)25    mock.EXPECT().MyMethod(gomock.Any()).Return("abc")26    actual := MyFunction(mock)27    if actual != "abc" {28        t.Errorf("expected %s, got %s", "abc", actual)29    }30}

Full Screen

Full Screen

finish

Using AI Code Generation

copy

Full Screen

1import (2func main() {3    ctrl := gomock.NewController(t)4    mockObject := mock.NewMockInterface(ctrl)5    mockObject.EXPECT().Method1().Return("Hello World")6    result := myFunc(mockObject)7    if result != "Hello World" {8        t.Errorf("Expected result to be 'Hello World', got '%s'", result)9    }10    ctrl.Finish()11}12func myFunc(mockObject *mock.Interface) string {13    return mockObject.Method1()14}15import (16func main() {17    ctrl := gomock.NewController(t)18    mockObject := mock.NewMockInterface(ctrl)19    mockObject.EXPECT().Method1().Return("Hello World")20    result := myFunc(mockObject)21    if result != "Hello World" {22        t.Errorf("Expected result to be 'Hello World', got '%s'", result)23    }

Full Screen

Full Screen

finish

Using AI Code Generation

copy

Full Screen

1import (2func TestHello(t *testing.T) {3        ctrl := gomock.NewController(t)4        defer ctrl.Finish()5        mock := mocks.NewMockHello(ctrl)6        mock.EXPECT().HelloWorld().Return("Hello World")7        fmt.Println(mock.HelloWorld())8}9import (10type Hello interface {11        HelloWorld() string12}13func main() {14        mock := mocks.NewMockHello(nil)15        mock.EXPECT().HelloWorld().Return("Hello World")16        fmt.Println(mock.HelloWorld())17}18import (19type Hello interface {20        HelloWorld() string21}22func main() {23        mock := mocks.NewMockHello(nil)24        mock.EXPECT().HelloWorld().Return("Hello World")25        fmt.Println(mock.HelloWorld())26}27import (28type Hello interface {29        HelloWorld() string30}31func main() {32        mock := mocks.NewMockHello(nil)33        mock.EXPECT().HelloWorld().Return("Hello World")34        fmt.Println(mock.HelloWorld())35}36import (37type Hello interface {38        HelloWorld() string39}40func main() {41        mock := mocks.NewMockHello(nil)42        mock.EXPECT().HelloWorld().Return("Hello World")43        fmt.Println(mock.HelloWorld())44}45import (46type Hello interface {

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful