github.com/grailbio/bigslice@v0.0.0-20230519005545-30c4c12152ad/internal/walker/walker_test.go (about)

     1  // Copyright 2017 GRAIL, Inc. All rights reserved.
     2  // Use of this source code is governed by the Apache 2.0
     3  // license that can be found in the LICENSE file.
     4  
     5  package walker
     6  
     7  import (
     8  	"os"
     9  	"path/filepath"
    10  	"reflect"
    11  	"sort"
    12  	"testing"
    13  
    14  	"github.com/grailbio/testutil"
    15  )
    16  
    17  func TestWalker(t *testing.T) {
    18  	dir, cleanup := testutil.TempDir(t, "", "")
    19  	defer cleanup()
    20  	testutil.CreateDirectoryTree(t, dir, 2, 2, 10)
    21  	dirlist, filelist := testutil.ListRecursively(t, dir)
    22  	dirs := map[string]bool{}
    23  	for _, dir := range dirlist {
    24  		dirs[dir] = true
    25  	}
    26  	files := map[string]bool{}
    27  	for _, file := range filelist {
    28  		files[file] = true
    29  	}
    30  	var w Walker
    31  	w.Init(dir)
    32  	for w.Scan() {
    33  		if w.Info().IsDir() {
    34  			if !dirs[w.Path()] {
    35  				t.Fatalf("unexpected directory %q", w.Path())
    36  			}
    37  			delete(dirs, w.Path())
    38  		} else {
    39  			if !files[w.Path()] {
    40  				t.Fatalf("unexpected file %q", w.Path())
    41  			}
    42  			delete(files, w.Path())
    43  		}
    44  	}
    45  	if err := w.Err(); err != nil {
    46  		t.Fatal(err)
    47  	}
    48  	if got, want := dirs, map[string]bool{}; !reflect.DeepEqual(got, want) {
    49  		t.Fatalf("got %v, want %v", got, want)
    50  	}
    51  	if got, want := files, map[string]bool{}; !reflect.DeepEqual(got, want) {
    52  		t.Fatalf("got %v, want %v", got, want)
    53  	}
    54  }
    55  
    56  func TestWalkerSymlinks(t *testing.T) {
    57  	dir, cleanup := testutil.TempDir(t, "", "")
    58  	defer cleanup()
    59  	p := func(p ...string) string {
    60  		p = append([]string{dir}, p...)
    61  		return filepath.Join(p...)
    62  	}
    63  	if err := os.MkdirAll(p("dir"), 0777); err != nil {
    64  		t.Fatal(err)
    65  	}
    66  	f, err := os.Create(p("dir", "file"))
    67  	if err != nil {
    68  		t.Fatal(err)
    69  	}
    70  	defer f.Close()
    71  	if err := os.Symlink(p("dir"), p("link")); err != nil {
    72  		t.Fatal(err)
    73  	}
    74  	var w Walker
    75  	w.Init(dir)
    76  	var paths []string
    77  	for w.Scan() {
    78  		paths = append(paths, w.Relpath())
    79  	}
    80  	sort.Strings(paths)
    81  	if got, want := paths, []string{".", "dir", "dir/file", "link", "link/file"}; !reflect.DeepEqual(got, want) {
    82  		t.Errorf("got %v, want %v", got, want)
    83  	}
    84  }