How to use Patch method of client Package

Best Testkube code snippet using client.Patch

cliapi_test.go

Source:cliapi_test.go Github

copy

Full Screen

...36 errPerm = fmt.Errorf("permission denied")37 errFileDir = fmt.Errorf("no such file or directory")38 errPortInv = fmt.Errorf("Invalid containerPort")39)40func unpatchAll(t *testing.T, pList []*mpatch.Patch) {41 for _, p := range pList {42 if p != nil {43 if err := p.Unpatch(); err != nil {44 t.Errorf("unpatch error: %v", err)45 }46 }47 }48}49func getDockerClientErrFunc(t *testing.T, ctrl *gomock.Controller) []*mpatch.Patch {50 var patch *mpatch.Patch51 patch, _ = mpatch.PatchMethod(getDockerClient, func() (*client.Client, error) {52 unpatch(t, patch)53 return nil, testError54 })55 return nil56}57func patchIsValidFile(t *testing.T, isValid bool) {58 var patch *mpatch.Patch59 patch, _ = mpatch.PatchMethod(eputils.IsValidFile, func(filename string) bool {60 unpatch(t, patch)61 return isValid62 })63}64func patchOpenFile(t *testing.T, file *os.File, err error) {65 var patch *mpatch.Patch66 patch, _ = mpatch.PatchMethod(os.OpenFile, func(name string, flag int, perm os.FileMode) (*os.File, error) {67 unpatch(t, patch)68 return file, err69 })70}71//nolint:unparam72func patchStat(t *testing.T, fileInfo fs.FileInfo, err error) {73 var patch *mpatch.Patch74 patch, _ = mpatch.PatchMethod(os.Stat, func(name string) (fs.FileInfo, error) {75 unpatch(t, patch)76 return fileInfo, err77 })78}79//nolint:unparam80func patchReadAll(t *testing.T, data []byte, err error) {81 var patch *mpatch.Patch82 patch, _ = mpatch.PatchMethod(ioutil.ReadAll, func(r io.Reader) ([]byte, error) {83 unpatch(t, patch)84 return data, err85 })86}87func patchReadFile(t *testing.T, data []byte, err error) {88 var patch *mpatch.Patch89 patch, _ = mpatch.PatchMethod(os.ReadFile, func(name string) ([]byte, error) {90 unpatch(t, patch)91 return data, err92 })93}94func patchJsonMarshal(t *testing.T, data []byte, err error) {95 var patch *mpatch.Patch96 patch, _ = mpatch.PatchMethod(json.Marshal, func(_ interface{}) ([]byte, error) {97 unpatch(t, patch)98 return data, err99 })100}101func patchDisplayJSONMessagesStream(t *testing.T, err error) {102 var patch *mpatch.Patch103 patch, _ = mpatch.PatchMethod(jsonmessage.DisplayJSONMessagesStream, func(in io.Reader, out io.Writer, terminalFd uintptr, isTerminal bool, auxCallback func(jsonmessage.JSONMessage)) error {104 unpatch(t, patch)105 return err106 })107}108func TestGetDockerClient(t *testing.T) {109 normalFunc := func(ctrl *gomock.Controller, mockOutput error) []*mpatch.Patch {110 mockDockerClientInterface := clientmock.NewMockDockerClientInterface(ctrl)111 patch, err := mpatch.PatchMethod(client.NewClientWithOpts, mockDockerClientInterface.NewClientWithOpts)112 if err != nil {113 t.Errorf("mpatch error: %v", err)114 }115 mockDockerClientInterface.EXPECT().116 NewClientWithOpts(gomock.Any(), gomock.Any()).117 Return(nil, mockOutput)118 return []*mpatch.Patch{patch}119 }120 cases := []struct {121 mockOutput error122 wantErr error123 funcBeforeTest func(*gomock.Controller, error) []*mpatch.Patch124 }{125 {126 mockOutput: testError,127 wantErr: testError,128 funcBeforeTest: normalFunc,129 },130 {131 mockOutput: nil,132 wantErr: nil,133 },134 }135 for n, testCase := range cases {136 t.Logf("TestGetContainerByName case %d start", n)137 func() {138 ctrl := gomock.NewController(t)139 defer ctrl.Finish()140 if testCase.funcBeforeTest != nil {141 pList := testCase.funcBeforeTest(ctrl, testCase.mockOutput)142 defer unpatchAll(t, pList)143 }144 _, err := getDockerClient()145 if !errors.Is(err, testCase.wantErr) &&146 (err == nil || !strings.Contains(err.Error(), testCase.wantErr.Error())) {147 t.Errorf("Unexpected error: %v", err)148 }149 }()150 t.Logf("TestGetContainerByName case %d End", n)151 }152 t.Log("Done")153}154// Test Entry155func TestGetContainerByName(t *testing.T) {156 normalFunc := func(ctrl *gomock.Controller, mockOutput []types.Container) []*mpatch.Patch {157 cli := &client.Client{}158 mockDockerClientInterface := clientmock.NewMockDockerClientInterface(ctrl)159 patch, err := mpatch.PatchInstanceMethodByName(reflect.TypeOf(cli), "ContainerList", mockDockerClientInterface.ContainerList)160 if err != nil {161 t.Errorf("mpatch error")162 }163 mockDockerClientInterface.EXPECT().164 ContainerList(gomock.Any(), gomock.Any(), gomock.Any()).165 Return(mockOutput, nil)166 return []*mpatch.Patch{patch}167 }168 ownGetDockerClientErrFunc := func(ctrl *gomock.Controller, _ []types.Container) []*mpatch.Patch {169 getDockerClientErrFunc(t, ctrl)170 return nil171 }172 ContainerListErrFunc := func(ctrl *gomock.Controller, mockOutput []types.Container) []*mpatch.Patch {173 cli := &client.Client{}174 mockDockerClientInterface := clientmock.NewMockDockerClientInterface(ctrl)175 patch, err := mpatch.PatchInstanceMethodByName(reflect.TypeOf(cli), "ContainerList", mockDockerClientInterface.ContainerList)176 if err != nil {177 t.Errorf("mpatch error")178 }179 mockDockerClientInterface.EXPECT().180 ContainerList(gomock.Any(), gomock.Any(), gomock.Any()).181 Return(mockOutput, testError)182 return []*mpatch.Patch{patch}183 }184 cases := []struct {185 mockOutput []types.Container186 wantOutput *types.Container187 wantErr error188 funcBeforeTest func(*gomock.Controller, []types.Container) []*mpatch.Patch189 }{190 {191 mockOutput: []types.Container{192 {ID: "testId1"},193 {ID: "testId2"},194 },195 wantOutput: &types.Container{ID: "testId1"},196 wantErr: nil,197 funcBeforeTest: normalFunc,198 },199 {200 mockOutput: []types.Container{},201 wantOutput: nil,202 wantErr: nil,203 funcBeforeTest: normalFunc,204 },205 {206 mockOutput: nil,207 wantOutput: nil,208 funcBeforeTest: ownGetDockerClientErrFunc,209 wantErr: testError,210 },211 {212 mockOutput: nil,213 wantOutput: nil,214 funcBeforeTest: ContainerListErrFunc,215 wantErr: testError,216 },217 }218 for n, testCase := range cases {219 t.Logf("TestGetContainerByName case %d start", n)220 func() {221 ctrl := gomock.NewController(t)222 defer ctrl.Finish()223 if testCase.funcBeforeTest != nil {224 pList := testCase.funcBeforeTest(ctrl, testCase.mockOutput)225 defer unpatchAll(t, pList)226 }227 container, err := GetContainerByName("test")228 if !errors.Is(err, testCase.wantErr) &&229 (err == nil || !strings.Contains(err.Error(), testCase.wantErr.Error())) {230 t.Errorf("Unexpected error: %v", err)231 }232 if container != nil && testCase.wantOutput != nil && container.ID != testCase.wantOutput.ID {233 t.Errorf("Get wrong container: %v, want container: %v", *container, *testCase.wantOutput)234 }235 }()236 t.Logf("TestGetContainerByName case %d End", n)237 }238 t.Log("Done")239}240func TestImagePull(t *testing.T) {241 normalFunc := func(t *testing.T, ctrl *gomock.Controller) []*mpatch.Patch {242 cli := &client.Client{}243 mockDockerClientInterface := clientmock.NewMockDockerClientInterface(ctrl)244 patch, err := mpatch.PatchInstanceMethodByName(reflect.TypeOf(cli), "ImagePull", mockDockerClientInterface.ImagePull)245 if err != nil {246 t.Errorf("mpatch error")247 }248 readerCloser := io.NopCloser(strings.NewReader("Hello, world!"))249 mockDockerClientInterface.EXPECT().250 ImagePull(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(readerCloser, nil)251 patchDisplayJSONMessagesStream(t, nil)252 return []*mpatch.Patch{patch}253 }254 displayJSONMessagesStreamErrorFunc := func(t *testing.T, ctrl *gomock.Controller) []*mpatch.Patch {255 cli := &client.Client{}256 mockDockerClientInterface := clientmock.NewMockDockerClientInterface(ctrl)257 patch, err := mpatch.PatchInstanceMethodByName(reflect.TypeOf(cli), "ImagePull", mockDockerClientInterface.ImagePull)258 if err != nil {259 t.Errorf("mpatch error")260 }261 readerCloser := io.NopCloser(strings.NewReader("Hello, world!"))262 mockDockerClientInterface.EXPECT().263 ImagePull(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(readerCloser, nil)264 patchDisplayJSONMessagesStream(t, testError)265 return []*mpatch.Patch{patch}266 }267 jsonMarshalFunc := func(t *testing.T, ctrl *gomock.Controller) []*mpatch.Patch {268 patchJsonMarshal(t, nil, testError)269 return nil270 }271 cases := []struct {272 authConfig *types.AuthConfig273 wantErr error274 funcBeforeTest func(*testing.T, *gomock.Controller) []*mpatch.Patch275 }{276 {277 authConfig: &types.AuthConfig{},278 wantErr: nil,279 funcBeforeTest: normalFunc,280 },281 {282 authConfig: nil,283 wantErr: nil,284 funcBeforeTest: normalFunc,285 },286 {287 authConfig: nil,288 wantErr: testError,289 funcBeforeTest: getDockerClientErrFunc,290 },291 {292 authConfig: &types.AuthConfig{},293 wantErr: testError,294 funcBeforeTest: jsonMarshalFunc,295 },296 {297 authConfig: &types.AuthConfig{},298 wantErr: testError,299 funcBeforeTest: displayJSONMessagesStreamErrorFunc,300 },301 }302 for n, testCase := range cases {303 t.Logf("TestImagePull case %d start", n)304 func() {305 ctrl := gomock.NewController(t)306 defer ctrl.Finish()307 if testCase.funcBeforeTest != nil {308 pList := testCase.funcBeforeTest(t, ctrl)309 defer unpatchAll(t, pList)310 }311 err := ImagePull("test", &types.AuthConfig{})312 if !errors.Is(err, testCase.wantErr) &&313 (err == nil || !strings.Contains(err.Error(), testCase.wantErr.Error())) {314 t.Errorf("Unexpected error: %v", err)315 }316 }()317 t.Logf("TestImagePull case %d End", n)318 }319 t.Log("Done")320}321func TestImagePush(t *testing.T) {322 normalFunc := func(t *testing.T, ctrl *gomock.Controller) []*mpatch.Patch {323 mockDockerClientInterface := clientmock.NewMockDockerClientInterface(ctrl)324 cli := &client.Client{}325 patch, err := mpatch.PatchInstanceMethodByName(reflect.TypeOf(cli), "ImagePush", mockDockerClientInterface.ImagePush)326 if err != nil {327 t.Errorf("mpatch error")328 }329 readerCloser := io.NopCloser(strings.NewReader("Hello, world!"))330 mockDockerClientInterface.EXPECT().331 ImagePush(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(readerCloser, nil)332 patchDisplayJSONMessagesStream(t, nil)333 return []*mpatch.Patch{patch}334 }335 displayJSONMessagesStreamErrorFunc := func(t *testing.T, ctrl *gomock.Controller) []*mpatch.Patch {336 mockDockerClientInterface := clientmock.NewMockDockerClientInterface(ctrl)337 cli := &client.Client{}338 patch, err := mpatch.PatchInstanceMethodByName(reflect.TypeOf(cli), "ImagePush", mockDockerClientInterface.ImagePush)339 if err != nil {340 t.Errorf("mpatch error")341 }342 readerCloser := io.NopCloser(strings.NewReader("Hello, world!"))343 mockDockerClientInterface.EXPECT().344 ImagePush(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(readerCloser, nil)345 patchDisplayJSONMessagesStream(t, testError)346 return []*mpatch.Patch{patch}347 }348 jsonMarshalFunc := func(t *testing.T, ctrl *gomock.Controller) []*mpatch.Patch {349 patchJsonMarshal(t, nil, testError)350 return nil351 }352 cases := []struct {353 authConfig *types.AuthConfig354 wantErr error355 funcBeforeTest func(*testing.T, *gomock.Controller) []*mpatch.Patch356 }{357 {358 authConfig: &types.AuthConfig{},359 wantErr: nil,360 funcBeforeTest: normalFunc,361 },362 {363 authConfig: nil,364 wantErr: nil,365 funcBeforeTest: normalFunc,366 },367 {368 authConfig: nil,369 wantErr: testError,370 funcBeforeTest: getDockerClientErrFunc,371 },372 {373 authConfig: &types.AuthConfig{},374 wantErr: testError,375 funcBeforeTest: jsonMarshalFunc,376 },377 {378 authConfig: &types.AuthConfig{},379 wantErr: testError,380 funcBeforeTest: displayJSONMessagesStreamErrorFunc,381 },382 }383 for n, testCase := range cases {384 t.Logf("TestImagePush case %d start", n)385 func() {386 ctrl := gomock.NewController(t)387 defer ctrl.Finish()388 if testCase.funcBeforeTest != nil {389 pList := testCase.funcBeforeTest(t, ctrl)390 defer unpatchAll(t, pList)391 }392 err := ImagePush("test", testCase.authConfig)393 if !errors.Is(err, testCase.wantErr) &&394 (err == nil || !strings.Contains(err.Error(), testCase.wantErr.Error())) {395 t.Errorf("Unexpected error: %v", err)396 }397 }()398 t.Logf("TestImagePush case %d end", n)399 }400 t.Log("Done")401}402func TestImagePushToRegistry(t *testing.T) {403 conf := api.Customconfig{404 Registry: &api.CustomconfigRegistry{405 User: "user",406 Password: "password",407 },408 }409 // CASE1410 patchTagImageToLocal, err := mpatch.PatchMethod(TagImageToLocal, func(string, string) (string, error) { return "", testError })411 if err != nil {412 t.Errorf("mpatch error")413 }414 err = ImagePushToRegistry("testimage", "testregistry", &conf)415 unpatch(t, patchTagImageToLocal)416 if !errors.Is(err, testError) {417 t.Errorf("expected %v, function returned %v", testError, err)418 }419 // CASE2420 patchTagImageToLocal, err = mpatch.PatchMethod(TagImageToLocal, func(string, string) (string, error) { return "newtag", nil })421 if err != nil {422 t.Errorf("mpatch error")423 }424 patchImagePush, err := mpatch.PatchMethod(ImagePush, func(string, *types.AuthConfig) error { return testError })425 if err != nil {426 t.Errorf("mpatch error")427 }428 err = ImagePushToRegistry("testimage", "testregistry", &conf)429 unpatch(t, patchTagImageToLocal)430 unpatch(t, patchImagePush)431 if !errors.Is(err, testError) {432 t.Errorf("expected %v, function returned %v", testError, err)433 }434 // CASE3435 p1, err := mpatch.PatchMethod(TagImageToLocal, func(string, string) (string, error) { return "newtag", nil })436 if err != nil {437 t.Errorf("mpatch error")438 }439 p2, err := mpatch.PatchMethod(ImagePush, func(string, *types.AuthConfig) error { return nil })440 if err != nil {441 t.Errorf("mpatch error")442 }443 defer unpatchAll(t, []*mpatch.Patch{p1, p2})444 if err = ImagePushToRegistry("testimage", "testregistry", &conf); err != nil {445 t.Errorf("Failed")446 }447 t.Log("Done")448}449func TestImageBuild(t *testing.T) {450 normalFunc := func(t *testing.T, ctrl *gomock.Controller) []*mpatch.Patch {451 os.Setenv("http_proxy", "test_http_proxy")452 mockDockerClientInterface := clientmock.NewMockDockerClientInterface(ctrl)453 cli := &client.Client{}454 patch, err := mpatch.PatchInstanceMethodByName(reflect.TypeOf(cli), "ImageBuild", mockDockerClientInterface.ImageBuild)455 if err != nil {456 t.Errorf("mpatch error")457 }458 patchIsValidFile(t, true)459 patchOpenFile(t, &os.File{}, nil)460 readerCloser := io.NopCloser(strings.NewReader("TestImageBuild Body!"))461 mockDockerClientInterface.EXPECT().462 ImageBuild(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(types.ImageBuildResponse{Body: readerCloser}, nil)463 return []*mpatch.Patch{patch}464 }465 openFileErrorFunc := func(t *testing.T, ctrl *gomock.Controller) []*mpatch.Patch {466 patchIsValidFile(t, true)467 patchOpenFile(t, nil, errPerm)468 return nil469 }470 imageBulildErrorFunc := func(t *testing.T, ctrl *gomock.Controller) []*mpatch.Patch {471 mockDockerClientInterface := clientmock.NewMockDockerClientInterface(ctrl)472 cli := &client.Client{}473 patch, err := mpatch.PatchInstanceMethodByName(reflect.TypeOf(cli), "ImageBuild", mockDockerClientInterface.ImageBuild)474 if err != nil {475 t.Errorf("mpatch error")476 }477 patchIsValidFile(t, true)478 patchOpenFile(t, &os.File{}, nil)479 mockDockerClientInterface.EXPECT().480 ImageBuild(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(types.ImageBuildResponse{}, testError)481 return []*mpatch.Patch{patch}482 }483 readBuildResponseErrorFunc := func(t *testing.T, ctrl *gomock.Controller) []*mpatch.Patch {484 mockDockerClientInterface := clientmock.NewMockDockerClientInterface(ctrl)485 cli := &client.Client{}486 patch, err := mpatch.PatchInstanceMethodByName(reflect.TypeOf(cli), "ImageBuild", mockDockerClientInterface.ImageBuild)487 if err != nil {488 t.Errorf("mpatch error")489 }490 patchIsValidFile(t, true)491 patchOpenFile(t, &os.File{}, nil)492 patchReadAll(t, nil, testError)493 readerCloser := io.NopCloser(strings.NewReader("TestImageBuild Body!"))494 mockDockerClientInterface.EXPECT().495 ImageBuild(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(types.ImageBuildResponse{Body: readerCloser}, nil)496 return []*mpatch.Patch{patch}497 }498 closeBuildResponseBodyErrorFunc := func(t *testing.T, ctrl *gomock.Controller) []*mpatch.Patch {499 mockDockerClientInterface := clientmock.NewMockDockerClientInterface(ctrl)500 cli := &client.Client{}501 patch, err := mpatch.PatchInstanceMethodByName(reflect.TypeOf(cli), "ImageBuild", mockDockerClientInterface.ImageBuild)502 if err != nil {503 t.Errorf("mpatch error")504 }505 patchIsValidFile(t, true)506 patchOpenFile(t, &os.File{}, nil)507 patchReadAll(t, nil, testError)508 mockDockerClientInterface.EXPECT().509 ImageBuild(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(types.ImageBuildResponse{Body: &os.File{}}, nil)510 return []*mpatch.Patch{patch}511 }512 cases := []struct {513 dockerBuildTar string514 dockerFilePathInTar string515 tag string516 wantErr error517 funcBeforeTest func(*testing.T, *gomock.Controller) []*mpatch.Patch518 funcAfterTest func()519 }{520 {521 dockerBuildTar: "tmp/TestImageBuild.test.data",522 dockerFilePathInTar: "test_file_path_in_tar",523 tag: "test_tag",524 wantErr: nil,525 funcBeforeTest: normalFunc,526 },527 {528 dockerBuildTar: "test_build_tar",529 dockerFilePathInTar: "test_file_path_in_tar",530 tag: "test_tag",531 wantErr: testError,532 funcBeforeTest: getDockerClientErrFunc,533 },534 {535 dockerBuildTar: "",536 dockerFilePathInTar: "test_file_path_in_tar",537 tag: "test_tag",538 wantErr: eputils.GetError("errInvalidFile"),539 funcBeforeTest: nil,540 },541 {542 dockerBuildTar: "tmp/TestImageBuild.test.data",543 dockerFilePathInTar: "test_file_path_in_tar",544 tag: "test_tag",545 wantErr: errPerm,546 funcBeforeTest: openFileErrorFunc,547 },548 {549 dockerBuildTar: "tmp/TestImageBuild.test.data",550 dockerFilePathInTar: "test_file_path_in_tar",551 tag: "test_tag",552 wantErr: testError,553 funcBeforeTest: imageBulildErrorFunc,554 },555 {556 dockerBuildTar: "tmp/TestImageBuild.test.data",557 dockerFilePathInTar: "test_file_path_in_tar",558 tag: "test_tag",559 wantErr: testError,560 funcBeforeTest: readBuildResponseErrorFunc,561 },562 {563 dockerBuildTar: "tmp/TestImageBuild.test.data",564 dockerFilePathInTar: "test_file_path_in_tar",565 tag: "test_tag",566 wantErr: errArg,567 funcBeforeTest: closeBuildResponseBodyErrorFunc,568 },569 }570 for n, testCase := range cases {571 t.Logf("TestImageBuild case %d start", n)572 func() {573 ctrl := gomock.NewController(t)574 defer ctrl.Finish()575 if testCase.funcBeforeTest != nil {576 pList := testCase.funcBeforeTest(t, ctrl)577 defer unpatchAll(t, pList)578 }579 err := ImageBuild(testCase.dockerBuildTar, testCase.dockerFilePathInTar, testCase.tag)580 if testCase.funcAfterTest != nil {581 testCase.funcAfterTest()582 }583 if !errors.Is(err, testCase.wantErr) &&584 (err == nil || !strings.Contains(err.Error(), testCase.wantErr.Error())) {585 t.Errorf("Unexpected error: %v", err)586 }587 }()588 t.Logf("TestImageBuild case %d end", n)589 }590 t.Log("Done")591}592func TestImageLoad(t *testing.T) {593 normalFunc := func(t *testing.T, ctrl *gomock.Controller) []*mpatch.Patch {594 patchStat(t, nil, nil)595 patchIsValidFile(t, true)596 patchOpenFile(t, &os.File{}, nil)597 mockDockerClientInterface := clientmock.NewMockDockerClientInterface(ctrl)598 cli := &client.Client{}599 patch, err := mpatch.PatchInstanceMethodByName(reflect.TypeOf(cli), "ImageLoad", mockDockerClientInterface.ImageLoad)600 if err != nil {601 t.Errorf("mpatch error")602 }603 readerCloser := io.NopCloser(strings.NewReader("TestImageLoad Body!"))604 mockDockerClientInterface.EXPECT().605 ImageLoad(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(types.ImageLoadResponse{Body: readerCloser}, nil)606 return []*mpatch.Patch{patch}607 }608 NotValidFileFunc := func(t *testing.T, ctrl *gomock.Controller) []*mpatch.Patch {609 patchStat(t, nil, nil)610 patchIsValidFile(t, false)611 return nil612 }613 openFileErrorFunc := func(t *testing.T, ctrl *gomock.Controller) []*mpatch.Patch {614 patchStat(t, nil, nil)615 patchIsValidFile(t, true)616 patchOpenFile(t, nil, testError)617 return nil618 }619 ImageLoadErrorFunc := func(t *testing.T, ctrl *gomock.Controller) []*mpatch.Patch {620 patchStat(t, nil, nil)621 patchIsValidFile(t, true)622 patchOpenFile(t, &os.File{}, nil)623 mockDockerClientInterface := clientmock.NewMockDockerClientInterface(ctrl)624 cli := &client.Client{}625 patch, err := mpatch.PatchInstanceMethodByName(reflect.TypeOf(cli), "ImageLoad", mockDockerClientInterface.ImageLoad)626 if err != nil {627 t.Errorf("mpatch error")628 }629 mockDockerClientInterface.EXPECT().630 ImageLoad(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(types.ImageLoadResponse{}, testError)631 return []*mpatch.Patch{patch}632 }633 readLoadResponseErrorFunc := func(t *testing.T, ctrl *gomock.Controller) []*mpatch.Patch {634 patchStat(t, nil, nil)635 patchIsValidFile(t, true)636 patchOpenFile(t, &os.File{}, nil)637 patchReadAll(t, nil, testError)638 mockDockerClientInterface := clientmock.NewMockDockerClientInterface(ctrl)639 cli := &client.Client{}640 patch, err := mpatch.PatchInstanceMethodByName(reflect.TypeOf(cli), "ImageLoad", mockDockerClientInterface.ImageLoad)641 if err != nil {642 t.Errorf("mpatch error")643 }644 mockDockerClientInterface.EXPECT().645 ImageLoad(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(types.ImageLoadResponse{Body: io.NopCloser(strings.NewReader(""))}, nil)646 return []*mpatch.Patch{patch}647 }648 closeResponseBodyErrorFunc := func(t *testing.T, ctrl *gomock.Controller) []*mpatch.Patch {649 patchStat(t, nil, nil)650 patchIsValidFile(t, true)651 patchOpenFile(t, &os.File{}, nil)652 patchReadAll(t, nil, testError)653 mockDockerClientInterface := clientmock.NewMockDockerClientInterface(ctrl)654 cli := &client.Client{}655 patch, err := mpatch.PatchInstanceMethodByName(reflect.TypeOf(cli), "ImageLoad", mockDockerClientInterface.ImageLoad)656 if err != nil {657 t.Errorf("mpatch error")658 }659 mockDockerClientInterface.EXPECT().660 ImageLoad(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(types.ImageLoadResponse{Body: &os.File{}}, nil)661 return []*mpatch.Patch{patch}662 }663 cases := []struct {664 tarball string665 wantErr error666 funcBeforeTest func(*testing.T, *gomock.Controller) []*mpatch.Patch667 funcAfterTest func()668 }{669 {670 tarball: "tmp/TestImageLoad.test.data",671 wantErr: nil,672 funcBeforeTest: normalFunc,673 },674 {675 tarball: "",676 wantErr: testError,677 funcBeforeTest: getDockerClientErrFunc,678 },679 {680 tarball: "tmp/TestImageLoad.test.data",681 wantErr: eputils.GetError("errInvalidFile"),682 funcBeforeTest: NotValidFileFunc,683 },684 {685 tarball: "test_tarball",686 wantErr: errFileDir,687 funcBeforeTest: nil,688 },689 {690 tarball: "tmp/TestImageLoad.test.data",691 wantErr: testError,692 funcBeforeTest: openFileErrorFunc,693 },694 {695 tarball: "tmp/TestImageLoad.test.data",696 wantErr: testError,697 funcBeforeTest: ImageLoadErrorFunc,698 },699 {700 tarball: "tmp/TestImageLoad.test.data",701 wantErr: testError,702 funcBeforeTest: readLoadResponseErrorFunc,703 },704 {705 tarball: "tmp/TestImageLoad.test.data",706 wantErr: errArg,707 funcBeforeTest: closeResponseBodyErrorFunc,708 },709 }710 for n, testCase := range cases {711 t.Logf("TestImageLoad case %d start", n)712 func() {713 ctrl := gomock.NewController(t)714 defer ctrl.Finish()715 if testCase.funcBeforeTest != nil {716 pList := testCase.funcBeforeTest(t, ctrl)717 defer unpatchAll(t, pList)718 }719 err := ImageLoad(testCase.tarball)720 if testCase.funcAfterTest != nil {721 testCase.funcAfterTest()722 }723 if !errors.Is(err, testCase.wantErr) &&724 (err == nil || !strings.Contains(err.Error(), testCase.wantErr.Error())) {725 t.Errorf("Unexpected error: %v", err)726 }727 }()728 t.Logf("TestImageLoad case %d end", n)729 }730 t.Log("Done")731}732func TestCreateContainer(t *testing.T) {733 normalFunc := func(t *testing.T, ctrl *gomock.Controller) []*mpatch.Patch {734 mockDockerClientInterface := clientmock.NewMockDockerClientInterface(ctrl)735 mockDockerClientWrapperImage := clientmock.NewMockDockerClientWrapperImage(ctrl)736 cli := &client.Client{}737 patchNetworkCreate, err := mpatch.PatchInstanceMethodByName(reflect.TypeOf(cli), "NetworkCreate", mockDockerClientInterface.NetworkCreate)738 if err != nil {739 t.Errorf("mpatch error")740 }741 patchContainerCreate, err := mpatch.PatchInstanceMethodByName(reflect.TypeOf(cli), "ContainerCreate", mockDockerClientInterface.ContainerCreate)742 if err != nil {743 t.Errorf("mpatch error")744 }745 patchImagePull, err := mpatch.PatchMethod(ImagePull, mockDockerClientWrapperImage.ImagePull)746 if err != nil {747 t.Errorf("mpatch error")748 }749 mockDockerClientWrapperImage.EXPECT().ImagePull(gomock.Any(), gomock.Any()).Return(nil).Times(1)750 mockDockerClientInterface.EXPECT().751 NetworkCreate(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).752 Return(types.NetworkCreateResponse{}, nil)753 mockDockerClientInterface.EXPECT().754 ContainerCreate(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).755 Return(container.ContainerCreateCreatedBody{ID: "test_id"}, nil)756 return []*mpatch.Patch{patchNetworkCreate, patchContainerCreate, patchImagePull}757 }758 ImagePullErrFunc := func(t *testing.T, ctrl *gomock.Controller) []*mpatch.Patch {759 patchImagePull, err := mpatch.PatchMethod(ImagePull, func(imageRef string, authConf *types.AuthConfig) error {760 return testError761 })762 if err != nil {763 t.Errorf("mpatch error")764 }765 return []*mpatch.Patch{patchImagePull}766 }767 NetworkCreateErrorFunc := func(t *testing.T, ctrl *gomock.Controller) []*mpatch.Patch {768 mockDockerClientInterface := clientmock.NewMockDockerClientInterface(ctrl)769 cli := &client.Client{}770 patch, err := mpatch.PatchInstanceMethodByName(reflect.TypeOf(cli), "NetworkCreate", mockDockerClientInterface.NetworkCreate)771 if err != nil {772 t.Errorf("mpatch error")773 }774 mockDockerClientInterface.EXPECT().775 NetworkCreate(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).776 Return(types.NetworkCreateResponse{}, testError)777 return []*mpatch.Patch{patch}778 }779 containerCreateErrorFunc := func(t *testing.T, ctrl *gomock.Controller) []*mpatch.Patch {780 cli := &client.Client{}781 mockDockerClientInterface := clientmock.NewMockDockerClientInterface(ctrl)782 patch, err := mpatch.PatchInstanceMethodByName(reflect.TypeOf(cli), "ContainerCreate", mockDockerClientInterface.ContainerCreate)783 if err != nil {784 t.Errorf("mpatch error")785 }786 mockDockerClientInterface.EXPECT().787 ContainerCreate(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).788 Return(container.ContainerCreateCreatedBody{}, testError)789 return []*mpatch.Patch{patch}790 }791 cases := []struct {792 imageName string793 containerName string794 hostName string795 networkMode string796 networkNames []string797 userInContainer string798 ports []string799 needPullImage bool800 wantRespId string801 wantErr error802 funcBeforeTest func(*testing.T, *gomock.Controller) []*mpatch.Patch803 funcAfterTest func()804 }{805 {806 imageName: "test_image",807 containerName: "test_container_name",808 hostName: "test_host",809 networkMode: "macvlan",810 networkNames: []string{"test_network_name"},811 userInContainer: "test_user",812 needPullImage: true,813 wantRespId: "test_id",814 wantErr: nil,815 funcBeforeTest: normalFunc,816 },817 {818 wantRespId: "",819 wantErr: testError,820 funcBeforeTest: getDockerClientErrFunc,821 },822 {823 wantRespId: "",824 needPullImage: true,825 wantErr: testError,826 funcBeforeTest: ImagePullErrFunc,827 },828 {829 networkMode: "macvlan",830 ports: []string{"___...|||"},831 needPullImage: false,832 wantRespId: "",833 wantErr: errPortInv,834 funcBeforeTest: nil,835 },836 {837 networkMode: "macvlan",838 networkNames: []string{"test_network_name"},839 ports: []string{"8000:8000"},840 needPullImage: false,841 wantRespId: "",842 wantErr: testError,843 funcBeforeTest: NetworkCreateErrorFunc,844 },845 {846 networkMode: "macvlan",847 needPullImage: false,848 wantRespId: "",849 wantErr: testError,850 funcBeforeTest: containerCreateErrorFunc,851 },852 }853 for n, testCase := range cases {854 t.Logf("TestCreateContainer case %d start", n)855 func() {856 ctrl := gomock.NewController(t)857 defer ctrl.Finish()858 if testCase.funcBeforeTest != nil {859 pList := testCase.funcBeforeTest(t, ctrl)860 defer unpatchAll(t, pList)861 }862 respId, err := CreateContainer(863 testCase.imageName,864 testCase.containerName,865 testCase.hostName,866 testCase.networkMode,867 testCase.networkNames,868 testCase.userInContainer,869 true, testCase.needPullImage, true, true,870 nil, nil, nil, nil, nil, testCase.ports, nil, nil, nil,871 "restart",872 )873 if testCase.funcAfterTest != nil {874 testCase.funcAfterTest()875 }876 if !errors.Is(err, testCase.wantErr) &&877 (err == nil || !strings.Contains(err.Error(), testCase.wantErr.Error())) {878 t.Errorf("Unexpected error: %v", err)879 }880 if respId != testCase.wantRespId {881 t.Errorf("Get wrong resp id: %v", respId)882 }883 }()884 t.Logf("TestCreateContainer case %d end", n)885 }886 t.Log("Done")887}888func TestStartContainer(t *testing.T) {889 normalFunc := func(t *testing.T, ctrl *gomock.Controller) []*mpatch.Patch {890 cli := &client.Client{}891 mockDockerClientInterface := clientmock.NewMockDockerClientInterface(ctrl)892 mockDockerClientWrapperContainer := clientmock.NewMockDockerClientWrapperContainer(ctrl)893 patchContainerStart, err := mpatch.PatchInstanceMethodByName(reflect.TypeOf(cli), "ContainerStart", mockDockerClientInterface.ContainerStart)894 if err != nil {895 t.Errorf("mpatch error")896 }897 patchContainerLogs, err := mpatch.PatchInstanceMethodByName(reflect.TypeOf(cli), "ContainerLogs", mockDockerClientInterface.ContainerLogs)898 if err != nil {899 t.Errorf("mpatch error")900 }901 patchGetContainerByName, err := mpatch.PatchMethod(GetContainerByName, mockDockerClientWrapperContainer.GetContainerByName)902 if err != nil {903 t.Errorf("mpatch error")904 }905 patchContainerInspect, err := mpatch.PatchInstanceMethodByName(reflect.TypeOf(cli), "ContainerInspect", mockDockerClientInterface.ContainerInspect)906 if err != nil {907 t.Errorf("mpatch error")908 }909 mockDockerClientWrapperContainer.EXPECT().910 GetContainerByName(gomock.Any()).911 Return(&types.Container{ID: "test_id"}, nil).Times(1)912 mockDockerClientInterface.EXPECT().913 ContainerStart(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).914 Return(nil)915 readerCloser := io.NopCloser(strings.NewReader("Hello, world!"))916 mockDockerClientInterface.EXPECT().917 ContainerLogs(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).918 Return(readerCloser, nil)919 test_ExitCode := types.ContainerState{ExitCode: 0}920 test_ContainerJsonBase := types.ContainerJSONBase{State: &test_ExitCode}921 res := types.ContainerJSON{ContainerJSONBase: &test_ContainerJsonBase, Mounts: nil, Config: nil, NetworkSettings: nil}922 mockDockerClientInterface.EXPECT().923 ContainerInspect(gomock.Any(), gomock.Any(), gomock.Any()).924 Return(res, nil)925 return []*mpatch.Patch{patchContainerStart, patchContainerLogs, patchGetContainerByName, patchContainerInspect}926 }927 getContainerNameErrorFunc := func(t *testing.T, ctrl *gomock.Controller) []*mpatch.Patch {928 mockDockerClientWrapperContainer := clientmock.NewMockDockerClientWrapperContainer(ctrl)929 patch, err := mpatch.PatchMethod(GetContainerByName, mockDockerClientWrapperContainer.GetContainerByName)930 if err != nil {931 t.Errorf("mpatch error")932 }933 mockDockerClientWrapperContainer.EXPECT().934 GetContainerByName(gomock.Any()).Return(nil, testError).Times(1)935 return []*mpatch.Patch{patch}936 }937 getContainerNameNilFunc := func(t *testing.T, ctrl *gomock.Controller) []*mpatch.Patch {938 mockDockerClientWrapperContainer := clientmock.NewMockDockerClientWrapperContainer(ctrl)939 patch, err := mpatch.PatchMethod(GetContainerByName, mockDockerClientWrapperContainer.GetContainerByName)940 if err != nil {941 t.Errorf("mpatch error")942 }943 mockDockerClientWrapperContainer.EXPECT().944 GetContainerByName(gomock.Any()).Return(nil, nil).Times(1)945 return []*mpatch.Patch{patch}946 }947 startContainerErrorFunc := func(t *testing.T, ctrl *gomock.Controller) []*mpatch.Patch {948 cli := &client.Client{}949 mockDockerClientInterface := clientmock.NewMockDockerClientInterface(ctrl)950 patch, err := mpatch.PatchInstanceMethodByName(reflect.TypeOf(cli), "ContainerStart", mockDockerClientInterface.ContainerStart)951 if err != nil {952 t.Errorf("mpatch error")953 }954 mockDockerClientInterface.EXPECT().955 ContainerStart(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).956 Return(testError)957 return []*mpatch.Patch{patch}958 }959 containerLogsErrorFunc := func(t *testing.T, ctrl *gomock.Controller) []*mpatch.Patch {960 cli := &client.Client{}961 mockDockerClientInterface := clientmock.NewMockDockerClientInterface(ctrl)962 patchContainerStart, err := mpatch.PatchInstanceMethodByName(reflect.TypeOf(cli), "ContainerStart", mockDockerClientInterface.ContainerStart)963 if err != nil {964 t.Errorf("mpatch error")965 }966 patchContainerLogs, err := mpatch.PatchInstanceMethodByName(reflect.TypeOf(cli), "ContainerLogs", mockDockerClientInterface.ContainerLogs)967 if err != nil {968 t.Errorf("mpatch error")969 }970 mockDockerClientInterface.EXPECT().971 ContainerStart(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).972 Return(nil)973 mockDockerClientInterface.EXPECT().974 ContainerLogs(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).975 Return(nil, testError)976 return []*mpatch.Patch{patchContainerStart, patchContainerLogs}977 }978 containerInspectErrorFunc := func(t *testing.T, ctrl *gomock.Controller) []*mpatch.Patch {979 cli := &client.Client{}980 mockDockerClientInterface := clientmock.NewMockDockerClientInterface(ctrl)981 mockDockerClientWrapperContainer := clientmock.NewMockDockerClientWrapperContainer(ctrl)982 patchGetContainerByName, err := mpatch.PatchMethod(GetContainerByName, mockDockerClientWrapperContainer.GetContainerByName)983 if err != nil {984 t.Errorf("mpatch error")985 }986 patchContainerStart, err := mpatch.PatchInstanceMethodByName(reflect.TypeOf(cli), "ContainerStart", mockDockerClientInterface.ContainerStart)987 if err != nil {988 t.Errorf("mpatch error")989 }990 patchContainerLogs, err := mpatch.PatchInstanceMethodByName(reflect.TypeOf(cli), "ContainerLogs", mockDockerClientInterface.ContainerLogs)991 if err != nil {992 t.Errorf("mpatch error")993 }994 patchContainerInspect, err := mpatch.PatchInstanceMethodByName(reflect.TypeOf(cli), "ContainerInspect", mockDockerClientInterface.ContainerInspect)995 if err != nil {996 t.Errorf("mpatch error")997 }998 mockDockerClientWrapperContainer.EXPECT().999 GetContainerByName(gomock.Any()).1000 Return(&types.Container{ID: "test_id"}, nil).AnyTimes()1001 mockDockerClientInterface.EXPECT().1002 ContainerStart(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).1003 Return(nil)1004 readerCloser := io.NopCloser(strings.NewReader("Hello, world!"))1005 mockDockerClientInterface.EXPECT().1006 ContainerLogs(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).1007 Return(readerCloser, nil)1008 mockDockerClientInterface.EXPECT().1009 ContainerInspect(gomock.Any(), gomock.Any(), gomock.Any()).1010 Return(types.ContainerJSON{}, testError)1011 return []*mpatch.Patch{patchGetContainerByName, patchContainerStart, patchContainerLogs, patchContainerInspect}1012 }1013 containerInspectNilFunc := func(t *testing.T, ctrl *gomock.Controller) []*mpatch.Patch {1014 cli := &client.Client{}1015 mockDockerClientInterface := clientmock.NewMockDockerClientInterface(ctrl)1016 mockDockerClientWrapperContainer := clientmock.NewMockDockerClientWrapperContainer(ctrl)1017 patchGetContainerByName, err := mpatch.PatchMethod(GetContainerByName, mockDockerClientWrapperContainer.GetContainerByName)1018 if err != nil {1019 t.Errorf("mpatch error")1020 }1021 patchContainerStart, err := mpatch.PatchInstanceMethodByName(reflect.TypeOf(cli), "ContainerStart", mockDockerClientInterface.ContainerStart)1022 if err != nil {1023 t.Errorf("mpatch error")1024 }1025 patchContainerLogs, err := mpatch.PatchInstanceMethodByName(reflect.TypeOf(cli), "ContainerLogs", mockDockerClientInterface.ContainerLogs)1026 if err != nil {1027 t.Errorf("mpatch error")1028 }1029 patchContainerInspect, err := mpatch.PatchInstanceMethodByName(reflect.TypeOf(cli), "ContainerInspect", mockDockerClientInterface.ContainerInspect)1030 if err != nil {1031 t.Errorf("mpatch error")1032 }1033 mockDockerClientWrapperContainer.EXPECT().1034 GetContainerByName(gomock.Any()).1035 Return(&types.Container{ID: "test_id"}, nil).AnyTimes()1036 mockDockerClientInterface.EXPECT().1037 ContainerStart(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).1038 Return(nil)1039 readerCloser := io.NopCloser(strings.NewReader("Hello, world!"))1040 mockDockerClientInterface.EXPECT().1041 ContainerLogs(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).1042 Return(readerCloser, nil)1043 mockDockerClientInterface.EXPECT().1044 ContainerInspect(gomock.Any(), gomock.Any(), gomock.Any()).1045 Return(types.ContainerJSON{}, nil)1046 return []*mpatch.Patch{patchGetContainerByName, patchContainerStart, patchContainerLogs, patchContainerInspect}1047 }1048 containerInspectExitCodeErrorFunc := func(t *testing.T, ctrl *gomock.Controller) []*mpatch.Patch {1049 cli := &client.Client{}1050 mockDockerClientInterface := clientmock.NewMockDockerClientInterface(ctrl)1051 mockDockerClientWrapperContainer := clientmock.NewMockDockerClientWrapperContainer(ctrl)1052 patchGetContainerByName, err := mpatch.PatchMethod(GetContainerByName, mockDockerClientWrapperContainer.GetContainerByName)1053 if err != nil {1054 t.Errorf("mpatch error")1055 }1056 patchContainerStart, err := mpatch.PatchInstanceMethodByName(reflect.TypeOf(cli), "ContainerStart", mockDockerClientInterface.ContainerStart)1057 if err != nil {1058 t.Errorf("mpatch error")1059 }1060 patchContainerLogs, err := mpatch.PatchInstanceMethodByName(reflect.TypeOf(cli), "ContainerLogs", mockDockerClientInterface.ContainerLogs)1061 if err != nil {1062 t.Errorf("mpatch error")1063 }1064 patchContainerInspect, err := mpatch.PatchInstanceMethodByName(reflect.TypeOf(cli), "ContainerInspect", mockDockerClientInterface.ContainerInspect)1065 if err != nil {1066 t.Errorf("mpatch error")1067 }1068 mockDockerClientWrapperContainer.EXPECT().1069 GetContainerByName(gomock.Any()).1070 Return(&types.Container{ID: "test_id"}, nil).AnyTimes()1071 mockDockerClientInterface.EXPECT().1072 ContainerStart(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).1073 Return(nil)1074 readerCloser := io.NopCloser(strings.NewReader("Hello, world!"))1075 mockDockerClientInterface.EXPECT().1076 ContainerLogs(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).1077 Return(readerCloser, nil)1078 test_ExitCode := types.ContainerState{ExitCode: 1}1079 test_ContainerJsonBase := types.ContainerJSONBase{State: &test_ExitCode}1080 res := types.ContainerJSON{ContainerJSONBase: &test_ContainerJsonBase, Mounts: nil, Config: nil, NetworkSettings: nil}1081 mockDockerClientInterface.EXPECT().1082 ContainerInspect(gomock.Any(), gomock.Any(), gomock.Any()).1083 Return(res, nil)1084 return []*mpatch.Patch{patchContainerStart, patchContainerLogs, patchGetContainerByName, patchContainerInspect}1085 }1086 cases := []struct {1087 containerID string1088 containerName string1089 runInBackground bool1090 wantErr error1091 funcBeforeTest func(*testing.T, *gomock.Controller) []*mpatch.Patch1092 funcAfterTest func()1093 }{1094 {1095 containerID: "",1096 containerName: "test_container_name",1097 runInBackground: false,1098 wantErr: nil,1099 funcBeforeTest: normalFunc,1100 },1101 {1102 containerID: "",1103 containerName: "test_container_name",1104 wantErr: testError,1105 funcBeforeTest: getDockerClientErrFunc,1106 },1107 {1108 containerID: "",1109 containerName: "test_container_name",1110 wantErr: testError,1111 funcBeforeTest: getContainerNameErrorFunc,1112 },1113 {1114 containerID: "",1115 containerName: "test_container_name",1116 wantErr: eputils.GetError("errNoContainer"),1117 funcBeforeTest: getContainerNameNilFunc,1118 },1119 {1120 containerID: "test_container_id",1121 containerName: "test_container_name",1122 runInBackground: true,1123 wantErr: testError,1124 funcBeforeTest: startContainerErrorFunc,1125 },1126 {1127 containerID: "test_container_id",1128 containerName: "test_container_name",1129 runInBackground: false,1130 wantErr: testError,1131 funcBeforeTest: containerLogsErrorFunc,1132 },1133 {1134 containerID: "test_container_id",1135 containerName: "test_container_name",1136 runInBackground: false,1137 wantErr: testError,1138 funcBeforeTest: containerInspectErrorFunc,1139 },1140 {1141 containerID: "test_container_id",1142 containerName: "test_container_name",1143 runInBackground: false,1144 wantErr: eputils.GetError("errAbnormalExit"),1145 funcBeforeTest: containerInspectNilFunc,1146 },1147 {1148 containerID: "test_container_id",1149 containerName: "test_container_name",1150 runInBackground: false,1151 wantErr: eputils.GetError("errAbnormalExit"),1152 funcBeforeTest: containerInspectExitCodeErrorFunc,1153 },1154 }1155 for n, testCase := range cases {1156 t.Logf("TestStartContainer case %d start", n)1157 func() {1158 ctrl := gomock.NewController(t)1159 defer ctrl.Finish()1160 if testCase.funcBeforeTest != nil {1161 pList := testCase.funcBeforeTest(t, ctrl)1162 defer unpatchAll(t, pList)1163 }1164 err := StartContainer(testCase.containerID, testCase.containerName, testCase.runInBackground)1165 if testCase.funcAfterTest != nil {1166 testCase.funcAfterTest()1167 }1168 if !errors.Is(err, testCase.wantErr) &&1169 (err == nil || !strings.Contains(err.Error(), testCase.wantErr.Error())) {1170 t.Errorf("Unexpected error: %v", err)1171 }1172 }()1173 t.Logf("TestStartContainer case %d end", n)1174 }1175 t.Log("Done")1176}1177func TestRunContainer(t *testing.T) {1178 normalFunc := func(t *testing.T, ctrl *gomock.Controller) []*mpatch.Patch {1179 mockDockerClientWrapperContainer := clientmock.NewMockDockerClientWrapperContainer(ctrl)1180 patchCreateContainer, err := mpatch.PatchMethod(CreateContainer, mockDockerClientWrapperContainer.CreateContainer)1181 if err != nil {1182 t.Errorf("mpatch error")1183 }1184 patchStartContainer, err := mpatch.PatchMethod(StartContainer, mockDockerClientWrapperContainer.StartContainer)1185 if err != nil {1186 t.Errorf("mpatch error")1187 }1188 mockDockerClientWrapperContainer.EXPECT().1189 CreateContainer(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(),1190 gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(),1191 gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).1192 Return("test_id", nil).Times(1)1193 mockDockerClientWrapperContainer.EXPECT().1194 StartContainer(gomock.Any(), gomock.Any(), gomock.Any()).1195 Return(nil).Times(1)1196 return []*mpatch.Patch{patchCreateContainer, patchStartContainer}1197 }1198 createContainerErrorFunc := func(t *testing.T, ctrl *gomock.Controller) []*mpatch.Patch {1199 mockDockerClientWrapperContainer := clientmock.NewMockDockerClientWrapperContainer(ctrl)1200 patchCreateContainer, err := mpatch.PatchMethod(CreateContainer, mockDockerClientWrapperContainer.CreateContainer)1201 if err != nil {1202 t.Errorf("mpatch error")1203 }1204 mockDockerClientWrapperContainer.EXPECT().1205 CreateContainer(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(),1206 gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(),1207 gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).1208 Return("", testError).Times(1)1209 return []*mpatch.Patch{patchCreateContainer}1210 }1211 startContainerErrorFunc := func(t *testing.T, ctrl *gomock.Controller) []*mpatch.Patch {1212 mockDockerClientWrapperContainer := clientmock.NewMockDockerClientWrapperContainer(ctrl)1213 patchCreateContainer, err := mpatch.PatchMethod(CreateContainer, mockDockerClientWrapperContainer.CreateContainer)1214 if err != nil {1215 t.Errorf("mpatch error")1216 }1217 patchStartContainer, err := mpatch.PatchMethod(StartContainer, mockDockerClientWrapperContainer.StartContainer)1218 if err != nil {1219 t.Errorf("mpatch error")1220 }1221 mockDockerClientWrapperContainer.EXPECT().1222 CreateContainer(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(),1223 gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(),1224 gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).1225 Return("test_id", nil).Times(1)1226 mockDockerClientWrapperContainer.EXPECT().1227 StartContainer(gomock.Any(), gomock.Any(), gomock.Any()).1228 Return(testError).Times(1)1229 return []*mpatch.Patch{patchCreateContainer, patchStartContainer}1230 }1231 cases := []struct {1232 wantCntId string1233 wantErr error1234 funcBeforeTest func(*testing.T, *gomock.Controller) []*mpatch.Patch1235 funcAfterTest func()1236 }{1237 {1238 wantCntId: "test_id",1239 wantErr: nil,1240 funcBeforeTest: normalFunc,1241 },1242 {1243 wantCntId: "",1244 wantErr: testError,1245 funcBeforeTest: createContainerErrorFunc,1246 },1247 {1248 wantCntId: "test_id",1249 wantErr: testError,1250 funcBeforeTest: startContainerErrorFunc,1251 },1252 }1253 ctrl := gomock.NewController(t)1254 defer ctrl.Finish()1255 for n, testCase := range cases {1256 t.Logf("TestRunContainer case %d start", n)1257 func() {1258 ctrl := gomock.NewController(t)1259 defer ctrl.Finish()1260 if testCase.funcBeforeTest != nil {1261 pList := testCase.funcBeforeTest(t, ctrl)1262 defer unpatchAll(t, pList)1263 }1264 cntId, err := RunContainer("test_image",1265 "test_container_name",1266 "test_host",1267 "macvlan",1268 []string{"test_network_name"},1269 "test_user",1270 true, true, true, true,1271 nil, nil, nil, nil, nil, nil, nil, nil, nil,1272 "restart")1273 if testCase.funcAfterTest != nil {1274 testCase.funcAfterTest()1275 }1276 if !errors.Is(err, testCase.wantErr) &&1277 (err == nil || !strings.Contains(err.Error(), testCase.wantErr.Error())) {1278 t.Errorf("Unexpected error: %v", err)1279 }1280 if cntId != testCase.wantCntId {1281 t.Errorf("Get wrong container id: %v", cntId)1282 }1283 }()1284 t.Logf("TestRunContainer case %d end", n)1285 }1286 t.Log("Done")1287}1288func TestStopContainer(t *testing.T) {1289 normalFunc := func(t *testing.T, ctrl *gomock.Controller) []*mpatch.Patch {1290 cli := &client.Client{}1291 mockDockerClientInterface := clientmock.NewMockDockerClientInterface(ctrl)1292 mockDockerClientWrapperContainer := clientmock.NewMockDockerClientWrapperContainer(ctrl)1293 patchContainerStop, err := mpatch.PatchInstanceMethodByName(reflect.TypeOf(cli), "ContainerStop", mockDockerClientInterface.ContainerStop)1294 if err != nil {1295 t.Errorf("mpatch error")1296 }1297 patchGetContainerByName, err := mpatch.PatchMethod(GetContainerByName, mockDockerClientWrapperContainer.GetContainerByName)1298 if err != nil {1299 t.Errorf("mpatch error")1300 }1301 mockDockerClientWrapperContainer.EXPECT().1302 GetContainerByName(gomock.Any()).Return(&types.Container{ID: "test_id123456789", State: "running"}, nil).Times(1)1303 mockDockerClientInterface.EXPECT().1304 ContainerStop(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).1305 Return(nil)1306 return []*mpatch.Patch{patchContainerStop, patchGetContainerByName}1307 }1308 getContainerByNameErrorFunc := func(t *testing.T, ctrl *gomock.Controller) []*mpatch.Patch {1309 patchGetContainerByName, err := mpatch.PatchMethod(GetContainerByName, func(containerName string) (*types.Container, error) {1310 return nil, testError1311 })1312 if err != nil {1313 t.Errorf("mpatch error")1314 }1315 return []*mpatch.Patch{patchGetContainerByName}1316 }1317 containerStopErrorFunc := func(t *testing.T, ctrl *gomock.Controller) []*mpatch.Patch {1318 cli := &client.Client{}1319 mockDockerClientInterface := clientmock.NewMockDockerClientInterface(ctrl)1320 mockDockerClientWrapperContainer := clientmock.NewMockDockerClientWrapperContainer(ctrl)1321 patchContainerStop, err := mpatch.PatchInstanceMethodByName(reflect.TypeOf(cli), "ContainerStop", mockDockerClientInterface.ContainerStop)1322 if err != nil {1323 t.Errorf("mpatch error")1324 }1325 patchGetContainerByName, err := mpatch.PatchMethod(GetContainerByName, mockDockerClientWrapperContainer.GetContainerByName)1326 if err != nil {1327 t.Errorf("mpatch error")1328 }1329 mockDockerClientWrapperContainer.EXPECT().1330 GetContainerByName(gomock.Any()).Return(&types.Container{ID: "test_id123456789", State: "running"}, nil).Times(1)1331 mockDockerClientInterface.EXPECT().1332 ContainerStop(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).1333 Return(testError)1334 return []*mpatch.Patch{patchContainerStop, patchGetContainerByName}1335 }1336 cases := []struct {1337 containerName string1338 wantErr error1339 funcBeforeTest func(*testing.T, *gomock.Controller) []*mpatch.Patch1340 funcAfterTest func()1341 }{1342 {1343 containerName: "test_container_name",1344 wantErr: nil,1345 funcBeforeTest: normalFunc,1346 },1347 {1348 containerName: "test_container_name",1349 wantErr: testError,1350 funcBeforeTest: getDockerClientErrFunc,1351 },1352 {1353 containerName: "test_container_name",1354 wantErr: testError,1355 funcBeforeTest: getContainerByNameErrorFunc,1356 },1357 {1358 containerName: "test_container_name",1359 wantErr: testError,1360 funcBeforeTest: containerStopErrorFunc,1361 },1362 }1363 for n, testCase := range cases {1364 t.Logf("TestStopContainer case %d start", n)1365 func() {1366 ctrl := gomock.NewController(t)1367 defer ctrl.Finish()1368 if testCase.funcBeforeTest != nil {1369 pList := testCase.funcBeforeTest(t, ctrl)1370 defer unpatchAll(t, pList)1371 }1372 err := StopContainer(testCase.containerName)1373 if testCase.funcAfterTest != nil {1374 testCase.funcAfterTest()1375 }1376 if !errors.Is(err, testCase.wantErr) &&1377 (err == nil || !strings.Contains(err.Error(), testCase.wantErr.Error())) {1378 t.Errorf("Unexpected error: %v", err)1379 }1380 }()1381 t.Logf("TestStopContainer case %d end", n)1382 }1383 t.Log("Done")1384}1385func TestRemoveContainer(t *testing.T) {1386 normalFunc := func(t *testing.T, ctrl *gomock.Controller) []*mpatch.Patch {1387 cli := &client.Client{}1388 mockDockerClientInterface := clientmock.NewMockDockerClientInterface(ctrl)1389 mockDockerClientWrapperContainer := clientmock.NewMockDockerClientWrapperContainer(ctrl)1390 patchContainerRemove, err := mpatch.PatchInstanceMethodByName(reflect.TypeOf(cli), "ContainerRemove", mockDockerClientInterface.ContainerRemove)1391 if err != nil {1392 t.Errorf("mpatch error")1393 }1394 patchStopContainer, err := mpatch.PatchMethod(StopContainer, mockDockerClientWrapperContainer.StopContainer)1395 if err != nil {1396 t.Errorf("mpatch error")1397 }1398 patchGetGetContainerByName, err := mpatch.PatchMethod(GetContainerByName, mockDockerClientWrapperContainer.GetContainerByName)1399 if err != nil {1400 t.Errorf("mpatch error")1401 }1402 mockDockerClientWrapperContainer.EXPECT().1403 StopContainer(gomock.Any()).Return(nil).Times(1)1404 mockDockerClientWrapperContainer.EXPECT().1405 GetContainerByName(gomock.Any()).Return(&types.Container{ID: "test_id123456789", State: "running"}, nil).Times(1)1406 mockDockerClientInterface.EXPECT().1407 ContainerRemove(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).1408 Return(nil)1409 return []*mpatch.Patch{patchContainerRemove, patchStopContainer, patchGetGetContainerByName}1410 }1411 stopContainerErrorFunc := func(t *testing.T, ctrl *gomock.Controller) []*mpatch.Patch {1412 mockDockerClientWrapperContainer := clientmock.NewMockDockerClientWrapperContainer(ctrl)1413 patchStopContainer, err := mpatch.PatchMethod(StopContainer, mockDockerClientWrapperContainer.StopContainer)1414 if err != nil {1415 t.Errorf("mpatch error")1416 }1417 mockDockerClientWrapperContainer.EXPECT().1418 StopContainer(gomock.Any()).Return(testError).Times(1)1419 return []*mpatch.Patch{patchStopContainer}1420 }1421 getContainerByNameErrorFunc := func(t *testing.T, ctrl *gomock.Controller) []*mpatch.Patch {1422 mockDockerClientWrapperContainer := clientmock.NewMockDockerClientWrapperContainer(ctrl)1423 patchStopContainer, err := mpatch.PatchMethod(StopContainer, mockDockerClientWrapperContainer.StopContainer)1424 if err != nil {1425 t.Errorf("mpatch error")1426 }1427 patchGetGetContainerByName, err := mpatch.PatchMethod(GetContainerByName, mockDockerClientWrapperContainer.GetContainerByName)1428 if err != nil {1429 t.Errorf("mpatch error")1430 }1431 mockDockerClientWrapperContainer.EXPECT().1432 StopContainer(gomock.Any()).Return(nil).Times(1)1433 mockDockerClientWrapperContainer.EXPECT().1434 GetContainerByName(gomock.Any()).Return(nil, testError).Times(1)1435 return []*mpatch.Patch{patchStopContainer, patchGetGetContainerByName}1436 }1437 containerRemoveErrorFunc := func(t *testing.T, ctrl *gomock.Controller) []*mpatch.Patch {1438 cli := &client.Client{}1439 mockDockerClientInterface := clientmock.NewMockDockerClientInterface(ctrl)1440 mockDockerClientWrapperContainer := clientmock.NewMockDockerClientWrapperContainer(ctrl)1441 patchContainerRemove, err := mpatch.PatchInstanceMethodByName(reflect.TypeOf(cli), "ContainerRemove", mockDockerClientInterface.ContainerRemove)1442 if err != nil {1443 t.Errorf("mpatch error")1444 }1445 patchStopContainer, err := mpatch.PatchMethod(StopContainer, mockDockerClientWrapperContainer.StopContainer)1446 if err != nil {1447 t.Errorf("mpatch error")1448 }1449 patchGetGetContainerByName, err := mpatch.PatchMethod(GetContainerByName, mockDockerClientWrapperContainer.GetContainerByName)1450 if err != nil {1451 t.Errorf("mpatch error")1452 }1453 mockDockerClientWrapperContainer.EXPECT().1454 StopContainer(gomock.Any()).Return(nil).Times(1)1455 mockDockerClientWrapperContainer.EXPECT().1456 GetContainerByName(gomock.Any()).Return(&types.Container{ID: "test_id123456789", State: "running"}, nil).Times(1)1457 mockDockerClientInterface.EXPECT().1458 ContainerRemove(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).1459 Return(testError)1460 return []*mpatch.Patch{patchContainerRemove, patchStopContainer, patchGetGetContainerByName}1461 }1462 cases := []struct {1463 containerName string1464 wantErr error1465 funcBeforeTest func(*testing.T, *gomock.Controller) []*mpatch.Patch1466 funcAfterTest func()1467 }{1468 {1469 containerName: "test_container_name",1470 wantErr: nil,1471 funcBeforeTest: normalFunc,1472 },1473 {1474 containerName: "test_container_name",1475 wantErr: testError,1476 funcBeforeTest: getDockerClientErrFunc,1477 },1478 {1479 containerName: "test_container_name",1480 wantErr: testError,1481 funcBeforeTest: stopContainerErrorFunc,1482 },1483 {1484 containerName: "test_container_name",1485 wantErr: testError,1486 funcBeforeTest: getContainerByNameErrorFunc,1487 },1488 {1489 containerName: "test_container_name",1490 wantErr: testError,1491 funcBeforeTest: containerRemoveErrorFunc,1492 },1493 }1494 for n, testCase := range cases {1495 t.Logf("TestRemoveContainer case %d start", n)1496 func() {1497 ctrl := gomock.NewController(t)1498 defer ctrl.Finish()1499 if testCase.funcBeforeTest != nil {1500 pList := testCase.funcBeforeTest(t, ctrl)1501 defer unpatchAll(t, pList)1502 }1503 err := RemoveContainer(testCase.containerName)1504 if testCase.funcAfterTest != nil {1505 testCase.funcAfterTest()1506 }1507 if !errors.Is(err, testCase.wantErr) &&1508 (err == nil || !strings.Contains(err.Error(), testCase.wantErr.Error())) {1509 t.Errorf("Unexpected error: %v", err)1510 }1511 }()1512 t.Logf("TestRemoveContainer case %d end", n)1513 }1514 t.Log("Done")1515}1516func TestTagImageToLocal(t *testing.T) {1517 normalFunc := func(ctrl *gomock.Controller, retErr error) []*mpatch.Patch {1518 cli := &client.Client{}1519 mockDockerClientInterface := clientmock.NewMockDockerClientInterface(ctrl)1520 patchImageInspectWithRaw, err := mpatch.PatchInstanceMethodByName(reflect.TypeOf(cli), "ImageInspectWithRaw", mockDockerClientInterface.ImageInspectWithRaw)1521 if err != nil {1522 t.Errorf("mpatch error")1523 }1524 patchImageTag, err := mpatch.PatchInstanceMethodByName(reflect.TypeOf(cli), "ImageTag", mockDockerClientInterface.ImageTag)1525 if err != nil {1526 t.Errorf("mpatch error")1527 }1528 mockDockerClientInterface.EXPECT().1529 ImageInspectWithRaw(gomock.Any(), gomock.Any(), gomock.Any()).1530 Return(types.ImageInspect{ID: "test_id"}, nil, nil)1531 mockDockerClientInterface.EXPECT().1532 ImageTag(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).1533 Return(retErr)1534 return []*mpatch.Patch{patchImageInspectWithRaw, patchImageTag}1535 }1536 imageInspectWithRawErrorFunc := func(ctrl *gomock.Controller, retErr error) []*mpatch.Patch {1537 cli := &client.Client{}1538 mockDockerClientInterface := clientmock.NewMockDockerClientInterface(ctrl)1539 patchImageInspectWithRaw, err := mpatch.PatchInstanceMethodByName(reflect.TypeOf(cli), "ImageInspectWithRaw", mockDockerClientInterface.ImageInspectWithRaw)1540 if err != nil {1541 t.Errorf("mpatch error")1542 }1543 mockDockerClientInterface.EXPECT().1544 ImageInspectWithRaw(gomock.Any(), gomock.Any(), gomock.Any()).1545 Return(types.ImageInspect{}, nil, retErr)1546 return []*mpatch.Patch{patchImageInspectWithRaw}1547 }1548 cases := []struct {1549 imageTag string1550 registryURL string1551 wantNewTag string1552 wantErr error1553 funcBeforeTest func(*testing.T, *gomock.Controller) []*mpatch.Patch1554 funcAfterTest func()1555 }{1556 {1557 imageTag: "test_image_tag",1558 registryURL: "test_registry_url",1559 wantNewTag: "test_registry_url/test_image_tag",1560 wantErr: nil,1561 funcBeforeTest: func(t *testing.T, ctrl *gomock.Controller) []*mpatch.Patch {1562 return normalFunc(ctrl, nil)1563 },1564 },1565 {1566 imageTag: "test_image_tag",1567 registryURL: "test_registry_url",1568 wantNewTag: "",1569 wantErr: testError,1570 funcBeforeTest: getDockerClientErrFunc,1571 },1572 {1573 imageTag: "test_image_tag",1574 registryURL: "test_registry_url",1575 wantNewTag: "",1576 wantErr: testError,1577 funcBeforeTest: func(t *testing.T, ctrl *gomock.Controller) []*mpatch.Patch {1578 return imageInspectWithRawErrorFunc(ctrl, testError)1579 },1580 },1581 {1582 imageTag: "test_image_tag",1583 registryURL: "test_registry_url",1584 wantNewTag: "",1585 wantErr: testError,1586 funcBeforeTest: func(t *testing.T, ctrl *gomock.Controller) []*mpatch.Patch {1587 return normalFunc(ctrl, testError)1588 },1589 },1590 }1591 for n, testCase := range cases {1592 t.Logf("TestTagImageToLocal case %d start", n)1593 func() {1594 ctrl := gomock.NewController(t)1595 defer ctrl.Finish()1596 if testCase.funcBeforeTest != nil {1597 pList := testCase.funcBeforeTest(t, ctrl)1598 defer unpatchAll(t, pList)1599 }1600 newTag, err := TagImageToLocal(testCase.imageTag, testCase.registryURL)1601 if testCase.funcAfterTest != nil {1602 testCase.funcAfterTest()1603 }1604 if !errors.Is(err, testCase.wantErr) &&1605 (err == nil || !strings.Contains(err.Error(), testCase.wantErr.Error())) {1606 t.Errorf("Unexpected error: %v", err)1607 }1608 if newTag != testCase.wantNewTag {1609 t.Errorf("Get wrong tag: %v", newTag)1610 }1611 }()1612 t.Logf("TestTagImageToLocal case %d end", n)1613 }1614 t.Log("Done")1615}1616func TestTagImage(t *testing.T) {1617 normalFunc := func(t *testing.T, ctrl *gomock.Controller) []*mpatch.Patch {1618 cli := &client.Client{}1619 mockDockerClientInterface := clientmock.NewMockDockerClientInterface(ctrl)1620 patchImageInspectWithRaw, err := mpatch.PatchInstanceMethodByName(reflect.TypeOf(cli), "ImageInspectWithRaw", mockDockerClientInterface.ImageInspectWithRaw)1621 if err != nil {1622 t.Errorf("mpatch error")1623 }1624 patchImageTag, err := mpatch.PatchInstanceMethodByName(reflect.TypeOf(cli), "ImageTag", mockDockerClientInterface.ImageTag)1625 if err != nil {1626 t.Errorf("mpatch error")1627 }1628 mockDockerClientInterface.EXPECT().1629 ImageInspectWithRaw(gomock.Any(), gomock.Any(), gomock.Any()).1630 Return(types.ImageInspect{ID: "test_id"}, nil, nil)1631 mockDockerClientInterface.EXPECT().1632 ImageTag(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).1633 Return(nil)1634 return []*mpatch.Patch{patchImageInspectWithRaw, patchImageTag}1635 }1636 imageInspectWithRawErrorFunc := func(t *testing.T, ctrl *gomock.Controller) []*mpatch.Patch {1637 cli := &client.Client{}1638 mockDockerClientInterface := clientmock.NewMockDockerClientInterface(ctrl)1639 patchImageInspectWithRaw, err := mpatch.PatchInstanceMethodByName(reflect.TypeOf(cli), "ImageInspectWithRaw", mockDockerClientInterface.ImageInspectWithRaw)1640 if err != nil {1641 t.Errorf("mpatch error")1642 }1643 mockDockerClientInterface.EXPECT().1644 ImageInspectWithRaw(gomock.Any(), gomock.Any(), gomock.Any()).1645 Return(types.ImageInspect{}, nil, testError)1646 return []*mpatch.Patch{patchImageInspectWithRaw}1647 }1648 imageTagErrorFunc := func(t *testing.T, ctrl *gomock.Controller) []*mpatch.Patch {1649 cli := &client.Client{}1650 mockDockerClientInterface := clientmock.NewMockDockerClientInterface(ctrl)1651 patchImageInspectWithRaw, err := mpatch.PatchInstanceMethodByName(reflect.TypeOf(cli), "ImageInspectWithRaw", mockDockerClientInterface.ImageInspectWithRaw)1652 if err != nil {1653 t.Errorf("mpatch error")1654 }1655 patchImageTag, err := mpatch.PatchInstanceMethodByName(reflect.TypeOf(cli), "ImageTag", mockDockerClientInterface.ImageTag)1656 if err != nil {1657 t.Errorf("mpatch error")1658 }1659 mockDockerClientInterface.EXPECT().1660 ImageInspectWithRaw(gomock.Any(), gomock.Any(), gomock.Any()).1661 Return(types.ImageInspect{ID: "test_id"}, nil, nil)1662 mockDockerClientInterface.EXPECT().1663 ImageTag(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).1664 Return(testError)1665 return []*mpatch.Patch{patchImageInspectWithRaw, patchImageTag}1666 }1667 cases := []struct {1668 imageTag string1669 newTag string1670 wantErr error1671 funcBeforeTest func(*testing.T, *gomock.Controller) []*mpatch.Patch1672 funcAfterTest func()1673 }{1674 {1675 imageTag: "test_image_tag",1676 newTag: "test_new_tag",1677 wantErr: nil,1678 funcBeforeTest: normalFunc,1679 },1680 {1681 imageTag: "test_image_tag",1682 newTag: "test_new_tag",1683 wantErr: testError,1684 funcBeforeTest: getDockerClientErrFunc,1685 },1686 {1687 imageTag: "test_image_tag",1688 newTag: "test_new_tag",1689 wantErr: testError,1690 funcBeforeTest: imageInspectWithRawErrorFunc,1691 },1692 {1693 imageTag: "test_image_tag",1694 newTag: "test_new_tag",1695 wantErr: testError,1696 funcBeforeTest: imageTagErrorFunc,1697 },1698 }1699 for n, testCase := range cases {1700 t.Logf("TestTagImage case %d start", n)1701 func() {1702 ctrl := gomock.NewController(t)1703 defer ctrl.Finish()1704 if testCase.funcBeforeTest != nil {1705 pList := testCase.funcBeforeTest(t, ctrl)1706 defer unpatchAll(t, pList)1707 }1708 err := TagImage(testCase.imageTag, testCase.newTag)1709 if testCase.funcAfterTest != nil {1710 testCase.funcAfterTest()1711 }1712 if !errors.Is(err, testCase.wantErr) &&1713 (err == nil || !strings.Contains(err.Error(), testCase.wantErr.Error())) {1714 t.Errorf("Unexpected error: %v", err)1715 }1716 }()1717 t.Logf("TestTagImage case %d end", n)1718 }1719 t.Log("Done")1720}1721func TestGetCertPoolCfgWithCustomCa(t *testing.T) {1722 wrong_tarball := "wrong_tarball"1723 tlscfg, err := GetCertPoolCfgWithCustomCa(wrong_tarball)1724 if err != nil {1725 t.Errorf("Unexpect error returned. %v", err)1726 } else if tlscfg != nil {1727 t.Errorf("Unexpect tls config returned. %v", tlscfg)1728 }1729 patchSystemCertPool, err := mpatch.PatchMethod(x509.SystemCertPool, func() (*x509.CertPool, error) {1730 return nil, nil1731 })1732 if err != nil {1733 t.Errorf("mpatch error")1734 }1735 defer unpatch(t, patchSystemCertPool)1736 tarballFileName := "tmp/TestGetCertPoolCfgWithCustomCa.test.data"1737 patchReadFile(t, []byte("test"), nil)1738 patchFileExists, err := mpatch.PatchMethod(eputils.FileExists, func(_ string) bool {1739 return true1740 })1741 if err != nil {1742 t.Errorf("mpatch error")1743 }1744 defer unpatch(t, patchFileExists)1745 tlscfg, err = GetCertPoolCfgWithCustomCa(tarballFileName)1746 if err != nil {1747 t.Errorf("Unexpect error returned. %v", err)1748 } else if tlscfg == nil {1749 t.Errorf("Get empty tls config.")1750 }1751 patchReadFile(t, nil, testError)1752 tlscfg, err = GetCertPoolCfgWithCustomCa(tarballFileName)1753 if err == nil || !strings.Contains(err.Error(), testError.Error()) {1754 t.Errorf("Unexpect error returned. %v", err)1755 } else if tlscfg != nil {1756 t.Errorf("Unexpect tls config returned. %v", tlscfg)1757 }1758 t.Log("Done")1759}1760func TestGetImageNewTag(t *testing.T) {1761 registryurl := "testregistry"1762 cases := []struct {1763 input, expectedoutput string1764 }{1765 {1766 input: "testtag:latest",1767 expectedoutput: registryurl + "/" + "testtag:latest",1768 },1769 {1770 input: "testtag:1.1",1771 expectedoutput: registryurl + "/" + "testtag:1.1",1772 },1773 {1774 input: "docker.io/testtag:1.1",1775 expectedoutput: registryurl + "/" + "docker.io/testtag:1.1",1776 },1777 {1778 input: "testregistry:5555/testtag:1.1",1779 expectedoutput: registryurl + "/" + "testtag:1.1",1780 },1781 {1782 input: "testtag:1.1@SHA256",1783 expectedoutput: registryurl + "/" + "testtag:1.1",1784 },1785 }1786 for _, c := range cases {1787 input := c.input1788 expectedoutput := c.expectedoutput1789 testoutput := GetImageNewTag(input, registryurl)1790 if testoutput != expectedoutput {1791 t.Errorf("GetImageNewTag(%s, %s) expected %s but got %s",1792 input, registryurl, expectedoutput, testoutput)1793 }1794 }1795 t.Log("Done")1796}1797func TestErrCase(t *testing.T) {1798 wrong_tarball := "wrong_tarball"1799 wrong_imgref := "wrong_imgref:not_exist"1800 wrong_auth, _ := GetAuthConf("wrong_address", "wrong_port", "wrong_user", "wrong_password")1801 if err := ImagePull(wrong_imgref, wrong_auth); err == nil {1802 t.Errorf("ImagePull() not return error with wrong input")1803 }1804 if err := ImagePull(wrong_imgref, nil); err == nil {1805 t.Errorf("ImagePull() not return error with wrong input")1806 }1807 if err := ImagePush(wrong_imgref, wrong_auth); err == nil {1808 t.Logf("Expected wrong_imgref and wrong_auth.")1809 }1810 if err := ImagePush(wrong_imgref, nil); err == nil {1811 t.Logf("Expected wrong_imgref.")1812 }1813 wrong_dockerfile := "wrong_dockerfile"1814 wrong_tag := "wrong_tag"1815 wrong_registryurl := "wrong_registryurl"1816 _, cf, _, ok := runtime.Caller(0)1817 if !ok {1818 t.Errorf("Failed to get current test file.")1819 }1820 cwd := filepath.Join(filepath.Dir(cf))1821 wrong_tarball2 := filepath.Join(cwd, "test-containers.yml")1822 if err := ImageBuild(wrong_tarball, wrong_dockerfile, wrong_tag); err == nil {1823 t.Errorf("ImageBuild() not return error with wrong input")1824 }1825 if err := ImageBuild(wrong_tarball2, wrong_dockerfile, wrong_tag); err == nil {1826 t.Errorf("ImageBuild() not return error with wrong input")1827 }1828 if err := ImageLoad(wrong_tarball); err == nil {1829 t.Errorf("ImageLoad() not return error with wrong input")1830 }1831 if err := ImageLoad(wrong_tarball2); err == nil {1832 t.Logf("Expected wrong_tarball2.")1833 }1834 if newtag, err := TagImageToLocal(wrong_tag, wrong_registryurl); err == nil {1835 t.Errorf("TagImageToLocal() not return error with wrong input, but return with %s", newtag)1836 }1837 if _, err := TagImageToLocal("hello-world:latest", ""); err == nil {1838 t.Logf("Expected null tag.")1839 }1840 //auth.go1841 if _, err := GetAuthConf("", "", "", ""); err == nil {1842 t.Errorf("GetAuthConf() not return error with wrong input")1843 }1844 t.Log("Done")1845}1846func TestGetHostImages(t *testing.T) {1847 normalFunc := func(t *testing.T, ctrl *gomock.Controller) []*mpatch.Patch {1848 cli := &client.Client{}1849 mockDockerClientInterface := clientmock.NewMockDockerClientInterface(ctrl)1850 patchImageList, err := mpatch.PatchInstanceMethodByName(reflect.TypeOf(cli), "ImageList", mockDockerClientInterface.ImageList)1851 if err != nil {1852 t.Errorf("mpatch error")1853 }1854 mockDockerClientInterface.EXPECT().1855 ImageList(gomock.Any(), gomock.Any(), gomock.Any()).1856 Return([]types.ImageSummary{1857 {RepoTags: []string{"helloworld:latest", "helloworld:2.0"}},1858 {RepoTags: []string{"test:1.0", "test:2.0"}},1859 }, nil)1860 return []*mpatch.Patch{patchImageList}1861 }1862 ImageListErrFunc := func(t *testing.T, ctrl *gomock.Controller) []*mpatch.Patch {1863 cli := &client.Client{}1864 mockDockerClientInterface := clientmock.NewMockDockerClientInterface(ctrl)1865 patchImageList, err := mpatch.PatchInstanceMethodByName(reflect.TypeOf(cli), "ImageList", mockDockerClientInterface.ImageList)1866 if err != nil {1867 t.Errorf("mpatch error")1868 }1869 mockDockerClientInterface.EXPECT().1870 ImageList(gomock.Any(), gomock.Any(), gomock.Any()).1871 Return(nil, testError)1872 return []*mpatch.Patch{patchImageList}1873 }1874 cases := []struct {1875 name string1876 wantErr error1877 funcBeforeTest func(*testing.T, *gomock.Controller) []*mpatch.Patch1878 funcAfterTest func()1879 }{1880 {1881 name: "test_normal",1882 wantErr: nil,1883 funcBeforeTest: normalFunc,1884 },1885 {1886 name: "test_get_docker_client_err",1887 wantErr: testError,1888 funcBeforeTest: getDockerClientErrFunc,1889 },1890 {1891 name: "test_images_list_err",...

Full Screen

Full Screen

cluster.go

Source:cluster.go Github

copy

Full Screen

...79// ControllerName returns the name of the controller that created the scope.80func (cs *ClusterScope) ControllerName() string {81 return cs.controllerName82}83// Patch persists the resource and status.84func (cs *ClusterScope) Patch() error {85 applicableConditions := []clusterv1.ConditionType{86 infrav1.LoadBalancerAvailableCondition,87 }88 conditions.SetSummary(cs.MvmCluster,89 conditions.WithConditions(applicableConditions...),90 conditions.WithStepCounterIf(cs.MvmCluster.DeletionTimestamp.IsZero()),91 conditions.WithStepCounter(),92 )93 err := cs.patchHelper.Patch(94 context.TODO(),95 cs.MvmCluster,96 patch.WithOwnedConditions{Conditions: []clusterv1.ConditionType{97 clusterv1.ReadyCondition,98 infrav1.LoadBalancerAvailableCondition,99 }})100 if err != nil {101 return fmt.Errorf("unable to patch cluster: %w", err)102 }103 return nil104}105// Close closes the current scope persisting the resource and status.106func (cs *ClusterScope) Close() error {107 return cs.Patch()108}109// Placement is used to get the placement configuration for the cluster.110func (cs *ClusterScope) Placement() infrav1.Placement {111 return cs.MvmCluster.Spec.Placement112}...

Full Screen

Full Screen

tasks.go

Source:tasks.go Github

copy

Full Screen

...11func GetDeployStages() [][]manage.ExecuteItem {12 tasks := [][]manage.ExecuteItem{13 {14 migration.ChangeCrdTask,15 PatchTask{},16 },17 {18 deployTask,19 },20 }21 return tasks22}23type PatchTask struct {24}25func (m PatchTask) Run(manage *manage.OperatorManage) error {26 fmt.Println("PatchTask Run")27 client := manage.K8sClient28 ns := corev1.Namespace{}29 err := client.Get(context.Background(), types.NamespacedName{Name: "default"}, &ns)30 if err != nil {31 return err32 }33 if len(ns.Labels) == 0 {34 ns.Labels = make(map[string]string)35 }36 ns.Labels["asm-opr-patch"] = "test-fy"37 if err := client.Update(context.Background(), &ns); err != nil {38 return err39 }40 return nil41}42var _ manage.ExecuteItem = PatchTask{}43func (m PatchTask) PreRun(client client.Client) error {44 fmt.Println("PatchTask prerun")45 return nil46}47func (m PatchTask) PostRun(client client.Client) error {48 fmt.Println("PatchTask PostRun")49 return nil50}51func (m PatchTask) PreCheck(client client.Client) (bool, error) {52 fmt.Println("PatchTask PreCheck")53 return true, nil54}55func (m PatchTask) PostCheck(client client.Client) (bool, error) {56 fmt.Println("PatchTask PostCheck")57 return true, nil58}...

Full Screen

Full Screen

Patch

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 if err != nil {4 log.Fatal(err)5 }6 defer client.Disconnect(context.Background())7 collection := client.Database("test").Collection("books")8 filter := bson.D{{"title", "The little prince"}}9 update := bson.D{10 {"$set", bson.D{11 {"author", "Antoine de Saint-Exupéry"},12 }},13 }14 res, err := collection.UpdateOne(context.Background(), filter, update)15 if err != nil {16 log.Fatal(err)17 }18 fmt.Printf("Matched %v documents and ", res.MatchedCount)19 fmt.Printf("updated %v documents.\n", res.ModifiedCount)20 filter = bson.D{{"title", "The little prince"}}21 update = bson.D{22 {"$set", bson.D{23 {"author", "Antoine de Saint-Exupéry"},24 {"title", "The Little Prince"},25 }},26 }27 res, err = collection.UpdateOne(context.Background(), filter, update)28 if err != nil {29 log.Fatal(err)30 }31 fmt.Printf("Matched %v documents and ", res.MatchedCount)32 fmt.Printf("updated %v documents.\n", res.ModifiedCount)33 filter = bson.D{{"title", "The Little Prince"}}34 update = bson.D{35 {"$set", bson.D{36 {"author", "Antoine de Saint-Exupéry"},37 {"title", "The Little Prince"},38 }},39 }

Full Screen

Full Screen

Patch

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 req, err := http.NewRequest("PATCH", url, nil)4 if err != nil {5 fmt.Println(err)6 }7 client := &http.Client{}8 resp, err := client.Do(req)9 if err != nil {10 fmt.Println(err)11 }12 defer resp.Body.Close()13 fmt.Println("response Status:", resp.Status)14 fmt.Println("response Headers:", resp.Header)15}16response Headers: map[Access-Control-Allow-Credentials:[true] Access-Control-Allow-Origin:[*] Connection:[keep-alive] Content-Length:[0] Content-Type:[text/html; charset=utf-8] Date:[Mon, 26 Oct 2020 14:34:17 GMT] Server:[gunicorn/19.9.0] X-Powered-By:[Flask] X-Powered-By:[Python/3.6] X-Processed-Time:[0.0009281635284423828]]17import (18func main() {19 req, err := http.NewRequest("DELETE", url, nil)20 if err != nil {21 fmt.Println(err)22 }23 client := &http.Client{}24 resp, err := client.Do(req)25 if err != nil {26 fmt.Println(err)27 }28 defer resp.Body.Close()29 fmt.Println("response Status:", resp.Status)30 fmt.Println("response Headers:", resp.Header)31}32response Headers: map[Access-Control-Allow-Credentials:[true] Access-Control-Allow-Origin:[*] Connection:[keep-alive] Content-Length:[0] Content-Type:[text/html; charset=utf-8] Date:[Mon,

Full Screen

Full Screen

Patch

Using AI Code Generation

copy

Full Screen

1import (2type Employee struct {3}4func main() {5 emp := Employee{6 }7 json, err := json.Marshal(emp)8 if err != nil {9 log.Fatal(err)10 }11 if err != nil {12 log.Fatal(err)13 }14 req.Header.Set("Content-Type", "application/json")15 client := &http.Client{}16 resp, err := client.Do(req)17 if err != nil {18 log.Fatal(err)19 }20 defer resp.Body.Close()21 fmt.Println("response Status:", resp.Status)22 fmt.Println("response Headers:", resp.Header)23}24response Headers: map[Content-Type:[application/json; charset=utf-8] Date:[Tue, 24 Sep 2019 07:28:41 GMT] Content-Length:[0]]25import (26func main() {27 if err != nil {28 log.Fatal(err)29 }30 client := &http.Client{}31 resp, err := client.Do(req)32 if err != nil {33 log.Fatal(err)34 }35 defer resp.Body.Close()36 fmt.Println("response Status:", resp.Status)37 fmt.Println("response Headers:", resp.Header)38}

Full Screen

Full Screen

Patch

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 client := &http.Client{}4 req.Header.Set("Content-Type", "application/json")5 resp, err := client.Do(req)6 if err != nil {7 log.Fatal(err)8 }9 defer resp.Body.Close()10 fmt.Println("response Status:", resp.Status)11 fmt.Println("response Headers:", resp.Header)12}13import (14func main() {15 http.HandleFunc("/patch", patch)16 log.Fatal(http.ListenAndServe(":8080", nil))17}18func patch(w http.ResponseWriter, r *http.Request) {19 fmt.Println("Method:", r.Method)20 if r.Method == "PATCH" {21 body, err := ioutil.ReadAll(r.Body)22 if err != nil {23 panic(err)24 }25 fmt.Println("Body:", string(body))26 fmt.Fprintf(w, "Patch request processed successfully")27 }28}

Full Screen

Full Screen

Patch

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 config, err := rest.InClusterConfig()4 if err != nil {5 panic(err.Error())6 }7 clientset, err := kubernetes.NewForConfig(config)8 if err != nil {9 panic(err.Error())10 }11 pod, err := clientset.CoreV1().Pods("default").Get(context.Background(), "mypod", metav1.GetOptions{})12 if errors.IsNotFound(err) {13 log.Printf("Pod %s in namespace %s not found", "mypod", "default")14 } else if statusError, isStatus := err.(*errors.StatusError); isStatus {15 log.Printf("Error getting pod %s in namespace %s: %v",16 } else if err != nil {17 panic(err.Error())18 } else {19 log.Printf("Found pod %s in namespace %s", "mypod", "default")20 }21 pod, err = clientset.CoreV1().Pods("default").Update(context.Background(), pod, metav1.UpdateOptions{})22 if err != nil {23 panic(err.Error())24 }25 fmt.Printf("Updated pod %s in namespace %s26 patch := []byte(`{"metadata":{"labels":{"app":"patchedapp"}}}`)27 pod, err = clientset.CoreV1().Pods("default").Patch(context.Background(), "mypod", types.MergePatchType, patch, metav1.PatchOptions{})28 if err != nil {29 panic(err.Error())30 }31 fmt.Printf("Patched pod %s in namespace %s32}

Full Screen

Full Screen

Patch

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 if err != nil {4 log.Fatal(err)5 }6 proxy := httputil.NewSingleHostReverseProxy(u)7 handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {8 proxy.ServeHTTP(w, r)9 })10 server := &http.Server{11 }12 log.Fatal(server.ListenAndServe())13}14import (15func main() {16 if err != nil {17 log.Fatal(err)18 }19 proxy := httputil.NewSingleHostReverseProxy(u)20 handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {21 proxy.ServeHTTP(w, r)22 })23 server := &http.Server{24 }25 log.Fatal(server.ListenAndServe())26}27import (28func main() {29 if err != nil {30 log.Fatal(err)31 }32 proxy := httputil.NewSingleHostReverseProxy(u)

Full Screen

Full Screen

Patch

Using AI Code Generation

copy

Full Screen

1import (2type User struct {3}4func main() {5 client := &http.Client{}6 user := User{ID: 2, FirstName: "Nikhil", LastName: "Raj", Email: "

Full Screen

Full Screen

Automation Testing Tutorials

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

LambdaTest Learning Hubs:

YouTube

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

Run Testkube automation tests on LambdaTest cloud grid

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

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful