github.com/devcamcar/cli@v0.0.0-20181107134215-706a05759d18/testharness/harness_test.go (about) 1 package testharness 2 3 import ( 4 "io/ioutil" 5 "os" 6 "path" 7 "testing" 8 ) 9 10 func assertFileExists(t *testing.T, destPath string) { 11 stat, err := os.Stat(destPath) 12 if err != nil { 13 t.Fatalf("expecting path %s to exist", destPath) 14 } 15 16 if stat.Size() == 0 { 17 t.Fatalf("expecting path %s to contain data ", destPath) 18 } 19 20 } 21 22 func assertContents(t *testing.T, destPath, content string) { 23 data, err := ioutil.ReadFile(destPath) 24 if err != nil { 25 t.Fatalf("Error reading file %s : %s", destPath, err) 26 } 27 28 if string(data) != content { 29 t.Fatalf("expecting %s to contain `%s` but was `%s`", destPath, content, string(data)) 30 } 31 32 } 33 34 func TestCopyContext(t *testing.T) { 35 36 ctx := Create(t) 37 defer ctx.Cleanup() 38 ctx.CopyFiles(map[string]string{ 39 "testdir/testfiles": "tf", 40 "harness.go": "harness.go", 41 "harness_test.go": "foo/cli_test.go", 42 }) 43 44 assertContents(t, path.Join(ctx.testDir, "tf/test.txt"), "hello world") 45 assertFileExists(t, path.Join(ctx.testDir, "harness.go")) 46 assertFileExists(t, path.Join(ctx.testDir, "foo/cli_test.go")) 47 } 48 49 func TestFileManipulation(t *testing.T) { 50 51 ctx := Create(t) 52 defer ctx.Cleanup() 53 54 ctx.WithFile("fileA.txt", "Foo", 0644) 55 assertContents(t, path.Join(ctx.testDir, "fileA.txt"), "Foo") 56 57 ctx.MkDir("td") 58 ctx.WithFile("td/file.txt", "Foo", 0644) 59 assertContents(t, path.Join(ctx.testDir, "td/file.txt"), "Foo") 60 61 contents := ctx.GetFile("td/file.txt") 62 if contents != "Foo" { 63 t.Errorf("Failed to get file contents , expected Foo, got %s", contents) 64 } 65 66 ctx.MkDir("testDir") 67 ctx.Cd("testDir") 68 ctx.WithFile("fileB.txt", "Bar", 0644) 69 70 assertContents(t, path.Join(ctx.testDir, "testDir/fileB.txt"), "Bar") 71 72 contents = ctx.GetFile("fileB.txt") 73 if contents != "Bar" { 74 t.Errorf("Failed to get file contents , expected Bar, got %s", contents) 75 } 76 77 ctx.Cd("") 78 ctx.WithFile("baseFile", "value1", 0644) 79 80 ctx.FileAppend("baseFile", "value2") 81 assertContents(t, path.Join(ctx.testDir, "baseFile"), "value1value2") 82 83 } 84 85 func TestDirOps(t *testing.T) { 86 87 ctx := Create(t) 88 defer ctx.Cleanup() 89 ctx.MkDir("foo") 90 ctx.Cd("foo") 91 ctx.Cd("../") 92 ctx.MkDir("bar") 93 ctx.Cd("bar") 94 ctx.MkDir("baz") 95 ctx.Cd("baz") 96 ctx.WithFile("bob.txt", "some text", 0644) 97 ctx.Cd("") 98 99 ctx.WithFile("root.txt", "some text", 0644) 100 assertFileExists(t, path.Join(ctx.testDir, "foo")) 101 assertFileExists(t, path.Join(ctx.testDir, "bar")) 102 assertFileExists(t, path.Join(ctx.testDir, "bar/baz")) 103 assertFileExists(t, path.Join(ctx.testDir, "bar/baz/bob.txt")) 104 assertFileExists(t, path.Join(ctx.testDir, "root.txt")) 105 106 }