gitea源码

html_internal_test.go 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. // Copyright 2018 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package markup
  4. import (
  5. "fmt"
  6. "strconv"
  7. "strings"
  8. "testing"
  9. "code.gitea.io/gitea/modules/setting"
  10. testModule "code.gitea.io/gitea/modules/test"
  11. "code.gitea.io/gitea/modules/util"
  12. "github.com/stretchr/testify/assert"
  13. )
  14. const (
  15. TestAppURL = "http://localhost:3000/"
  16. TestRepoURL = TestAppURL + "test-owner/test-repo/"
  17. )
  18. // externalIssueLink an HTML link to an alphanumeric-style issue
  19. func externalIssueLink(baseURL, class, name string) string {
  20. return link(util.URLJoin(baseURL, name), class, name)
  21. }
  22. // numericLink an HTML to a numeric-style issue
  23. func numericIssueLink(baseURL, class string, index int, marker string) string {
  24. return link(util.URLJoin(baseURL, strconv.Itoa(index)), class, fmt.Sprintf("%s%d", marker, index))
  25. }
  26. // link an HTML link
  27. func link(href, class, contents string) string {
  28. extra := util.Iif(class != "", ` class="`+class+`"`, "")
  29. return fmt.Sprintf(`<a href="%s"%s>%s</a>`, href, extra, contents)
  30. }
  31. var numericMetas = map[string]string{
  32. "format": "https://someurl.com/{user}/{repo}/{index}",
  33. "user": "someUser",
  34. "repo": "someRepo",
  35. "style": IssueNameStyleNumeric,
  36. "markupAllowShortIssuePattern": "true",
  37. }
  38. var alphanumericMetas = map[string]string{
  39. "format": "https://someurl.com/{user}/{repo}/{index}",
  40. "user": "someUser",
  41. "repo": "someRepo",
  42. "style": IssueNameStyleAlphanumeric,
  43. "markupAllowShortIssuePattern": "true",
  44. }
  45. var regexpMetas = map[string]string{
  46. "format": "https://someurl.com/{user}/{repo}/{index}",
  47. "user": "someUser",
  48. "repo": "someRepo",
  49. "style": IssueNameStyleRegexp,
  50. }
  51. // these values should match the TestOrgRepo const above
  52. var localMetas = map[string]string{
  53. "user": "test-owner",
  54. "repo": "test-repo",
  55. "markupAllowShortIssuePattern": "true",
  56. }
  57. func TestRender_IssueIndexPattern(t *testing.T) {
  58. // numeric: render inputs without valid mentions
  59. test := func(s string) {
  60. testRenderIssueIndexPattern(t, s, s, NewTestRenderContext())
  61. testRenderIssueIndexPattern(t, s, s, NewTestRenderContext(numericMetas))
  62. }
  63. // should not render anything when there are no mentions
  64. test("")
  65. test("this is a test")
  66. test("test 123 123 1234")
  67. test("#")
  68. test("# # #")
  69. test("# 123")
  70. test("#abcd")
  71. test("test#1234")
  72. test("#1234test")
  73. test("#abcd")
  74. test("test!1234")
  75. test("!1234test")
  76. test(" test !1234test")
  77. test("/home/gitea/#1234")
  78. test("/home/gitea/!1234")
  79. // should not render issue mention without leading space
  80. test("test#54321 issue")
  81. // should not render issue mention without trailing space
  82. test("test #54321issue")
  83. }
  84. func TestRender_IssueIndexPattern2(t *testing.T) {
  85. setting.AppURL = TestAppURL
  86. // numeric: render inputs with valid mentions
  87. test := func(s, expectedFmt, marker string, indices ...int) {
  88. var path, prefix string
  89. isExternal := false
  90. if marker == "!" {
  91. path = "pulls"
  92. prefix = "/someUser/someRepo/pulls/"
  93. } else {
  94. path = "issues"
  95. prefix = "https://someurl.com/someUser/someRepo/"
  96. isExternal = true
  97. }
  98. links := make([]any, len(indices))
  99. for i, index := range indices {
  100. links[i] = numericIssueLink(util.URLJoin("/test-owner/test-repo", path), "ref-issue", index, marker)
  101. }
  102. expectedNil := fmt.Sprintf(expectedFmt, links...)
  103. testRenderIssueIndexPattern(t, s, expectedNil, NewTestRenderContext(TestAppURL, localMetas))
  104. class := "ref-issue"
  105. if isExternal {
  106. class += " ref-external-issue"
  107. }
  108. for i, index := range indices {
  109. links[i] = numericIssueLink(prefix, class, index, marker)
  110. }
  111. expectedNum := fmt.Sprintf(expectedFmt, links...)
  112. testRenderIssueIndexPattern(t, s, expectedNum, NewTestRenderContext(TestAppURL, numericMetas))
  113. }
  114. // should render freestanding mentions
  115. test("#1234 test", "%s test", "#", 1234)
  116. test("test #8 issue", "test %s issue", "#", 8)
  117. test("!1234 test", "%s test", "!", 1234)
  118. test("test !8 issue", "test %s issue", "!", 8)
  119. test("test issue #1234", "test issue %s", "#", 1234)
  120. test("fixes issue #1234.", "fixes issue %s.", "#", 1234)
  121. // should render mentions in parentheses / brackets
  122. test("(#54321 issue)", "(%s issue)", "#", 54321)
  123. test("[#54321 issue]", "[%s issue]", "#", 54321)
  124. test("test (#9801 extra) issue", "test (%s extra) issue", "#", 9801)
  125. test("test (!9801 extra) issue", "test (%s extra) issue", "!", 9801)
  126. test("test (#1)", "test (%s)", "#", 1)
  127. // should render multiple issue mentions in the same line
  128. test("#54321 #1243", "%s %s", "#", 54321, 1243)
  129. test("wow (#54321 #1243)", "wow (%s %s)", "#", 54321, 1243)
  130. test("(#4)(#5)", "(%s)(%s)", "#", 4, 5)
  131. test("#1 (#4321) test", "%s (%s) test", "#", 1, 4321)
  132. // should render with :
  133. test("#1234: test", "%s: test", "#", 1234)
  134. test("wow (#54321: test)", "wow (%s: test)", "#", 54321)
  135. }
  136. func TestRender_IssueIndexPattern3(t *testing.T) {
  137. setting.AppURL = TestAppURL
  138. // alphanumeric: render inputs without valid mentions
  139. test := func(s string) {
  140. testRenderIssueIndexPattern(t, s, s, NewTestRenderContext(alphanumericMetas))
  141. }
  142. test("")
  143. test("this is a test")
  144. test("test 123 123 1234")
  145. test("#")
  146. test("# 123")
  147. test("#abcd")
  148. test("test #123")
  149. test("abc-1234") // issue prefix must be capital
  150. test("ABc-1234") // issue prefix must be _all_ capital
  151. test("ABCDEFGHIJK-1234") // the limit is 10 characters in the prefix
  152. test("ABC1234") // dash is required
  153. test("test ABC- test") // number is required
  154. test("test -1234 test") // prefix is required
  155. test("testABC-123 test") // leading space is required
  156. test("test ABC-123test") // trailing space is required
  157. test("ABC-0123") // no leading zero
  158. }
  159. func TestRender_IssueIndexPattern4(t *testing.T) {
  160. setting.AppURL = TestAppURL
  161. // alphanumeric: render inputs with valid mentions
  162. test := func(s, expectedFmt string, names ...string) {
  163. links := make([]any, len(names))
  164. for i, name := range names {
  165. links[i] = externalIssueLink("https://someurl.com/someUser/someRepo/", "ref-issue ref-external-issue", name)
  166. }
  167. expected := fmt.Sprintf(expectedFmt, links...)
  168. testRenderIssueIndexPattern(t, s, expected, NewTestRenderContext(alphanumericMetas))
  169. }
  170. test("OTT-1234 test", "%s test", "OTT-1234")
  171. test("test T-12 issue", "test %s issue", "T-12")
  172. test("test issue ABCDEFGHIJ-1234567890", "test issue %s", "ABCDEFGHIJ-1234567890")
  173. }
  174. func TestRender_IssueIndexPattern5(t *testing.T) {
  175. setting.AppURL = TestAppURL
  176. // regexp: render inputs without valid mentions
  177. test := func(s, expectedFmt, pattern string, ids, names []string) {
  178. metas := regexpMetas
  179. metas["regexp"] = pattern
  180. links := make([]any, len(ids))
  181. for i, id := range ids {
  182. links[i] = link(util.URLJoin("https://someurl.com/someUser/someRepo/", id), "ref-issue ref-external-issue", names[i])
  183. }
  184. expected := fmt.Sprintf(expectedFmt, links...)
  185. testRenderIssueIndexPattern(t, s, expected, NewTestRenderContext(metas))
  186. }
  187. test("abc ISSUE-123 def", "abc %s def",
  188. "ISSUE-(\\d+)",
  189. []string{"123"},
  190. []string{"ISSUE-123"},
  191. )
  192. test("abc (ISSUE 123) def", "abc %s def",
  193. "\\(ISSUE (\\d+)\\)",
  194. []string{"123"},
  195. []string{"(ISSUE 123)"},
  196. )
  197. test("abc ISSUE-123 def", "abc %s def",
  198. "(ISSUE-(\\d+))",
  199. []string{"ISSUE-123"},
  200. []string{"ISSUE-123"},
  201. )
  202. testRenderIssueIndexPattern(t, "will not match", "will not match", NewTestRenderContext(regexpMetas))
  203. }
  204. func TestRender_IssueIndexPattern_NoShortPattern(t *testing.T) {
  205. setting.AppURL = TestAppURL
  206. metas := map[string]string{
  207. "format": "https://someurl.com/{user}/{repo}/{index}",
  208. "user": "someUser",
  209. "repo": "someRepo",
  210. "style": IssueNameStyleNumeric,
  211. }
  212. testRenderIssueIndexPattern(t, "#1", "#1", NewTestRenderContext(metas))
  213. testRenderIssueIndexPattern(t, "#1312", "#1312", NewTestRenderContext(metas))
  214. testRenderIssueIndexPattern(t, "!1", "!1", NewTestRenderContext(metas))
  215. }
  216. func TestRender_PostProcessIssueTitle(t *testing.T) {
  217. setting.AppURL = TestAppURL
  218. metas := map[string]string{
  219. "format": "https://someurl.com/{user}/{repo}/{index}",
  220. "user": "someUser",
  221. "repo": "someRepo",
  222. "style": IssueNameStyleNumeric,
  223. }
  224. actual, err := PostProcessIssueTitle(NewTestRenderContext(metas), "#1")
  225. assert.NoError(t, err)
  226. assert.Equal(t, "#1", actual)
  227. }
  228. func testRenderIssueIndexPattern(t *testing.T, input, expected string, ctx *RenderContext) {
  229. var buf strings.Builder
  230. err := postProcess(ctx, []processor{issueIndexPatternProcessor}, strings.NewReader(input), &buf)
  231. assert.NoError(t, err)
  232. assert.Equal(t, expected, buf.String(), "input=%q", input)
  233. }
  234. func TestRender_AutoLink(t *testing.T) {
  235. setting.AppURL = TestAppURL
  236. test := func(input, expected string) {
  237. var buffer strings.Builder
  238. err := PostProcessDefault(NewTestRenderContext(localMetas), strings.NewReader(input), &buffer)
  239. assert.NoError(t, err)
  240. assert.Equal(t, strings.TrimSpace(expected), strings.TrimSpace(buffer.String()))
  241. buffer.Reset()
  242. err = PostProcessDefault(NewTestRenderContext(localMetas), strings.NewReader(input), &buffer)
  243. assert.NoError(t, err)
  244. assert.Equal(t, strings.TrimSpace(expected), strings.TrimSpace(buffer.String()))
  245. }
  246. // render valid issue URLs
  247. test(util.URLJoin(TestRepoURL, "issues", "3333"),
  248. numericIssueLink(util.URLJoin(TestRepoURL, "issues"), "ref-issue", 3333, "#"))
  249. // render valid commit URLs
  250. tmp := util.URLJoin(TestRepoURL, "commit", "d8a994ef243349f321568f9e36d5c3f444b99cae")
  251. test(tmp, "<a href=\""+tmp+"\" class=\"commit\"><code>d8a994ef24</code></a>")
  252. tmp += "#diff-2"
  253. test(tmp, "<a href=\""+tmp+"\" class=\"commit\"><code>d8a994ef24 (diff-2)</code></a>")
  254. // render other commit URLs
  255. tmp = "https://external-link.gitea.io/go-gitea/gitea/commit/d8a994ef243349f321568f9e36d5c3f444b99cae#diff-2"
  256. test(tmp, "<a href=\""+tmp+"\" class=\"commit\"><code>d8a994ef24 (diff-2)</code></a>")
  257. }
  258. func TestRender_FullIssueURLs(t *testing.T) {
  259. setting.AppURL = TestAppURL
  260. defer testModule.MockVariableValue(&RenderBehaviorForTesting.DisableAdditionalAttributes, true)()
  261. test := func(input, expected string) {
  262. var result strings.Builder
  263. err := postProcess(NewTestRenderContext(localMetas), []processor{fullIssuePatternProcessor}, strings.NewReader(input), &result)
  264. assert.NoError(t, err)
  265. assert.Equal(t, expected, result.String())
  266. }
  267. test("Here is a link https://git.osgeo.org/gogs/postgis/postgis/pulls/6",
  268. "Here is a link https://git.osgeo.org/gogs/postgis/postgis/pulls/6")
  269. test("Look here http://localhost:3000/person/repo/issues/4",
  270. `Look here <a href="http://localhost:3000/person/repo/issues/4" class="ref-issue">person/repo#4</a>`)
  271. test("http://localhost:3000/person/repo/issues/4#issuecomment-1234",
  272. `<a href="http://localhost:3000/person/repo/issues/4#issuecomment-1234" class="ref-issue">person/repo#4 (comment)</a>`)
  273. test("http://localhost:3000/test-owner/test-repo/issues/4",
  274. `<a href="http://localhost:3000/test-owner/test-repo/issues/4" class="ref-issue">#4</a>`)
  275. test("http://localhost:3000/test-owner/test-repo/issues/4 test",
  276. `<a href="http://localhost:3000/test-owner/test-repo/issues/4" class="ref-issue">#4</a> test`)
  277. test("http://localhost:3000/test-owner/test-repo/issues/4?a=1&b=2#comment-123 test",
  278. `<a href="http://localhost:3000/test-owner/test-repo/issues/4?a=1&amp;b=2#comment-123" class="ref-issue">#4 (comment)</a> test`)
  279. test("http://localhost:3000/testOrg/testOrgRepo/pulls/2/files#issuecomment-24",
  280. "http://localhost:3000/testOrg/testOrgRepo/pulls/2/files#issuecomment-24")
  281. test("http://localhost:3000/testOrg/testOrgRepo/pulls/2/files",
  282. "http://localhost:3000/testOrg/testOrgRepo/pulls/2/files")
  283. }
  284. func TestRegExp_sha1CurrentPattern(t *testing.T) {
  285. trueTestCases := []string{
  286. "d8a994ef243349f321568f9e36d5c3f444b99cae",
  287. "abcdefabcdefabcdefabcdefabcdefabcdefabcd",
  288. "(abcdefabcdefabcdefabcdefabcdefabcdefabcd)",
  289. "[abcdefabcdefabcdefabcdefabcdefabcdefabcd]",
  290. "abcdefabcdefabcdefabcdefabcdefabcdefabcd.",
  291. "abcdefabcdefabcdefabcdefabcdefabcdefabcd:",
  292. }
  293. falseTestCases := []string{
  294. "test",
  295. "abcdefg",
  296. "e59ff077-2d03-4e6b-964d-63fbaea81f",
  297. "abcdefghijklmnopqrstuvwxyzabcdefghijklmn",
  298. "abcdefghijklmnopqrstuvwxyzabcdefghijklmO",
  299. }
  300. for _, testCase := range trueTestCases {
  301. assert.True(t, globalVars().hashCurrentPattern.MatchString(testCase))
  302. }
  303. for _, testCase := range falseTestCases {
  304. assert.False(t, globalVars().hashCurrentPattern.MatchString(testCase))
  305. }
  306. }
  307. func TestRegExp_anySHA1Pattern(t *testing.T) {
  308. testCases := map[string]anyHashPatternResult{
  309. "https://github.com/jquery/jquery/blob/a644101ed04d0beacea864ce805e0c4f86ba1cd1/test/unit/event.js#L2703": {
  310. CommitID: "a644101ed04d0beacea864ce805e0c4f86ba1cd1",
  311. SubPath: "/test/unit/event.js",
  312. QueryHash: "L2703",
  313. },
  314. "https://github.com/jquery/jquery/blob/a644101ed04d0beacea864ce805e0c4f86ba1cd1/test/unit/event.js": {
  315. CommitID: "a644101ed04d0beacea864ce805e0c4f86ba1cd1",
  316. SubPath: "/test/unit/event.js",
  317. },
  318. "https://github.com/jquery/jquery/commit/0705be475092aede1eddae01319ec931fb9c65fc": {
  319. CommitID: "0705be475092aede1eddae01319ec931fb9c65fc",
  320. },
  321. "https://github.com/jquery/jquery/tree/0705be475092aede1eddae01319ec931fb9c65fc/src": {
  322. CommitID: "0705be475092aede1eddae01319ec931fb9c65fc",
  323. SubPath: "/src",
  324. },
  325. "https://try.gogs.io/gogs/gogs/commit/d8a994ef243349f321568f9e36d5c3f444b99cae#diff-2": {
  326. CommitID: "d8a994ef243349f321568f9e36d5c3f444b99cae",
  327. QueryHash: "diff-2",
  328. },
  329. "non-url": {},
  330. "http://a/b/c/d/e/1234567812345678123456781234567812345678123456781234567812345678?a=b#L1-L2": {
  331. CommitID: "1234567812345678123456781234567812345678123456781234567812345678",
  332. QueryHash: "L1-L2",
  333. },
  334. "http://a/b/c/d/e/1234567812345678123456781234567812345678123456781234567812345678.": {
  335. CommitID: "1234567812345678123456781234567812345678123456781234567812345678",
  336. },
  337. "http://a/b/c/d/e/1234567812345678123456781234567812345678123456781234567812345678/sub.": {
  338. CommitID: "1234567812345678123456781234567812345678123456781234567812345678",
  339. SubPath: "/sub",
  340. },
  341. "http://a/b/c/d/e/1234567812345678123456781234567812345678123456781234567812345678?a=b.": {
  342. CommitID: "1234567812345678123456781234567812345678123456781234567812345678",
  343. },
  344. "http://a/b/c/d/e/1234567812345678123456781234567812345678123456781234567812345678?a=b&c=d": {
  345. CommitID: "1234567812345678123456781234567812345678123456781234567812345678",
  346. },
  347. "http://a/b/c/d/e/1234567812345678123456781234567812345678123456781234567812345678#hash.": {
  348. CommitID: "1234567812345678123456781234567812345678123456781234567812345678",
  349. QueryHash: "hash",
  350. },
  351. }
  352. for k, v := range testCases {
  353. ret, ok := anyHashPatternExtract(k)
  354. if v.CommitID == "" {
  355. assert.False(t, ok)
  356. } else {
  357. assert.Equal(t, strings.TrimSuffix(k, "."), ret.FullURL)
  358. assert.Equal(t, v.CommitID, ret.CommitID)
  359. assert.Equal(t, v.SubPath, ret.SubPath)
  360. assert.Equal(t, v.QueryHash, ret.QueryHash)
  361. }
  362. }
  363. }
  364. func TestRegExp_shortLinkPattern(t *testing.T) {
  365. trueTestCases := []string{
  366. "[[stuff]]",
  367. "[[]]",
  368. "[[stuff|title=Difficult name with spaces*!]]",
  369. }
  370. falseTestCases := []string{
  371. "test",
  372. "abcdefg",
  373. "[[]",
  374. "[[",
  375. "[]",
  376. "]]",
  377. "abcdefghijklmnopqrstuvwxyz",
  378. }
  379. for _, testCase := range trueTestCases {
  380. assert.True(t, globalVars().shortLinkPattern.MatchString(testCase))
  381. }
  382. for _, testCase := range falseTestCases {
  383. assert.False(t, globalVars().shortLinkPattern.MatchString(testCase))
  384. }
  385. }