github.com/whatlly/hugo@v0.47.1/tpl/strings/regexp_test.go (about) 1 // Copyright 2017 The Hugo Authors. All rights reserved. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // http://www.apache.org/licenses/LICENSE-2.0 7 // 8 // Unless required by applicable law or agreed to in writing, software 9 // distributed under the License is distributed on an "AS IS" BASIS, 10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 // See the License for the specific language governing permissions and 12 // limitations under the License. 13 14 package strings 15 16 import ( 17 "fmt" 18 "testing" 19 20 "github.com/stretchr/testify/assert" 21 "github.com/stretchr/testify/require" 22 ) 23 24 func TestFindRE(t *testing.T) { 25 t.Parallel() 26 27 for i, test := range []struct { 28 expr string 29 content interface{} 30 limit interface{} 31 expect interface{} 32 }{ 33 {"[G|g]o", "Hugo is a static site generator written in Go.", 2, []string{"go", "Go"}}, 34 {"[G|g]o", "Hugo is a static site generator written in Go.", -1, []string{"go", "Go"}}, 35 {"[G|g]o", "Hugo is a static site generator written in Go.", 1, []string{"go"}}, 36 {"[G|g]o", "Hugo is a static site generator written in Go.", "1", []string{"go"}}, 37 {"[G|g]o", "Hugo is a static site generator written in Go.", nil, []string(nil)}, 38 // errors 39 {"[G|go", "Hugo is a static site generator written in Go.", nil, false}, 40 {"[G|g]o", t, nil, false}, 41 } { 42 errMsg := fmt.Sprintf("[%d] %v", i, test) 43 44 result, err := ns.FindRE(test.expr, test.content, test.limit) 45 46 if b, ok := test.expect.(bool); ok && !b { 47 require.Error(t, err, errMsg) 48 continue 49 } 50 51 require.NoError(t, err, errMsg) 52 assert.Equal(t, test.expect, result, errMsg) 53 } 54 } 55 56 func TestReplaceRE(t *testing.T) { 57 t.Parallel() 58 59 for i, test := range []struct { 60 pattern interface{} 61 repl interface{} 62 s interface{} 63 expect interface{} 64 }{ 65 {"^https?://([^/]+).*", "$1", "http://gohugo.io/docs", "gohugo.io"}, 66 {"^https?://([^/]+).*", "$2", "http://gohugo.io/docs", ""}, 67 {"(ab)", "AB", "aabbaab", "aABbaAB"}, 68 // errors 69 {"(ab", "AB", "aabb", false}, // invalid re 70 {tstNoStringer{}, "$2", "http://gohugo.io/docs", false}, 71 {"^https?://([^/]+).*", tstNoStringer{}, "http://gohugo.io/docs", false}, 72 {"^https?://([^/]+).*", "$2", tstNoStringer{}, false}, 73 } { 74 errMsg := fmt.Sprintf("[%d] %v", i, test) 75 76 result, err := ns.ReplaceRE(test.pattern, test.repl, test.s) 77 78 if b, ok := test.expect.(bool); ok && !b { 79 require.Error(t, err, errMsg) 80 continue 81 } 82 83 require.NoError(t, err, errMsg) 84 assert.Equal(t, test.expect, result, errMsg) 85 } 86 }