util_test.go 8.3 KB

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