待测试函数包:
package sortFile
import(
"io/ioutil"
"math/rand"
"time"
"strings"
"strconv"
"fmt"
"path/filepath"
"os"
"sort"
)
const threadChanNu = 10
const randMaxNu =1000
// 写入数据
func WriteFile(allFilePath,s string)bool {
dir,_ := filepath.Split(allFilePath)
_,err := os.Stat(dir)
if err != nil {
os.MkdirAll(dir,os.ModePerm)
}
err = ioutil.WriteFile(allFilePath,[]byte(s),0666)
if err != nil {
return false
}
return true
}
func writeDataToFile(v int,fileNameInt int) {
//1. 开始产生数据
rand.Seed(time.Now().UnixNano())
randSplice := make([]string,v)
for dix := 0; dix < v; dix++ {
randSplice[dix] =strconv.Itoa(rand.Intn(v))
}
//2. 开始写入文件中 e:/chan/v.txt
writePath := "e:/chan/"+strconv.Itoa(fileNameInt)+".txt"
bl := WriteFile(writePath,strings.Join(randSplice,","))
if !bl {
fmt.Println("写入文件错误!")
return
}
fmt.Println(writePath,"写入完成")
flgChan<- fileNameInt
}
func ReadDataAndStoreWrtie(path string) {
//1. 判断文件路径是否存在
_,err := os.Lstat(path)
if err != nil {
fmt.Println("读取文件错误!filePath:",path)
return
}
//2. 读取文件内内容
var readSpliceByte []byte
readSpliceByte,err = ioutil.ReadFile(path)
if err != nil {
return
}
readStrSlice := strings.Split(string(readSpliceByte),",")
readIntSlice := make([]int , len(readStrSlice))
for idx, v := range readStrSlice {
readIntSlice[idx],_ = strconv.Atoi(v)
}
sort.Ints(readIntSlice);
var build strings.Builder
for _, v := range readIntSlice {
build.WriteString(strconv.Itoa(v)+",")
}
fileName := filepath.Base(path)
fileNoExt := fileName[:strings.LastIndex(fileName,".")]
fmt.Println("文件名为:",fileNoExt)
WriteFile("e:/chan/"+fileNoExt+"_stor.txt",build.String())
}
var flgChan =make(chan int ,threadChanNu)
//练习一
func GoroutineOne() {
for i := 0; i < threadChanNu; i++ {
go writeDataToFile(randMaxNu,i)
}
for i := 0; i < threadChanNu; i++ {
val := <- flgChan
// 开启读取线程 排序后再写入另外一个文件
go ReadDataAndStoreWrtie("e:/chan/"+strconv.Itoa(val)+".txt")
}
close(flgChan)
}
单元测试文件sort_test.go:
方法名Test开始,后边第一个字母不能小写
运行命令 go test -v 全部测试
指定测试文件测试 go test -v 测试文件名.go 依赖文件名.go
指定方法的我运行不成功: 网上说是 go test -v -test.run 方法名
package sortFile
import(
"testing"
"fmt"
)
func TestGoroutineOne(t *testing.T) {
GoroutineOne()
fmt.Println("运行完毕!")
}