Example #1
0
def main(argv=None):
    if argv is None:
        argv = sys.argv
    try:
        try:
            opts, args = getopt.getopt(argv[1:], "h", ["help"])
        except getopt.error, msg:
            raise Usage(msg)
        # main code
        schema = Schema("kml22gx.xsd")
        filename = argv[1]
        with open(filename) as f:
            kmldoc = parse(f, schema=schema)
            print write_python_script_for_kml_document(kmldoc)
Example #2
0
def main(argv=None):
    if argv is None:
        argv = sys.argv
    try:
        try:
            opts, args = getopt.getopt(argv[1:], "h", ["help"])
        except getopt.error, msg:
             raise Usage(msg)
        # main code
        schema = Schema("kml22gx.xsd")
        filename = argv[1]
        with open(filename) as f:
            kmldoc = parse(f, schema=schema)
            print write_python_script_for_kml_document(kmldoc)
Example #3
0
    def test_write_python_script_for_kml_document_with_comments(self):
        """Tests the creation of an OGC KML document with several comments"""
        test_datafile = (Path(__file__).parent /
                         'testfiles' /
                         'simple_file_with_comments.kml')
        schema = Schema('kml22gx.xsd')
        with test_datafile.open('rb') as f:
            doc = pykml.parser.parse(f, schema=schema)
        script = write_python_script_for_kml_document(doc)

        # create a temporary python file
        with tempfile.NamedTemporaryFile(mode='wt', suffix='.py', delete=False) as f:
            temp_python_file = f.name
            f.write(script)

        # Execute the temporary python file to create a KML file.
        # PYTHONPATH may need to be set so that the pykml module is found.
        current_env = os.environ.copy()
        # May be required if not using an IDE.
        # current_env['PYTHONPATH'] = os.fspath(Path(__file__).parent)

        with tempfile.NamedTemporaryFile(mode='wb', suffix='.kml', delete=False) as f:
            temp_kml_file = f.name
            exit_code = subprocess.call(['python', temp_python_file], stdout=f, env=current_env)
        self.assertEqual(exit_code, 0)

        # parse and validate the KML generated by the temporary script
        doc2 = pykml.parser.parse(temp_kml_file, schema=schema)
        # test that the root element is as expected
        self.assertEqual(doc2.docinfo.root_name, 'kml')
        # test that the original and generated documents are equivalent
        self.assertXmlEquivalentOutputs(etree.tostring(doc), etree.tostring(doc2))

        os.unlink(temp_python_file)
        os.unlink(temp_kml_file)
Example #4
0
    def test_write_python_script_for_kml_document(self):
        """Tests the creation of a trivial OGC KML document."""
        from pykml.factory import write_python_script_for_kml_document

        doc = KML.kml(
            KML.Document(
                ATOM.author(ATOM.name("J. K. Rowling")),
                ATOM.link(href="http://www.harrypotter.com"),
                KML.Placemark(KML.name("Hogwarts"),
                              KML.Point(KML.coordinates("1,1")))))
        script = write_python_script_for_kml_document(doc)
        self.assertEqual(
            script, 'from lxml import etree\n'
            'from pykml.factory import KML_ElementMaker as KML\n'
            'from pykml.factory import ATOM_ElementMaker as ATOM\n'
            'from pykml.factory import GX_ElementMaker as GX\n'
            '\n'
            'doc = KML.kml(\n'
            '  KML.Document(\n'
            '    ATOM.author(\n'
            '      ATOM.name(\'J. K. Rowling\'),\n'
            '    ),\n'
            '    ATOM.link(  href="http://www.harrypotter.com",\n'
            '),\n'
            '    KML.Placemark(\n'
            '      KML.name(\'Hogwarts\'),\n'
            '      KML.Point(\n'
            '        KML.coordinates(\'1,1\'),\n'
            '      ),\n'
            '    ),\n'
            '  ),\n'
            ')\n'
            'print(etree.tostring(etree.ElementTree(doc),pretty_print=True).decode())\n'
        )
Example #5
0
    def test_write_python_script_for_multiline_coordinate_string(self):
        """Tests the creation of a trivial OGC KML document."""
        test_datafile = (Path(__file__).parent /
                         'testfiles' /
                         'google_kml_reference' /
                         'altitudemode_reference.kml')
        with test_datafile.open('rb') as f:
            doc = pykml.parser.parse(f, schema=None)
        script = write_python_script_for_kml_document(doc)
        expected = \
            'from lxml import etree\n' \
            'from pykml.factory import KML_ElementMaker as KML\n' \
            'from pykml.factory import ATOM_ElementMaker as ATOM\n' \
            'from pykml.factory import GX_ElementMaker as GX\n' \
            '\n' \
            'doc = KML.kml(\n' \
            '  etree.Comment(\' required when using gx-prefixed elements \'),\n' \
            '  KML.Placemark(\n' \
            '    KML.name(\'gx:altitudeMode Example\'),\n' \
            '    KML.LookAt(\n' \
            '      KML.longitude(\'146.806\'),\n' \
            '      KML.latitude(\'12.219\'),\n' \
            '      KML.heading(\'-60\'),\n' \
            '      KML.tilt(\'70\'),\n' \
            '      KML.range(\'6300\'),\n' \
            '      GX.altitudeMode(\'relativeToSeaFloor\'),\n' \
            '    ),\n' \
            '    KML.LineString(\n' \
            '      KML.extrude(\'1\'),\n' \
            '      GX.altitudeMode(\'relativeToSeaFloor\'),\n' \
            '      KML.coordinates(\n' \
            '      \'146.825,12.233,400 \'\n' \
            '      \'146.820,12.222,400 \'\n' \
            '      \'146.812,12.212,400 \'\n' \
            '      \'146.796,12.209,400 \'\n' \
            '      \'146.788,12.205,400 \'\n' \
            '      ),\n' \
            '    ),\n' \
            '  ),\n' \
            ')\n' \
            'print(etree.tostring(etree.ElementTree(doc), \n' \
            '                     encoding=\'utf-8\', \n' \
            '                     xml_declaration=True, \n' \
            '                     pretty_print=True).decode(\'utf-8\'))\n'

        self.assertEqual(script, expected)
Example #6
0
    def test_write_python_script_for_multiline_coordinate_string(self):
        """Tests the creation of a trivial OGC KML document."""
        from pykml.factory import write_python_script_for_kml_document
        
        test_datafile = path.join(
            path.dirname(__file__),
            'testfiles',
            'google_kml_reference/altitudemode_reference.kml'
        )
        with open(test_datafile) as f:
            doc = parse(f, schema=None)
        script = write_python_script_for_kml_document(doc)
        self.assertEquals(
            script,
'from lxml import etree\n'
'from pykml.factory import KML_ElementMaker as KML\n'
'from pykml.factory import ATOM_ElementMaker as ATOM\n'
'from pykml.factory import GX_ElementMaker as GX\n'
'\n'
'doc = KML.kml(\n'
'  etree.Comment(\' required when using gx-prefixed elements \'),\n'
'  KML.Placemark(\n'
'    KML.name(\'gx:altitudeMode Example\'),\n'
'    KML.LookAt(\n'
'      KML.longitude(\'146.806\'),\n'
'      KML.latitude(\'12.219\'),\n'
'      KML.heading(\'-60\'),\n'
'      KML.tilt(\'70\'),\n'
'      KML.range(\'6300\'),\n'
'      GX.altitudeMode(\'relativeToSeaFloor\'),\n'
'    ),\n'
'    KML.LineString(\n'
'      KML.extrude(\'1\'),\n'
'      GX.altitudeMode(\'relativeToSeaFloor\'),\n'
'      KML.coordinates(\n'
'      \'146.825,12.233,400 \'\n'
'      \'146.820,12.222,400 \'\n'
'      \'146.812,12.212,400 \'\n'
'      \'146.796,12.209,400 \'\n'
'      \'146.788,12.205,400 \'\n'
'      ),\n'
'    ),\n'
'  ),\n'
')\n'
'print etree.tostring(etree.ElementTree(doc),pretty_print=True)\n'
        )
Example #7
0
    def test_write_python_script_for_multiline_coordinate_string(self):
        """Tests the creation of a trivial OGC KML document."""
        from pykml.factory import write_python_script_for_kml_document
        
        test_datafile = path.join(
            path.dirname(__file__),
            'testfiles',
            'google_kml_reference/altitudemode_reference.kml'
        )
        with open(test_datafile) as f:
            doc = parse(f, schema=None)
        script = write_python_script_for_kml_document(doc)
        self.assertEquals(
            script,
'from lxml import etree\n'
'from pykml.factory import KML_ElementMaker as KML\n'
'from pykml.factory import ATOM_ElementMaker as ATOM\n'
'from pykml.factory import GX_ElementMaker as GX\n'
'\n'
'doc = KML.kml(\n'
'  etree.Comment(\' required when using gx-prefixed elements \'),\n'
'  KML.Placemark(\n'
'    KML.name(\'gx:altitudeMode Example\'),\n'
'    KML.LookAt(\n'
'      KML.longitude(\'146.806\'),\n'
'      KML.latitude(\'12.219\'),\n'
'      KML.heading(\'-60\'),\n'
'      KML.tilt(\'70\'),\n'
'      KML.range(\'6300\'),\n'
'      GX.altitudeMode(\'relativeToSeaFloor\'),\n'
'    ),\n'
'    KML.LineString(\n'
'      KML.extrude(\'1\'),\n'
'      GX.altitudeMode(\'relativeToSeaFloor\'),\n'
'      KML.coordinates(\n'
'      \'146.825,12.233,400 \'\n'
'      \'146.820,12.222,400 \'\n'
'      \'146.812,12.212,400 \'\n'
'      \'146.796,12.209,400 \'\n'
'      \'146.788,12.205,400 \'\n'
'      ),\n'
'    ),\n'
'  ),\n'
')\n'
'print etree.tostring(etree.ElementTree(doc),pretty_print=True)\n'
        )
Example #8
0
    def test_write_python_script_for_kml_document(self):
        """Tests the creation of a trivial OGC KML document."""
        doc = KML.kml(
            KML.Document(
                ATOM.author(
                    ATOM.name('J. K. Rowling')
                ),
                ATOM.link(href='http://www.harrypotter.com'),
                KML.Placemark(
                    KML.name('Hogwarts'),
                    KML.Point(
                        KML.coordinates('1,1')
                    )
                )
            )
        )
        script = write_python_script_for_kml_document(doc)
        expected = \
            'from lxml import etree\n' \
            'from pykml.factory import KML_ElementMaker as KML\n' \
            'from pykml.factory import ATOM_ElementMaker as ATOM\n' \
            'from pykml.factory import GX_ElementMaker as GX\n' \
            '\n' \
            'doc = KML.kml(\n' \
            '  KML.Document(\n' \
            '    ATOM.author(\n' \
            '      ATOM.name(\'J. K. Rowling\'),\n' \
            '    ),\n' \
            '    ATOM.link(href=\'http://www.harrypotter.com\',\n' \
            '),\n' \
            '    KML.Placemark(\n' \
            '      KML.name(\'Hogwarts\'),\n' \
            '      KML.Point(\n' \
            '        KML.coordinates(\'1,1\'),\n' \
            '      ),\n' \
            '    ),\n' \
            '  ),\n' \
            ')\n' \
            'print(etree.tostring(etree.ElementTree(doc), \n' \
            '                     encoding=\'utf-8\', \n' \
            '                     xml_declaration=True, \n' \
            '                     pretty_print=True).decode(\'utf-8\'))\n'

        self.assertEqual(script, expected)
 def test_write_python_script_for_kml_document(self):
     """Tests the creation of a trivial OGC KML document."""
     from pykml.factory import write_python_script_for_kml_document
     
     doc = KML.kml(
         KML.Document(
             ATOM.author(
                 ATOM.name("J. K. Rowling")
             ),
             ATOM.link(href="http://www.harrypotter.com"),
             KML.Placemark(
                 KML.name("Hogwarts"),
                 KML.Point(
                     KML.coordinates("1,1")
                 )
             )
         )
     )
     script = write_python_script_for_kml_document(doc)
     self.assertEquals(
         script,
         'from lxml import etree\n'
         'from pykml.factory import KML_ElementMaker as KML\n'
         'from pykml.factory import ATOM_ElementMaker as ATOM\n'
         'from pykml.factory import GX_ElementMaker as GX\n'
         '\n'
         'doc = KML.kml(\n'
         '  KML.Document(\n'
         '    ATOM.author(\n'
         '      ATOM.name(\'J. K. Rowling\'),\n'
         '    ),\n'
         '    ATOM.link(  href="http://www.harrypotter.com",\n'
         '),\n'
         '    KML.Placemark(\n'
         '      KML.name(\'Hogwarts\'),\n'
         '      KML.Point(\n'
         '        KML.coordinates(\'1,1\'),\n'
         '      ),\n'
         '    ),\n'
         '  ),\n'
         ')\n'
         'print etree.tostring(etree.ElementTree(doc),pretty_print=True)\n'
     )
Example #10
0
def main(argv=None):
    if argv is None:
        argv = sys.argv
    try:
        try:
            opts, args = getopt.getopt(argv[1:], "h", ["help"])
        except getopt.error as msg:
             raise Usage(msg)
        # main code
        schema = Schema("kml22gx.xsd")
        filename = argv[1]
        with open(filename) as f:
            kmldoc = parse(f, schema=schema)
            print(write_python_script_for_kml_document(kmldoc))

    except Usage as err:
        print(err.msg, file=sys.stderr)
        print("for help use --help", file=sys.stderr)
        return 2
 def test_write_python_script_for_kml_document_with_comments(self):
     """Tests the creation of an OGC KML document with several comments"""
     import os
     import tempfile
     from pykml.parser import parse
     from pykml.factory import write_python_script_for_kml_document
     
     test_datafile = path.join(
         path.dirname(__file__),
         'testfiles',
         'simple_file_with_comments.kml'
     )
     schema = Schema('kml22gx.xsd')
     with open(test_datafile) as f:
         doc = parse(f, schema=schema)
     script = write_python_script_for_kml_document(doc)
     
     # create a temporary python file
     handle, tfile = tempfile.mkstemp(suffix='.py')
     #print tfile  # Useful for debugging
     with open(tfile, 'w') as f:
         f.write(script)
     
     # execute the temporary python file to create a KML file
     import subprocess
     current_env = os.environ.copy()
     current_env["PYTHONPATH"] = os.path.abspath(os.path.join(os.getcwd(),'..'))
     handle, temp_kml_file = tempfile.mkstemp(suffix='.kml')
     #print temp_kml_file  # Useful for debugging
     with open(temp_kml_file, 'w') as f:
         exit_code = subprocess.call(["python",tfile], stdout=f, env=current_env)
     self.assertEqual(exit_code, 0)
     
     # parse and validate the KML generated by the temporary script
     doc2 = parse(temp_kml_file, schema=schema)
     # test that the root element is as expected
     self.assertEqual(doc2.docinfo.root_name, 'kml')
     
     self.assertEqual(etree.tostring(doc), etree.tostring(doc2))
     
     #import ipdb; ipdb.set_trace()
     pass
Example #12
0
    def test_write_python_script_for_kml_document_with_comments(self):
        """Tests the creation of an OGC KML document with several comments"""
        import os
        import tempfile
        from pykml.parser import parse
        from pykml.factory import write_python_script_for_kml_document
        
        test_datafile = path.join(
            path.dirname(__file__),
            'testfiles',
            'simple_file_with_comments.kml'
        )
        schema = Schema('kml22gx.xsd')
        with open(test_datafile) as f:
            doc = parse(f, schema=schema)
        script = write_python_script_for_kml_document(doc)
        
        # create a temporary python file
        handle, tfile = tempfile.mkstemp(suffix='.py')
        #print tfile  # Useful for debugging
        with open(tfile, 'w') as f:
            f.write(script)
        
        # execute the temporary python file to create a KML file
        import subprocess
        current_env = os.environ.copy()
        current_env["PYTHONPATH"] = os.path.abspath(
                                    os.path.join(path.dirname(__file__),'../..')
                                )
        handle, temp_kml_file = tempfile.mkstemp(suffix='.kml')
        #print temp_kml_file  # Useful for debugging
        with open(temp_kml_file, 'w') as f:
            exit_code = subprocess.call(["python",tfile], stdout=f, env=current_env)
        self.assertEqual(exit_code, 0)
        
        # parse and validate the KML generated by the temporary script
        doc2 = parse(temp_kml_file, schema=schema)
        # test that the root element is as expected
        self.assertEqual(doc2.docinfo.root_name, 'kml')

        # test that the original and generated documents are equivalent
        self.assertTrue(compare_etree(doc.getroot(), doc2.getroot()))
Example #13
0
 def test_write_python_script_for_kml_document_with_namespaces(self):
     """Tests the creation of an OGC KML document with several namespaces"""
     import os
     import tempfile
     from pykml.parser import parse
     from pykml.factory import write_python_script_for_kml_document
     
     test_datafile = path.join(
         path.dirname(__file__),
         'testfiles',
         'google_kml_developers_guide/complete_tour_example.kml'
     )
     schema = Schema('kml22gx.xsd')
     with open(test_datafile) as f:
         doc = parse(f, schema=schema)
     script = write_python_script_for_kml_document(doc)
     
     # create a temporary python file
     handle, tfile = tempfile.mkstemp(suffix='.py')
     #print tfile  #uncomment to print the temporary filename
     with open(tfile, 'w') as f:
         f.write(script)
     
     # execute the temporary python file to create a KML file
     # set the PYTHONPATH variable so that it references the root
     # of the pyKML library
     import subprocess
     current_env = os.environ.copy()
     current_env["PYTHONPATH"] = os.path.abspath(
                                 os.path.join(path.dirname(__file__),'../..')
                             )
     handle, temp_kml_file = tempfile.mkstemp(suffix='.kml')
     #print temp_kml_file
     with open(temp_kml_file, 'w') as f:
         exit_code = subprocess.call(["python",tfile], stdout=f, env=current_env)
     self.assertEqual(exit_code, 0)
     
     # parse and validate the KML generated by the temporary script
     doc2 = parse(temp_kml_file, schema=schema)
     # test that the root element is as expected
     self.assertEqual(doc2.docinfo.root_name, 'kml')
Example #14
0
 def test_write_python_script_for_kml_document_with_namespaces(self):
     """Tests the creation of an OGC KML document with several namespaces"""
     import os
     import tempfile
     from pykml.parser import parse
     from pykml.factory import write_python_script_for_kml_document
     
     test_datafile = path.join(
         path.dirname(__file__),
         'testfiles',
         'google_kml_developers_guide/complete_tour_example.kml'
     )
     schema = Schema('kml22gx.xsd')
     with open(test_datafile) as f:
         doc = parse(f, schema=schema)
     script = write_python_script_for_kml_document(doc)
     
     # create a temporary python file
     handle, tfile = tempfile.mkstemp(suffix='.py')
     #print tfile  #uncomment to print the temporary filename
     with open(tfile, 'w') as f:
         f.write(script)
     
     # execute the temporary python file to create a KML file
     # set the PYTHONPATH variable so that it references the root
     # of the pyKML library
     import subprocess
     current_env = os.environ.copy()
     current_env["PYTHONPATH"] = os.path.abspath(
                                 os.path.join(path.dirname(__file__),'../..')
                             )
     handle, temp_kml_file = tempfile.mkstemp(suffix='.kml')
     #print temp_kml_file
     with open(temp_kml_file, 'w') as f:
         exit_code = subprocess.call(["python",tfile], stdout=f, env=current_env)
     self.assertEqual(exit_code, 0)
     
     # parse and validate the KML generated by the temporary script
     doc2 = parse(temp_kml_file, schema=schema)
     # test that the root element is as expected
     self.assertEqual(doc2.docinfo.root_name, 'kml')
Example #15
0
def kml2pykml(*args):
    if args is None:
        args = sys.argv

    parser = argparse.ArgumentParser(description='Convert KML to pyKML')
    parser.add_argument('input', help='file name or URL of KML')
    parser.add_argument('-v', '--version', action='version',
                        version=f'%(prog)s {pykml_version}')

    # ArgumentParser can throw a SystemExit
    namespace = parser.parse_args(args=args)

    try:
        with get_xml_file_object(namespace.input) as file_object:
            # There is no schema as no validation occurs
            kmldoc = parse(file_object)
            print(write_python_script_for_kml_document(kmldoc))
            return 0

    except FileOpenException as e:
        print('Unable to retrieve "{}"'.format(namespace.input), file=sys.stderr)
        print('Error:', e.args[0], file=sys.stderr)
        return 1
Example #16
0
 def test_write_python_script_for_kml_document_with_cdata(self):
     """Tests the creation of an OGC KML document with a cdata tag"""
     import os
     import tempfile
     from pykml.parser import parse
     from pykml.factory import write_python_script_for_kml_document
     
     test_datafile = path.join(
         path.dirname(__file__),
         'testfiles',
         'google_kml_tutorial/using_the_cdata_element.kml'
     )
     file = 'test/testfiles/'
     schema = Schema('kml22gx.xsd')
     with open(test_datafile) as f:
         doc = parse(f, schema=schema)
     script = write_python_script_for_kml_document(doc)
     self.assertEquals(
         script,
         'from lxml import etree\n'
         'from pykml.factory import KML_ElementMaker as KML\n'
         'from pykml.factory import ATOM_ElementMaker as ATOM\n'
         'from pykml.factory import GX_ElementMaker as GX\n'
         '\n'
         'doc = KML.kml(\n'
         '  KML.Document(\n'
         '    KML.Placemark(\n'
         '      KML.name(\'CDATA example\'),\n'
         '      KML.description(\n'
         '          \'<h1>CDATA Tags are useful!</h1> \'\n'
         '          \'<p><font color="red">Text is <i>more readable</i> and \'\n'
         '          \'<b>easier to write</b> when you can avoid using entity \'\n'
         '          \'references.</font></p> \'\n'
         '      ),\n'
         '      KML.Point(\n'
         '        KML.coordinates(\'102.595626,14.996729\'),\n'
         '      ),\n'
         '    ),\n'
         '  ),\n'
         ')\n'
         'print etree.tostring(etree.ElementTree(doc),pretty_print=True)\n'
     )
     # create a temporary python file
     handle, tfile = tempfile.mkstemp(suffix='.py')
     #print tfile
     with open(tfile, 'w') as f:
         f.write(script)
     
     # execute the temporary python file to create a KML file
     import subprocess
     current_env = os.environ.copy()
     current_env["PYTHONPATH"] = os.path.abspath(
                                 os.path.join(path.dirname(__file__),'../..')
                             )
     handle, temp_kml_file = tempfile.mkstemp(suffix='.kml')
     with open(temp_kml_file, 'w') as f:
         exit_code = subprocess.call(
                 ["python",tfile],
                 stdout=f,
                 env=current_env
         )
     self.assertEqual(exit_code, 0)
     
     # parse and validate the KML generated by the temporary script
     doc2 = parse(temp_kml_file, schema=schema)
     # test that the root element is as expected
     self.assertEqual(doc2.docinfo.root_name, 'kml')
Example #17
0
from pykml.factory import KML_ElementMaker as KML
from pykml.factory import ATOM_ElementMaker as ATOM
from pykml.factory import GX_ElementMaker as GX
from lxml import etree
from pykml import parser

from pykml.factory import write_python_script_for_kml_document
from os import path
kml_file = path.join( \
    './test', \
    'Mouton_Citrus.kml')
with open(kml_file) as f:
    doc = parser.parse(f).getroot()

script = write_python_script_for_kml_document(doc)

print script
print etree.tostring(etree.ElementTree(doc), pretty_print=True)
Example #18
0
    def test_write_python_script_for_kml_document_with_cdata(self):
        """Tests the creation of an OGC KML document with a cdata tag"""
        test_datafile = (Path(__file__).parent /
                         'testfiles' /
                         'google_kml_tutorial' /
                         'using_the_cdata_element.kml')
        schema = Schema('kml22gx.xsd')
        with test_datafile.open('rb') as f:
            doc = pykml.parser.parse(f, schema=schema)
        script = write_python_script_for_kml_document(doc)
        expected = \
            'from lxml import etree\n' \
            'from pykml.factory import KML_ElementMaker as KML\n' \
            'from pykml.factory import ATOM_ElementMaker as ATOM\n' \
            'from pykml.factory import GX_ElementMaker as GX\n' \
            '\n' \
            'doc = KML.kml(\n' \
            '  KML.Document(\n' \
            '    KML.Placemark(\n' \
            '      KML.name(\'CDATA example\'),\n' \
            '      KML.description(\n' \
            '          \'<h1>CDATA Tags are useful!</h1> \'\n' \
            '          \'<p><font color="red">Text is <i>more readable</i> and \'\n' \
            '          \'<b>easier to write</b> when you can avoid using entity \'\n' \
            '          \'references.</font></p> \'\n' \
            '      ),\n' \
            '      KML.Point(\n' \
            '        KML.coordinates(\'102.595626,14.996729\'),\n' \
            '      ),\n' \
            '    ),\n' \
            '  ),\n' \
            ')\n' \
            'print(etree.tostring(etree.ElementTree(doc), \n' \
            '                     encoding=\'utf-8\', \n' \
            '                     xml_declaration=True, \n' \
            '                     pretty_print=True).decode(\'utf-8\'))\n'

        self.assertEqual(script, expected)

        # create a temporary python file
        with tempfile.NamedTemporaryFile(mode='wt', suffix='.py', delete=False) as f:
            temp_python_file = f.name
            f.write(script)

        # Execute the temporary python file to create a KML file.
        # PYTHONPATH may need to be set so that the pykml module is found.
        current_env = os.environ.copy()
        # May be required if not using an IDE.
        # current_env['PYTHONPATH'] = os.fspath(Path(__file__).parent)

        with tempfile.NamedTemporaryFile(mode='wb', suffix='.kml', delete=False) as f:
            temp_kml_file = f.name
            exit_code = subprocess.call(['python', temp_python_file], stdout=f, env=current_env)
        self.assertEqual(exit_code, 0)

        # parse and validate the KML generated by the temporary script
        doc2 = pykml.parser.parse(temp_kml_file, schema=schema)
        # test that the root element is as expected
        self.assertEqual(doc2.docinfo.root_name, 'kml')

        os.unlink(temp_python_file)
        os.unlink(temp_kml_file)
 def test_write_python_script_for_kml_document_with_cdata(self):
     """Tests the creation of an OGC KML document with a cdata tag"""
     import os
     import tempfile
     from pykml.parser import parse
     from pykml.factory import write_python_script_for_kml_document
     
     test_datafile = path.join(
         path.dirname(__file__),
         'testfiles',
         'google_kml_tutorial/using_the_cdata_element.kml'
     )
     file = 'test/testfiles/'
     schema = Schema('kml22gx.xsd')
     with open(test_datafile) as f:
         doc = parse(f, schema=schema)
     script = write_python_script_for_kml_document(doc)
     self.assertEquals(
         script,
         'from lxml import etree\n'
         'from pykml.factory import KML_ElementMaker as KML\n'
         'from pykml.factory import ATOM_ElementMaker as ATOM\n'
         'from pykml.factory import GX_ElementMaker as GX\n'
         '\n'
         'doc = KML.kml(\n'
         '  KML.Document(\n'
         '    KML.Placemark(\n'
         '      KML.name(\'CDATA example\'),\n'
         '      KML.description(\n'
         '          \'<h1>CDATA Tags are useful!</h1>\'\n'
         '          \'<p><font color="red">Text is <i>more readable</i> and \'\n'
         '          \'<b>easier to write</b> when you can avoid using entity \'\n'
         '          \'references.</font></p>\'\n'
         '      ),\n'
         '      KML.Point(\n'
         '        KML.coordinates(\'102.595626,14.996729\'),\n'
         '      ),\n'
         '    ),\n'
         '  ),\n'
         ')\n'
         'print etree.tostring(etree.ElementTree(doc),pretty_print=True)\n'
     )
     # create a temporary python file
     handle, tfile = tempfile.mkstemp(suffix='.py')
     #print tfile
     with open(tfile, 'w') as f:
         f.write(script)
     
     # execute the temporary python file to create a KML file
     import subprocess
     current_env = os.environ.copy()
     current_env["PYTHONPATH"] = os.path.abspath(os.path.join(os.getcwd(),'..'))
     handle, temp_kml_file = tempfile.mkstemp(suffix='.kml')
     #print temp_kml_file
     with open(temp_kml_file, 'w') as f:
         exit_code = subprocess.call(
                 ["python",tfile],
                 stdout=f,
                 env=current_env
         )
     self.assertEqual(exit_code, 0)
     
     # parse and validate the KML generated by the temporary script
     doc2 = parse(temp_kml_file, schema=schema)
     # test that the root element is as expected
     self.assertEqual(doc2.docinfo.root_name, 'kml')