test_sitemaps.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. from __future__ import unicode_literals
  2. import zipfile
  3. from io import BytesIO
  4. from xml.dom import minidom
  5. from django.conf import settings
  6. from django.contrib.sites.models import Site
  7. from django.test import (
  8. TestCase, modify_settings, override_settings, skipUnlessDBFeature,
  9. )
  10. from .models import City, Country
  11. @modify_settings(INSTALLED_APPS={'append': ['django.contrib.sites', 'django.contrib.sitemaps']})
  12. @override_settings(ROOT_URLCONF='gis_tests.geoapp.urls')
  13. @skipUnlessDBFeature("gis_enabled")
  14. class GeoSitemapTest(TestCase):
  15. def setUp(self):
  16. super(GeoSitemapTest, self).setUp()
  17. Site(id=settings.SITE_ID, domain="example.com", name="example.com").save()
  18. def assertChildNodes(self, elem, expected):
  19. "Taken from syndication/tests.py."
  20. actual = set(n.nodeName for n in elem.childNodes)
  21. expected = set(expected)
  22. self.assertEqual(actual, expected)
  23. def test_geositemap_kml(self):
  24. "Tests KML/KMZ geographic sitemaps."
  25. for kml_type in ('kml', 'kmz'):
  26. doc = minidom.parseString(self.client.get('/sitemaps/%s.xml' % kml_type).content)
  27. # Ensuring the right sitemaps namespace is present.
  28. urlset = doc.firstChild
  29. self.assertEqual(urlset.getAttribute('xmlns'), 'http://www.sitemaps.org/schemas/sitemap/0.9')
  30. urls = urlset.getElementsByTagName('url')
  31. self.assertEqual(2, len(urls)) # Should only be 2 sitemaps.
  32. for url in urls:
  33. self.assertChildNodes(url, ['loc'])
  34. # Getting the relative URL since we don't have a real site.
  35. kml_url = url.getElementsByTagName('loc')[0].childNodes[0].data.split('http://example.com')[1]
  36. if kml_type == 'kml':
  37. kml_doc = minidom.parseString(self.client.get(kml_url).content)
  38. elif kml_type == 'kmz':
  39. # Have to decompress KMZ before parsing.
  40. buf = BytesIO(self.client.get(kml_url).content)
  41. with zipfile.ZipFile(buf) as zf:
  42. self.assertEqual(1, len(zf.filelist))
  43. self.assertEqual('doc.kml', zf.filelist[0].filename)
  44. kml_doc = minidom.parseString(zf.read('doc.kml'))
  45. # Ensuring the correct number of placemarks are in the KML doc.
  46. if 'city' in kml_url:
  47. model = City
  48. elif 'country' in kml_url:
  49. model = Country
  50. self.assertEqual(model.objects.count(), len(kml_doc.getElementsByTagName('Placemark')))