Skip to content

Commit

Permalink
common: Replace StringDataCompare with slices.Contains and cleanup st…
Browse files Browse the repository at this point in the history
…ring funcs
  • Loading branch information
thrasher- committed Aug 19, 2024
1 parent 17c2ef2 commit a11ddd3
Show file tree
Hide file tree
Showing 31 changed files with 200 additions and 333 deletions.
2 changes: 1 addition & 1 deletion cmd/apichecker/apicheck.go
Original file line number Diff line number Diff line change
Expand Up @@ -309,7 +309,7 @@ func checkMissingExchanges() []string {
}
supportedExchs := exchange.Exchanges
for z := 0; z < len(supportedExchs); {
if common.StringDataContainsInsensitive(tempArray, supportedExchs[z]) {
if common.StringSliceContainsInsensitive(tempArray, supportedExchs[z]) {
supportedExchs = append(supportedExchs[:z], supportedExchs[z+1:]...)
continue
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"errors"
"os"
"reflect"
"slices"
"strings"
"testing"
"time"
Expand Down Expand Up @@ -51,14 +52,14 @@ func TestAllExchangeWrappers(t *testing.T) {
name := strings.ToLower(cfg.Exchanges[i].Name)
t.Run(name+" wrapper tests", func(t *testing.T) {
t.Parallel()
if common.StringDataContains(unsupportedExchangeNames, name) {
if slices.Contains(unsupportedExchangeNames, name) {
t.Skipf("skipping unsupported exchange %v", name)
}
if singleExchangeOverride != "" && name != singleExchangeOverride {
t.Skip("skipping ", name, " due to override")
}
ctx := context.Background()
if isCITest() && common.StringDataContains(blockedCIExchanges, name) {
if isCITest() && slices.Contains(blockedCIExchanges, name) {
// rather than skipping tests where execution is blocked, provide an expired
// context, so no executions can take place
var cancelFn context.CancelFunc
Expand Down
98 changes: 26 additions & 72 deletions common/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import (
"os"
"os/user"
"path/filepath"
"reflect"
"regexp"
"slices"
"strconv"
Expand Down Expand Up @@ -135,66 +134,42 @@ func NewHTTPClientWithTimeout(t time.Duration) *http.Client {
return h
}

// StringSliceDifference concatenates slices together based on its index and
// returns an individual string array
func StringSliceDifference(slice1, slice2 []string) []string {
var diff []string
for i := range 2 {
for _, s1 := range slice1 {
found := false
for _, s2 := range slice2 {
if s1 == s2 {
found = true
break
}
}
if !found {
diff = append(diff, s1)
}
// SliceDifference returns the elements that are in slice1 or slice2 but not in both
func SliceDifference[T comparable](slice1, slice2 []T) []T {
var diff []T
for x := range slice1 {
if !slices.Contains(slice2, slice1[x]) {
diff = append(diff, slice1[x])
}
if i == 0 {
slice1, slice2 = slice2, slice1
}
for x := range slice2 {
if !slices.Contains(slice1, slice2[x]) {
diff = append(diff, slice2[x])
}
}
return diff
}

// StringDataContains checks the substring array with an input and returns a bool
func StringDataContains(haystack []string, needle string) bool {
data := strings.Join(haystack, ",")
return strings.Contains(data, needle)
}

// StringDataCompare data checks the substring array with an input and returns a bool
func StringDataCompare(haystack []string, needle string) bool {
for x := range haystack {
if haystack[x] == needle {
return true
}
}
return false
// StringSliceContains returns whether case sensitive needle is contained within haystack
func StringSliceContains(haystack []string, needle string) bool {
return slices.ContainsFunc(haystack, func(s string) bool {
return strings.Contains(s, needle)
})
}

// StringDataCompareInsensitive data checks the substring array with an input and returns
// a bool irrespective of lower or upper case strings
func StringDataCompareInsensitive(haystack []string, needle string) bool {
for x := range haystack {
if strings.EqualFold(haystack[x], needle) {
return true
}
}
return false
// StringSliceCompareInsensitive returns whether case insensitive needle exists within haystack
func StringSliceCompareInsensitive(haystack []string, needle string) bool {
return slices.ContainsFunc(haystack, func(s string) bool {
return strings.EqualFold(s, needle)
})
}

// StringDataContainsInsensitive checks the substring array with an input and returns
// a bool irrespective of lower or upper case strings
func StringDataContainsInsensitive(haystack []string, needle string) bool {
for _, data := range haystack {
if strings.Contains(strings.ToUpper(data), strings.ToUpper(needle)) {
return true
}
}
return false
// StringSliceContainsInsensitive returns whether case insensitive needle is contained within haystack
func StringSliceContainsInsensitive(haystack []string, needle string) bool {
needleUpper := strings.ToUpper(needle)
return slices.ContainsFunc(haystack, func(s string) bool {
return strings.Contains(strings.ToUpper(s), needleUpper)
})
}

// IsEnabled takes in a boolean param and returns a string if it is enabled
Expand Down Expand Up @@ -421,27 +396,6 @@ func AddPaddingOnUpperCase(s string) string {
return strings.Join(result, " ")
}

// InArray checks if _val_ belongs to _array_
func InArray(val, array interface{}) (exists bool, index int) {
exists = false
index = -1
if array == nil {
return
}
switch reflect.TypeOf(array).Kind() {
case reflect.Array, reflect.Slice:
s := reflect.ValueOf(array)
for i := range s.Len() {
if reflect.DeepEqual(val, s.Index(i).Interface()) {
index = i
exists = true
return
}
}
}
return
}

// fmtError holds a formatted msg and the errors which formatted it
type fmtError struct {
errs []error
Expand Down
128 changes: 22 additions & 106 deletions common/common_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import (
"os"
"os/user"
"path/filepath"
"reflect"
"runtime"
"strconv"
"strings"
Expand Down Expand Up @@ -236,85 +235,41 @@ func TestIsValidCryptoAddress(t *testing.T) {
}
}

func TestStringSliceDifference(t *testing.T) {
func TestSliceDifference(t *testing.T) {
t.Parallel()
originalInputOne := []string{"hello"}
originalInputTwo := []string{"hello", "moto"}
expectedOutput := []string{"hello moto"}
actualResult := StringSliceDifference(originalInputOne, originalInputTwo)
if reflect.DeepEqual(expectedOutput, actualResult) {
t.Errorf("Expected '%s'. Actual '%s'",
expectedOutput, actualResult)
}
}

func TestStringDataContains(t *testing.T) {
t.Parallel()
originalHaystack := []string{"hello", "world", "USDT", "Contains", "string"}
originalNeedle := "USD"
anotherNeedle := "thing"
actualResult := StringDataContains(originalHaystack, originalNeedle)
if expectedOutput := true; actualResult != expectedOutput {
t.Errorf("Expected '%v'. Actual '%v'",
expectedOutput, actualResult)
}
actualResult = StringDataContains(originalHaystack, anotherNeedle)
if expectedOutput := false; actualResult != expectedOutput {
t.Errorf("Expected '%v'. Actual '%v'",
expectedOutput, actualResult)
}
assert.ElementsMatch(t, []string{"world", "go"}, SliceDifference([]string{"hello", "world"}, []string{"hello", "go"}))
assert.ElementsMatch(t, []int64{1, 2, 5, 6}, SliceDifference([]int64{1, 2, 3, 4}, []int64{3, 4, 5, 6}))
assert.ElementsMatch(t, []float64{1.1, 4.4}, SliceDifference([]float64{1.1, 2.2, 3.3}, []float64{2.2, 3.3, 4.4}))
type mixedType struct {
A string
B int
}
assert.ElementsMatch(t, []mixedType{{"A", 1}, {"D", 4}}, SliceDifference([]mixedType{{"A", 1}, {"B", 2}, {"C", 3}}, []mixedType{{"B", 2}, {"C", 3}, {"D", 4}}))
assert.ElementsMatch(t, []int{1, 2, 3}, SliceDifference([]int{}, []int{1, 2, 3}))
assert.ElementsMatch(t, []int{1, 2, 3}, SliceDifference([]int{1, 2, 3}, []int{}))
assert.Empty(t, SliceDifference([]int{}, []int{}))
}

func TestStringDataCompare(t *testing.T) {
func TestStringSliceContains(t *testing.T) {
t.Parallel()
originalHaystack := []string{"hello", "WoRld", "USDT", "Contains", "string"}
originalNeedle := "WoRld"
anotherNeedle := "USD"
actualResult := StringDataCompare(originalHaystack, originalNeedle)
if expectedOutput := true; actualResult != expectedOutput {
t.Errorf("Expected '%v'. Actual '%v'",
expectedOutput, actualResult)
}
actualResult = StringDataCompare(originalHaystack, anotherNeedle)
if expectedOutput := false; actualResult != expectedOutput {
t.Errorf("Expected '%v'. Actual '%v'",
expectedOutput, actualResult)
}
originalHaystack := []string{"hello", "world", "USDT", "Contains", "string"}
assert.True(t, StringSliceContains(originalHaystack, "USD"), "Should contain 'USD'")
assert.False(t, StringSliceContains(originalHaystack, "thing"), "Should not contain 'thing'")
}

func TestStringDataCompareUpper(t *testing.T) {
func TestStringSliceCompareInsensitive(t *testing.T) {
t.Parallel()
originalHaystack := []string{"hello", "WoRld", "USDT", "Contains", "string"}
originalNeedle := "WoRld"
anotherNeedle := "WoRldD"
actualResult := StringDataCompareInsensitive(originalHaystack, originalNeedle)
if expectedOutput := true; actualResult != expectedOutput {
t.Errorf("Expected '%v'. Actual '%v'",
expectedOutput, actualResult)
}

actualResult = StringDataCompareInsensitive(originalHaystack, anotherNeedle)
if expectedOutput := false; actualResult != expectedOutput {
t.Errorf("Expected '%v'. Actual '%v'",
expectedOutput, actualResult)
}
assert.False(t, StringSliceCompareInsensitive(originalHaystack, "USD"), "Should not contain 'USD'")
assert.True(t, StringSliceCompareInsensitive(originalHaystack, "WORLD"), "Should find 'WoRld'")
}

func TestStringDataContainsUpper(t *testing.T) {
func TestStringSliceContainsInsensitive(t *testing.T) {
t.Parallel()
originalHaystack := []string{"bLa", "BrO", "sUp"}
originalNeedle := "Bla"
anotherNeedle := "ning"
actualResult := StringDataContainsInsensitive(originalHaystack, originalNeedle)
if expectedOutput := true; actualResult != expectedOutput {
t.Errorf("Expected '%v'. Actual '%v'",
expectedOutput, actualResult)
}
actualResult = StringDataContainsInsensitive(originalHaystack, anotherNeedle)
if expectedOutput := false; actualResult != expectedOutput {
t.Errorf("Expected '%v'. Actual '%v'",
expectedOutput, actualResult)
}
assert.True(t, StringSliceContainsInsensitive(originalHaystack, "Bla"), "Should contain 'Bla'")
assert.False(t, StringSliceContainsInsensitive(originalHaystack, "ning"), "Should not contain 'ning'")
}

func TestYesOrNo(t *testing.T) {
Expand Down Expand Up @@ -589,45 +544,6 @@ func TestAddPaddingOnUpperCase(t *testing.T) {
}
}

func TestInArray(t *testing.T) {
t.Parallel()
InArray(nil, nil)

array := [6]int{2, 3, 5, 7, 11, 13}
isIn, pos := InArray(5, array)
if !isIn {
t.Errorf("failed to find the value within the array")
}
if pos != 2 {
t.Errorf("failed return the correct position of the value in the array")
}
isIn, _ = InArray(1, array)
if isIn {
t.Errorf("found a non existent value in the array")
}

slice := make([]int, 0)
slice = append(append(slice, 5), 3)
isIn, pos = InArray(5, slice)
if !isIn {
t.Errorf("failed to find the value within the slice")
}
if pos != 0 {
t.Errorf("failed return the correct position of the value in the slice")
}
isIn, pos = InArray(3, slice)
if !isIn {
t.Errorf("failed to find the value within the slice")
}
if pos != 1 {
t.Errorf("failed return the correct position of the value in the slice")
}
isIn, _ = InArray(1, slice)
if isIn {
t.Errorf("found a non existent value in the slice")
}
}

func TestErrors(t *testing.T) {
t.Parallel()

Expand Down
7 changes: 4 additions & 3 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"os"
"path/filepath"
"runtime"
"slices"
"strconv"
"strings"
"time"
Expand Down Expand Up @@ -49,7 +50,7 @@ func (c *Config) GetExchangeBankAccounts(exchangeName, id, depositingCurrency st
if strings.EqualFold(c.Exchanges[x].Name, exchangeName) {
for y := range c.Exchanges[x].BankAccounts {
if strings.EqualFold(c.Exchanges[x].BankAccounts[y].ID, id) {
if common.StringDataCompareInsensitive(
if common.StringSliceCompareInsensitive(
strings.Split(c.Exchanges[x].BankAccounts[y].SupportedCurrencies, ","),
depositingCurrency) {
return &c.Exchanges[x].BankAccounts[y], nil
Expand Down Expand Up @@ -1162,7 +1163,7 @@ func (c *Config) CheckCurrencyConfigValues() error {
}

for i := range c.Currency.ForexProviders {
if !common.StringDataContainsInsensitive(supported, c.Currency.ForexProviders[i].Name) {
if !common.StringSliceContainsInsensitive(supported, c.Currency.ForexProviders[i].Name) {
log.Warnf(log.ConfigMgr,
"%s forex provider not supported, please remove from config.\n",
c.Currency.ForexProviders[i].Name)
Expand Down Expand Up @@ -1307,7 +1308,7 @@ func (c *Config) checkDatabaseConfig() error {
return nil
}

if !common.StringDataCompare(database.SupportedDrivers, c.Database.Driver) {
if !slices.Contains(database.SupportedDrivers, c.Database.Driver) {
c.Database.Enabled = false
return fmt.Errorf("unsupported database driver %v, database disabled", c.Database.Driver)
}
Expand Down
16 changes: 5 additions & 11 deletions config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"os"
"path/filepath"
"runtime"
"slices"
"strings"
"testing"
"time"
Expand Down Expand Up @@ -1110,7 +1111,7 @@ func TestGetEnabledExchanges(t *testing.T) {
}}

exchanges := cfg.GetEnabledExchanges()
if !common.StringDataCompare(exchanges, bfx) {
if !slices.Contains(exchanges, bfx) {
t.Error(
"TestGetEnabledExchanges. Expected exchange Bitfinex not found",
)
Expand Down Expand Up @@ -1730,18 +1731,11 @@ func TestCheckConnectionMonitorConfig(t *testing.T) {
t.Parallel()

var c Config
c.ConnectionMonitor.CheckInterval = 0
c.ConnectionMonitor.DNSList = nil
c.ConnectionMonitor.PublicDomainList = nil
c.CheckConnectionMonitorConfig()

if c.ConnectionMonitor.CheckInterval != connchecker.DefaultCheckInterval ||
len(common.StringSliceDifference(
c.ConnectionMonitor.DNSList, connchecker.DefaultDNSList)) != 0 ||
len(common.StringSliceDifference(
c.ConnectionMonitor.PublicDomainList, connchecker.DefaultDomainList)) != 0 {
t.Error("unexpected values")
}
assert.Equal(t, connchecker.DefaultCheckInterval, c.ConnectionMonitor.CheckInterval)
assert.Equal(t, connchecker.DefaultDNSList, c.ConnectionMonitor.DNSList)
assert.Equal(t, connchecker.DefaultDomainList, c.ConnectionMonitor.PublicDomainList)
}

func TestDefaultFilePath(t *testing.T) {
Expand Down
Loading

0 comments on commit a11ddd3

Please sign in to comment.