Skip to content

Commit

Permalink
feat: add strutil (#10)
Browse files Browse the repository at this point in the history
* add strutil

* add strutil unit tests

* update strutil unit tests
  • Loading branch information
shipengqi authored Aug 29, 2022
1 parent c26ffa5 commit 2a77532
Show file tree
Hide file tree
Showing 3 changed files with 90 additions and 0 deletions.
2 changes: 2 additions & 0 deletions strutil/doc.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
// Package strutil is common string utils for Go.
package strutil
20 changes: 20 additions & 0 deletions strutil/str.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package strutil

import "strings"

// EqualsIgnoreCase check if str1 is equal to str2 ignoring case sensitivity
func EqualsIgnoreCase(str1, str2 string) bool {
// SA6005 - Inefficient string comparison with strings.ToLower or strings.ToUpper
// if strings.ToLower(s1) == strings.ToLower(s2) { ... }
return strings.EqualFold(str1, str2)
}

// ContainsIgnoreCase check if str1 contains str2 ignoring case sensitivity
func ContainsIgnoreCase(str1, str2 string) bool {
return strings.Contains(strings.ToLower(str1), strings.ToLower(str2))
}

// IsEmpty check if value is empty string or blank string.
func IsEmpty(str string) bool {
return strings.TrimSpace(str) == ""
}
68 changes: 68 additions & 0 deletions strutil/str_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package strutil

import (
"fmt"
"testing"

"github.com/stretchr/testify/assert"
)

func TestContainsIgnoreCase(t *testing.T) {
tests := []struct {
title string
input string
input2 string
expected bool
}{
{"should be true", "test lower case", "LoWer", true},
{"should be false", "test lower case", "LLL", false},
{"should be true", "TEST UPPER CASE", "upper", true},
}

for _, v := range tests {
t.Run(fmt.Sprintf("'%s' contains '%s' %s", v.input, v.input2, v.title), func(t *testing.T) {
got := ContainsIgnoreCase(v.input, v.input2)
assert.Equal(t, v.expected, got)
})
}
}

func TestEqualsIgnoreCase(t *testing.T) {
tests := []struct {
title string
input string
input2 string
expected bool
}{
{"should be true", "lower", "LoWer", true},
{"should be true", "lower", "LOWER", true},
{"should be true", "UPPER", "upper", true},
{"should be false", "UPPER", "u", false},
}

for _, v := range tests {
t.Run(fmt.Sprintf("'%s' equals '%s' %s", v.input, v.input2, v.title), func(t *testing.T) {
got := EqualsIgnoreCase(v.input, v.input2)
assert.Equal(t, v.expected, got)
})
}
}

func TestIsEmpty(t *testing.T) {
tests := []struct {
title string
input string
expected bool
}{
{"should be empty", "", true},
{"blank string should be empty", " ", true},
{"line break should be empty", " \n ", true},
}

for _, v := range tests {
t.Run(v.title, func(t *testing.T) {
got := IsEmpty(v.input)
assert.Equal(t, v.expected, got)
})
}
}

0 comments on commit 2a77532

Please sign in to comment.