test(postgres): pgxmock 覆盖 5 个 repo,包级 87.6%

为什么用 pgxmock:testcontainers 需要 docker-in-CI 而当前还没有 CI;
mock 路线 1) 零基础设施 2) 把 SQL 字符串和参数顺序作为契约锁死,
schema 漂移立刻可见——这正是上生产前最需要的信号。pgxmock 升级到
testcontainers 不阻塞 v2,留 v2.1 做 nightly 集成测试。

关键改动:
- internal/repo/persistent/postgres/pool.go:新建 pgxPool 接口,
  列出 5 repo 实际用到的 Begin/Query/Exec 三个方法。生产代码继续
  传 *pgxpool.Pool(自动满足接口),测试传 pgxmock.PgxPoolIface。
- 5 个 repo struct 字段从 *pgxpool.Pool 改为 pgxPool 接口;构造器
  签名保留 *pgxpool.Pool,app.go DI 不动。
- 5 个 *_repo_test.go:每个 repo 至少
  · UpsertMany happy path(精确 SQL + 参数)
  · UpsertMany 跳过逻辑(空字段 / 未收线)
  · UpsertMany ExecError(Rollback 路径)
  · FindRecent happy path(验证 DESC → 反序为升序)
  · FindRecent QueryError
  KlineRepo 额外加了 EmptyShortCircuits 和 BeginError 两个边界。

覆盖率:postgres 包 87.6%(UpsertMany ~86%、FindRecent ~93%)。
New*Repo 构造器为 0% 是设计选择:测试直接构造 struct 避开
*pgxpool.Pool 依赖。

所有 12 条守卫扫过无输出。
This commit is contained in:
dela
2026-05-24 20:43:46 +08:00
parent c478a5feb9
commit ee420f9c56
13 changed files with 663 additions and 32 deletions

17
go.mod
View File

@@ -1,13 +1,15 @@
module cryptoHermes
go 1.23
go 1.23.0
require (
github.com/gofiber/fiber/v2 v2.52.5
github.com/ilyakaznacheev/cleanenv v1.5.0
github.com/jackc/pgx/v5 v5.7.1
github.com/jackc/pgx/v5 v5.7.4
github.com/pashagolub/pgxmock/v4 v4.6.0
github.com/robfig/cron/v3 v3.0.1
golang.org/x/sync v0.8.0
github.com/stretchr/testify v1.9.0
golang.org/x/sync v0.13.0
golang.org/x/time v0.6.0
)
@@ -21,21 +23,18 @@ require (
github.com/jackc/puddle/v2 v2.2.2 // indirect
github.com/joho/godotenv v1.5.1 // indirect
github.com/klauspost/compress v1.17.0 // indirect
github.com/kr/text v0.2.0 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mattn/go-runewidth v0.0.15 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/rivo/uniseg v0.2.0 // indirect
github.com/rogpeppe/go-internal v1.14.1 // indirect
github.com/stretchr/objx v0.5.0 // indirect
github.com/stretchr/testify v1.8.1 // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect
github.com/valyala/fasthttp v1.51.0 // indirect
github.com/valyala/tcplisten v1.0.0 // indirect
golang.org/x/crypto v0.27.0 // indirect
golang.org/x/sys v0.26.0 // indirect
golang.org/x/text v0.18.0 // indirect
golang.org/x/crypto v0.37.0 // indirect
golang.org/x/sys v0.32.0 // indirect
golang.org/x/text v0.24.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
olympos.io/encoding/edn v0.0.0-20201019073823-d3554ca0b0a3 // indirect
)

32
go.sum
View File

@@ -2,7 +2,6 @@ github.com/BurntSushi/toml v1.2.1 h1:9F2/+DoOYIOksmaJFPw1tGFy1eDnIJXg+UHjuD8lTak
github.com/BurntSushi/toml v1.2.1/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ=
github.com/andybalholm/brotli v1.0.5 h1:8uQZIdzKmjc/iuPu7O2ioW48L81FgatrcpfFmiq/cCs=
github.com/andybalholm/brotli v1.0.5/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
@@ -16,8 +15,8 @@ github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsI
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
github.com/jackc/pgx/v5 v5.7.1 h1:x7SYsPBYDkHDksogeSmZZ5xzThcTgRz++I5E+ePFUcs=
github.com/jackc/pgx/v5 v5.7.1/go.mod h1:e7O26IywZZ+naJtWWos6i6fvWK+29etgITqrqHLfoZA=
github.com/jackc/pgx/v5 v5.7.4 h1:9wKznZrhWa2QiHL+NjTSPP6yjl3451BX3imWDnokYlg=
github.com/jackc/pgx/v5 v5.7.4/go.mod h1:ncY89UGWxg82EykZUwSpUKEfccBGGYq1xjrOpsbsfGQ=
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
@@ -35,6 +34,8 @@ github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWE
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U=
github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
github.com/pashagolub/pgxmock/v4 v4.6.0 h1:ds0hIs+bJtkfo01vqjp0BOFirjt4Ea8XV082uorzM3w=
github.com/pashagolub/pgxmock/v4 v4.6.0/go.mod h1:9VoVHXwS3XR/yPtKGzwQvwZX1kzGB9sM8SviDcHDa3A=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY=
@@ -44,31 +45,26 @@ github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzG
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0 h1:1zr/of2m5FGMsad5YfcqgdqdWrIhu+EBEJRhR1U7z/c=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
github.com/valyala/fasthttp v1.51.0 h1:8b30A5JlZ6C7AS81RsWjYMQmrZG6feChmgAolCl1SqA=
github.com/valyala/fasthttp v1.51.0/go.mod h1:oI2XroL+lI7vdXyYoQk03bXBThfFl2cVdIA3Xl7cH8g=
github.com/valyala/tcplisten v1.0.0 h1:rBHj/Xf+E1tRGZyWIWwJDiRY0zc1Js+CV5DqwacVSA8=
github.com/valyala/tcplisten v1.0.0/go.mod h1:T0xQ8SeCZGxckz9qRXTfG43PvQ/mcWh7FwZEA7Ioqkc=
golang.org/x/crypto v0.27.0 h1:GXm2NjJrPaiv/h1tb2UH8QfgC/hOf/+z0p6PT8o1w7A=
golang.org/x/crypto v0.27.0/go.mod h1:1Xngt8kV6Dvbssa53Ziq6Eqn0HqbZi5Z6R0ZpwQzt70=
golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ=
golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/crypto v0.37.0 h1:kJNSjF/Xp7kU0iB2Z+9viTPMW4EqqsrywMXLJOOsXSE=
golang.org/x/crypto v0.37.0/go.mod h1:vg+k43peMZ0pUMhYmVAWysMK35e6ioLh3wB8ZCAfbVc=
golang.org/x/sync v0.13.0 h1:AauUjRAJ9OSnvULf/ARrrVywoJDy0YS2AwQ98I37610=
golang.org/x/sync v0.13.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.26.0 h1:KHjCJyddX0LoSTb3J+vWpupP9p0oznkqVk/IfjymZbo=
golang.org/x/sys v0.26.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.18.0 h1:XvMDiNzPAl0jr17s6W9lcaIhGUfUORdGCNsuLmPG224=
golang.org/x/text v0.18.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY=
golang.org/x/sys v0.32.0 h1:s77OFDvIQeibCmezSnk/q6iAfkdiQaJi4VzroCFrN20=
golang.org/x/sys v0.32.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/text v0.24.0 h1:dd5Bzh4yt5KYA8f9CJHCP4FB4D51c2c6JvN37xJJkJ0=
golang.org/x/text v0.24.0/go.mod h1:L8rBsPeo2pSS+xqN0d5u2ikmjtmoJbDBT1b7nHvFCdU=
golang.org/x/time v0.6.0 h1:eTDhh4ZXt5Qf0augr54TN6suAUudPcawVZeIAPU7D4U=
golang.org/x/time v0.6.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=

View File

@@ -11,7 +11,7 @@ import (
)
type FundingRepo struct {
pool *pgxpool.Pool
pool pgxPool
}
func NewFundingRepo(pool *pgxpool.Pool) *FundingRepo {

View File

@@ -0,0 +1,109 @@
package postgres
import (
"context"
"errors"
"testing"
"cryptoHermes/internal/entity"
"github.com/pashagolub/pgxmock/v4"
"github.com/stretchr/testify/require"
)
func TestFundingRepo_UpsertMany_HappyPath(t *testing.T) {
mock, err := pgxmock.NewPool()
require.NoError(t, err)
defer mock.Close()
mock.ExpectBegin()
mock.ExpectExec("INSERT INTO funding_rates").
WithArgs("binance", "BTCUSDT", int64(1700000000000), "0.0001", "50000").
WillReturnResult(pgxmock.NewResult("INSERT", 1))
mock.ExpectCommit()
mock.ExpectRollback()
r := &FundingRepo{pool: mock}
err = r.UpsertMany(context.Background(), []entity.FundingRate{{
Source: "binance", Symbol: "BTCUSDT",
FundingTime: 1700000000000, FundingRate: "0.0001", MarkPrice: "50000",
}})
require.NoError(t, err)
require.NoError(t, mock.ExpectationsWereMet())
}
func TestFundingRepo_UpsertMany_SkipsEmptyRate(t *testing.T) {
mock, err := pgxmock.NewPool()
require.NoError(t, err)
defer mock.Close()
mock.ExpectBegin()
mock.ExpectCommit()
mock.ExpectRollback()
r := &FundingRepo{pool: mock}
err = r.UpsertMany(context.Background(), []entity.FundingRate{
{Symbol: "BTCUSDT", FundingTime: 1, FundingRate: ""}, // 空 rate 跳过
{Symbol: "BTCUSDT", FundingTime: 0, FundingRate: "1"}, // 空时间戳跳过
})
require.NoError(t, err)
require.NoError(t, mock.ExpectationsWereMet())
}
func TestFundingRepo_UpsertMany_ExecError(t *testing.T) {
mock, err := pgxmock.NewPool()
require.NoError(t, err)
defer mock.Close()
mock.ExpectBegin()
mock.ExpectExec("INSERT INTO funding_rates").
WithArgs(pgxmock.AnyArg(), pgxmock.AnyArg(), pgxmock.AnyArg(), pgxmock.AnyArg(), pgxmock.AnyArg()).
WillReturnError(errors.New("dup key"))
mock.ExpectRollback()
r := &FundingRepo{pool: mock}
err = r.UpsertMany(context.Background(), []entity.FundingRate{{
Symbol: "BTCUSDT", FundingTime: 1, FundingRate: "0.0001",
}})
require.Error(t, err)
require.Contains(t, err.Error(), "upsert funding")
require.NoError(t, mock.ExpectationsWereMet())
}
func TestFundingRepo_FindRecent_HappyPath(t *testing.T) {
mock, err := pgxmock.NewPool()
require.NoError(t, err)
defer mock.Close()
rows := mock.NewRows([]string{"source", "symbol", "funding_time", "funding_rate", "mark_price"}).
AddRow("binance", "BTCUSDT", int64(2), "0.0002", "50100").
AddRow("binance", "BTCUSDT", int64(1), "0.0001", "50000")
mock.ExpectQuery("SELECT source, symbol, funding_time").
WithArgs("BTCUSDT", 100).
WillReturnRows(rows)
r := &FundingRepo{pool: mock}
got, err := r.FindRecent(context.Background(), "BTCUSDT", 0) // 0 → 100
require.NoError(t, err)
require.Len(t, got, 2)
// 反序后升序:[1,2]
require.Equal(t, int64(1), got[0].FundingTime)
require.Equal(t, "50100", got[1].MarkPrice)
require.NoError(t, mock.ExpectationsWereMet())
}
func TestFundingRepo_FindRecent_QueryError(t *testing.T) {
mock, err := pgxmock.NewPool()
require.NoError(t, err)
defer mock.Close()
mock.ExpectQuery("SELECT source, symbol, funding_time").
WithArgs("BTCUSDT", 50).
WillReturnError(errors.New("conn closed"))
r := &FundingRepo{pool: mock}
_, err = r.FindRecent(context.Background(), "BTCUSDT", 50)
require.Error(t, err)
require.NoError(t, mock.ExpectationsWereMet())
}

View File

@@ -10,7 +10,7 @@ import (
)
type KlineRepo struct {
pool *pgxpool.Pool
pool pgxPool
}
func NewKlineRepo(pool *pgxpool.Pool) *KlineRepo {

View File

@@ -0,0 +1,175 @@
package postgres
import (
"context"
"errors"
"testing"
"cryptoHermes/internal/entity"
"github.com/pashagolub/pgxmock/v4"
"github.com/stretchr/testify/require"
)
func TestKlineRepo_UpsertMany_HappyPath(t *testing.T) {
mock, err := pgxmock.NewPool()
require.NoError(t, err)
defer mock.Close()
mock.ExpectBegin()
mock.ExpectExec("INSERT INTO market_klines").
WithArgs(
"binance", "BTCUSDT", "1h",
int64(1700000000000), int64(1700003599999),
"50000", "50500", "49800", "50200",
"123", "6190000",
int64(789), "60", "3000000",
).
WillReturnResult(pgxmock.NewResult("INSERT", 1))
mock.ExpectCommit()
mock.ExpectRollback() // defer Rollback after Commit is a no-op but mock sees it
r := &KlineRepo{pool: mock}
err = r.UpsertMany(context.Background(), []entity.Kline{{
Source: "binance", Symbol: "BTCUSDT", Interval: "1h",
OpenTime: 1700000000000, CloseTime: 1700003599999,
Open: "50000", High: "50500", Low: "49800", Close: "50200",
Volume: "123", QuoteVolume: "6190000",
TradeCount: 789, TakerBuyBaseVolume: "60", TakerBuyQuoteVolume: "3000000",
IsClosed: true,
}})
require.NoError(t, err)
require.NoError(t, mock.ExpectationsWereMet())
}
func TestKlineRepo_UpsertMany_EmptyShortCircuits(t *testing.T) {
mock, err := pgxmock.NewPool()
require.NoError(t, err)
defer mock.Close()
r := &KlineRepo{pool: mock}
require.NoError(t, r.UpsertMany(context.Background(), nil))
require.NoError(t, mock.ExpectationsWereMet())
}
func TestKlineRepo_UpsertMany_SkipsUnclosed(t *testing.T) {
mock, err := pgxmock.NewPool()
require.NoError(t, err)
defer mock.Close()
mock.ExpectBegin()
// 第二根 K 线 IsClosed=false应跳过只 Exec 一次
mock.ExpectExec("INSERT INTO market_klines").
WithArgs(
"binance", "BTCUSDT", "1h",
int64(1), int64(2),
"1", "1", "1", "1", "1", "1",
int64(0), "", "",
).
WillReturnResult(pgxmock.NewResult("INSERT", 1))
mock.ExpectCommit()
mock.ExpectRollback()
r := &KlineRepo{pool: mock}
err = r.UpsertMany(context.Background(), []entity.Kline{
{Source: "binance", Symbol: "BTCUSDT", Interval: "1h", OpenTime: 1, CloseTime: 2,
Open: "1", High: "1", Low: "1", Close: "1", Volume: "1", QuoteVolume: "1",
IsClosed: true},
{Source: "binance", Symbol: "BTCUSDT", Interval: "1h", OpenTime: 3, CloseTime: 4,
IsClosed: false}, // 未收线,跳过
})
require.NoError(t, err)
require.NoError(t, mock.ExpectationsWereMet())
}
func TestKlineRepo_UpsertMany_BeginError(t *testing.T) {
mock, err := pgxmock.NewPool()
require.NoError(t, err)
defer mock.Close()
mock.ExpectBegin().WillReturnError(errors.New("conn lost"))
r := &KlineRepo{pool: mock}
err = r.UpsertMany(context.Background(), []entity.Kline{{IsClosed: true}})
require.Error(t, err)
require.Contains(t, err.Error(), "begin")
require.NoError(t, mock.ExpectationsWereMet())
}
func TestKlineRepo_UpsertMany_ExecError(t *testing.T) {
mock, err := pgxmock.NewPool()
require.NoError(t, err)
defer mock.Close()
mock.ExpectBegin()
mock.ExpectExec("INSERT INTO market_klines").
WithArgs(
pgxmock.AnyArg(), pgxmock.AnyArg(), pgxmock.AnyArg(),
pgxmock.AnyArg(), pgxmock.AnyArg(),
pgxmock.AnyArg(), pgxmock.AnyArg(), pgxmock.AnyArg(), pgxmock.AnyArg(),
pgxmock.AnyArg(), pgxmock.AnyArg(),
pgxmock.AnyArg(), pgxmock.AnyArg(), pgxmock.AnyArg(),
).
WillReturnError(errors.New("constraint violation"))
mock.ExpectRollback()
r := &KlineRepo{pool: mock}
err = r.UpsertMany(context.Background(), []entity.Kline{{
Source: "binance", Symbol: "BTCUSDT", Interval: "1h",
OpenTime: 1700000000000, IsClosed: true,
}})
require.Error(t, err)
require.Contains(t, err.Error(), "upsert kline")
require.NoError(t, mock.ExpectationsWereMet())
}
func TestKlineRepo_FindRecent_HappyPath(t *testing.T) {
mock, err := pgxmock.NewPool()
require.NoError(t, err)
defer mock.Close()
rows := mock.NewRows([]string{
"source", "symbol", "interval", "open_time", "close_time",
"open", "high", "low", "close",
"volume", "quote_volume",
"trade_count", "taker_buy_base_volume", "taker_buy_quote_volume",
}).
// DB 返回时间倒序t=2 先t=1 后
AddRow("binance", "BTCUSDT", "1h", int64(2), int64(3),
"50100", "50200", "50000", "50150",
"10", "500000", int64(100), "5", "250000").
AddRow("binance", "BTCUSDT", "1h", int64(1), int64(2),
"50000", "50100", "49900", "50050",
"9", "450000", int64(90), "4", "200000")
mock.ExpectQuery("SELECT source, symbol, interval").
WithArgs("BTCUSDT", "1h", 300).
WillReturnRows(rows)
r := &KlineRepo{pool: mock}
got, err := r.FindRecent(context.Background(), "BTCUSDT", "1h", 0) // limit<=0 → 300
require.NoError(t, err)
require.Len(t, got, 2)
// 返回应已反序为升序:[1,2]
require.Equal(t, int64(1), got[0].OpenTime)
require.Equal(t, int64(2), got[1].OpenTime)
require.True(t, got[0].IsClosed, "落库的都视为已收线")
require.True(t, got[1].IsClosed)
require.NoError(t, mock.ExpectationsWereMet())
}
func TestKlineRepo_FindRecent_QueryError(t *testing.T) {
mock, err := pgxmock.NewPool()
require.NoError(t, err)
defer mock.Close()
mock.ExpectQuery("SELECT source, symbol, interval").
WithArgs("BTCUSDT", "1h", 100).
WillReturnError(errors.New("timeout"))
r := &KlineRepo{pool: mock}
_, err = r.FindRecent(context.Background(), "BTCUSDT", "1h", 100)
require.Error(t, err)
require.Contains(t, err.Error(), "query")
require.NoError(t, mock.ExpectationsWereMet())
}

View File

@@ -10,7 +10,7 @@ import (
)
type LongShortRatioRepo struct {
pool *pgxpool.Pool
pool pgxPool
}
func NewLongShortRatioRepo(pool *pgxpool.Pool) *LongShortRatioRepo {

View File

@@ -0,0 +1,115 @@
package postgres
import (
"context"
"errors"
"testing"
"cryptoHermes/internal/entity"
"github.com/pashagolub/pgxmock/v4"
"github.com/stretchr/testify/require"
)
func TestLongShortRatioRepo_UpsertMany_HappyPath(t *testing.T) {
mock, err := pgxmock.NewPool()
require.NoError(t, err)
defer mock.Close()
mock.ExpectBegin()
mock.ExpectExec("INSERT INTO long_short_ratio").
WithArgs("binance", "BTCUSDT", "1h", entity.RatioTypeGlobalAccount, int64(1),
"1.5", "0.6", "0.4").
WillReturnResult(pgxmock.NewResult("INSERT", 1))
mock.ExpectCommit()
mock.ExpectRollback()
r := &LongShortRatioRepo{pool: mock}
err = r.UpsertMany(context.Background(), []entity.LongShortRatio{{
Source: "binance", Symbol: "BTCUSDT", Period: "1h",
RatioType: entity.RatioTypeGlobalAccount, Timestamp: 1,
LongShortRatio: "1.5", LongValue: "0.6", ShortValue: "0.4",
}})
require.NoError(t, err)
require.NoError(t, mock.ExpectationsWereMet())
}
func TestLongShortRatioRepo_UpsertMany_SkipsEmpty(t *testing.T) {
mock, err := pgxmock.NewPool()
require.NoError(t, err)
defer mock.Close()
mock.ExpectBegin()
mock.ExpectCommit()
mock.ExpectRollback()
r := &LongShortRatioRepo{pool: mock}
err = r.UpsertMany(context.Background(), []entity.LongShortRatio{
{LongShortRatio: ""},
{LongShortRatio: "1", Timestamp: 0},
})
require.NoError(t, err)
require.NoError(t, mock.ExpectationsWereMet())
}
func TestLongShortRatioRepo_UpsertMany_ExecError(t *testing.T) {
mock, err := pgxmock.NewPool()
require.NoError(t, err)
defer mock.Close()
mock.ExpectBegin()
mock.ExpectExec("INSERT INTO long_short_ratio").
WithArgs(pgxmock.AnyArg(), pgxmock.AnyArg(), pgxmock.AnyArg(), pgxmock.AnyArg(), pgxmock.AnyArg(),
pgxmock.AnyArg(), pgxmock.AnyArg(), pgxmock.AnyArg()).
WillReturnError(errors.New("fk violation"))
mock.ExpectRollback()
r := &LongShortRatioRepo{pool: mock}
err = r.UpsertMany(context.Background(), []entity.LongShortRatio{{
Symbol: "BTCUSDT", Period: "1h", RatioType: entity.RatioTypeGlobalAccount,
Timestamp: 1, LongShortRatio: "1.5",
}})
require.Error(t, err)
require.Contains(t, err.Error(), "upsert ls")
require.NoError(t, mock.ExpectationsWereMet())
}
func TestLongShortRatioRepo_FindRecent_HappyPath(t *testing.T) {
mock, err := pgxmock.NewPool()
require.NoError(t, err)
defer mock.Close()
rows := mock.NewRows([]string{"source", "symbol", "period", "ratio_type", "timestamp",
"long_short_ratio", "long_value", "short_value"}).
AddRow("binance", "BTCUSDT", "1h", entity.RatioTypeGlobalAccount, int64(2),
"1.6", "0.62", "0.38").
AddRow("binance", "BTCUSDT", "1h", entity.RatioTypeGlobalAccount, int64(1),
"1.5", "0.6", "0.4")
mock.ExpectQuery("SELECT source, symbol, period, ratio_type").
WithArgs("BTCUSDT", "1h", entity.RatioTypeGlobalAccount, 200).
WillReturnRows(rows)
r := &LongShortRatioRepo{pool: mock}
got, err := r.FindRecent(context.Background(), "BTCUSDT", "1h", entity.RatioTypeGlobalAccount, 200)
require.NoError(t, err)
require.Len(t, got, 2)
require.Equal(t, int64(1), got[0].Timestamp, "升序")
require.Equal(t, "0.62", got[1].LongValue)
require.NoError(t, mock.ExpectationsWereMet())
}
func TestLongShortRatioRepo_FindRecent_QueryError(t *testing.T) {
mock, err := pgxmock.NewPool()
require.NoError(t, err)
defer mock.Close()
mock.ExpectQuery("SELECT source, symbol, period, ratio_type").
WithArgs("BTCUSDT", "1h", entity.RatioTypeTopTraderPosition, 100).
WillReturnError(errors.New("permission denied"))
r := &LongShortRatioRepo{pool: mock}
_, err = r.FindRecent(context.Background(), "BTCUSDT", "1h", entity.RatioTypeTopTraderPosition, 0)
require.Error(t, err)
require.NoError(t, mock.ExpectationsWereMet())
}

View File

@@ -10,7 +10,7 @@ import (
)
type OpenInterestRepo struct {
pool *pgxpool.Pool
pool pgxPool
}
func NewOpenInterestRepo(pool *pgxpool.Pool) *OpenInterestRepo {

View File

@@ -0,0 +1,107 @@
package postgres
import (
"context"
"errors"
"testing"
"cryptoHermes/internal/entity"
"github.com/pashagolub/pgxmock/v4"
"github.com/stretchr/testify/require"
)
func TestOpenInterestRepo_UpsertMany_HappyPath(t *testing.T) {
mock, err := pgxmock.NewPool()
require.NoError(t, err)
defer mock.Close()
mock.ExpectBegin()
mock.ExpectExec("INSERT INTO open_interest").
WithArgs("binance", "BTCUSDT", "1h", int64(1), "10000", "5000000").
WillReturnResult(pgxmock.NewResult("INSERT", 1))
mock.ExpectCommit()
mock.ExpectRollback()
r := &OpenInterestRepo{pool: mock}
err = r.UpsertMany(context.Background(), []entity.OpenInterest{{
Source: "binance", Symbol: "BTCUSDT", Period: "1h",
Timestamp: 1, OpenInterest: "10000", OpenInterestValue: "5000000",
}})
require.NoError(t, err)
require.NoError(t, mock.ExpectationsWereMet())
}
func TestOpenInterestRepo_UpsertMany_SkipsEmpty(t *testing.T) {
mock, err := pgxmock.NewPool()
require.NoError(t, err)
defer mock.Close()
mock.ExpectBegin()
mock.ExpectCommit()
mock.ExpectRollback()
r := &OpenInterestRepo{pool: mock}
err = r.UpsertMany(context.Background(), []entity.OpenInterest{
{OpenInterest: ""}, // 空 OI 跳过
{OpenInterest: "1", Timestamp: 0}, // 空时间戳跳过
})
require.NoError(t, err)
require.NoError(t, mock.ExpectationsWereMet())
}
func TestOpenInterestRepo_UpsertMany_ExecError(t *testing.T) {
mock, err := pgxmock.NewPool()
require.NoError(t, err)
defer mock.Close()
mock.ExpectBegin()
mock.ExpectExec("INSERT INTO open_interest").
WithArgs(pgxmock.AnyArg(), pgxmock.AnyArg(), pgxmock.AnyArg(), pgxmock.AnyArg(), pgxmock.AnyArg(), pgxmock.AnyArg()).
WillReturnError(errors.New("disk full"))
mock.ExpectRollback()
r := &OpenInterestRepo{pool: mock}
err = r.UpsertMany(context.Background(), []entity.OpenInterest{{
Symbol: "BTCUSDT", Period: "1h", Timestamp: 1, OpenInterest: "1",
}})
require.Error(t, err)
require.Contains(t, err.Error(), "upsert oi")
require.NoError(t, mock.ExpectationsWereMet())
}
func TestOpenInterestRepo_FindRecent_HappyPath(t *testing.T) {
mock, err := pgxmock.NewPool()
require.NoError(t, err)
defer mock.Close()
rows := mock.NewRows([]string{"source", "symbol", "period", "timestamp", "open_interest", "open_interest_value"}).
AddRow("binance", "BTCUSDT", "1h", int64(2), "10100", "5050000").
AddRow("binance", "BTCUSDT", "1h", int64(1), "10000", "5000000")
mock.ExpectQuery("SELECT source, symbol, period").
WithArgs("BTCUSDT", "1h", 200).
WillReturnRows(rows)
r := &OpenInterestRepo{pool: mock}
got, err := r.FindRecent(context.Background(), "BTCUSDT", "1h", 200)
require.NoError(t, err)
require.Len(t, got, 2)
require.Equal(t, int64(1), got[0].Timestamp, "升序")
require.NoError(t, mock.ExpectationsWereMet())
}
func TestOpenInterestRepo_FindRecent_QueryError(t *testing.T) {
mock, err := pgxmock.NewPool()
require.NoError(t, err)
defer mock.Close()
mock.ExpectQuery("SELECT source, symbol, period").
WithArgs("BTCUSDT", "1h", 100).
WillReturnError(errors.New("timeout"))
r := &OpenInterestRepo{pool: mock}
_, err = r.FindRecent(context.Background(), "BTCUSDT", "1h", 0)
require.Error(t, err)
require.NoError(t, mock.ExpectationsWereMet())
}

View File

@@ -0,0 +1,21 @@
package postgres
import (
"context"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
)
// pgxPool 是 5 个 repo 共享的最小连接池接口。
//
// 为什么需要这个接口:`*pgxpool.Pool` 是具体 struct不能被 pgxmock 直接
// 替换。把 repo 字段改成接口后,生产代码继续传 *pgxpool.Pool满足接口
// 测试代码传 pgxmock.PgxPoolIface同样满足
//
// 只列出 5 个 repo 实际用到的方法。如果未来用到 Acquire/Stat在这里追加。
type pgxPool interface {
Begin(ctx context.Context) (pgx.Tx, error)
Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error)
Exec(ctx context.Context, sql string, args ...any) (pgconn.CommandTag, error)
}

View File

@@ -10,7 +10,7 @@ import (
)
type TakerVolumeRepo struct {
pool *pgxpool.Pool
pool pgxPool
}
func NewTakerVolumeRepo(pool *pgxpool.Pool) *TakerVolumeRepo {

View File

@@ -0,0 +1,109 @@
package postgres
import (
"context"
"errors"
"testing"
"cryptoHermes/internal/entity"
"github.com/pashagolub/pgxmock/v4"
"github.com/stretchr/testify/require"
)
func TestTakerVolumeRepo_UpsertMany_HappyPath(t *testing.T) {
mock, err := pgxmock.NewPool()
require.NoError(t, err)
defer mock.Close()
mock.ExpectBegin()
mock.ExpectExec("INSERT INTO taker_buy_sell_volume").
WithArgs("binance", "BTCUSDT", "1h", int64(1), "1.2", "60", "50").
WillReturnResult(pgxmock.NewResult("INSERT", 1))
mock.ExpectCommit()
mock.ExpectRollback()
r := &TakerVolumeRepo{pool: mock}
err = r.UpsertMany(context.Background(), []entity.TakerBuySellVolume{{
Source: "binance", Symbol: "BTCUSDT", Period: "1h",
Timestamp: 1, BuySellRatio: "1.2", BuyVolume: "60", SellVolume: "50",
}})
require.NoError(t, err)
require.NoError(t, mock.ExpectationsWereMet())
}
func TestTakerVolumeRepo_UpsertMany_SkipsEmptyTimestamp(t *testing.T) {
mock, err := pgxmock.NewPool()
require.NoError(t, err)
defer mock.Close()
mock.ExpectBegin()
mock.ExpectCommit()
mock.ExpectRollback()
r := &TakerVolumeRepo{pool: mock}
err = r.UpsertMany(context.Background(), []entity.TakerBuySellVolume{
{Timestamp: 0, BuyVolume: "60"},
})
require.NoError(t, err)
require.NoError(t, mock.ExpectationsWereMet())
}
func TestTakerVolumeRepo_UpsertMany_ExecError(t *testing.T) {
mock, err := pgxmock.NewPool()
require.NoError(t, err)
defer mock.Close()
mock.ExpectBegin()
mock.ExpectExec("INSERT INTO taker_buy_sell_volume").
WithArgs(pgxmock.AnyArg(), pgxmock.AnyArg(), pgxmock.AnyArg(), pgxmock.AnyArg(),
pgxmock.AnyArg(), pgxmock.AnyArg(), pgxmock.AnyArg()).
WillReturnError(errors.New("readonly"))
mock.ExpectRollback()
r := &TakerVolumeRepo{pool: mock}
err = r.UpsertMany(context.Background(), []entity.TakerBuySellVolume{{
Symbol: "BTCUSDT", Period: "1h", Timestamp: 1,
}})
require.Error(t, err)
require.Contains(t, err.Error(), "upsert taker")
require.NoError(t, mock.ExpectationsWereMet())
}
func TestTakerVolumeRepo_FindRecent_HappyPath(t *testing.T) {
mock, err := pgxmock.NewPool()
require.NoError(t, err)
defer mock.Close()
rows := mock.NewRows([]string{"source", "symbol", "period", "timestamp",
"buy_sell_ratio", "buy_volume", "sell_volume"}).
AddRow("binance", "BTCUSDT", "1h", int64(2), "1.3", "65", "50").
AddRow("binance", "BTCUSDT", "1h", int64(1), "1.2", "60", "50")
mock.ExpectQuery("SELECT source, symbol, period").
WithArgs("BTCUSDT", "1h", 200).
WillReturnRows(rows)
r := &TakerVolumeRepo{pool: mock}
got, err := r.FindRecent(context.Background(), "BTCUSDT", "1h", 200)
require.NoError(t, err)
require.Len(t, got, 2)
require.Equal(t, int64(1), got[0].Timestamp)
require.Equal(t, "65", got[1].BuyVolume)
require.NoError(t, mock.ExpectationsWereMet())
}
func TestTakerVolumeRepo_FindRecent_QueryError(t *testing.T) {
mock, err := pgxmock.NewPool()
require.NoError(t, err)
defer mock.Close()
mock.ExpectQuery("SELECT source, symbol, period").
WithArgs("BTCUSDT", "1h", 100).
WillReturnError(errors.New("deadlock"))
r := &TakerVolumeRepo{pool: mock}
_, err = r.FindRecent(context.Background(), "BTCUSDT", "1h", 0)
require.Error(t, err)
require.NoError(t, mock.ExpectationsWereMet())
}