functions_test.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package template // import "miniflux.app/v2/internal/template"
  4. import (
  5. "html/template"
  6. "strings"
  7. "testing"
  8. "time"
  9. "miniflux.app/v2/internal/locale"
  10. )
  11. func TestDict(t *testing.T) {
  12. d, err := dict("k1", "v1", "k2", "v2")
  13. if err != nil {
  14. t.Fatalf(`The dict should be valid: %v`, err)
  15. }
  16. if value, found := d["k1"]; found {
  17. if value != "v1" {
  18. t.Fatalf(`Unexpected value for k1: got %q`, value)
  19. }
  20. }
  21. if value, found := d["k2"]; found {
  22. if value != "v2" {
  23. t.Fatalf(`Unexpected value for k2: got %q`, value)
  24. }
  25. }
  26. }
  27. func TestDictWithInvalidNumberOfArguments(t *testing.T) {
  28. _, err := dict("k1")
  29. if err == nil {
  30. t.Fatal(`An error should be returned if the number of arguments are not even`)
  31. }
  32. }
  33. func TestDictWithInvalidMap(t *testing.T) {
  34. _, err := dict(1, 2)
  35. if err == nil {
  36. t.Fatal(`An error should be returned if the dict keys are not string`)
  37. }
  38. }
  39. func TestTruncate(t *testing.T) {
  40. scenarios := []struct {
  41. name string
  42. input string
  43. max int
  44. expected string
  45. }{
  46. {
  47. name: "short ascii",
  48. input: "Short text",
  49. max: 25,
  50. expected: "Short text",
  51. },
  52. {
  53. name: "short unicode",
  54. input: "Короткий текст",
  55. max: 25,
  56. expected: "Короткий текст",
  57. },
  58. {
  59. name: "exact ascii length",
  60. input: "Short text",
  61. max: len("Short text"),
  62. expected: "Short text",
  63. },
  64. {
  65. name: "long ascii",
  66. input: "This is a really pretty long English text",
  67. max: 25,
  68. expected: "This is a really pretty l…",
  69. },
  70. {
  71. name: "long unicode",
  72. input: "Это реально очень длинный русский текст",
  73. max: 25,
  74. expected: "Это реально очень длинный…",
  75. },
  76. }
  77. for _, scenario := range scenarios {
  78. t.Run(scenario.name, func(t *testing.T) {
  79. result := truncate(scenario.input, scenario.max)
  80. if result != scenario.expected {
  81. t.Fatalf(`Unexpected output, got %q instead of %q`, result, scenario.expected)
  82. }
  83. })
  84. }
  85. }
  86. func TestTruncateInvalidMax(t *testing.T) {
  87. scenarios := []struct {
  88. name string
  89. max int
  90. }{
  91. {name: "zero", max: 0},
  92. {name: "negative", max: -1},
  93. }
  94. for _, scenario := range scenarios {
  95. t.Run(scenario.name, func(t *testing.T) {
  96. defer func() {
  97. if recover() == nil {
  98. t.Fatal("Expected panic for non-positive max")
  99. }
  100. }()
  101. _ = truncate("Short text", scenario.max)
  102. })
  103. }
  104. }
  105. func TestIsEmail(t *testing.T) {
  106. if !isEmail("user@domain.tld") {
  107. t.Fatal(`This email is valid and should returns true`)
  108. }
  109. if isEmail("invalid") {
  110. t.Fatal(`This email is not valid and should returns false`)
  111. }
  112. }
  113. func TestUntrustedURL(t *testing.T) {
  114. scenarios := map[string]template.URL{
  115. // Pass-through: schemes accepted by the sanitizer allowlist.
  116. "https://example.org/article": "https://example.org/article",
  117. "http://example.org/article": "http://example.org/article",
  118. "mailto:author@example.org": "mailto:author@example.org",
  119. "magnet:?xt=urn:btih:abc": "magnet:?xt=urn:btih:abc",
  120. "feed:https://example.org/": "feed:https://example.org/",
  121. // Rewritten to "#": schemes that enable script execution or
  122. // local-resource access, plus malformed inputs.
  123. "javascript:alert(1)": "#",
  124. "JavaScript:alert(1)": "#",
  125. "data:text/html,<script>alert(1)</script>": "#",
  126. "vbscript:msgbox(1)": "#",
  127. "file:///etc/passwd": "#",
  128. "//evil.example.org/path": "#",
  129. "/relative/path": "#",
  130. "": "#",
  131. }
  132. for input, expected := range scenarios {
  133. t.Run(input, func(t *testing.T) {
  134. if actual := untrustedURL(input); actual != expected {
  135. t.Errorf("untrustedURL(%q) = %q, want %q", input, actual, expected)
  136. }
  137. })
  138. }
  139. }
  140. func TestDuration(t *testing.T) {
  141. now := time.Now()
  142. var dt = []struct {
  143. in time.Time
  144. out string
  145. }{
  146. {time.Time{}, ""},
  147. {now.Add(time.Hour), "1h0m0s"},
  148. {now.Add(time.Minute), "1m0s"},
  149. {now.Add(time.Minute * 40), "40m0s"},
  150. {now.Add(time.Millisecond * 40), "0s"},
  151. {now.Add(time.Millisecond * 80), "0s"},
  152. {now.Add(time.Millisecond * 400), "0s"},
  153. {now.Add(time.Millisecond * 800), "1s"},
  154. {now.Add(time.Millisecond * 4321), "4s"},
  155. {now.Add(time.Millisecond * 8765), "9s"},
  156. {now.Add(time.Microsecond * 12345678), "12s"},
  157. {now.Add(time.Microsecond * 87654321), "1m28s"},
  158. }
  159. for i, tt := range dt {
  160. if out := durationImpl(tt.in, now); out != tt.out {
  161. t.Errorf(`%d. content mismatch for "%v": expected=%q got=%q`, i, tt.in, tt.out, out)
  162. }
  163. }
  164. }
  165. func TestElapsedTime(t *testing.T) {
  166. printer := locale.NewPrinter("en_US")
  167. var dt = []struct {
  168. in time.Time
  169. out string
  170. }{
  171. {time.Time{}, printer.Print("time_elapsed.not_yet")},
  172. {time.Now().Add(time.Hour), printer.Print("time_elapsed.not_yet")},
  173. {time.Now(), printer.Print("time_elapsed.now")},
  174. {time.Now().Add(-time.Minute), printer.Plural("time_elapsed.minutes", 1, 1)},
  175. {time.Now().Add(-time.Minute * 40), printer.Plural("time_elapsed.minutes", 40, 40)},
  176. {time.Now().Add(-time.Hour), printer.Plural("time_elapsed.hours", 1, 1)},
  177. {time.Now().Add(-time.Hour * 3), printer.Plural("time_elapsed.hours", 3, 3)},
  178. {time.Now().Add(-time.Hour * 32), printer.Print("time_elapsed.yesterday")},
  179. {time.Now().Add(-time.Hour * 24 * 3), printer.Plural("time_elapsed.days", 3, 3)},
  180. {time.Now().Add(-time.Hour * 24 * 14), printer.Plural("time_elapsed.days", 14, 14)},
  181. {time.Now().Add(-time.Hour * 24 * 15), printer.Plural("time_elapsed.days", 15, 15)},
  182. {time.Now().Add(-time.Hour * 24 * 21), printer.Plural("time_elapsed.weeks", 3, 3)},
  183. {time.Now().Add(-time.Hour * 24 * 32), printer.Plural("time_elapsed.months", 1, 1)},
  184. {time.Now().Add(-time.Hour * 24 * 60), printer.Plural("time_elapsed.months", 2, 2)},
  185. {time.Now().Add(-time.Hour * 24 * 366), printer.Plural("time_elapsed.years", 1, 1)},
  186. {time.Now().Add(-time.Hour * 24 * 365 * 3), printer.Plural("time_elapsed.years", 3, 3)},
  187. }
  188. for i, tt := range dt {
  189. if out := elapsedTime(printer, "Local", tt.in); out != tt.out {
  190. t.Errorf(`%d. content mismatch for "%v": expected=%q got=%q`, i, tt.in, tt.out, out)
  191. }
  192. }
  193. }
  194. func TestFormatFileSize(t *testing.T) {
  195. scenarios := []struct {
  196. input int64
  197. expected string
  198. }{
  199. {0, "0 B"},
  200. {1, "1 B"},
  201. {500, "500 B"},
  202. {1024, "1.0 KiB"},
  203. {43520, "42.5 KiB"},
  204. {5000 * 1024 * 1024, "4.9 GiB"},
  205. }
  206. for _, scenario := range scenarios {
  207. result := formatFileSize(scenario.input)
  208. if result != scenario.expected {
  209. t.Errorf(`Unexpected result, got %q instead of %q for %d`, result, scenario.expected, scenario.input)
  210. }
  211. }
  212. }
  213. func TestQueryString(t *testing.T) {
  214. params, err := dict("q", "ai", "unread", true, "offset", 20)
  215. if err != nil {
  216. t.Fatalf(`The dict should be valid: %v`, err)
  217. }
  218. got := (&funcMap{}).Map()["queryString"].(func(map[string]any) string)(params)
  219. if got == "" {
  220. t.Fatalf("Expected a query string, got an empty string")
  221. }
  222. if !strings.HasPrefix(got, "?") {
  223. t.Fatalf(`Expected query string to start with "?", got %q`, got)
  224. }
  225. if !strings.Contains(got, "q=ai") {
  226. t.Fatalf(`Expected query string to contain q=ai, got %q`, got)
  227. }
  228. if !strings.Contains(got, "unread=1") {
  229. t.Fatalf(`Expected query string to contain unread=1, got %q`, got)
  230. }
  231. if !strings.Contains(got, "offset=20") {
  232. t.Fatalf(`Expected query string to contain offset=20, got %q`, got)
  233. }
  234. empty, err := dict("q", "", "unread", false, "offset", 0)
  235. if err != nil {
  236. t.Fatalf(`The dict should be valid: %v`, err)
  237. }
  238. got = (&funcMap{}).Map()["queryString"].(func(map[string]any) string)(empty)
  239. if got != "" {
  240. t.Fatalf(`Expected empty query string, got %q`, got)
  241. }
  242. }