// Copyright 2017 The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package strings
import (
"fmt"
"html/template"
"testing"
"github.com/gohugoio/hugo/deps"
"github.com/spf13/cast"
"github.com/spf13/viper"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
var ns = New(&deps.Deps{Cfg: viper.New()})
type tstNoStringer struct{}
func TestChomp(t *testing.T) {
t.Parallel()
for i, test := range []struct {
s interface{}
expect interface{}
}{
{"\n a\n", "\n a"},
{"\n a\n\n", "\n a"},
{"\n a\r\n", "\n a"},
{"\n a\n\r\n", "\n a"},
{"\n a\r\r", "\n a"},
{"\n a\r", "\n a"},
// errors
{tstNoStringer{}, false},
} {
errMsg := fmt.Sprintf("[%d] %v", i, test)
result, err := ns.Chomp(test.s)
if b, ok := test.expect.(bool); ok && !b {
require.Error(t, err, errMsg)
continue
}
require.NoError(t, err, errMsg)
assert.Equal(t, test.expect, result, errMsg)
// repeat the check with template.HTML input
result, err = ns.Chomp(template.HTML(cast.ToString(test.s)))
require.NoError(t, err, errMsg)
assert.Equal(t, template.HTML(cast.ToString(test.expect)), result, errMsg)
}
}
func TestContains(t *testing.T) {
t.Parallel()
for i, test := range []struct {
s interface{}
substr interface{}
expect bool
isErr bool
}{
{"", "", true, false},
{"123", "23", true, false},
{"123", "234", false, false},
{"123", "", true, false},
{"", "a", false, false},
{123, "23", true, false},
{123, "234", false, false},
{123, "", true, false},
{template.HTML("123"), []byte("23"), true, false},
{template.HTML("123"), []byte("234"), false, false},
{template.HTML("123"), []byte(""), true, false},
// errors
{"", tstNoStringer{}, false, true},
{tstNoStringer{}, "", false, true},
} {
errMsg := fmt.Sprintf("[%d] %v", i, test)
result, err := ns.Contains(test.s, test.substr)
if test.isErr {
require.Error(t, err, errMsg)
continue
}
require.NoError(t, err, errMsg)
assert.Equal(t, test.expect, result, errMsg)
}
}
func TestContainsAny(t *testing.T) {
t.Parallel()
for i, test := range []struct {
s interface{}
substr interface{}
expect bool
isErr bool
}{
{"", "", false, false},
{"", "1", false, false},