github.com/xyproto/u-root@v6.0.1-0.20200302025726-5528e0c77a3c+incompatible/pkg/loop/losetup_linux_test.go (about)

     1  // Copyright 2019 the u-root Authors. All rights reserved
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package loop
     6  
     7  import (
     8  	"io/ioutil"
     9  	"os"
    10  	"path/filepath"
    11  	"syscall"
    12  	"testing"
    13  
    14  	"github.com/u-root/u-root/pkg/cp"
    15  	"github.com/u-root/u-root/pkg/mount"
    16  	"golang.org/x/sys/unix"
    17  )
    18  
    19  const (
    20  	_LOOP_MAJOR = 7
    21  )
    22  
    23  func skipIfNotRoot(t *testing.T) {
    24  	if os.Getuid() != 0 {
    25  		t.Skipf("Skipping test since we are not root")
    26  	}
    27  }
    28  
    29  func TestFindDevice(t *testing.T) {
    30  	skipIfNotRoot(t)
    31  
    32  	loopdev, err := FindDevice()
    33  	if err != nil {
    34  		t.Fatalf("Failed to find loop device: %v", err)
    35  	}
    36  
    37  	s, err := os.Stat(loopdev)
    38  	if err != nil {
    39  		t.Fatalf("Could not stat loop device: %v", err)
    40  	}
    41  
    42  	st := s.Sys().(*syscall.Stat_t)
    43  	if m := unix.Major(st.Rdev); m != _LOOP_MAJOR {
    44  		t.Fatalf("Device %s is not a loop device: got major no %d, want %d", loopdev, m, _LOOP_MAJOR)
    45  	}
    46  }
    47  
    48  func TestSetFile(t *testing.T) {
    49  	skipIfNotRoot(t)
    50  
    51  	tmpDir, err := ioutil.TempDir("", "u-root-losetup-")
    52  	if err != nil {
    53  		t.Fatal(err)
    54  	}
    55  	testdisk := filepath.Join(tmpDir, "testdisk")
    56  	if err := cp.Copy("./testdata/pristine-vfat-disk", testdisk); err != nil {
    57  		t.Fatal(err)
    58  	}
    59  
    60  	loopdev, err := FindDevice()
    61  	if err != nil {
    62  		t.Fatalf("Failed to find loop device: %v", err)
    63  	}
    64  
    65  	if err := SetFile(loopdev, testdisk); err != nil {
    66  		t.Fatalf("Failed to associate disk: %v", err)
    67  	}
    68  
    69  	if err := os.MkdirAll("/tmp/disk", 0755); err != nil && !os.IsExist(err) {
    70  		t.Fatalf("Could not create /tmp/disk: %v", err)
    71  	}
    72  
    73  	mp, err := mount.Mount(loopdev, "/tmp/disk", "vfat", "", 0)
    74  	if err != nil {
    75  		t.Fatalf("Failed to mount /tmp/disk: %v", err)
    76  	}
    77  	defer mp.Unmount(0) //nolint:errcheck
    78  
    79  	if err := ioutil.WriteFile("/tmp/disk/foobar", []byte("Are you feeling it now Mr Krabs"), 0755); err != nil {
    80  		t.Fatal(err)
    81  	}
    82  }