From cdac765d152823e5f604ed760b37df07db770dc6 Mon Sep 17 00:00:00 2001 From: Thomas Hipp Date: Mon, 2 Jul 2018 21:12:54 +0200 Subject: [PATCH] tests: Use testify Signed-off-by: Thomas Hipp --- generators/dump_test.go | 42 ++++-------- generators/generators_test.go | 59 +++++------------ generators/hostname_test.go | 30 +++------ generators/hosts_test.go | 30 +++------ generators/template_test.go | 37 ++++------- image/lxc_test.go | 121 +++++++++------------------------- image/lxd_test.go | 72 +++++++------------- shared/definition_test.go | 57 +++++----------- shared/osarch_test.go | 18 ++--- shared/util_test.go | 52 ++++++--------- 10 files changed, 153 insertions(+), 365 deletions(-) diff --git a/generators/dump_test.go b/generators/dump_test.go index bb417bb..8b40acf 100644 --- a/generators/dump_test.go +++ b/generators/dump_test.go @@ -7,7 +7,7 @@ import ( "path/filepath" "testing" - lxd "github.com/lxc/lxd/shared" + "github.com/stretchr/testify/require" "github.com/lxc/distrobuilder/shared" ) @@ -20,35 +20,25 @@ func TestDumpGeneratorRunLXC(t *testing.T) { defer teardown(cacheDir) generator := Get("dump") - if generator == nil { - t.Fatal("Expected dump generator, got nil") - } + require.Equal(t, DumpGenerator{}, generator) err := generator.RunLXC(cacheDir, rootfsDir, nil, shared.DefinitionFile{ Path: "/hello/world", Content: "hello world", }) - if err != nil { - t.Fatalf("Unexpected error: %s", err) - } + require.NoError(t, err) - if !lxd.PathExists(filepath.Join(rootfsDir, "hello", "world")) { - t.Fatalf("Directory '%s' wasn't created", "/hello/world") - } + require.FileExists(t, filepath.Join(rootfsDir, "hello", "world")) var buffer bytes.Buffer file, err := os.Open(filepath.Join(rootfsDir, "hello", "world")) - if err != nil { - t.Fatalf("Unexpected error: %s", err) - } + require.NoError(t, err) defer file.Close() io.Copy(&buffer, file) - if buffer.String() != "hello world\n" { - t.Fatalf("Expected '%s', got '%s'", "hello world", buffer.String()) - } + require.Equal(t, "hello world\n", buffer.String()) } func TestDumpGeneratorRunLXD(t *testing.T) { @@ -59,33 +49,23 @@ func TestDumpGeneratorRunLXD(t *testing.T) { defer teardown(cacheDir) generator := Get("dump") - if generator == nil { - t.Fatal("Expected dump generator, got nil") - } + require.Equal(t, DumpGenerator{}, generator) err := generator.RunLXD(cacheDir, rootfsDir, nil, shared.DefinitionFile{ Path: "/hello/world", Content: "hello world", }) - if err != nil { - t.Fatalf("Unexpected error: %s", err) - } + require.NoError(t, err) - if !lxd.PathExists(filepath.Join(rootfsDir, "hello", "world")) { - t.Fatalf("Directory '%s' wasn't created", "/hello/world") - } + require.FileExists(t, filepath.Join(rootfsDir, "hello", "world")) var buffer bytes.Buffer file, err := os.Open(filepath.Join(rootfsDir, "hello", "world")) - if err != nil { - t.Fatalf("Unexpected error: %s", err) - } + require.NoError(t, err) defer file.Close() io.Copy(&buffer, file) - if buffer.String() != "hello world\n" { - t.Fatalf("Expected '%s', got '%s'", "hello world", buffer.String()) - } + require.Equal(t, "hello world\n", buffer.String()) } diff --git a/generators/generators_test.go b/generators/generators_test.go index 63a9dd6..2721b27 100644 --- a/generators/generators_test.go +++ b/generators/generators_test.go @@ -5,16 +5,15 @@ import ( "io" "os" "path/filepath" - "reflect" "testing" + + "github.com/stretchr/testify/require" ) func setup(t *testing.T, cacheDir string) { // Create rootfs directory err := os.MkdirAll(filepath.Join(cacheDir, "rootfs"), 0755) - if err != nil { - t.Fatalf("Failed to create rootfs directory: %s", err) - } + require.NoError(t, err) } func teardown(cacheDir string) { @@ -23,19 +22,13 @@ func teardown(cacheDir string) { func TestGet(t *testing.T) { generator := Get("hostname") - if generator == nil || reflect.DeepEqual(&generator, HostnameGenerator{}) { - t.Fatal("Expected hostname generator") - } + require.Equal(t, HostnameGenerator{}, generator) generator = Get("hosts") - if generator == nil || reflect.DeepEqual(&generator, HostsGenerator{}) { - t.Fatal("Expected hosts generator") - } + require.Equal(t, HostsGenerator{}, generator) generator = Get("") - if generator != nil { - t.Fatalf("Expected nil, got '%v'", generator) - } + require.Nil(t, generator) } func TestRestoreFiles(t *testing.T) { @@ -47,9 +40,7 @@ func TestRestoreFiles(t *testing.T) { // Create test directory err := os.MkdirAll(filepath.Join(cacheDir, "rootfs", "testdir1"), 0755) - if err != nil { - t.Fatalf("Failed to create test directory: %s", err) - } + require.NoError(t, err) // Create original test file createTestFile(t, filepath.Join(cacheDir, "rootfs", "testdir1", "testfile1"), @@ -57,25 +48,17 @@ func TestRestoreFiles(t *testing.T) { // Chmod cache directory which should lead to StoreFile failing err = os.Chmod(cacheDir, 0600) - if err != nil { - t.Fatalf("Failed to chmod cache directory: %s", err) - } + require.NoError(t, err) err = StoreFile(cacheDir, cacheDir, filepath.Join("/testdir1", "testfile1")) - if err == nil { - t.Fatal("Expected failure") - } + require.Error(t, err) // Restore permissions err = os.Chmod(cacheDir, 0755) - if err != nil { - t.Fatalf("Failed to chmod cache directory: %s", err) - } + require.NoError(t, err) err = StoreFile(cacheDir, rootfsDir, filepath.Join("/testdir1", "testfile1")) - if err != nil { - t.Fatalf("Failed to store file: %s", err) - } + require.NoError(t, err) validateTestFile(t, filepath.Join(cacheDir, "tmp", "testdir1", "testfile1"), "original file") @@ -85,9 +68,7 @@ func TestRestoreFiles(t *testing.T) { "modified file") err = RestoreFiles(cacheDir, rootfsDir) - if err != nil { - t.Fatalf("Failed to restore file: %s", err) - } + require.NoError(t, err) validateTestFile(t, filepath.Join(cacheDir, "rootfs", "testdir1", "testfile1"), "original file") @@ -95,28 +76,20 @@ func TestRestoreFiles(t *testing.T) { func createTestFile(t *testing.T, path, content string) { file, err := os.Create(path) - if err != nil { - t.Fatalf("Unexpected error: %s", err) - } + require.NoError(t, err) defer file.Close() _, err = file.WriteString(content) - if err != nil { - t.Fatalf("Failed to write to testfile") - } + require.NoError(t, err) } func validateTestFile(t *testing.T, path, content string) { file, err := os.Open(path) - if err != nil { - t.Fatalf("Failed to open testfile: %s", err) - } + require.NoError(t, err) defer file.Close() var buffer bytes.Buffer io.Copy(&buffer, file) - if buffer.String() != content { - t.Fatalf("Expected file content to be '%s', got '%s'", content, buffer.String()) - } + require.Equal(t, content, buffer.String()) } diff --git a/generators/hostname_test.go b/generators/hostname_test.go index 16036b5..b750505 100644 --- a/generators/hostname_test.go +++ b/generators/hostname_test.go @@ -5,6 +5,8 @@ import ( "path/filepath" "testing" + "github.com/stretchr/testify/require" + "github.com/lxc/distrobuilder/image" "github.com/lxc/distrobuilder/shared" ) @@ -17,9 +19,7 @@ func TestHostnameGeneratorRunLXC(t *testing.T) { defer teardown(cacheDir) generator := Get("hostname") - if generator == nil { - t.Fatal("Expected hostname generator, got nil") - } + require.Equal(t, HostnameGenerator{}, generator) definition := shared.Definition{ Image: shared.DefinitionImage{ @@ -31,25 +31,19 @@ func TestHostnameGeneratorRunLXC(t *testing.T) { image := image.NewLXCImage(cacheDir, "", cacheDir, definition) err := os.MkdirAll(filepath.Join(cacheDir, "rootfs", "etc"), 0755) - if err != nil { - t.Fatalf("Unexpected error: %s", err) - } + require.NoError(t, err) createTestFile(t, filepath.Join(cacheDir, "rootfs", "etc", "hostname"), "hostname") err = generator.RunLXC(cacheDir, rootfsDir, image, shared.DefinitionFile{Path: "/etc/hostname"}) - if err != nil { - t.Fatalf("Unexpected error: %s", err) - } + require.NoError(t, err) validateTestFile(t, filepath.Join(cacheDir, "tmp", "etc", "hostname"), "hostname") validateTestFile(t, filepath.Join(cacheDir, "rootfs", "etc", "hostname"), "LXC_NAME\n") err = RestoreFiles(cacheDir, rootfsDir) - if err != nil { - t.Fatalf("Failed to restore files: %s", err) - } + require.NoError(t, err) validateTestFile(t, filepath.Join(cacheDir, "rootfs", "etc", "hostname"), "hostname") } @@ -62,9 +56,7 @@ func TestHostnameGeneratorRunLXD(t *testing.T) { defer teardown(cacheDir) generator := Get("hostname") - if generator == nil { - t.Fatal("Expected hostname generator, got nil") - } + require.Equal(t, HostnameGenerator{}, generator) definition := shared.Definition{ Image: shared.DefinitionImage{ @@ -76,17 +68,13 @@ func TestHostnameGeneratorRunLXD(t *testing.T) { image := image.NewLXDImage(cacheDir, "", cacheDir, definition) err := os.MkdirAll(filepath.Join(cacheDir, "rootfs", "etc"), 0755) - if err != nil { - t.Fatalf("Unexpected error: %s", err) - } + require.NoError(t, err) createTestFile(t, filepath.Join(cacheDir, "rootfs", "etc", "hostname"), "hostname") err = generator.RunLXD(cacheDir, rootfsDir, image, shared.DefinitionFile{Path: "/etc/hostname"}) - if err != nil { - t.Fatalf("Unexpected error: %s", err) - } + require.NoError(t, err) validateTestFile(t, filepath.Join(cacheDir, "templates", "hostname.tpl"), "{{ container.name }}\n") } diff --git a/generators/hosts_test.go b/generators/hosts_test.go index cc4553f..6b38819 100644 --- a/generators/hosts_test.go +++ b/generators/hosts_test.go @@ -5,6 +5,8 @@ import ( "path/filepath" "testing" + "github.com/stretchr/testify/require" + "github.com/lxc/distrobuilder/image" "github.com/lxc/distrobuilder/shared" ) @@ -17,9 +19,7 @@ func TestHostsGeneratorRunLXC(t *testing.T) { defer teardown(cacheDir) generator := Get("hosts") - if generator == nil { - t.Fatal("Expected hosts generator, got nil") - } + require.Equal(t, HostsGenerator{}, generator) definition := shared.Definition{ Image: shared.DefinitionImage{ @@ -31,18 +31,14 @@ func TestHostsGeneratorRunLXC(t *testing.T) { image := image.NewLXCImage(cacheDir, "", cacheDir, definition) err := os.MkdirAll(filepath.Join(cacheDir, "rootfs", "etc"), 0755) - if err != nil { - t.Fatalf("Unexpected error: %s", err) - } + require.NoError(t, err) createTestFile(t, filepath.Join(cacheDir, "rootfs", "etc", "hosts"), "127.0.0.1\tlocalhost\n127.0.0.1\tdistrobuilder\n") err = generator.RunLXC(cacheDir, rootfsDir, image, shared.DefinitionFile{Path: "/etc/hosts"}) - if err != nil { - t.Fatalf("Unexpected error: %s", err) - } + require.NoError(t, err) validateTestFile(t, filepath.Join(cacheDir, "tmp", "etc", "hosts"), "127.0.0.1\tlocalhost\n127.0.0.1\tdistrobuilder\n") @@ -50,9 +46,7 @@ func TestHostsGeneratorRunLXC(t *testing.T) { "127.0.0.1\tlocalhost\n127.0.0.1\tLXC_NAME\n") err = RestoreFiles(cacheDir, rootfsDir) - if err != nil { - t.Fatalf("Failed to restore files: %s", err) - } + require.NoError(t, err) validateTestFile(t, filepath.Join(cacheDir, "rootfs", "etc", "hosts"), "127.0.0.1\tlocalhost\n127.0.0.1\tdistrobuilder\n") @@ -66,9 +60,7 @@ func TestHostsGeneratorRunLXD(t *testing.T) { defer teardown(cacheDir) generator := Get("hosts") - if generator == nil { - t.Fatal("Expected hosts generator, got nil") - } + require.Equal(t, HostsGenerator{}, generator) definition := shared.Definition{ Image: shared.DefinitionImage{ @@ -80,18 +72,14 @@ func TestHostsGeneratorRunLXD(t *testing.T) { image := image.NewLXDImage(cacheDir, "", cacheDir, definition) err := os.MkdirAll(filepath.Join(cacheDir, "rootfs", "etc"), 0755) - if err != nil { - t.Fatalf("Unexpected error: %s", err) - } + require.NoError(t, err) createTestFile(t, filepath.Join(cacheDir, "rootfs", "etc", "hosts"), "127.0.0.1\tlocalhost\n127.0.0.1\tdistrobuilder\n") err = generator.RunLXD(cacheDir, rootfsDir, image, shared.DefinitionFile{Path: "/etc/hosts"}) - if err != nil { - t.Fatalf("Unexpected error: %s", err) - } + require.NoError(t, err) validateTestFile(t, filepath.Join(cacheDir, "templates", "hosts.tpl"), "127.0.0.1\tlocalhost\n127.0.0.1\t{{ container.name }}\n") diff --git a/generators/template_test.go b/generators/template_test.go index b5748e0..da84f9f 100644 --- a/generators/template_test.go +++ b/generators/template_test.go @@ -3,9 +3,10 @@ package generators import ( "os" "path/filepath" - "reflect" "testing" + "github.com/stretchr/testify/require" + "github.com/lxc/distrobuilder/image" "github.com/lxc/distrobuilder/shared" ) @@ -18,9 +19,7 @@ func TestTemplateGeneratorRunLXD(t *testing.T) { defer teardown(cacheDir) generator := Get("template") - if generator == nil { - t.Fatal("Expected template generator, got nil") - } + require.Equal(t, TemplateGenerator{}, generator) definition := shared.Definition{ Image: shared.DefinitionImage{ @@ -32,9 +31,7 @@ func TestTemplateGeneratorRunLXD(t *testing.T) { image := image.NewLXDImage(cacheDir, "", cacheDir, definition) err := os.MkdirAll(filepath.Join(cacheDir, "rootfs", "root"), 0755) - if err != nil { - t.Fatalf("Unexpected error: %s", err) - } + require.NoError(t, err) createTestFile(t, filepath.Join(cacheDir, "rootfs", "root", "template"), "--test--") @@ -44,9 +41,7 @@ func TestTemplateGeneratorRunLXD(t *testing.T) { Content: "==test==", Path: "/root/template", }) - if err != nil { - t.Fatalf("Unexpected error: %s", err) - } + require.NoError(t, err) validateTestFile(t, filepath.Join(cacheDir, "templates", "template.tpl"), "==test==\n") validateTestFile(t, filepath.Join(cacheDir, "rootfs", "root", "template"), "--test--") @@ -60,9 +55,7 @@ func TestTemplateGeneratorRunLXDDefaultWhen(t *testing.T) { defer teardown(cacheDir) generator := Get("template") - if generator == nil { - t.Fatal("Expected template generator, got nil") - } + require.Equal(t, TemplateGenerator{}, generator) definition := shared.Definition{ Image: shared.DefinitionImage{ @@ -79,9 +72,8 @@ func TestTemplateGeneratorRunLXDDefaultWhen(t *testing.T) { Content: "==test==", Path: "test-default-when", }) - if err != nil { - t.Fatalf("Unexpected error: %s", err) - } + require.NoError(t, err) + err = generator.RunLXD(cacheDir, rootfsDir, image, shared.DefinitionFile{ Generator: "template", Name: "test-when", @@ -91,16 +83,11 @@ func TestTemplateGeneratorRunLXDDefaultWhen(t *testing.T) { When: []string{"create"}, }, }) - if err != nil { - t.Fatalf("Unexpected error: %s", err) - } + require.NoError(t, err) testvalue := []string{"create", "copy"} - if reflect.DeepEqual(image.Metadata.Templates["test-default-when"].When, testvalue) == false { - t.Fatalf("When default value not correct [%v] != [%v]", image.Metadata.Templates["test-default-when"].When, testvalue) - } + require.Equal(t, image.Metadata.Templates["test-default-when"].When, testvalue) + testvalue = []string{"create"} - if reflect.DeepEqual(image.Metadata.Templates["test-when"].When, testvalue) == false { - t.Fatalf("When value not correct [%v] != [%v]", image.Metadata.Templates["test-when"].When, testvalue) - } + require.Equal(t, image.Metadata.Templates["test-when"].When, testvalue) } diff --git a/image/lxc_test.go b/image/lxc_test.go index b72eca2..ad8885c 100644 --- a/image/lxc_test.go +++ b/image/lxc_test.go @@ -7,12 +7,12 @@ import ( "log" "os" "path/filepath" - "reflect" - "regexp" "strings" "syscall" "testing" + "github.com/stretchr/testify/require" + "github.com/lxc/distrobuilder/shared" ) @@ -96,14 +96,8 @@ func TestNewLXCImage(t *testing.T) { image := NewLXCImage(lxcCacheDir(), "", lxcCacheDir(), lxcDef) defer teardownLXC() - if image.cacheDir != lxcCacheDir() { - t.Fatalf("Expected image.cacheDir to be '%s', got '%s'", lxcCacheDir(), - image.cacheDir) - } - - if !reflect.DeepEqual(image.definition, lxcDef) { - t.Fatalf("lxcImageDef and image.definition are not equal") - } + require.Equal(t, lxcCacheDir(), image.cacheDir) + require.Equal(t, lxcDef, image.definition) } func TestLXCAddTemplate(t *testing.T) { @@ -111,44 +105,33 @@ func TestLXCAddTemplate(t *testing.T) { defer teardownLXC() // Make sure templates file is empty. - info, err := os.Stat(filepath.Join(lxcCacheDir(), "metadata", "templates")) - if err == nil && info.Size() > 0 { - t.Fatalf("Expected file size to be 0, got %d", info.Size()) - } + _, err := os.Stat(filepath.Join(lxcCacheDir(), "metadata", "templates")) + require.EqualError(t, err, fmt.Sprintf("stat %s: no such file or directory", + filepath.Join(lxcCacheDir(), "metadata", "templates"))) // Add first template entry. image.AddTemplate("/path/file1") file, err := os.Open(filepath.Join(lxcCacheDir(), "metadata", "templates")) - if err != nil { - t.Fatalf("Unexpected error: %s", err) - } + require.NoError(t, err) // Copy file content to buffer. var buffer bytes.Buffer io.Copy(&buffer, file) file.Close() - if buffer.String() != "/path/file1\n" { - t.Fatalf("Expected templates content to be '%s', got '%s'", - "/path/file", buffer.String()) - } + require.Equal(t, "/path/file1\n", buffer.String()) // Add second template entry. image.AddTemplate("/path/file2") file, err = os.Open(filepath.Join(lxcCacheDir(), "metadata", "templates")) - if err != nil { - t.Fatalf("Unexpected error: %s", err) - } + require.NoError(t, err) // Copy file content to buffer. buffer.Reset() io.Copy(&buffer, file) file.Close() - if buffer.String() != "/path/file1\n/path/file2\n" { - t.Fatalf("Expected templates content to be '%s', got '%s'", - "/path/file1\n/path/file2", buffer.String()) - } + require.Equal(t, "/path/file1\n/path/file2\n", buffer.String()) } func TestLXCBuild(t *testing.T) { @@ -156,14 +139,10 @@ func TestLXCBuild(t *testing.T) { defer teardownLXC() err := os.MkdirAll(filepath.Join(lxcCacheDir(), "rootfs"), 0755) - if err != nil { - t.Fatalf("Unexpected error: %s", err) - } + require.NoError(t, err) err = image.Build() - if err != nil { - t.Fatalf("Unexpected error: %s", err) - } + require.NoError(t, err) defer func() { os.Remove("meta.tar.xz") os.Remove("rootfs.tar.xz") @@ -229,40 +208,23 @@ func TestLXCCreateMetadataBasic(t *testing.T) { image := tt.prepareImage(*defaultImage) err := image.createMetadata() if tt.shouldFail { - if err == nil { - t.Fatalf("Expected to fail, but didn't: %s", tt.name) - } - - match, _ := regexp.MatchString(tt.expectedError, err.Error()) - if !match { - t.Fatalf("Expected to fail with '%s', got '%s'", tt.expectedError, - err.Error()) - } - } - if !tt.shouldFail && err != nil { - t.Fatalf("Unexpected error: %s", err) + require.Regexp(t, tt.expectedError, err) + } else { + require.NoError(t, err) } } // Verify create-message template f, err := os.Open(filepath.Join(lxcCacheDir(), "metadata", "create-message")) - if err != nil { - t.Fatalf("Unexpected error: %s", err) - } + require.NoError(t, err) defer f.Close() var buf bytes.Buffer _, err = io.Copy(&buf, f) - if err != nil { - t.Fatalf("Unexpected error: %s", err) - } - - expected := fmt.Sprintf("Welcome to %s %s\n", - strings.Title(lxcDef.Image.Distribution), lxcDef.Image.Release) - if buf.String() != expected { - t.Fatalf("create-message: Expected '%s', got '%s'", expected, - buf.String()) - } + require.NoError(t, err) + require.Equal(t, fmt.Sprintf("Welcome to %s %s\n", + strings.Title(lxcDef.Image.Distribution), lxcDef.Image.Release), + buf.String()) } func TestLXCCreateMetadataConfig(t *testing.T) { @@ -316,27 +278,18 @@ func TestLXCCreateMetadataConfig(t *testing.T) { } err := image.createMetadata() - if err != nil { - t.Fatalf("Unexpected error: %s", err) - } + require.NoError(t, err) for _, tt := range tests { log.Printf("Checking '%s'", tt.configFile) file, err := os.Open(filepath.Join(lxcCacheDir(), "metadata", tt.configFile)) - if err != nil { - t.Fatalf("Unexpected error: %s", err) - } + require.NoError(t, err) var buffer bytes.Buffer _, err = io.Copy(&buffer, file) file.Close() - if err != nil { - t.Fatalf("Unexpected error: %s", err) - } - - if buffer.String() != tt.expected { - t.Fatalf("Expected '%s', got '%s'", tt.expected, buffer.String()) - } + require.NoError(t, err) + require.Equal(t, tt.expected, buffer.String()) } } @@ -348,28 +301,20 @@ func TestLXCPackMetadata(t *testing.T) { }() err := image.createMetadata() - if err != nil { - t.Fatalf("Unexpected error: %s", err) - } + require.NoError(t, err) err = image.packMetadata() - if err != nil { - t.Fatalf("Unexpected error: %s", err) - } + require.NoError(t, err) // Include templates directory. image.AddTemplate("/path/file") err = image.packMetadata() - if err != nil { - t.Fatalf("Unexpected error: %s", err) - } + require.NoError(t, err) // Provoke error by removing the metadata directory os.RemoveAll(filepath.Join(lxcCacheDir(), "metadata")) err = image.packMetadata() - if err == nil { - t.Fatal("Expected failure") - } + require.Error(t, err) } @@ -379,14 +324,10 @@ func TestLXCWriteMetadata(t *testing.T) { // Should fail due to invalid path err := image.writeMetadata("/path/file", "", false) - if err == nil { - t.Fatal("Expected failure") - } + require.Error(t, err) // Should succeed err = image.writeMetadata("test", "metadata", false) - if err != nil { - t.Fatalf("Unexpected failure: %s", err) - } + require.NoError(t, err) os.Remove("test") } diff --git a/image/lxd_test.go b/image/lxd_test.go index f6d03da..d9efcd1 100644 --- a/image/lxd_test.go +++ b/image/lxd_test.go @@ -5,11 +5,10 @@ import ( "log" "os" "path/filepath" - "reflect" "strings" "testing" - lxd "github.com/lxc/lxd/shared" + "github.com/stretchr/testify/require" "github.com/lxc/distrobuilder/shared" ) @@ -36,36 +35,30 @@ func setupLXD(t *testing.T) *LXDImage { cacheDir := filepath.Join(os.TempDir(), "distrobuilder-test") err := os.MkdirAll(filepath.Join(cacheDir, "rootfs"), 0755) - if err != nil { - t.Fatalf("Failed to create rootfs directory: %s", err) - } + require.NoError(t, err) err = os.MkdirAll(filepath.Join(cacheDir, "templates"), 0755) - if err != nil { - t.Fatalf("Failed to create templates directory: %s", err) - } + require.NoError(t, err) image := NewLXDImage(cacheDir, "", cacheDir, lxdDef) - // Check cache directory - if image.cacheDir != cacheDir { - teardownLXD(t) - t.Fatalf("Expected cacheDir to be '%s', is '%s'", cacheDir, image.cacheDir) - } + fail := true + defer func() { + if fail { + teardownLXD(t) + } + }() - if !reflect.DeepEqual(lxdDef, image.definition) { - teardownLXD(t) - t.Fatal("lxdDef and image.definition are not equal") - } + // Check cache directory + require.Equal(t, cacheDir, image.cacheDir) + require.Equal(t, lxdDef, image.definition) lxdDef.SetDefaults() err = lxdDef.Validate() - if err != nil { - teardownLXD(t) - t.Fatalf("Failed to validate image: %s", err) - } + require.NoError(t, err) + fail = false return image } @@ -84,46 +77,31 @@ func TestLXDBuild(t *testing.T) { func testLXDBuildSplitImage(t *testing.T, image *LXDImage) { // Create split tarball and squashfs. err := image.Build(false, "xz") - if err != nil { - t.Fatalf("Unexpected error: %s", err) - } + require.NoError(t, err) defer func() { os.Remove("lxd.tar.xz") os.Remove("rootfs.squashfs") }() - if !lxd.PathExists("lxd.tar.xz") { - t.Fatalf("File '%s' does not exist", "lxd.tar.xz") - } - - if !lxd.PathExists("rootfs.squashfs") { - t.Fatalf("File '%s' does not exist", "rootfs.squashfs") - } + require.FileExists(t, "lxd.tar.xz") + require.FileExists(t, "rootfs.squashfs") } func testLXDBuildUnifiedImage(t *testing.T, image *LXDImage) { // Create unified tarball with custom name. err := image.Build(true, "xz") - if err != nil { - t.Fatalf("Unexpected error: %s", err) - } + require.NoError(t, err) defer os.Remove("ubuntu-17.10-x86_64-testing.tar.xz") - if !lxd.PathExists("ubuntu-17.10-x86_64-testing.tar.xz") { - t.Fatalf("File '%s' does not exist", "ubuntu-17.10-x86_64-testing.tar.xz") - } + require.FileExists(t, "ubuntu-17.10-x86_64-testing.tar.xz") // Create unified tarball with default name. image.definition.Image.Name = "" err = image.Build(true, "xz") - if err != nil { - t.Fatalf("Unexpected error: %s", err) - } + require.NoError(t, err) defer os.Remove("lxd.tar.xz") - if !lxd.PathExists("lxd.tar.xz") { - t.Fatalf("File '%s' does not exist", "lxd.tar.xz") - } + require.FileExists(t, "lxd.tar.xz") } func TestLXDCreateMetadata(t *testing.T) { @@ -131,9 +109,7 @@ func TestLXDCreateMetadata(t *testing.T) { defer teardownLXD(t) err := image.createMetadata() - if err != nil { - t.Fatalf("Unexpected error: %s", err) - } + require.NoError(t, err) tests := []struct { name string @@ -176,8 +152,6 @@ func TestLXDCreateMetadata(t *testing.T) { for i, tt := range tests { log.Printf("Running test #%d: %s", i, tt.name) - if tt.have != tt.expected { - t.Fatalf("Expected '%s', got '%s'", tt.expected, tt.have) - } + require.Equal(t, tt.expected, tt.have) } } diff --git a/shared/definition_test.go b/shared/definition_test.go index e078a5a..36957eb 100644 --- a/shared/definition_test.go +++ b/shared/definition_test.go @@ -2,10 +2,10 @@ package shared import ( "log" - "regexp" "testing" "github.com/lxc/lxd/shared" + "github.com/stretchr/testify/require" ) func TestSetDefinitionDefaults(t *testing.T) { @@ -15,13 +15,8 @@ func TestSetDefinitionDefaults(t *testing.T) { uname, _ := shared.Uname() - if def.Image.Architecture != uname.Machine { - t.Fatalf("Expected image.arch to be '%s', got '%s'", uname.Machine, def.Image.Architecture) - } - - if def.Image.Expiry != "30d" { - t.Fatalf("Expected image.expiry to be '%s', got '%s'", "30d", def.Image.Expiry) - } + require.Equal(t, uname.Machine, def.Image.Architecture) + require.Equal(t, "30d", def.Image.Expiry) } func TestValidateDefinition(t *testing.T) { @@ -213,16 +208,10 @@ func TestValidateDefinition(t *testing.T) { log.Printf("Running test #%d: %s", i, tt.name) tt.definition.SetDefaults() err := tt.definition.Validate() - if !tt.shouldFail && err != nil { - t.Fatalf("Validation failed: %s", err) - } else if tt.shouldFail { - if err == nil { - t.Fatal("Expected failure") - } - match, _ := regexp.MatchString(tt.expected, err.Error()) - if !match { - t.Fatalf("Validation failed: Expected '%s', got '%s'", tt.expected, err.Error()) - } + if tt.shouldFail { + require.Regexp(t, tt.expected, err) + } else { + require.NoError(t, err) } } } @@ -255,38 +244,22 @@ func TestDefinitionSetValue(t *testing.T) { } err := d.SetValue("image.release", "bionic") - if err != nil { - t.Fatalf("Unexpected error: %s", err) - } - if d.Image.Release != "bionic" { - t.Fatalf("Expected '%s', got '%s'", "bionic", d.Image.Release) - } + require.NoError(t, err) + require.Equal(t, "bionic", d.Image.Release) err = d.SetValue("actions.0.trigger", "post-files") - if err != nil { - t.Fatalf("Unexpected error: %s", err) - } - if d.Actions[0].Trigger != "post-files" { - t.Fatalf("Expected '%s', got '%s'", "post-files", d.Actions[0].Trigger) - } + require.NoError(t, err) + require.Equal(t, "post-files", d.Actions[0].Trigger) // Index out of bounds err = d.SetValue("actions.3.trigger", "post-files") - if err == nil || err.Error() != "Index out of range" { - t.Fatal("Expected index out of range") - } + require.EqualError(t, err, "Index out of range") // Nonsense err = d.SetValue("image", "[foo: bar]") - if err == nil || err.Error() != "Unsupported type 'struct'" { - t.Fatal("Expected unsupported assignment") - } + require.EqualError(t, err, "Unsupported type 'struct'") err = d.SetValue("source.ignore_release", "true") - if err != nil { - t.Fatalf("Unexpected error: %s", err) - } - if !d.Source.IgnoreRelease { - t.Fatalf("Expected '%v', got '%v'", true, d.Source.IgnoreRelease) - } + require.NoError(t, err) + require.Equal(t, true, d.Source.IgnoreRelease) } diff --git a/shared/osarch_test.go b/shared/osarch_test.go index b946a6d..4068033 100644 --- a/shared/osarch_test.go +++ b/shared/osarch_test.go @@ -3,6 +3,8 @@ package shared import ( "log" "testing" + + "github.com/stretchr/testify/require" ) func TestGetArch(t *testing.T) { @@ -41,21 +43,13 @@ func TestGetArch(t *testing.T) { for i, tt := range tests { log.Printf("Running test #%d: %s %s", i, tt.distro, tt.arch) arch, err := GetArch(tt.distro, tt.arch) - if err != nil { - t.Fatalf("Unexpected error: %s", err) - } - if arch != tt.expected { - t.Fatalf("Wrong arch: Expected '%s', got '%s'", tt.expected, arch) - } + require.NoError(t, err) + require.Equal(t, tt.expected, arch) } _, err := GetArch("distro", "") - if err == nil || err.Error() != "Architecture map isn't supported: distro" { - t.Fatalf("Expected unsupported architecture map, got '%s'", err) - } + require.EqualError(t, err, "Architecture map isn't supported: distro") _, err = GetArch("debian", "arch") - if err == nil || err.Error() != "Architecture isn't supported: arch" { - t.Fatalf("Expected unsupported architecture, got '%s'", err) - } + require.EqualError(t, err, "Architecture isn't supported: arch") } diff --git a/shared/util_test.go b/shared/util_test.go index 187adcb..360be5e 100644 --- a/shared/util_test.go +++ b/shared/util_test.go @@ -8,6 +8,7 @@ import ( "testing" lxd "github.com/lxc/lxd/shared" + "github.com/stretchr/testify/require" "gopkg.in/flosch/pongo2.v3" ) @@ -83,36 +84,29 @@ func TestVerifyFile(t *testing.T) { log.Printf("Running test #%d: %s", i, tt.name) valid, err := VerifyFile(tt.signedFile, tt.signatureFile, tt.keys, tt.keyserver) - if !tt.shouldFail && !valid { - t.Fatalf("Failed to verify: %s\n%s", tt.name, err) - } - if tt.shouldFail && valid { - t.Fatalf("Expected to fail: %s", tt.name) + if tt.shouldFail { + require.Error(t, err) + require.False(t, valid) + } else { + require.NoError(t, err) + require.True(t, valid) } } } func TestCreateGPGKeyring(t *testing.T) { keyring, err := CreateGPGKeyring("keyserver.ubuntu.com", []string{"0x5DE8949A899C8D99"}) - if err != nil { - t.Fatalf("Unexpected error: %s", err) - } + require.NoError(t, err) - if !lxd.PathExists(keyring) { - t.Fatalf("Failed to create GPG keyring '%s'", keyring) - } + require.FileExists(t, keyring) os.RemoveAll(path.Dir(keyring)) // This shouldn't fail, but the keyring file should not be created since // there are no keys to be exported. keyring, err = CreateGPGKeyring("", []string{}) - if err != nil { - t.Fatalf("Unexpected error: %s", err) - } + require.NoError(t, err) - if lxd.PathExists(keyring) { - t.Fatalf("GPG keyring '%s' should not exist", keyring) - } + require.False(t, lxd.PathExists(keyring), "File should not exist") os.RemoveAll(path.Dir(keyring)) } @@ -175,11 +169,11 @@ func TestRenderTemplate(t *testing.T) { for i, tt := range tests { log.Printf("Running test #%d: %s", i, tt.name) ret, err := RenderTemplate(tt.template, tt.iface) - if tt.shouldFail && err == nil { - t.Fatal("test should have failed") - } - if ret != tt.expected { - t.Fatalf("expected '%s', got '%s'", tt.expected, ret) + if tt.shouldFail { + require.Error(t, err) + } else { + require.NoError(t, err) + require.Equal(t, tt.expected, ret) } } } @@ -198,21 +192,17 @@ func TestSetEnvVariables(t *testing.T) { for _, e := range env { v, set := os.LookupEnv(e.Key) - if !set || e.Value != v { - t.Fatalf("Expected %s to be '%s', got '%s'", e.Key, e.Value, v) - } + require.True(t, set) + require.Equal(t, e.Value, v) } // Reset env variables SetEnvVariables(oldEnv) val, set := os.LookupEnv("FOO") - if !set || val != "bar" { - t.Fatalf("Expected %s to be '%s', got '%s'", "FOO", "bar", val) - } + require.True(t, set) + require.Equal(t, val, "bar") val, set = os.LookupEnv("BAR") - if set { - t.Fatalf("Expected %s to be unset", "BAR") - } + require.False(t, set, "Expected 'BAR' to be unset") }