go.charczuk.com@v0.0.0-20240327042549-bc490516bd1a/sdk/assert/it_matches.go (about)

     1  /*
     2  
     3  Copyright (c) 2023 - Present. Will Charczuk. All rights reserved.
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file at the root of the repository.
     5  
     6  */
     7  
     8  package assert
     9  
    10  import (
    11  	"fmt"
    12  	"regexp"
    13  	"testing"
    14  )
    15  
    16  // ItMatches is a test helper to verify that an expression matches a given string.
    17  func ItMatches(t *testing.T, expr string, actual any, message ...any) {
    18  	t.Helper()
    19  	if !matches(expr, actual) {
    20  		Fatalf(t, "expected %v to match %v", []any{actual, expr}, message)
    21  	}
    22  }
    23  
    24  // ItNotMatches is a test helper to verify that an expression does not match a given string.
    25  func ItNotMatches(t *testing.T, expr string, actual any, message ...any) {
    26  	t.Helper()
    27  	if matches(expr, actual) {
    28  		Fatalf(t, "expected %v not to match %v", []any{actual, expr}, message)
    29  	}
    30  }
    31  
    32  func matches(expr string, actual any) bool {
    33  	compiled := regexp.MustCompile(expr)
    34  	return compiled.MatchString(fmt.Sprint(actual))
    35  }