Golang单元测试实战

 

vscode 工具生成测试文件、测试代码

 

package main

import (
	"os"
	"strings"
)

func ExtractDir(isDIr bool, p string) string {
	if isDIr {
		return p
	}
	ps := "/"
	l := strings.Split(p, ps)
	n := len(l) - 1
	p = strings.Join(l[0:n], ps)
	return p
}

func CreateDirIfIsNotExist(isDIr bool, p string, perm os.FileMode) error {
	// isDIr 由调用者声明是从文件或者目录,来创建目录(由具体的业务场景判断,因为无法从字符串判断)。
	d := ExtractDir(isDIr, p)
	_, err := os.Open(p)
	if os.IsNotExist(err) {
		// 注意路径穿越检查
		// secguide/Go安全指南.md at main · Tencent/secguide · GitHub https://github.com/Tencent/secguide/blob/main/Go%E5%AE%89%E5%85%A8%E6%8C%87%E5%8D%97.md#121%E5%BF%85%E9%A1%BB-%E8%B7%AF%E5%BE%84%E7%A9%BF%E8%B6%8A%E6%A3%80%E6%9F%A5
		err := os.MkdirAll(d, os.ModeDir)
		return err
	}
	return nil
}

func NewFile(name string, data []byte, perm os.FileMode) error {
	err := os.WriteFile(name, data, perm)
	return err
}

 

package main

import (
	"os"
	"testing"
)

func TestCreateDirIfIsNotExist(t *testing.T) {
	type args struct {
		isDIr bool
		p     string
		perm  os.FileMode
	}
	tests := []struct {
		name    string
		args    args
		wantErr bool
	}{
		{name: "", args: args{isDIr: true, p: "test2/atxt", perm: 0777}},
		{name: "", args: args{isDIr: true, p: "test3/t1/atxt", perm: 0777}},
		{name: "", args: args{isDIr: true, p: "../../testa/t1/atxt", perm: 0777}},
		{name: "", args: args{isDIr: true, p: "../../../testb/t1/atxt", perm: 0777}},
		{name: "", args: args{isDIr: false, p: "atest2/a/b.txt", perm: 0777}},
		{name: "", args: args{isDIr: false, p: "atest3/t1/a/b.txt", perm: 0777}},
		{name: "", args: args{isDIr: false, p: "../../atest/t1/a/b.txt", perm: 0777}},
		{name: "", args: args{isDIr: false, p: "../../../atest/t1/a/b.txt", perm: 0777}},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			if err := CreateDirIfIsNotExist(tt.args.isDIr, tt.args.p, tt.args.perm); (err != nil) != tt.wantErr {
				t.Errorf("CreateDirIfIsNotExist() error = %v, wantErr %v", err, tt.wantErr)
			}
		})
	}
}

func TestNewFile(t *testing.T) {
	type args struct {
		name string
		data []byte
		perm os.FileMode
	}
	tests := []struct {
		name    string
		args    args
		wantErr bool
	}{
		{name: "", args: args{name: "atest2/a/b.txt", data: []byte("1"), perm: 0777}},
		{name: "", args: args{name: "atest3/t1/a/b.txt", data: []byte("1"), perm: 0777}},
		{name: "", args: args{name: "../../atest/t1/a/b.txt", data: []byte("1"), perm: 0777}},
		{name: "", args: args{name: "../../../atest/t1/a/b.txt", data: []byte("1"), perm: 0777}},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			if err := NewFile(tt.args.name, tt.args.data, tt.args.perm); (err != nil) != tt.wantErr {
				t.Errorf("NewFile() error = %v, wantErr %v", err, tt.wantErr)
			}
		})
	}
}

  

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

一文说尽Golang单元测试实战的那些事儿

一文说尽Golang单元测试实战的那些事儿 https://mp.weixin.qq.com/s/AuUd-S0g4QX_68CDO6jJWg

posted @ 2021-12-17 09:23  papering  阅读(115)  评论(0编辑  收藏  举报