Skip to content

Commit

Permalink
pytest-dev#7467 create subdirectories if they do not exist for --log-…
Browse files Browse the repository at this point in the history
…file and log_file
  • Loading branch information
symonk committed Jul 8, 2020
1 parent 678c1a0 commit b61d523
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
6 changes: 6 additions & 0 deletions src/_pytest/logging.py
Expand Up @@ -531,11 +531,17 @@ def __init__(self, config: Config) -> None:
# File logging.
self.log_file_level = get_log_level_for_setting(config, "log_file_level")
log_file = get_option_ini(config, "log_file") or os.devnull
if log_file != os.devnull:
directory = os.path.dirname(os.path.abspath(log_file))
if not os.path.isdir(directory):
os.makedirs(directory)

self.log_file_handler = _FileHandler(log_file, mode="w", encoding="UTF-8")
log_file_format = get_option_ini(config, "log_file_format", "log_format")
log_file_date_format = get_option_ini(
config, "log_file_date_format", "log_date_format"
)

log_file_formatter = logging.Formatter(
log_file_format, datefmt=log_file_date_format
)
Expand Down
44 changes: 44 additions & 0 deletions testing/logging/test_reporting.py
Expand Up @@ -5,6 +5,7 @@

import pytest
from _pytest.capture import CaptureManager
from _pytest.config import ExitCode
from _pytest.pytester import Testdir
from _pytest.terminal import TerminalReporter

Expand Down Expand Up @@ -1152,3 +1153,46 @@ def test_bad_log(monkeypatch):
)
result = testdir.runpytest()
result.assert_outcomes(passed=1)


def test_log_file_cli_subdirectories_are_successfully_created(testdir):
path = testdir.makepyfile(""" def test_logger(): pass """)
expected = os.path.join(os.path.dirname(path), "foo", "bar")
result = testdir.runpytest("--log-file=foo/bar/logf.log")
assert "logf.log" in os.listdir(expected)
assert result.ret == ExitCode.OK


def test_log_file_cli_no_subdirectories_works_ok(testdir):
path = testdir.makepyfile(""" def test_logger(): pass """)
expected = os.path.join(os.path.dirname(path))
result = testdir.runpytest("--log-file=logf.log")
assert "logf.log" in os.listdir(expected)
assert result.ret == ExitCode.OK


def test_log_file_marker_subdirectories_are_successfully_created(testdir):
path = testdir.makeini(
"""
[pytest]
log_file = sub/logf.log
""",
)
expected = os.path.join(os.path.dirname(path), "sub")
result = testdir.runpytest()
assert "logf.log" in os.listdir(expected)
assert result.ret == ExitCode.OK


def test_log_file_marker_no_subdirectories_works_ok(testdir):
path = testdir.makeini(
"""
[pytest]
log_file = logf.log
""",
)
testdir.makepyfile(""" def test_logger(): pass """)
expected = os.path.join(os.path.dirname(path))
result = testdir.runpytest()
assert "logf.log" in os.listdir(expected)
assert result.ret == ExitCode.OK

0 comments on commit b61d523

Please sign in to comment.