util_test.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. package util
  2. import (
  3. "errors"
  4. "io"
  5. "net/netip"
  6. "os"
  7. "path/filepath"
  8. "strings"
  9. "testing"
  10. "time"
  11. "golang.org/x/time/rate"
  12. "github.com/stretchr/testify/require"
  13. )
  14. func TestRandomString(t *testing.T) {
  15. s1 := RandomString(10)
  16. s2 := RandomString(10)
  17. s3 := RandomString(12)
  18. require.Equal(t, 10, len(s1))
  19. require.Equal(t, 10, len(s2))
  20. require.Equal(t, 12, len(s3))
  21. require.NotEqual(t, s1, s2)
  22. }
  23. func TestFileExists(t *testing.T) {
  24. filename := filepath.Join(t.TempDir(), "somefile.txt")
  25. require.Nil(t, os.WriteFile(filename, []byte{0x25, 0x86}, 0600))
  26. require.True(t, FileExists(filename))
  27. require.False(t, FileExists(filename+".doesnotexist"))
  28. }
  29. func TestInStringList(t *testing.T) {
  30. s := []string{"one", "two"}
  31. require.True(t, Contains(s, "two"))
  32. require.False(t, Contains(s, "three"))
  33. }
  34. func TestInStringListAll(t *testing.T) {
  35. s := []string{"one", "two", "three", "four"}
  36. require.True(t, ContainsAll(s, []string{"two", "four"}))
  37. require.False(t, ContainsAll(s, []string{"three", "five"}))
  38. }
  39. func TestContains(t *testing.T) {
  40. s := []int{1, 2}
  41. require.True(t, Contains(s, 2))
  42. require.False(t, Contains(s, 3))
  43. }
  44. func TestContainsAll(t *testing.T) {
  45. require.True(t, ContainsAll([]int{1, 2, 3}, []int{2, 3}))
  46. require.False(t, ContainsAll([]int{1, 1}, []int{1, 2}))
  47. }
  48. func TestContainsIP(t *testing.T) {
  49. require.True(t, ContainsIP([]netip.Prefix{netip.MustParsePrefix("fd00::/8"), netip.MustParsePrefix("1.1.0.0/16")}, netip.MustParseAddr("1.1.1.1")))
  50. require.True(t, ContainsIP([]netip.Prefix{netip.MustParsePrefix("fd00::/8"), netip.MustParsePrefix("1.1.0.0/16")}, netip.MustParseAddr("fd12:1234:5678::9876")))
  51. require.False(t, ContainsIP([]netip.Prefix{netip.MustParsePrefix("fd00::/8"), netip.MustParsePrefix("1.1.0.0/16")}, netip.MustParseAddr("1.2.0.1")))
  52. require.False(t, ContainsIP([]netip.Prefix{netip.MustParsePrefix("fd00::/8"), netip.MustParsePrefix("1.1.0.0/16")}, netip.MustParseAddr("fc00::1")))
  53. }
  54. func TestSplitNoEmpty(t *testing.T) {
  55. require.Equal(t, []string{}, SplitNoEmpty("", ","))
  56. require.Equal(t, []string{}, SplitNoEmpty(",,,", ","))
  57. require.Equal(t, []string{"tag1", "tag2"}, SplitNoEmpty("tag1,tag2", ","))
  58. require.Equal(t, []string{"tag1", "tag2"}, SplitNoEmpty("tag1,tag2,", ","))
  59. }
  60. func TestParsePriority(t *testing.T) {
  61. priorities := []string{"", "1", "2", "3", "4", "5", "min", "LOW", " default ", "HIgh", "max", "urgent"}
  62. expected := []int{0, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 5}
  63. for i, priority := range priorities {
  64. actual, err := ParsePriority(priority)
  65. require.Nil(t, err)
  66. require.Equal(t, expected[i], actual)
  67. }
  68. }
  69. func TestParsePriority_Invalid(t *testing.T) {
  70. priorities := []string{"-1", "6", "aa", "-", "o=1"}
  71. for _, priority := range priorities {
  72. _, err := ParsePriority(priority)
  73. require.Equal(t, errInvalidPriority, err)
  74. }
  75. }
  76. func TestPriorityString(t *testing.T) {
  77. priorities := []int{0, 1, 2, 3, 4, 5}
  78. expected := []string{"default", "min", "low", "default", "high", "max"}
  79. for i, priority := range priorities {
  80. actual, err := PriorityString(priority)
  81. require.Nil(t, err)
  82. require.Equal(t, expected[i], actual)
  83. }
  84. }
  85. func TestPriorityString_Invalid(t *testing.T) {
  86. _, err := PriorityString(99)
  87. require.Equal(t, err, errInvalidPriority)
  88. }
  89. func TestShortTopicURL(t *testing.T) {
  90. require.Equal(t, "ntfy.sh/mytopic", ShortTopicURL("https://ntfy.sh/mytopic"))
  91. require.Equal(t, "ntfy.sh/mytopic", ShortTopicURL("http://ntfy.sh/mytopic"))
  92. require.Equal(t, "lalala", ShortTopicURL("lalala"))
  93. }
  94. func TestParseSize_10GSuccess(t *testing.T) {
  95. s, err := ParseSize("10G")
  96. if err != nil {
  97. t.Fatal(err)
  98. }
  99. require.Equal(t, int64(10*1024*1024*1024), s)
  100. }
  101. func TestParseSize_10MUpperCaseSuccess(t *testing.T) {
  102. s, err := ParseSize("10M")
  103. if err != nil {
  104. t.Fatal(err)
  105. }
  106. require.Equal(t, int64(10*1024*1024), s)
  107. }
  108. func TestParseSize_10kLowerCaseSuccess(t *testing.T) {
  109. s, err := ParseSize("10k")
  110. if err != nil {
  111. t.Fatal(err)
  112. }
  113. require.Equal(t, int64(10*1024), s)
  114. }
  115. func TestParseSize_FailureInvalid(t *testing.T) {
  116. _, err := ParseSize("not a size")
  117. if err == nil {
  118. t.Fatalf("expected error, but got none")
  119. }
  120. }
  121. func TestSplitKV(t *testing.T) {
  122. key, value := SplitKV(" key = value ", "=")
  123. require.Equal(t, "key", key)
  124. require.Equal(t, "value", value)
  125. key, value = SplitKV(" value ", "=")
  126. require.Equal(t, "", key)
  127. require.Equal(t, "value", value)
  128. key, value = SplitKV("mykey=value=with=separator ", "=")
  129. require.Equal(t, "mykey", key)
  130. require.Equal(t, "value=with=separator", value)
  131. }
  132. func TestLastString(t *testing.T) {
  133. require.Equal(t, "last", LastString([]string{"first", "second", "last"}, "default"))
  134. require.Equal(t, "default", LastString([]string{}, "default"))
  135. }
  136. func TestQuoteCommand(t *testing.T) {
  137. require.Equal(t, `ls -al "Document Folder"`, QuoteCommand([]string{"ls", "-al", "Document Folder"}))
  138. require.Equal(t, `rsync -av /home/phil/ root@example.com:/home/phil/`, QuoteCommand([]string{"rsync", "-av", "/home/phil/", "root@example.com:/home/phil/"}))
  139. require.Equal(t, `/home/sweet/home "Äöü this is a test" "\a\b"`, QuoteCommand([]string{"/home/sweet/home", "Äöü this is a test", "\\a\\b"}))
  140. }
  141. func TestBasicAuth(t *testing.T) {
  142. require.Equal(t, "Basic cGhpbDpwaGls", BasicAuth("phil", "phil"))
  143. }
  144. func TestBearerAuth(t *testing.T) {
  145. require.Equal(t, "Bearer sometoken", BearerAuth("sometoken"))
  146. }
  147. type testJSON struct {
  148. Name string `json:"name"`
  149. Something int `json:"something"`
  150. }
  151. func TestReadJSON_Success(t *testing.T) {
  152. v, err := UnmarshalJSON[testJSON](io.NopCloser(strings.NewReader(`{"name":"some name","something":99}`)))
  153. require.Nil(t, err)
  154. require.Equal(t, "some name", v.Name)
  155. require.Equal(t, 99, v.Something)
  156. }
  157. func TestReadJSON_Failure(t *testing.T) {
  158. _, err := UnmarshalJSON[testJSON](io.NopCloser(strings.NewReader(`{"na`)))
  159. require.Equal(t, ErrUnmarshalJSON, err)
  160. }
  161. func TestReadJSONWithLimit_Success(t *testing.T) {
  162. v, err := UnmarshalJSONWithLimit[testJSON](io.NopCloser(strings.NewReader(`{"name":"some name","something":99}`)), 100, false)
  163. require.Nil(t, err)
  164. require.Equal(t, "some name", v.Name)
  165. require.Equal(t, 99, v.Something)
  166. }
  167. func TestReadJSONWithLimit_FailureTooLong(t *testing.T) {
  168. _, err := UnmarshalJSONWithLimit[testJSON](io.NopCloser(strings.NewReader(`{"name":"some name","something":99}`)), 10, false)
  169. require.Equal(t, ErrTooLargeJSON, err)
  170. }
  171. func TestReadJSONWithLimit_AllowEmpty(t *testing.T) {
  172. v, err := UnmarshalJSONWithLimit[testJSON](io.NopCloser(strings.NewReader(` `)), 10, true)
  173. require.Nil(t, err)
  174. require.Equal(t, "", v.Name)
  175. require.Equal(t, 0, v.Something)
  176. }
  177. func TestReadJSONWithLimit_NoAllowEmpty(t *testing.T) {
  178. _, err := UnmarshalJSONWithLimit[testJSON](io.NopCloser(strings.NewReader(` `)), 10, false)
  179. require.Equal(t, ErrUnmarshalJSON, err)
  180. }
  181. func TestRetry_Succeeds(t *testing.T) {
  182. start := time.Now()
  183. delays, i := []time.Duration{10 * time.Millisecond, 50 * time.Millisecond, 100 * time.Millisecond, time.Second}, 0
  184. fn := func() (*int, error) {
  185. i++
  186. if i < len(delays) {
  187. return nil, errors.New("error")
  188. }
  189. return Int(99), nil
  190. }
  191. result, err := Retry[int](fn, delays...)
  192. require.Nil(t, err)
  193. require.Equal(t, 99, *result)
  194. require.True(t, time.Since(start).Milliseconds() > 150)
  195. }
  196. func TestRetry_Fails(t *testing.T) {
  197. fn := func() (*int, error) {
  198. return nil, errors.New("fails")
  199. }
  200. _, err := Retry[int](fn, 10*time.Millisecond)
  201. require.Error(t, err)
  202. }
  203. func TestMinMax(t *testing.T) {
  204. require.Equal(t, 10, MinMax(9, 10, 99))
  205. require.Equal(t, 99, MinMax(100, 10, 99))
  206. require.Equal(t, 50, MinMax(50, 10, 99))
  207. }
  208. func TestMax(t *testing.T) {
  209. require.Equal(t, 9, Max(1, 9))
  210. require.Equal(t, 9, Max(9, 1))
  211. require.Equal(t, rate.Every(time.Minute), Max(rate.Every(time.Hour), rate.Every(time.Minute)))
  212. }
  213. func TestPointerFunctions(t *testing.T) {
  214. i, s, ti := Int(99), String("abc"), Time(time.Unix(99, 0))
  215. require.Equal(t, 99, *i)
  216. require.Equal(t, "abc", *s)
  217. require.Equal(t, time.Unix(99, 0), *ti)
  218. }
  219. func TestMaybeMarshalJSON(t *testing.T) {
  220. require.Equal(t, `"aa"`, MaybeMarshalJSON("aa"))
  221. require.Equal(t, `[
  222. "aa",
  223. "bb"
  224. ]`, MaybeMarshalJSON([]string{"aa", "bb"}))
  225. require.Equal(t, "<cannot serialize>", MaybeMarshalJSON(func() {}))
  226. require.Equal(t, `"`+strings.Repeat("x", 4999), MaybeMarshalJSON(strings.Repeat("x", 6000)))
  227. }