test_upload.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. """Tests for distutils.command.upload."""
  2. import os
  3. import unittest
  4. import unittest.mock as mock
  5. from urllib.request import HTTPError
  6. from test.support import run_unittest
  7. from distutils.command import upload as upload_mod
  8. from distutils.command.upload import upload
  9. from distutils.core import Distribution
  10. from distutils.errors import DistutilsError
  11. from distutils.log import ERROR, INFO
  12. from distutils.tests.test_config import PYPIRC, PyPIRCCommandTestCase
  13. PYPIRC_LONG_PASSWORD = """\
  14. [distutils]
  15. index-servers =
  16. server1
  17. server2
  18. [server1]
  19. username:me
  20. password:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
  21. [server2]
  22. username:meagain
  23. password: secret
  24. realm:acme
  25. repository:http://another.pypi/
  26. """
  27. PYPIRC_NOPASSWORD = """\
  28. [distutils]
  29. index-servers =
  30. server1
  31. [server1]
  32. username:me
  33. """
  34. class FakeOpen(object):
  35. def __init__(self, url, msg=None, code=None):
  36. self.url = url
  37. if not isinstance(url, str):
  38. self.req = url
  39. else:
  40. self.req = None
  41. self.msg = msg or 'OK'
  42. self.code = code or 200
  43. def getheader(self, name, default=None):
  44. return {
  45. 'content-type': 'text/plain; charset=utf-8',
  46. }.get(name.lower(), default)
  47. def read(self):
  48. return b'xyzzy'
  49. def getcode(self):
  50. return self.code
  51. class uploadTestCase(PyPIRCCommandTestCase):
  52. def setUp(self):
  53. super(uploadTestCase, self).setUp()
  54. self.old_open = upload_mod.urlopen
  55. upload_mod.urlopen = self._urlopen
  56. self.last_open = None
  57. self.next_msg = None
  58. self.next_code = None
  59. def tearDown(self):
  60. upload_mod.urlopen = self.old_open
  61. super(uploadTestCase, self).tearDown()
  62. def _urlopen(self, url):
  63. self.last_open = FakeOpen(url, msg=self.next_msg, code=self.next_code)
  64. return self.last_open
  65. def test_finalize_options(self):
  66. # new format
  67. self.write_file(self.rc, PYPIRC)
  68. dist = Distribution()
  69. cmd = upload(dist)
  70. cmd.finalize_options()
  71. for attr, waited in (('username', 'me'), ('password', 'secret'),
  72. ('realm', 'pypi'),
  73. ('repository', 'https://pypi.python.org/pypi')):
  74. self.assertEqual(getattr(cmd, attr), waited)
  75. def test_saved_password(self):
  76. # file with no password
  77. self.write_file(self.rc, PYPIRC_NOPASSWORD)
  78. # make sure it passes
  79. dist = Distribution()
  80. cmd = upload(dist)
  81. cmd.finalize_options()
  82. self.assertEqual(cmd.password, None)
  83. # make sure we get it as well, if another command
  84. # initialized it at the dist level
  85. dist.password = 'xxx'
  86. cmd = upload(dist)
  87. cmd.finalize_options()
  88. self.assertEqual(cmd.password, 'xxx')
  89. def test_upload(self):
  90. tmp = self.mkdtemp()
  91. path = os.path.join(tmp, 'xxx')
  92. self.write_file(path)
  93. command, pyversion, filename = 'xxx', '2.6', path
  94. dist_files = [(command, pyversion, filename)]
  95. self.write_file(self.rc, PYPIRC_LONG_PASSWORD)
  96. # lets run it
  97. pkg_dir, dist = self.create_dist(dist_files=dist_files)
  98. cmd = upload(dist)
  99. cmd.show_response = 1
  100. cmd.ensure_finalized()
  101. cmd.run()
  102. # what did we send ?
  103. headers = dict(self.last_open.req.headers)
  104. self.assertEqual(headers['Content-length'], '2161')
  105. content_type = headers['Content-type']
  106. self.assertTrue(content_type.startswith('multipart/form-data'))
  107. self.assertEqual(self.last_open.req.get_method(), 'POST')
  108. expected_url = 'https://pypi.python.org/pypi'
  109. self.assertEqual(self.last_open.req.get_full_url(), expected_url)
  110. self.assertTrue(b'xxx' in self.last_open.req.data)
  111. # The PyPI response body was echoed
  112. results = self.get_logs(INFO)
  113. self.assertEqual(results[-1], 75 * '-' + '\nxyzzy\n' + 75 * '-')
  114. def test_upload_fails(self):
  115. self.next_msg = "Not Found"
  116. self.next_code = 404
  117. self.assertRaises(DistutilsError, self.test_upload)
  118. def test_wrong_exception_order(self):
  119. tmp = self.mkdtemp()
  120. path = os.path.join(tmp, 'xxx')
  121. self.write_file(path)
  122. dist_files = [('xxx', '2.6', path)] # command, pyversion, filename
  123. self.write_file(self.rc, PYPIRC_LONG_PASSWORD)
  124. pkg_dir, dist = self.create_dist(dist_files=dist_files)
  125. tests = [
  126. (OSError('oserror'), 'oserror', OSError),
  127. (HTTPError('url', 400, 'httperror', {}, None),
  128. 'Upload failed (400): httperror', DistutilsError),
  129. ]
  130. for exception, expected, raised_exception in tests:
  131. with self.subTest(exception=type(exception).__name__):
  132. with mock.patch('distutils.command.upload.urlopen',
  133. new=mock.Mock(side_effect=exception)):
  134. with self.assertRaises(raised_exception):
  135. cmd = upload(dist)
  136. cmd.ensure_finalized()
  137. cmd.run()
  138. results = self.get_logs(ERROR)
  139. self.assertIn(expected, results[-1])
  140. self.clear_logs()
  141. def test_suite():
  142. return unittest.makeSuite(uploadTestCase)
  143. if __name__ == "__main__":
  144. run_unittest(test_suite())