90 lines
2.4 KiB
Go
90 lines
2.4 KiB
Go
// fileparse_test.go Day 44:TXT/CSV/XLSX 三格式抽取+格式拒绝。
|
|
package fileparse
|
|
|
|
import (
|
|
"bytes"
|
|
"strings"
|
|
"testing"
|
|
|
|
"github.com/xuri/excelize/v2"
|
|
)
|
|
|
|
func TestParseTxt(t *testing.T) {
|
|
in := "13800138000\n13800138001\r\n\n 13800138002 \n13800138003,张三\n"
|
|
res, err := Parse(strings.NewReader(in), "numbers.txt")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
want := []string{"13800138000", "13800138001", "13800138002", "13800138003"}
|
|
if len(res.Mobiles) != len(want) || res.Rows != len(want) {
|
|
t.Fatalf("got %v rows=%d want %v", res.Mobiles, res.Rows, want)
|
|
}
|
|
for i, m := range res.Mobiles {
|
|
if m != want[i] {
|
|
t.Fatalf("行 %d: got %q want %q", i, m, want[i])
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestParseCsvWithBOM(t *testing.T) {
|
|
var b bytes.Buffer
|
|
b.WriteString("\xEF\xBB\xBF") // UTF-8 BOM(Excel 另存常见)
|
|
b.WriteString("手机号,姓名\n13800138000,张三\n13800138001,李四\n")
|
|
res, err := Parse(&b, "list.csv")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
// parse 层不做表头启发,首行「手机号」原样返回(启发在 fileimport)
|
|
want := []string{"手机号", "13800138000", "13800138001"}
|
|
if len(res.Mobiles) != 3 {
|
|
t.Fatalf("got %v", res.Mobiles)
|
|
}
|
|
for i, m := range want {
|
|
if res.Mobiles[i] != m {
|
|
t.Fatalf("行 %d: got %q want %q", i, res.Mobiles[i], m)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestParseXlsx(t *testing.T) {
|
|
f := excelize.NewFile()
|
|
sheet := f.GetSheetName(0)
|
|
_ = f.SetCellValue(sheet, "A1", "手机号")
|
|
_ = f.SetCellValue(sheet, "A2", "13800138000")
|
|
_ = f.SetCellValue(sheet, "A3", "13800138001")
|
|
_ = f.SetCellValue(sheet, "A4", "1.39E+10") // 文本形态科学计数法
|
|
var buf bytes.Buffer
|
|
if err := f.Write(&buf); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
res, err := Parse(bytes.NewReader(buf.Bytes()), "名单.xlsx")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if len(res.Mobiles) != 4 {
|
|
t.Fatalf("got %v", res.Mobiles)
|
|
}
|
|
if res.Mobiles[0] != "手机号" || res.Mobiles[1] != "13800138000" {
|
|
t.Fatalf("xlsx 列抽取: %v", res.Mobiles)
|
|
}
|
|
if got := expandScientific("1.39E+10"); got != "13900000000" {
|
|
t.Fatalf("科学计数法还原: got %q", got)
|
|
}
|
|
}
|
|
|
|
func TestParseRejectUnknown(t *testing.T) {
|
|
if _, err := Parse(strings.NewReader("x"), "a.docx"); err == nil {
|
|
t.Fatal("不支持的格式应报错")
|
|
}
|
|
}
|
|
|
|
func TestParseEmpty(t *testing.T) {
|
|
res, err := Parse(strings.NewReader("\n \n"), "e.txt")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if len(res.Mobiles) != 0 {
|
|
t.Fatalf("空文件应无号码: %v", res.Mobiles)
|
|
}
|
|
}
|