美文网首页
利用go test测试文件上传

利用go test测试文件上传

作者: kingeasternsun | 来源:发表于2017-09-12 11:15 被阅读0次

我们都知道go语言的testing包提供了丰富的测试功能,方便我们在开发时进行单元测试,但是之前一直没有看到过如何进行文件上传单元测试相关的文章,直到看到了B站的这个视频「教程」Go语言基础 (O'Reilly),不得不说这个go语言学习视频比国内的不知要高到哪里去了,讲解清晰,涵盖范围广,学完感觉水平瞬间上了一个等级。

文件上传服务端代码

func upload(w http.ResponseWriter, r *http.Request) {
    file, head, err := r.FormFile("my_file")
    if err != nil {
        fmt.Sprintln(err)
        fmt.Fprintln(w, err)

        return
    }

    localFileDir := "/tmp/upload/"
    err = os.MkdirAll(localFileDir, 0777)
    if err != nil {
        fmt.Sprintln(err)
        fmt.Fprintln(w, err)

        return
    }

    localFilePath := localFileDir + head.Filename

    localFile, err := os.Create(localFilePath)
    if err != nil {
        fmt.Sprintln(err)
        fmt.Fprintln(w, err)

        return
    }
    defer localFile.Close()

    io.Copy(localFile, file)
    fmt.Fprintln(w, localFilePath)

}

测试代码

func TestUpload(t *testing.T) {
    path := "/home/ubuntu/test.go"//要上传文件所在路径
    file, err := os.Open(path)
    if err != nil {
        t.Error(err)
    }

    defer file.Close()
    body := &bytes.Buffer{}
    writer := multipart.NewWriter(body)
    part, err := writer.CreateFormFile("my_file", filepath.Base(path))
    if err != nil {
                writer.Close()
        t.Error(err)
    }
    io.Copy(part, file)
    writer.Close()

    req := httptest.NewRequest("POST", "/upload", body)
    req.Header.Set("Content-Type", writer.FormDataContentType())
    res := httptest.NewRecorder()

    upload(res, req)

    if res.Code != http.StatusOK {
        t.Error("not 200")
    }

    t.Log(res.Body.String())
    // t.Log(io.read)

}

测试代码中关键的部分在于使用了"mime/multipart"包

  1. 首先创建一个writer
    body := &bytes.Buffer{}
    writer := multipart.NewWriter(body)
  1. 然后往multipart中写入域"my_file"和文件名filepath.Base(path)

"my_file"和服务端中
file, head, err := r.FormFile("my_file")
对应。

3.最后上传文件


    io.Copy(part, file)
    writer.Close()

相关文章

  • 利用go test测试文件上传

    我们都知道go语言的testing包提供了丰富的测试功能,方便我们在开发时进行单元测试,但是之前一直没有看到过如何...

  • 单元测试&基准测试&样本测试&测试覆盖率

    1.单元测试 1.1.go test 目录 1.2.go test 测试源码文件 测试的源码文件 1.3.go t...

  • GO学习笔记(17) -测试

    测试工具 —go test go test命令用于对Go语言编写的程序进行测试。 测试规范 测试文件必须为"_te...

  • 16.手撕Go语言-测试

    Go提供了test工具用于代码的单元测试,test工具会查找包下以_test.go结尾的文件,调用测试文件中以Te...

  • go test 单元测试

    go test 单元测试 文件格式:go单元测试,有固定的名称格式,所有以_test.go为后缀名的源文件在执行g...

  • go test指令

    go test 默认执行当前目录下以xxx_test.go的测试文件。go test -v 可以看到详细的输出信息...

  • Go基本程序结构

    编写测试程序 测试程序: 源码文件以_test结尾:x x x_test.go 测试方法名以Test开头:func...

  • go test测试用法

    在golang里才_test结尾的文件,并以Test开头的函数名则为测试方法. 测试整个项目 go test ./...

  • 1 - Go的基础知识

    测试 源码文件为 xx_test.go 测试方法名以 Test 开头 使用 t.Log("xxx") ,可以在测试...

  • php和golang通信,双向管道

    新建php文件,保存为proc.php 新建go文件,保存为 test_proc.go 手动测试

网友评论

      本文标题:利用go test测试文件上传

      本文链接:https://www.haomeiwen.com/subject/fqqcsxtx.html