Files
ucan/toolkit/server/extargs/custom_test.go

116 lines
2.7 KiB
Go
Raw Permalink Normal View History

package extargs
import (
"fmt"
"testing"
"github.com/ipld/go-ipld-prime/datamodel"
"github.com/ipld/go-ipld-prime/fluent/qp"
"github.com/stretchr/testify/require"
2025-08-05 12:11:20 +02:00
"github.com/ucan-wg/go-ucan/pkg/policy"
"github.com/ucan-wg/go-ucan/pkg/policy/literal"
)
2025-08-05 12:11:20 +02:00
func ExampleCustomExtArgs() {
// Note: this is an example for how to build arguments, but you likely want to use CustomExtArgs
// through UcanCtx.
pol := policy.Policy{} // policies from the delegations
// We will construct the following args:
2025-08-05 12:11:20 +02:00
// "key": {
// "ntwk":"eth-mainnet",
// "quota":{
// "ur":1234,
// "udc":1234,
// "arch":1234,
// "down":1234,
// "store":1234,
// "up":1234
// }
// }
2025-08-05 12:11:20 +02:00
customArgs := NewCustomExtArgs("key", pol, func(ma datamodel.MapAssembler) {
qp.MapEntry(ma, "ntwk", qp.String("eth-mainnet"))
qp.MapEntry(ma, "quota", qp.Map(6, func(ma datamodel.MapAssembler) {
qp.MapEntry(ma, "ur", qp.Int(1234))
qp.MapEntry(ma, "udc", qp.Int(1234))
qp.MapEntry(ma, "arch", qp.Int(1234))
qp.MapEntry(ma, "down", qp.Int(1234))
qp.MapEntry(ma, "store", qp.Int(1234))
qp.MapEntry(ma, "up", qp.Int(1234))
}))
})
2025-08-05 12:11:20 +02:00
err := customArgs.Verify()
fmt.Println(err)
// Output:
// <nil>
}
2025-08-05 12:11:20 +02:00
func TestCustom(t *testing.T) {
assembler := func(ma datamodel.MapAssembler) {
qp.MapEntry(ma, "ntwk", qp.String("eth-mainnet"))
qp.MapEntry(ma, "quota", qp.Map(6, func(ma datamodel.MapAssembler) {
qp.MapEntry(ma, "ur", qp.Int(1234))
qp.MapEntry(ma, "udc", qp.Int(1234))
qp.MapEntry(ma, "arch", qp.Int(1234))
qp.MapEntry(ma, "down", qp.Int(1234))
qp.MapEntry(ma, "store", qp.Int(1234))
qp.MapEntry(ma, "up", qp.Int(1234))
}))
}
tests := []struct {
name string
pol policy.Policy
expected bool
}{
{
name: "no policies",
pol: policy.Policy{},
expected: true,
},
{
name: "matching args",
pol: policy.MustConstruct(
2025-08-05 12:11:20 +02:00
policy.Equal(".key.ntwk", literal.String("eth-mainnet")),
policy.LessThanOrEqual(".key.quota.ur", literal.Int(1234)),
),
expected: true,
},
{
name: "wrong network",
pol: policy.MustConstruct(
2025-08-05 12:11:20 +02:00
policy.Equal(".key.ntwk", literal.String("avalanche-fuji")),
policy.LessThanOrEqual(".key.quota.ur", literal.Int(1234)),
),
expected: false,
},
{
name: "unrespected quota",
pol: policy.MustConstruct(
2025-08-05 12:11:20 +02:00
policy.Equal(".key.ntwk", literal.String("eth-mainnet")),
policy.LessThanOrEqual(".key.quota.ur", literal.Int(100)),
),
expected: false,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
2025-08-05 12:11:20 +02:00
extArgs := NewCustomExtArgs("key", tc.pol, assembler)
_, err := extArgs.Args()
require.NoError(t, err)
if tc.expected {
require.NoError(t, extArgs.Verify())
} else {
require.Error(t, extArgs.Verify())
}
})
}
}