Skip to content

Commit 79fe204

Browse files
vaneseltinewebknjaz
authored andcommitted
Improve test suite handling of paths, temp files (#3957)
* Improve test suite handling of paths, temp files This updates most uses of `os.path` to instead use `pathlib.Path`. Relatedly, and following up from #3955 (which replaced pytest's `tmpdir` fixture with `tmp_path`), this removes most ad-hoc tempfile creation in favor of the `tmp_path` fixture. Following conversion, unnecessary `os` and `tempfile` imports were removed. Most pathlib changes involve straightforward changes from `os` functions such as `os.mkdir` or `os.path.abspath` to their equivalent methods in `pathlib.Path`. Changing ad-hoc temporary path to `tmp_path` involved removing the `tmp_dir_path` fixture and replacing its functionality with `tmp_path` in `test_save_load` and `test_guess_filename_with_tempfile`. On `test_static_route_user_home` function: * I think that the intention of this test is to ensure that aiohttp correctly expands the home path if passed in a string. I refactored it to `pathlib.Path` and cut out duplication of `relative_to()` calls. But if it's not doing anything but expanding `~`, then it's testing the functionality of `pathlib.Path`, not aiohttp. On `unix_sockname` fixture: This fixture uses `tempfile.TemporaryDirectory`. Because it's a somewhat complicated fixture used across multiple test modules, I left it as-is for now. On `str(tmp_path)` and even `pathlib.Path(str(tmp_path))`: pytest uses `pathlib2` to provide `tmp_path` for Python 3.5 (only). This is mostly fine but it fails on a couple of corner cases, such as `os.symlink()` which blocks all but `str` and `PurePath` via isinstance type checking. In several cases, this requires conversion to string or conversion to string and then into `pathlib.Path` to maintain code compatibility. See: pytest-dev/pytest/issues/5017 * Correct test_guess_filename to use file object * Update symlink in tests; more guess_filename tests
1 parent 81c141d commit 79fe204

11 files changed

+132
-148
lines changed

CHANGES/3957.misc

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Improve test suite handling of paths and temp files to consistently use pathlib and pytest fixtures.

tests/test_client_request.py

+9-12
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import asyncio
44
import hashlib
55
import io
6-
import os.path
6+
import pathlib
77
import urllib.parse
88
import zlib
99
from http.cookies import SimpleCookie
@@ -789,15 +789,14 @@ async def test_chunked_transfer_encoding(loop, conn) -> None:
789789

790790

791791
async def test_file_upload_not_chunked(loop) -> None:
792-
here = os.path.dirname(__file__)
793-
fname = os.path.join(here, 'aiohttp.png')
794-
with open(fname, 'rb') as f:
792+
file_path = pathlib.Path(__file__).parent / 'aiohttp.png'
793+
with file_path.open('rb') as f:
795794
req = ClientRequest(
796795
'post', URL('http://python.org/'),
797796
data=f,
798797
loop=loop)
799798
assert not req.chunked
800-
assert req.headers['CONTENT-LENGTH'] == str(os.path.getsize(fname))
799+
assert req.headers['CONTENT-LENGTH'] == str(file_path.stat().st_size)
801800
await req.close()
802801

803802

@@ -816,23 +815,21 @@ async def test_precompressed_data_stays_intact(loop) -> None:
816815

817816

818817
async def test_file_upload_not_chunked_seek(loop) -> None:
819-
here = os.path.dirname(__file__)
820-
fname = os.path.join(here, 'aiohttp.png')
821-
with open(fname, 'rb') as f:
818+
file_path = pathlib.Path(__file__).parent / 'aiohttp.png'
819+
with file_path.open('rb') as f:
822820
f.seek(100)
823821
req = ClientRequest(
824822
'post', URL('http://python.org/'),
825823
data=f,
826824
loop=loop)
827825
assert req.headers['CONTENT-LENGTH'] == \
828-
str(os.path.getsize(fname) - 100)
826+
str(file_path.stat().st_size - 100)
829827
await req.close()
830828

831829

832830
async def test_file_upload_force_chunked(loop) -> None:
833-
here = os.path.dirname(__file__)
834-
fname = os.path.join(here, 'aiohttp.png')
835-
with open(fname, 'rb') as f:
831+
file_path = pathlib.Path(__file__).parent / 'aiohttp.png'
832+
with file_path.open('rb') as f:
836833
req = ClientRequest(
837834
'post', URL('http://python.org/'),
838835
data=f,

tests/test_cookiejar.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
11
import asyncio
22
import datetime
33
import itertools
4-
import os
5-
import tempfile
4+
import pathlib
65
import unittest
76
from http.cookies import SimpleCookie
87
from unittest import mock
@@ -144,8 +143,10 @@ async def test_constructor(loop, cookies_to_send, cookies_to_receive) -> None:
144143
assert jar._loop is loop
145144

146145

147-
async def test_save_load(loop, cookies_to_send, cookies_to_receive) -> None:
148-
file_path = tempfile.mkdtemp() + '/aiohttp.test.cookie'
146+
async def test_save_load(
147+
tmp_path, loop, cookies_to_send, cookies_to_receive
148+
) -> None:
149+
file_path = pathlib.Path(str(tmp_path)) / 'aiohttp.test.cookie'
149150

150151
# export cookie jar
151152
jar_save = CookieJar()
@@ -159,7 +160,6 @@ async def test_save_load(loop, cookies_to_send, cookies_to_receive) -> None:
159160
for cookie in jar_load:
160161
jar_test[cookie.key] = cookie
161162

162-
os.unlink(file_path)
163163
assert jar_test == cookies_to_receive
164164

165165

tests/test_helpers.py

+12-3
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
import gc
44
import os
55
import platform
6-
import tempfile
76
from unittest import mock
87

98
import pytest
@@ -46,11 +45,21 @@ def test_parse_mimetype(mimetype, expected) -> None:
4645

4746
# ------------------- guess_filename ----------------------------------
4847

49-
def test_guess_filename_with_tempfile() -> None:
50-
with tempfile.TemporaryFile() as fp:
48+
def test_guess_filename_with_file_object(tmp_path) -> None:
49+
file_path = tmp_path / 'test_guess_filename'
50+
with file_path.open('w+b') as fp:
5151
assert (helpers.guess_filename(fp, 'no-throw') is not None)
5252

5353

54+
def test_guess_filename_with_path(tmp_path) -> None:
55+
file_path = tmp_path / 'test_guess_filename'
56+
assert (helpers.guess_filename(file_path, 'no-throw') is not None)
57+
58+
59+
def test_guess_filename_with_default() -> None:
60+
assert (helpers.guess_filename(None, 'no-throw') == 'no-throw')
61+
62+
5463
# ------------------- BasicAuth -----------------------------------
5564

5665
def test_basic_auth1() -> None:

tests/test_multipart.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import asyncio
22
import io
33
import json
4+
import pathlib
45
import zlib
56
from unittest import mock
67

@@ -1266,7 +1267,7 @@ async def test_preserve_content_disposition_header(self, buf, stream):
12661267
"""
12671268
https://github.com/aio-libs/aiohttp/pull/3475#issuecomment-451072381
12681269
"""
1269-
with open(__file__, 'rb') as fobj:
1270+
with pathlib.Path(__file__).open('rb') as fobj:
12701271
with aiohttp.MultipartWriter('form-data', boundary=':') as writer:
12711272
part = writer.append(
12721273
fobj,
@@ -1297,7 +1298,7 @@ async def test_set_content_disposition_override(self, buf, stream):
12971298
"""
12981299
https://github.com/aio-libs/aiohttp/pull/3475#issuecomment-451072381
12991300
"""
1300-
with open(__file__, 'rb') as fobj:
1301+
with pathlib.Path(__file__).open('rb') as fobj:
13011302
with aiohttp.MultipartWriter('form-data', boundary=':') as writer:
13021303
part = writer.append(
13031304
fobj,
@@ -1328,7 +1329,7 @@ async def test_reset_content_disposition_header(self, buf, stream):
13281329
"""
13291330
https://github.com/aio-libs/aiohttp/pull/3475#issuecomment-451072381
13301331
"""
1331-
with open(__file__, 'rb') as fobj:
1332+
with pathlib.Path(__file__).open('rb') as fobj:
13321333
with aiohttp.MultipartWriter('form-data', boundary=':') as writer:
13331334
part = writer.append(
13341335
fobj,

tests/test_proxy_functional.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -537,7 +537,7 @@ async def test_proxy_from_env_http_with_auth_from_netrc(
537537
netrc_file = tmp_path / 'test_netrc'
538538
netrc_file_data = 'machine 127.0.0.1 login %s password %s' % (
539539
auth.login, auth.password)
540-
with open(str(netrc_file), 'w') as f:
540+
with netrc_file.open('w') as f:
541541
f.write(netrc_file_data)
542542
mocker.patch.dict(os.environ, {'http_proxy': str(proxy.url),
543543
'NETRC': str(netrc_file)})
@@ -559,7 +559,7 @@ async def test_proxy_from_env_http_without_auth_from_netrc(
559559
netrc_file = tmp_path / 'test_netrc'
560560
netrc_file_data = 'machine 127.0.0.2 login %s password %s' % (
561561
auth.login, auth.password)
562-
with open(str(netrc_file), 'w') as f:
562+
with netrc_file.open('w') as f:
563563
f.write(netrc_file_data)
564564
mocker.patch.dict(os.environ, {'http_proxy': str(proxy.url),
565565
'NETRC': str(netrc_file)})
@@ -581,7 +581,7 @@ async def test_proxy_from_env_http_without_auth_from_wrong_netrc(
581581
netrc_file = tmp_path / 'test_netrc'
582582
invalid_data = 'machine 127.0.0.1 %s pass %s' % (
583583
auth.login, auth.password)
584-
with open(str(netrc_file), 'w') as f:
584+
with netrc_file.open('w') as f:
585585
f.write(invalid_data)
586586

587587
mocker.patch.dict(os.environ, {'http_proxy': str(proxy.url),

0 commit comments

Comments
 (0)