Best Mock code snippet using gomock.Nil
user_usecase_test.go
Source:user_usecase_test.go
...134 defer controller.Finish()135 mockUserRepository := mock_user.NewMockRepository(controller)136 userUsecase := usecase.NewUserUsecaseImpl(mockUserRepository)137 dateTimeDep, err := timestamps.NewDateTime("10.11.2021 18:10")138 assert.Nil(t, err)139 dateTimeArr, err := timestamps.NewDateTime("10.11.2021 18:15")140 assert.Nil(t, err)141 routeTmp := &models.RouteTmp{142 UserAuthorId: 101,143 LocDep: "ÐоÑпÑÑ ÐнеÑго",144 LocArr: "ÐоÑпÑÑ Ð£ÐÐ",145 MinPrice: 500,146 DateTimeDep: *dateTimeDep,147 DateTimeArr: *dateTimeArr,148 }149 expectedRouteTmp := &models.RouteTmp{150 Id: 1,151 UserAuthorId: routeTmp.UserAuthorId,152 LocDep: routeTmp.LocDep,153 LocArr: routeTmp.LocArr,154 MinPrice: routeTmp.MinPrice,155 DateTimeDep: routeTmp.DateTimeDep,156 DateTimeArr: routeTmp.DateTimeArr,157 }158 mockUserRepository.159 EXPECT().160 InsertRouteTmp(gomock.Eq(routeTmp)).161 DoAndReturn(func(routeTmp *models.RouteTmp) (*models.RouteTmp, error) {162 routeTmp.Id = expectedRouteTmp.Id163 return routeTmp, nil164 })165 response_ := userUsecase.CreateRouteTmp(routeTmp)166 assert.Equal(t, response.NewResponse(consts.Created, expectedRouteTmp), response_)167}168func TestUserUsecase_GetRouteTmp(t *testing.T) {169 controller := gomock.NewController(t)170 defer controller.Finish()171 mockUserRepository := mock_user.NewMockRepository(controller)172 userUsecase := usecase.NewUserUsecaseImpl(mockUserRepository)173 dateTimeDep, err := timestamps.NewDateTime("13.11.2021 11:45")174 assert.Nil(t, err)175 dateTimeArr, err := timestamps.NewDateTime("13.11.2021 11:50")176 assert.Nil(t, err)177 expectedRouteTmp := &models.RouteTmp{178 Id: 1,179 UserAuthorId: 101,180 LocDep: "ÐоÑпÑÑ ÐнеÑго",181 LocArr: "ÐоÑпÑÑ Ð£ÐÐ",182 MinPrice: 500,183 DateTimeDep: *dateTimeDep,184 DateTimeArr: *dateTimeArr,185 }186 mockUserRepository.187 EXPECT().188 SelectRouteTmp(gomock.Eq(expectedRouteTmp.Id)).189 Return(expectedRouteTmp, nil)190 response_ := userUsecase.GetRouteTmp(expectedRouteTmp.UserAuthorId, expectedRouteTmp.Id)191 assert.Equal(t, response.NewResponse(consts.OK, expectedRouteTmp), response_)192}193func TestUserUsecase_GetRouteTmp_forbidden(t *testing.T) {194 controller := gomock.NewController(t)195 defer controller.Finish()196 mockUserRepository := mock_user.NewMockRepository(controller)197 userUsecase := usecase.NewUserUsecaseImpl(mockUserRepository)198 dateTimeDep, err := timestamps.NewDateTime("13.11.2021 11:45")199 assert.Nil(t, err)200 dateTimeArr, err := timestamps.NewDateTime("13.11.2021 11:50")201 assert.Nil(t, err)202 expectedRouteTmp := &models.RouteTmp{203 Id: 1,204 UserAuthorId: 101,205 LocDep: "ÐоÑпÑÑ ÐнеÑго",206 LocArr: "ÐоÑпÑÑ Ð£ÐÐ",207 MinPrice: 500,208 DateTimeDep: *dateTimeDep,209 DateTimeArr: *dateTimeArr,210 }211 mockUserRepository.212 EXPECT().213 SelectRouteTmp(gomock.Eq(expectedRouteTmp.Id)).214 Return(expectedRouteTmp, nil)215 response_ := userUsecase.GetRouteTmp(expectedRouteTmp.UserAuthorId+1, expectedRouteTmp.Id)216 assert.Equal(t, response.NewEmptyResponse(consts.Forbidden), response_)217}218func TestUserUsecase_GetRouteTmp_notFound(t *testing.T) {219 controller := gomock.NewController(t)220 defer controller.Finish()221 mockUserRepository := mock_user.NewMockRepository(controller)222 userUsecase := usecase.NewUserUsecaseImpl(mockUserRepository)223 const userId uint32 = 101224 const routeTmpId uint32 = 1225 mockUserRepository.226 EXPECT().227 SelectRouteTmp(gomock.Eq(routeTmpId)).228 Return(nil, consts.RepErrNotFound)229 response_ := userUsecase.GetRouteTmp(userId, routeTmpId)230 assert.Equal(t, response.NewEmptyResponse(consts.NotFound), response_)231}232func TestUserUsecase_UpdateRouteTmp(t *testing.T) {233 controller := gomock.NewController(t)234 defer controller.Finish()235 mockUserRepository := mock_user.NewMockRepository(controller)236 userUsecase := usecase.NewUserUsecaseImpl(mockUserRepository)237 dateTimeDep1, err := timestamps.NewDateTime("13.11.2021 13:50")238 assert.Nil(t, err)239 dateTimeArr1, err := timestamps.NewDateTime("13.11.2021 13:55")240 assert.Nil(t, err)241 routeTmp := &models.RouteTmp{242 Id: 1,243 UserAuthorId: 101,244 LocDep: "ÐбÑежиÑие â10",245 LocArr: "УÐÐ",246 MinPrice: 500,247 DateTimeDep: *dateTimeDep1,248 DateTimeArr: *dateTimeArr1,249 }250 dateTimeDep2, err := timestamps.NewDateTime("13.11.2021 14:00")251 assert.Nil(t, err)252 dateTimeArr2, err := timestamps.NewDateTime("13.11.2021 14:05")253 assert.Nil(t, err)254 expectedRouteTmp := &models.RouteTmp{255 Id: routeTmp.Id,256 UserAuthorId: routeTmp.UserAuthorId,257 LocDep: "ÐбÑежиÑие â9",258 LocArr: "СÐ",259 MinPrice: 600,260 DateTimeDep: *dateTimeDep2,261 DateTimeArr: *dateTimeArr2,262 }263 call := mockUserRepository.264 EXPECT().265 SelectRouteTmp(gomock.Eq(routeTmp.Id)).266 Return(routeTmp, nil)267 mockUserRepository.268 EXPECT().269 UpdateRouteTmp(gomock.Eq(expectedRouteTmp)).270 Return(expectedRouteTmp, nil).271 After(call)272 response_ := userUsecase.UpdateRouteTmp(expectedRouteTmp)273 assert.Equal(t, response.NewResponse(consts.OK, expectedRouteTmp), response_)274}275func TestUserUsecase_UpdateRouteTmp_forbidden(t *testing.T) {276 controller := gomock.NewController(t)277 defer controller.Finish()278 mockUserRepository := mock_user.NewMockRepository(controller)279 userUsecase := usecase.NewUserUsecaseImpl(mockUserRepository)280 dateTimeDep1, err := timestamps.NewDateTime("13.11.2021 13:50")281 assert.Nil(t, err)282 dateTimeArr1, err := timestamps.NewDateTime("13.11.2021 13:55")283 assert.Nil(t, err)284 routeTmp := &models.RouteTmp{285 Id: 1,286 UserAuthorId: 101,287 LocDep: "ÐбÑежиÑие â10",288 LocArr: "УÐÐ",289 MinPrice: 500,290 DateTimeDep: *dateTimeDep1,291 DateTimeArr: *dateTimeArr1,292 }293 dateTimeDep2, err := timestamps.NewDateTime("13.11.2021 14:00")294 assert.Nil(t, err)295 dateTimeArr2, err := timestamps.NewDateTime("13.11.2021 14:05")296 assert.Nil(t, err)297 expectedRouteTmp := &models.RouteTmp{298 Id: routeTmp.Id,299 UserAuthorId: 102,300 LocDep: "ÐбÑежиÑие â9",301 LocArr: "СÐ",302 MinPrice: 600,303 DateTimeDep: *dateTimeDep2,304 DateTimeArr: *dateTimeArr2,305 }306 mockUserRepository.307 EXPECT().308 SelectRouteTmp(gomock.Eq(routeTmp.Id)).309 Return(routeTmp, nil)310 response_ := userUsecase.UpdateRouteTmp(expectedRouteTmp)311 assert.Equal(t, response.NewEmptyResponse(consts.Forbidden), response_)312}313func TestUserUsecase_UpdateRouteTmp_notFound(t *testing.T) {314 controller := gomock.NewController(t)315 defer controller.Finish()316 mockUserRepository := mock_user.NewMockRepository(controller)317 userUsecase := usecase.NewUserUsecaseImpl(mockUserRepository)318 dateTimeDep, err := timestamps.NewDateTime("13.11.2021 13:55")319 assert.Nil(t, err)320 dateTimeArr, err := timestamps.NewDateTime("13.11.2021 14:00")321 assert.Nil(t, err)322 routeTmp := &models.RouteTmp{323 Id: 1,324 UserAuthorId: 101,325 LocDep: "ÐоÑпÑÑ ÐнеÑго",326 LocArr: "ÐоÑпÑÑ Ð£ÐÐ",327 MinPrice: 500,328 DateTimeDep: *dateTimeDep,329 DateTimeArr: *dateTimeArr,330 }331 mockUserRepository.332 EXPECT().333 SelectRouteTmp(gomock.Eq(routeTmp.Id)).334 Return(nil, consts.RepErrNotFound)335 response_ := userUsecase.UpdateRouteTmp(routeTmp)336 assert.Equal(t, response.NewEmptyResponse(consts.NotFound), response_)337}338func TestUserUsecase_DeleteRouteTmp(t *testing.T) {339 controller := gomock.NewController(t)340 defer controller.Finish()341 mockUserRepository := mock_user.NewMockRepository(controller)342 userUsecase := usecase.NewUserUsecaseImpl(mockUserRepository)343 dateTimeDep, err := timestamps.NewDateTime("13.11.2021 17:20")344 assert.Nil(t, err)345 dateTimeArr, err := timestamps.NewDateTime("13.11.2021 17:25")346 assert.Nil(t, err)347 expectedRouteTmp := &models.RouteTmp{348 Id: 1,349 UserAuthorId: 101,350 LocDep: "ÐоÑпÑÑ ÐнеÑго",351 LocArr: "ÐоÑпÑÑ Ð£ÐÐ",352 MinPrice: 500,353 DateTimeDep: *dateTimeDep,354 DateTimeArr: *dateTimeArr,355 }356 call := mockUserRepository.357 EXPECT().358 SelectRouteTmp(gomock.Eq(expectedRouteTmp.Id)).359 Return(expectedRouteTmp, nil)360 mockUserRepository.361 EXPECT().362 DeleteRouteTmp(gomock.Eq(expectedRouteTmp.Id)).363 Return(expectedRouteTmp, nil).364 After(call)365 response_ := userUsecase.DeleteRouteTmp(expectedRouteTmp.UserAuthorId, expectedRouteTmp.Id)366 assert.Equal(t, response.NewResponse(consts.OK, expectedRouteTmp), response_)367}368func TestUserUsecase_DeleteRouteTmp_forbidden(t *testing.T) {369 controller := gomock.NewController(t)370 defer controller.Finish()371 mockUserRepository := mock_user.NewMockRepository(controller)372 userUsecase := usecase.NewUserUsecaseImpl(mockUserRepository)373 dateTimeDep, err := timestamps.NewDateTime("13.11.2021 17:20")374 assert.Nil(t, err)375 dateTimeArr, err := timestamps.NewDateTime("13.11.2021 17:25")376 assert.Nil(t, err)377 expectedRouteTmp := &models.RouteTmp{378 Id: 1,379 UserAuthorId: 101,380 LocDep: "ÐоÑпÑÑ ÐнеÑго",381 LocArr: "ÐоÑпÑÑ Ð£ÐÐ",382 MinPrice: 500,383 DateTimeDep: *dateTimeDep,384 DateTimeArr: *dateTimeArr,385 }386 mockUserRepository.387 EXPECT().388 SelectRouteTmp(gomock.Eq(expectedRouteTmp.Id)).389 Return(expectedRouteTmp, nil)390 response_ := userUsecase.DeleteRouteTmp(expectedRouteTmp.UserAuthorId+1, expectedRouteTmp.Id)391 assert.Equal(t, response.NewEmptyResponse(consts.Forbidden), response_)392}393func TestUserUsecase_DeleteRouteTmp_notFound(t *testing.T) {394 controller := gomock.NewController(t)395 defer controller.Finish()396 mockUserRepository := mock_user.NewMockRepository(controller)397 userUsecase := usecase.NewUserUsecaseImpl(mockUserRepository)398 const routeTmpId uint32 = 1399 const userAuthorId uint32 = 101400 mockUserRepository.401 EXPECT().402 SelectRouteTmp(gomock.Eq(routeTmpId)).403 Return(nil, consts.RepErrNotFound)404 response_ := userUsecase.DeleteRouteTmp(userAuthorId, routeTmpId)405 assert.Equal(t, response.NewEmptyResponse(consts.NotFound), response_)406}407func TestUserUsecase_ListRouteTmp(t *testing.T) {408 controller := gomock.NewController(t)409 defer controller.Finish()410 mockUserRepository := mock_user.NewMockRepository(controller)411 userUsecase := usecase.NewUserUsecaseImpl(mockUserRepository)412 const userId uint32 = 101413 dateTimeDep1, err := timestamps.NewDateTime("17.11.2021 10:25")414 assert.Nil(t, err)415 dateTimeArr1, err := timestamps.NewDateTime("17.11.2021 10:30")416 assert.Nil(t, err)417 dateTimeDep2, err := timestamps.NewDateTime("17.11.2021 10:35")418 assert.Nil(t, err)419 dateTimeArr2, err := timestamps.NewDateTime("17.11.2021 10:40")420 assert.Nil(t, err)421 expectedRoutesTmp := &models.RoutesTmp{422 &models.RouteTmp{423 Id: 1,424 UserAuthorId: userId,425 LocDep: "ÐбÑежиÑие â10",426 LocArr: "УÐÐ",427 MinPrice: 500,428 DateTimeDep: *dateTimeDep1,429 DateTimeArr: *dateTimeArr1,430 },431 &models.RouteTmp{432 Id: 2,433 UserAuthorId: userId,434 LocDep: "ÐбÑежиÑие â9",435 LocArr: "СÐ",436 MinPrice: 600,437 DateTimeDep: *dateTimeDep2,438 DateTimeArr: *dateTimeArr2,439 },440 }441 mockUserRepository.442 EXPECT().443 SelectRouteTmpArrayByUserAuthorId(gomock.Eq(userId)).444 Return(expectedRoutesTmp, nil)445 response_ := userUsecase.ListRouteTmp(userId)446 assert.Equal(t, response.NewResponse(consts.OK, expectedRoutesTmp), response_)447}448func TestUserUsecase_CreateRoutePerm(t *testing.T) {449 controller := gomock.NewController(t)450 defer controller.Finish()451 mockUserRepository := mock_user.NewMockRepository(controller)452 userUsecase := usecase.NewUserUsecaseImpl(mockUserRepository)453 timeDep, err := timestamps.NewTime("12:30")454 assert.Nil(t, err)455 timeArr, err := timestamps.NewTime("12:35")456 assert.Nil(t, err)457 routePerm := &models.RoutePerm{458 UserAuthorId: 2,459 LocDep: "ÐоÑпÑÑ ÐнеÑго",460 LocArr: "ÐоÑпÑÑ Ð£ÐÐ",461 MinPrice: 500,462 EvenWeek: true,463 OddWeek: false,464 DayOfWeek: timestamps.DayOfWeekWednesday,465 TimeDep: *timeDep,466 TimeArr: *timeArr,467 }468 expectedRoutePerm := &models.RoutePerm{469 Id: 1,470 UserAuthorId: routePerm.UserAuthorId,471 LocDep: routePerm.LocDep,472 LocArr: routePerm.LocArr,473 MinPrice: routePerm.MinPrice,474 EvenWeek: routePerm.EvenWeek,475 OddWeek: routePerm.OddWeek,476 DayOfWeek: routePerm.DayOfWeek,477 TimeDep: routePerm.TimeDep,478 TimeArr: routePerm.TimeArr,479 }480 mockUserRepository.481 EXPECT().482 InsertRoutePerm(gomock.Eq(routePerm)).483 DoAndReturn(func(routePerm *models.RoutePerm) (*models.RoutePerm, error) {484 routePerm.Id = expectedRoutePerm.Id485 return routePerm, nil486 })487 response_ := userUsecase.CreateRoutePerm(routePerm)488 assert.Equal(t, response.NewResponse(consts.Created, expectedRoutePerm), response_)489}490func TestUserUsecase_GetRoutePerm(t *testing.T) {491 controller := gomock.NewController(t)492 defer controller.Finish()493 mockUserRepository := mock_user.NewMockRepository(controller)494 userUsecase := usecase.NewUserUsecaseImpl(mockUserRepository)495 timeDep, err := timestamps.NewTime("15:00")496 assert.Nil(t, err)497 timeArr, err := timestamps.NewTime("15:05")498 assert.Nil(t, err)499 expectedRoutePerm := &models.RoutePerm{500 Id: 1,501 UserAuthorId: 101,502 LocDep: "ÐоÑпÑÑ ÐнеÑго",503 LocArr: "ÐоÑпÑÑ Ð£ÐÐ",504 MinPrice: 500,505 EvenWeek: true,506 OddWeek: false,507 DayOfWeek: timestamps.DayOfWeekWednesday,508 TimeDep: *timeDep,509 TimeArr: *timeArr,510 }511 mockUserRepository.512 EXPECT().513 SelectRoutePerm(gomock.Eq(expectedRoutePerm.Id)).514 Return(expectedRoutePerm, nil)515 response_ := userUsecase.GetRoutePerm(expectedRoutePerm.UserAuthorId, expectedRoutePerm.Id)516 assert.Equal(t, response.NewResponse(consts.OK, expectedRoutePerm), response_)517}518func TestUserUsecase_GetRoutePerm_forbidden(t *testing.T) {519 controller := gomock.NewController(t)520 defer controller.Finish()521 mockUserRepository := mock_user.NewMockRepository(controller)522 userUsecase := usecase.NewUserUsecaseImpl(mockUserRepository)523 timeDep, err := timestamps.NewTime("15:00")524 assert.Nil(t, err)525 timeArr, err := timestamps.NewTime("15:05")526 assert.Nil(t, err)527 expectedRoutePerm := &models.RoutePerm{528 Id: 1,529 UserAuthorId: 101,530 LocDep: "ÐоÑпÑÑ ÐнеÑго",531 LocArr: "ÐоÑпÑÑ Ð£ÐÐ",532 MinPrice: 500,533 EvenWeek: true,534 OddWeek: false,535 DayOfWeek: timestamps.DayOfWeekWednesday,536 TimeDep: *timeDep,537 TimeArr: *timeArr,538 }539 mockUserRepository.540 EXPECT().541 SelectRoutePerm(gomock.Eq(expectedRoutePerm.Id)).542 Return(expectedRoutePerm, nil)543 response_ := userUsecase.GetRoutePerm(expectedRoutePerm.UserAuthorId+1, expectedRoutePerm.Id)544 assert.Equal(t, response.NewEmptyResponse(consts.Forbidden), response_)545}546func TestUserUsecase_GetRoutePerm_notFound(t *testing.T) {547 controller := gomock.NewController(t)548 defer controller.Finish()549 mockUserRepository := mock_user.NewMockRepository(controller)550 userUsecase := usecase.NewUserUsecaseImpl(mockUserRepository)551 const userId uint32 = 101552 const routePermId uint32 = 1553 mockUserRepository.554 EXPECT().555 SelectRoutePerm(gomock.Eq(routePermId)).556 Return(nil, consts.RepErrNotFound)557 response_ := userUsecase.GetRoutePerm(userId, routePermId)558 assert.Equal(t, response.NewEmptyResponse(consts.NotFound), response_)559}560func TestUserUsecase_UpdateRoutePerm(t *testing.T) {561 controller := gomock.NewController(t)562 defer controller.Finish()563 mockUserRepository := mock_user.NewMockRepository(controller)564 userUsecase := usecase.NewUserUsecaseImpl(mockUserRepository)565 timeDep1, err := timestamps.NewTime("16:20")566 assert.Nil(t, err)567 timeArr1, err := timestamps.NewTime("16:25")568 assert.Nil(t, err)569 routePerm := &models.RoutePerm{570 Id: 1,571 UserAuthorId: 101,572 LocDep: "ÐбÑежиÑие â10",573 LocArr: "УÐÐ",574 MinPrice: 500,575 EvenWeek: true,576 OddWeek: false,577 DayOfWeek: timestamps.DayOfWeekWednesday,578 TimeDep: *timeDep1,579 TimeArr: *timeArr1,580 }581 timeDep2, err := timestamps.NewTime("16:30")582 assert.Nil(t, err)583 timeArr2, err := timestamps.NewTime("16:35")584 assert.Nil(t, err)585 expectedRoutePerm := &models.RoutePerm{586 Id: 1,587 UserAuthorId: routePerm.UserAuthorId,588 LocDep: "ÐбÑежиÑие â9",589 LocArr: "СÐ",590 MinPrice: 600,591 EvenWeek: false,592 OddWeek: true,593 DayOfWeek: timestamps.DayOfWeekSaturday,594 TimeDep: *timeDep2,595 TimeArr: *timeArr2,596 }597 call := mockUserRepository.598 EXPECT().599 SelectRoutePerm(gomock.Eq(routePerm.Id)).600 Return(routePerm, nil)601 mockUserRepository.602 EXPECT().603 UpdateRoutePerm(gomock.Eq(expectedRoutePerm)).604 Return(expectedRoutePerm, nil).605 After(call)606 response_ := userUsecase.UpdateRoutePerm(expectedRoutePerm)607 assert.Equal(t, response.NewResponse(consts.OK, expectedRoutePerm), response_)608}609func TestUserUsecase_UpdateRoutePerm_forbidden(t *testing.T) {610 controller := gomock.NewController(t)611 defer controller.Finish()612 mockUserRepository := mock_user.NewMockRepository(controller)613 userUsecase := usecase.NewUserUsecaseImpl(mockUserRepository)614 timeDep1, err := timestamps.NewTime("16:20")615 assert.Nil(t, err)616 timeArr1, err := timestamps.NewTime("16:25")617 assert.Nil(t, err)618 routePerm := &models.RoutePerm{619 Id: 1,620 UserAuthorId: 101,621 LocDep: "ÐбÑежиÑие â10",622 LocArr: "УÐÐ",623 MinPrice: 500,624 EvenWeek: true,625 OddWeek: false,626 DayOfWeek: timestamps.DayOfWeekWednesday,627 TimeDep: *timeDep1,628 TimeArr: *timeArr1,629 }630 timeDep2, err := timestamps.NewTime("16:30")631 assert.Nil(t, err)632 timeArr2, err := timestamps.NewTime("16:35")633 assert.Nil(t, err)634 expectedRoutePerm := &models.RoutePerm{635 Id: routePerm.Id,636 UserAuthorId: 102,637 LocDep: "ÐбÑежиÑие â9",638 LocArr: "СÐ",639 MinPrice: 600,640 EvenWeek: false,641 OddWeek: true,642 DayOfWeek: timestamps.DayOfWeekSaturday,643 TimeDep: *timeDep2,644 TimeArr: *timeArr2,645 }646 mockUserRepository.647 EXPECT().648 SelectRoutePerm(gomock.Eq(routePerm.Id)).649 Return(routePerm, nil)650 response_ := userUsecase.UpdateRoutePerm(expectedRoutePerm)651 assert.Equal(t, response.NewEmptyResponse(consts.Forbidden), response_)652}653func TestUserUsecase_UpdateRoutePerm_notFound(t *testing.T) {654 controller := gomock.NewController(t)655 defer controller.Finish()656 mockUserRepository := mock_user.NewMockRepository(controller)657 userUsecase := usecase.NewUserUsecaseImpl(mockUserRepository)658 timeDep, err := timestamps.NewTime("15:00")659 assert.Nil(t, err)660 timeArr, err := timestamps.NewTime("15:05")661 assert.Nil(t, err)662 routePerm := &models.RoutePerm{663 Id: 1,664 UserAuthorId: 101,665 LocDep: "ÐоÑпÑÑ ÐнеÑго",666 LocArr: "ÐоÑпÑÑ Ð£ÐÐ",667 MinPrice: 500,668 EvenWeek: true,669 OddWeek: false,670 DayOfWeek: timestamps.DayOfWeekWednesday,671 TimeDep: *timeDep,672 TimeArr: *timeArr,673 }674 mockUserRepository.675 EXPECT().676 SelectRoutePerm(gomock.Eq(routePerm.Id)).677 Return(nil, consts.RepErrNotFound)678 response_ := userUsecase.UpdateRoutePerm(routePerm)679 assert.Equal(t, response.NewEmptyResponse(consts.NotFound), response_)680}681func TestUserUsecase_DeleteRoutePerm(t *testing.T) {682 controller := gomock.NewController(t)683 defer controller.Finish()684 mockUserRepository := mock_user.NewMockRepository(controller)685 userUsecase := usecase.NewUserUsecaseImpl(mockUserRepository)686 timeDep, err := timestamps.NewTime("15:00")687 assert.Nil(t, err)688 timeArr, err := timestamps.NewTime("15:05")689 assert.Nil(t, err)690 expectedRoutePerm := &models.RoutePerm{691 Id: 1,692 UserAuthorId: 101,693 LocDep: "ÐоÑпÑÑ ÐнеÑго",694 LocArr: "ÐоÑпÑÑ Ð£ÐÐ",695 MinPrice: 500,696 EvenWeek: true,697 OddWeek: false,698 DayOfWeek: timestamps.DayOfWeekWednesday,699 TimeDep: *timeDep,700 TimeArr: *timeArr,701 }702 call := mockUserRepository.703 EXPECT().704 SelectRoutePerm(gomock.Eq(expectedRoutePerm.Id)).705 Return(expectedRoutePerm, nil)706 mockUserRepository.707 EXPECT().708 DeleteRoutePerm(gomock.Eq(expectedRoutePerm.Id)).709 Return(expectedRoutePerm, nil).710 After(call)711 response_ := userUsecase.DeleteRoutePerm(expectedRoutePerm.UserAuthorId, expectedRoutePerm.Id)712 assert.Equal(t, response.NewResponse(consts.OK, expectedRoutePerm), response_)713}714func TestUserUsecase_DeleteRoutePerm_forbidden(t *testing.T) {715 controller := gomock.NewController(t)716 defer controller.Finish()717 mockUserRepository := mock_user.NewMockRepository(controller)718 userUsecase := usecase.NewUserUsecaseImpl(mockUserRepository)719 timeDep, err := timestamps.NewTime("15:00")720 assert.Nil(t, err)721 timeArr, err := timestamps.NewTime("15:05")722 assert.Nil(t, err)723 expectedRoutePerm := &models.RoutePerm{724 Id: 1,725 UserAuthorId: 101,726 LocDep: "ÐоÑпÑÑ ÐнеÑго",727 LocArr: "ÐоÑпÑÑ Ð£ÐÐ",728 MinPrice: 500,729 EvenWeek: true,730 OddWeek: false,731 DayOfWeek: timestamps.DayOfWeekWednesday,732 TimeDep: *timeDep,733 TimeArr: *timeArr,734 }735 mockUserRepository.736 EXPECT().737 SelectRoutePerm(gomock.Eq(expectedRoutePerm.Id)).738 Return(expectedRoutePerm, nil)739 response_ := userUsecase.DeleteRoutePerm(expectedRoutePerm.UserAuthorId+1, expectedRoutePerm.Id)740 assert.Equal(t, response.NewEmptyResponse(consts.Forbidden), response_)741}742func TestUserUsecase_DeleteRoutePerm_notFound(t *testing.T) {743 controller := gomock.NewController(t)744 defer controller.Finish()745 mockUserRepository := mock_user.NewMockRepository(controller)746 userUsecase := usecase.NewUserUsecaseImpl(mockUserRepository)747 const routePermId uint32 = 1748 const userAuthorId uint32 = 101749 mockUserRepository.750 EXPECT().751 SelectRoutePerm(gomock.Eq(routePermId)).752 Return(nil, consts.RepErrNotFound)753 response_ := userUsecase.DeleteRoutePerm(userAuthorId, routePermId)754 assert.Equal(t, response.NewEmptyResponse(consts.NotFound), response_)755}756func TestUserUsecase_ListRoutePerm(t *testing.T) {757 controller := gomock.NewController(t)758 defer controller.Finish()759 mockUserRepository := mock_user.NewMockRepository(controller)760 userUsecase := usecase.NewUserUsecaseImpl(mockUserRepository)761 const userId uint32 = 101762 timeDep1, err := timestamps.NewTime("17:30")763 assert.Nil(t, err)764 timeArr1, err := timestamps.NewTime("17:35")765 assert.Nil(t, err)766 timeDep2, err := timestamps.NewTime("17:40")767 assert.Nil(t, err)768 timeArr2, err := timestamps.NewTime("17:45")769 assert.Nil(t, err)770 expectedRoutesPerm := &models.RoutesPerm{771 &models.RoutePerm{772 Id: 1,773 UserAuthorId: userId,774 LocDep: "ÐбÑежиÑие â10",775 LocArr: "УÐÐ",776 MinPrice: 500,777 EvenWeek: true,778 OddWeek: false,779 DayOfWeek: timestamps.DayOfWeekWednesday,780 TimeDep: *timeDep1,781 TimeArr: *timeArr1,782 },783 &models.RoutePerm{...
snapshot_restore_test.go
Source:snapshot_restore_test.go
...137 Name: "snapshot",138 },139 },140 },141 errChecker: IsNil,142 },143 { // no cleanup144 kubeCli: fake.NewSimpleClientset(),145 dynCli: fakedynamic.NewSimpleDynamicClient(runtime.NewScheme()),146 args: &types.CSISnapshotRestoreArgs{147 Cleanup: false,148 },149 prepare: func(f *fields) {150 gomock.InOrder(151 f.stepperOps.EXPECT().ValidateArgs(gomock.Any(), gomock.Any()).Return(nil),152 f.stepperOps.EXPECT().CreateApplication(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, nil, nil),153 f.stepperOps.EXPECT().ValidateData(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil),154 f.stepperOps.EXPECT().SnapshotApplication(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, nil),155 f.stepperOps.EXPECT().RestoreApplication(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, nil, nil),156 f.stepperOps.EXPECT().ValidateData(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil),157 )158 },159 result: &types.CSISnapshotRestoreResults{},160 errChecker: IsNil,161 },162 { // restored data validation fails163 kubeCli: fake.NewSimpleClientset(),164 dynCli: fakedynamic.NewSimpleDynamicClient(runtime.NewScheme()),165 args: &types.CSISnapshotRestoreArgs{166 Cleanup: false,167 },168 prepare: func(f *fields) {169 gomock.InOrder(170 f.stepperOps.EXPECT().ValidateArgs(gomock.Any(), gomock.Any()).Return(nil),171 f.stepperOps.EXPECT().CreateApplication(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, nil, nil),172 f.stepperOps.EXPECT().ValidateData(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil),173 f.stepperOps.EXPECT().SnapshotApplication(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, nil),174 f.stepperOps.EXPECT().RestoreApplication(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, nil, nil),175 f.stepperOps.EXPECT().ValidateData(gomock.Any(), gomock.Any(), gomock.Any()).Return(fmt.Errorf("validation error")),176 )177 },178 result: &types.CSISnapshotRestoreResults{},179 errChecker: NotNil,180 },181 { // restore error, objects still returned182 kubeCli: fake.NewSimpleClientset(),183 dynCli: fakedynamic.NewSimpleDynamicClient(runtime.NewScheme()),184 args: &types.CSISnapshotRestoreArgs{185 Cleanup: false,186 },187 prepare: func(f *fields) {188 gomock.InOrder(189 f.stepperOps.EXPECT().ValidateArgs(gomock.Any(), gomock.Any()).Return(nil),190 f.stepperOps.EXPECT().CreateApplication(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, nil, nil),191 f.stepperOps.EXPECT().ValidateData(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil),192 f.stepperOps.EXPECT().SnapshotApplication(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, nil),193 f.stepperOps.EXPECT().RestoreApplication(gomock.Any(), gomock.Any(), gomock.Any()).Return(194 &v1.Pod{195 ObjectMeta: metav1.ObjectMeta{196 Name: "pod2",197 Namespace: "ns",198 },199 },200 &v1.PersistentVolumeClaim{201 ObjectMeta: metav1.ObjectMeta{202 Name: "pvc2",203 Namespace: "ns",204 },205 },206 fmt.Errorf("restore error"),207 ),208 )209 },210 result: &types.CSISnapshotRestoreResults{211 ClonedPVC: &v1.PersistentVolumeClaim{212 ObjectMeta: metav1.ObjectMeta{213 Name: "pvc2",214 Namespace: "ns",215 },216 },217 ClonedPod: &v1.Pod{218 ObjectMeta: metav1.ObjectMeta{219 Name: "pod2",220 Namespace: "ns",221 },222 },223 },224 errChecker: NotNil,225 },226 { // restore error, no objects returned227 kubeCli: fake.NewSimpleClientset(),228 dynCli: fakedynamic.NewSimpleDynamicClient(runtime.NewScheme()),229 args: &types.CSISnapshotRestoreArgs{230 Cleanup: false,231 },232 prepare: func(f *fields) {233 gomock.InOrder(234 f.stepperOps.EXPECT().ValidateArgs(gomock.Any(), gomock.Any()).Return(nil),235 f.stepperOps.EXPECT().CreateApplication(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, nil, nil),236 f.stepperOps.EXPECT().ValidateData(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil),237 f.stepperOps.EXPECT().SnapshotApplication(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, nil),238 f.stepperOps.EXPECT().RestoreApplication(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, nil, fmt.Errorf("restore error")),239 )240 },241 result: &types.CSISnapshotRestoreResults{},242 errChecker: NotNil,243 },244 { // snapshot error, object still returned245 kubeCli: fake.NewSimpleClientset(),246 dynCli: fakedynamic.NewSimpleDynamicClient(runtime.NewScheme()),247 args: &types.CSISnapshotRestoreArgs{248 Cleanup: false,249 },250 prepare: func(f *fields) {251 gomock.InOrder(252 f.stepperOps.EXPECT().ValidateArgs(gomock.Any(), gomock.Any()).Return(nil),253 f.stepperOps.EXPECT().CreateApplication(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, nil, nil),254 f.stepperOps.EXPECT().ValidateData(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil),255 f.stepperOps.EXPECT().SnapshotApplication(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(256 &snapv1.VolumeSnapshot{257 ObjectMeta: metav1.ObjectMeta{258 Name: "snapshot",259 },260 },261 fmt.Errorf("snapshot error"),262 ),263 )264 },265 result: &types.CSISnapshotRestoreResults{266 Snapshot: &snapv1.VolumeSnapshot{267 ObjectMeta: metav1.ObjectMeta{268 Name: "snapshot",269 },270 },271 },272 errChecker: NotNil,273 },274 { // snapshot error, object not returned275 kubeCli: fake.NewSimpleClientset(),276 dynCli: fakedynamic.NewSimpleDynamicClient(runtime.NewScheme()),277 args: &types.CSISnapshotRestoreArgs{278 Cleanup: false,279 },280 prepare: func(f *fields) {281 gomock.InOrder(282 f.stepperOps.EXPECT().ValidateArgs(gomock.Any(), gomock.Any()).Return(nil),283 f.stepperOps.EXPECT().CreateApplication(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, nil, nil),284 f.stepperOps.EXPECT().ValidateData(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil),285 f.stepperOps.EXPECT().SnapshotApplication(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, fmt.Errorf("snapshot error")),286 )287 },288 result: &types.CSISnapshotRestoreResults{},289 errChecker: NotNil,290 },291 { // created data validation error292 kubeCli: fake.NewSimpleClientset(),293 dynCli: fakedynamic.NewSimpleDynamicClient(runtime.NewScheme()),294 args: &types.CSISnapshotRestoreArgs{295 Cleanup: false,296 },297 prepare: func(f *fields) {298 gomock.InOrder(299 f.stepperOps.EXPECT().ValidateArgs(gomock.Any(), gomock.Any()).Return(nil),300 f.stepperOps.EXPECT().CreateApplication(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, nil, nil),301 f.stepperOps.EXPECT().ValidateData(gomock.Any(), gomock.Any(), gomock.Any()).Return(fmt.Errorf("validation error")),302 )303 },304 result: &types.CSISnapshotRestoreResults{},305 errChecker: NotNil,306 },307 { // create error, objects still returned308 kubeCli: fake.NewSimpleClientset(),309 dynCli: fakedynamic.NewSimpleDynamicClient(runtime.NewScheme()),310 args: &types.CSISnapshotRestoreArgs{311 Cleanup: false,312 },313 prepare: func(f *fields) {314 gomock.InOrder(315 f.stepperOps.EXPECT().ValidateArgs(gomock.Any(), gomock.Any()).Return(nil),316 f.stepperOps.EXPECT().CreateApplication(gomock.Any(), gomock.Any(), gomock.Any()).Return(317 &v1.Pod{318 ObjectMeta: metav1.ObjectMeta{319 Name: "pod1",320 Namespace: "ns",321 },322 },323 &v1.PersistentVolumeClaim{324 ObjectMeta: metav1.ObjectMeta{325 Name: "pvc1",326 Namespace: "ns",327 },328 },329 fmt.Errorf("create error"),330 ),331 )332 },333 result: &types.CSISnapshotRestoreResults{334 OriginalPVC: &v1.PersistentVolumeClaim{335 ObjectMeta: metav1.ObjectMeta{336 Name: "pvc1",337 Namespace: "ns",338 },339 },340 OriginalPod: &v1.Pod{341 ObjectMeta: metav1.ObjectMeta{342 Name: "pod1",343 Namespace: "ns",344 },345 },346 },347 errChecker: NotNil,348 },349 { // create error, objects not returned350 kubeCli: fake.NewSimpleClientset(),351 dynCli: fakedynamic.NewSimpleDynamicClient(runtime.NewScheme()),352 args: &types.CSISnapshotRestoreArgs{353 Cleanup: false,354 },355 prepare: func(f *fields) {356 gomock.InOrder(357 f.stepperOps.EXPECT().ValidateArgs(gomock.Any(), gomock.Any()).Return(nil),358 f.stepperOps.EXPECT().CreateApplication(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, nil, fmt.Errorf("create error")),359 )360 },361 result: &types.CSISnapshotRestoreResults{},362 errChecker: NotNil,363 },364 { // args validate error365 kubeCli: fake.NewSimpleClientset(),366 dynCli: fakedynamic.NewSimpleDynamicClient(runtime.NewScheme()),367 args: &types.CSISnapshotRestoreArgs{368 Cleanup: false,369 },370 prepare: func(f *fields) {371 gomock.InOrder(372 f.stepperOps.EXPECT().ValidateArgs(gomock.Any(), gomock.Any()).Return(fmt.Errorf("create error")),373 )374 },375 result: &types.CSISnapshotRestoreResults{},376 errChecker: NotNil,377 },378 { // empty cli379 kubeCli: nil,380 dynCli: fakedynamic.NewSimpleDynamicClient(runtime.NewScheme()),381 result: &types.CSISnapshotRestoreResults{},382 errChecker: NotNil,383 },384 { // empty dyncli385 kubeCli: fake.NewSimpleClientset(),386 dynCli: nil,387 result: &types.CSISnapshotRestoreResults{},388 errChecker: NotNil,389 },390 } {391 ctrl := gomock.NewController(c)392 defer ctrl.Finish()393 f := fields{394 stepperOps: mocks.NewMockSnapshotRestoreStepper(ctrl),395 }396 if tc.prepare != nil {397 tc.prepare(&f)398 }399 runner := &SnapshotRestoreRunner{400 KubeCli: tc.kubeCli,401 DynCli: tc.dynCli,402 srSteps: f.stepperOps,403 }404 result, err := runner.RunSnapshotRestoreHelper(ctx, tc.args)405 c.Check(err, tc.errChecker)406 c.Assert(result, DeepEquals, tc.result)407 }408}409func (s *CSITestSuite) TestRunSnapshotRestoreRunner(c *C) {410 ctx := context.Background()411 r := &SnapshotRestoreRunner{}412 _, err := r.RunSnapshotRestore(ctx, nil)413 c.Check(err, NotNil)414}...
messages_handlers_test.go
Source:messages_handlers_test.go
1package handlers2import (3 "errors"4 "fmt"5 "github.com/aliparlakci/armut-backend-assessment/common"6 "github.com/aliparlakci/armut-backend-assessment/mocks"7 "github.com/aliparlakci/armut-backend-assessment/models"8 "github.com/aliparlakci/armut-backend-assessment/services"9 "github.com/gin-gonic/gin"10 "github.com/golang/mock/gomock"11 "go.mongodb.org/mongo-driver/bson/primitive"12 "mime/multipart"13 "net/http"14 "net/http/httptest"15 "testing"16 "time"17)18// These test cases does not cover "Unauthorized" requests (i.e. requests without a proper session cookie)19// because authorization check is handled in Protected Middleware20func TestGetAllMessages(t *testing.T) {21 tests := []struct {22 Prepare func(getter *mocks.MockMessageGetter)23 ExpectedCode int24 ExpectedBody gin.H25 }{26 {27 Prepare: func(getter *mocks.MockMessageGetter) {28 getter.EXPECT().GetAllMessages(gomock.Any(), "johndoe").Return([]models.Message{29 {30 ID: primitive.ObjectID{},31 From: "iskralawrence",32 To: "aliparlakci",33 Body: "hey cutie :)",34 IsRead: false,35 SendAt: time.Time{},36 },37 }, nil).MinTimes(1)38 },39 ExpectedCode: http.StatusOK,40 ExpectedBody: gin.H{"result": []gin.H{41 {42 "id": "000000000000000000000000",43 "from": "iskralawrence",44 "to": "aliparlakci",45 "body": "hey cutie :)",46 "is_read": false,47 "send_at": time.Time{},48 },49 }},50 }, {51 Prepare: func(getter *mocks.MockMessageGetter) {52 getter.EXPECT().GetAllMessages(gomock.Any(), "johndoe").Return(nil, errors.New("")).MinTimes(1)53 },54 ExpectedCode: http.StatusInternalServerError,55 ExpectedBody: gin.H{},56 },57 }58 for i, tt := range tests {59 testName := fmt.Sprintf("[%v]", i)60 t.Run(testName, func(t *testing.T) {61 ctrl := gomock.NewController(t)62 defer ctrl.Finish()63 mockedMessageGetter := mocks.NewMockMessageGetter(ctrl)64 if tt.Prepare != nil {65 tt.Prepare(mockedMessageGetter)66 }67 recorder := httptest.NewRecorder()68 _, r := gin.CreateTestContext(recorder)69 r.Use(func(c *gin.Context) {70 c.Set("user", models.User{Username: "johndoe"})71 })72 r.GET("/api/messages", GetAllMessages(mockedMessageGetter))73 request, err := http.NewRequest(http.MethodGet, "/api/messages", nil)74 if err != nil {75 t.Fatal(err)76 }77 r.ServeHTTP(recorder, request)78 if bodyAssertion, err := common.AreBodiesEqual(tt.ExpectedBody, recorder.Result().Body); err != nil {79 t.Fatal(err)80 } else if !bodyAssertion {81 t.Errorf("response bodies don't match")82 }83 if recorder.Result().StatusCode != tt.ExpectedCode {84 t.Errorf("want %v, got %v", tt.ExpectedCode, recorder.Result().StatusCode)85 }86 })87 }88}89func TestGetNewMessages(t *testing.T) {90 tests := []struct {91 Prepare func(getter *mocks.MockMessageGetter)92 ExpectedCode int93 ExpectedBody gin.H94 }{95 {96 Prepare: func(getter *mocks.MockMessageGetter) {97 getter.EXPECT().GetNewMessages(gomock.Any(), "johndoe").Return([]models.Message{98 {99 ID: primitive.ObjectID{},100 From: "iskralawrence",101 To: "aliparlakci",102 Body: "hey cutie :)",103 IsRead: false,104 SendAt: time.Time{},105 },106 }, nil).MinTimes(1)107 },108 ExpectedCode: http.StatusOK,109 ExpectedBody: gin.H{"result": []gin.H{110 {111 "id": "000000000000000000000000",112 "from": "iskralawrence",113 "to": "aliparlakci",114 "body": "hey cutie :)",115 "is_read": false,116 "send_at": time.Time{},117 },118 }},119 }, {120 Prepare: func(getter *mocks.MockMessageGetter) {121 getter.EXPECT().GetNewMessages(gomock.Any(), "johndoe").Return(nil, errors.New("")).MinTimes(1)122 },123 ExpectedCode: http.StatusInternalServerError,124 ExpectedBody: gin.H{},125 },126 }127 for i, tt := range tests {128 testName := fmt.Sprintf("[%v]", i)129 t.Run(testName, func(t *testing.T) {130 ctrl := gomock.NewController(t)131 defer ctrl.Finish()132 mockedMessageGetter := mocks.NewMockMessageGetter(ctrl)133 if tt.Prepare != nil {134 tt.Prepare(mockedMessageGetter)135 }136 recorder := httptest.NewRecorder()137 _, r := gin.CreateTestContext(recorder)138 r.Use(func(c *gin.Context) {139 c.Set("user", models.User{Username: "johndoe"})140 })141 r.GET("/api/messages/new", GetNewMessages(mockedMessageGetter))142 request, err := http.NewRequest(http.MethodGet, "/api/messages/new", nil)143 if err != nil {144 t.Fatal(err)145 }146 r.ServeHTTP(recorder, request)147 if bodyAssertion, err := common.AreBodiesEqual(tt.ExpectedBody, recorder.Result().Body); err != nil {148 t.Fatal(err)149 } else if !bodyAssertion {150 t.Errorf("response bodies don't match")151 }152 if recorder.Result().StatusCode != tt.ExpectedCode {153 t.Errorf("want %v, got %v", tt.ExpectedCode, recorder.Result().StatusCode)154 }155 })156 }157}158func TestCheckNewMessages(t *testing.T) {159 tests := []struct {160 Prepare func(getter *mocks.MockMessageGetter)161 ExpectedCode int162 ExpectedBody gin.H163 }{164 {165 Prepare: func(getter *mocks.MockMessageGetter) {166 getter.EXPECT().CheckNewMessages(gomock.Any(), "johndoe").Return(5, nil).MinTimes(1)167 },168 ExpectedCode: http.StatusOK,169 ExpectedBody: gin.H{"result": 5},170 }, {171 Prepare: func(getter *mocks.MockMessageGetter) {172 getter.EXPECT().CheckNewMessages(gomock.Any(), "johndoe").Return(0, errors.New("")).MinTimes(1)173 },174 ExpectedCode: http.StatusInternalServerError,175 ExpectedBody: gin.H{},176 },177 }178 for i, tt := range tests {179 testName := fmt.Sprintf("[%v]", i)180 t.Run(testName, func(t *testing.T) {181 ctrl := gomock.NewController(t)182 defer ctrl.Finish()183 mockedMessageGetter := mocks.NewMockMessageGetter(ctrl)184 if tt.Prepare != nil {185 tt.Prepare(mockedMessageGetter)186 }187 recorder := httptest.NewRecorder()188 _, r := gin.CreateTestContext(recorder)189 r.Use(func(c *gin.Context) {190 c.Set("user", models.User{Username: "johndoe"})191 })192 r.GET("/api/messages/check", CheckNewMessages(mockedMessageGetter))193 request, err := http.NewRequest(http.MethodGet, "/api/messages/check", nil)194 if err != nil {195 t.Fatal(err)196 }197 r.ServeHTTP(recorder, request)198 if bodyAssertion, err := common.AreBodiesEqual(tt.ExpectedBody, recorder.Result().Body); err != nil {199 t.Fatal(err)200 } else if !bodyAssertion {201 t.Errorf("response bodies don't match")202 }203 if recorder.Result().StatusCode != tt.ExpectedCode {204 t.Errorf("want %v, got %v", tt.ExpectedCode, recorder.Result().StatusCode)205 }206 })207 }208}209func TestSendMessage(t *testing.T) {210 tests := []struct {211 Body multipart.Form212 Prepare func(sender *mocks.MockMessageSender)213 ExpectedCode int214 ExpectedBody gin.H215 }{216 {217 Body: multipart.Form{218 Value: map[string][]string{219 "to": {"ozkanugur"},220 "body": {"ozkan selam, mazhar ben. bugun biraz asabiydim ama mazaretim var. aksam anlatirim"},221 },222 },223 Prepare: func(sender *mocks.MockMessageSender) {224 sender.EXPECT().SendMessage(gomock.Any(), "ozkan selam, mazhar ben. bugun biraz asabiydim ama mazaretim var. aksam anlatirim", "mazhar", "ozkanugur").Return("", nil).MinTimes(1)225 },226 ExpectedCode: http.StatusCreated,227 ExpectedBody: gin.H{"result": "message is successfully sent"},228 }, {229 Body: multipart.Form{230 Value: map[string][]string{231 "body": {"keske arkadasim olsa da ben de ozkan abi gibi mesajlassam..."},232 },233 },234 Prepare: func(sender *mocks.MockMessageSender) {235 sender.EXPECT().SendMessage(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Times(0)236 },237 ExpectedCode: http.StatusBadRequest,238 ExpectedBody: gin.H{},239 }, {240 Body: multipart.Form{241 Value: map[string][]string{242 "to": {"fuatguner"},243 },244 },245 Prepare: func(sender *mocks.MockMessageSender) {246 sender.EXPECT().SendMessage(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Times(0)247 },248 ExpectedCode: http.StatusBadRequest,249 ExpectedBody: gin.H{},250 }, {251 Body: multipart.Form{252 Value: map[string][]string{253 "to": {"tarkan"},254 "body": {"tarkanla mesajlasmak bu kadar kolay miymis yav"},255 },256 },257 Prepare: func(sender *mocks.MockMessageSender) {258 sender.EXPECT().SendMessage(gomock.Any(), "tarkanla mesajlasmak bu kadar kolay miymis yav", "mazhar", "tarkan").Return(259 "",260 services.ErrNoUser,261 ).MinTimes(1)262 },263 ExpectedCode: http.StatusBadRequest,264 ExpectedBody: gin.H{"result": "user does not exist"},265 }, {266 Body: multipart.Form{267 Value: map[string][]string{268 "to": {"tarkan"},269 "body": {"tarkanla mesajlasmak bu kadar kolay miymis yav"},270 }},271 Prepare: func(sender *mocks.MockMessageSender) {272 sender.EXPECT().SendMessage(gomock.Any(), "tarkanla mesajlasmak bu kadar kolay miymis yav", "mazhar", "tarkan").Return("", errors.New("")).MinTimes(1)273 },274 ExpectedCode: http.StatusInternalServerError,275 ExpectedBody: gin.H{},276 },277 }278 for i, tt := range tests {279 testName := fmt.Sprintf("[%v]", i)280 t.Run(testName, func(t *testing.T) {281 ctrl := gomock.NewController(t)282 defer ctrl.Finish()283 mockedMessageSender := mocks.NewMockMessageSender(ctrl)284 if tt.Prepare != nil {285 tt.Prepare(mockedMessageSender)286 }287 recorder := httptest.NewRecorder()288 _, r := gin.CreateTestContext(recorder)289 r.Use(func(c *gin.Context) {290 c.Set("user", models.User{Username: "mazhar"})291 })292 r.POST("/api/messages/send", SendMessage(mockedMessageSender))293 request, err := http.NewRequest(http.MethodPost, "/api/messages/send", nil)294 request.MultipartForm = &tt.Body295 request.Header.Set("Content-Type", "multipart/form-data")296 if err != nil {297 t.Fatal(err)298 }299 r.ServeHTTP(recorder, request)300 if bodyAssertion, err := common.AreBodiesEqual(tt.ExpectedBody, recorder.Result().Body); err != nil {301 t.Fatal(err)302 } else if !bodyAssertion {303 t.Errorf("response bodies don't match")304 }305 if recorder.Result().StatusCode != tt.ExpectedCode {306 t.Errorf("want %v, got %v", tt.ExpectedCode, recorder.Result().StatusCode)307 }308 })309 }310}311func TestReadMessage(t *testing.T) {312 tests := []struct {313 Endpoint string314 Prepare func(reader *mocks.MockMessageReader)315 ExpectedCode int316 ExpectedBody gin.H317 }{318 {319 Endpoint: "/api/messages/read/123456",320 Prepare: func(reader *mocks.MockMessageReader) {321 reader.EXPECT().ReadMessage(gomock.Any(), "123456", "johndoe").Return(nil).MinTimes(1)322 },323 ExpectedCode: http.StatusOK,324 ExpectedBody: gin.H{},325 }, {326 Endpoint: "/api/messages/read/",327 Prepare: func(reader *mocks.MockMessageReader) {328 reader.EXPECT().ReadMessage(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil).Times(0)329 },330 ExpectedCode: http.StatusBadRequest,331 ExpectedBody: gin.H{},332 },333 }334 for i, tt := range tests {335 testName := fmt.Sprintf("[%v]", i)336 t.Run(testName, func(t *testing.T) {337 ctrl := gomock.NewController(t)338 defer ctrl.Finish()339 mockedMessageReader := mocks.NewMockMessageReader(ctrl)340 if tt.Prepare != nil {341 tt.Prepare(mockedMessageReader)342 }343 recorder := httptest.NewRecorder()344 _, r := gin.CreateTestContext(recorder)345 r.Use(func(c *gin.Context) {346 c.Set("user", models.User{Username: "johndoe"})347 })348 r.PUT("/api/messages/read/:id", ReadMessage(mockedMessageReader))349 request, err := http.NewRequest(http.MethodPut, tt.Endpoint, nil)350 if err != nil {351 t.Fatal(err)352 }353 r.ServeHTTP(recorder, request)354 if bodyAssertion, err := common.AreBodiesEqual(tt.ExpectedBody, recorder.Result().Body); err != nil {355 t.Fatal(err)356 } else if !bodyAssertion {357 t.Errorf("response bodies don't match")358 }359 if recorder.Result().StatusCode != tt.ExpectedCode {360 t.Errorf("want %v, got %v", tt.ExpectedCode, recorder.Result().StatusCode)361 }362 })363 }364}365func TestReadMessages(t *testing.T) {366 tests := []struct {367 Endpoint string368 Prepare func(reader *mocks.MockMessageReader)369 ExpectedCode int370 ExpectedBody gin.H371 }{372 {373 Endpoint: "/api/messages/user/ali",374 Prepare: func(reader *mocks.MockMessageReader) {375 reader.EXPECT().ReadMessagesFromUser(gomock.Any(), "ali", "johndoe").Return(nil).MinTimes(1)376 },377 ExpectedCode: http.StatusOK,378 ExpectedBody: gin.H{},379 }, {380 Endpoint: "/api/messages/user/",381 Prepare: func(reader *mocks.MockMessageReader) {382 reader.EXPECT().ReadMessagesFromUser(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil).Times(0)383 },384 ExpectedCode: http.StatusBadRequest,385 ExpectedBody: gin.H{},386 },387 }388 for i, tt := range tests {389 testName := fmt.Sprintf("[%v]", i)390 t.Run(testName, func(t *testing.T) {391 ctrl := gomock.NewController(t)392 defer ctrl.Finish()393 mockedMessageReader := mocks.NewMockMessageReader(ctrl)394 if tt.Prepare != nil {395 tt.Prepare(mockedMessageReader)396 }397 recorder := httptest.NewRecorder()398 _, r := gin.CreateTestContext(recorder)399 r.Use(func(c *gin.Context) {400 c.Set("user", models.User{Username: "johndoe"})401 })402 r.PUT("/api/messages/user/:username", ReadMessages(mockedMessageReader))403 request, err := http.NewRequest(http.MethodPut, tt.Endpoint, nil)404 if err != nil {405 t.Fatal(err)406 }407 r.ServeHTTP(recorder, request)408 if bodyAssertion, err := common.AreBodiesEqual(tt.ExpectedBody, recorder.Result().Body); err != nil {409 t.Fatal(err)410 } else if !bodyAssertion {411 t.Errorf("response bodies don't match")412 }413 if recorder.Result().StatusCode != tt.ExpectedCode {414 t.Errorf("want %v, got %v", tt.ExpectedCode, recorder.Result().StatusCode)415 }416 })417 }418}...
pvc_inspector_test.go
Source:pvc_inspector_test.go
...96 },97 ),98 )99 },100 errChecker: IsNil,101 },102 {103 // portforward failure104 kubeCli: fake.NewSimpleClientset(),105 dynCli: fakedynamic.NewSimpleDynamicClient(runtime.NewScheme()),106 args: &types.PVCBrowseArgs{},107 prepare: func(f *fields) {108 gomock.InOrder(109 f.stepperOps.EXPECT().ValidateArgs(gomock.Any(), gomock.Any()).Return(nil, nil),110 f.stepperOps.EXPECT().SnapshotPVC(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, nil),111 f.stepperOps.EXPECT().CreateInspectorApplication(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, nil, nil),112 f.stepperOps.EXPECT().PortForwardAPod(gomock.Any(), gomock.Any(), gomock.Any()).Return(fmt.Errorf("portforward error")),113 f.stepperOps.EXPECT().Cleanup(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()),114 )115 },116 errChecker: NotNil,117 },118 {119 // createapp failure120 kubeCli: fake.NewSimpleClientset(),121 dynCli: fakedynamic.NewSimpleDynamicClient(runtime.NewScheme()),122 args: &types.PVCBrowseArgs{},123 prepare: func(f *fields) {124 gomock.InOrder(125 f.stepperOps.EXPECT().ValidateArgs(gomock.Any(), gomock.Any()).Return(nil, nil),126 f.stepperOps.EXPECT().SnapshotPVC(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, nil),127 f.stepperOps.EXPECT().CreateInspectorApplication(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, nil, fmt.Errorf("createapp error")),128 f.stepperOps.EXPECT().Cleanup(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()),129 )130 },131 errChecker: NotNil,132 },133 {134 // snapshot failure135 kubeCli: fake.NewSimpleClientset(),136 dynCli: fakedynamic.NewSimpleDynamicClient(runtime.NewScheme()),137 args: &types.PVCBrowseArgs{},138 prepare: func(f *fields) {139 gomock.InOrder(140 f.stepperOps.EXPECT().ValidateArgs(gomock.Any(), gomock.Any()).Return(nil, nil),141 f.stepperOps.EXPECT().SnapshotPVC(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, fmt.Errorf("snapshot error")),142 f.stepperOps.EXPECT().Cleanup(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()),143 )144 },145 errChecker: NotNil,146 },147 {148 // validate failure149 kubeCli: fake.NewSimpleClientset(),150 dynCli: fakedynamic.NewSimpleDynamicClient(runtime.NewScheme()),151 args: &types.PVCBrowseArgs{},152 prepare: func(f *fields) {153 gomock.InOrder(154 f.stepperOps.EXPECT().ValidateArgs(gomock.Any(), gomock.Any()).Return(nil, fmt.Errorf("snapshot error")),155 f.stepperOps.EXPECT().Cleanup(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()),156 )157 },158 errChecker: NotNil,159 },160 {161 // emptycli failure162 kubeCli: nil,163 dynCli: fakedynamic.NewSimpleDynamicClient(runtime.NewScheme()),164 args: &types.PVCBrowseArgs{},165 prepare: func(f *fields) {166 gomock.InOrder(167 f.stepperOps.EXPECT().Cleanup(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()),168 )169 },170 errChecker: NotNil,171 },172 {173 // emptydyncli failure174 kubeCli: fake.NewSimpleClientset(),175 dynCli: nil,176 args: &types.PVCBrowseArgs{},177 prepare: func(f *fields) {178 gomock.InOrder(179 f.stepperOps.EXPECT().Cleanup(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()),180 )181 },182 errChecker: NotNil,183 },184 } {185 ctrl := gomock.NewController(c)186 defer ctrl.Finish()187 f := fields{188 stepperOps: mocks.NewMockPVCBrowserStepper(ctrl),189 }190 if tc.prepare != nil {191 tc.prepare(&f)192 }193 runner := &PVCBrowseRunner{194 KubeCli: tc.kubeCli,195 DynCli: tc.dynCli,196 browserSteps: f.stepperOps,197 }198 err := runner.RunPVCBrowseHelper(ctx, tc.args)199 c.Check(err, tc.errChecker)200 }201}202func (s *CSITestSuite) TestPVCBrowseRunner(c *C) {203 ctx := context.Background()204 r := &PVCBrowseRunner{205 browserSteps: &pvcBrowserSteps{},206 }207 err := r.RunPVCBrowseHelper(ctx, nil)208 c.Check(err, NotNil)209}...
request_test.go
Source:request_test.go
1// Package core2//3// @author: xwc11254package core5import (6 "fmt"7 pbftProtocol "github.com/chain5j/chain5j-pbft/protocol"8 "github.com/chain5j/chain5j-pbft/protocol/mockpbft"9 "github.com/chain5j/chain5j-pbft/validator"10 "github.com/chain5j/chain5j-pkg/crypto/signature"11 "github.com/chain5j/chain5j-pkg/event"12 cmath "github.com/chain5j/chain5j-pkg/math"13 "github.com/chain5j/chain5j-pkg/types"14 "github.com/chain5j/chain5j-pkg/util/dateutil"15 "github.com/chain5j/chain5j-pkg/util/hexutil"16 "github.com/chain5j/chain5j-protocol/mock"17 "github.com/chain5j/chain5j-protocol/models"18 "github.com/chain5j/logger"19 "github.com/chain5j/logger/zap"20 "github.com/golang/mock/gomock"21 "math/big"22 "testing"23)24func init() {25 zap.InitWithConfig(&logger.LogConfig{26 Console: logger.ConsoleLogConfig{27 Level: 4,28 Modules: "*",29 ShowPath: false,30 Format: "",31 UseColor: true,32 Console: true,33 },34 File: logger.FileLogConfig{},35 })36}37func TestHandleRequest(t *testing.T) {38 mockCtl := gomock.NewController(t)39 mockPBFTBackend := mockpbft.NewMockPBFTBackend(mockCtl)40 // 0x1c7dd8ac4be69e3bcc9ba2e609bf7bb767f40824894b20c4eddbe36d2461f16641 // 0x7C286d572eCD157f230DF3F19A7F127AADF37ADc42 // 0xf3bf2f58e4e369d101786024b5f5719851b9c7f39add700db3e55ff363d3a3f443 // 0x2213830F680cD75FeA3AD4D37BBC0E244A412c0444 priv, _ := signature.HexToECDSA(signature.P256, "0xf3bf2f58e4e369d101786024b5f5719851b9c7f39add700db3e55ff363d3a3f4")45 //priv, _ := signature.GenerateKeyWithECDSA(signature.P256)46 privBytes := signature.FromECDSA(priv)47 fmt.Println(hexutil.Encode(privBytes))48 addr := signature.PubkeyToAddress(&priv.PublicKey)49 fmt.Println(addr.Hex())50 data := hexutil.MustDecode("0xf8b980b889f887c28001f882f87fa000000000000000000000000000000000000000000000000000000000000000000180a0000000000000000000000000000000000000000000000000000000000000000080846169273f80834c4b40c080a00000000000000000000000000000000000000000000000000000000000000000808800000000000000008080c0c0aa307837433238366435373265434431353766323330444633463139413746313237414144463337414463c080")51 signResult, err := signature.SignWithECDSA(priv, data)52 if err != nil {53 t.Fatal(err)54 }55 mockPBFTBackend.EXPECT().ID().Return("0x2213830F680cD75FeA3AD4D37BBC0E244A412c04").AnyTimes()56 mockPBFTBackend.EXPECT().Sign(gomock.Any()).Return(57 signResult,58 nil,59 ).AnyTimes()60 blockCount := 561 blocks := make([]*models.Block, blockCount)62 for i := 0; i < blockCount; i++ {63 header := &models.Header{64 ParentHash: types.EmptyHash,65 Height: uint64(i),66 StateRoots: nil,67 TxRoot: types.EmptyHash,68 TxCount: 0,69 Timestamp: uint64(dateutil.CurrentTimeSecond()),70 GasUsed: 0,71 GasLimit: 5000000,72 Consensus: nil,73 ArchiveHash: nil,74 LogsBloom: nil,75 Extra: nil,76 Memo: nil,77 Signature: nil,78 }79 blocks[i] = models.NewBlock(header, nil, nil)80 }81 newView := &pbftProtocol.View{82 Sequence: new(big.Int).Add(big.NewInt(int64(blocks[0].Height())), cmath.Big1),83 Round: new(big.Int),84 }85 valSet := validator.NewSet([]string{86 "0x2213830F680cD75FeA3AD4D37BBC0E244A412c04",87 //"0x7C286d572eCD157f230DF3F19A7F127AADF37ADc",88 }, pbftProtocol.RoundRobin)89 mockPBFTBackend.EXPECT().Validators(gomock.Any()).Return(valSet).AnyTimes()90 mockPBFTBackend.EXPECT().Verify(gomock.Any()).Return(nil).AnyTimes()91 mockPBFTBackend.EXPECT().Commit(gomock.Any(), gomock.Any()).Return(nil).AnyTimes()92 mockPBFTBackend.EXPECT().LastProposal().DoAndReturn(func() (pbftProtocol.Proposal, string) {93 return blocks[0], "0x2213830F680cD75FeA3AD4D37BBC0E244A412c04"94 }).AnyTimes()95 // 设置è°ç¨é¡ºåº: gomock.InOrder()96 // Broadcaster97 mockBroadcaster := mock.NewMockBroadcaster(mockCtl)98 mockBroadcaster.EXPECT().SubscribeMsg(gomock.Any(), gomock.Any()).Return(event.NewSubscription(func(quit <-chan struct{}) error {99 return nil100 })).AnyTimes()101 mockBroadcaster.EXPECT().Broadcast(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil).AnyTimes()102 engine := NewEngine(mockPBFTBackend, mockBroadcaster)103 engineCore := engine.(*core)104 engineCore.currentRoundState = newRoundState(newView, valSet, types.Hash{}, nil, nil)105 engineCore.valSet = valSet106 go engineCore.handleLoop()107 {108 // oldMessage109 err := engine.Request(&pbftProtocol.Request{110 Proposal: blocks[0],111 })112 if err != nil {113 t.Error(err)114 }115 }116 for i := uint64(1); i < uint64(5); i++ {117 {118 err := engine.Request(&pbftProtocol.Request{119 Proposal: blocks[i],120 })121 if err != nil {122 t.Error(err)123 }124 }125 }126 var stop chan struct{}127 <-stop128}...
Nil
Using AI Code Generation
1import (2func TestNil(t *testing.T) {3 ctrl := gomock.NewController(t)4 defer ctrl.Finish()5 mock := NewMockMock(ctrl)6 mock.EXPECT().DoSomething(gomock.Nil()).Return(nil)7 mock.DoSomething(nil)8}9import (10func TestNil(t *testing.T) {11 ctrl := gomock.NewController(t)12 defer ctrl.Finish()13 mock := NewMockMock(ctrl)14 mock.EXPECT().DoSomething(gomock.Any()).Return(nil)15 mock.DoSomething(nil)16}17import (18func TestNil(t *testing.T) {19 ctrl := gomock.NewController(t)20 defer ctrl.Finish()21 mock := NewMockMock(ctrl)22 mock.EXPECT().DoSomething(gomock.Any()).Return(nil)23 mock.DoSomething(nil)24}25import (26func TestNil(t *testing.T) {27 ctrl := gomock.NewController(t)28 defer ctrl.Finish()29 mock := NewMockMock(ctrl)30 mock.EXPECT().DoSomething(gomock.Any()).Return(nil)31 mock.DoSomething(nil)32}33import (34func TestNil(t *testing.T) {35 ctrl := gomock.NewController(t)36 defer ctrl.Finish()37 mock := NewMockMock(ctrl)
Nil
Using AI Code Generation
1import (2func TestNil(t *testing.T) {3 ctrl := gomock.NewController(t)4 defer ctrl.Finish()5 mock := NewMockFoo(ctrl)6 mock.EXPECT().Bar().Return("bar")7 assert.Equal(t, "bar", mock.Bar())8 fmt.Println("mock.Bar() called successfully")9 mock.EXPECT().Bar().Return(nil)10 assert.Equal(t, nil, mock.Bar())11 fmt.Println("mock.Bar() called successfully with nil")12}13import (14func TestNil(t *testing.T) {15 ctrl := gomock.NewController(t)16 defer ctrl.Finish()17 mock := NewMockFoo(ctrl)18 mock.EXPECT().Bar().Return("bar")19 assert.Equal(t, "bar", mock.Bar())20 fmt.Println("mock.Bar() called successfully")21 mock.EXPECT().Bar().Return(gomock.Nil())22 assert.Equal(t, nil, mock.Bar())23 fmt.Println("mock.Bar() called successfully with nil")24}25--- PASS: TestNil (0.00s)26 1_test.go:35: mock.Bar() called successfully27 1_test.go:43: mock.Bar() called successfully with nil28--- PASS: TestNil (0.00s)29 2_test.go:35: mock.Bar() called successfully30 2_test.go:43: mock.Bar() called successfully with nil
Nil
Using AI Code Generation
1import (2func TestNil(t *testing.T) {3 ctrl := gomock.NewController(t)4 defer ctrl.Finish()5 mockFoo := mock.NewMockFoo(ctrl)6 mockFoo.EXPECT().Bar().Return("bar").Times(1)7 mockFoo.EXPECT().Bar().Return("bar").Times(1)8 mockFoo.EXPECT().Bar().Return("bar").Times(1)9 fmt.Println(mockFoo.Bar())10 fmt.Println(mockFoo.Bar())11 fmt.Println(mockFoo.Bar())12}13import (14func TestAny(t *testing.T) {15 ctrl := gomock.NewController(t)16 defer ctrl.Finish()17 mockFoo := mock.NewMockFoo(ctrl)18 mockFoo.EXPECT().Bar(gomock.Any()).Return("bar")19 fmt.Println(mockFoo.Bar(1))20 fmt.Println(mockFoo.Bar(2))21 fmt.Println(mockFoo.Bar(3))22}23import (24func TestDo(t *testing.T) {25 ctrl := gomock.NewController(t)26 defer ctrl.Finish()27 mockFoo := mock.NewMockFoo(ctrl)28 mockFoo.EXPECT().Bar(gomock.Any()).Do(func(x interface{}) {29 fmt.Println(x)30 }).Return("bar")31 fmt.Println(mockFoo.Bar(1))32 fmt.Println(mockFoo.Bar(2))33 fmt.Println(mockFoo.Bar(3))34}35import (36func TestDo(t *testing.T) {37 ctrl := gomock.NewController(t)38 defer ctrl.Finish()39 mockFoo := mock.NewMockFoo(ctrl)40 mockFoo.EXPECT().Bar(gomock.Any()).Do(func(x interface{}) {41 fmt.Println(x)42 }).Return("bar")43 fmt.Println(mockFoo.Bar(1))44 fmt.Println(mockFoo.Bar(2))
Nil
Using AI Code Generation
1import (2func TestNil(t *testing.T) {3 ctrl := gomock.NewController(t)4 defer ctrl.Finish()5 mockLogger := logrus.New()6 mockLogger.Info("some info")7 fmt.Println("some info")8}9import (10func TestNil2(t *testing.T) {11 ctrl := gomock.NewController(t)12 defer ctrl.Finish()13 mockLogger := logrus.New()14 mockLogger.Info("some info")15 fmt.Println("some info")16}17import (18func TestNil3(t *testing.T) {19 ctrl := gomock.NewController(t)20 defer ctrl.Finish()21 mockLogger := logrus.New()22 mockLogger.Info("some info")23 fmt.Println("some info")24}25import (26func TestNil4(t *testing
Nil
Using AI Code Generation
1func TestNil(t *testing.T) {2 mockCtrl := gomock.NewController(t)3 defer mockCtrl.Finish()4 mock := NewMockFoo(mockCtrl)5 mock.EXPECT().Bar().Return(nil)6 mock.Bar()7}8func TestReturn(t *testing.T) {9 mockCtrl := gomock.NewController(t)10 defer mockCtrl.Finish()11 mock := NewMockFoo(mockCtrl)12 mock.EXPECT().Bar().Return(&Foo{})13 mock.Bar()14}15func TestReturn(t *testing.T) {16 mockCtrl := gomock.NewController(t)17 defer mockCtrl.Finish()18 mock := NewMockFoo(mockCtrl)19 mock.EXPECT().Bar().Return(&Foo{})20 mock.Bar()21}22func TestReturn(t *testing.T) {23 mockCtrl := gomock.NewController(t)24 defer mockCtrl.Finish()25 mock := NewMockFoo(mockCtrl)26 mock.EXPECT().Bar().Return(&Foo{})27 mock.Bar()28}29func TestReturn(t *testing.T) {30 mockCtrl := gomock.NewController(t)31 defer mockCtrl.Finish()32 mock := NewMockFoo(mockCtrl)33 mock.EXPECT().Bar().Return(&Foo{})34 mock.Bar()35}36func TestReturn(t *testing.T) {37 mockCtrl := gomock.NewController(t)38 defer mockCtrl.Finish()39 mock := NewMockFoo(mockCtrl)40 mock.EXPECT().Bar().Return(&Foo{})41 mock.Bar()42}43func TestReturn(t *testing.T) {44 mockCtrl := gomock.NewController(t)45 defer mockCtrl.Finish()46 mock := NewMockFoo(mockCtrl)47 mock.EXPECT().Bar().Return(&Foo{})48 mock.Bar()49}
Nil
Using AI Code Generation
1func TestNil(t *testing.T) {2 ctrl := gomock.NewController(t)3 defer ctrl.Finish()4 mock := mock.NewMockInterface(ctrl)5 mock.EXPECT().Add(1, 2).Return(3)6 fmt.Println(mock.Add(1, 2))7}8func TestNil2(t *testing.T) {9 ctrl := gomock.NewController(t)10 defer ctrl.Finish()11 mock := mock.NewMockInterface(ctrl)12 mock.EXPECT().Add(1, 2).Return(3)13 fmt.Println(mock.Add(1, 2))14}15func TestNil3(t *testing.T) {16 ctrl := gomock.NewController(t)17 defer ctrl.Finish()18 mock := mock.NewMockInterface(ctrl)19 mock.EXPECT().Add(1, 2).Return(3)20 fmt.Println(mock.Add(1, 2))21}22 C:\Go\src\1.go (from $GOROOT)23 C:\Users\user\go\src\1.go (from $GOPATH)24 C:\Go\src\2.go (from $GOROOT)25 C:\Users\user\go\src\2.go (from $GOPATH)26 C:\Go\src\3.go (from $GOROOT)27 C:\Users\user\go\src\3.go (from $
Nil
Using AI Code Generation
1func TestNil(t *testing.T) {2 ctrl := gomock.NewController(t)3 defer ctrl.Finish()4 mock := NewMockMyInterface(ctrl)5 mock.EXPECT().DoSomething().Return(nil)6 mock.DoSomething()7}8func TestNil2(t *testing.T) {9 ctrl := gomock.NewController(t)10 defer ctrl.Finish()11 mock := NewMockMyInterface(ctrl)12 mock.EXPECT().DoSomething().Return(nil)13 mock.DoSomething()14}15func TestNil3(t *testing.T) {16 ctrl := gomock.NewController(t)17 defer ctrl.Finish()18 mock := NewMockMyInterface(ctrl)19 mock.EXPECT().DoSomething().Return(nil)20 mock.DoSomething()21}22func TestNil4(t *testing.T) {23 ctrl := gomock.NewController(t)24 defer ctrl.Finish()25 mock := NewMockMyInterface(ctrl)26 mock.EXPECT().DoSomething().Return(nil)27 mock.DoSomething()28}29func TestNil5(t *testing.T) {30 ctrl := gomock.NewController(t)31 defer ctrl.Finish()32 mock := NewMockMyInterface(ctrl)33 mock.EXPECT().DoSomething().Return(nil)34 mock.DoSomething()35}36func TestNil6(t *testing.T) {37 ctrl := gomock.NewController(t)38 defer ctrl.Finish()39 mock := NewMockMyInterface(ctrl)40 mock.EXPECT().DoSomething().Return(nil)41 mock.DoSomething()42}43func TestNil7(t *testing.T) {44 ctrl := gomock.NewController(t)45 defer ctrl.Finish()46 mock := NewMockMyInterface(ctrl)47 mock.EXPECT().DoSomething().Return(nil)48 mock.DoSomething()49}50func TestNil8(t *testing.T) {51 ctrl := gomock.NewController(t)52 defer ctrl.Finish()53 mock := NewMockMyInterface(ctrl)54 mock.EXPECT().Do
Nil
Using AI Code Generation
1func TestNil(t *testing.T) {2mockCtrl = gomock.NewController(t)3defer mockCtrl.Finish()4mock := NewMockMyInterface(mockCtrl)5mock.EXPECT().MyMethod().Return(nil)6}7func TestNil(t *testing.T) {8mockCtrl = gomock.NewController(t)9defer mockCtrl.Finish()10mock := NewMockMyInterface(mockCtrl)11mock.EXPECT().MyMethod().Return(nil)12}13func TestNil(t *testing.T) {14mockCtrl = gomock.NewController(t)15defer mockCtrl.Finish()16mock := NewMockMyInterface(mockCtrl)17mock.EXPECT().MyMethod().Return(nil)18}19func TestNil(t *testing.T) {20mockCtrl = gomock.NewController(t)21defer mockCtrl.Finish()22mock := NewMockMyInterface(mockCtrl)23mock.EXPECT().MyMethod().Return(nil)24}25func TestNil(t *testing.T) {26mockCtrl = gomock.NewController(t)27defer mockCtrl.Finish()28mock := NewMockMyInterface(mockCtrl)29mock.EXPECT().MyMethod().Return(nil)30}31func TestNil(t *testing.T) {32mockCtrl = gomock.NewController(t)33defer mockCtrl.Finish()34mock := NewMockMyInterface(mockCtrl)35mock.EXPECT().MyMethod
Nil
Using AI Code Generation
1import (2type MockInterface interface {3 DoSomething() error4}5func TestNil(t *testing.T) {6 ctrl := gomock.NewController(t)7 defer ctrl.Finish()8 mockObj := NewMockInterface(ctrl)9 mockObj.EXPECT().DoSomething().Return(nil)10 err := mockObj.DoSomething()11 assert.Nil(t, err)12}13import (14type MockInterface interface {15 DoSomething() error16}17func TestNil(t *testing.T) {18 ctrl := gomock.NewController(t)19 defer ctrl.Finish()20 mockObj := NewMockInterface(ctrl)21 mockObj.EXPECT().DoSomething().Return(fmt.Errorf("Some error"))22 err := mockObj.DoSomething()23 assert.NotNil(t, err)24}25--- PASS: TestNil (0.00s)26--- PASS: TestNil (0.00s)
Nil
Using AI Code Generation
1import (2func main() {3 ctrl := gomock.NewController(nil)4 defer ctrl.Finish()5 mockObj := mock.NewMockMyInterface(ctrl)6 mockObj.EXPECT().MyMethod().Return(5)7 fmt.Println(mockObj.MyMethod())8}9import (10func main() {11 ctrl := gomock.NewController(nil)12 defer ctrl.Finish()13 mockObj := mock.NewMockMyInterface(ctrl)14 gomock.InOrder(15 mockObj.EXPECT().MyMethod().Return(5),16 mockObj.EXPECT().MyMethod().Return(6),17 fmt.Println(mockObj.MyMethod())18 fmt.Println(mockObj.MyMethod())19}20import (21func main() {22 ctrl := gomock.NewController(nil)23 defer ctrl.Finish()24 mockObj := mock.NewMockMyInterface(ctrl)25 mockObj.EXPECT().MyMethod2(gomock.Any()).Return(5)26 fmt.Println(mockObj.MyMethod2(5))27 fmt.Println(mockObj.MyMethod2(6))28}
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!!