Best Mock code snippet using gomock.DoAndReturn
manager_test.go
Source:manager_test.go
...53 DataSourceInstanceSettings: &backend.DataSourceInstanceSettings{54 UID: "xyz",55 },56 }57 mockContextGetter.EXPECT().GetPluginContext(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(user *models.SignedInUser, pluginID string, datasourceUID string, skipCache bool) (backend.PluginContext, bool, error) {58 require.Equal(t, int64(2), user.UserId)59 require.Equal(t, int64(1), user.OrgId)60 require.Equal(t, testPluginContext.PluginID, pluginID)61 require.Equal(t, testPluginContext.DataSourceInstanceSettings.UID, datasourceUID)62 return testPluginContext, true, nil63 }).Times(0)64 mockPacketSender.EXPECT().Send("1/test", gomock.Any()).Times(1)65 mockStreamRunner := NewMockStreamRunner(mockCtrl)66 mockStreamRunner.EXPECT().RunStream(67 gomock.Any(), gomock.Any(), gomock.Any(),68 ).DoAndReturn(func(ctx context.Context, req *backend.RunStreamRequest, sender *backend.StreamSender) error {69 require.Equal(t, "test", req.Path)70 close(startedCh)71 err := sender.SendJSON([]byte("{}"))72 require.NoError(t, err)73 <-ctx.Done()74 close(doneCh)75 return ctx.Err()76 }).Times(1)77 result, err := manager.SubmitStream(context.Background(), &models.SignedInUser{UserId: 2, OrgId: 1}, "1/test", "test", testPluginContext, mockStreamRunner, false)78 require.NoError(t, err)79 require.False(t, result.StreamExists)80 // try submit the same.81 result, err = manager.SubmitStream(context.Background(), &models.SignedInUser{UserId: 2, OrgId: 1}, "1/test", "test", backend.PluginContext{}, mockStreamRunner, false)82 require.NoError(t, err)83 require.True(t, result.StreamExists)84 waitWithTimeout(t, startedCh, time.Second)85 require.Len(t, manager.streams, 1)86 cancel()87 waitWithTimeout(t, doneCh, time.Second)88}89func TestStreamManager_SubmitStream_DifferentOrgID(t *testing.T) {90 mockCtrl := gomock.NewController(t)91 defer mockCtrl.Finish()92 mockPacketSender := NewMockChannelSender(mockCtrl)93 mockPresenceGetter := NewMockPresenceGetter(mockCtrl)94 mockContextGetter := NewMockPluginContextGetter(mockCtrl)95 manager := NewManager(mockPacketSender, mockPresenceGetter, mockContextGetter)96 ctx, cancel := context.WithCancel(context.Background())97 defer cancel()98 go func() {99 _ = manager.Run(ctx)100 }()101 startedCh1 := make(chan struct{})102 startedCh2 := make(chan struct{})103 doneCh1 := make(chan struct{})104 doneCh2 := make(chan struct{})105 mockPacketSender.EXPECT().Send("1/test", gomock.Any()).Times(1)106 mockPacketSender.EXPECT().Send("2/test", gomock.Any()).Times(1)107 mockContextGetter.EXPECT().GetPluginContext(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(user *models.SignedInUser, pluginID string, datasourceUID string, skipCache bool) (backend.PluginContext, bool, error) {108 return backend.PluginContext{}, true, nil109 }).Times(0)110 mockStreamRunner1 := NewMockStreamRunner(mockCtrl)111 mockStreamRunner1.EXPECT().RunStream(112 gomock.Any(), gomock.Any(), gomock.Any(),113 ).DoAndReturn(func(ctx context.Context, req *backend.RunStreamRequest, sender *backend.StreamSender) error {114 require.Equal(t, "test", req.Path)115 close(startedCh1)116 err := sender.SendJSON([]byte("{}"))117 require.NoError(t, err)118 <-ctx.Done()119 close(doneCh1)120 return ctx.Err()121 }).Times(1)122 mockStreamRunner2 := NewMockStreamRunner(mockCtrl)123 mockStreamRunner2.EXPECT().RunStream(124 gomock.Any(), gomock.Any(), gomock.Any(),125 ).DoAndReturn(func(ctx context.Context, req *backend.RunStreamRequest, sender *backend.StreamSender) error {126 require.Equal(t, "test", req.Path)127 close(startedCh2)128 err := sender.SendJSON([]byte("{}"))129 require.NoError(t, err)130 <-ctx.Done()131 close(doneCh2)132 return ctx.Err()133 }).Times(1)134 result, err := manager.SubmitStream(context.Background(), &models.SignedInUser{UserId: 2, OrgId: 1}, "1/test", "test", backend.PluginContext{}, mockStreamRunner1, false)135 require.NoError(t, err)136 require.False(t, result.StreamExists)137 // try submit the same channel but different orgID.138 result, err = manager.SubmitStream(context.Background(), &models.SignedInUser{UserId: 2, OrgId: 2}, "2/test", "test", backend.PluginContext{}, mockStreamRunner2, false)139 require.NoError(t, err)140 require.False(t, result.StreamExists)141 waitWithTimeout(t, startedCh1, time.Second)142 waitWithTimeout(t, startedCh2, time.Second)143 require.Len(t, manager.streams, 2)144 cancel()145 waitWithTimeout(t, doneCh1, time.Second)146 waitWithTimeout(t, doneCh2, time.Second)147}148func TestStreamManager_SubmitStream_CloseNoSubscribers(t *testing.T) {149 mockCtrl := gomock.NewController(t)150 defer mockCtrl.Finish()151 mockPacketSender := NewMockChannelSender(mockCtrl)152 mockPresenceGetter := NewMockPresenceGetter(mockCtrl)153 mockContextGetter := NewMockPluginContextGetter(mockCtrl)154 // Create manager with very fast num subscribers checks.155 manager := NewManager(156 mockPacketSender,157 mockPresenceGetter,158 mockContextGetter,159 WithCheckConfig(10*time.Millisecond, 3),160 )161 ctx, cancel := context.WithCancel(context.Background())162 defer cancel()163 go func() {164 _ = manager.Run(ctx)165 }()166 startedCh := make(chan struct{})167 doneCh := make(chan struct{})168 mockContextGetter.EXPECT().GetPluginContext(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(user *models.SignedInUser, pluginID string, datasourceUID string, skipCache bool) (backend.PluginContext, bool, error) {169 return backend.PluginContext{}, true, nil170 }).Times(0)171 mockPresenceGetter.EXPECT().GetNumSubscribers("1/test").Return(0, nil).Times(3)172 mockStreamRunner := NewMockStreamRunner(mockCtrl)173 mockStreamRunner.EXPECT().RunStream(gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(ctx context.Context, req *backend.RunStreamRequest, sender *backend.StreamSender) error {174 close(startedCh)175 <-ctx.Done()176 close(doneCh)177 return ctx.Err()178 }).Times(1)179 _, err := manager.SubmitStream(context.Background(), &models.SignedInUser{UserId: 2, OrgId: 1}, "1/test", "test", backend.PluginContext{}, mockStreamRunner, false)180 require.NoError(t, err)181 waitWithTimeout(t, startedCh, time.Second)182 waitWithTimeout(t, doneCh, time.Second)183 require.Len(t, manager.streams, 0)184}185func TestStreamManager_SubmitStream_ErrorRestartsRunStream(t *testing.T) {186 mockCtrl := gomock.NewController(t)187 defer mockCtrl.Finish()188 mockPacketSender := NewMockChannelSender(mockCtrl)189 mockPresenceGetter := NewMockPresenceGetter(mockCtrl)190 mockContextGetter := NewMockPluginContextGetter(mockCtrl)191 manager := NewManager(mockPacketSender, mockPresenceGetter, mockContextGetter)192 ctx, cancel := context.WithCancel(context.Background())193 defer cancel()194 go func() {195 _ = manager.Run(ctx)196 }()197 numErrors := 3198 currentErrors := 0199 testPluginContext := backend.PluginContext{200 OrgID: 1,201 PluginID: "test-plugin",202 DataSourceInstanceSettings: &backend.DataSourceInstanceSettings{203 UID: "xyz",204 },205 }206 mockContextGetter.EXPECT().GetPluginContext(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(user *models.SignedInUser, pluginID string, datasourceUID string, skipCache bool) (backend.PluginContext, bool, error) {207 require.Equal(t, int64(2), user.UserId)208 require.Equal(t, int64(1), user.OrgId)209 require.Equal(t, testPluginContext.PluginID, pluginID)210 require.Equal(t, testPluginContext.DataSourceInstanceSettings.UID, datasourceUID)211 return testPluginContext, true, nil212 }).Times(numErrors)213 mockStreamRunner := NewMockStreamRunner(mockCtrl)214 mockStreamRunner.EXPECT().RunStream(215 gomock.Any(), gomock.Any(), gomock.Any(),216 ).DoAndReturn(func(ctx context.Context, req *backend.RunStreamRequest, sender *backend.StreamSender) error {217 if currentErrors >= numErrors {218 return nil219 }220 currentErrors++221 return errors.New("boom")222 }).Times(numErrors + 1)223 result, err := manager.SubmitStream(context.Background(), &models.SignedInUser{UserId: 2, OrgId: 1}, "test", "test", testPluginContext, mockStreamRunner, false)224 require.NoError(t, err)225 require.False(t, result.StreamExists)226 waitWithTimeout(t, result.CloseNotify, time.Second)227}228func TestStreamManager_SubmitStream_NilErrorStopsRunStream(t *testing.T) {229 mockCtrl := gomock.NewController(t)230 defer mockCtrl.Finish()231 mockPacketSender := NewMockChannelSender(mockCtrl)232 mockPresenceGetter := NewMockPresenceGetter(mockCtrl)233 mockContextGetter := NewMockPluginContextGetter(mockCtrl)234 manager := NewManager(mockPacketSender, mockPresenceGetter, mockContextGetter)235 ctx, cancel := context.WithCancel(context.Background())236 defer cancel()237 go func() {238 _ = manager.Run(ctx)239 }()240 mockContextGetter.EXPECT().GetPluginContext(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(user *models.SignedInUser, pluginID string, datasourceUID string, skipCache bool) (backend.PluginContext, bool, error) {241 return backend.PluginContext{}, true, nil242 }).Times(0)243 mockStreamRunner := NewMockStreamRunner(mockCtrl)244 mockStreamRunner.EXPECT().RunStream(245 gomock.Any(), gomock.Any(), gomock.Any(),246 ).DoAndReturn(func(ctx context.Context, req *backend.RunStreamRequest, sender *backend.StreamSender) error {247 return nil248 }).Times(1)249 result, err := manager.SubmitStream(context.Background(), &models.SignedInUser{UserId: 2, OrgId: 1}, "test", "test", backend.PluginContext{}, mockStreamRunner, false)250 require.NoError(t, err)251 require.False(t, result.StreamExists)252 waitWithTimeout(t, result.CloseNotify, time.Second)253}254func TestStreamManager_HandleDatasourceUpdate(t *testing.T) {255 mockCtrl := gomock.NewController(t)256 defer mockCtrl.Finish()257 mockPacketSender := NewMockChannelSender(mockCtrl)258 mockPresenceGetter := NewMockPresenceGetter(mockCtrl)259 mockContextGetter := NewMockPluginContextGetter(mockCtrl)260 manager := NewManager(mockPacketSender, mockPresenceGetter, mockContextGetter)261 ctx, cancel := context.WithCancel(context.Background())262 defer cancel()263 go func() {264 _ = manager.Run(ctx)265 }()266 testPluginContext := backend.PluginContext{267 OrgID: 1,268 PluginID: "test-plugin",269 DataSourceInstanceSettings: &backend.DataSourceInstanceSettings{270 UID: "xyz",271 },272 }273 mockContextGetter.EXPECT().GetPluginContext(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(user *models.SignedInUser, pluginID string, datasourceUID string, skipCache bool) (backend.PluginContext, bool, error) {274 require.Equal(t, int64(2), user.UserId)275 require.Equal(t, int64(1), user.OrgId)276 require.Equal(t, testPluginContext.PluginID, pluginID)277 require.Equal(t, testPluginContext.DataSourceInstanceSettings.UID, datasourceUID)278 return testPluginContext, true, nil279 }).Times(1)280 isFirstCall := true281 doneCh1 := make(chan struct{})282 doneCh2 := make(chan struct{})283 mockStreamRunner := NewMockStreamRunner(mockCtrl)284 mockStreamRunner.EXPECT().RunStream(285 gomock.Any(), gomock.Any(), gomock.Any(),286 ).DoAndReturn(func(ctx context.Context, req *backend.RunStreamRequest, sender *backend.StreamSender) error {287 if isFirstCall {288 // first RunStream will wait till context done.289 isFirstCall = false290 close(doneCh1)291 <-ctx.Done()292 return ctx.Err()293 }294 // second RunStream finishes immediately since we are waiting for it below.295 close(doneCh2)296 return nil297 }).Times(2)298 result, err := manager.SubmitStream(context.Background(), &models.SignedInUser{UserId: 2, OrgId: 1}, "test", "test", testPluginContext, mockStreamRunner, false)299 require.NoError(t, err)300 require.False(t, result.StreamExists)301 waitWithTimeout(t, doneCh1, time.Second)302 err = manager.HandleDatasourceUpdate(1, "xyz")303 require.NoError(t, err)304 waitWithTimeout(t, result.CloseNotify, time.Second)305 waitWithTimeout(t, doneCh2, time.Second)306}307func TestStreamManager_HandleDatasourceDelete(t *testing.T) {308 mockCtrl := gomock.NewController(t)309 defer mockCtrl.Finish()310 mockPacketSender := NewMockChannelSender(mockCtrl)311 mockPresenceGetter := NewMockPresenceGetter(mockCtrl)312 mockContextGetter := NewMockPluginContextGetter(mockCtrl)313 manager := NewManager(mockPacketSender, mockPresenceGetter, mockContextGetter)314 ctx, cancel := context.WithCancel(context.Background())315 defer cancel()316 go func() {317 _ = manager.Run(ctx)318 }()319 testPluginContext := backend.PluginContext{320 OrgID: 1,321 PluginID: "test-plugin",322 DataSourceInstanceSettings: &backend.DataSourceInstanceSettings{323 UID: "xyz",324 },325 }326 mockContextGetter.EXPECT().GetPluginContext(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(user *models.SignedInUser, pluginID string, datasourceUID string, skipCache bool) (backend.PluginContext, bool, error) {327 require.Equal(t, int64(2), user.UserId)328 require.Equal(t, int64(1), user.OrgId)329 require.Equal(t, testPluginContext.PluginID, pluginID)330 require.Equal(t, testPluginContext.DataSourceInstanceSettings.UID, datasourceUID)331 return testPluginContext, true, nil332 }).Times(0)333 doneCh := make(chan struct{})334 mockStreamRunner := NewMockStreamRunner(mockCtrl)335 mockStreamRunner.EXPECT().RunStream(336 gomock.Any(), gomock.Any(), gomock.Any(),337 ).DoAndReturn(func(ctx context.Context, req *backend.RunStreamRequest, sender *backend.StreamSender) error {338 close(doneCh)339 <-ctx.Done()340 return ctx.Err()341 }).Times(1)342 result, err := manager.SubmitStream(context.Background(), &models.SignedInUser{UserId: 2, OrgId: 1}, "test", "test", testPluginContext, mockStreamRunner, false)343 require.NoError(t, err)344 require.False(t, result.StreamExists)345 waitWithTimeout(t, doneCh, time.Second)346 err = manager.HandleDatasourceDelete(1, "xyz")347 require.NoError(t, err)348 waitWithTimeout(t, result.CloseNotify, time.Second)349}...
sopsyaml_test.go
Source:sopsyaml_test.go
...15 t.Run("Finds File Immediate", func(t *testing.T) {16 ctrl := gomock.NewController(t)17 defer ctrl.Finish()18 mock := mock_oswrap.NewMockOsWrap(ctrl)19 mock.EXPECT().Stat(gomock.Eq(".sops.yaml")).DoAndReturn(func(c string) (*os.FileInfo, error) {20 return nil, nil21 })22 osWrap = mock23 got, err := FindConfigFile(".")24 if err != nil {25 t.Errorf("FindConfigFile() got err %v", err)26 }27 if got != ".sops.yaml" {28 t.Errorf("FindConfigFile() = %v, want \".sops.yaml\"", got)29 }30 osWrap = origOw31 })32 t.Run("not found after never getting Stat", func(t *testing.T) {33 ctrl := gomock.NewController(t)34 defer ctrl.Finish()35 mock := mock_oswrap.NewMockOsWrap(ctrl)36 mock.EXPECT().Stat(testhelpers.RegexMatches(`^.*\.git$`)).DoAndReturn(func(c string) (*os.FileInfo, error) {37 return nil, fmt.Errorf("Not Found") // Never git38 }).AnyTimes()39 mock.EXPECT().Stat(testhelpers.RegexMatches(`^.*\.sops.yaml$`)).DoAndReturn(func(c string) (*os.FileInfo, error) {40 return nil, fmt.Errorf("Not Found")41 }).AnyTimes()42 osWrap = mock43 _, err := FindConfigFile(".")44 if err == nil {45 t.Errorf("FindConfigFile() expected err")46 }47 osWrap = origOw48 })49 t.Run("levels deep", func(t *testing.T) {50 ctrl := gomock.NewController(t)51 defer ctrl.Finish()52 mock := mock_oswrap.NewMockOsWrap(ctrl)53 mock.EXPECT().Stat(testhelpers.RegexMatches(`^.*\.git$`)).DoAndReturn(func(c string) (*os.FileInfo, error) {54 return nil, fmt.Errorf("Not Found") // Never git55 }).AnyTimes()56 mock.EXPECT().Stat(gomock.Eq(".sops.yaml")).DoAndReturn(func(c string) (*os.FileInfo, error) {57 return nil, fmt.Errorf("Not Found")58 })59 mock.EXPECT().Stat(gomock.Eq("../.sops.yaml")).DoAndReturn(func(c string) (*os.FileInfo, error) {60 return nil, fmt.Errorf("Not Found")61 })62 mock.EXPECT().Stat(gomock.Eq("../../.sops.yaml")).DoAndReturn(func(c string) (*os.FileInfo, error) {63 return nil, nil //found64 })65 osWrap = mock66 got, err := FindConfigFile(".")67 if err != nil {68 t.Errorf("FindConfigFile() got err %v", err)69 }70 if got != "../../.sops.yaml" {71 t.Errorf("FindConfigFile() = %v, want \"../../.sops.yaml\"", got)72 }73 osWrap = origOw74 })75 t.Run("different start", func(t *testing.T) {76 ctrl := gomock.NewController(t)77 defer ctrl.Finish()78 mock := mock_oswrap.NewMockOsWrap(ctrl)79 mock.EXPECT().Stat(testhelpers.RegexMatches(`^.*\.git$`)).DoAndReturn(func(c string) (*os.FileInfo, error) {80 return nil, fmt.Errorf("Not Found") // Never git81 }).AnyTimes()82 mock.EXPECT().Stat(gomock.Not(gomock.Eq("directory/.sops.yaml"))).DoAndReturn(func(c string) (*os.FileInfo, error) {83 return nil, fmt.Errorf("Not Found")84 }).AnyTimes()85 mock.EXPECT().Stat(gomock.Eq("directory/.sops.yaml")).DoAndReturn(func(c string) (*os.FileInfo, error) {86 return nil, nil //found87 })88 osWrap = mock89 got, err := FindConfigFile("directory/here/goes/further/")90 if err != nil {91 t.Errorf("FindConfigFile() got err %v", err)92 }93 if got != "directory/.sops.yaml" {94 t.Errorf("FindConfigFile() = %v, want \"directory/.sops.yaml\"", got)95 }96 osWrap = origOw97 })98 t.Run("stops at git repo", func(t *testing.T) {99 ctrl := gomock.NewController(t)100 defer ctrl.Finish()101 mock := mock_oswrap.NewMockOsWrap(ctrl)102 mock.EXPECT().Stat(gomock.Eq(".git")).DoAndReturn(func(c string) (*os.FileInfo, error) {103 return nil, nil //find git immediately104 })105 mock.EXPECT().Stat(gomock.Eq(".sops.yaml")).DoAndReturn(func(c string) (*os.FileInfo, error) {106 return nil, fmt.Errorf("Not Found")107 })108 osWrap = mock109 _, err := FindConfigFile(".")110 if err == nil {111 t.Errorf("FindConfigFile() expected err")112 }113 osWrap = origOw114 })115}116func TestLoadConfigFile(t *testing.T) {117 origOw := osWrap118 t.Run("file error", func(t *testing.T) {119 ctrl := gomock.NewController(t)120 defer ctrl.Finish()121 mock := mock_oswrap.NewMockOsWrap(ctrl)122 mock.EXPECT().ReadFile(gomock.Eq("filepath")).DoAndReturn(func(c string) ([]byte, error) {123 return nil, fmt.Errorf("a file read error")124 })125 osWrap = mock126 _, err := LoadConfigFile("filepath")127 if err == nil {128 t.Errorf("LoadConfigFile() expected err")129 }130 osWrap = origOw131 })132 t.Run("yaml error", func(t *testing.T) {133 ctrl := gomock.NewController(t)134 defer ctrl.Finish()135 mock := mock_oswrap.NewMockOsWrap(ctrl)136 mock.EXPECT().ReadFile(gomock.Eq("filepath")).DoAndReturn(func(c string) ([]byte, error) {137 yml := []byte(`138 ~~~not yaml139 at all140 `)141 return yml, nil142 })143 osWrap = mock144 _, err := LoadConfigFile("filepath")145 if err == nil {146 t.Fatalf("LoadConfigFile() expected yaml err")147 }148 if !strings.Contains(err.Error(), "unmarshal") {149 t.Fatalf("expected an unmarshal error")150 }151 osWrap = origOw152 })153 t.Run("successful parse", func(t *testing.T) {154 ctrl := gomock.NewController(t)155 defer ctrl.Finish()156 mock := mock_oswrap.NewMockOsWrap(ctrl)157 mock.EXPECT().ReadFile(gomock.Eq("filepath")).DoAndReturn(func(c string) ([]byte, error) {158 yml := []byte(`159yaml:160- in161- a string162`)163 return yml, nil164 })165 osWrap = mock166 yml, err := LoadConfigFile("filepath")167 if err != nil {168 t.Errorf("LoadConfigFile() got err: %v", err)169 }170 stringRep := fmt.Sprintf("%v", yml)171 if stringRep != "&[{yaml [in a string]}]" {172 t.Errorf("LoadConfigFile() = %v, want \"&[{yaml [in a string]}]\"", stringRep)173 }174 osWrap = origOw175 })176}177func TestWriteConfigFile(t *testing.T) {178 origOw := osWrap179 t.Run("cant unmarshal", func(t *testing.T) {180 //TODO what are valid errors here181 t.Skipf("Unsure what would error in yaml yet")182 })183 t.Run("cant write", func(t *testing.T) {184 t.Skipf("Reflection of FileMode is messed up")185 ctrl := gomock.NewController(t)186 defer ctrl.Finish()187 mock := mock_oswrap.NewMockOsWrap(ctrl)188 expected := []byte(`{}189`)190 // expectedMode := os.FileMode(0644)191 mock.EXPECT().WriteFile(gomock.Eq("filepath"), gomock.Eq(expected), gomock.Eq(0644)).DoAndReturn(func(c string, args ...string) error {192 return fmt.Errorf("a file read error")193 })194 osWrap = mock195 yml := make(yaml.MapSlice, 0)196 err := WriteConfigFile("filepath", &yml)197 if err == nil {198 t.Fatalf("WriteConfigFile() expected an error")199 }200 if err.Error() != "Error" {201 t.Fatalf("WriteConfigFile() unexpected error %v", err)202 }203 osWrap = origOw204 })205 t.Run("write", func(t *testing.T) {206 t.Skipf("Reflection of FileMode is messed up")207 yml := yaml.MapSlice{208 yaml.MapItem{Key: "yaml", Value: "one"},209 }210 ctrl := gomock.NewController(t)211 defer ctrl.Finish()212 mock := mock_oswrap.NewMockOsWrap(ctrl)213 expected := []byte(`yaml: one214`)215 mock.EXPECT().WriteFile(gomock.Eq("filepath"), gomock.Eq(expected), gomock.Eq(0644)).DoAndReturn(func(c string, args ...string) error {216 return nil217 })218 osWrap = mock219 err := WriteConfigFile("filepath", &yml)220 if err != nil {221 t.Errorf("WriteConfigFile() unexpected error %v", err)222 }223 osWrap = origOw224 })225}226func unmarshalStringHelper(str string) *yaml.MapSlice {227 var data yaml.MapSlice228 err := (yaml.CommentUnmarshaler{}).Unmarshal([]byte(str), &data)229 if err != nil {230 panic(err)231 }232 return &data233}234func TestExtractConfigEncryptFiles(t *testing.T) {235 type args struct {236 data *yaml.MapSlice237 }238 tests := []struct {239 name string240 args args241 want []string242 wantErr bool243 }{244 {245 name: "encrypted_files not array",246 args: args{data: unmarshalStringHelper("foo: bar\nencrypted_files: nope")},247 want: nil,248 wantErr: true,249 },250 {251 name: "encrypted_files not array of strings",252 args: args{data: unmarshalStringHelper("foo: bar\nencrypted_files: [1, 2, 3]")},253 want: nil,254 wantErr: true,255 },256 {257 name: "encrypted_files element doesn't exist",258 args: args{data: unmarshalStringHelper("foo: bar")},259 want: []string{},260 wantErr: false,261 },262 {263 name: "encrypted_files is empty array",264 args: args{data: unmarshalStringHelper("foo: bar\nencrypted_files: []")},265 want: []string{},266 wantErr: false,267 },268 {269 name: "encrypted_files is array with values",270 args: args{data: unmarshalStringHelper("foo: bar\nencrypted_files:\n - first\n - second")},271 want: []string{"first", "second"},272 wantErr: false,273 },274 }275 for _, tt := range tests {276 t.Run(tt.name, func(t *testing.T) {277 got, err := ExtractConfigEncryptFiles(tt.args.data)278 if (err != nil) != tt.wantErr {279 t.Errorf("ExtractConfigEncryptFiles() error = %v, wantErr %v", err, tt.wantErr)280 return281 }282 if !reflect.DeepEqual(got, tt.want) {283 t.Errorf("ExtractConfigEncryptFiles() = %v, want %v", got, tt.want)284 }285 })286 }287}288func TestGetConfigEncryptFiles(t *testing.T) {289 origOw := osWrap290 t.Run("load a file", func(t *testing.T) {291 ctrl := gomock.NewController(t)292 defer ctrl.Finish()293 mock := mock_oswrap.NewMockOsWrap(ctrl)294 mock.EXPECT().Stat(gomock.Eq(".sops.yaml")).DoAndReturn(func(c string) (*os.FileInfo, error) {295 return nil, nil296 })297 mock.EXPECT().ReadFile(gomock.Eq(".sops.yaml")).DoAndReturn(func(c string) ([]byte, error) {298 yml := []byte(`299foo: bar300encrypted_files:301- one302- two303`)304 return yml, nil305 })306 osWrap = mock307 got, err := GetConfigEncryptFiles(".")308 if err != nil {309 t.Errorf("GetConfigEncryptFiles() got err %v", err)310 }311 expected := []string{"one", "two"}312 if !reflect.DeepEqual(got, expected) {313 t.Errorf("GetConfigEncryptFiles() = %v, want %v", got, expected)314 }315 osWrap = origOw316 })317 t.Run("err on file find", func(t *testing.T) {318 ctrl := gomock.NewController(t)319 defer ctrl.Finish()320 mock := mock_oswrap.NewMockOsWrap(ctrl)321 mock.EXPECT().Stat(gomock.Eq(".git")).DoAndReturn(func(c string) (*os.FileInfo, error) {322 return nil, nil //find git immediately323 }).AnyTimes()324 mock.EXPECT().Stat(gomock.Eq(".sops.yaml")).DoAndReturn(func(c string) (*os.FileInfo, error) {325 return nil, fmt.Errorf("Not Found")326 }).AnyTimes()327 osWrap = mock328 _, err := GetConfigEncryptFiles(".")329 if err == nil {330 t.Errorf("GetConfigEncryptFiles() expected an error")331 }332 osWrap = origOw333 })334 t.Run("err on config load", func(t *testing.T) {335 ctrl := gomock.NewController(t)336 defer ctrl.Finish()337 mock := mock_oswrap.NewMockOsWrap(ctrl)338 mock.EXPECT().Stat(gomock.Eq(".sops.yaml")).DoAndReturn(func(c string) (*os.FileInfo, error) {339 return nil, nil340 })341 mock.EXPECT().ReadFile(gomock.Eq(".sops.yaml")).DoAndReturn(func(c string) ([]byte, error) {342 yml := []byte(`~~not good`)343 return yml, nil344 })345 osWrap = mock346 _, err := GetConfigEncryptFiles(".")347 if err == nil {348 t.Errorf("GetConfigEncryptFiles() expected an error")349 }350 osWrap = origOw351 })352 t.Run("err config extract", func(t *testing.T) {353 ctrl := gomock.NewController(t)354 defer ctrl.Finish()355 mock := mock_oswrap.NewMockOsWrap(ctrl)356 mock.EXPECT().Stat(gomock.Eq(".sops.yaml")).DoAndReturn(func(c string) (*os.FileInfo, error) {357 return nil, nil358 })359 mock.EXPECT().ReadFile(gomock.Eq(".sops.yaml")).DoAndReturn(func(c string) ([]byte, error) {360 yml := []byte(`encrypted_files: [1,2,3]`)361 return yml, nil362 })363 osWrap = mock364 _, err := GetConfigEncryptFiles(".")365 if err == nil {366 t.Errorf("GetConfigEncryptFiles() expected an error")367 }368 osWrap = origOw369 })370}371func TestReplaceConfigEncryptFiles(t *testing.T) {372 type args struct {373 data *yaml.MapSlice374 encFiles []string375 }376 //use string representation for ease377 tests := []struct {378 name string379 args args380 want string381 wantErr bool382 }{383 {384 name: "Replace existing set",385 args: args{386 data: unmarshalStringHelper("foo: bar\nencrypted_files:\n - first\n - second"),387 encFiles: []string{"one", "two"},388 },389 want: "&[{foo bar} {encrypted_files [one two]}]",390 wantErr: false,391 },392 {393 name: "Replace with an empty item",394 args: args{395 data: unmarshalStringHelper("foo: bar\nencrypted_files:\n - first\n - second"),396 encFiles: []string{},397 },398 want: "&[{foo bar} {encrypted_files []}]",399 wantErr: false,400 },401 {402 name: "Replace empty with nonempty",403 args: args{404 data: unmarshalStringHelper("foo: bar\nencrypted_files: []"),405 encFiles: []string{"one", "two"},406 },407 want: "&[{foo bar} {encrypted_files [one two]}]",408 wantErr: false,409 },410 {411 name: "adds new top level key",412 args: args{413 data: unmarshalStringHelper("foo: bar"),414 encFiles: []string{"one", "two"},415 },416 want: "&[{foo bar} {encrypted_files [one two]}]",417 wantErr: false,418 },419 //todo whats the error case here420 }421 for _, tt := range tests {422 t.Run(tt.name, func(t *testing.T) {423 got, err := ReplaceConfigEncryptFiles(tt.args.data, tt.args.encFiles)424 if (err != nil) != tt.wantErr {425 t.Errorf("ReplaceConfigEncryptFiles() error = %v, wantErr %v", err, tt.wantErr)426 return427 }428 if !reflect.DeepEqual(fmt.Sprintf("%v", got), tt.want) {429 t.Errorf("ReplaceConfigEncryptFiles() = %v, want %v", got, tt.want)430 }431 })432 }433}434func TestWriteEncryptFilesToDisk(t *testing.T) {435 origOw := osWrap436 t.Run("write a file", func(t *testing.T) {437 t.Skipf("Reflection of FileMode is messed up")438 ctrl := gomock.NewController(t)439 defer ctrl.Finish()440 mock := mock_oswrap.NewMockOsWrap(ctrl)441 expected := []byte("foo: bar\nencrypted_files:\n- first\n- second\n")442 mock.EXPECT().WriteFile(gomock.Eq("filepath"), gomock.Eq(expected), gomock.Eq(0644)).DoAndReturn(func(c string, args ...string) error {443 return nil444 })445 osWrap = mock446 data := unmarshalStringHelper("foo: bar")447 err := WriteEncryptFilesToDisk("filepath", data, []string{"first", "second"})448 if err != nil {449 t.Errorf("GetConfigEncryptFiles() got err %v", err)450 }451 osWrap = origOw452 })453 t.Run("file write error", func(t *testing.T) {454 t.Skipf("Reflection of FileMode is messed up")455 ctrl := gomock.NewController(t)456 defer ctrl.Finish()457 mock := mock_oswrap.NewMockOsWrap(ctrl)458 expected := []byte("foo: bar\nencrypted_files:\n- first\n- second\n")459 mock.EXPECT().WriteFile(gomock.Eq("filepath"), gomock.Eq(expected), gomock.Eq(0644)).DoAndReturn(func(c string, args ...string) error {460 return fmt.Errorf("some write error")461 })462 osWrap = mock463 data := unmarshalStringHelper("foo: bar")464 err := WriteEncryptFilesToDisk("filepath", data, []string{"first", "second"})465 if err == nil {466 t.Fatalf("GetConfigEncryptFiles() expected an error")467 }468 osWrap = origOw469 })470}...
verifier_info_test.go
Source:verifier_info_test.go
...34 defer ctrl.Finish()35 client = NewMockRpcClient(ctrl)36 client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).Return(errors.New("test"))37 loadDefaultAccountStake()38 client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(result interface{}, method string, args ...interface{}) error {39 *result.(*rpc_interface.CurBalanceResp) = rpc_interface.CurBalanceResp{}40 return nil41 })42 loadDefaultAccountStake()43 client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(result interface{}, method string, args ...interface{}) error {44 *result.(*rpc_interface.CurBalanceResp) = rpc_interface.CurBalanceResp{45 Balance: (*hexutil.Big)(big.NewInt(0)),46 }47 return nil48 })49 loadDefaultAccountStake()50 assert.Equal(t, defaultAccountStake, "0"+consts.CoinDIPName)51 client = nil52}53func TestPrintDefaultAccountStake(t *testing.T) {54 PrintDefaultAccountStake()55}56func TestPrintCommandsModuleName(t *testing.T) {57 PrintCommandsModuleName()58}59func TestAsyncLogElectionTx(t *testing.T) {60 ctrl := gomock.NewController(t)61 defer ctrl.Finish()62 client = NewMockRpcClient(ctrl)63 logElectionTxTickerTime = 1 * time.Millisecond64 SyncStatus.Store(true)65 client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any()).Return(errors.New("test")).AnyTimes()66 timer := AsyncLogElectionTx()67 time.Sleep(2 * time.Millisecond)68 timer.Stop()69 time.Sleep(2 * time.Millisecond)70 client = nil71}72func Test_loadRegistedAccounts(t *testing.T) {73 ctrl := gomock.NewController(t)74 defer ctrl.Finish()75 client = NewMockRpcClient(ctrl)76 client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any()).Return(errors.New("test"))77 loadRegistedAccounts()78 client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any()).DoAndReturn(func(result interface{}, method string, args ...interface{}) error {79 *result.(*[]accounts.WalletIdentifier) = []accounts.WalletIdentifier{80 {},81 }82 return nil83 })84 client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).Return(errors.New("test"))85 loadRegistedAccounts()86 client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any()).DoAndReturn(func(result interface{}, method string, args ...interface{}) error {87 *result.(*[]accounts.WalletIdentifier) = []accounts.WalletIdentifier{88 {},89 }90 return nil91 })92 client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(result interface{}, method string, args ...interface{}) error {93 *result.(*[]accounts.Account) = []accounts.Account{94 {95 Address: common.HexToAddress("0x1234"),96 },97 }98 return nil99 })100 client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).Return(errors.New("test"))101 loadRegistedAccounts()102 client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any()).DoAndReturn(func(result interface{}, method string, args ...interface{}) error {103 *result.(*[]accounts.WalletIdentifier) = []accounts.WalletIdentifier{104 {},105 }106 return nil107 })108 client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(result interface{}, method string, args ...interface{}) error {109 *result.(*[]accounts.Account) = []accounts.Account{110 {111 Address: common.HexToAddress("0x1234"),112 },113 }114 return nil115 })116 client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(result interface{}, method string, args ...interface{}) error {117 *result.(*rpc_interface.VerifierStatus) = rpc_interface.VerifierStatus{118 Status: "Registered",119 }120 return nil121 })122 loadRegistedAccounts()123 client = nil124}125func Test_logElection(t *testing.T) {126 ctrl := gomock.NewController(t)127 defer ctrl.Finish()128 client = NewMockRpcClient(ctrl)129 trackingAccounts = []accounts.Account{}130 logElection()131 trackingAccounts = append(trackingAccounts, accounts.Account{Address: common.HexToAddress("0x1234")})132 client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any()).Return(errors.New("test"))133 logElection()134 client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any()).DoAndReturn(func(result interface{}, method string, args ...interface{}) error {135 *result.(*rpc_interface.BlockResp) = rpc_interface.BlockResp{136 Header: model.Header{137 Bloom: iblt.NewBloom(iblt.NewBloomConfig(8, 4)),138 },139 }140 return nil141 })142 client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).Return(errors.New("test"))143 logElection()144 client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any()).DoAndReturn(func(result interface{}, method string, args ...interface{}) error {145 *result.(*rpc_interface.BlockResp) = rpc_interface.BlockResp{146 Header: model.Header{147 Bloom: iblt.NewBloom(iblt.NewBloomConfig(8, 4)),148 },149 }150 return nil151 })152 client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil)153 client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).Return(errors.New("test"))154 client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).Return(errors.New("test"))155 logElection()156 client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any()).DoAndReturn(func(result interface{}, method string, args ...interface{}) error {157 *result.(*rpc_interface.BlockResp) = rpc_interface.BlockResp{158 Header: model.Header{159 Bloom: iblt.NewBloom(iblt.NewBloomConfig(8, 4)),160 },161 }162 return nil163 })164 client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil)165 client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).Return(errors.New("test"))166 client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(result interface{}, method string, args ...interface{}) error {167 *result.(*rpc_interface.VerifierStatus) = rpc_interface.VerifierStatus{168 Status: VerifierStatusNoRegistered,169 }170 return nil171 })172 logElection()173 client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any()).DoAndReturn(func(result interface{}, method string, args ...interface{}) error {174 *result.(*rpc_interface.BlockResp) = rpc_interface.BlockResp{175 Header: model.Header{176 Bloom: iblt.NewBloom(iblt.NewBloomConfig(8, 4)),177 },178 }179 return nil180 })181 client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil)182 client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).Return(errors.New("test"))183 client.(*MockRpcClient).EXPECT().Call(gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(result interface{}, method string, args ...interface{}) error {184 *result.(*rpc_interface.VerifierStatus) = rpc_interface.VerifierStatus{185 Status: VerifierStatusRegistered,186 }187 return nil188 })189 logElection()190 time.Sleep(1 * time.Millisecond)191 client = nil192}193func Test_isVerifier(t *testing.T) {194 address1 := common.HexToAddress("0x1234")195 address2 := common.HexToAddress("0x1233")196 verifierAddresses := []common.Address{address1}197 assert.Equal(t, isVerifier(address2, verifierAddresses), false)...
DoAndReturn
Using AI Code Generation
1import (2type MockInterface struct {3}4type MockInterfaceMockRecorder struct {5}6func NewMockInterface(ctrl *gomock.Controller) *MockInterface {7 mock := &MockInterface{ctrl: ctrl}8 mock.recorder = &MockInterfaceMockRecorder{mock}9}10func (m *MockInterface) EXPECT() *MockInterfaceMockRecorder {11}12func (m *MockInterface) DoAndReturn(arg0 func() (string, error)) (string, error) {13 m.ctrl.T.Helper()14 ret := m.ctrl.Call(m, "DoAndReturn", arg0)15 ret0, _ := ret[0].(string)16 ret1, _ := ret[1].(error)17}18func (mr *MockInterfaceMockRecorder) DoAndReturn(arg0 interface{}) *gomock.Call {19 mr.mock.ctrl.T.Helper()20 return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DoAndReturn", reflect.TypeOf((*MockInterface)(nil).DoAndReturn), arg0)21}22import (23type MockInterface struct {24}
DoAndReturn
Using AI Code Generation
1import (2func TestDoAndReturn(t *testing.T) {3 ctrl := gomock.NewController(t)4 defer ctrl.Finish()5 mock := NewMockMyInterface(ctrl)6 mock.EXPECT().DoSomething().DoAndReturn(func() string {7 }).Times(2)8 result := mock.DoSomething()9 fmt.Println(result)10 result = mock.DoSomething()11 fmt.Println(result)12}13import (14func TestDoAndReturn(t *testing.T) {15 ctrl := gomock.NewController(t)16 defer ctrl.Finish()17 mock := NewMockMyInterface(ctrl)18 mock.EXPECT().DoSomething().DoAndReturn(func() string {19 }).Times(2)20 result := mock.DoSomething()21 fmt.Println(result)22 result = mock.DoSomething()23 fmt.Println(result)24}25import (26func TestDoAndReturn(t *testing.T) {27 ctrl := gomock.NewController(t)28 defer ctrl.Finish()29 mock := NewMockMyInterface(ctrl)30 mock.EXPECT().DoSomething().DoAndReturn(func() string {31 }).Times(2)32 result := mock.DoSomething()33 fmt.Println(result)34 result = mock.DoSomething()35 fmt.Println(result)
DoAndReturn
Using AI Code Generation
1func (m *MockFoo) DoAndReturn(foo interface{}) *gomock.Call {2 m.ctrl.T.Helper()3 return m.ctrl.RecordCallWithMethodType(m, "DoAndReturn", reflect.TypeOf((*MockFoo)(nil).DoAndReturn), foo)4}5func (m *MockFoo) DoAndReturn(foo interface{}) *gomock.Call {6 m.ctrl.T.Helper()7 return m.ctrl.RecordCallWithMethodType(m, "DoAndReturn", reflect.TypeOf((*MockFoo)(nil).DoAndReturn), foo)8}9type Foo interface {10 Do() interface{}11}12type Foo interface {13 Do() interface{}14}15type MockFoo struct {16}17type MockFooMockRecorder struct {18}19func NewMockFoo(ctrl *gomock.Controller) *MockFoo {20 mock := &MockFoo{ctrl: ctrl}21 mock.recorder = &MockFooMockRecorder{mock}22}23func (m *MockFoo) EXPECT() *MockFooMockRecorder {24}25func (m *MockFoo) Do() interface{} {26 m.ctrl.T.Helper()27 ret := m.ctrl.Call(m, "Do")28 ret0, _ := ret[0].(interface{})29}30func (mr *MockFooMockRecorder) Do() *gomock.Call {31 mr.mock.ctrl.T.Helper()32 return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Do", reflect.TypeOf((*MockFoo)(nil).Do))33}34testing.tRunner.func1(0xc0000f0d00)
DoAndReturn
Using AI Code Generation
1import (2func main() {3 ctrl := gomock.NewController(nil)4 mock := NewMockFoo(ctrl)5 seq := gomock.InOrder(6 mock.EXPECT().Do("hello").DoAndReturn(func(s string) string {7 fmt.Println("Do called with ", s)8 }),9 mock.EXPECT().Do("world").DoAndReturn(func(s string) string {10 fmt.Println("Do called with ", s)11 }),12 fmt.Println(mock.Do("hello"))13 fmt.Println(mock.Do("world"))14 seq.Times(1)15}16import (17func TestDoAndReturn(t *testing.T) {18 ctrl := gomock.NewController(t)19 mock := NewMockFoo(ctrl)20 gomock.InOrder(21 mock.EXPECT().Do("hello").DoAndReturn(func(s string) string {22 }),23 mock.EXPECT().Do("world").DoAndReturn(func(s string) string {24 }),25 if mock.Do("hello") != "hello" {26 t.Error("Expected hello")27 }28 if mock.Do("world") != "world" {29 t.Error("Expected world")30 }31}
DoAndReturn
Using AI Code Generation
1mockCtrl := gomock.NewController(t)2defer mockCtrl.Finish()3mockRepo := NewMockRepository(mockCtrl)4mockRepo.EXPECT().DoAndReturn(gomock.Any(), gomock.Any()).Do(func(arg1, arg2 interface{}) {5}).Return(nil)6mockCtrl := gomock.NewController(t)7defer mockCtrl.Finish()8mockRepo := NewMockRepository(mockCtrl)9mockRepo.EXPECT().DoAndReturn(gomock.Any(), gomock.Any()).Do(func(arg1, arg2 interface{}) {10}).Return(nil)11panic: interface conversion: interface {} is nil, not *mock_repository.MockRepository12main.main()13mockCtrl := gomock.NewController(t)14defer mockCtrl.Finish()15mockRepo := NewMockRepository(mockCtrl)16mockRepo.EXPECT().DoAndReturn(gomock.Any(), gomock.Any()).Do(func(arg1, arg2 interface{}) {17}).Return(nil)18mockRepo.EXPECT().DoAndReturn(gomock.Any(), gomock.Any()).Do(func(arg1, arg2 interface{}) {19}).Return(nil)20panic: interface conversion: interface {} is nil, not *mock_repository.MockRepository21main.main()22import (23type MockRepository struct {24}25type _MockRepositoryRecorder struct {26}27func NewMockRepository(ctrl *gomock.Controller) *
DoAndReturn
Using AI Code Generation
1import (2type Mocked struct {3}4type MockedMockRecorder struct {5}6func NewMocked() *Mocked {7 mock := &Mocked{}8 mock.mock = &MockedMockRecorder{mock}9}10func (_m *MockedMockRecorder) DoAndReturn(arg0 interface{}) *gomock.Call {11}12func (m *Mocked) DoAndReturn(arg0 interface{}) {13 m.mock.DoAndReturn(arg0)14}15func testFunction(arg0 interface{}) {16 fmt.Println("I am in testFunction")17}18func TestDoAndReturn(t *testing.T) {19 ctrl := gomock.NewController(t)20 defer ctrl.Finish()21 mocked := NewMocked()22 mocked.DoAndReturn(testFunction)23}24--- PASS: TestDoAndReturn (0.00s)
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!