Add new comparators: Exists and NotExists ()

This commit is contained in:
sunboyy 2022-11-12 16:09:59 +07:00 committed by GitHub
parent 482dd095a6
commit 1e0ab5d701
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
9 changed files with 232 additions and 23 deletions
internal/testutils

View file

@ -5,6 +5,60 @@ import (
"strings"
)
// lineMismatchedError is an error indicating unmatched line when comparing
// string using ExpectMultiLineString.
type lineMismatchedError struct {
LineNumber int
Expected string
Received string
}
// NewLineMismatchedError is a constructor for lineMismatchedError.
func NewLineMismatchedError(lineNumber int, expected, received string) error {
return lineMismatchedError{
LineNumber: lineNumber,
Expected: expected,
Received: received,
}
}
func (err lineMismatchedError) Error() string {
return fmt.Sprintf("at line %d\nexpected: %v\nreceived: %v", err.LineNumber,
err.Expected, err.Received)
}
type missingLinesError struct {
MissingLines []string
}
// NewMissingLinesError is a constructor for missingLinesError.
func NewMissingLinesError(missingLines []string) error {
return missingLinesError{
MissingLines: missingLines,
}
}
func (err missingLinesError) Error() string {
return fmt.Sprintf("missing lines:\n%s",
strings.Join(err.MissingLines, "\n"))
}
type unexpectedLinesError struct {
UnexpectedLines []string
}
// NewUnexpectedLinesError is a constructor for unexpectedLinesError.
func NewUnexpectedLinesError(unexpectedLines []string) error {
return unexpectedLinesError{
UnexpectedLines: unexpectedLines,
}
}
func (err unexpectedLinesError) Error() string {
return fmt.Sprintf("unexpected lines:\n%s",
strings.Join(err.UnexpectedLines, "\n"))
}
// ExpectMultiLineString compares two multi-line strings and report the
// difference.
func ExpectMultiLineString(expected, actual string) error {
@ -18,14 +72,14 @@ func ExpectMultiLineString(expected, actual string) error {
for i := 0; i < numberOfComparableLines; i++ {
if expectedLines[i] != actualLines[i] {
return fmt.Errorf("at line %d\nexpected: %v\nreceived: %v", i+1, expectedLines[i], actualLines[i])
return NewLineMismatchedError(i+1, expectedLines[i], actualLines[i])
}
}
if len(expectedLines) < len(actualLines) {
return fmt.Errorf("unexpected lines:\n%s", strings.Join(actualLines[len(expectedLines):], "\n"))
return NewUnexpectedLinesError(actualLines[len(expectedLines):])
} else if len(expectedLines) > len(actualLines) {
return fmt.Errorf("missing lines:\n%s", strings.Join(expectedLines[len(actualLines):], "\n"))
return NewMissingLinesError(expectedLines[len(actualLines):])
}
return nil