From c0b4d1f5f138864e51d2e77ba73bbc9361374e1a Mon Sep 17 00:00:00 2001 From: Mauro Franceschini Date: Sun, 3 Apr 2022 09:50:47 +0200 Subject: [PATCH] feat: added described.As matcher --- described/as.go | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 described/as.go diff --git a/described/as.go b/described/as.go new file mode 100644 index 0000000..e104864 --- /dev/null +++ b/described/as.go @@ -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) +}