Create subdirectories if they do not exist when specified for log file (#7468)

Co-authored-by: Bruno Oliveira <nicoddemus@gmail.com>
This commit is contained in:
Simon K 2020-07-11 17:40:28 +01:00 committed by GitHub
parent 7b65b2337b
commit 7f467ebc9a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 16 additions and 0 deletions

View File

@ -0,0 +1 @@
``--log-file`` CLI option and ``log_file`` ini marker now create subdirectories if needed.

View File

@ -531,11 +531,17 @@ class LoggingPlugin:
# 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
)

View File

@ -5,6 +5,7 @@ from typing import cast
import pytest
from _pytest.capture import CaptureManager
from _pytest.config import ExitCode
from _pytest.pytester import Testdir
from _pytest.terminal import TerminalReporter
@ -1152,3 +1153,11 @@ def test_logging_emit_error_supressed(testdir: Testdir) -> None:
)
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(str(path)), "foo", "bar")
result = testdir.runpytest("--log-file=foo/bar/logf.log")
assert "logf.log" in os.listdir(expected)
assert result.ret == ExitCode.OK