'Tests KML/KMZ geographic sitemaps.'

def test_geositemap_kml(self):

    for kml_type in ('kml', 'kmz'):
        doc = minidom.parseString(self.client.get(('/sitemaps/%s.xml' % kml_type)).content)
        urlset = doc.firstChild
        self.assertEqual(urlset.getAttribute(u'xmlns'), u'http://www.sitemaps.org/schemas/sitemap/0.9')
        self.assertEqual(urlset.getAttribute(u'xmlns:geo'), u'http://www.google.com/geo/schemas/sitemap/1.0')
        urls = urlset.getElementsByTagName('url')
        self.assertEqual(2, len(urls))
        for url in urls:
            self.assertChildNodes(url, ['loc', 'geo:geo'])
            geo_elem = url.getElementsByTagName('geo:geo')[0]
            geo_format = geo_elem.getElementsByTagName('geo:format')[0]
            self.assertEqual(kml_type, geo_format.childNodes[0].data)
            kml_url = url.getElementsByTagName('loc')[0].childNodes[0].data.split('http://example.com')[1]
            if (kml_type == 'kml'):
                kml_doc = minidom.parseString(self.client.get(kml_url).content)
            elif (kml_type == 'kmz'):
                buf = cStringIO.StringIO(self.client.get(kml_url).content)
                zf = zipfile.ZipFile(buf)
                self.assertEqual(1, len(zf.filelist))
                self.assertEqual('doc.kml', zf.filelist[0].filename)
                kml_doc = minidom.parseString(zf.read('doc.kml'))
            if ('city' in kml_url):
                model = City
            elif ('country' in kml_url):
                model = Country
            self.assertEqual(model.objects.count(), len(kml_doc.getElementsByTagName('Placemark')))
