Skip to content

Commit

Permalink
feat: Add ordered array assertion for RESP values
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
ryan-gang committed Jun 12, 2024
1 parent b4e9649 commit 39df651
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
44 changes: 44 additions & 0 deletions internal/resp_assertions/ordered_array_assertion.go
Original file line number Diff line number Diff line change
@@ -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
}
8 changes: 8 additions & 0 deletions internal/tester_definition.go
Original file line number Diff line number Diff line change
Expand Up @@ -192,5 +192,13 @@ var testerDefinition = tester_definition.TesterDefinition{
Slug: "xu1",
TestFunc: testStreamsXreadBlockMaxID,
},
{
Slug: "xv1",
TestFunc: testTxSuccess,
},
{
Slug: "jy1",
TestFunc: testTxErr,
},
},
}

0 comments on commit 39df651

Please sign in to comment.