Skip to content
This repository has been archived by the owner on Jan 13, 2024. It is now read-only.

Commit

Permalink
feat: added described.As matcher
Browse files Browse the repository at this point in the history
  • Loading branch information
maurofran committed Apr 3, 2022
1 parent fa51eed commit c0b4d1f
Showing 1 changed file with 45 additions and 0 deletions.
45 changes: 45 additions & 0 deletions described/as.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package described

import (
"github.com/maurofran/hamcrest4go/matcher"
"regexp"
"strconv"
"strings"
)

var argPattern = regexp.MustCompile("%([0-9]+)")

// As gets a description decorator matcher.
func As[T any](template string, matcher matcher.Matcher[T], args ...interface{}) matcher.Matcher[T] {
return as[T]{
matcher: matcher,
template: template,
args: args,
}
}

type as[T any] struct {
matcher matcher.Matcher[T]
template string
args []interface{}
}

func (a as[T]) Matches(value T) bool {
return a.matcher.Matches(value)
}

func (a as[T]) DescribeTo(description matcher.Description) {
parts := argPattern.Split(a.template, -1)
for _, part := range parts {
if strings.HasPrefix(part, "%") {
idx, _ := strconv.Atoi(part[1:])
description.AppendValue(a.args[idx])
} else {
description.AppendText(part)
}
}
}

func (a as[T]) DescribeMismatch(actual T, description matcher.Description) {
a.matcher.DescribeMismatch(actual, description)
}

0 comments on commit c0b4d1f

Please sign in to comment.