PageRenderTime 39ms CodeModel.GetById 11ms app.highlight 23ms RepoModel.GetById 1ms app.codeStats 0ms

/Lib/test/test_cmd_line_script.py

http://unladen-swallow.googlecode.com/
Python | 224 lines | 216 code | 6 blank | 2 comment | 1 complexity | 3cb61302857d751695c142d5dbc4fb98 MD5 | raw file
  1# Tests command line execution of scripts
  2
  3import unittest
  4import os
  5import os.path
  6import sys
  7import test.test_support
  8import tempfile
  9import subprocess
 10import py_compile
 11import contextlib
 12import shutil
 13import zipfile
 14
 15verbose = test.test_support.verbose
 16
 17# XXX ncoghlan: Should we consider moving these to test_support?
 18from test_cmd_line import _spawn_python, _exhaust_python
 19
 20def _run_python(*args):
 21    if __debug__:
 22        p = _spawn_python(*args)
 23    else:
 24        p = _spawn_python('-O', *args)
 25    stdout_data, return_code = _exhaust_python(p)
 26    return return_code, stdout_data
 27
 28@contextlib.contextmanager
 29def temp_dir():
 30    dirname = tempfile.mkdtemp()
 31    dirname = os.path.realpath(dirname)
 32    try:
 33        yield dirname
 34    finally:
 35        shutil.rmtree(dirname)
 36
 37test_source = """\
 38# Script may be run with optimisation enabled, so don't rely on assert
 39# statements being executed
 40def assertEqual(lhs, rhs):
 41    if lhs != rhs:
 42        raise AssertionError('%r != %r' % (lhs, rhs))
 43def assertIdentical(lhs, rhs):
 44    if lhs is not rhs:
 45        raise AssertionError('%r is not %r' % (lhs, rhs))
 46# Check basic code execution
 47result = ['Top level assignment']
 48def f():
 49    result.append('Lower level reference')
 50f()
 51assertEqual(result, ['Top level assignment', 'Lower level reference'])
 52# Check population of magic variables
 53assertEqual(__name__, '__main__')
 54print '__file__==%r' % __file__
 55print '__package__==%r' % __package__
 56# Check the sys module
 57import sys
 58assertIdentical(globals(), sys.modules[__name__].__dict__)
 59print 'sys.argv[0]==%r' % sys.argv[0]
 60"""
 61
 62def _make_test_script(script_dir, script_basename, source=test_source):
 63    script_filename = script_basename+os.extsep+'py'
 64    script_name = os.path.join(script_dir, script_filename)
 65    script_file = open(script_name, 'w')
 66    script_file.write(source)
 67    script_file.close()
 68    return script_name
 69
 70def _compile_test_script(script_name):
 71    py_compile.compile(script_name, doraise=True)
 72    if __debug__:
 73        compiled_name = script_name + 'c'
 74    else:
 75        compiled_name = script_name + 'o'
 76    return compiled_name
 77
 78def _make_test_zip(zip_dir, zip_basename, script_name, name_in_zip=None):
 79    zip_filename = zip_basename+os.extsep+'zip'
 80    zip_name = os.path.join(zip_dir, zip_filename)
 81    zip_file = zipfile.ZipFile(zip_name, 'w')
 82    if name_in_zip is None:
 83        name_in_zip = os.path.basename(script_name)
 84    zip_file.write(script_name, name_in_zip)
 85    zip_file.close()
 86    #if verbose:
 87    #    zip_file = zipfile.ZipFile(zip_name, 'r')
 88    #    print 'Contents of %r:' % zip_name
 89    #    zip_file.printdir()
 90    #    zip_file.close()
 91    return zip_name, os.path.join(zip_name, name_in_zip)
 92
 93def _make_test_pkg(pkg_dir):
 94    os.mkdir(pkg_dir)
 95    _make_test_script(pkg_dir, '__init__', '')
 96
 97def _make_test_zip_pkg(zip_dir, zip_basename, pkg_name, script_basename,
 98                       source=test_source, depth=1):
 99    init_name = _make_test_script(zip_dir, '__init__', '')
100    init_basename = os.path.basename(init_name)
101    script_name = _make_test_script(zip_dir, script_basename, source)
102    pkg_names = [os.sep.join([pkg_name]*i) for i in range(1, depth+1)]
103    script_name_in_zip = os.path.join(pkg_names[-1], os.path.basename(script_name))
104    zip_filename = zip_basename+os.extsep+'zip'
105    zip_name = os.path.join(zip_dir, zip_filename)
106    zip_file = zipfile.ZipFile(zip_name, 'w')
107    for name in pkg_names:
108        init_name_in_zip = os.path.join(name, init_basename)
109        zip_file.write(init_name, init_name_in_zip)
110    zip_file.write(script_name, script_name_in_zip)
111    zip_file.close()
112    os.unlink(init_name)
113    os.unlink(script_name)
114    #if verbose:
115    #    zip_file = zipfile.ZipFile(zip_name, 'r')
116    #    print 'Contents of %r:' % zip_name
117    #    zip_file.printdir()
118    #    zip_file.close()
119    return zip_name, os.path.join(zip_name, script_name_in_zip)
120
121# There's no easy way to pass the script directory in to get
122# -m to work (avoiding that is the whole point of making
123# directories and zipfiles executable!)
124# So we fake it for testing purposes with a custom launch script
125launch_source = """\
126import sys, os.path, runpy
127sys.path.insert(0, %s)
128runpy._run_module_as_main(%r)
129"""
130
131def _make_launch_script(script_dir, script_basename, module_name, path=None):
132    if path is None:
133        path = "os.path.dirname(__file__)"
134    else:
135        path = repr(path)
136    source = launch_source % (path, module_name)
137    return _make_test_script(script_dir, script_basename, source)
138
139class CmdLineTest(unittest.TestCase):
140    def _check_script(self, script_name, expected_file,
141                            expected_argv0, expected_package,
142                            *cmd_line_switches):
143        run_args = cmd_line_switches + (script_name,)
144        exit_code, data = _run_python(*run_args)
145        if verbose:
146            print 'Output from test script %r:' % script_name
147            print data
148        self.assertEqual(exit_code, 0)
149        printed_file = '__file__==%r' % expected_file
150        printed_argv0 = 'sys.argv[0]==%r' % expected_argv0
151        printed_package = '__package__==%r' % expected_package
152        if verbose:
153            print 'Expected output:'
154            print printed_file
155            print printed_package
156            print printed_argv0
157        self.assert_(printed_file in data)
158        self.assert_(printed_package in data)
159        self.assert_(printed_argv0 in data)
160
161    def test_basic_script(self):
162        with temp_dir() as script_dir:
163            script_name = _make_test_script(script_dir, 'script')
164            self._check_script(script_name, script_name, script_name, None)
165
166    def test_script_compiled(self):
167        with temp_dir() as script_dir:
168            script_name = _make_test_script(script_dir, 'script')
169            compiled_name = _compile_test_script(script_name)
170            os.remove(script_name)
171            self._check_script(compiled_name, compiled_name, compiled_name, None)
172
173    def test_directory(self):
174        with temp_dir() as script_dir:
175            script_name = _make_test_script(script_dir, '__main__')
176            self._check_script(script_dir, script_name, script_dir, '')
177
178    def test_directory_compiled(self):
179        with temp_dir() as script_dir:
180            script_name = _make_test_script(script_dir, '__main__')
181            compiled_name = _compile_test_script(script_name)
182            os.remove(script_name)
183            self._check_script(script_dir, compiled_name, script_dir, '')
184
185    def test_zipfile(self):
186        with temp_dir() as script_dir:
187            script_name = _make_test_script(script_dir, '__main__')
188            zip_name, run_name = _make_test_zip(script_dir, 'test_zip', script_name)
189            self._check_script(zip_name, run_name, zip_name, '')
190
191    def test_zipfile_compiled(self):
192        with temp_dir() as script_dir:
193            script_name = _make_test_script(script_dir, '__main__')
194            compiled_name = _compile_test_script(script_name)
195            zip_name, run_name = _make_test_zip(script_dir, 'test_zip', compiled_name)
196            self._check_script(zip_name, run_name, zip_name, '')
197
198    def test_module_in_package(self):
199        with temp_dir() as script_dir:
200            pkg_dir = os.path.join(script_dir, 'test_pkg')
201            _make_test_pkg(pkg_dir)
202            script_name = _make_test_script(pkg_dir, 'script')
203            launch_name = _make_launch_script(script_dir, 'launch', 'test_pkg.script')
204            self._check_script(launch_name, script_name, script_name, 'test_pkg')
205
206    def test_module_in_package_in_zipfile(self):
207        with temp_dir() as script_dir:
208            zip_name, run_name = _make_test_zip_pkg(script_dir, 'test_zip', 'test_pkg', 'script')
209            launch_name = _make_launch_script(script_dir, 'launch', 'test_pkg.script', zip_name)
210            self._check_script(launch_name, run_name, run_name, 'test_pkg')
211
212    def test_module_in_subpackage_in_zipfile(self):
213        with temp_dir() as script_dir:
214            zip_name, run_name = _make_test_zip_pkg(script_dir, 'test_zip', 'test_pkg', 'script', depth=2)
215            launch_name = _make_launch_script(script_dir, 'launch', 'test_pkg.test_pkg.script', zip_name)
216            self._check_script(launch_name, run_name, run_name, 'test_pkg.test_pkg')
217
218
219def test_main():
220    test.test_support.run_unittest(CmdLineTest)
221    test.test_support.reap_children()
222
223if __name__ == '__main__':
224    test_main()