robots_test.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package sitemap
  2. import (
  3. "io/ioutil"
  4. "net/http"
  5. "net/http/httptest"
  6. "testing"
  7. )
  8. func TestAddSitemapUrl(t *testing.T) {
  9. robot := Robots()
  10. robot.Agent(AllAgents).AddSitemapUrl(SiteMap().ToUrl(WithHost("https://qor5.dev.com")))
  11. s := robot.ToTxt()
  12. expected := "User-agent: *\nSitemap: https:/qor5.dev.com/sitemap.xml\n\n"
  13. if s != expected {
  14. t.Errorf("\n\tExpected value: \n%s \tbut got: \n%s", expected, s)
  15. }
  16. }
  17. func TestAllow(t *testing.T) {
  18. robot := Robots()
  19. robot.Agent(AllAgents).Allow("/product1", "/product2")
  20. s := robot.ToTxt()
  21. expected := "User-agent: *\nAllow: /product1\nAllow: /product2\n\n"
  22. if s != expected {
  23. t.Errorf("\n\tExpected value: \n%s \tbut got: \n%s", expected, s)
  24. }
  25. }
  26. func TestDisallow(t *testing.T) {
  27. robot := Robots()
  28. robot.Agent(AllAgents).Disallow("/product1", "/product2")
  29. s := robot.ToTxt()
  30. expected := "User-agent: *\nDisallow: /product1\nDisallow: /product2\n\n"
  31. if s != expected {
  32. t.Errorf("\n\tExpected value: \n%s \tbut got: \n%s", expected, s)
  33. }
  34. }
  35. func TestRobotsServeHTTP(t *testing.T) {
  36. robot := Robots()
  37. robot.Agent(GoogleAgent).Disallow("/admin", "/product").AddSitemapUrl(SiteMap().ToUrl(WithHost("https://qor5.dev.com")))
  38. robot.Agent(DuckDuckAgent).Allow("/admin1", "/product2").Disallow("/product1")
  39. serveMux := http.NewServeMux()
  40. robot.MountTo(serveMux)
  41. server := httptest.NewServer(serveMux)
  42. resp, err := http.Get(server.URL + "/robots.txt")
  43. if err != nil {
  44. t.Error(err)
  45. }
  46. s, err := ioutil.ReadAll(resp.Body)
  47. if err != nil {
  48. t.Error(err)
  49. }
  50. expected := "User-agent: Googlebot\nDisallow: /admin\nDisallow: /product\nSitemap: https:/qor5.dev.com/sitemap.xml\n\nUser-agent: DuckDuckBot\nDisallow: /product1\nAllow: /admin1\nAllow: /product2\n\n"
  51. if string(s) != expected {
  52. t.Errorf("\n\tExpected value: \n%s \tbut got: \n%s", expected, s)
  53. }
  54. }