How to use writeFile method of build Package

Best Syzkaller code snippet using build.writeFile

container_test.go

Source:container_test.go Github

copy

Full Screen

1//+build !skipcontainertests2// Tests that involve spinning up/interacting with actual containers3package build4import (5 "io/ioutil"6 "strings"7 "testing"8 "time"9 "github.com/docker/distribution/reference"10 "github.com/stretchr/testify/assert"11 "github.com/windmilleng/tilt/internal/dockerfile"12 "github.com/windmilleng/tilt/internal/model"13)14// * * * IMAGE BUILDER * * *15func TestStaticDockerfile(t *testing.T) {16 f := newDockerBuildFixture(t)17 defer f.teardown()18 df := dockerfile.Dockerfile(`19FROM alpine20WORKDIR /src21ADD a.txt .22RUN cp a.txt b.txt23ADD dir/c.txt .24`)25 f.WriteFile("a.txt", "a")26 f.WriteFile("dir/c.txt", "c")27 f.WriteFile("missing.txt", "missing")28 ref, err := f.b.BuildDockerfile(f.ctx, f.ps, f.getNameFromTest(), df, f.Path(), model.EmptyMatcher, model.DockerBuildArgs{})29 if err != nil {30 t.Fatal(err)31 }32 pcs := []expectedFile{33 expectedFile{Path: "/src/a.txt", Contents: "a"},34 expectedFile{Path: "/src/b.txt", Contents: "a"},35 expectedFile{Path: "/src/c.txt", Contents: "c"},36 expectedFile{Path: "/src/dir/c.txt", Missing: true},37 expectedFile{Path: "/src/missing.txt", Missing: true},38 }39 f.assertFilesInImage(ref, pcs)40}41func TestStaticDockerfileWithBuildArgs(t *testing.T) {42 f := newDockerBuildFixture(t)43 defer f.teardown()44 df := dockerfile.Dockerfile(`FROM alpine45ARG some_variable_name46ADD $some_variable_name /test.txt`)47 f.WriteFile("awesome_variable", "hi im an awesome variable")48 ba := model.DockerBuildArgs{49 "some_variable_name": "awesome_variable",50 }51 ref, err := f.b.BuildDockerfile(f.ctx, f.ps, f.getNameFromTest(), df, f.Path(), model.EmptyMatcher, ba)52 if err != nil {53 t.Fatal(err)54 }55 expected := []expectedFile{56 expectedFile{Path: "/test.txt", Contents: "hi im an awesome variable"},57 }58 f.assertFilesInImage(ref, expected)59}60func TestMount(t *testing.T) {61 f := newDockerBuildFixture(t)62 defer f.teardown()63 // write some files in to it64 f.WriteFile("hi/hello", "hi hello")65 f.WriteFile("sup", "my name is dan")66 m := model.Mount{67 LocalPath: f.Path(),68 ContainerPath: "/src",69 }70 ref, err := f.b.BuildImageFromScratch(f.ctx, f.ps, f.getNameFromTest(), simpleDockerfile, []model.Mount{m}, model.EmptyMatcher, nil, model.Cmd{})71 if err != nil {72 t.Fatal(err)73 }74 pcs := []expectedFile{75 expectedFile{Path: "/src/hi/hello", Contents: "hi hello"},76 expectedFile{Path: "/src/sup", Contents: "my name is dan"},77 }78 f.assertFilesInImage(ref, pcs)79}80func TestMountFileToDirectory(t *testing.T) {81 f := newDockerBuildFixture(t)82 defer f.teardown()83 f.WriteFile("sup", "my name is dan")84 m := model.Mount{85 LocalPath: f.JoinPath("sup"),86 ContainerPath: "/src/",87 }88 ref, err := f.b.BuildImageFromScratch(f.ctx, f.ps, f.getNameFromTest(), simpleDockerfile, []model.Mount{m}, model.EmptyMatcher, nil, model.Cmd{})89 if err != nil {90 t.Fatal(err)91 }92 pcs := []expectedFile{93 expectedFile{Path: "/src/sup", Contents: "my name is dan"},94 }95 f.assertFilesInImage(ref, pcs)96}97func TestMultipleMounts(t *testing.T) {98 f := newDockerBuildFixture(t)99 defer f.teardown()100 // write some files in to it101 f.WriteFile("hi/hello", "hi hello")102 f.WriteFile("bye/ciao/goodbye", "bye laterz")103 m1 := model.Mount{104 LocalPath: f.JoinPath("hi"),105 ContainerPath: "/hello_there",106 }107 m2 := model.Mount{108 LocalPath: f.JoinPath("bye"),109 ContainerPath: "goodbye_there",110 }111 ref, err := f.b.BuildImageFromScratch(f.ctx, f.ps, f.getNameFromTest(), simpleDockerfile, []model.Mount{m1, m2}, model.EmptyMatcher, nil, model.Cmd{})112 if err != nil {113 t.Fatal(err)114 }115 pcs := []expectedFile{116 expectedFile{Path: "/hello_there/hello", Contents: "hi hello"},117 expectedFile{Path: "/goodbye_there/ciao/goodbye", Contents: "bye laterz"},118 }119 f.assertFilesInImage(ref, pcs)120}121func TestMountCollisions(t *testing.T) {122 f := newDockerBuildFixture(t)123 defer f.teardown()124 // write some files in to it125 f.WriteFile("hi/hello", "hi hello")126 f.WriteFile("bye/hello", "bye laterz")127 // Mounting two files to the same place in the container -- expect the second mount128 // to take precedence (file should contain "bye laterz")129 m1 := model.Mount{130 LocalPath: f.JoinPath("hi"),131 ContainerPath: "/hello_there",132 }133 m2 := model.Mount{134 LocalPath: f.JoinPath("bye"),135 ContainerPath: "/hello_there",136 }137 ref, err := f.b.BuildImageFromScratch(f.ctx, f.ps, f.getNameFromTest(), simpleDockerfile, []model.Mount{m1, m2}, model.EmptyMatcher, nil, model.Cmd{})138 if err != nil {139 t.Fatal(err)140 }141 pcs := []expectedFile{142 expectedFile{Path: "/hello_there/hello", Contents: "bye laterz"},143 }144 f.assertFilesInImage(ref, pcs)145}146func TestPush(t *testing.T) {147 f := newDockerBuildFixture(t)148 defer f.teardown()149 f.startRegistry()150 // write some files in to it151 f.WriteFile("hi/hello", "hi hello")152 f.WriteFile("sup", "my name is dan")153 m := model.Mount{154 LocalPath: f.Path(),155 ContainerPath: "/src",156 }157 name, err := reference.WithName("localhost:5005/myimage")158 if err != nil {159 t.Fatal(err)160 }161 ref, err := f.b.BuildImageFromScratch(f.ctx, f.ps, name, simpleDockerfile, []model.Mount{m}, model.EmptyMatcher, nil, model.Cmd{})162 if err != nil {163 t.Fatal(err)164 }165 namedTagged, err := f.b.PushImage(f.ctx, ref, ioutil.Discard)166 if err != nil {167 t.Fatal(err)168 }169 pcs := []expectedFile{170 expectedFile{Path: "/src/hi/hello", Contents: "hi hello"},171 expectedFile{Path: "/src/sup", Contents: "my name is dan"},172 }173 f.assertFilesInImage(namedTagged, pcs)174}175func TestPushInvalid(t *testing.T) {176 f := newDockerBuildFixture(t)177 defer f.teardown()178 m := model.Mount{179 LocalPath: f.Path(),180 ContainerPath: "/src",181 }182 name, err := reference.WithName("localhost:5005/myimage")183 if err != nil {184 t.Fatal(err)185 }186 ref, err := f.b.BuildImageFromScratch(f.ctx, f.ps, name, simpleDockerfile, []model.Mount{m}, model.EmptyMatcher, nil, model.Cmd{})187 if err != nil {188 t.Fatal(err)189 }190 _, err = f.b.PushImage(f.ctx, ref, ioutil.Discard)191 msg := `pushing image "localhost:5005/myimage"`192 if err == nil || !strings.Contains(err.Error(), msg) {193 t.Fatalf("Expected error containing %q, actual: %v", msg, err)194 }195}196func TestBuildOneStep(t *testing.T) {197 f := newDockerBuildFixture(t)198 defer f.teardown()199 steps := model.ToSteps(f.Path(), []model.Cmd{200 model.ToShellCmd("echo -n hello >> hi"),201 })202 ref, err := f.b.BuildImageFromScratch(f.ctx, f.ps, f.getNameFromTest(), simpleDockerfile, []model.Mount{}, model.EmptyMatcher, steps, model.Cmd{})203 if err != nil {204 t.Fatal(err)205 }206 expected := []expectedFile{207 expectedFile{Path: "hi", Contents: "hello"},208 }209 f.assertFilesInImage(ref, expected)210}211func TestBuildMultipleSteps(t *testing.T) {212 f := newDockerBuildFixture(t)213 defer f.teardown()214 steps := model.ToSteps(f.Path(), []model.Cmd{215 model.ToShellCmd("echo -n hello >> hi"),216 model.ToShellCmd("echo -n sup >> hi2"),217 })218 ref, err := f.b.BuildImageFromScratch(f.ctx, f.ps, f.getNameFromTest(), simpleDockerfile, []model.Mount{}, model.EmptyMatcher, steps, model.Cmd{})219 if err != nil {220 t.Fatal(err)221 }222 expected := []expectedFile{223 expectedFile{Path: "hi", Contents: "hello"},224 expectedFile{Path: "hi2", Contents: "sup"},225 }226 f.assertFilesInImage(ref, expected)227}228func TestBuildMultipleStepsRemoveFiles(t *testing.T) {229 f := newDockerBuildFixture(t)230 defer f.teardown()231 steps := model.ToSteps(f.Path(), []model.Cmd{232 model.Cmd{Argv: []string{"sh", "-c", "echo -n hello >> hi"}},233 model.Cmd{Argv: []string{"sh", "-c", "echo -n sup >> hi2"}},234 model.Cmd{Argv: []string{"sh", "-c", "rm hi"}},235 })236 ref, err := f.b.BuildImageFromScratch(f.ctx, f.ps, f.getNameFromTest(), simpleDockerfile, []model.Mount{}, model.EmptyMatcher, steps, model.Cmd{})237 if err != nil {238 t.Fatal(err)239 }240 expected := []expectedFile{241 expectedFile{Path: "hi2", Contents: "sup"},242 expectedFile{Path: "hi", Missing: true},243 }244 f.assertFilesInImage(ref, expected)245}246func TestBuildFailingStep(t *testing.T) {247 f := newDockerBuildFixture(t)248 defer f.teardown()249 steps := model.ToSteps(f.Path(), []model.Cmd{250 model.ToShellCmd("echo hello && exit 1"),251 })252 _, err := f.b.BuildImageFromScratch(f.ctx, f.ps, f.getNameFromTest(), simpleDockerfile, []model.Mount{}, model.EmptyMatcher, steps, model.Cmd{})253 if assert.NotNil(t, err) {254 assert.Contains(t, err.Error(), "hello")255 // Different versions of docker have a different error string256 hasExitCode1 := strings.Contains(err.Error(), "exit code 1") ||257 strings.Contains(err.Error(), "returned a non-zero code: 1") ||258 strings.Contains(err.Error(), "exit code: 1")259 if !hasExitCode1 {260 t.Errorf("Expected failure with exit code 1, actual: %v", err)261 }262 }263}264func TestEntrypoint(t *testing.T) {265 f := newDockerBuildFixture(t)266 defer f.teardown()267 entrypoint := model.ToShellCmd("echo -n hello >> hi")268 d, err := f.b.BuildImageFromScratch(f.ctx, f.ps, f.getNameFromTest(), simpleDockerfile, nil, model.EmptyMatcher, nil, entrypoint)269 if err != nil {270 t.Fatal(err)271 }272 expected := []expectedFile{273 expectedFile{Path: "hi", Contents: "hello"},274 }275 // Start container WITHOUT overriding entrypoint (which assertFilesInImage... does)276 cID := f.startContainer(f.ctx, containerConfig(d))277 f.assertFilesInContainer(f.ctx, cID, expected)278}279func TestDockerfileWithEntrypointPermitted(t *testing.T) {280 f := newDockerBuildFixture(t)281 defer f.teardown()282 df := dockerfile.Dockerfile(`FROM alpine283ENTRYPOINT ["sleep", "100000"]`)284 _, err := f.b.BuildImageFromScratch(f.ctx, f.ps, f.getNameFromTest(), df, nil, model.EmptyMatcher, nil, model.Cmd{})285 if err != nil {286 t.Errorf("Unexpected error %v", err)287 }288}289// TODO(maia): test mount err cases290// TODO(maia): tests for tar code291func TestSelectiveAddFilesToExisting(t *testing.T) {292 f := newDockerBuildFixture(t)293 defer f.teardown()294 f.WriteFile("hi/hello", "hi hello")295 f.WriteFile("sup", "we should delete this file")296 f.WriteFile("nested/sup", "we should delete this file (and the whole dir)")297 f.WriteFile("unchanged", "should be unchanged")298 mounts := []model.Mount{299 model.Mount{300 LocalPath: f.Path(),301 ContainerPath: "/src",302 },303 }304 existing, err := f.b.BuildImageFromScratch(f.ctx, f.ps, f.getNameFromTest(), simpleDockerfile, mounts, model.EmptyMatcher, nil, model.Cmd{})305 if err != nil {306 t.Fatal(err)307 }308 f.WriteFile("hi/hello", "hello world") // change contents309 f.Rm("sup") // delete a file310 f.Rm("nested") // delete a directory311 files := []string{"hi/hello", "sup", "nested"}312 pms, err := FilesToPathMappings(f.JoinPaths(files), mounts)313 if err != nil {314 f.t.Fatal("FilesToPathMappings:", err)315 }316 ref, err := f.b.BuildImageFromExisting(f.ctx, f.ps, existing, pms, model.EmptyMatcher, nil)317 if err != nil {318 t.Fatal(err)319 }320 pcs := []expectedFile{321 expectedFile{Path: "/src/hi/hello", Contents: "hello world"},322 expectedFile{Path: "/src/sup", Missing: true},323 expectedFile{Path: "/src/nested/sup", Missing: true}, // should have deleted whole directory324 expectedFile{Path: "/src/unchanged", Contents: "should be unchanged"},325 }326 f.assertFilesInImage(ref, pcs)327}328func TestExecStepsOnExisting(t *testing.T) {329 f := newDockerBuildFixture(t)330 defer f.teardown()331 f.WriteFile("foo", "hello world")332 m := model.Mount{333 LocalPath: f.Path(),334 ContainerPath: "/src",335 }336 existing, err := f.b.BuildImageFromScratch(f.ctx, f.ps, f.getNameFromTest(), simpleDockerfile, []model.Mount{m}, model.EmptyMatcher, nil, model.Cmd{})337 if err != nil {338 t.Fatal(err)339 }340 step := model.ToShellCmd("echo -n foo contains: $(cat /src/foo) >> /src/bar")341 steps := model.ToSteps(f.Path(), []model.Cmd{step})342 ref, err := f.b.BuildImageFromExisting(f.ctx, f.ps, existing, MountsToPathMappings([]model.Mount{m}), model.EmptyMatcher, steps)343 if err != nil {344 t.Fatal(err)345 }346 pcs := []expectedFile{347 expectedFile{Path: "/src/foo", Contents: "hello world"},348 expectedFile{Path: "/src/bar", Contents: "foo contains: hello world"},349 }350 f.assertFilesInImage(ref, pcs)351}352func TestBuildImageFromExistingPreservesEntrypoint(t *testing.T) {353 f := newDockerBuildFixture(t)354 defer f.teardown()355 f.WriteFile("foo", "hello world")356 m := model.Mount{357 LocalPath: f.Path(),358 ContainerPath: "/src",359 }360 entrypoint := model.ToShellCmd("echo -n foo contains: $(cat /src/foo) >> /src/bar")361 existing, err := f.b.BuildImageFromScratch(f.ctx, f.ps, f.getNameFromTest(), simpleDockerfile, []model.Mount{m}, model.EmptyMatcher, nil, entrypoint)362 if err != nil {363 t.Fatal(err)364 }365 // change contents of `foo` so when entrypoint exec's the second time, it366 // will change the contents of `bar`367 f.WriteFile("foo", "a whole new world")368 ref, err := f.b.BuildImageFromExisting(f.ctx, f.ps, existing, MountsToPathMappings([]model.Mount{m}), model.EmptyMatcher, nil)369 if err != nil {370 t.Fatal(err)371 }372 expected := []expectedFile{373 expectedFile{Path: "/src/foo", Contents: "a whole new world"},374 expectedFile{Path: "/src/bar", Contents: "foo contains: a whole new world"},375 }376 // Start container WITHOUT overriding entrypoint (which assertFilesInImage... does)377 cID := f.startContainer(f.ctx, containerConfig(ref))378 f.assertFilesInContainer(f.ctx, cID, expected)379}380func TestBuildDockerWithStepsFromExistingPreservesEntrypoint(t *testing.T) {381 f := newDockerBuildFixture(t)382 defer f.teardown()383 f.WriteFile("foo", "hello world")384 m := model.Mount{385 LocalPath: f.Path(),386 ContainerPath: "/src",387 }388 step := model.ToShellCmd("echo -n hello >> /src/baz")389 entrypoint := model.ToShellCmd("echo -n foo contains: $(cat /src/foo) >> /src/bar")390 steps := model.ToSteps(f.Path(), []model.Cmd{step})391 existing, err := f.b.BuildImageFromScratch(f.ctx, f.ps, f.getNameFromTest(), simpleDockerfile, []model.Mount{m}, model.EmptyMatcher, steps, entrypoint)392 if err != nil {393 t.Fatal(err)394 }395 // change contents of `foo` so when entrypoint exec's the second time, it396 // will change the contents of `bar`397 f.WriteFile("foo", "a whole new world")398 ref, err := f.b.BuildImageFromExisting(f.ctx, f.ps, existing, MountsToPathMappings([]model.Mount{m}), model.EmptyMatcher, steps)399 if err != nil {400 t.Fatal(err)401 }402 expected := []expectedFile{403 expectedFile{Path: "/src/foo", Contents: "a whole new world"},404 expectedFile{Path: "/src/bar", Contents: "foo contains: a whole new world"},405 expectedFile{Path: "/src/baz", Contents: "hellohello"},406 }407 // Start container WITHOUT overriding entrypoint (which assertFilesInImage... does)408 cID := f.startContainer(f.ctx, containerConfig(ref))409 f.assertFilesInContainer(f.ctx, cID, expected)410}411// * * * CONTAINER UPDATER * * *412func TestUpdateInContainerE2E(t *testing.T) {413 f := newDockerBuildFixture(t)414 defer f.teardown()415 f.WriteFile("delete_me", "will be deleted")416 m := model.Mount{417 LocalPath: f.Path(),418 ContainerPath: "/src",419 }420 // Allows us to track number of times the entrypoint has been called (i.e. how421 // many times container has been (re)started -- also, sleep a bit so container422 // stays alive for us to manipulate.423 initStartcount := model.ToShellCmd("echo -n 0 > /src/startcount")424 entrypoint := model.ToShellCmd(425 "echo -n $(($(cat /src/startcount)+1)) > /src/startcount && sleep 210")426 steps := model.ToSteps(f.Path(), []model.Cmd{initStartcount})427 imgRef, err := f.b.BuildImageFromScratch(f.ctx, f.ps, f.getNameFromTest(), simpleDockerfile, []model.Mount{m}, model.EmptyMatcher, steps, entrypoint)428 if err != nil {429 t.Fatal(err)430 }431 cID := f.startContainer(f.ctx, containerConfig(imgRef))432 f.Rm("delete_me") // expect to be deleted from container on update433 f.WriteFile("foo", "hello world")434 paths := []pathMapping{435 pathMapping{LocalPath: f.JoinPath("delete_me"), ContainerPath: "/src/delete_me"},436 pathMapping{LocalPath: f.JoinPath("foo"), ContainerPath: "/src/foo"},437 }438 touchBar := model.ToShellCmd("touch /src/bar")439 cUpdater := ContainerUpdater{dcli: f.dcli}440 err = cUpdater.UpdateInContainer(f.ctx, cID, paths, model.EmptyMatcher, []model.Cmd{touchBar}, f.ps.Writer(f.ctx))441 if err != nil {442 f.t.Fatal(err)443 }444 expected := []expectedFile{445 expectedFile{Path: "/src/delete_me", Missing: true},446 expectedFile{Path: "/src/foo", Contents: "hello world"},447 expectedFile{Path: "/src/bar", Contents: ""}, // from cmd448 expectedFile{Path: "/src/startcount", Contents: "2"}, // from entrypoint (confirm container restarted)449 }450 f.assertFilesInContainer(f.ctx, cID, expected)451}452func TestReapOneImage(t *testing.T) {453 f := newDockerBuildFixture(t)454 defer f.teardown()455 m := model.Mount{456 LocalPath: f.Path(),457 ContainerPath: "/src",458 }459 df1 := simpleDockerfile460 ref1, err := f.b.BuildImageFromScratch(f.ctx, f.ps, f.getNameFromTest(), df1, []model.Mount{m}, model.EmptyMatcher, nil, model.Cmd{})461 if err != nil {462 t.Fatal(err)463 }464 label := dockerfile.Label("tilt.reaperTest")465 f.b.extraLabels[label] = "1"466 df2 := simpleDockerfile.Run(model.ToShellCmd("echo hi >> hi.txt"))467 ref2, err := f.b.BuildImageFromScratch(f.ctx, f.ps, f.getNameFromTest(), df2, []model.Mount{m}, model.EmptyMatcher, nil, model.Cmd{})468 if err != nil {469 t.Fatal(err)470 }471 err = f.reaper.RemoveTiltImages(f.ctx, time.Now().Add(time.Second), false, FilterByLabel(label))472 if err != nil {473 t.Fatal(err)474 }475 f.assertImageExists(ref1)476 f.assertImageNotExists(ref2)477}478func TestConditionalRunInRealDocker(t *testing.T) {479 f := newDockerBuildFixture(t)480 defer f.teardown()481 f.WriteFile("a.txt", "a")482 f.WriteFile("b.txt", "b")483 m := model.Mount{484 LocalPath: f.Path(),485 ContainerPath: "/src",486 }487 step1 := model.Step{488 Cmd: model.ToShellCmd("cat /src/a.txt >> /src/c.txt"),489 Triggers: []string{"a.txt"},490 BaseDirectory: f.Path(),491 }492 step2 := model.Step{493 Cmd: model.ToShellCmd("cat /src/b.txt >> /src/d.txt"),494 }495 ref, err := f.b.BuildImageFromScratch(f.ctx, f.ps, f.getNameFromTest(), simpleDockerfile, []model.Mount{m}, model.EmptyMatcher, []model.Step{step1, step2}, model.Cmd{})496 if err != nil {497 t.Fatal(err)498 }499 pcs := []expectedFile{500 expectedFile{Path: "/src/a.txt", Contents: "a"},501 expectedFile{Path: "/src/b.txt", Contents: "b"},502 expectedFile{Path: "/src/c.txt", Contents: "a"},503 expectedFile{Path: "/src/d.txt", Contents: "b"},504 }505 f.assertFilesInImage(ref, pcs)506}...

Full Screen

Full Screen

builder_test.go

Source:builder_test.go Github

copy

Full Screen

1package builder2import (3 "bytes"4 "encoding/json"5 "fmt"6 "io"7 "io/ioutil"8 "os"9 "path/filepath"10 "testing"11 "golang.org/x/net/context"12 "github.com/docker/docker/api/types"13 "github.com/docker/docker/pkg/archive"14 "github.com/docker/docker/pkg/jsonmessage"15 "github.com/triompha/libcompose/test"16)17type DaemonClient struct {18 test.NopClient19 contextDir string20 imageName string21 changes int22 message jsonmessage.JSONMessage23}24func (c *DaemonClient) ImageBuild(ctx context.Context, context io.Reader, options types.ImageBuildOptions) (types.ImageBuildResponse, error) {25 if c.imageName != "" {26 if len(options.Tags) != 1 || options.Tags[0] != c.imageName {27 return types.ImageBuildResponse{}, fmt.Errorf("expected image %q, got %v", c.imageName, options.Tags)28 }29 }30 if c.contextDir != "" {31 tmp, err := ioutil.TempDir("", "image-build-test")32 if err != nil {33 return types.ImageBuildResponse{}, err34 }35 if err := archive.Untar(context, tmp, nil); err != nil {36 return types.ImageBuildResponse{}, err37 }38 changes, err := archive.ChangesDirs(tmp, c.contextDir)39 if err != nil {40 return types.ImageBuildResponse{}, err41 }42 if len(changes) != c.changes {43 return types.ImageBuildResponse{}, fmt.Errorf("expected %d changes, got %v", c.changes, changes)44 }45 b, err := json.Marshal(c.message)46 if err != nil {47 return types.ImageBuildResponse{}, err48 }49 return types.ImageBuildResponse{50 Body: ioutil.NopCloser(bytes.NewReader(b)),51 }, nil52 }53 return c.NopClient.ImageBuild(ctx, context, options)54}55func TestBuildInvalidContextDirectoryOrDockerfile(t *testing.T) {56 tmpDir, err := ioutil.TempDir("", "daemonbuilder-test")57 if err != nil {58 t.Fatal(err)59 }60 testCases := []struct {61 contextDirectory string62 dockerfile string63 expected string64 }{65 {66 contextDirectory: "",67 dockerfile: "",68 expected: "Cannot locate Dockerfile: Dockerfile",69 },70 {71 contextDirectory: "",72 dockerfile: "test.Dockerfile",73 expected: "Cannot locate Dockerfile: test.Dockerfile",74 },75 {76 contextDirectory: "/I/DONT/EXISTS",77 dockerfile: "",78 expected: "Cannot locate Dockerfile: Dockerfile",79 },80 {81 contextDirectory: "/I/DONT/EXISTS",82 dockerfile: "test.Dockerfile",83 expected: "Cannot locate Dockerfile: /I/DONT/EXISTS/test.Dockerfile",84 },85 {86 contextDirectory: tmpDir,87 dockerfile: "test.Dockerfile",88 expected: "Cannot locate Dockerfile: " + filepath.Join(tmpDir, "test.Dockerfile"),89 },90 }91 for _, c := range testCases {92 builder := &DaemonBuilder{93 ContextDirectory: c.contextDirectory,94 Dockerfile: c.dockerfile,95 }96 err := builder.Build(context.Background(), "image")97 if err == nil || err.Error() != c.expected {98 t.Fatalf("expected an error %q, got %s", c.expected, err)99 }100 }101}102func TestBuildWithClientBuildError(t *testing.T) {103 tmpDir, err := ioutil.TempDir("", "daemonbuilder-test")104 if err != nil {105 t.Fatal(err)106 }107 defer os.RemoveAll(tmpDir)108 if err := ioutil.WriteFile(filepath.Join(tmpDir, DefaultDockerfileName), []byte("FROM busybox"), 0700); err != nil {109 t.Fatal(err)110 }111 imageName := "image"112 client := &DaemonClient{}113 builder := &DaemonBuilder{114 ContextDirectory: tmpDir,115 Client: client,116 }117 err = builder.Build(context.Background(), imageName)118 if err == nil || err.Error() != "Engine no longer exists" {119 t.Fatalf("expected an 'Engine no longer exists', got %s", err)120 }121}122func TestBuildWithDefaultDockerfile(t *testing.T) {123 tmpDir, err := ioutil.TempDir("", "daemonbuilder-test")124 if err != nil {125 t.Fatal(err)126 }127 defer os.RemoveAll(tmpDir)128 if err := ioutil.WriteFile(filepath.Join(tmpDir, DefaultDockerfileName), []byte("FROM busybox"), 0700); err != nil {129 t.Fatal(err)130 }131 if err := ioutil.WriteFile(filepath.Join(tmpDir, "afile"), []byte("another file"), 0700); err != nil {132 t.Fatal(err)133 }134 imageName := "image"135 client := &DaemonClient{136 contextDir: tmpDir,137 imageName: imageName,138 }139 builder := &DaemonBuilder{140 ContextDirectory: tmpDir,141 Client: client,142 }143 err = builder.Build(context.Background(), imageName)144 if err != nil {145 t.Fatal(err)146 }147}148func TestBuildWithDefaultLowercaseDockerfile(t *testing.T) {149 tmpDir, err := ioutil.TempDir("", "daemonbuilder-test")150 if err != nil {151 t.Fatal(err)152 }153 defer os.RemoveAll(tmpDir)154 if err := ioutil.WriteFile(filepath.Join(tmpDir, "dockerfile"), []byte("FROM busybox"), 0700); err != nil {155 t.Fatal(err)156 }157 if err := ioutil.WriteFile(filepath.Join(tmpDir, "afile"), []byte("another file"), 0700); err != nil {158 t.Fatal(err)159 }160 imageName := "image"161 client := &DaemonClient{162 contextDir: tmpDir,163 imageName: imageName,164 }165 builder := &DaemonBuilder{166 ContextDirectory: tmpDir,167 Client: client,168 }169 err = builder.Build(context.Background(), imageName)170 if err != nil {171 t.Fatal(err)172 }173}174func TestBuildWithSpecificDockerfile(t *testing.T) {175 tmpDir, err := ioutil.TempDir("", "daemonbuilder-test")176 if err != nil {177 t.Fatal(err)178 }179 defer os.RemoveAll(tmpDir)180 if err := ioutil.WriteFile(filepath.Join(tmpDir, "test.Dockerfile"), []byte("FROM busybox"), 0700); err != nil {181 t.Fatal(err)182 }183 if err := ioutil.WriteFile(filepath.Join(tmpDir, "afile"), []byte("another file"), 0700); err != nil {184 t.Fatal(err)185 }186 imageName := "image"187 client := &DaemonClient{188 contextDir: tmpDir,189 imageName: imageName,190 }191 builder := &DaemonBuilder{192 ContextDirectory: tmpDir,193 Dockerfile: "test.Dockerfile",194 Client: client,195 }196 err = builder.Build(context.Background(), imageName)197 if err != nil {198 t.Fatal(err)199 }200}201func TestBuildWithDockerignoreNothing(t *testing.T) {202 tmpDir, err := ioutil.TempDir("", "daemonbuilder-test")203 if err != nil {204 t.Fatal(err)205 }206 defer os.RemoveAll(tmpDir)207 if err := ioutil.WriteFile(filepath.Join(tmpDir, "test.Dockerfile"), []byte("FROM busybox"), 0700); err != nil {208 t.Fatal(err)209 }210 if err := ioutil.WriteFile(filepath.Join(tmpDir, "afile"), []byte("another file"), 0700); err != nil {211 t.Fatal(err)212 }213 if err := ioutil.WriteFile(filepath.Join(tmpDir, ".dockerignore"), []byte(""), 0700); err != nil {214 t.Fatal(err)215 }216 imageName := "image"217 client := &DaemonClient{218 contextDir: tmpDir,219 imageName: imageName,220 }221 builder := &DaemonBuilder{222 ContextDirectory: tmpDir,223 Dockerfile: "test.Dockerfile",224 Client: client,225 }226 err = builder.Build(context.Background(), imageName)227 if err != nil {228 t.Fatal(err)229 }230}231func TestBuildWithDockerignoreDockerfileAndItself(t *testing.T) {232 tmpDir, err := ioutil.TempDir("", "daemonbuilder-test")233 if err != nil {234 t.Fatal(err)235 }236 defer os.RemoveAll(tmpDir)237 if err := ioutil.WriteFile(filepath.Join(tmpDir, "test.Dockerfile"), []byte("FROM busybox"), 0700); err != nil {238 t.Fatal(err)239 }240 if err := ioutil.WriteFile(filepath.Join(tmpDir, "afile"), []byte("another file"), 0700); err != nil {241 t.Fatal(err)242 }243 if err := ioutil.WriteFile(filepath.Join(tmpDir, ".dockerignore"), []byte("Dockerfile\n.dockerignore"), 0700); err != nil {244 t.Fatal(err)245 }246 imageName := "image"247 client := &DaemonClient{248 contextDir: tmpDir,249 imageName: imageName,250 }251 builder := &DaemonBuilder{252 ContextDirectory: tmpDir,253 Dockerfile: "test.Dockerfile",254 Client: client,255 }256 err = builder.Build(context.Background(), imageName)257 if err != nil {258 t.Fatal(err)259 }260}261func TestBuildWithDockerignoreAfile(t *testing.T) {262 tmpDir, err := ioutil.TempDir("", "daemonbuilder-test")263 if err != nil {264 t.Fatal(err)265 }266 defer os.RemoveAll(tmpDir)267 if err := ioutil.WriteFile(filepath.Join(tmpDir, "test.Dockerfile"), []byte("FROM busybox"), 0700); err != nil {268 t.Fatal(err)269 }270 if err := ioutil.WriteFile(filepath.Join(tmpDir, "afile"), []byte("another file"), 0700); err != nil {271 t.Fatal(err)272 }273 if err := ioutil.WriteFile(filepath.Join(tmpDir, ".dockerignore"), []byte("afile"), 0700); err != nil {274 t.Fatal(err)275 }276 imageName := "image"277 client := &DaemonClient{278 contextDir: tmpDir,279 imageName: imageName,280 changes: 1,281 }282 builder := &DaemonBuilder{283 ContextDirectory: tmpDir,284 Dockerfile: "test.Dockerfile",285 Client: client,286 }287 err = builder.Build(context.Background(), imageName)288 if err != nil {289 t.Fatal(err)290 }291}292func TestBuildWithErrorJSONMessage(t *testing.T) {293 tmpDir, err := ioutil.TempDir("", "daemonbuilder-test")294 if err != nil {295 t.Fatal(err)296 }297 defer os.RemoveAll(tmpDir)298 if err := ioutil.WriteFile(filepath.Join(tmpDir, DefaultDockerfileName), []byte("FROM busybox"), 0700); err != nil {299 t.Fatal(err)300 }301 if err := ioutil.WriteFile(filepath.Join(tmpDir, "afile"), []byte("another file"), 0700); err != nil {302 t.Fatal(err)303 }304 imageName := "image"305 client := &DaemonClient{306 contextDir: tmpDir,307 imageName: imageName,308 message: jsonmessage.JSONMessage{309 Error: &jsonmessage.JSONError{310 Code: 0,311 Message: "error",312 },313 },314 }315 builder := &DaemonBuilder{316 ContextDirectory: tmpDir,317 Client: client,318 }319 err = builder.Build(context.Background(), imageName)320 expectedError := "Status: error, Code: 1"321 if err == nil || err.Error() != expectedError {322 t.Fatalf("expected an error about %q, got %s", expectedError, err)323 }324}...

Full Screen

Full Screen

writeFile

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 file, err := os.Create("test.txt")4 if err != nil {5 fmt.Println(err)6 }7 defer file.Close()8 file.WriteString("Hello World")9}10import (11func main() {12 file, err := os.OpenFile("test.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)13 if err != nil {14 fmt.Println(err)15 }16 defer file.Close()17 file.WriteString("Hello World")18}

Full Screen

Full Screen

writeFile

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 var file, err = os.OpenFile("file.txt", os.O_RDWR, 0644)4 if isError(err) {5 }6 defer file.Close()7 var text = []byte("Hello\nWorld")8 n, err := file.Write(text)9 if isError(err) {10 }11 fmt.Printf("Written %d bytes12 err = file.Sync()13 if isError(err) {14 }15 var text2 = []byte("Hello\nWorld")16 n, err = file.Write(text2)17 if isError(err) {18 }19 fmt.Printf("Written %d bytes20 err = file.Sync()21 if isError(err) {22 }23 var text3 = []byte("Hello\nWorld")24 n, err = file.Write(text3)25 if isError(err) {26 }27 fmt.Printf("Written %d bytes28 err = file.Sync()29 if isError(err) {30 }31 var text4 = []byte("Hello\nWorld")32 n, err = file.Write(text4)33 if isError(err) {34 }35 fmt.Printf("Written %d bytes36 err = file.Sync()37 if isError(err) {38 }39 var text5 = []byte("Hello\nWorld")40 n, err = file.Write(text5)41 if isError(err) {42 }43 fmt.Printf("Written %d bytes44 err = file.Sync()45 if isError(err) {46 }47 var text6 = []byte("Hello\nWorld")

Full Screen

Full Screen

writeFile

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 file, err := os.Create("test.txt")4 if err != nil {5 fmt.Println(err)6 }7 _, err = file.Write([]byte("This is a test file"))8 if err != nil {9 fmt.Println(err)10 file.Close()11 }12 err = file.Close()13 if err != nil {14 fmt.Println(err)15 }16 file, err = os.OpenFile("test.txt", os.O_RDWR, 0644)17 if err != nil {18 fmt.Println(err)19 }20 bs := make([]byte, 5)21 _, err = file.Read(bs)22 if err != nil {23 fmt.Println(err)24 }25 fmt.Println(string(bs))26 _, err = file.Seek(6, 0)27 if err != nil {28 fmt.Println(err)29 }30 _, err = file.Read(bs)31 if err != nil {32 fmt.Println(err)33 }34 fmt.Println(string(bs))35 err = file.Close()36 if err != nil {37 fmt.Println(err)38 }39}40func ReadFile(filename string) ([]byte, error)41import (42func main() {43 bs, err := ioutil.ReadFile("test.txt")44 if err != nil {45 }46 str := string(bs)47 fmt.Println(str)

Full Screen

Full Screen

writeFile

Using AI Code Generation

copy

Full Screen

1import "fmt"2func main() {3 b.writeFile()4}5import "fmt"6type build struct {7}8func (b build) writeFile() {9 fmt.Println("Write file")10}11import "fmt"12type build struct {13}14func (b build) WriteFile() {15 fmt.Println("Write file")16}17func main() {18 b.WriteFile()19}20import "fmt"21type build struct {22}23func (b build) writeFile() {24 fmt.Println("Write file")25}26func main() {27 b.writeFile()28}

Full Screen

Full Screen

writeFile

Using AI Code Generation

copy

Full Screen

1import "fmt"2import "os"3func main() {4 file, err := os.Create("test.txt")5 if err != nil {6 fmt.Println("Error in creating file")7 }8 _, err = file.WriteString("Hello World")9 if err != nil {10 fmt.Println("Error in writing to file")11 }12 err = file.Close()13 if err != nil {14 fmt.Println("Error in closing file")15 }16}17import "fmt"18import "os"19func main() {20 file, err := os.OpenFile("test.txt", os.O_APPEND|os.O_WRONLY, 0600)21 if err != nil {22 fmt.Println("Error in opening file")23 }24 _, err = file.WriteString("Hello World")25 if err != nil {26 fmt.Println("Error in writing to file")27 }28 err = file.Close()29 if err != nil {30 fmt.Println("Error in closing file")31 }32}33import "fmt"34import "io/ioutil"35func main() {36 err := ioutil.WriteFile("test.txt", []byte("Hello World"), 0644)37 if err != nil {38 fmt.Println("Error in creating file")39 }40 err = ioutil.WriteFile("test.txt", []byte("Hello World"), 0644)

Full Screen

Full Screen

writeFile

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Writing to a file in Go")4 writeFile()5}6func writeFile() {7 file, err := os.Create("C:/Users/HP/Desktop/GoLang/2.txt")8 if err != nil {9 fmt.Println(err)10 }11 defer file.Close()12 file.WriteString("Writing to a file in Go")13}14import (15func main() {16 fmt.Println("Reading a file in Go")17 readFile()18}19func readFile() {20 data, err := ioutil.ReadFile("C:/Users/HP/Desktop/GoLang/2.txt")21 if err != nil {22 fmt.Println(err)23 }24 fmt.Println("Contents of file:", string(data))25}

Full Screen

Full Screen

writeFile

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 absPath, _ := filepath.Abs("")4 file, err := os.Create(absPath + "/test.txt")5 if err != nil {6 fmt.Println(err)7 }8 file.WriteString("Hello World")9 file.Close()10}

Full Screen

Full Screen

Automation Testing Tutorials

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

LambdaTest Learning Hubs:

YouTube

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

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful