github.com/Mirantis/virtlet@v1.5.2-0.20191204181327-1659b8a48e9b/pkg/diskimage/diskimage_test.go (about) 1 /* 2 Copyright 2019 Mirantis 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package diskimage 18 19 import ( 20 "io/ioutil" 21 "os" 22 "os/exec" 23 "path/filepath" 24 "runtime" 25 "sort" 26 "strings" 27 "testing" 28 ) 29 30 func verifyFiles(t *testing.T, imagePath, dir string, expectedFiles ...string) { 31 sort.Strings(expectedFiles) 32 exp := strings.Join(expectedFiles, "\n") 33 files, err := ListFiles(imagePath, dir) 34 if err != nil { 35 t.Fatalf("ListFiles(): %v", err) 36 } 37 actual := strings.Join(files, "\n") 38 if exp != actual { 39 t.Errorf("bad file list: expected:\n%s\n-- got --\n%s", exp, actual) 40 } 41 } 42 43 func verifyContent(t *testing.T, imagePath, filePath, exp string) { 44 actual, err := Cat(imagePath, filePath) 45 if err != nil { 46 t.Fatalf("ListFiles(): %v", err) 47 } 48 if exp != actual { 49 t.Errorf("bad file content for %q: expected:\n%s\n-- got --\n%s", filePath, exp, actual) 50 } 51 } 52 53 func TestDiskImage(t *testing.T) { 54 if runtime.GOOS != "linux" { 55 t.Skip("libguestfs is only supported on Linux") 56 } 57 58 tmpDir, err := ioutil.TempDir("", "diskimage") 59 if err != nil { 60 t.Fatalf("TempDir(): %v", err) 61 } 62 defer os.RemoveAll(tmpDir) 63 64 imagePath := filepath.Join(tmpDir, "image.qcow2") 65 if out, err := exec.Command("qemu-img", "create", "-f", "qcow2", imagePath, "10M").CombinedOutput(); err != nil { 66 t.Fatalf("qemu-img create: %q: %v\noutput:\n%v", imagePath, err, out) 67 } 68 69 if err := FormatDisk(imagePath); err != nil { 70 t.Fatalf("FormatDisk(): %v", err) 71 } 72 73 verifyFiles(t, imagePath, "/", "lost+found") 74 75 if err := Put(imagePath, map[string][]byte{ 76 "/foo/bar.txt": []byte("foobar"), 77 "/foo/baz.txt": []byte("baz"), 78 }); err != nil { 79 t.Fatalf("Put(): %v", err) 80 } 81 82 verifyFiles(t, imagePath, "/", "foo", "lost+found") 83 verifyFiles(t, imagePath, "/foo", "bar.txt", "baz.txt") 84 verifyContent(t, imagePath, "/foo/bar.txt", "foobar") 85 verifyContent(t, imagePath, "/foo/baz.txt", "baz") 86 87 if _, err := Cat(imagePath, "/nosuchfile"); err == nil { 88 t.Errorf("didn't get the expected error") 89 } else if !strings.Contains(err.Error(), "No such file or directory") { 90 t.Errorf("bad error message: %q", err.Error()) 91 } 92 }