github.com/duglin/docker@v1.13.1/builder/dockerignore_test.go (about) 1 package builder 2 3 import ( 4 "io/ioutil" 5 "log" 6 "os" 7 "sort" 8 "testing" 9 ) 10 11 const shouldStayFilename = "should_stay" 12 13 func extractFilenames(files []os.FileInfo) []string { 14 filenames := make([]string, len(files), len(files)) 15 16 for i, file := range files { 17 filenames[i] = file.Name() 18 } 19 20 return filenames 21 } 22 23 func checkDirectory(t *testing.T, dir string, expectedFiles []string) { 24 files, err := ioutil.ReadDir(dir) 25 26 if err != nil { 27 t.Fatalf("Could not read directory: %s", err) 28 } 29 30 if len(files) != len(expectedFiles) { 31 log.Fatalf("Directory should contain exactly %d file(s), got %d", len(expectedFiles), len(files)) 32 } 33 34 filenames := extractFilenames(files) 35 sort.Strings(filenames) 36 sort.Strings(expectedFiles) 37 38 for i, filename := range filenames { 39 if filename != expectedFiles[i] { 40 t.Fatalf("File %s should be in the directory, got: %s", expectedFiles[i], filename) 41 } 42 } 43 } 44 45 func executeProcess(t *testing.T, contextDir string) { 46 modifiableCtx := &tarSumContext{root: contextDir} 47 ctx := DockerIgnoreContext{ModifiableContext: modifiableCtx} 48 49 err := ctx.Process([]string{DefaultDockerfileName}) 50 51 if err != nil { 52 t.Fatalf("Error when executing Process: %s", err) 53 } 54 } 55 56 func TestProcessShouldRemoveDockerfileDockerignore(t *testing.T) { 57 contextDir, cleanup := createTestTempDir(t, "", "builder-dockerignore-process-test") 58 defer cleanup() 59 60 createTestTempFile(t, contextDir, shouldStayFilename, testfileContents, 0777) 61 createTestTempFile(t, contextDir, dockerignoreFilename, "Dockerfile\n.dockerignore", 0777) 62 createTestTempFile(t, contextDir, DefaultDockerfileName, dockerfileContents, 0777) 63 64 executeProcess(t, contextDir) 65 66 checkDirectory(t, contextDir, []string{shouldStayFilename}) 67 68 } 69 70 func TestProcessNoDockerignore(t *testing.T) { 71 contextDir, cleanup := createTestTempDir(t, "", "builder-dockerignore-process-test") 72 defer cleanup() 73 74 createTestTempFile(t, contextDir, shouldStayFilename, testfileContents, 0777) 75 createTestTempFile(t, contextDir, DefaultDockerfileName, dockerfileContents, 0777) 76 77 executeProcess(t, contextDir) 78 79 checkDirectory(t, contextDir, []string{shouldStayFilename, DefaultDockerfileName}) 80 81 } 82 83 func TestProcessShouldLeaveAllFiles(t *testing.T) { 84 contextDir, cleanup := createTestTempDir(t, "", "builder-dockerignore-process-test") 85 defer cleanup() 86 87 createTestTempFile(t, contextDir, shouldStayFilename, testfileContents, 0777) 88 createTestTempFile(t, contextDir, DefaultDockerfileName, dockerfileContents, 0777) 89 createTestTempFile(t, contextDir, dockerignoreFilename, "input1\ninput2", 0777) 90 91 executeProcess(t, contextDir) 92 93 checkDirectory(t, contextDir, []string{shouldStayFilename, DefaultDockerfileName, dockerignoreFilename}) 94 95 }