Skip to content

Commit 96025c5

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 (cherry picked from commit 79fe204)
1 parent 6018c7f commit 96025c5

File tree

10 files changed

+165
-163
lines changed

10 files changed

+165
-163
lines changed

CHANGES/3957.misc

Lines changed: 1 addition & 0 deletions
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

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import asyncio
22
import hashlib
33
import io
4-
import os.path
4+
import pathlib
55
import urllib.parse
66
import zlib
77
from http.cookies import BaseCookie, Morsel, SimpleCookie
@@ -921,12 +921,11 @@ async def test_chunked_transfer_encoding(loop, conn) -> None:
921921

922922

923923
async def test_file_upload_not_chunked(loop) -> None:
924-
here = os.path.dirname(__file__)
925-
fname = os.path.join(here, "aiohttp.png")
926-
with open(fname, "rb") as f:
924+
file_path = pathlib.Path(__file__).parent / "aiohttp.png"
925+
with file_path.open("rb") as f:
927926
req = ClientRequest("post", URL("http://python.org/"), data=f, loop=loop)
928927
assert not req.chunked
929-
assert req.headers["CONTENT-LENGTH"] == str(os.path.getsize(fname))
928+
assert req.headers["CONTENT-LENGTH"] == str(file_path.stat().st_size)
930929
await req.close()
931930

932931

@@ -947,19 +946,17 @@ async def test_precompressed_data_stays_intact(loop) -> None:
947946

948947

949948
async def test_file_upload_not_chunked_seek(loop) -> None:
950-
here = os.path.dirname(__file__)
951-
fname = os.path.join(here, "aiohttp.png")
952-
with open(fname, "rb") as f:
949+
file_path = pathlib.Path(__file__).parent / "aiohttp.png"
950+
with file_path.open("rb") as f:
953951
f.seek(100)
954952
req = ClientRequest("post", URL("http://python.org/"), data=f, loop=loop)
955-
assert req.headers["CONTENT-LENGTH"] == str(os.path.getsize(fname) - 100)
953+
assert req.headers["CONTENT-LENGTH"] == str(file_path.stat().st_size - 100)
956954
await req.close()
957955

958956

959957
async def test_file_upload_force_chunked(loop) -> None:
960-
here = os.path.dirname(__file__)
961-
fname = os.path.join(here, "aiohttp.png")
962-
with open(fname, "rb") as f:
958+
file_path = pathlib.Path(__file__).parent / "aiohttp.png"
959+
with file_path.open("rb") as f:
963960
req = ClientRequest(
964961
"post", URL("http://python.org/"), data=f, chunked=True, loop=loop
965962
)

tests/test_cookiejar.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
11
import asyncio
22
import datetime
33
import itertools
4-
import os
4+
import pathlib
55
import pickle
6-
import tempfile
76
import unittest
87
from http.cookies import BaseCookie, Morsel, SimpleCookie
98
from unittest import mock
@@ -178,8 +177,10 @@ async def test_constructor_with_expired(
178177
assert jar._loop is loop
179178

180179

181-
async def test_save_load(loop, cookies_to_send, cookies_to_receive) -> None:
182-
file_path = tempfile.mkdtemp() + "/aiohttp.test.cookie"
180+
async def test_save_load(
181+
tmp_path, loop, cookies_to_send, cookies_to_receive
182+
) -> None:
183+
file_path = pathlib.Path(str(tmp_path)) / "aiohttp.test.cookie"
183184

184185
# export cookie jar
185186
jar_save = CookieJar(loop=loop)
@@ -193,7 +194,6 @@ async def test_save_load(loop, cookies_to_send, cookies_to_receive) -> None:
193194
for cookie in jar_load:
194195
jar_test[cookie.key] = cookie
195196

196-
os.unlink(file_path)
197197
assert jar_test == cookies_to_receive
198198

199199

tests/test_helpers.py

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
import gc
55
import platform
66
import sys
7-
import tempfile
87
import weakref
98
from math import ceil, modf
109
from pathlib import Path
@@ -73,9 +72,19 @@ def test_parse_mimetype(mimetype, expected) -> None:
7372
# ------------------- guess_filename ----------------------------------
7473

7574

76-
def test_guess_filename_with_tempfile() -> None:
77-
with tempfile.TemporaryFile() as fp:
78-
assert helpers.guess_filename(fp, "no-throw") is not None
75+
def test_guess_filename_with_file_object(tmp_path) -> None:
76+
file_path = tmp_path / "test_guess_filename"
77+
with file_path.open("w+b") as fp:
78+
assert (helpers.guess_filename(fp, "no-throw") is not None)
79+
80+
81+
def test_guess_filename_with_path(tmp_path) -> None:
82+
file_path = tmp_path / "test_guess_filename"
83+
assert (helpers.guess_filename(file_path, "no-throw") is not None)
84+
85+
86+
def test_guess_filename_with_default() -> None:
87+
assert (helpers.guess_filename(None, "no-throw") == "no-throw")
7988

8089

8190
# ------------------- BasicAuth -----------------------------------

tests/test_multipart.py

Lines changed: 4 additions & 3 deletions
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

@@ -1270,7 +1271,7 @@ async def test_write_preserves_content_disposition(self, buf, stream) -> None:
12701271

12711272
async def test_preserve_content_disposition_header(self, buf, stream):
12721273
# https://github.com/aio-libs/aiohttp/pull/3475#issuecomment-451072381
1273-
with open(__file__, "rb") as fobj:
1274+
with pathlib.Path(__file__).open("rb") as fobj:
12741275
with aiohttp.MultipartWriter("form-data", boundary=":") as writer:
12751276
part = writer.append(
12761277
fobj,
@@ -1297,7 +1298,7 @@ async def test_preserve_content_disposition_header(self, buf, stream):
12971298

12981299
async def test_set_content_disposition_override(self, buf, stream):
12991300
# https://github.com/aio-libs/aiohttp/pull/3475#issuecomment-451072381
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,
@@ -1324,7 +1325,7 @@ async def test_set_content_disposition_override(self, buf, stream):
13241325

13251326
async def test_reset_content_disposition_header(self, buf, stream):
13261327
# https://github.com/aio-libs/aiohttp/pull/3475#issuecomment-451072381
1327-
with open(__file__, "rb") as fobj:
1328+
with pathlib.Path(__file__).open("rb") as fobj:
13281329
with aiohttp.MultipartWriter("form-data", boundary=":") as writer:
13291330
part = writer.append(
13301331
fobj,

tests/test_proxy_functional.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -731,7 +731,7 @@ async def test_proxy_from_env_http_with_auth_from_netrc(
731731
auth.login,
732732
auth.password,
733733
)
734-
with open(str(netrc_file), "w") as f:
734+
with netrc_file.open("w") as f:
735735
f.write(netrc_file_data)
736736
mocker.patch.dict(
737737
os.environ, {"http_proxy": str(proxy.url), "NETRC": str(netrc_file)}
@@ -757,7 +757,7 @@ async def test_proxy_from_env_http_without_auth_from_netrc(
757757
auth.login,
758758
auth.password,
759759
)
760-
with open(str(netrc_file), "w") as f:
760+
with netrc_file.open("w") as f:
761761
f.write(netrc_file_data)
762762
mocker.patch.dict(
763763
os.environ, {"http_proxy": str(proxy.url), "NETRC": str(netrc_file)}
@@ -780,7 +780,7 @@ async def test_proxy_from_env_http_without_auth_from_wrong_netrc(
780780
auth = aiohttp.BasicAuth("user", "pass")
781781
netrc_file = tmp_path / "test_netrc"
782782
invalid_data = f"machine 127.0.0.1 {auth.login} pass {auth.password}"
783-
with open(str(netrc_file), "w") as f:
783+
with netrc_file.open("w") as f:
784784
f.write(invalid_data)
785785

786786
mocker.patch.dict(

0 commit comments

Comments
 (0)