From 39df6516e9285b2ccab894dd9aa656e6773358a7 Mon Sep 17 00:00:00 2001 From: Ryan Gang Date: Wed, 12 Jun 2024 19:18:57 +0530 Subject: [PATCH] feat: Add ordered array assertion for RESP values This commit adds a new `OrderedArrayAssertion` struct to the `resp_assertions` package. This assertion is used to compare the order of actual and expected values in an array. It checks that the length of the actual array matches the expected length, and then iterates through each element to compare their types and values. If any element does not match, an error is returned. The `OrderedArrayAssertion` is useful for cases where the order of elements in an array matters, such as when comparing the response of a Redis command. --- .../ordered_array_assertion.go | 44 +++++++++++++++++++ internal/tester_definition.go | 8 ++++ 2 files changed, 52 insertions(+) create mode 100644 internal/resp_assertions/ordered_array_assertion.go diff --git a/internal/resp_assertions/ordered_array_assertion.go b/internal/resp_assertions/ordered_array_assertion.go new file mode 100644 index 0000000..def0ba3 --- /dev/null +++ b/internal/resp_assertions/ordered_array_assertion.go @@ -0,0 +1,44 @@ +package resp_assertions + +import ( + "bytes" + "fmt" + + resp_value "github.com/codecrafters-io/redis-tester/internal/resp/value" +) + +// OrderedArrayAssertion : Order of the actual and expected values matters. +// All RESP values are accepted as elements in this array. +// We don't alter the ordering. +type OrderedArrayAssertion struct { + ExpectedValue []resp_value.Value +} + +func NewOrderedArrayAssertion(expectedValue []resp_value.Value) RESPAssertion { + return OrderedArrayAssertion{ExpectedValue: expectedValue} +} + +func (a OrderedArrayAssertion) Run(value resp_value.Value) error { + if value.Type != resp_value.ARRAY { + return fmt.Errorf("Expected an array, got %s", value.Type) + } + + if len(value.Array()) != len(a.ExpectedValue) { + return fmt.Errorf("Expected %d elements in array, got %d (%s)", len(a.ExpectedValue), len(value.Array()), value.FormattedString()) + } + + for i, expectedValue := range a.ExpectedValue { + actualElement := value.Array()[i] + + if actualElement.Type != expectedValue.Type { + return fmt.Errorf("Expected element #%d to be a %s, got %s", i+1, expectedValue.Type, actualElement.Type) + } + + // ToDo: Equal or EqualFold ? + if !bytes.Equal(actualElement.Bytes(), expectedValue.Bytes()) { + return fmt.Errorf("Expected element #%d to be %q, got %q", i+1, expectedValue.FormattedString(), actualElement.FormattedString()) + } + } + + return nil +} diff --git a/internal/tester_definition.go b/internal/tester_definition.go index f7a470b..aec7e62 100644 --- a/internal/tester_definition.go +++ b/internal/tester_definition.go @@ -192,5 +192,13 @@ var testerDefinition = tester_definition.TesterDefinition{ Slug: "xu1", TestFunc: testStreamsXreadBlockMaxID, }, + { + Slug: "xv1", + TestFunc: testTxSuccess, + }, + { + Slug: "jy1", + TestFunc: testTxErr, + }, }, }