You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

sitemap_test.go 1.9KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // Copyright 2022 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package sitemap
  5. import (
  6. "bytes"
  7. "encoding/xml"
  8. "fmt"
  9. "strings"
  10. "testing"
  11. "time"
  12. "github.com/stretchr/testify/assert"
  13. )
  14. func TestOk(t *testing.T) {
  15. testReal := func(s *Sitemap, name string, urls []URL, expected string) {
  16. for _, url := range urls {
  17. s.Add(url)
  18. }
  19. buf := &bytes.Buffer{}
  20. _, err := s.WriteTo(buf)
  21. assert.NoError(t, nil, err)
  22. assert.Equal(t, xml.Header+"<"+name+" xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">"+expected+"</"+name+">\n", buf.String())
  23. }
  24. test := func(urls []URL, expected string) {
  25. testReal(NewSitemap(), "urlset", urls, expected)
  26. testReal(NewSitemapIndex(), "sitemapindex", urls, expected)
  27. }
  28. ts := time.Unix(1651322008, 0).UTC()
  29. test(
  30. []URL{},
  31. "",
  32. )
  33. test(
  34. []URL{
  35. {URL: "https://gitea.io/test1", LastMod: &ts},
  36. },
  37. "<url><loc>https://gitea.io/test1</loc><lastmod>2022-04-30T12:33:28Z</lastmod></url>",
  38. )
  39. test(
  40. []URL{
  41. {URL: "https://gitea.io/test2", LastMod: nil},
  42. },
  43. "<url><loc>https://gitea.io/test2</loc></url>",
  44. )
  45. test(
  46. []URL{
  47. {URL: "https://gitea.io/test1", LastMod: &ts},
  48. {URL: "https://gitea.io/test2", LastMod: nil},
  49. },
  50. "<url><loc>https://gitea.io/test1</loc><lastmod>2022-04-30T12:33:28Z</lastmod></url>"+
  51. "<url><loc>https://gitea.io/test2</loc></url>",
  52. )
  53. }
  54. func TestTooManyURLs(t *testing.T) {
  55. s := NewSitemap()
  56. for i := 0; i < 50001; i++ {
  57. s.Add(URL{URL: fmt.Sprintf("https://gitea.io/test%d", i)})
  58. }
  59. buf := &bytes.Buffer{}
  60. _, err := s.WriteTo(buf)
  61. assert.EqualError(t, err, "The sitemap contains too many URLs: 50001")
  62. }
  63. func TestSitemapTooBig(t *testing.T) {
  64. s := NewSitemap()
  65. s.Add(URL{URL: strings.Repeat("b", sitemapFileLimit)})
  66. buf := &bytes.Buffer{}
  67. _, err := s.WriteTo(buf)
  68. assert.EqualError(t, err, "The sitemap is too big: 52428931")
  69. }