/
test_upload.py
453 lines (365 loc) · 13.6 KB
/
test_upload.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
# Copyright 2014 Ian Cordasco
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
import os
import pretend
import pytest
import requests
from twine import cli
from twine import exceptions
from twine import package as package_file
from twine.commands import upload
from . import helpers
RELEASE_URL = "https://pypi.org/project/twine/1.5.0/"
NEW_RELEASE_URL = "https://pypi.org/project/twine/1.6.5/"
@pytest.fixture
def stub_response():
"""Mock successful upload of a package."""
return pretend.stub(
is_redirect=False, status_code=201, raise_for_status=lambda: None
)
@pytest.fixture
def stub_repository(stub_response):
"""Allow assertions on the uploaded package."""
return pretend.stub(
upload=pretend.call_recorder(lambda package: stub_response),
close=lambda: None,
release_urls=lambda packages: set(),
)
@pytest.fixture
def upload_settings(make_settings, stub_repository):
"""Use the stub repository when uploading."""
upload_settings = make_settings()
upload_settings.create_repository = lambda: stub_repository
return upload_settings
@pytest.fixture
def caplog(caplog):
caplog.set_level(logging.INFO, logger="twine")
return caplog
def test_make_package_pre_signed_dist(upload_settings, caplog):
"""Create a PackageFile and print path, size, and user-provided signature."""
filename = helpers.WHEEL_FIXTURE
expected_size = "15.4 KB"
signed_filename = helpers.WHEEL_FIXTURE + ".asc"
signatures = {os.path.basename(signed_filename): signed_filename}
upload_settings.sign = True
upload_settings.verbose = True
package = upload._make_package(filename, signatures, upload_settings)
assert package.filename == filename
assert package.gpg_signature is not None
captured = caplog.text
assert captured.count(f"{filename} ({expected_size})") == 1
assert captured.count(f"Signed with {signed_filename}") == 1
def test_make_package_unsigned_dist(upload_settings, monkeypatch, caplog):
"""Create a PackageFile and print path, size, and Twine-generated signature."""
filename = helpers.NEW_WHEEL_FIXTURE
expected_size = "21.9 KB"
signatures = {}
upload_settings.sign = True
upload_settings.verbose = True
def stub_sign(package, *_):
package.gpg_signature = (package.signed_basefilename, b"signature")
monkeypatch.setattr(package_file.PackageFile, "sign", stub_sign)
package = upload._make_package(filename, signatures, upload_settings)
assert package.filename == filename
assert package.gpg_signature is not None
captured = caplog.text
assert captured.count(f"{filename} ({expected_size})") == 1
assert captured.count(f"Signed with {package.signed_filename}") == 1
def test_successs_prints_release_urls(upload_settings, stub_repository, capsys):
"""Print PyPI release URLS for each uploaded package."""
stub_repository.release_urls = lambda packages: {RELEASE_URL, NEW_RELEASE_URL}
result = upload.upload(
upload_settings,
[
helpers.WHEEL_FIXTURE,
helpers.SDIST_FIXTURE,
helpers.NEW_SDIST_FIXTURE,
helpers.NEW_WHEEL_FIXTURE,
],
)
assert result is None
captured = capsys.readouterr()
assert captured.out.count(RELEASE_URL) == 1
assert captured.out.count(NEW_RELEASE_URL) == 1
def test_print_packages_if_verbose(upload_settings, caplog):
"""Print the path and file size of each distribution attempting to be uploaded."""
dists_to_upload = {
helpers.WHEEL_FIXTURE: "15.4 KB",
helpers.SDIST_FIXTURE: "20.8 KB",
helpers.NEW_SDIST_FIXTURE: "26.1 KB",
helpers.NEW_WHEEL_FIXTURE: "21.9 KB",
}
upload_settings.verbose = True
result = upload.upload(upload_settings, dists_to_upload)
assert result is None
captured = caplog.text
for filename, size in dists_to_upload.items():
assert captured.count(f"{filename} ({size})") == 1
def test_success_with_pre_signed_distribution(upload_settings, stub_repository):
"""Add GPG signature provided by user to uploaded package."""
# Upload a pre-signed distribution
result = upload.upload(
upload_settings, [helpers.WHEEL_FIXTURE, helpers.WHEEL_FIXTURE + ".asc"]
)
assert result is None
# The signature shoud be added via package.add_gpg_signature()
package = stub_repository.upload.calls[0].args[0]
assert package.gpg_signature == (
"twine-1.5.0-py2.py3-none-any.whl.asc",
b"signature",
)
def test_success_when_gpg_is_run(upload_settings, stub_repository, monkeypatch):
"""Add GPG signature generated by gpg command to uploaded package."""
# Indicate that upload() should run_gpg() to generate the signature, which
# we'll stub out to use WHEEL_FIXTURE + ".asc"
upload_settings.sign = True
upload_settings.sign_with = "gpg"
monkeypatch.setattr(
package_file.PackageFile,
"run_gpg",
pretend.call_recorder(lambda cls, gpg_args: None),
)
# Upload an unsigned distribution
result = upload.upload(upload_settings, [helpers.WHEEL_FIXTURE])
assert result is None
# The signature shoud be added via package.sign()
package = stub_repository.upload.calls[0].args[0]
assert len(package.run_gpg.calls) == 1
assert helpers.WHEEL_FIXTURE in package.run_gpg.calls[0].args[1]
assert package.gpg_signature == (
"twine-1.5.0-py2.py3-none-any.whl.asc",
b"signature",
)
@pytest.mark.parametrize("verbose", [False, True])
def test_exception_for_http_status(verbose, upload_settings, stub_response, caplog):
upload_settings.verbose = verbose
log_level = logging.INFO if verbose else logging.WARNING
caplog.set_level(log_level, logger="twine")
stub_response.is_redirect = False
stub_response.status_code = 403
stub_response.text = "Invalid or non-existent authentication information"
stub_response.raise_for_status = pretend.raiser(requests.HTTPError)
with pytest.raises(requests.HTTPError):
upload.upload(upload_settings, [helpers.WHEEL_FIXTURE])
captured = caplog.text
assert RELEASE_URL not in captured
if verbose:
assert stub_response.text in captured
assert "--verbose" not in captured
else:
assert stub_response.text not in captured
assert "--verbose" in captured
def test_get_config_old_format(make_settings, pypirc):
try:
make_settings(
"""
[server-login]
username:foo
password:bar
"""
)
except KeyError as err:
assert all(
text in err.args[0]
for text in [
"'pypi'",
"--repository-url",
pypirc,
"https://docs.python.org/",
]
)
def test_deprecated_repo(make_settings):
with pytest.raises(exceptions.UploadToDeprecatedPyPIDetected) as err:
upload_settings = make_settings(
"""
[pypi]
repository: https://pypi.python.org/pypi/
username:foo
password:bar
"""
)
upload.upload(upload_settings, [helpers.WHEEL_FIXTURE])
assert all(
text in err.value.args[0]
for text in [
"https://pypi.python.org/pypi/",
"https://upload.pypi.org/legacy/",
"https://test.pypi.org/legacy/",
"https://packaging.python.org/",
]
)
def test_exception_for_redirect(make_settings):
# Not using fixtures because this setup is significantly different
upload_settings = make_settings(
"""
[pypi]
repository: https://test.pypi.org/legacy
username:foo
password:bar
"""
)
stub_response = pretend.stub(
is_redirect=True,
status_code=301,
headers={"location": "https://test.pypi.org/legacy/"},
)
stub_repository = pretend.stub(
upload=lambda package: stub_response, close=lambda: None
)
upload_settings.create_repository = lambda: stub_repository
with pytest.raises(exceptions.RedirectDetected) as err:
upload.upload(upload_settings, [helpers.WHEEL_FIXTURE])
assert "https://test.pypi.org/legacy/" in err.value.args[0]
def test_prints_skip_message_for_uploaded_package(
upload_settings, stub_repository, capsys
):
upload_settings.skip_existing = True
# Short-circuit the upload
stub_repository.package_is_uploaded = lambda package: True
result = upload.upload(upload_settings, [helpers.WHEEL_FIXTURE])
assert result is None
captured = capsys.readouterr()
assert "Skipping twine-1.5.0-py2.py3-none-any.whl" in captured.out
assert RELEASE_URL not in captured.out
def test_prints_skip_message_for_response(
upload_settings, stub_response, stub_repository, capsys
):
upload_settings.skip_existing = True
stub_response.status_code = 409
# Do the upload, triggering the error response
stub_repository.package_is_uploaded = lambda package: False
result = upload.upload(upload_settings, [helpers.WHEEL_FIXTURE])
assert result is None
captured = capsys.readouterr()
assert "Skipping twine-1.5.0-py2.py3-none-any.whl" in captured.out
assert RELEASE_URL not in captured.out
@pytest.mark.parametrize(
"response_kwargs",
[
pytest.param(
dict(
status_code=400,
reason=(
'A file named "twine-1.5.0-py2.py3-none-any.whl" already '
"exists for twine-1.5.0."
),
),
id="pypi",
),
pytest.param(
dict(
status_code=400,
reason=(
"Repository does not allow updating assets: pypi for url: "
"http://www.foo.bar"
),
),
id="nexus",
),
pytest.param(
dict(
status_code=409,
reason=(
'A file named "twine-1.5.0-py2.py3-none-any.whl" already '
"exists for twine-1.5.0."
),
),
id="pypiserver",
),
pytest.param(
dict(
status_code=403,
text=(
"Not enough permissions to overwrite artifact "
"'pypi-local:twine/1.5.0/twine-1.5.0-py2.py3-none-any.whl'"
"(user 'twine-deployer' needs DELETE permission)."
),
),
id="artifactory_old",
),
pytest.param(
dict(
status_code=403,
text=(
"Not enough permissions to delete/overwrite artifact "
"'pypi-local:twine/1.5.0/twine-1.5.0-py2.py3-none-any.whl'"
"(user 'twine-deployer' needs DELETE permission)."
),
),
id="artifactory_new",
),
],
)
def test_skip_existing_skips_files_on_repository(response_kwargs):
assert upload.skip_upload(
response=pretend.stub(**response_kwargs),
skip_existing=True,
package=package_file.PackageFile.from_filename(helpers.WHEEL_FIXTURE, None),
)
@pytest.mark.parametrize(
"response_kwargs",
[
pytest.param(
dict(status_code=400, reason="Invalid credentials"), id="wrong_reason"
),
pytest.param(dict(status_code=404), id="wrong_code"),
],
)
def test_skip_upload_doesnt_match(response_kwargs):
assert not upload.skip_upload(
response=pretend.stub(**response_kwargs),
skip_existing=True,
package=package_file.PackageFile.from_filename(helpers.WHEEL_FIXTURE, None),
)
def test_skip_upload_respects_skip_existing():
assert not upload.skip_upload(
response=pretend.stub(),
skip_existing=False,
package=package_file.PackageFile.from_filename(helpers.WHEEL_FIXTURE, None),
)
def test_values_from_env(monkeypatch):
def none_upload(*args, **settings_kwargs):
pass
replaced_upload = pretend.call_recorder(none_upload)
monkeypatch.setattr(upload, "upload", replaced_upload)
testenv = {
"TWINE_USERNAME": "pypiuser",
"TWINE_PASSWORD": "pypipassword",
"TWINE_CERT": "/foo/bar.crt",
}
with helpers.set_env(**testenv):
cli.dispatch(["upload", "path/to/file"])
upload_settings = replaced_upload.calls[0].args[0]
assert "pypipassword" == upload_settings.password
assert "pypiuser" == upload_settings.username
assert "/foo/bar.crt" == upload_settings.cacert
@pytest.mark.parametrize(
"repo_url",
["https://upload.pypi.org/", "https://test.pypi.org/", "https://pypi.org/"],
)
def test_check_status_code_for_wrong_repo_url(repo_url, make_settings):
upload_settings = make_settings()
# override defaults to use incorrect URL
upload_settings.repository_config["repository"] = repo_url
with pytest.raises(exceptions.InvalidPyPIUploadURL):
upload.upload(
upload_settings,
[
helpers.WHEEL_FIXTURE,
helpers.SDIST_FIXTURE,
helpers.NEW_SDIST_FIXTURE,
helpers.NEW_WHEEL_FIXTURE,
],
)