github.com/qiniu/x@v1.11.9/bytes/replace_test.go (about)

     1  /*
     2   Copyright 2020 Qiniu Limited (qiniu.com)
     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       http://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 bytes
    18  
    19  import (
    20  	"strings"
    21  	"testing"
    22  )
    23  
    24  type replaceCase struct {
    25  	s    string
    26  	src  string
    27  	dest string
    28  	n    int
    29  }
    30  
    31  func stringReplace(b string, src, dest string, n int) string {
    32  
    33  	return string(Replace([]byte(b), []byte(src), []byte(dest), n))
    34  }
    35  
    36  func TestReplace(t *testing.T) {
    37  
    38  	cases := []replaceCase{
    39  		{"hello, world!", "world", "xsw", -1},
    40  		{"hello, world world world", "world", "xsw", 1},
    41  		{"hello, world world world", "world", "xsw", 2},
    42  		{"hello, world world world", "world", "xsw", -1},
    43  		{"hello, xsw!", "xsw", "world", -1},
    44  		{"hello, xsw xsw xsw", "xsw", "world", 1},
    45  		{"hello, xsw xsw xsw", "xsw", "world", 2},
    46  		{"hello, xsw xsw xsw", "xsw", "world", -1},
    47  	}
    48  
    49  	for _, c := range cases {
    50  		ret := stringReplace(c.s, c.src, c.dest, c.n)
    51  		expected := strings.Replace(c.s, c.src, c.dest, c.n)
    52  		if ret != expected {
    53  			t.Fatal("Replace failed:", c, "ret:", ret, "expected:", expected)
    54  		}
    55  	}
    56  }
    57  
    58  func stringInsertAt(b string, off int, text string) string {
    59  
    60  	return string(ReplaceAt([]byte(b), off, 0, []byte(text)))
    61  }
    62  
    63  func TestInsertAt(t *testing.T) {
    64  
    65  	ret := stringInsertAt("helloworld", 5, ", ")
    66  	if ret != "hello, world" {
    67  		t.Fatal("InsertAt failed:", ret)
    68  	}
    69  }