github.com/apptainer/singularity@v3.1.1+incompatible/pkg/image/unpacker/squashfs_test.go (about) 1 // Copyright (c) 2019, Sylabs Inc. All rights reserved. 2 // This software is licensed under a 3-clause BSD license. Please consult the 3 // LICENSE.md file distributed with the sources of this project regarding your 4 // rights to use or distribute this software. 5 6 package unpacker 7 8 import ( 9 "bufio" 10 "io/ioutil" 11 "os" 12 "os/exec" 13 "path/filepath" 14 "testing" 15 ) 16 17 func createArchive(t *testing.T) *os.File { 18 mk, err := exec.LookPath("mksquashfs") 19 if err != nil { 20 t.SkipNow() 21 } 22 f, err := ioutil.TempFile("", "archive-") 23 if err != nil { 24 t.Fatal(err) 25 } 26 cmd := exec.Command(mk, ".", f.Name(), "-noappend", "-no-progress") 27 if err := cmd.Run(); err != nil { 28 t.Fatal(err) 29 } 30 return f 31 } 32 33 func isExist(path string) bool { 34 _, err := os.Stat(path) 35 return !os.IsNotExist(err) 36 } 37 38 func TestSquashfs(t *testing.T) { 39 s := NewSquashfs() 40 41 if !s.HasUnsquashfs() { 42 t.SkipNow() 43 } 44 45 dir, err := ioutil.TempDir("", "unpacker-") 46 if err != nil { 47 t.Fatal(err) 48 } 49 defer os.RemoveAll(dir) 50 51 // create archive with files present in this directory 52 archive := createArchive(t) 53 defer os.Remove(archive.Name()) 54 55 savedPath := s.UnsquashfsPath 56 57 // test with an empty unsquashfs path 58 s.UnsquashfsPath = "" 59 if err := s.ExtractAll(archive, dir); err == nil { 60 t.Errorf("unexpected success with empty unsquashfs path") 61 } 62 // test with a bad unsquashfs path 63 s.UnsquashfsPath = "/unsquashfs-no-exists" 64 if err := s.ExtractAll(archive, dir); err == nil { 65 t.Errorf("unexpected success with bad unsquashfs path") 66 } 67 68 s.UnsquashfsPath = savedPath 69 70 // extract all into temporary folder 71 if err := s.ExtractAll(archive, dir); err != nil { 72 t.Error(err) 73 } 74 75 // check if squashfs.go was extracted 76 path := filepath.Join(dir, "squashfs.go") 77 if !isExist(path) { 78 t.Errorf("extraction failed, %s is missing", path) 79 } 80 os.Remove(path) 81 82 // check if squashfs_test.go was extracted 83 path = filepath.Join(dir, "squashfs_test.go") 84 if !isExist(path) { 85 t.Errorf("extraction failed, %s is missing", path) 86 } 87 os.Remove(path) 88 89 // test with an empty file list 90 if err := s.ExtractFiles([]string{}, archive, dir); err == nil { 91 t.Errorf("unexpected success with empty file list") 92 } 93 94 // extract squashfs_test.go only 95 if err := s.ExtractFiles([]string{"squashfs_test.go"}, bufio.NewReader(archive), dir); err != nil { 96 t.Error(err) 97 } 98 // check that squashfs.go was not extracted 99 path = filepath.Join(dir, "squashfs.go") 100 if isExist(path) { 101 t.Errorf("file extraction failed, %s is present", path) 102 } 103 // check that squashfs_test.go was extracted 104 path = filepath.Join(dir, "squashfs_test.go") 105 if !isExist(path) { 106 t.Errorf("file extraction failed, %s is missing", path) 107 } 108 }