github.com/khulnasoft-lab/tunnel-db@v0.0.0-20231117205118-74e1113bd007/pkg/utils/utils_test.go (about)

     1  package utils
     2  
     3  import (
     4  	"io"
     5  	"os"
     6  	"path/filepath"
     7  	"strings"
     8  	"testing"
     9  )
    10  
    11  func touch(t *testing.T, name string) {
    12  	f, err := os.Create(name)
    13  	if err != nil {
    14  		t.Fatal(err)
    15  	}
    16  	if err := f.Close(); err != nil {
    17  		t.Fatal(err)
    18  	}
    19  }
    20  
    21  func write(t *testing.T, name string, content string) {
    22  	err := os.WriteFile(name, []byte(content), 0666)
    23  	if err != nil {
    24  		t.Fatal(err)
    25  	}
    26  }
    27  
    28  func TestFileWalk(t *testing.T) {
    29  	td := t.TempDir()
    30  
    31  	if err := os.MkdirAll(filepath.Join(td, "dir"), 0755); err != nil {
    32  		t.Fatal(err)
    33  	}
    34  	touch(t, filepath.Join(td, "dir/foo1"))
    35  	touch(t, filepath.Join(td, "dir/foo2"))
    36  	write(t, filepath.Join(td, "dir/foo3"), "foo3")
    37  
    38  	sawDir := false
    39  	sawFoo1 := false
    40  	sawFoo2 := false
    41  	var contentFoo3 []byte
    42  	var err error
    43  
    44  	walker := func(r io.Reader, path string) error {
    45  		if strings.HasSuffix(path, "dir") {
    46  			sawDir = true
    47  		}
    48  		if strings.HasSuffix(path, "foo1") {
    49  			sawFoo1 = true
    50  		}
    51  		if strings.HasSuffix(path, "foo2") {
    52  			sawFoo2 = true
    53  		}
    54  		if strings.HasSuffix(path, "foo3") {
    55  			contentFoo3, err = io.ReadAll(r)
    56  			if err != nil {
    57  				t.Fatal(err)
    58  			}
    59  		}
    60  		return nil
    61  	}
    62  
    63  	err = FileWalk(td, walker)
    64  	if err != nil {
    65  		t.Fatal(err)
    66  	}
    67  	if sawDir {
    68  		t.Error("directories must not be passed to walkFn")
    69  	}
    70  	if sawFoo1 || sawFoo2 {
    71  		t.Error("an empty file must not be passed to walkFn")
    72  	}
    73  	if string(contentFoo3) != "foo3" {
    74  		t.Error("The file content is wrong")
    75  	}
    76  }