From 3e80496d5a2f4df93aa200b56b71a075a2ebf4e5 Mon Sep 17 00:00:00 2001 From: abhiraj-mengade Date: Thu, 1 Aug 2024 10:32:55 +0530 Subject: [PATCH] Add: StatusMatch function for elegantly handingling Status Checks --- tests/path_gateway_ipns_test.go | 4 ++-- tooling/test/sugar.go | 31 +++++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/tests/path_gateway_ipns_test.go b/tests/path_gateway_ipns_test.go index 93eeb5568..53d0e3818 100644 --- a/tests/path_gateway_ipns_test.go +++ b/tests/path_gateway_ipns_test.go @@ -67,7 +67,7 @@ func TestGatewayIPNSPath(t *testing.T) { Request: Request(). Path("/ipns/{{name}}", ipnsV1V2BrokenValueV1), Response: Expect(). - StatusBetween(500, 599), + StatusMatch("5xx"), }, { Name: "GET for /ipns/name with valid V2 and broken V1 signature succeeds", @@ -120,7 +120,7 @@ func TestGatewayIPNSPath(t *testing.T) { Request: Request(). Path("/ipns/{{name}}", ipnsV1V2BrokenSigV2), Response: Expect(). - StatusBetween(500, 599), + StatusMatch("5xx"), }, } diff --git a/tooling/test/sugar.go b/tooling/test/sugar.go index cbe0228da..764e45244 100644 --- a/tooling/test/sugar.go +++ b/tooling/test/sugar.go @@ -4,6 +4,9 @@ import ( "fmt" "net/http" "net/url" + "regexp" + "strconv" + "strings" "testing" "github.com/ipfs/gateway-conformance/tooling" @@ -162,6 +165,34 @@ func (e ExpectBuilder) Status(statusCode int) ExpectBuilder { return e } +func (e ExpectBuilder) StatusMatch(pattern string) ExpectBuilder { + re := regexp.MustCompile(`^(\d+)(x+)$`) + matches := re.FindStringSubmatch(pattern) + if len(matches) != 3 { + panic("invalid status pattern") + } + + // Extract the leading digits and the number of 'x' characters + leadingDigits := matches[1] + numXs := len(matches[2]) + + // Compute the lower bound + from, err := strconv.Atoi(leadingDigits + strings.Repeat("0", numXs)) + if err != nil { + panic(fmt.Sprintf("invalid status pattern: %v", err)) + } + + // Compute the upper bound + to, err := strconv.Atoi(leadingDigits + strings.Repeat("9", numXs)) + if err != nil { + panic(fmt.Sprintf("invalid status pattern: %v", err)) + } + + e.StatusCodeFrom_ = from + e.StatusCodeTo_ = to + return e +} + func (e ExpectBuilder) StatusBetween(from, to int) ExpectBuilder { e.StatusCodeFrom_ = from e.StatusCodeTo_ = to