How to use NewTestClient method of client Package

Best Testkube code snippet using client.NewTestClient

image_test.go

Source:image_test.go Github

copy

Full Screen

1// Copyright 2014 go-dockerclient authors. All rights reserved.2// Use of this source code is governed by a BSD-style3// license that can be found in the LICENSE file.4package docker5import (6 "bytes"7 "encoding/base64"8 "encoding/json"9 "io/ioutil"10 "net/http"11 "net/url"12 "os"13 "reflect"14 "strings"15 "testing"16)17func newTestClient(rt *FakeRoundTripper) Client {18 endpoint := "http://localhost:4243"19 u, _ := parseEndpoint("http://localhost:4243")20 client := Client{21 HTTPClient: &http.Client{Transport: rt},22 endpoint: endpoint,23 endpointURL: u,24 SkipServerVersionCheck: true,25 }26 return client27}28type stdoutMock struct {29 *bytes.Buffer30}31func (m stdoutMock) Close() error {32 return nil33}34type stdinMock struct {35 *bytes.Buffer36}37func (m stdinMock) Close() error {38 return nil39}40func TestListImages(t *testing.T) {41 body := `[42 {43 "Repository":"base",44 "Tag":"ubuntu-12.10",45 "Id":"b750fe79269d",46 "Created":136410265847 },48 {49 "Repository":"base",50 "Tag":"ubuntu-quantal",51 "Id":"b750fe79269d",52 "Created":136410265853 },54 {55 "RepoTag": [56 "ubuntu:12.04",57 "ubuntu:precise",58 "ubuntu:latest"59 ],60 "Id": "8dbd9e392a964c",61 "Created": 1365714795,62 "Size": 131506275,63 "VirtualSize": 13150627564 },65 {66 "RepoTag": [67 "ubuntu:12.10",68 "ubuntu:quantal"69 ],70 "ParentId": "27cf784147099545",71 "Id": "b750fe79269d2e",72 "Created": 1364102658,73 "Size": 24653,74 "VirtualSize": 18011613575 }76]`77 var expected []APIImages78 err := json.Unmarshal([]byte(body), &expected)79 if err != nil {80 t.Fatal(err)81 }82 client := newTestClient(&FakeRoundTripper{message: body, status: http.StatusOK})83 images, err := client.ListImages(false)84 if err != nil {85 t.Error(err)86 }87 if !reflect.DeepEqual(images, expected) {88 t.Errorf("ListImages: Wrong return value. Want %#v. Got %#v.", expected, images)89 }90}91func TestListImagesParameters(t *testing.T) {92 fakeRT := &FakeRoundTripper{message: "null", status: http.StatusOK}93 client := newTestClient(fakeRT)94 _, err := client.ListImages(false)95 if err != nil {96 t.Fatal(err)97 }98 req := fakeRT.requests[0]99 if req.Method != "GET" {100 t.Errorf("ListImages(false: Wrong HTTP method. Want GET. Got %s.", req.Method)101 }102 if all := req.URL.Query().Get("all"); all != "0" {103 t.Errorf("ListImages(false): Wrong parameter. Want all=0. Got all=%s", all)104 }105 fakeRT.Reset()106 _, err = client.ListImages(true)107 if err != nil {108 t.Fatal(err)109 }110 req = fakeRT.requests[0]111 if all := req.URL.Query().Get("all"); all != "1" {112 t.Errorf("ListImages(true): Wrong parameter. Want all=1. Got all=%s", all)113 }114}115func TestImageHistory(t *testing.T) {116 body := `[117 {118 "Id": "25daec02219d2d852f7526137213a9b199926b4b24e732eab5b8bc6c49bd470e",119 "Tags": [120 "debian:7.6",121 "debian:latest",122 "debian:7",123 "debian:wheezy"124 ],125 "Created": 1409856216,126 "CreatedBy": "/bin/sh -c #(nop) CMD [/bin/bash]"127 },128 {129 "Id": "41026a5347fb5be6ed16115bf22df8569697139f246186de9ae8d4f67c335dce",130 "Created": 1409856213,131 "CreatedBy": "/bin/sh -c #(nop) ADD file:1ee9e97209d00e3416a4543b23574cc7259684741a46bbcbc755909b8a053a38 in /",132 "Size": 85178663133 },134 {135 "Id": "511136ea3c5a64f264b78b5433614aec563103b4d4702f3ba7d4d2698e22c158",136 "Tags": [137 "scratch:latest"138 ],139 "Created": 1371157430140 }141]`142 var expected []ImageHistory143 err := json.Unmarshal([]byte(body), &expected)144 if err != nil {145 t.Fatal(err)146 }147 client := newTestClient(&FakeRoundTripper{message: body, status: http.StatusOK})148 history, err := client.ImageHistory("debian:latest")149 if err != nil {150 t.Error(err)151 }152 if !reflect.DeepEqual(history, expected) {153 t.Errorf("ImageHistory: Wrong return value. Want %#v. Got %#v.", expected, history)154 }155}156func TestRemoveImage(t *testing.T) {157 name := "test"158 fakeRT := &FakeRoundTripper{message: "", status: http.StatusNoContent}159 client := newTestClient(fakeRT)160 err := client.RemoveImage(name)161 if err != nil {162 t.Fatal(err)163 }164 req := fakeRT.requests[0]165 expectedMethod := "DELETE"166 if req.Method != expectedMethod {167 t.Errorf("RemoveImage(%q): Wrong HTTP method. Want %s. Got %s.", name, expectedMethod, req.Method)168 }169 u, _ := url.Parse(client.getURL("/images/" + name))170 if req.URL.Path != u.Path {171 t.Errorf("RemoveImage(%q): Wrong request path. Want %q. Got %q.", name, u.Path, req.URL.Path)172 }173}174func TestRemoveImageNotFound(t *testing.T) {175 client := newTestClient(&FakeRoundTripper{message: "no such image", status: http.StatusNotFound})176 err := client.RemoveImage("test:")177 if err != ErrNoSuchImage {178 t.Errorf("RemoveImage: wrong error. Want %#v. Got %#v.", ErrNoSuchImage, err)179 }180}181func TestInspectImage(t *testing.T) {182 body := `{183 "id":"b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc",184 "parent":"27cf784147099545",185 "created":"2013-03-23T22:24:18.818426-07:00",186 "container":"3d67245a8d72ecf13f33dffac9f79dcdf70f75acb84d308770391510e0c23ad0",187 "container_config":{"Memory":0}188}`189 var expected Image190 json.Unmarshal([]byte(body), &expected)191 fakeRT := &FakeRoundTripper{message: body, status: http.StatusOK}192 client := newTestClient(fakeRT)193 image, err := client.InspectImage(expected.ID)194 if err != nil {195 t.Fatal(err)196 }197 if !reflect.DeepEqual(*image, expected) {198 t.Errorf("InspectImage(%q): Wrong image returned. Want %#v. Got %#v.", expected.ID, expected, *image)199 }200 req := fakeRT.requests[0]201 if req.Method != "GET" {202 t.Errorf("InspectImage(%q): Wrong HTTP method. Want GET. Got %s.", expected.ID, req.Method)203 }204 u, _ := url.Parse(client.getURL("/images/" + expected.ID + "/json"))205 if req.URL.Path != u.Path {206 t.Errorf("InspectImage(%q): Wrong request URL. Want %q. Got %q.", expected.ID, u.Path, req.URL.Path)207 }208}209func TestInspectImageNotFound(t *testing.T) {210 client := newTestClient(&FakeRoundTripper{message: "no such image", status: http.StatusNotFound})211 name := "test"212 image, err := client.InspectImage(name)213 if image != nil {214 t.Errorf("InspectImage(%q): expected <nil> image, got %#v.", name, image)215 }216 if err != ErrNoSuchImage {217 t.Errorf("InspectImage(%q): wrong error. Want %#v. Got %#v.", name, ErrNoSuchImage, err)218 }219}220func TestPushImage(t *testing.T) {221 fakeRT := &FakeRoundTripper{message: "Pushing 1/100", status: http.StatusOK}222 client := newTestClient(fakeRT)223 var buf bytes.Buffer224 err := client.PushImage(PushImageOptions{Name: "test", OutputStream: &buf}, AuthConfiguration{})225 if err != nil {226 t.Fatal(err)227 }228 expected := "Pushing 1/100"229 if buf.String() != expected {230 t.Errorf("PushImage: Wrong output. Want %q. Got %q.", expected, buf.String())231 }232 req := fakeRT.requests[0]233 if req.Method != "POST" {234 t.Errorf("PushImage: Wrong HTTP method. Want POST. Got %s.", req.Method)235 }236 u, _ := url.Parse(client.getURL("/images/test/push"))237 if req.URL.Path != u.Path {238 t.Errorf("PushImage: Wrong request path. Want %q. Got %q.", u.Path, req.URL.Path)239 }240 if query := req.URL.Query().Encode(); query != "" {241 t.Errorf("PushImage: Wrong query string. Want no parameters, got %q.", query)242 }243 auth, err := base64.URLEncoding.DecodeString(req.Header.Get("X-Registry-Auth"))244 if err != nil {245 t.Errorf("PushImage: caught error decoding auth. %#v", err.Error())246 }247 if strings.TrimSpace(string(auth)) != "{}" {248 t.Errorf("PushImage: wrong body. Want %q. Got %q.",249 base64.URLEncoding.EncodeToString([]byte("{}")), req.Header.Get("X-Registry-Auth"))250 }251}252func TestPushImageWithAuthentication(t *testing.T) {253 fakeRT := &FakeRoundTripper{message: "Pushing 1/100", status: http.StatusOK}254 client := newTestClient(fakeRT)255 var buf bytes.Buffer256 inputAuth := AuthConfiguration{257 Username: "gopher",258 Password: "gopher123",259 Email: "gopher@tsuru.io",260 }261 err := client.PushImage(PushImageOptions{Name: "test", OutputStream: &buf}, inputAuth)262 if err != nil {263 t.Fatal(err)264 }265 req := fakeRT.requests[0]266 var gotAuth AuthConfiguration267 auth, err := base64.URLEncoding.DecodeString(req.Header.Get("X-Registry-Auth"))268 if err != nil {269 t.Errorf("PushImage: caught error decoding auth. %#v", err.Error())270 }271 err = json.Unmarshal(auth, &gotAuth)272 if err != nil {273 t.Fatal(err)274 }275 if !reflect.DeepEqual(gotAuth, inputAuth) {276 t.Errorf("PushImage: wrong auth configuration. Want %#v. Got %#v.", inputAuth, gotAuth)277 }278}279func TestPushImageCustomRegistry(t *testing.T) {280 fakeRT := &FakeRoundTripper{message: "Pushing 1/100", status: http.StatusOK}281 client := newTestClient(fakeRT)282 var authConfig AuthConfiguration283 var buf bytes.Buffer284 opts := PushImageOptions{285 Name: "test", Registry: "docker.tsuru.io",286 OutputStream: &buf,287 }288 err := client.PushImage(opts, authConfig)289 if err != nil {290 t.Fatal(err)291 }292 req := fakeRT.requests[0]293 expectedQuery := "registry=docker.tsuru.io"294 if query := req.URL.Query().Encode(); query != expectedQuery {295 t.Errorf("PushImage: Wrong query string. Want %q. Got %q.", expectedQuery, query)296 }297}298func TestPushImageNoName(t *testing.T) {299 client := Client{}300 err := client.PushImage(PushImageOptions{}, AuthConfiguration{})301 if err != ErrNoSuchImage {302 t.Errorf("PushImage: got wrong error. Want %#v. Got %#v.", ErrNoSuchImage, err)303 }304}305func TestPullImage(t *testing.T) {306 fakeRT := &FakeRoundTripper{message: "Pulling 1/100", status: http.StatusOK}307 client := newTestClient(fakeRT)308 var buf bytes.Buffer309 err := client.PullImage(PullImageOptions{Repository: "base", OutputStream: &buf},310 AuthConfiguration{})311 if err != nil {312 t.Fatal(err)313 }314 expected := "Pulling 1/100"315 if buf.String() != expected {316 t.Errorf("PullImage: Wrong output. Want %q. Got %q.", expected, buf.String())317 }318 req := fakeRT.requests[0]319 if req.Method != "POST" {320 t.Errorf("PullImage: Wrong HTTP method. Want POST. Got %s.", req.Method)321 }322 u, _ := url.Parse(client.getURL("/images/create"))323 if req.URL.Path != u.Path {324 t.Errorf("PullImage: Wrong request path. Want %q. Got %q.", u.Path, req.URL.Path)325 }326 expectedQuery := "fromImage=base"327 if query := req.URL.Query().Encode(); query != expectedQuery {328 t.Errorf("PullImage: Wrong query strin. Want %q. Got %q.", expectedQuery, query)329 }330}331func TestPullImageWithRawJSON(t *testing.T) {332 body := `333 {"status":"Pulling..."}334 {"status":"Pulling", "progress":"1 B/ 100 B", "progressDetail":{"current":1, "total":100}}335 `336 fakeRT := &FakeRoundTripper{337 message: body,338 status: http.StatusOK,339 header: map[string]string{340 "Content-Type": "application/json",341 },342 }343 client := newTestClient(fakeRT)344 var buf bytes.Buffer345 err := client.PullImage(PullImageOptions{346 Repository: "base",347 OutputStream: &buf,348 RawJSONStream: true,349 }, AuthConfiguration{})350 if err != nil {351 t.Fatal(err)352 }353 if buf.String() != body {354 t.Errorf("PullImage: Wrong raw output. Want %q. Got %q", body, buf.String())355 }356}357func TestPullImageWithoutOutputStream(t *testing.T) {358 fakeRT := &FakeRoundTripper{message: "Pulling 1/100", status: http.StatusOK}359 client := newTestClient(fakeRT)360 opts := PullImageOptions{361 Repository: "base",362 Registry: "docker.tsuru.io",363 }364 err := client.PullImage(opts, AuthConfiguration{})365 if err != nil {366 t.Fatal(err)367 }368 req := fakeRT.requests[0]369 expected := map[string][]string{"fromImage": {"base"}, "registry": {"docker.tsuru.io"}}370 got := map[string][]string(req.URL.Query())371 if !reflect.DeepEqual(got, expected) {372 t.Errorf("PullImage: wrong query string. Want %#v. Got %#v.", expected, got)373 }374}375func TestPullImageCustomRegistry(t *testing.T) {376 fakeRT := &FakeRoundTripper{message: "Pulling 1/100", status: http.StatusOK}377 client := newTestClient(fakeRT)378 var buf bytes.Buffer379 opts := PullImageOptions{380 Repository: "base",381 Registry: "docker.tsuru.io",382 OutputStream: &buf,383 }384 err := client.PullImage(opts, AuthConfiguration{})385 if err != nil {386 t.Fatal(err)387 }388 req := fakeRT.requests[0]389 expected := map[string][]string{"fromImage": {"base"}, "registry": {"docker.tsuru.io"}}390 got := map[string][]string(req.URL.Query())391 if !reflect.DeepEqual(got, expected) {392 t.Errorf("PullImage: wrong query string. Want %#v. Got %#v.", expected, got)393 }394}395func TestPullImageTag(t *testing.T) {396 fakeRT := &FakeRoundTripper{message: "Pulling 1/100", status: http.StatusOK}397 client := newTestClient(fakeRT)398 var buf bytes.Buffer399 opts := PullImageOptions{400 Repository: "base",401 Registry: "docker.tsuru.io",402 Tag: "latest",403 OutputStream: &buf,404 }405 err := client.PullImage(opts, AuthConfiguration{})406 if err != nil {407 t.Fatal(err)408 }409 req := fakeRT.requests[0]410 expected := map[string][]string{"fromImage": {"base"}, "registry": {"docker.tsuru.io"}, "tag": {"latest"}}411 got := map[string][]string(req.URL.Query())412 if !reflect.DeepEqual(got, expected) {413 t.Errorf("PullImage: wrong query string. Want %#v. Got %#v.", expected, got)414 }415}416func TestPullImageNoRepository(t *testing.T) {417 var opts PullImageOptions418 client := Client{}419 err := client.PullImage(opts, AuthConfiguration{})420 if err != ErrNoSuchImage {421 t.Errorf("PullImage: got wrong error. Want %#v. Got %#v.", ErrNoSuchImage, err)422 }423}424func TestImportImageFromUrl(t *testing.T) {425 fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK}426 client := newTestClient(fakeRT)427 var buf bytes.Buffer428 opts := ImportImageOptions{429 Source: "http://mycompany.com/file.tar",430 Repository: "testimage",431 Tag: "tag",432 OutputStream: &buf,433 }434 err := client.ImportImage(opts)435 if err != nil {436 t.Fatal(err)437 }438 req := fakeRT.requests[0]439 expected := map[string][]string{"fromSrc": {opts.Source}, "repo": {opts.Repository}, "tag": {opts.Tag}}440 got := map[string][]string(req.URL.Query())441 if !reflect.DeepEqual(got, expected) {442 t.Errorf("ImportImage: wrong query string. Want %#v. Got %#v.", expected, got)443 }444}445func TestImportImageFromInput(t *testing.T) {446 fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK}447 client := newTestClient(fakeRT)448 in := bytes.NewBufferString("tar content")449 var buf bytes.Buffer450 opts := ImportImageOptions{451 Source: "-", Repository: "testimage",452 InputStream: in, OutputStream: &buf,453 Tag: "tag",454 }455 err := client.ImportImage(opts)456 if err != nil {457 t.Fatal(err)458 }459 req := fakeRT.requests[0]460 expected := map[string][]string{"fromSrc": {opts.Source}, "repo": {opts.Repository}, "tag": {opts.Tag}}461 got := map[string][]string(req.URL.Query())462 if !reflect.DeepEqual(got, expected) {463 t.Errorf("ImportImage: wrong query string. Want %#v. Got %#v.", expected, got)464 }465 body, err := ioutil.ReadAll(req.Body)466 if err != nil {467 t.Errorf("ImportImage: caugth error while reading body %#v", err.Error())468 }469 e := "tar content"470 if string(body) != e {471 t.Errorf("ImportImage: wrong body. Want %#v. Got %#v.", e, string(body))472 }473}474func TestImportImageDoesNotPassesInputIfSourceIsNotDash(t *testing.T) {475 fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK}476 client := newTestClient(fakeRT)477 var buf bytes.Buffer478 in := bytes.NewBufferString("foo")479 opts := ImportImageOptions{480 Source: "http://test.com/container.tar", Repository: "testimage",481 InputStream: in, OutputStream: &buf,482 }483 err := client.ImportImage(opts)484 if err != nil {485 t.Fatal(err)486 }487 req := fakeRT.requests[0]488 expected := map[string][]string{"fromSrc": {opts.Source}, "repo": {opts.Repository}}489 got := map[string][]string(req.URL.Query())490 if !reflect.DeepEqual(got, expected) {491 t.Errorf("ImportImage: wrong query string. Want %#v. Got %#v.", expected, got)492 }493 body, err := ioutil.ReadAll(req.Body)494 if err != nil {495 t.Errorf("ImportImage: caugth error while reading body %#v", err.Error())496 }497 if string(body) != "" {498 t.Errorf("ImportImage: wrong body. Want nothing. Got %#v.", string(body))499 }500}501func TestImportImageShouldPassTarContentToBodyWhenSourceIsFilePath(t *testing.T) {502 fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK}503 client := newTestClient(fakeRT)504 var buf bytes.Buffer505 tarPath := "testing/data/container.tar"506 opts := ImportImageOptions{507 Source: tarPath, Repository: "testimage",508 OutputStream: &buf,509 }510 err := client.ImportImage(opts)511 if err != nil {512 t.Fatal(err)513 }514 tar, err := os.Open(tarPath)515 if err != nil {516 t.Fatal(err)517 }518 req := fakeRT.requests[0]519 tarContent, err := ioutil.ReadAll(tar)520 body, err := ioutil.ReadAll(req.Body)521 if err != nil {522 t.Fatal(err)523 }524 if !reflect.DeepEqual(tarContent, body) {525 t.Errorf("ImportImage: wrong body. Want %#v content. Got %#v.", tarPath, body)526 }527}528func TestImportImageShouldChangeSourceToDashWhenItsAFilePath(t *testing.T) {529 fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK}530 client := newTestClient(fakeRT)531 var buf bytes.Buffer532 tarPath := "testing/data/container.tar"533 opts := ImportImageOptions{534 Source: tarPath, Repository: "testimage",535 OutputStream: &buf,536 }537 err := client.ImportImage(opts)538 if err != nil {539 t.Fatal(err)540 }541 req := fakeRT.requests[0]542 expected := map[string][]string{"fromSrc": {"-"}, "repo": {opts.Repository}}543 got := map[string][]string(req.URL.Query())544 if !reflect.DeepEqual(got, expected) {545 t.Errorf("ImportImage: wrong query string. Want %#v. Got %#v.", expected, got)546 }547}548func TestBuildImageParameters(t *testing.T) {549 fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK}550 client := newTestClient(fakeRT)551 var buf bytes.Buffer552 opts := BuildImageOptions{553 Name: "testImage",554 NoCache: true,555 SuppressOutput: true,556 RmTmpContainer: true,557 ForceRmTmpContainer: true,558 InputStream: &buf,559 OutputStream: &buf,560 }561 err := client.BuildImage(opts)562 if err != nil && strings.Index(err.Error(), "build image fail") == -1 {563 t.Fatal(err)564 }565 req := fakeRT.requests[0]566 expected := map[string][]string{"t": {opts.Name}, "nocache": {"1"}, "q": {"1"}, "rm": {"1"}, "forcerm": {"1"}}567 got := map[string][]string(req.URL.Query())568 if !reflect.DeepEqual(got, expected) {569 t.Errorf("BuildImage: wrong query string. Want %#v. Got %#v.", expected, got)570 }571}572func TestBuildImageParametersForRemoteBuild(t *testing.T) {573 fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK}574 client := newTestClient(fakeRT)575 var buf bytes.Buffer576 opts := BuildImageOptions{577 Name: "testImage",578 Remote: "testing/data/container.tar",579 SuppressOutput: true,580 OutputStream: &buf,581 }582 err := client.BuildImage(opts)583 if err != nil {584 t.Fatal(err)585 }586 req := fakeRT.requests[0]587 expected := map[string][]string{"t": {opts.Name}, "remote": {opts.Remote}, "q": {"1"}}588 got := map[string][]string(req.URL.Query())589 if !reflect.DeepEqual(got, expected) {590 t.Errorf("BuildImage: wrong query string. Want %#v. Got %#v.", expected, got)591 }592}593func TestBuildImageMissingRepoAndNilInput(t *testing.T) {594 fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK}595 client := newTestClient(fakeRT)596 var buf bytes.Buffer597 opts := BuildImageOptions{598 Name: "testImage",599 SuppressOutput: true,600 OutputStream: &buf,601 }602 err := client.BuildImage(opts)603 if err != ErrMissingRepo {604 t.Errorf("BuildImage: wrong error returned. Want %#v. Got %#v.", ErrMissingRepo, err)605 }606}607func TestBuildImageMissingOutputStream(t *testing.T) {608 fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK}609 client := newTestClient(fakeRT)610 opts := BuildImageOptions{Name: "testImage"}611 err := client.BuildImage(opts)612 if err != ErrMissingOutputStream {613 t.Errorf("BuildImage: wrong error returned. Want %#v. Got %#v.", ErrMissingOutputStream, err)614 }615}616func TestBuildImageWithRawJSON(t *testing.T) {617 body := `618 {"stream":"Step 0 : FROM ubuntu:latest\n"}619 {"stream":" ---\u003e 4300eb9d3c8d\n"}620 {"stream":"Step 1 : MAINTAINER docker <eng@docker.com>\n"}621 {"stream":" ---\u003e Using cache\n"}622 {"stream":" ---\u003e 3a3ed758c370\n"}623 {"stream":"Step 2 : CMD /usr/bin/top\n"}624 {"stream":" ---\u003e Running in 36b1479cc2e4\n"}625 {"stream":" ---\u003e 4b6188aebe39\n"}626 {"stream":"Removing intermediate container 36b1479cc2e4\n"}627 {"stream":"Successfully built 4b6188aebe39\n"}628 `629 fakeRT := &FakeRoundTripper{630 message: body,631 status: http.StatusOK,632 header: map[string]string{633 "Content-Type": "application/json",634 },635 }636 client := newTestClient(fakeRT)637 var buf bytes.Buffer638 opts := BuildImageOptions{639 Name: "testImage",640 RmTmpContainer: true,641 InputStream: &buf,642 OutputStream: &buf,643 RawJSONStream: true,644 }645 err := client.BuildImage(opts)646 if err != nil {647 t.Fatal(err)648 }649 if buf.String() != body {650 t.Errorf("BuildImage: Wrong raw output. Want %q. Got %q.", body, buf.String())651 }652}653func TestBuildImageRemoteWithoutName(t *testing.T) {654 fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK}655 client := newTestClient(fakeRT)656 var buf bytes.Buffer657 opts := BuildImageOptions{658 Remote: "testing/data/container.tar",659 SuppressOutput: true,660 OutputStream: &buf,661 }662 err := client.BuildImage(opts)663 if err != nil {664 t.Fatal(err)665 }666 req := fakeRT.requests[0]667 expected := map[string][]string{"t": {opts.Remote}, "remote": {opts.Remote}, "q": {"1"}}668 got := map[string][]string(req.URL.Query())669 if !reflect.DeepEqual(got, expected) {670 t.Errorf("BuildImage: wrong query string. Want %#v. Got %#v.", expected, got)671 }672}673func TestTagImageParameters(t *testing.T) {674 fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK}675 client := newTestClient(fakeRT)676 opts := TagImageOptions{Repo: "testImage"}677 err := client.TagImage("base", opts)678 if err != nil && strings.Index(err.Error(), "tag image fail") == -1 {679 t.Fatal(err)680 }681 req := fakeRT.requests[0]682 expected := "http://localhost:4243/images/base/tag?repo=testImage"683 got := req.URL.String()684 if !reflect.DeepEqual(got, expected) {685 t.Errorf("TagImage: wrong query string. Want %#v. Got %#v.", expected, got)686 }687}688func TestTagImageMissingRepo(t *testing.T) {689 fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK}690 client := newTestClient(fakeRT)691 opts := TagImageOptions{Repo: "testImage"}692 err := client.TagImage("", opts)693 if err != ErrNoSuchImage {694 t.Errorf("TestTag: wrong error returned. Want %#v. Got %#v.",695 ErrNoSuchImage, err)696 }697}698func TestIsUrl(t *testing.T) {699 url := "http://foo.bar/"700 result := isURL(url)701 if !result {702 t.Errorf("isURL: wrong match. Expected %#v to be a url. Got %#v.", url, result)703 }704 url = "/foo/bar.tar"705 result = isURL(url)706 if result {707 t.Errorf("isURL: wrong match. Expected %#v to not be a url. Got %#v", url, result)708 }709}710func TestLoadImage(t *testing.T) {711 fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK}712 client := newTestClient(fakeRT)713 tar, err := os.Open("testing/data/container.tar")714 if err != nil {715 t.Fatal(err)716 } else {717 defer tar.Close()718 }719 opts := LoadImageOptions{InputStream: tar}720 err = client.LoadImage(opts)721 if nil != err {722 t.Error(err)723 }724 req := fakeRT.requests[0]725 if req.Method != "POST" {726 t.Errorf("LoadImage: wrong method. Expected %q. Got %q.", "POST", req.Method)727 }728 if req.URL.Path != "/images/load" {729 t.Errorf("LoadImage: wrong URL. Expected %q. Got %q.", "/images/load", req.URL.Path)730 }731}732func TestExportImage(t *testing.T) {733 var buf bytes.Buffer734 fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK}735 client := newTestClient(fakeRT)736 opts := ExportImageOptions{Name: "testimage", OutputStream: &buf}737 err := client.ExportImage(opts)738 if nil != err {739 t.Error(err)740 }741 req := fakeRT.requests[0]742 if req.Method != "GET" {743 t.Errorf("ExportImage: wrong method. Expected %q. Got %q.", "GET", req.Method)744 }745 expectedPath := "/images/testimage/get"746 if req.URL.Path != expectedPath {747 t.Errorf("ExportIMage: wrong path. Expected %q. Got %q.", expectedPath, req.URL.Path)748 }749}...

Full Screen

Full Screen

client_test.go

Source:client_test.go Github

copy

Full Screen

1package client2import (3 "encoding/json"4 "net/http"5 "net/http/httptest"6 "testing"7 "github.com/stretchr/testify/assert"8 "github.com/stretchr/testify/require"9)10const (11 testUser = "user"12 testPass = "pass"13 testSessToken = "sessToken"14 testHealthValue = "green"15)16func newTestClient(srvURL string) *Client {17 return New(nil, srvURL, testUser, testPass)18}19func TestClient_Login(t *testing.T) {20 ts := newTestHTTPServer()21 defer ts.Close()22 cl := newTestClient(ts.URL)23 assert.NoError(t, cl.Login())24 assert.Equal(t, testSessToken, cl.token.get())25}26func TestClient_LoginWrongCredentials(t *testing.T) {27 ts := newTestHTTPServer()28 defer ts.Close()29 cl := newTestClient(ts.URL)30 cl.username += "!"31 assert.Error(t, cl.Login())32}33func TestClient_Logout(t *testing.T) {34 ts := newTestHTTPServer()35 defer ts.Close()36 cl := newTestClient(ts.URL)37 assert.NoError(t, cl.Login())38 assert.NoError(t, cl.Logout())39 assert.Zero(t, cl.token.get())40}41func TestClient_Ping(t *testing.T) {42 ts := newTestHTTPServer()43 defer ts.Close()44 cl := newTestClient(ts.URL)45 require.NoError(t, cl.Login())46 assert.NoError(t, cl.Ping())47}48func TestClient_PingWithReAuthentication(t *testing.T) {49 ts := newTestHTTPServer()50 defer ts.Close()51 cl := newTestClient(ts.URL)52 require.NoError(t, cl.Login())53 cl.token.set("")54 assert.NoError(t, cl.Ping())55 assert.Equal(t, testSessToken, cl.token.get())56}57func TestClient_ApplMgmt(t *testing.T) {58 ts := newTestHTTPServer()59 defer ts.Close()60 cl := newTestClient(ts.URL)61 require.NoError(t, cl.Login())62 v, err := cl.ApplMgmt()63 assert.NoError(t, err)64 assert.Equal(t, testHealthValue, v)65}66func TestClient_DatabaseStorage(t *testing.T) {67 ts := newTestHTTPServer()68 defer ts.Close()69 cl := newTestClient(ts.URL)70 require.NoError(t, cl.Login())71 v, err := cl.DatabaseStorage()72 assert.NoError(t, err)73 assert.Equal(t, testHealthValue, v)74}75func TestClient_Load(t *testing.T) {76 ts := newTestHTTPServer()77 defer ts.Close()78 cl := newTestClient(ts.URL)79 require.NoError(t, cl.Login())80 v, err := cl.Load()81 assert.NoError(t, err)82 assert.Equal(t, testHealthValue, v)83}84func TestClient_Mem(t *testing.T) {85 ts := newTestHTTPServer()86 defer ts.Close()87 cl := newTestClient(ts.URL)88 require.NoError(t, cl.Login())89 v, err := cl.Mem()90 assert.NoError(t, err)91 assert.Equal(t, testHealthValue, v)92}93func TestClient_SoftwarePackages(t *testing.T) {94 ts := newTestHTTPServer()95 defer ts.Close()96 cl := newTestClient(ts.URL)97 require.NoError(t, cl.Login())98 v, err := cl.SoftwarePackages()99 assert.NoError(t, err)100 assert.Equal(t, testHealthValue, v)101}102func TestClient_Storage(t *testing.T) {103 ts := newTestHTTPServer()104 defer ts.Close()105 cl := newTestClient(ts.URL)106 require.NoError(t, cl.Login())107 v, err := cl.Storage()108 assert.NoError(t, err)109 assert.Equal(t, testHealthValue, v)110}111func TestClient_Swap(t *testing.T) {112 ts := newTestHTTPServer()113 defer ts.Close()114 cl := newTestClient(ts.URL)115 require.NoError(t, cl.Login())116 v, err := cl.Swap()117 assert.NoError(t, err)118 assert.Equal(t, testHealthValue, v)119}120func TestClient_System(t *testing.T) {121 ts := newTestHTTPServer()122 defer ts.Close()123 cl := newTestClient(ts.URL)124 require.NoError(t, cl.Login())125 v, err := cl.System()126 assert.NoError(t, err)127 assert.Equal(t, testHealthValue, v)128}129func TestClient_InvalidDataOnLogin(t *testing.T) {130 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {131 _, _ = w.Write([]byte("hello\n and goodbye!"))132 }))133 defer ts.Close()134 cl := newTestClient(ts.URL)135 assert.Error(t, cl.Login())136}137func TestClient_404OnLogin(t *testing.T) {138 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {139 w.WriteHeader(404)140 }))141 defer ts.Close()142 cl := newTestClient(ts.URL)143 assert.Error(t, cl.Login())144}145func newTestHTTPServer() *httptest.Server {146 return httptest.NewServer(&mockVCSAServer{147 username: testUser,148 password: testPass,149 sessionID: testSessToken,150 })151}152type mockVCSAServer struct {153 username string154 password string155 sessionID string156}157func (m mockVCSAServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {158 switch r.URL.Path {159 default:160 w.WriteHeader(http.StatusNotFound)161 case pathCISSession:162 m.handleSession(w, r)163 case164 pathHealthApplMgmt,165 pathHealthDatabaseStorage,166 pathHealthLoad,167 pathHealthMem,168 pathHealthSoftwarePackager,169 pathHealthStorage,170 pathHealthSwap,171 pathHealthSystem:172 m.handleHealth(w, r)173 }174}175func (m mockVCSAServer) handleHealth(w http.ResponseWriter, r *http.Request) {176 if r.Method != http.MethodGet {177 w.WriteHeader(http.StatusBadRequest)178 return179 }180 if !m.isSessionAuthenticated(r) {181 w.WriteHeader(http.StatusUnauthorized)182 return183 }184 w.Header().Set("Content-Type", "application/json")185 w.WriteHeader(http.StatusOK)186 s := struct{ Value string }{Value: testHealthValue}187 b, _ := json.Marshal(s)188 _, _ = w.Write(b)189}190func (m mockVCSAServer) handleSession(w http.ResponseWriter, r *http.Request) {191 switch r.Method {192 default:193 w.WriteHeader(http.StatusBadRequest)194 case http.MethodDelete:195 m.handleSessionDelete(w, r)196 case http.MethodPost:197 if r.URL.RawQuery == "" {198 m.handleSessionCreate(w, r)199 } else {200 m.handleSessionGet(w, r)201 }202 }203}204func (m mockVCSAServer) handleSessionCreate(w http.ResponseWriter, r *http.Request) {205 if !m.isReqAuthenticated(r) {206 w.WriteHeader(http.StatusUnauthorized)207 return208 }209 w.WriteHeader(http.StatusOK)210 s := struct{ Value string }{Value: m.sessionID}211 b, _ := json.Marshal(s)212 _, _ = w.Write(b)213}214func (m mockVCSAServer) handleSessionGet(w http.ResponseWriter, r *http.Request) {215 if !m.isSessionAuthenticated(r) {216 w.WriteHeader(http.StatusUnauthorized)217 return218 }219 w.WriteHeader(http.StatusOK)220 s := struct{ Value struct{ User string } }{Value: struct{ User string }{User: m.username}}221 b, _ := json.Marshal(s)222 _, _ = w.Write(b)223}224func (m mockVCSAServer) handleSessionDelete(w http.ResponseWriter, r *http.Request) {225 if !m.isSessionAuthenticated(r) {226 w.WriteHeader(http.StatusUnauthorized)227 return228 }229 w.WriteHeader(http.StatusOK)230}231func (m mockVCSAServer) isReqAuthenticated(r *http.Request) bool {232 u, p, ok := r.BasicAuth()233 return ok && m.username == u && p == m.password234}235func (m mockVCSAServer) isSessionAuthenticated(r *http.Request) bool {236 return r.Header.Get(apiSessIDKey) == m.sessionID237}...

Full Screen

Full Screen

file_sources_test.go

Source:file_sources_test.go Github

copy

Full Screen

...11 ctlres "github.com/vmware-tanzu/carvel-kapp/pkg/kapp/resources"12)13func TestHTTPFileSources(t *testing.T) {14 url := "http://example.com/some/path"15 client := NewTestClient(func(req *http.Request) *http.Response {16 // Test request parameters17 require.Equal(t, req.URL.String(), url)18 return &http.Response{19 StatusCode: http.StatusOK,20 // Send response to be tested21 Body: ioutil.NopCloser(bytes.NewBufferString(`OK`)),22 // Must be set to non-nil value or it panics23 Header: make(http.Header),24 }25 })26 fileSource := ctlres.NewHTTPFileSource(url)27 fileSource.Client = client28 body, err := fileSource.Bytes()29 require.NoError(t, err)30 require.Equal(t, []byte("OK"), body)31 // 2xx Status Codes32 client = NewTestClient(func(req *http.Request) *http.Response {33 // Test request parameters34 require.Equal(t, req.URL.String(), url)35 return &http.Response{36 StatusCode: http.StatusIMUsed,37 Body: ioutil.NopCloser(bytes.NewBufferString(`OK`)),38 Header: make(http.Header),39 }40 })41 fileSource = ctlres.NewHTTPFileSource(url)42 fileSource.Client = client43 body, err = fileSource.Bytes()44 require.NoError(t, err)45 require.Equal(t, []byte("OK"), body)46 // Non-OK HTTP Status Code47 status := "404 Not Found"48 client = NewTestClient(func(req *http.Request) *http.Response {49 // Test request parameters50 require.Equal(t, req.URL.String(), url)51 return &http.Response{52 StatusCode: http.StatusNotFound,53 Status: status,54 Header: make(http.Header),55 }56 })57 fileSource = ctlres.NewHTTPFileSource(url)58 fileSource.Client = client59 body, err = fileSource.Bytes()60 require.EqualError(t, err, fmt.Sprintf("Requesting URL '%s': %s", url, status))61}62// NewTestClient returns *http.Client with Transport replaced to avoid making real calls63func NewTestClient(fn RoundTripFunc) *http.Client {64 return &http.Client{65 Transport: RoundTripFunc(fn),66 }67}68type RoundTripFunc func(req *http.Request) *http.Response69func (f RoundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {70 return f(req), nil71}...

Full Screen

Full Screen

NewTestClient

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 str, err := req.String()4 if err != nil {5 panic(err)6 }7 fmt.Println(str)8}9import (10func main() {11 str, err := req.String()12 if err != nil {13 panic(err)14 }15 fmt.Println(str)16}17import (18func main() {19 str, err := req.String()20 if err != nil {21 panic(err)22 }23 fmt.Println(str)24}25import (26func main() {27 str, err := req.String()28 if err != nil {29 panic(err)30 }31 fmt.Println(str)32}33import (34func main() {35 str, err := req.String()36 if err != nil {37 panic(err)38 }39 fmt.Println(str)40}41import (42func main() {43 str, err := req.String()44 if err != nil {45 panic(err)46 }47 fmt.Println(str)48}

Full Screen

Full Screen

NewTestClient

Using AI Code Generation

copy

Full Screen

1func main() {2 client := client.NewTestClient()3 fmt.Printf("Client: %v4}5import (6type TestClient struct {7}8func NewTestClient() *TestClient {9 return &TestClient{Name: "Test Client"}10}11func (t *TestClient) String() string {12 return fmt.Sprintf("TestClient: %v", t.Name)13}

Full Screen

Full Screen

NewTestClient

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("client main")4 client.NewTestClient()5}6import (7func NewTestClient() {8 fmt.Println("client")9}

Full Screen

Full Screen

NewTestClient

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("golclient test client")4 fmt.Println("golclient test client")5 golclient.NewTestClient()6}7import (8func main() {9 fmt.Println("golclient test client")10 fmt.Println("golclient test client")11 golclient.NewTestClient()12}13import (14func main() {15 fmt.Println("golclient test client")16 fmt.Println("golclient test client")17 golclient.NewTestClient()18}19import (20func main() {21 fmt.Println("golclient test client")22 fmt.Println("golclient test client")23 golclient.NewTestClient()24}25import (26func main() {27 fmt.Println("golclient test client")28 fmt.Println("golclient test client")29 golclient.NewTestClient()30}31import (32func main() {33 fmt.Println("golclient test client")34 fmt.Println("golclient test client")35 golclient.NewTestClient()36}37import (

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