add test helper for price side quantity assertion

This commit is contained in:
c9s 2024-10-28 14:22:34 +08:00
parent f4df9a09e2
commit 6004114696
No known key found for this signature in database
GPG Key ID: 7385E7E464CB0A54
2 changed files with 76 additions and 0 deletions

View File

@ -111,4 +111,31 @@ func TestLiquidityOrderGenerator(t *testing.T) {
{Side: types.SideTypeBuy, Price: Number("1.9600"), Quantity: Number("620.54")},
}, orders[28:30])
})
t.Run("bid orders 2", func(t *testing.T) {
orders := g.Generate(types.SideTypeBuy, Number(1000.0), Number(0.29), Number(0.20), 30, scale)
assert.Len(t, orders, 30)
totalQuoteQuantity := fixedpoint.NewFromInt(0)
for _, o := range orders {
totalQuoteQuantity = totalQuoteQuantity.Add(o.Quantity.Mul(o.Price))
}
assert.InDelta(t, 1000.0, totalQuoteQuantity.Float64(), 1.0)
AssertOrdersPriceSideQuantityFromText(t, `
BUY,0.2899,65.41
BUY,0.2868,68.61
BUY,0.2837,71.97
BUY,0.2806,75.5
BUY,0.2775,79.2
BUY,0.2744,83.07
BUY,0.2713,87.14
BUY,0.2682,91.41
BUY,0.2651,95.88
BUY,0.262,100.58
BUY,0.2589,105.5
BUY,0.2558,110.67
BUY,0.2527,116.09
`, orders[0:13])
})
}

View File

@ -1,6 +1,8 @@
package testhelper
import (
"fmt"
"strings"
"testing"
"github.com/stretchr/testify/assert"
@ -28,6 +30,53 @@ type PriceSideQuantityAssert struct {
Quantity fixedpoint.Value
}
func ParsePriceSideQuantityAssertions(text string) []PriceSideQuantityAssert {
var asserts []PriceSideQuantityAssert
lines := strings.Split(text, "\n")
for _, line := range lines {
line = strings.TrimSpace(line)
if line == "" {
continue
}
cols := strings.SplitN(line, ",", 3)
if len(cols) < 3 {
panic(fmt.Errorf("column length should be 3, got %d", len(cols)))
}
side := strings.TrimSpace(cols[0])
price := fixedpoint.MustNewFromString(strings.TrimSpace(cols[1]))
quantity := fixedpoint.MustNewFromString(strings.TrimSpace(cols[2]))
asserts = append(asserts, PriceSideQuantityAssert{
Price: price,
Side: types.SideType(side),
Quantity: quantity,
})
}
return asserts
}
func AssertOrdersPriceSideQuantityFromText(
t *testing.T, text string, orders []types.SubmitOrder,
) {
asserts := ParsePriceSideQuantityAssertions(text)
assert.Equalf(t, len(asserts), len(orders), "expecting %d orders", len(asserts))
actualInText := "Actual Orders:\n"
for i, a := range asserts {
order := orders[i]
assert.Equalf(t, a.Price.Float64(), order.Price.Float64(), "order #%d price should be %f", i+1, a.Price.Float64())
assert.Equalf(t, a.Quantity.Float64(), order.Quantity.Float64(), "order #%d quantity should be %f", i+1, a.Quantity.Float64())
assert.Equalf(t, a.Side, orders[i].Side, "order at price %f should be %s", a.Price.Float64(), a.Side)
actualInText += fmt.Sprintf("%s,%s,%s\n", order.Side, order.Price.String(), order.Quantity.String())
}
if t.Failed() {
t.Log(actualInText)
}
}
// AssertOrdersPriceSide asserts the orders with the given price and side (slice)
func AssertOrdersPriceSideQuantity(
t *testing.T, asserts []PriceSideQuantityAssert, orders []types.SubmitOrder,