test_windows_wrappers.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. """
  2. Python Script Wrapper for Windows
  3. =================================
  4. setuptools includes wrappers for Python scripts that allows them to be
  5. executed like regular windows programs. There are 2 wrappers, one
  6. for command-line programs, cli.exe, and one for graphical programs,
  7. gui.exe. These programs are almost identical, function pretty much
  8. the same way, and are generated from the same source file. The
  9. wrapper programs are used by copying them to the directory containing
  10. the script they are to wrap and with the same name as the script they
  11. are to wrap.
  12. """
  13. from __future__ import absolute_import
  14. import sys
  15. import textwrap
  16. import subprocess
  17. import pytest
  18. from setuptools.command.easy_install import nt_quote_arg
  19. import pkg_resources
  20. pytestmark = pytest.mark.skipif(sys.platform != 'win32', reason="Windows only")
  21. class WrapperTester:
  22. @classmethod
  23. def prep_script(cls, template):
  24. python_exe = nt_quote_arg(sys.executable)
  25. return template % locals()
  26. @classmethod
  27. def create_script(cls, tmpdir):
  28. """
  29. Create a simple script, foo-script.py
  30. Note that the script starts with a Unix-style '#!' line saying which
  31. Python executable to run. The wrapper will use this line to find the
  32. correct Python executable.
  33. """
  34. script = cls.prep_script(cls.script_tmpl)
  35. with (tmpdir / cls.script_name).open('w') as f:
  36. f.write(script)
  37. # also copy cli.exe to the sample directory
  38. with (tmpdir / cls.wrapper_name).open('wb') as f:
  39. w = pkg_resources.resource_string('setuptools', cls.wrapper_source)
  40. f.write(w)
  41. class TestCLI(WrapperTester):
  42. script_name = 'foo-script.py'
  43. wrapper_source = 'cli-32.exe'
  44. wrapper_name = 'foo.exe'
  45. script_tmpl = textwrap.dedent("""
  46. #!%(python_exe)s
  47. import sys
  48. input = repr(sys.stdin.read())
  49. print(sys.argv[0][-14:])
  50. print(sys.argv[1:])
  51. print(input)
  52. if __debug__:
  53. print('non-optimized')
  54. """).lstrip()
  55. def test_basic(self, tmpdir):
  56. """
  57. When the copy of cli.exe, foo.exe in this example, runs, it examines
  58. the path name it was run with and computes a Python script path name
  59. by removing the '.exe' suffix and adding the '-script.py' suffix. (For
  60. GUI programs, the suffix '-script.pyw' is added.) This is why we
  61. named out script the way we did. Now we can run out script by running
  62. the wrapper:
  63. This example was a little pathological in that it exercised windows
  64. (MS C runtime) quoting rules:
  65. - Strings containing spaces are surrounded by double quotes.
  66. - Double quotes in strings need to be escaped by preceding them with
  67. back slashes.
  68. - One or more backslashes preceding double quotes need to be escaped
  69. by preceding each of them with back slashes.
  70. """
  71. self.create_script(tmpdir)
  72. cmd = [
  73. str(tmpdir / 'foo.exe'),
  74. 'arg1',
  75. 'arg 2',
  76. 'arg "2\\"',
  77. 'arg 4\\',
  78. 'arg5 a\\\\b',
  79. ]
  80. proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE)
  81. stdout, stderr = proc.communicate('hello\nworld\n'.encode('ascii'))
  82. actual = stdout.decode('ascii').replace('\r\n', '\n')
  83. expected = textwrap.dedent(r"""
  84. \foo-script.py
  85. ['arg1', 'arg 2', 'arg "2\\"', 'arg 4\\', 'arg5 a\\\\b']
  86. 'hello\nworld\n'
  87. non-optimized
  88. """).lstrip()
  89. assert actual == expected
  90. def test_with_options(self, tmpdir):
  91. """
  92. Specifying Python Command-line Options
  93. --------------------------------------
  94. You can specify a single argument on the '#!' line. This can be used
  95. to specify Python options like -O, to run in optimized mode or -i
  96. to start the interactive interpreter. You can combine multiple
  97. options as usual. For example, to run in optimized mode and
  98. enter the interpreter after running the script, you could use -Oi:
  99. """
  100. self.create_script(tmpdir)
  101. tmpl = textwrap.dedent("""
  102. #!%(python_exe)s -Oi
  103. import sys
  104. input = repr(sys.stdin.read())
  105. print(sys.argv[0][-14:])
  106. print(sys.argv[1:])
  107. print(input)
  108. if __debug__:
  109. print('non-optimized')
  110. sys.ps1 = '---'
  111. """).lstrip()
  112. with (tmpdir / 'foo-script.py').open('w') as f:
  113. f.write(self.prep_script(tmpl))
  114. cmd = [str(tmpdir / 'foo.exe')]
  115. proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT)
  116. stdout, stderr = proc.communicate()
  117. actual = stdout.decode('ascii').replace('\r\n', '\n')
  118. expected = textwrap.dedent(r"""
  119. \foo-script.py
  120. []
  121. ''
  122. ---
  123. """).lstrip()
  124. assert actual == expected
  125. class TestGUI(WrapperTester):
  126. """
  127. Testing the GUI Version
  128. -----------------------
  129. """
  130. script_name = 'bar-script.pyw'
  131. wrapper_source = 'gui-32.exe'
  132. wrapper_name = 'bar.exe'
  133. script_tmpl = textwrap.dedent("""
  134. #!%(python_exe)s
  135. import sys
  136. f = open(sys.argv[1], 'wb')
  137. bytes_written = f.write(repr(sys.argv[2]).encode('utf-8'))
  138. f.close()
  139. """).strip()
  140. def test_basic(self, tmpdir):
  141. """Test the GUI version with the simple scipt, bar-script.py"""
  142. self.create_script(tmpdir)
  143. cmd = [
  144. str(tmpdir / 'bar.exe'),
  145. str(tmpdir / 'test_output.txt'),
  146. 'Test Argument',
  147. ]
  148. proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT)
  149. stdout, stderr = proc.communicate()
  150. assert not stdout
  151. assert not stderr
  152. with (tmpdir / 'test_output.txt').open('rb') as f_out:
  153. actual = f_out.read().decode('ascii')
  154. assert actual == repr('Test Argument')