gitee.com/mirrors_u-root/u-root@v7.0.0+incompatible/pkg/mount/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  	"golang.org/x/sys/unix"
    16  )
    17  
    18  const (
    19  	_LOOP_MAJOR = 7
    20  )
    21  
    22  func skipIfNotRoot(t *testing.T) {
    23  	if os.Getuid() != 0 {
    24  		t.Skipf("Skipping test since we are not root")
    25  	}
    26  }
    27  
    28  func TestFindDevice(t *testing.T) {
    29  	skipIfNotRoot(t)
    30  
    31  	loopdev, err := FindDevice()
    32  	if err != nil {
    33  		t.Fatalf("Failed to find loop device: %v", err)
    34  	}
    35  
    36  	s, err := os.Stat(loopdev)
    37  	if err != nil {
    38  		t.Fatalf("Could not stat loop device: %v", err)
    39  	}
    40  
    41  	st := s.Sys().(*syscall.Stat_t)
    42  	if m := unix.Major(st.Rdev); m != _LOOP_MAJOR {
    43  		t.Fatalf("Device %s is not a loop device: got major no %d, want %d", loopdev, m, _LOOP_MAJOR)
    44  	}
    45  }
    46  
    47  func TestSetFile(t *testing.T) {
    48  	skipIfNotRoot(t)
    49  
    50  	tmpDir, err := ioutil.TempDir("", "u-root-losetup-")
    51  	if err != nil {
    52  		t.Fatal(err)
    53  	}
    54  	testdisk := filepath.Join(tmpDir, "testdisk")
    55  	if err := cp.Copy("./testdata/pristine-vfat-disk", testdisk); err != nil {
    56  		t.Fatal(err)
    57  	}
    58  
    59  	loopdev, err := New(testdisk, "vfat", "")
    60  	if err != nil {
    61  		t.Fatal(err)
    62  	}
    63  
    64  	if err := os.MkdirAll("/tmp/disk", 0755); err != nil && !os.IsExist(err) {
    65  		t.Fatalf("Could not create /tmp/disk: %v", err)
    66  	}
    67  
    68  	mp, err := loopdev.Mount("/tmp/disk", 0)
    69  	if err != nil {
    70  		t.Fatalf("Failed to mount /tmp/disk: %v", err)
    71  	}
    72  	defer mp.Unmount(0) //nolint:errcheck
    73  
    74  	if err := ioutil.WriteFile("/tmp/disk/foobar", []byte("Are you feeling it now Mr Krabs"), 0755); err != nil {
    75  		t.Fatal(err)
    76  	}
    77  }