Files

89 lines
2.5 KiB
Go

//go:build integration
package integration
import (
"context"
"fmt"
"os"
"os/exec"
"testing"
"time"
"go-sms/internal/repository/clickhouse"
)
func chAddr() string {
if a := os.Getenv("GOSMS_TEST_CH_ADDR"); a != "" {
return a
}
return "127.0.0.1:19000"
}
// TestClickHouse_BatchInsert 开发环境验收(Day 14):建表→批量插入→计数核对。
func TestClickHouse_BatchInsert(t *testing.T) {
conn, err := clickhouse.Open(clickhouse.Config{
Addrs: []string{chAddr()},
Database: "default",
Username: "gosms",
Password: "gosms123",
})
if err != nil {
t.Skipf("ClickHouse 不可达(make up),跳过: %v", err)
}
defer conn.Close()
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
if err := conn.Ping(ctx); err != nil {
t.Skipf("ClickHouse Ping 失败,跳过: %v", err)
}
table := fmt.Sprintf("go-sms_it_batch_%d", time.Now().UnixNano()%1000000)
// 建测试表(MergeTree)
// 直接用底层 DDL:经 Conn 接口扩展不足,此处借 Exec —— 使用 BatchInsert 校验为主,
// DDL 通过 docker exec clickhouse-client 执行
t.Logf("测试表: %s", table)
if out, err := execCH(fmt.Sprintf(
"CREATE TABLE `%s` (id UInt64, mobile String, status UInt8) ENGINE=MergeTree ORDER BY id", table)); err != nil {
t.Fatalf("建表失败: %v(%s)", err, out)
}
defer execCH("DROP TABLE IF EXISTS `" + table + "`")
rows := make([][]any, 0, 3)
for i := 0; i < 3; i++ {
rows = append(rows, []any{uint64(7300000000000000 + i), fmt.Sprintf("138%08d", i), uint8(i)})
}
if err := conn.BatchInsert(ctx, table, []string{"id", "mobile", "status"}, rows); err != nil {
t.Fatalf("BatchInsert 失败: %v", err)
}
// 空批次幂等
if err := conn.BatchInsert(ctx, table, []string{"id"}, nil); err != nil {
t.Fatalf("空批次应返回 nil: %v", err)
}
out, err := execCH(fmt.Sprintf("SELECT count(), max(mobile) FROM `%s`", table))
if err != nil {
t.Fatal(err)
}
t.Logf("插入结果: %s", out)
if want := "3\t13800000002"; trimSpace(out) != want {
t.Errorf("查询 = %q, 期望 %q", out, want)
}
}
// execCH 容器内执行 DDL/查询(ClickHouse 客户端)。
func execCH(sql string) (string, error) {
out, err := exec.Command("docker", "exec", "go-sms-clickhouse",
"clickhouse-client", "--user", "gosms", "--password", "gosms123", "--query", sql).Output()
return string(out), err
}
func trimSpace(s string) string {
for len(s) > 0 && (s[len(s)-1] == '\n' || s[len(s)-1] == '\r' || s[len(s)-1] == ' ') {
s = s[:len(s)-1]
}
return s
}