github.com/go-spring/spring-base@v1.1.3/assert/string.go (about)

     1  /*
     2   * Copyright 2012-2019 the original author or authors.
     3   *
     4   * Licensed under the Apache License, Version 2.0 (the "License");
     5   * you may not use this file except in compliance with the License.
     6   * You may obtain a copy of the License at
     7   *
     8   *      https://www.apache.org/licenses/LICENSE-2.0
     9   *
    10   * Unless required by applicable law or agreed to in writing, software
    11   * distributed under the License is distributed on an "AS IS" BASIS,
    12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13   * See the License for the specific language governing permissions and
    14   * limitations under the License.
    15   */
    16  
    17  package assert
    18  
    19  import (
    20  	"fmt"
    21  	"strings"
    22  )
    23  
    24  // StringAssertion assertion for type string.
    25  type StringAssertion struct {
    26  	t T
    27  	v string
    28  }
    29  
    30  // String returns an assertion for type string.
    31  func String(t T, v string) *StringAssertion {
    32  	return &StringAssertion{
    33  		t: t,
    34  		v: v,
    35  	}
    36  }
    37  
    38  // EqualFold assertion failed when v doesn't equal to `s` under Unicode case-folding.
    39  func (a *StringAssertion) EqualFold(s string, msg ...string) {
    40  	a.t.Helper()
    41  	if !strings.EqualFold(a.v, s) {
    42  		fail(a.t, fmt.Sprintf("'%s' doesn't equal fold to '%s'", a.v, s), msg...)
    43  	}
    44  }
    45  
    46  // HasPrefix assertion failed when v doesn't have prefix `prefix`.
    47  func (a *StringAssertion) HasPrefix(prefix string, msg ...string) *StringAssertion {
    48  	a.t.Helper()
    49  	if !strings.HasPrefix(a.v, prefix) {
    50  		fail(a.t, fmt.Sprintf("'%s' doesn't have prefix '%s'", a.v, prefix), msg...)
    51  	}
    52  	return a
    53  }
    54  
    55  // HasSuffix assertion failed when v doesn't have suffix `suffix`.
    56  func (a *StringAssertion) HasSuffix(suffix string, msg ...string) *StringAssertion {
    57  	a.t.Helper()
    58  	if !strings.HasSuffix(a.v, suffix) {
    59  		fail(a.t, fmt.Sprintf("'%s' doesn't have suffix '%s'", a.v, suffix), msg...)
    60  	}
    61  	return a
    62  }
    63  
    64  // Contains assertion failed when v doesn't contain substring `substr`.
    65  func (a *StringAssertion) Contains(substr string, msg ...string) *StringAssertion {
    66  	a.t.Helper()
    67  	if !strings.Contains(a.v, substr) {
    68  		fail(a.t, fmt.Sprintf("'%s' doesn't contain substr '%s'", a.v, substr), msg...)
    69  	}
    70  	return a
    71  }