test_sitemaps.py 2.7 KB

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