99 lines
2.7 KiB
Go
99 lines
2.7 KiB
Go
// fileimport_test.go Day 44:导入服务——去重/非法/表头启发/超限/对象键(依赖倒置 memStore)。
|
|
package submit
|
|
|
|
import (
|
|
"context"
|
|
"io"
|
|
"strconv"
|
|
"strings"
|
|
"testing"
|
|
|
|
"go-sms/internal/pkg/errors"
|
|
"go-sms/internal/pkg/storage"
|
|
"go-sms/internal/util"
|
|
)
|
|
|
|
// memStore 内存对象存储(测试替身)。
|
|
type memStore struct {
|
|
objects map[string]int64
|
|
}
|
|
|
|
var _ storage.ObjectStore = (*memStore)(nil)
|
|
|
|
func (m *memStore) Put(_ context.Context, key string, _ io.Reader, size int64, _ string) error {
|
|
if m.objects == nil {
|
|
m.objects = map[string]int64{}
|
|
}
|
|
m.objects[key] = size
|
|
return nil
|
|
}
|
|
|
|
func newImporter() (*FileImportService, *memStore) {
|
|
sf, _ := util.NewSnowflake(1)
|
|
st := &memStore{}
|
|
return NewFileImportService(st, sf), st
|
|
}
|
|
|
|
func TestFileImportTxt(t *testing.T) {
|
|
svc, st := newImporter()
|
|
in := "13800138000\n13800138000\n13800138001\nbad123\n"
|
|
res, err := svc.Import(context.Background(), strings.NewReader(in), "n.txt", int64(len(in)), 7)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if res.Valid != 2 || res.Duplicated != 1 || res.Invalid != 1 {
|
|
t.Fatalf("计数: %+v", res)
|
|
}
|
|
if !strings.HasPrefix(res.ObjectKey, "numbers/7/") || !strings.HasSuffix(res.ObjectKey, ".txt") {
|
|
t.Fatalf("对象键: %q", res.ObjectKey)
|
|
}
|
|
if _, ok := st.objects[res.ObjectKey]; !ok {
|
|
t.Fatal("对象未落存储")
|
|
}
|
|
if len(res.Preview) != 2 || res.Preview[0] != "13800138000" {
|
|
t.Fatalf("预览: %v", res.Preview)
|
|
}
|
|
}
|
|
|
|
func TestFileImportHeaderHeuristic(t *testing.T) {
|
|
svc, _ := newImporter()
|
|
in := "手机号,姓名\n13800138000,张三\n13800138001,李四\n"
|
|
res, err := svc.Import(context.Background(), strings.NewReader(in), "h.csv", int64(len(in)), 1)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if !res.HeaderSkip || res.Valid != 2 || res.Invalid != 0 {
|
|
t.Fatalf("表头启发: %+v", res)
|
|
}
|
|
}
|
|
|
|
func TestFileImportAllInvalid(t *testing.T) {
|
|
svc, _ := newImporter()
|
|
in := "abc\ndef\n"
|
|
_, err := svc.Import(context.Background(), strings.NewReader(in), "bad.txt", int64(len(in)), 1)
|
|
if err == nil || err.(*errors.Error).Code != "ISC:400" {
|
|
t.Fatalf("全非法应 400: %v", err)
|
|
}
|
|
}
|
|
|
|
func TestFileImportOverLimit(t *testing.T) {
|
|
svc, _ := newImporter()
|
|
var b strings.Builder
|
|
for i := 0; i <= MaxMobiles; i++ {
|
|
b.WriteString(strconv.FormatInt(13900000000+int64(i), 10))
|
|
b.WriteString("\n")
|
|
}
|
|
_, err := svc.Import(context.Background(), strings.NewReader(b.String()), "big.txt", int64(b.Len()), 1)
|
|
if err == nil || !strings.Contains(err.Error(), "超单次上限") {
|
|
t.Fatalf("超限应拒绝: %v", err)
|
|
}
|
|
}
|
|
|
|
func TestFileImportRejectExt(t *testing.T) {
|
|
svc, _ := newImporter()
|
|
_, err := svc.Import(context.Background(), strings.NewReader("x"), "a.doc", 1, 1)
|
|
if err == nil {
|
|
t.Fatal("不支持的扩展名应拒绝")
|
|
}
|
|
}
|