github.com/u-root/u-root@v7.0.1-0.20200915234505-ad7babab0a8e+incompatible/pkg/cp/cp_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 cp_test
     6  
     7  import (
     8  	"io/ioutil"
     9  	"os"
    10  	"path/filepath"
    11  	"testing"
    12  
    13  	"github.com/u-root/u-root/pkg/cp"
    14  	"github.com/u-root/u-root/pkg/cp/cmp"
    15  )
    16  
    17  func copyAndTest(t *testing.T, o cp.Options, src, dst string) {
    18  	if err := o.Copy(src, dst); err != nil {
    19  		t.Fatalf("Copy(%q -> %q) = %v, want %v", src, dst, err, nil)
    20  	}
    21  	if err := cmp.IsEqualTree(o, src, dst); err != nil {
    22  		t.Fatalf("Expected %q and %q to be same, got %v", src, dst, err)
    23  	}
    24  }
    25  
    26  func TestSimpleCopy(t *testing.T) {
    27  	tmpDir, err := ioutil.TempDir("", "u-root-pkg-cp-")
    28  	if err != nil {
    29  		t.Fatal(err)
    30  	}
    31  	defer os.RemoveAll(tmpDir)
    32  
    33  	// Copy a directory.
    34  	origd := filepath.Join(tmpDir, "directory")
    35  	if err := os.Mkdir(origd, 0744); err != nil {
    36  		t.Fatal(err)
    37  	}
    38  
    39  	copyAndTest(t, cp.Default, origd, filepath.Join(tmpDir, "directory-copied"))
    40  	copyAndTest(t, cp.NoFollowSymlinks, origd, filepath.Join(tmpDir, "directory-copied-2"))
    41  
    42  	// Copy a file.
    43  	origf := filepath.Join(tmpDir, "normal-file")
    44  	if err := ioutil.WriteFile(origf, []byte("F is for fire that burns down the whole town"), 0766); err != nil {
    45  		t.Fatal(err)
    46  	}
    47  
    48  	copyAndTest(t, cp.Default, origf, filepath.Join(tmpDir, "normal-file-copied"))
    49  	copyAndTest(t, cp.NoFollowSymlinks, origf, filepath.Join(tmpDir, "normal-file-copied-2"))
    50  
    51  	// Copy a symlink.
    52  	origs := filepath.Join(tmpDir, "foobar")
    53  	// foobar -> normal-file
    54  	if err := os.Symlink(origf, origs); err != nil {
    55  		t.Fatal(err)
    56  	}
    57  
    58  	copyAndTest(t, cp.Default, origf, filepath.Join(tmpDir, "foobar-copied"))
    59  	copyAndTest(t, cp.NoFollowSymlinks, origf, filepath.Join(tmpDir, "foobar-copied-just-symlink"))
    60  }