Skip to content

Commit

Permalink
Add cd_clean_tmp_dir() test utility context manager
Browse files Browse the repository at this point in the history
  • Loading branch information
jkbrzt committed Jun 3, 2024
1 parent 78aa25d commit d238725
Show file tree
Hide file tree
Showing 4 changed files with 52 additions and 52 deletions.
66 changes: 29 additions & 37 deletions tests/test_downloads.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
parse_content_range, filename_from_content_disposition, filename_from_url,
get_unique_filename, ContentRangeError, Downloader, PARTIAL_CONTENT
)
from .utils import http, MockEnvironment
from .utils import http, MockEnvironment, cd_clean_tmp_dir


class Response(niquests.Response):
Expand Down Expand Up @@ -160,32 +160,26 @@ def test_download_no_Content_Length(self, mock_env, httpbin_both):
assert not downloader.interrupted

def test_download_output_from_content_disposition(self, mock_env, httpbin_both):
with tempfile.TemporaryDirectory() as tmp_dirname:
orig_cwd = os.getcwd()
os.chdir(tmp_dirname)
try:
assert not os.path.isfile('filename.bin')
downloader = Downloader(mock_env)
downloader.start(
final_response=Response(
url=httpbin_both.url + '/',
headers={
'Content-Length': 5,
'Content-Disposition': 'attachment; filename="filename.bin"',
}
),
initial_url='/'
)
downloader.chunk_downloaded(b'12345')
downloader.finish()
downloader.failed() # Stop the reporter
assert not downloader.interrupted
output_file_name = 'filename.bin'
with cd_clean_tmp_dir(assert_filenames_after=[output_file_name]):
downloader = Downloader(mock_env)
downloader.start(
final_response=Response(
url=httpbin_both.url + '/',
headers={
'Content-Length': 5,
'Content-Disposition': f'attachment; filename="{output_file_name}"',
}
),
initial_url='/'
)
downloader.chunk_downloaded(b'12345')
downloader.finish()
downloader.failed() # Stop the reporter
assert not downloader.interrupted

# TODO: Auto-close the file in that case?
downloader._output_file.close()
assert os.path.isfile('filename.bin')
finally:
os.chdir(orig_cwd)
# TODO: Auto-close the file in that case?
downloader._output_file.close()

def test_download_interrupted(self, mock_env, httpbin_both):
with open(os.devnull, 'w') as devnull:
Expand Down Expand Up @@ -239,7 +233,10 @@ def test_download_resumed(self, mock_env, httpbin_both):
downloader.start(
final_response=Response(
url=httpbin_both.url + '/',
headers={'Content-Length': 5, 'Content-Range': 'bytes 3-4/5'},
headers={
'Content-Length': 5,
'Content-Range': 'bytes 3-4/5',
},
status_code=PARTIAL_CONTENT
),
initial_url='/'
Expand All @@ -250,16 +247,11 @@ def test_download_resumed(self, mock_env, httpbin_both):
def test_download_with_redirect_original_url_used_for_filename(self, httpbin):
# Redirect from `/redirect/1` to `/get`.
expected_filename = '1.json'
orig_cwd = os.getcwd()
with tempfile.TemporaryDirectory() as tmp_dirname:
os.chdir(tmp_dirname)
try:
assert os.listdir('.') == []
http('--download', httpbin + '/redirect/1')
assert os.listdir('.') == [expected_filename]
finally:
os.chdir(orig_cwd)
with cd_clean_tmp_dir(assert_filenames_after=[expected_filename]):
http('--download', httpbin + '/redirect/1')

def test_download_gzip_content_encoding(self, httpbin):
r = http('--download', httpbin + '/gzip')
expected_filename = 'gzip.json'
with cd_clean_tmp_dir(assert_filenames_after=[expected_filename]):
r = http('--download', httpbin + '/gzip')
assert r.exit_status == 0
12 changes: 3 additions & 9 deletions tests/test_output.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
from httpie.output.formatters.colors import get_lexer, PIE_STYLE_NAMES, BUNDLED_STYLES
from httpie.status import ExitStatus
from .fixtures import XML_DATA_RAW, XML_DATA_FORMATTED
from .utils import COLOR, CRLF, HTTP_OK, MockEnvironment, http, DUMMY_URL, strip_colors
from .utils import COLOR, CRLF, HTTP_OK, MockEnvironment, http, DUMMY_URL, strip_colors, cd_clean_tmp_dir


# For ensuring test reproducibility, avoid using the unsorted
Expand Down Expand Up @@ -159,24 +159,20 @@ def test_quiet_with_explicit_output_options(self, httpbin, quiet_flags, output_o

@pytest.mark.parametrize('quiet_flags', QUIET_SCENARIOS)
@pytest.mark.parametrize('with_download', [True, False])
def test_quiet_with_output_redirection(self, tmp_path, httpbin, quiet_flags, with_download):
def test_quiet_with_output_redirection(self, httpbin, quiet_flags, with_download):
url = httpbin + '/robots.txt'
output_path = Path('output.txt')
env = MockEnvironment()
orig_cwd = os.getcwd()
output = niquests.get(url).text
extra_args = ['--download'] if with_download else []
os.chdir(tmp_path)
try:
assert os.listdir('.') == []
with cd_clean_tmp_dir(assert_filenames_after=[str(output_path)]):
r = http(
*quiet_flags,
'--output', str(output_path),
*extra_args,
url,
env=env
)
assert os.listdir('.') == [str(output_path)]
assert r == ''
assert r.stderr == ''
assert env.stderr is env.devnull
Expand All @@ -185,8 +181,6 @@ def test_quiet_with_output_redirection(self, tmp_path, httpbin, quiet_flags, wit
else:
assert env.stdout is not env.devnull # --output swaps stdout.
assert output_path.read_text(encoding=UTF8) == output
finally:
os.chdir(orig_cwd)


class TestVerboseFlag:
Expand Down
8 changes: 2 additions & 6 deletions tests/test_sessions.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
from httpie.sessions import Session
from httpie.utils import get_expired_cookies
from .test_auth_plugins import basic_auth
from .utils import DUMMY_HOST, HTTP_OK, MockEnvironment, http, mk_config_dir
from .utils import DUMMY_HOST, HTTP_OK, MockEnvironment, http, mk_config_dir, cd_clean_tmp_dir
from base64 import b64encode


Expand Down Expand Up @@ -253,13 +253,9 @@ def test_session_default_header_value_overwritten(self, httpbin):
def test_download_in_session(self, tmp_path, httpbin):
# https://github.com/httpie/cli/issues/412
self.start_session(httpbin)
cwd = os.getcwd()
os.chdir(tmp_path)
try:
with cd_clean_tmp_dir():
http('--session=test', '--download',
httpbin + '/get', env=self.env())
finally:
os.chdir(cwd)

@pytest.mark.parametrize(
'auth_require_param, auth_parse_param',
Expand Down
18 changes: 18 additions & 0 deletions tests/utils/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
"""Utilities for HTTPie test suite."""
import contextlib
import os
import re
import shlex
import sys
Expand Down Expand Up @@ -407,6 +409,7 @@ def http(
add_to_args.append('--timeout=3')

complete_args = [program_name, *add_to_args, *args]

# print(' '.join(complete_args))

def dump_stderr():
Expand Down Expand Up @@ -468,3 +471,18 @@ def dump_stderr():

finally:
env.cleanup()


@contextlib.contextmanager
def cd_clean_tmp_dir(assert_filenames_after: list = None):
"""Run commands inside a clean temporary directory, optionally checking for created file names."""
orig_cwd = os.getcwd()
with tempfile.TemporaryDirectory() as tmp_dirname:
os.chdir(tmp_dirname)
assert os.listdir('.') == []
try:
yield tmp_dirname
if assert_filenames_after is not None:
assert os.listdir('.') == assert_filenames_after
finally:
os.chdir(orig_cwd)

0 comments on commit d238725

Please sign in to comment.