123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110 |
- package fileutils
- import (
- "bytes"
- "os"
- "path/filepath"
- "testing"
- )
- const (
- testDirRelativePath = "./test_dir"
- )
- func TestPathExists(t *testing.T) {
- exist := PathExists("../fileutils")
- if !exist {
- t.Fatal("应该存在的目录不存在")
- }
- exist = PathExists("foo")
- if exist {
- t.Fatal("不应该存在的目录存在")
- }
- }
- func TestGetDirFiles(t *testing.T) {
- checkTestDir(t, testDirRelativePath)
- }
- func TestReadFileWithBuffer(t *testing.T) {
- buffer := bytes.Buffer{}
- err := ReadFileWithBuffer(filepath.Join(testDirRelativePath, "test.txt"), 1, func(b []byte) {
- buffer.Write(b)
- })
- if err != nil {
- t.Fatal(err)
- }
- if buffer.String() != "test content" {
- t.Fatal("读取失败")
- }
- }
- func TestZip(t *testing.T) {
- zipFileRelativePath := "test.zip"
- destUnzipFileDir := "./unzip_file_test_dir"
- destUnzipBytesDir := "./unzip_bytes_test_dir"
- err := ZipDir(testDirRelativePath, zipFileRelativePath)
- if err != nil {
- t.Fatal(err)
- }
- defer func() {
- err := os.RemoveAll(zipFileRelativePath)
- if err != nil {
- t.Fatal(err)
- }
- }()
- err = UnzipFile(zipFileRelativePath, destUnzipFileDir)
- if err != nil {
- t.Fatal(err)
- }
- defer func() {
- err := os.RemoveAll(destUnzipFileDir)
- if err != nil {
- t.Fatal(err)
- }
- }()
- checkTestDir(t, filepath.Join(destUnzipFileDir, "test_dir"))
- fileBytes, err := os.ReadFile(zipFileRelativePath)
- if err != nil {
- t.Fatal(err)
- }
- err = UnzipBytes(fileBytes, destUnzipBytesDir)
- if err != nil {
- t.Fatal(err)
- }
- defer func() {
- err := os.RemoveAll(destUnzipBytesDir)
- if err != nil {
- t.Fatal(err)
- }
- }()
- checkTestDir(t, filepath.Join(destUnzipBytesDir, "test_dir"))
- }
- func checkTestDir(t *testing.T, dirPath string) {
- filePaths, err := GetDirFiles(dirPath)
- if err != nil {
- t.Fatal(err)
- }
- if len(filePaths) != 2 {
- t.Fatal("文件数量不正确")
- }
- for _, filePath := range filePaths {
- if filePath != filepath.Join(dirPath, "test.txt") && filePath != filepath.Join(dirPath, "test_sub_dir/test_sub.txt") {
- t.Fatal("出现不存在的文件")
- }
- }
- }
|