forked from pypa/twine
/
test_utils.py
313 lines (254 loc) · 8.92 KB
/
test_utils.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
# Copyright 2013 Donald Stufft
#
# 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.path
import textwrap
import pretend
import pytest
import requests
from twine import exceptions
from twine import utils
from . import helpers
def test_get_config(tmpdir):
pypirc = os.path.join(str(tmpdir), ".pypirc")
with open(pypirc, "w") as fp:
fp.write(
textwrap.dedent(
"""
[distutils]
index-servers = pypi
[pypi]
username = testuser
password = testpassword
"""
)
)
assert utils.get_config(pypirc) == {
"pypi": {
"repository": utils.DEFAULT_REPOSITORY,
"username": "testuser",
"password": "testpassword",
},
}
def test_get_config_no_distutils(tmpdir):
"""Upload by default to PyPI if an index server is not set in .pypirc."""
pypirc = os.path.join(str(tmpdir), ".pypirc")
with open(pypirc, "w") as fp:
fp.write(
textwrap.dedent(
"""
[pypi]
username = testuser
password = testpassword
"""
)
)
assert utils.get_config(pypirc) == {
"pypi": {
"repository": utils.DEFAULT_REPOSITORY,
"username": "testuser",
"password": "testpassword",
},
"testpypi": {
"repository": utils.TEST_REPOSITORY,
"username": None,
"password": None,
},
}
def test_get_config_no_section(tmpdir):
pypirc = os.path.join(str(tmpdir), ".pypirc")
with open(pypirc, "w") as fp:
fp.write(
textwrap.dedent(
"""
[distutils]
index-servers = pypi foo
[pypi]
username = testuser
password = testpassword
"""
)
)
assert utils.get_config(pypirc) == {
"pypi": {
"repository": utils.DEFAULT_REPOSITORY,
"username": "testuser",
"password": "testpassword",
},
}
def test_get_config_override_pypi_url(tmpdir):
pypirc = os.path.join(str(tmpdir), ".pypirc")
with open(pypirc, "w") as fp:
fp.write(
textwrap.dedent(
"""
[pypi]
repository = http://pypiproxy
"""
)
)
assert utils.get_config(pypirc)["pypi"]["repository"] == "http://pypiproxy"
def test_get_config_missing(tmpdir):
pypirc = os.path.join(str(tmpdir), ".pypirc")
assert utils.get_config(pypirc) == {
"pypi": {
"repository": utils.DEFAULT_REPOSITORY,
"username": None,
"password": None,
},
"testpypi": {
"repository": utils.TEST_REPOSITORY,
"username": None,
"password": None,
},
}
def test_empty_userpass(tmpdir):
"""Suppress prompts if empty username and password are provided in .pypirc."""
pypirc = os.path.join(str(tmpdir), ".pypirc")
with open(pypirc, "w") as fp:
fp.write(
textwrap.dedent(
"""
[pypi]
username=
password=
"""
)
)
config = utils.get_config(pypirc)
pypi = config["pypi"]
assert pypi["username"] == pypi["password"] == ""
def test_get_repository_config_missing(tmpdir):
pypirc = os.path.join(str(tmpdir), ".pypirc")
repository_url = "https://notexisting.python.org/pypi"
exp = {
"repository": repository_url,
"username": None,
"password": None,
}
assert utils.get_repository_from_config(pypirc, "foo", repository_url) == exp
assert utils.get_repository_from_config(pypirc, "pypi", repository_url) == exp
exp = {
"repository": utils.DEFAULT_REPOSITORY,
"username": None,
"password": None,
}
assert utils.get_repository_from_config(pypirc, "pypi") == exp
@pytest.mark.parametrize(
"repo_url, message",
[
(
"ftp://test.pypi.org",
r"scheme was required to be one of \['http', 'https'\]",
),
("https:/", "host was required but missing."),
("//test.pypi.org", "scheme was required but missing."),
("foo.bar", "host, scheme were required but missing."),
],
)
def test_get_repository_config_with_invalid_url(tmpdir, repo_url, message):
"""Raise an exception for a URL with an invalid/missing scheme and/or host."""
pypirc = os.path.join(str(tmpdir), ".pypirc")
with pytest.raises(
exceptions.UnreachableRepositoryURLDetected, match=message,
):
utils.get_repository_from_config(pypirc, "pypi", repo_url)
def test_get_repository_config_missing_config(tmpdir):
"""Raise an exception when a repository isn't defined in .pypirc."""
pypirc = os.path.join(str(tmpdir), ".pypirc")
with pytest.raises(exceptions.InvalidConfiguration):
utils.get_repository_from_config(pypirc, "foobar")
def test_get_config_deprecated_pypirc():
tests_dir = os.path.dirname(os.path.abspath(__file__))
deprecated_pypirc_path = os.path.join(tests_dir, "fixtures", "deprecated-pypirc")
assert utils.get_config(deprecated_pypirc_path) == {
"pypi": {
"repository": utils.DEFAULT_REPOSITORY,
"username": "testusername",
"password": "testpassword",
},
"testpypi": {
"repository": utils.TEST_REPOSITORY,
"username": "testusername",
"password": "testpassword",
},
}
@pytest.mark.parametrize(
("cli_value", "config", "key", "strategy", "expected"),
(
("cli", {}, "key", lambda: "fallback", "cli"),
(None, {"key": "value"}, "key", lambda: "fallback", "value"),
(None, {}, "key", lambda: "fallback", "fallback"),
),
)
def test_get_userpass_value(cli_value, config, key, strategy, expected):
ret = utils.get_userpass_value(cli_value, config, key, strategy)
assert ret == expected
@pytest.mark.parametrize(
("env_name", "default", "environ", "expected"),
[
("MY_PASSWORD", None, {}, None),
("MY_PASSWORD", None, {"MY_PASSWORD": "foo"}, "foo"),
("URL", "https://example.org", {}, "https://example.org"),
("URL", "https://example.org", {"URL": "https://pypi.org"}, "https://pypi.org"),
],
)
def test_default_to_environment_action(env_name, default, environ, expected):
option_strings = ("-x", "--example")
dest = "example"
with helpers.set_env(**environ):
action = utils.EnvironmentDefault(
env=env_name, default=default, option_strings=option_strings, dest=dest,
)
assert action.env == env_name
assert action.default == expected
@pytest.mark.parametrize(
"repo_url", ["https://pypi.python.org", "https://testpypi.python.org"]
)
def test_check_status_code_for_deprecated_pypi_url(repo_url):
response = pretend.stub(status_code=410, url=repo_url)
# value of Verbose doesn't matter for this check
with pytest.raises(exceptions.UploadToDeprecatedPyPIDetected):
utils.check_status_code(response, False)
@pytest.mark.parametrize(
"repo_url", ["https://pypi.python.org", "https://testpypi.python.org"],
)
def test_check_status_code_for_missing_status_code(caplog, repo_url):
"""Print HTTP errors based on verbosity level."""
response = pretend.stub(
status_code=403,
url=repo_url,
raise_for_status=pretend.raiser(requests.HTTPError),
text="Forbidden",
)
caplog.set_level(logging.INFO, logger="twine")
with pytest.raises(requests.HTTPError):
utils.check_status_code(response, True)
# Different messages are printed based on the verbose level
captured = caplog.text
assert "Content received from server:\nForbidden\n" in captured
caplog.set_level(logging.WARNING, logger="twine")
with pytest.raises(requests.HTTPError):
utils.check_status_code(response, False)
captured = caplog.text
assert "NOTE: Try --verbose to see response content.\n" in captured
@pytest.mark.parametrize(
("size_in_bytes, formatted_size"),
[(3704, "3.6 KB"), (1153433, "1.1 MB"), (21412841, "20.4 MB")],
)
def test_get_file_size(size_in_bytes, formatted_size, monkeypatch):
"""Get the size of file as a string with units."""
monkeypatch.setattr(os.path, "getsize", lambda _: size_in_bytes)
file_size = utils.get_file_size(size_in_bytes)
assert file_size == formatted_size