util_test.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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. require.Nil(t, err)
  97. require.Equal(t, int64(10*1024*1024*1024), s)
  98. }
  99. func TestParseSize_10MUpperCaseSuccess(t *testing.T) {
  100. s, err := ParseSize("10M")
  101. require.Nil(t, err)
  102. require.Equal(t, int64(10*1024*1024), s)
  103. }
  104. func TestParseSize_10kLowerCaseSuccess(t *testing.T) {
  105. s, err := ParseSize("10k")
  106. require.Nil(t, err)
  107. require.Equal(t, int64(10*1024), s)
  108. }
  109. func TestParseSize_FailureInvalid(t *testing.T) {
  110. _, err := ParseSize("not a size")
  111. require.Error(t, err)
  112. }
  113. func TestFormatSize(t *testing.T) {
  114. values := []struct {
  115. size int64
  116. expected string
  117. }{
  118. {10, "10"},
  119. {10 * 1024, "10K"},
  120. {10 * 1024 * 1024, "10M"},
  121. {10 * 1024 * 1024 * 1024, "10G"},
  122. }
  123. for _, value := range values {
  124. require.Equal(t, value.expected, FormatSize(value.size))
  125. s, err := ParseSize(FormatSize(value.size))
  126. require.Nil(t, err)
  127. require.Equalf(t, value.size, s, "size does not match: %d != %d", value.size, s)
  128. }
  129. }
  130. func TestFormatSize_Rounded(t *testing.T) {
  131. require.Equal(t, "10K", FormatSize(10*1024+999))
  132. }
  133. func TestSplitKV(t *testing.T) {
  134. key, value := SplitKV(" key = value ", "=")
  135. require.Equal(t, "key", key)
  136. require.Equal(t, "value", value)
  137. key, value = SplitKV(" value ", "=")
  138. require.Equal(t, "", key)
  139. require.Equal(t, "value", value)
  140. key, value = SplitKV("mykey=value=with=separator ", "=")
  141. require.Equal(t, "mykey", key)
  142. require.Equal(t, "value=with=separator", value)
  143. }
  144. func TestLastString(t *testing.T) {
  145. require.Equal(t, "last", LastString([]string{"first", "second", "last"}, "default"))
  146. require.Equal(t, "default", LastString([]string{}, "default"))
  147. }
  148. func TestQuoteCommand(t *testing.T) {
  149. require.Equal(t, `ls -al "Document Folder"`, QuoteCommand([]string{"ls", "-al", "Document Folder"}))
  150. require.Equal(t, `rsync -av /home/phil/ root@example.com:/home/phil/`, QuoteCommand([]string{"rsync", "-av", "/home/phil/", "root@example.com:/home/phil/"}))
  151. require.Equal(t, `/home/sweet/home "Äöü this is a test" "\a\b"`, QuoteCommand([]string{"/home/sweet/home", "Äöü this is a test", "\\a\\b"}))
  152. }
  153. func TestBasicAuth(t *testing.T) {
  154. require.Equal(t, "Basic cGhpbDpwaGls", BasicAuth("phil", "phil"))
  155. }
  156. func TestBearerAuth(t *testing.T) {
  157. require.Equal(t, "Bearer sometoken", BearerAuth("sometoken"))
  158. }
  159. type testJSON struct {
  160. Name string `json:"name"`
  161. Something int `json:"something"`
  162. }
  163. func TestReadJSON_Success(t *testing.T) {
  164. v, err := UnmarshalJSON[testJSON](io.NopCloser(strings.NewReader(`{"name":"some name","something":99}`)))
  165. require.Nil(t, err)
  166. require.Equal(t, "some name", v.Name)
  167. require.Equal(t, 99, v.Something)
  168. }
  169. func TestReadJSON_Failure(t *testing.T) {
  170. _, err := UnmarshalJSON[testJSON](io.NopCloser(strings.NewReader(`{"na`)))
  171. require.Equal(t, ErrUnmarshalJSON, err)
  172. }
  173. func TestReadJSONWithLimit_Success(t *testing.T) {
  174. v, err := UnmarshalJSONWithLimit[testJSON](io.NopCloser(strings.NewReader(`{"name":"some name","something":99}`)), 100, false)
  175. require.Nil(t, err)
  176. require.Equal(t, "some name", v.Name)
  177. require.Equal(t, 99, v.Something)
  178. }
  179. func TestReadJSONWithLimit_FailureTooLong(t *testing.T) {
  180. _, err := UnmarshalJSONWithLimit[testJSON](io.NopCloser(strings.NewReader(`{"name":"some name","something":99}`)), 10, false)
  181. require.Equal(t, ErrTooLargeJSON, err)
  182. }
  183. func TestReadJSONWithLimit_AllowEmpty(t *testing.T) {
  184. v, err := UnmarshalJSONWithLimit[testJSON](io.NopCloser(strings.NewReader(` `)), 10, true)
  185. require.Nil(t, err)
  186. require.Equal(t, "", v.Name)
  187. require.Equal(t, 0, v.Something)
  188. }
  189. func TestReadJSONWithLimit_NoAllowEmpty(t *testing.T) {
  190. _, err := UnmarshalJSONWithLimit[testJSON](io.NopCloser(strings.NewReader(` `)), 10, false)
  191. require.Equal(t, ErrUnmarshalJSON, err)
  192. }
  193. func TestRetry_Succeeds(t *testing.T) {
  194. start := time.Now()
  195. delays, i := []time.Duration{10 * time.Millisecond, 50 * time.Millisecond, 100 * time.Millisecond, time.Second}, 0
  196. fn := func() (*int, error) {
  197. i++
  198. if i < len(delays) {
  199. return nil, errors.New("error")
  200. }
  201. return Int(99), nil
  202. }
  203. result, err := Retry[int](fn, delays...)
  204. require.Nil(t, err)
  205. require.Equal(t, 99, *result)
  206. require.True(t, time.Since(start).Milliseconds() > 150)
  207. }
  208. func TestRetry_Fails(t *testing.T) {
  209. fn := func() (*int, error) {
  210. return nil, errors.New("fails")
  211. }
  212. _, err := Retry[int](fn, 10*time.Millisecond)
  213. require.Error(t, err)
  214. }
  215. func TestMinMax(t *testing.T) {
  216. require.Equal(t, 10, MinMax(9, 10, 99))
  217. require.Equal(t, 99, MinMax(100, 10, 99))
  218. require.Equal(t, 50, MinMax(50, 10, 99))
  219. }
  220. func TestMax(t *testing.T) {
  221. require.Equal(t, 9, Max(1, 9))
  222. require.Equal(t, 9, Max(9, 1))
  223. require.Equal(t, rate.Every(time.Minute), Max(rate.Every(time.Hour), rate.Every(time.Minute)))
  224. }
  225. func TestPointerFunctions(t *testing.T) {
  226. i, s, ti := Int(99), String("abc"), Time(time.Unix(99, 0))
  227. require.Equal(t, 99, *i)
  228. require.Equal(t, "abc", *s)
  229. require.Equal(t, time.Unix(99, 0), *ti)
  230. }
  231. func TestMaybeMarshalJSON(t *testing.T) {
  232. require.Equal(t, `"aa"`, MaybeMarshalJSON("aa"))
  233. require.Equal(t, `[
  234. "aa",
  235. "bb"
  236. ]`, MaybeMarshalJSON([]string{"aa", "bb"}))
  237. require.Equal(t, "<cannot serialize>", MaybeMarshalJSON(func() {}))
  238. require.Equal(t, `"`+strings.Repeat("x", 4999), MaybeMarshalJSON(strings.Repeat("x", 6000)))
  239. }