首页 > 其他分享 >goframe gfile用法

goframe gfile用法

时间:2024-07-15 14:56:32浏览次数:9  
标签:string err gtest 用法 Assert goframe gfile func

        GoFrame 的  gfile  模块提供了一套丰富的文件和目录操作方法,使得文件系统的操作变得更加简单易用。以下是一些  gfile  的常用方法及其用法:

1. 获取绝对路径:使用  Abs  函数可以获取给定路径的绝对表示形式,如果路径不是绝对路径,它会与当前工作目录联接以转换为绝对路径 。


2. 获取文件名: Basename  函数可以返回路径的最后一个元素,即文件名,包括文件扩展名 。

3. 复制文件或目录: Copy  函数用于复制文件或目录,它支持不同情况下的复制操作,例如复制单个文件或整个目录 。

4. 获取文件扩展名: Ext  函数返回文件的扩展名,包括点( . ),而  ExtName  函数返回的扩展名则不包含点 。

5. 格式化文件大小: FormatSize  函数可以将文件大小转换为更易于阅读的格式 。

6. 读取文件内容: GetBytes  函数可以读取文件的全部内容,并以字节切片的形式返回 。

7. 读取文件的一部分内容: GetBytesByTwoOffsets  函数可以根据给定的起始和结束位置读取文件的一部分内容 。

8. 打开文件: Open  函数以只读模式打开文件或目录,而  OpenFile  和  OpenWithFlag  函数允许使用自定义的标志和权限来打开文件或目录 。

9. 获取特定字符的文件偏移量: GetNextCharOffsetByPath  函数可以根据给定的字符和起始位置返回文件中的偏移量 。

        这些方法提供了对文件系统进行操作的便利性,隐藏了底层实现的复杂性,使得开发者可以更专注于业务逻辑的实现。更多详细的使用示例和高级用法,可以查阅 GoFrame 的官方文档和接口文档 。

// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.

package gfile_test

import (
    "os"
    "path/filepath"
    "strings"
    "testing"

    "github.com/gogf/gf/v2/os/gfile"
    "github.com/gogf/gf/v2/os/gtime"
    "github.com/gogf/gf/v2/test/gtest"
    "github.com/gogf/gf/v2/util/gconv"
)

func Test_IsDir(t *testing.T) {
    gtest.C(t, func(t *gtest.T) {
       paths := "/testfile"
       createDir(paths)
       defer delTestFiles(paths)

       t.Assert(gfile.IsDir(testpath()+paths), true)
       t.Assert(gfile.IsDir("./testfile2"), false)
       t.Assert(gfile.IsDir("./testfile/tt.txt"), false)
       t.Assert(gfile.IsDir(""), false)
    })
}

func Test_IsEmpty(t *testing.T) {
    gtest.C(t, func(t *gtest.T) {
       path := "/testdir_" + gconv.String(gtime.TimestampNano())
       createDir(path)
       defer delTestFiles(path)

       t.Assert(gfile.IsEmpty(testpath()+path), true)
       t.Assert(gfile.IsEmpty(testpath()+path+gfile.Separator+"test.txt"), true)
    })
    gtest.C(t, func(t *gtest.T) {
       path := "/testfile_" + gconv.String(gtime.TimestampNano())
       createTestFile(path, "")
       defer delTestFiles(path)

       t.Assert(gfile.IsEmpty(testpath()+path), true)
    })
    gtest.C(t, func(t *gtest.T) {
       path := "/testfile_" + gconv.String(gtime.TimestampNano())
       createTestFile(path, "1")
       defer delTestFiles(path)

       t.Assert(gfile.IsEmpty(testpath()+path), false)
    })
}

func Test_Create(t *testing.T) {
    gtest.C(t, func(t *gtest.T) {
       var (
          err       error
          filepaths []string
          fileobj   *os.File
       )
       filepaths = append(filepaths, "/testfile_cc1.txt")
       filepaths = append(filepaths, "/testfile_cc2.txt")
       for _, v := range filepaths {
          fileobj, err = gfile.Create(testpath() + v)
          defer delTestFiles(v)
          fileobj.Close()
          t.AssertNil(err)
       }
    })

    gtest.C(t, func(t *gtest.T) {
       tmpPath := gfile.Join(gfile.Temp(), "test/testfile_cc1.txt")
       fileobj, err := gfile.Create(tmpPath)
       defer gfile.Remove(tmpPath)
       t.AssertNE(fileobj, nil)
       t.AssertNil(err)
       fileobj.Close()
    })
}

func Test_Open(t *testing.T) {
    gtest.C(t, func(t *gtest.T) {
       var (
          err     error
          files   []string
          flags   []bool
          fileobj *os.File
       )

       file1 := "/testfile_nc1.txt"
       createTestFile(file1, "")
       defer delTestFiles(file1)

       files = append(files, file1)
       flags = append(flags, true)

       files = append(files, "./testfile/file1/c1.txt")
       flags = append(flags, false)

       for k, v := range files {
          fileobj, err = gfile.Open(testpath() + v)
          fileobj.Close()
          if flags[k] {
             t.AssertNil(err)
          } else {
             t.AssertNE(err, nil)
          }

       }

    })
}

func Test_OpenFile(t *testing.T) {
    gtest.C(t, func(t *gtest.T) {
       var (
          err     error
          files   []string
          flags   []bool
          fileobj *os.File
       )

       files = append(files, "./testfile/file1/nc1.txt")
       flags = append(flags, false)

       f1 := "/testfile_tt.txt"
       createTestFile(f1, "")
       defer delTestFiles(f1)

       files = append(files, f1)
       flags = append(flags, true)

       for k, v := range files {
          fileobj, err = gfile.OpenFile(testpath()+v, os.O_RDWR, 0666)
          fileobj.Close()
          if flags[k] {
             t.AssertNil(err)
          } else {
             t.AssertNE(err, nil)
          }

       }

    })
}

func Test_OpenWithFlag(t *testing.T) {
    gtest.C(t, func(t *gtest.T) {
       var (
          err     error
          files   []string
          flags   []bool
          fileobj *os.File
       )

       file1 := "/testfile_t1.txt"
       createTestFile(file1, "")
       defer delTestFiles(file1)
       files = append(files, file1)
       flags = append(flags, true)

       files = append(files, "/testfiless/dirfiles/t1_no.txt")
       flags = append(flags, false)

       for k, v := range files {
          fileobj, err = gfile.OpenWithFlag(testpath()+v, os.O_RDWR)
          fileobj.Close()
          if flags[k] {
             t.AssertNil(err)
          } else {
             t.AssertNE(err, nil)
          }

       }

    })
}

func Test_OpenWithFlagPerm(t *testing.T) {
    gtest.C(t, func(t *gtest.T) {
       var (
          err     error
          files   []string
          flags   []bool
          fileobj *os.File
       )
       file1 := "/testfile_nc1.txt"
       createTestFile(file1, "")
       defer delTestFiles(file1)
       files = append(files, file1)
       flags = append(flags, true)

       files = append(files, "/testfileyy/tt.txt")
       flags = append(flags, false)

       for k, v := range files {
          fileobj, err = gfile.OpenWithFlagPerm(testpath()+v, os.O_RDWR, 0666)
          fileobj.Close()
          if flags[k] {
             t.AssertNil(err)
          } else {
             t.AssertNE(err, nil)
          }

       }

    })
}

func Test_Exists(t *testing.T) {

    gtest.C(t, func(t *gtest.T) {
       var (
          flag  bool
          files []string
          flags []bool
       )

       file1 := "/testfile_GetContents.txt"
       createTestFile(file1, "")
       defer delTestFiles(file1)

       files = append(files, file1)
       flags = append(flags, true)

       files = append(files, "./testfile/havefile1/tt_no.txt")
       flags = append(flags, false)

       for k, v := range files {
          flag = gfile.Exists(testpath() + v)
          if flags[k] {
             t.Assert(flag, true)
          } else {
             t.Assert(flag, false)
          }

       }

    })
}

func Test_Pwd(t *testing.T) {
    gtest.C(t, func(t *gtest.T) {
       paths, err := os.Getwd()
       t.AssertNil(err)
       t.Assert(gfile.Pwd(), paths)

    })
}

func Test_IsFile(t *testing.T) {
    gtest.C(t, func(t *gtest.T) {
       var (
          flag  bool
          files []string
          flags []bool
       )

       file1 := "/testfile_tt.txt"
       createTestFile(file1, "")
       defer delTestFiles(file1)
       files = append(files, file1)
       flags = append(flags, true)

       dir1 := "/testfiless"
       createDir(dir1)
       defer delTestFiles(dir1)
       files = append(files, dir1)
       flags = append(flags, false)

       files = append(files, "./testfiledd/tt1.txt")
       flags = append(flags, false)

       for k, v := range files {
          flag = gfile.IsFile(testpath() + v)
          if flags[k] {
             t.Assert(flag, true)
          } else {
             t.Assert(flag, false)
          }

       }

    })
}

func Test_Info(t *testing.T) {
    gtest.C(t, func(t *gtest.T) {
       var (
          err    error
          paths  string = "/testfile_t1.txt"
          files  os.FileInfo
          files2 os.FileInfo
       )

       createTestFile(paths, "")
       defer delTestFiles(paths)
       files, err = gfile.Stat(testpath() + paths)
       t.AssertNil(err)

       files2, err = os.Stat(testpath() + paths)
       t.AssertNil(err)

       t.Assert(files, files2)

    })
}

func Test_Move(t *testing.T) {
    gtest.C(t, func(t *gtest.T) {
       var (
          paths     string = "/ovetest"
          filepaths string = "/testfile_ttn1.txt"
          topath    string = "/testfile_ttn2.txt"
       )
       createDir("/ovetest")
       createTestFile(paths+filepaths, "a")

       defer delTestFiles(paths)

       yfile := testpath() + paths + filepaths
       tofile := testpath() + paths + topath

       t.Assert(gfile.Move(yfile, tofile), nil)

       // 检查移动后的文件是否真实存在
       _, err := os.Stat(tofile)
       t.Assert(os.IsNotExist(err), false)

    })
}

func Test_Rename(t *testing.T) {
    gtest.C(t, func(t *gtest.T) {
       var (
          paths  string = "/testfiles"
          ypath  string = "/testfilettm1.txt"
          topath string = "/testfilettm2.txt"
       )
       createDir(paths)
       createTestFile(paths+ypath, "a")
       defer delTestFiles(paths)

       ypath = testpath() + paths + ypath
       topath = testpath() + paths + topath

       t.Assert(gfile.Rename(ypath, topath), nil)
       t.Assert(gfile.IsFile(topath), true)

       t.AssertNE(gfile.Rename("", ""), nil)

    })

}

func Test_DirNames(t *testing.T) {
    gtest.C(t, func(t *gtest.T) {
       var (
          paths    string = "/testdirs"
          err      error
          readlist []string
       )
       havelist := []string{
          "t1.txt",
          "t2.txt",
       }

       // 创建测试文件
       createDir(paths)
       for _, v := range havelist {
          createTestFile(paths+"/"+v, "")
       }
       defer delTestFiles(paths)

       readlist, err = gfile.DirNames(testpath() + paths)

       t.AssertNil(err)
       t.AssertIN(readlist, havelist)

       _, err = gfile.DirNames("")
       t.AssertNE(err, nil)

    })
}

func Test_Glob(t *testing.T) {
    gtest.C(t, func(t *gtest.T) {
       var (
          paths      string = "/testfiles/*.txt"
          dirpath    string = "/testfiles"
          err        error
          resultlist []string
       )

       havelist1 := []string{
          "t1.txt",
          "t2.txt",
       }

       havelist2 := []string{
          testpath() + "/testfiles/t1.txt",
          testpath() + "/testfiles/t2.txt",
       }

       // ===============================构建测试文件
       createDir(dirpath)
       for _, v := range havelist1 {
          createTestFile(dirpath+"/"+v, "")
       }
       defer delTestFiles(dirpath)

       resultlist, err = gfile.Glob(testpath()+paths, true)
       t.AssertNil(err)
       t.Assert(resultlist, havelist1)

       resultlist, err = gfile.Glob(testpath()+paths, false)

       t.AssertNil(err)
       t.Assert(formatpaths(resultlist), formatpaths(havelist2))

       _, err = gfile.Glob("", true)
       t.AssertNil(err)

    })
}

func Test_Remove(t *testing.T) {
    gtest.C(t, func(t *gtest.T) {
       var (
          paths string = "/testfile_t1.txt"
       )
       createTestFile(paths, "")
       t.Assert(gfile.Remove(testpath()+paths), nil)

       t.Assert(gfile.Remove(""), nil)

       defer delTestFiles(paths)

    })
}

func Test_IsReadable(t *testing.T) {
    gtest.C(t, func(t *gtest.T) {
       var (
          paths1 string = "/testfile_GetContents.txt"
          paths2 string = "./testfile_GetContents_no.txt"
       )

       createTestFile(paths1, "")
       defer delTestFiles(paths1)

       t.Assert(gfile.IsReadable(testpath()+paths1), true)
       t.Assert(gfile.IsReadable(paths2), false)

    })
}

func Test_IsWritable(t *testing.T) {
    gtest.C(t, func(t *gtest.T) {
       var (
          paths1 string = "/testfile_GetContents.txt"
          paths2 string = "./testfile_GetContents_no.txt"
       )

       createTestFile(paths1, "")
       defer delTestFiles(paths1)
       t.Assert(gfile.IsWritable(testpath()+paths1), true)
       t.Assert(gfile.IsWritable(paths2), false)

    })
}

func Test_Chmod(t *testing.T) {
    gtest.C(t, func(t *gtest.T) {
       var (
          paths1 string = "/testfile_GetContents.txt"
          paths2 string = "./testfile_GetContents_no.txt"
       )
       createTestFile(paths1, "")
       defer delTestFiles(paths1)

       t.Assert(gfile.Chmod(testpath()+paths1, 0777), nil)
       t.AssertNE(gfile.Chmod(paths2, 0777), nil)

    })
}

// 获取绝对目录地址
func Test_RealPath(t *testing.T) {
    gtest.C(t, func(t *gtest.T) {
       var (
          paths1    string = "/testfile_files"
          readlPath string

          tempstr string
       )

       createDir(paths1)
       defer delTestFiles(paths1)

       readlPath = gfile.RealPath("./")

       tempstr, _ = filepath.Abs("./")

       t.Assert(readlPath, tempstr)

       t.Assert(gfile.RealPath("./nodirs"), "")

    })
}

// 获取当前执行文件的目录
func Test_SelfPath(t *testing.T) {
    gtest.C(t, func(t *gtest.T) {
       var (
          paths1    string
          readlPath string
          tempstr   string
       )
       readlPath = gfile.SelfPath()
       readlPath = filepath.ToSlash(readlPath)

       tempstr, _ = filepath.Abs(os.Args[0])
       paths1 = filepath.ToSlash(tempstr)
       paths1 = strings.Replace(paths1, "./", "/", 1)

       t.Assert(readlPath, paths1)

    })
}

func Test_SelfDir(t *testing.T) {
    gtest.C(t, func(t *gtest.T) {
       var (
          paths1    string
          readlPath string
          tempstr   string
       )
       readlPath = gfile.SelfDir()

       tempstr, _ = filepath.Abs(os.Args[0])
       paths1 = filepath.Dir(tempstr)

       t.Assert(readlPath, paths1)

    })
}

func Test_Basename(t *testing.T) {
    gtest.C(t, func(t *gtest.T) {
       var (
          paths1    string = "/testfilerr_GetContents.txt"
          readlPath string
       )

       createTestFile(paths1, "")
       defer delTestFiles(paths1)

       readlPath = gfile.Basename(testpath() + paths1)
       t.Assert(readlPath, "testfilerr_GetContents.txt")

    })
}

func Test_Dir(t *testing.T) {
    gtest.C(t, func(t *gtest.T) {
       var (
          paths1    string = "/testfiless"
          readlPath string
       )
       createDir(paths1)
       defer delTestFiles(paths1)

       readlPath = gfile.Dir(testpath() + paths1)

       t.Assert(readlPath, testpath())

       t.Assert(len(gfile.Dir(".")) > 0, true)
    })
}

func Test_Ext(t *testing.T) {
    gtest.C(t, func(t *gtest.T) {
       var (
          paths1   string = "/testfile_GetContents.txt"
          dirpath1        = "/testdirs"
       )
       createTestFile(paths1, "")
       defer delTestFiles(paths1)

       createDir(dirpath1)
       defer delTestFiles(dirpath1)

       t.Assert(gfile.Ext(testpath()+paths1), ".txt")
       t.Assert(gfile.Ext(testpath()+dirpath1), "")
    })

    gtest.C(t, func(t *gtest.T) {
       t.Assert(gfile.Ext("/var/www/test.js"), ".js")
       t.Assert(gfile.Ext("/var/www/test.min.js"), ".js")
       t.Assert(gfile.Ext("/var/www/test.js?1"), ".js")
       t.Assert(gfile.Ext("/var/www/test.min.js?v1"), ".js")
    })
}

func Test_ExtName(t *testing.T) {
    gtest.C(t, func(t *gtest.T) {
       t.Assert(gfile.ExtName("/var/www/test.js"), "js")
       t.Assert(gfile.ExtName("/var/www/test.min.js"), "js")
       t.Assert(gfile.ExtName("/var/www/test.js?v=1"), "js")
       t.Assert(gfile.ExtName("/var/www/test.min.js?v=1"), "js")
    })
}

func Test_TempDir(t *testing.T) {
    gtest.C(t, func(t *gtest.T) {
       t.Assert(gfile.Temp(), os.TempDir())
    })
}

func Test_Mkdir(t *testing.T) {
    gtest.C(t, func(t *gtest.T) {
       var (
          tpath string = "/testfile/createdir"
          err   error
       )

       defer delTestFiles("/testfile")

       err = gfile.Mkdir(testpath() + tpath)
       t.AssertNil(err)

       err = gfile.Mkdir("")
       t.AssertNE(err, nil)

       err = gfile.Mkdir(testpath() + tpath + "2/t1")
       t.AssertNil(err)

    })
}

func Test_Stat(t *testing.T) {
    gtest.C(t, func(t *gtest.T) {
       var (
          tpath1   = "/testfile_t1.txt"
          tpath2   = "./testfile_t1_no.txt"
          err      error
          fileiofo os.FileInfo
       )

       createTestFile(tpath1, "a")
       defer delTestFiles(tpath1)

       fileiofo, err = gfile.Stat(testpath() + tpath1)
       t.AssertNil(err)

       t.Assert(fileiofo.Size(), 1)

       _, err = gfile.Stat(tpath2)
       t.AssertNE(err, nil)

    })
}

func Test_MainPkgPath(t *testing.T) {
    gtest.C(t, func(t *gtest.T) {
       reads := gfile.MainPkgPath()
       t.Assert(reads, "")
    })
}

func Test_SelfName(t *testing.T) {
    gtest.C(t, func(t *gtest.T) {
       t.Assert(len(gfile.SelfName()) > 0, true)
    })
}

func Test_MTimestamp(t *testing.T) {
    gtest.C(t, func(t *gtest.T) {
       t.Assert(gfile.MTimestamp(gfile.Temp()) > 0, true)
    })
}

标签:string,err,gtest,用法,Assert,goframe,gfile,func
From: https://blog.csdn.net/leijmdas/article/details/140438437

相关文章

  • C++ STL is_sorted用法
    一:功能   检查一个区间内的元素是否有序,按升序(或降序)排列二:用法#include<algorithm>#include<iostream>intmain(){std::vector<int>data1={1,2,3,4,5};booltest1=std::is_sorted(data1.begin(),data1.end());std::cout<<std::boo......
  • C++惯用法:do...while(0)的妙用
    目录1.引言2.do...while(0)消除goto语句3.用do...while(0)包裹复杂的宏4.防止意外错误5.避免变量作用域问题1.引言        在C++中,do...while(0) 通常是用来做循环用的,然而我们做循环操作可能用for和while要多一些。经常看到一些开源代码会出现do...while(0)......
  • opencv中 在特征点匹配代码举例,以及queryIdx和trainIdx的用法
    一、用法在特征点匹配中,queryIdx和trainIdx是匹配对中的两个索引,用于指示匹配点在不同图像或特征向量中的位置。1.假设我们有两幅图像A和B,并使用特征点提取算法(如SIFT)从它们中提取出特征点和对应的描述子。2.在进行特征点匹配时,我们得到了一个匹配对,其中包含了两个特征点:特征点A......
  • C# Newtonsoft.Json 高级用法
    一、基本用法Json.Net是支持序列化和反序列化DataTable,DataSet,EntityFramework和Entity的。下面分别举例说明序列化和反序列化。//序列化DataTableDataTabledt=newDataTable();dt.Columns.Add("Age",Type.GetType("System.Int32"));dt.Columns.Add("Name",Type.Get......
  • 10个Python函数参数进阶用法及代码优化
    目录1.默认参数值:让函数更加灵活2.关键字参数:清晰的调用方式3.*args:拥抱不确定数量的位置参数4.**kwargs:处理不确定数量的关键字参数5.参数解包:简化多参数的传递6.命名关键字参数:限制关键字参数7.局部变量与全局变量:理解作用域8.高级:装饰器(@decorator)9.Lambd......
  • python每日学习4:函数的定义和各类参数定义与用法
    目录目录一、函数的定义二、参数的定义和用法1、必选参数2、默认参数3、可变参数4、关键字参数5、命名关键字参数三、参数在实际操作中的要求一、函数的定义1、函数代码块以def关键词开头,后接函数名称和圆括号()2、在圆括号内定义传入参数3、函数的第一行语句可以......
  • mybatis 中 foreach collection的三种用法
    转载:http://blog.sina.com.cn/s/blog_b0d90e8c0102v1q1.htmlforeach的主要用在构建in条件中,它可以在SQL语句中进行迭代一个集合。foreach元素的属性主要有item,index,collection,open,separator,close。    item表示集合中每一个元素进行迭代时的别名,    index指定一个名字,......
  • MYSQL中replace into的用法
    今天在编程的时候,学习了replaceinto的用法,真的很好用,是insertinto的增强版。在向表中插入数据时,我们经常会遇到这样的情况:1、首先判断数据是否存在;2、如果不存在,则插入;3、如果存在,则更新。###项目成本案例:::::  1IntegerupdateTransport(Reimbursementreimbursement);......
  • SQL中的case when then else end用法
    Case具有两种格式。简单Case函数和Case搜索函数。1--简单Case函数2CASEsex3WHEN'1'THEN'男'4WHEN'2'THEN'女'5ELSE'其他'END6--Case搜索函数7CASEWHENsex='1'THEN'男'8W......
  • 2024最新【内网隐蔽扫描,Nmap高级用法】(非常详细)零基础入门到精通,收藏这一篇就够了
    前言Nmap(NetworkMapper)是一款开源免费的网络发现和安全审计工具,主要用于扫描目标主机的开放端口、操作系统类型、启用的服务等信息。以下是Nmap的一些常见使用介绍Nmap的常见使用介绍「主机发现」:Nmap可以通过发送不同类型的探测包(如ICMPecho请求、TCPSYN包等)来检测......