/Lib/test/test_cmd_line_script.py

http://unladen-swallow.googlecode.com/ · Python · 224 lines · 182 code · 26 blank · 16 comment · 23 complexity · 3cb61302857d751695c142d5dbc4fb98 MD5 · raw file

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