|
| 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 | + |
| 5 | +package sitemap |
| 6 | + |
| 7 | +import ( |
| 8 | + "bytes" |
| 9 | + "encoding/xml" |
| 10 | + "fmt" |
| 11 | + "strings" |
| 12 | + "testing" |
| 13 | + "time" |
| 14 | + |
| 15 | + "github.com/stretchr/testify/assert" |
| 16 | +) |
| 17 | + |
| 18 | +func TestOk(t *testing.T) { |
| 19 | + testReal := func(s *Sitemap, name string, urls []URL, expected string) { |
| 20 | + for _, url := range urls { |
| 21 | + s.Add(url) |
| 22 | + } |
| 23 | + buf := &bytes.Buffer{} |
| 24 | + _, err := s.WriteTo(buf) |
| 25 | + assert.NoError(t, nil, err) |
| 26 | + assert.Equal(t, xml.Header+"<"+name+" xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">"+expected+"</"+name+">\n", buf.String()) |
| 27 | + } |
| 28 | + test := func(urls []URL, expected string) { |
| 29 | + testReal(NewSitemap(), "urlset", urls, expected) |
| 30 | + testReal(NewSitemapIndex(), "sitemapindex", urls, expected) |
| 31 | + } |
| 32 | + |
| 33 | + ts := time.Unix(1651322008, 0).UTC() |
| 34 | + |
| 35 | + test( |
| 36 | + []URL{}, |
| 37 | + "", |
| 38 | + ) |
| 39 | + test( |
| 40 | + []URL{ |
| 41 | + {URL: "https://gitea.io/test1", LastMod: &ts}, |
| 42 | + }, |
| 43 | + "<url><loc>https://gitea.io/test1</loc><lastmod>2022-04-30T12:33:28Z</lastmod></url>", |
| 44 | + ) |
| 45 | + test( |
| 46 | + []URL{ |
| 47 | + {URL: "https://gitea.io/test2", LastMod: nil}, |
| 48 | + }, |
| 49 | + "<url><loc>https://gitea.io/test2</loc></url>", |
| 50 | + ) |
| 51 | + test( |
| 52 | + []URL{ |
| 53 | + {URL: "https://gitea.io/test1", LastMod: &ts}, |
| 54 | + {URL: "https://gitea.io/test2", LastMod: nil}, |
| 55 | + }, |
| 56 | + "<url><loc>https://gitea.io/test1</loc><lastmod>2022-04-30T12:33:28Z</lastmod></url>"+ |
| 57 | + "<url><loc>https://gitea.io/test2</loc></url>", |
| 58 | + ) |
| 59 | +} |
| 60 | + |
| 61 | +func TestTooManyURLs(t *testing.T) { |
| 62 | + s := NewSitemap() |
| 63 | + for i := 0; i < 50001; i++ { |
| 64 | + s.Add(URL{URL: fmt.Sprintf("https://gitea.io/test%d", i)}) |
| 65 | + } |
| 66 | + buf := &bytes.Buffer{} |
| 67 | + _, err := s.WriteTo(buf) |
| 68 | + assert.EqualError(t, err, "The sitemap contains too many URLs: 50001") |
| 69 | +} |
| 70 | + |
| 71 | +func TestSitemapTooBig(t *testing.T) { |
| 72 | + s := NewSitemap() |
| 73 | + s.Add(URL{URL: strings.Repeat("b", sitemapFileLimit)}) |
| 74 | + buf := &bytes.Buffer{} |
| 75 | + _, err := s.WriteTo(buf) |
| 76 | + assert.EqualError(t, err, "The sitemap is too big: 52428931") |
| 77 | +} |
0 commit comments