util_test.go 8.5 KB

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