Question: Pytest trying to check if custom argument is a file crashes due to filename being too long I have a custom flag defined in , and when I try to assign it to a value that is too long pytest crashes before ever getting to my code. This reproduces even if the flag isn't defined, and even if the current working directory is . Failing example: If I reduce the length of the flag, I get the expected behavior for my project, and this different and expected error from my pytest MVP: I did a little digging into my version of pytest (7.0.0) to make sure I wasn't doing something wrong, but it looks like there is a blind call to with a path constructed from the argument in : It seems to me like there should be a try or something here, since in cases like mine the argument may not be a file at all, and that can cause OS level errors. Operating System: Ubuntu 20.04 LTS [x] a detailed description of the bug or problem you are having [x] output of from the virtual environment you are using [x] pytest and operating system versions [x] minimal example if possible Pytest trying to check if custom argument is a file crashes due to filename being too long I have a custom flag defined in , and when I try to assign it to a value that is too long pytest crashes before ever getting to my code. This reproduces even if the flag isn't defined, and even if the current working directory is . Failing example: If I reduce the length of the flag, I get the expected behavior for my project, and this different and expected error from my pytest MVP: I did a little digging into my version of pytest (7.0.0) to make sure I wasn't doing something wrong, but it looks like there is a blind call to with a path constructed from the argument in : It seems to me like there should be a try or something here, since in cases like mine the argument may not be a file at all, and that can cause OS level errors. Operating System: Ubuntu 20.04 LTS [x] a detailed description of the bug or problem you are having [x] output of from the virtual environment you are using [x] pytest and operating system versions [x] minimal example if possible

)         self._noconftest = namespace.noconftest         self._using_pyargs = namespace.pyargs        testpaths = namespace.file_or_dir        testpaths = namespace.file_or_dir + testpaths_ini         foundanchor = False         for testpath in testpaths:             path = str(testpath)


Question: Pytest trying to check if custom argument is a file crashes due to filename being too long I have a custom flag defined in , and when I try to assign it to a value that is too long pytest crashes before ever getting to my code. This reproduces even if the flag isn't defined, and even if the current working directory is . Failing example: If I reduce the length of the flag, I get the expected behavior for my project, and this different and expected error from my pytest MVP: I did a little digging into my version of pytest (7.0.0) to make sure I wasn't doing something wrong, but it looks like there is a blind call to with a path constructed from the argument in : It seems to me like there should be a try or something here, since in cases like mine the argument may not be a file at all, and that can cause OS level errors. Operating System: Ubuntu 20.04 LTS [x] a detailed description of the bug or problem you are having [x] output of from the virtual environment you are using [x] pytest and operating system versions [x] minimal example if possible Pytest trying to check if custom argument is a file crashes due to filename being too long I have a custom flag defined in , and when I try to assign it to a value that is too long pytest crashes before ever getting to my code. This reproduces even if the flag isn't defined, and even if the current working directory is . Failing example: If I reduce the length of the flag, I get the expected behavior for my project, and this different and expected error from my pytest MVP: I did a little digging into my version of pytest (7.0.0) to make sure I wasn't doing something wrong, but it looks like there is a blind call to with a path constructed from the argument in : It seems to me like there should be a try or something here, since in cases like mine the argument may not be a file at all, and that can cause OS level errors. Operating System: Ubuntu 20.04 LTS [x] a detailed description of the bug or problem you are having [x] output of from the virtual environment you are using [x] pytest and operating system versions [x] minimal example if possible

if i != -1:                 path = path[:i]             anchor = absolutepath(current / path)            if anchor.exists():  # we found some file object            # Ensure we do not break if what appears to be an anchor            # is in fact a very long option (#10169).            try:                anchor_exists = anchor.exists()            except OSError:  # pragma: no cover                anchor_exists = False            if anchor_exists:                 self._try_load_conftest(anchor, namespace.importmode, rootpath)                 foundanchor = True         if not foundanchor:


Question: Pytest trying to check if custom argument is a file crashes due to filename being too long I have a custom flag defined in , and when I try to assign it to a value that is too long pytest crashes before ever getting to my code. This reproduces even if the flag isn't defined, and even if the current working directory is . Failing example: If I reduce the length of the flag, I get the expected behavior for my project, and this different and expected error from my pytest MVP: I did a little digging into my version of pytest (7.0.0) to make sure I wasn't doing something wrong, but it looks like there is a blind call to with a path constructed from the argument in : It seems to me like there should be a try or something here, since in cases like mine the argument may not be a file at all, and that can cause OS level errors. Operating System: Ubuntu 20.04 LTS [x] a detailed description of the bug or problem you are having [x] output of from the virtual environment you are using [x] pytest and operating system versions [x] minimal example if possible Pytest trying to check if custom argument is a file crashes due to filename being too long I have a custom flag defined in , and when I try to assign it to a value that is too long pytest crashes before ever getting to my code. This reproduces even if the flag isn't defined, and even if the current working directory is . Failing example: If I reduce the length of the flag, I get the expected behavior for my project, and this different and expected error from my pytest MVP: I did a little digging into my version of pytest (7.0.0) to make sure I wasn't doing something wrong, but it looks like there is a blind call to with a path constructed from the argument in : It seems to me like there should be a try or something here, since in cases like mine the argument may not be a file at all, and that can cause OS level errors. Operating System: Ubuntu 20.04 LTS [x] a detailed description of the bug or problem you are having [x] output of from the virtual environment you are using [x] pytest and operating system versions [x] minimal example if possible

@hookimpl(trylast=True)     def pytest_load_initial_conftests(self, early_config: "Config") -> None:         self.pluginmanager._set_initial_conftests(            early_config.known_args_namespace, rootpath=early_config.rootpath            early_config.known_args_namespace,            rootpath=early_config.rootpath,            testpaths_ini=self.getini("testpaths"),         )      def _initini(self, args: Sequence[str]) -> None:


Question: UnboundLocalError: cannot access local variable 'x' where it is not associated with a value There seems to be a regression in pytest version when a walrus operator is used in an assert line. Code: Fails the test with error: in pytest version , whereas with pytest version it passes successfully. My Python version is . Looks like it has to do with PR .

]                 ):                     pytest_temp = self.variable()                    self.variables_overwrite[v.left.target.id] = pytest_temp                    self.variables_overwrite[                        v.left.target.id                    ] = v.left  # type:ignore[assignment]                     v.left.target.id = pytest_temp             self.push_format_context()             res, expl = self.visit(v)


Question: UnboundLocalError: cannot access local variable 'x' where it is not associated with a value There seems to be a regression in pytest version when a walrus operator is used in an assert line. Code: Fails the test with error: in pytest version , whereas with pytest version it passes successfully. My Python version is . Looks like it has to do with PR .

new_args = []         new_kwargs = []         for arg in call.args:            if isinstance(arg, ast.Name) and arg.id in self.variables_overwrite:                arg = self.variables_overwrite[arg.id]  # type:ignore[assignment]             res, expl = self.visit(arg)             arg_expls.append(expl)             new_args.append(res)         for keyword in call.keywords:            if (                isinstance(keyword.value, ast.Name)                and keyword.value.id in self.variables_overwrite            ):                keyword.value = self.variables_overwrite[                    keyword.value.id                ]  # type:ignore[assignment]             res, expl = self.visit(keyword.value)             new_kwargs.append(ast.keyword(keyword.arg, res))             if keyword.arg:


Question: UnboundLocalError: cannot access local variable 'x' where it is not associated with a value There seems to be a regression in pytest version when a walrus operator is used in an assert line. Code: Fails the test with error: in pytest version , whereas with pytest version it passes successfully. My Python version is . Looks like it has to do with PR .

self.push_format_context()         # We first check if we have overwritten a variable in the previous assert         if isinstance(comp.left, ast.Name) and comp.left.id in self.variables_overwrite:            comp.left.id = self.variables_overwrite[comp.left.id]            comp.left = self.variables_overwrite[                comp.left.id            ]  # type:ignore[assignment]        if isinstance(comp.left, namedExpr):            self.variables_overwrite[                comp.left.target.id            ] = comp.left  # type:ignore[assignment]         left_res, left_expl = self.visit(comp.left)         if isinstance(comp.left, (ast.Compare, ast.BoolOp)):             left_expl = f"({left_expl})"


Question: UnboundLocalError: cannot access local variable 'x' where it is not associated with a value There seems to be a regression in pytest version when a walrus operator is used in an assert line. Code: Fails the test with error: in pytest version , whereas with pytest version it passes successfully. My Python version is . Looks like it has to do with PR .

and next_operand.target.id == left_res.id             ):                 next_operand.target.id = self.variable()                self.variables_overwrite[left_res.id] = next_operand.target.id                self.variables_overwrite[                    left_res.id                ] = next_operand  # type:ignore[assignment]             next_res, next_expl = self.visit(next_operand)             if isinstance(next_operand, (ast.Compare, ast.BoolOp)):                 next_expl = f"({next_expl})"


Question: Issue warning/error if 'testpaths' does not match any files/folders We should issue a warning (or even an error?) if does not match any files or folders. I think an error is reasonable, even if it might break some incorrectly-configured suite out there. Originally posted by in This is not really a bug, but an intended (albeit questionable) behavior: The values of are actually globs, so globbing for in the root yields nothing. Given it finds nothing, pytest will behave as if called from the command-line without any parameters, which makes it search recursively from the current directory looking for to collect. If you create the directory, then pytest will correctly search in that directory only. I agree those 2 facts are surprising: fact that is a glob. This is but easy to overlook, probably we should add a glob to the example there. silently not finding anything, and then proceeding as usual. I don't think we can do anything more for 1, but for 2 seems like we should at least emit a warning if is defined but does not match anything.

args = []                         for path in testpaths:                             args.extend(sorted(glob.iglob(path, recursive=True)))<ins>                        if testpaths and not args:                            warning_text = (                                "No files were found in testpaths; "                                "consider removing or adjusting your testpaths configuration. "                                "Searching recursively from the current directory instead."                            )                            self.issue_config_time_warning(                                PytestConfigWarning(warning_text), stacklevel=3                            )</ins>                 if not args:                     source = Config.ArgsSource.INCOVATION_DIR                     args = [str(self.invocation_params.dir)]


Question: support sub-second granularity/precision in (strftime ) tl;dr pytest processing strftime specifier from arguments would allow me to accurately merge log messages from disparate sub-systems Tests I run have pytest log messages that print at the second granularity for the datetimestamp, e.g. . At the same time, other log file messages not generated by pytest print sub-second datetimestamps, e.g. . When reviewing the various logs, there are many message from other system components that are printing many log messages per second. Because pytest log messages are lacking sub-second precision, I am unable to align pytest log messages within other system log messages. For example, the system-under-test generates a log file like: and the driver of tests, pytest, generates a log file like: The pytest log messages cannot be precisely ordered among the other log messages that occurred during the datetime second , there were many things that occurred in the other system components within that second. Given the following pytest code To add sub-second granularity, it seems sensible to add within the but then I see the confusing output of pytest logging is ignoring the strftime specifier! I want pytest log messages to print sub-second granularity, e.g. process strftime within settings. <!-- A clear and concise description of what you want to happen. --Support strftime specifier in the various settings for date-format, e.g. , , . <!-- Provide examples of real-world use cases that this would enable and how it solves the problem described above. --In my complex testing system, this means all log messages would be printed to millisecond precision. This allows engineers investigating issues to more accurately merge disparate testing system logs by their natural ordering mechanism of a datetimestamp. <!-- Have you tried to workaround the problem using a pytest plugin or other tools? Or a different approach to solving this issue? Please elaborate here. --I can set the format to include . However, it's a little confusing to have to manipulate log datetimestamps by two different mechanisms, and . On the command-line run: This prints datetimestamps with millisecond precision <br /It is more intuitive for pytest to process the Python strftime specifier within all options.

import re from contextlib import contextmanager from contextlib import nullcontextfrom datetime import datetimefrom datetime import timedeltafrom datetime import timezone from io import StringIOfrom logging import LogRecord from pathlib import Path from typing import AbstractSet from typing import Dict


Question: support sub-second granularity/precision in (strftime ) tl;dr pytest processing strftime specifier from arguments would allow me to accurately merge log messages from disparate sub-systems Tests I run have pytest log messages that print at the second granularity for the datetimestamp, e.g. . At the same time, other log file messages not generated by pytest print sub-second datetimestamps, e.g. . When reviewing the various logs, there are many message from other system components that are printing many log messages per second. Because pytest log messages are lacking sub-second precision, I am unable to align pytest log messages within other system log messages. For example, the system-under-test generates a log file like: and the driver of tests, pytest, generates a log file like: The pytest log messages cannot be precisely ordered among the other log messages that occurred during the datetime second , there were many things that occurred in the other system components within that second. Given the following pytest code To add sub-second granularity, it seems sensible to add within the but then I see the confusing output of pytest logging is ignoring the strftime specifier! I want pytest log messages to print sub-second granularity, e.g. process strftime within settings. <!-- A clear and concise description of what you want to happen. --Support strftime specifier in the various settings for date-format, e.g. , , . <!-- Provide examples of real-world use cases that this would enable and how it solves the problem described above. --In my complex testing system, this means all log messages would be printed to millisecond precision. This allows engineers investigating issues to more accurately merge disparate testing system logs by their natural ordering mechanism of a datetimestamp. <!-- Have you tried to workaround the problem using a pytest plugin or other tools? Or a different approach to solving this issue? Please elaborate here. --I can set the format to include . However, it's a little confusing to have to manipulate log datetimestamps by two different mechanisms, and . On the command-line run: This prints datetimestamps with millisecond precision <br /It is more intuitive for pytest to process the Python strftime specifier within all options.

return _ANSI_ESCAPE_SEQ.sub("", text)  class ColoredLevelFormatter(logging.Formatter):class DatetimeFormatter(logging.Formatter):    """A logging formatter which formats record with    :func:`datetime.datetime.strftime` formatter instead of    :func:`time.strftime` in case of microseconds in format string.    """    def formatTime(self, record: LogRecord, datefmt=None) -> str:        if datefmt and "%f" in datefmt:            ct = self.converter(record.created)            tz = timezone(timedelta(seconds=ct.tm_gmtoff), ct.tm_zone)            # Construct `datetime.datetime` object from `struct_time`            # and msecs information from `record`            dt = datetime(*ct[0:6], microsecond=round(record.msecs * 1000), tzinfo=tz)            return dt.strftime(datefmt)        # Use `logging.Formatter` for non-microsecond formats        return super().formatTime(record, datefmt)class ColoredLevelFormatter(DatetimeFormatter):     """A logging formatter which colorizes the %(levelname)..s part of the     log format passed to __init__."""


Question: support sub-second granularity/precision in (strftime ) tl;dr pytest processing strftime specifier from arguments would allow me to accurately merge log messages from disparate sub-systems Tests I run have pytest log messages that print at the second granularity for the datetimestamp, e.g. . At the same time, other log file messages not generated by pytest print sub-second datetimestamps, e.g. . When reviewing the various logs, there are many message from other system components that are printing many log messages per second. Because pytest log messages are lacking sub-second precision, I am unable to align pytest log messages within other system log messages. For example, the system-under-test generates a log file like: and the driver of tests, pytest, generates a log file like: The pytest log messages cannot be precisely ordered among the other log messages that occurred during the datetime second , there were many things that occurred in the other system components within that second. Given the following pytest code To add sub-second granularity, it seems sensible to add within the but then I see the confusing output of pytest logging is ignoring the strftime specifier! I want pytest log messages to print sub-second granularity, e.g. process strftime within settings. <!-- A clear and concise description of what you want to happen. --Support strftime specifier in the various settings for date-format, e.g. , , . <!-- Provide examples of real-world use cases that this would enable and how it solves the problem described above. --In my complex testing system, this means all log messages would be printed to millisecond precision. This allows engineers investigating issues to more accurately merge disparate testing system logs by their natural ordering mechanism of a datetimestamp. <!-- Have you tried to workaround the problem using a pytest plugin or other tools? Or a different approach to solving this issue? Please elaborate here. --I can set the format to include . However, it's a little confusing to have to manipulate log datetimestamps by two different mechanisms, and . On the command-line run: This prints datetimestamps with millisecond precision <br /It is more intuitive for pytest to process the Python strftime specifier within all options.

config, "log_file_date_format", "log_date_format"         )         log_file_formatter = logging.Formatter(        log_file_formatter = DatetimeFormatter(             log_file_format, datefmt=log_file_date_format         )         self.log_file_handler.setFormatter(log_file_formatter)


Question: support sub-second granularity/precision in (strftime ) tl;dr pytest processing strftime specifier from arguments would allow me to accurately merge log messages from disparate sub-systems Tests I run have pytest log messages that print at the second granularity for the datetimestamp, e.g. . At the same time, other log file messages not generated by pytest print sub-second datetimestamps, e.g. . When reviewing the various logs, there are many message from other system components that are printing many log messages per second. Because pytest log messages are lacking sub-second precision, I am unable to align pytest log messages within other system log messages. For example, the system-under-test generates a log file like: and the driver of tests, pytest, generates a log file like: The pytest log messages cannot be precisely ordered among the other log messages that occurred during the datetime second , there were many things that occurred in the other system components within that second. Given the following pytest code To add sub-second granularity, it seems sensible to add within the but then I see the confusing output of pytest logging is ignoring the strftime specifier! I want pytest log messages to print sub-second granularity, e.g. process strftime within settings. <!-- A clear and concise description of what you want to happen. --Support strftime specifier in the various settings for date-format, e.g. , , . <!-- Provide examples of real-world use cases that this would enable and how it solves the problem described above. --In my complex testing system, this means all log messages would be printed to millisecond precision. This allows engineers investigating issues to more accurately merge disparate testing system logs by their natural ordering mechanism of a datetimestamp. <!-- Have you tried to workaround the problem using a pytest plugin or other tools? Or a different approach to solving this issue? Please elaborate here. --I can set the format to include . However, it's a little confusing to have to manipulate log datetimestamps by two different mechanisms, and . On the command-line run: This prints datetimestamps with millisecond precision <br /It is more intuitive for pytest to process the Python strftime specifier within all options.

create_terminal_writer(self._config), log_format, log_date_format             )         else:            formatter = logging.Formatter(log_format, log_date_format)            formatter = DatetimeFormatter(log_format, log_date_format)          formatter._style = PercentStyleMultiline(             formatter._style._fmt, auto_indent=auto_indent


Question: Pytest 7.3.2 changes in behaviour regarding and In , we have two test suites - the unit tests at and the integration test suite at . Both and are listed in testpaths- We then run either or using /. Each / dir contains a file, which adds some options using . One option that is common to both test suites is . Before 7.3.2, this setup seemed to work, we could run both unit tests and integration tests without issue. But on 7.3.2 (perhaps since ?) we get the following error: Is this an issue in our configuration, or a bug? Should we no longer use testpaths to list all the test suites? <details<summarypip list output</summary</detailsXref

#     def _set_initial_conftests(         self,        namespace: argparse.Namespace,        args: Sequence[Union[str, Path]],        pyargs: bool,        noconftest: bool,         rootpath: Path,        testpaths_ini: Sequence[str],        confcutdir: Optional[Path],        importmode: Union[ImportMode, str],     ) -> None:         """Load initial conftest files given a preparsed "namespace".


Question: Pytest 7.3.2 changes in behaviour regarding and In , we have two test suites - the unit tests at and the integration test suite at . Both and are listed in testpaths- We then run either or using /. Each / dir contains a file, which adds some options using . One option that is common to both test suites is . Before 7.3.2, this setup seemed to work, we could run both unit tests and integration tests without issue. But on 7.3.2 (perhaps since ?) we get the following error: Is this an issue in our configuration, or a bug? Should we no longer use testpaths to list all the test suites? <details<summarypip list output</summary</detailsXref

common options will not confuse our logic here.         """         current = Path.cwd()        self._confcutdir = (            absolutepath(current / namespace.confcutdir)            if namespace.confcutdir            else None        )        self._noconftest = namespace.noconftest        self._using_pyargs = namespace.pyargs        testpaths = namespace.file_or_dir + testpaths_ini        self._confcutdir = absolutepath(current / confcutdir) if confcutdir else None        self._noconftest = noconftest        self._using_pyargs = pyargs         foundanchor = False        for testpath in testpaths:            path = str(testpath)        for intitial_path in args:            path = str(intitial_path)             # remove node-id syntax             i = path.find("::")             if i != -1:


Question: Pytest 7.3.2 changes in behaviour regarding and In , we have two test suites - the unit tests at and the integration test suite at . Both and are listed in testpaths- We then run either or using /. Each / dir contains a file, which adds some options using . One option that is common to both test suites is . Before 7.3.2, this setup seemed to work, we could run both unit tests and integration tests without issue. But on 7.3.2 (perhaps since ?) we get the following error: Is this an issue in our configuration, or a bug? Should we no longer use testpaths to list all the test suites? <details<summarypip list output</summary</detailsXref

except OSError:  # pragma: no cover                 anchor_exists = False             if anchor_exists:                self._try_load_conftest(anchor, namespace.importmode, rootpath)                self._try_load_conftest(anchor, importmode, rootpath)                 foundanchor = True         if not foundanchor:            self._try_load_conftest(current, namespace.importmode, rootpath)            self._try_load_conftest(current, importmode, rootpath)      def _is_in_confcutdir(self, path: Path) -> bool:         """Whether a path is within the confcutdir.


Question: Pytest 7.3.2 changes in behaviour regarding and In , we have two test suites - the unit tests at and the integration test suite at . Both and are listed in testpaths- We then run either or using /. Each / dir contains a file, which adds some options using . One option that is common to both test suites is . Before 7.3.2, this setup seemed to work, we could run both unit tests and integration tests without issue. But on 7.3.2 (perhaps since ?) we get the following error: Is this an issue in our configuration, or a bug? Should we no longer use testpaths to list all the test suites? <details<summarypip list output</summary</detailsXref

@hookimpl(trylast=True)     def pytest_load_initial_conftests(self, early_config: "Config") -> None:        # We haven't fully parsed the command line arguments yet, so        # early_config.args it not set yet. But we need it for        # discovering the initial conftests. So "pre-run" the logic here.        # It will be done for real in `parse()`.        args, args_source = early_config._decide_args(            args=early_config.known_args_namespace.file_or_dir,            pyargs=early_config.known_args_namespace.pyargs,            testpaths=early_config.getini("testpaths"),            invocation_dir=early_config.invocation_params.dir,            rootpath=early_config.rootpath,            warn=False,        )         self.pluginmanager._set_initial_conftests(            early_config.known_args_namespace,            args=args,            pyargs=early_config.known_args_namespace.pyargs,            noconftest=early_config.known_args_namespace.noconftest,             rootpath=early_config.rootpath,            testpaths_ini=self.getini("testpaths"),            confcutdir=early_config.known_args_namespace.confcutdir,            importmode=early_config.known_args_namespace.importmode,         )      def _initini(self, args: Sequence[str]) -> None:


Question: Pytest 7.3.2 changes in behaviour regarding and In , we have two test suites - the unit tests at and the integration test suite at . Both and are listed in testpaths- We then run either or using /. Each / dir contains a file, which adds some options using . One option that is common to both test suites is . Before 7.3.2, this setup seemed to work, we could run both unit tests and integration tests without issue. But on 7.3.2 (perhaps since ?) we get the following error: Is this an issue in our configuration, or a bug? Should we no longer use testpaths to list all the test suites? <details<summarypip list output</summary</detailsXref

return args <ins>    def _decide_args(        self,        *,        args: List[str],        pyargs: List[str],        testpaths: List[str],        invocation_dir: Path,        rootpath: Path,        warn: bool,    ) -> Tuple[List[str], ArgsSource]:        """Decide the args (initial paths/nodeids) to use given the relevant inputs.        :param warn: Whether can issue warnings.        """        if args:            source = Config.ArgsSource.ARGS            result = args        else:            if invocation_dir == rootpath:                source = Config.ArgsSource.TESTPATHS                if pyargs:                    result = testpaths                else:                    result = []                    for path in testpaths:                        result.extend(sorted(glob.iglob(path, recursive=True)))                    if testpaths and not result:                        if warn:                            warning_text = (                                "No files were found in testpaths; "                                "consider removing or adjusting your testpaths configuration. "                                "Searching recursively from the current directory instead."                            )                            self.issue_config_time_warning(                                PytestConfigWarning(warning_text), stacklevel=3                            )            else:                result = []            if not result:                source = Config.ArgsSource.INCOVATION_DIR                result = [str(invocation_dir)]        return result, source</ins>     def _preparse(self, args: List[str], addopts: bool = True) -> None:         if addopts:             env_addopts = os.environ.get("PYTEST_ADDOPTS", "")


Question: Pytest 7.3.2 changes in behaviour regarding and In , we have two test suites - the unit tests at and the integration test suite at . Both and are listed in testpaths- We then run either or using /. Each / dir contains a file, which adds some options using . One option that is common to both test suites is . Before 7.3.2, this setup seemed to work, we could run both unit tests and integration tests without issue. But on 7.3.2 (perhaps since ?) we get the following error: Is this an issue in our configuration, or a bug? Should we no longer use testpaths to list all the test suites? <details<summarypip list output</summary</detailsXref

self.hook.pytest_cmdline_preparse(config=self, args=args)         self._parser.after_preparse = True  # type: ignore         try:            source = Config.ArgsSource.ARGS             args = self._parser.parse_setoption(                 args, self.option, namespace=self.option             )            if not args:                if self.invocation_params.dir == self.rootpath:                    source = Config.ArgsSource.TESTPATHS                    testpaths: List[str] = self.getini("testpaths")                    if self.known_args_namespace.pyargs:                        args = testpaths                    else:                        args = []                        for path in testpaths:                            args.extend(sorted(glob.iglob(path, recursive=True)))                        if testpaths and not args:                            warning_text = (                                "No files were found in testpaths; "                                "consider removing or adjusting your testpaths configuration. "                                "Searching recursively from the current directory instead."                            )                            self.issue_config_time_warning(                                PytestConfigWarning(warning_text), stacklevel=3                            )                if not args:                    source = Config.ArgsSource.INCOVATION_DIR                    args = [str(self.invocation_params.dir)]            self.args = args            self.args_source = source            self.args, self.args_source = self._decide_args(                args=args,                pyargs=self.known_args_namespace.pyargs,                testpaths=self.getini("testpaths"),                invocation_dir=self.invocation_params.dir,                rootpath=self.rootpath,                warn=True,            )         except PrintHelp:             pass


Question: Rewrite fails when first expression of file is a number and mistaken as docstring <!-- Thanks for submitting an issue! Quick check-list while reporting bugs: --- [x] a detailed description of the bug or problem you are having [x] output of from the virtual environment you are using [x] pytest and operating system versions [x] minimal example if possible use report an error it seems a error in collecting testcase

expect_docstring                 and isinstance(item, ast.Expr)                 and isinstance(item.value, ast.Constant)<ins>                and isinstance(item.value.value, str)</ins>             ):                 doc = item.value.value                 if self.is_rewrite_disabled(doc):


Question: Module imported twice under import-mode=importlib In pmxbot/pmxbot I'm attempting to switch pmxbot off of pkgresources style namespace packaging to PEP 420 namespace packages. To do so, I've needed to switch to for the and re-organize the tests to avoid import errors on the tests. Yet even after working around these issues, the tests are failing when the effect of doesn't seem to have had any effect. Investigating deeper, I see that initializer is executed and performs its actions (setting a class variable ), but when that happens, there are two different versions of present, one in and another found in : I haven't yet made a minimal reproducer, but I wanted to first capture this condition.

if mode is ImportMode.importlib:         module_name = module_name_from_path(path, root)<ins>        with contextlib.suppress(KeyError):            return sys.modules[module_name]</ins>          for meta_importer in sys.meta_path:             spec = meta_importer.find_spec(module_name, [str(path.parent)])


Question: () improperly matches warning When trying to pop a specific warning from a WarningsRecorder instance, the wrong warning is returned. I believe the issue is that pop uses issubclass I believe the correct comparison should be: Here is a minimum working example that triggers the buggy behavior: The test output is pytest 7.2.1 on archlinux. virtual environment is a clean conda environment with only python and pytest (and their dependencies installed from conda-forge). If this is indeed a bug, I'm happy to open a PR with my proposed solution. () improperly matches warning When trying to pop a specific warning from a WarningsRecorder instance, the wrong warning is returned. I believe the issue is that pop uses issubclass I believe the correct comparison should be: Here is a minimum working example that triggers the buggy behavior: The test output is pytest 7.2.1 on archlinux. virtual environment is a clean conda environment with only python and pytest (and their dependencies installed from conda-forge). If this is indeed a bug, I'm happy to open a PR with my proposed solution.

return len(self._list)      def pop(self, cls: Type[Warning] = Warning) -> "warnings.WarningMessage":        """Pop the first recorded warning, raise exception if not exists."""        """Pop the first recorded warning which is an instance of ``cls``,        but not an instance of a child class of any other match.        Raises ``AssertionError`` if there is no match.        """        best_idx: Optional[int] = None         for i, w in enumerate(self._list):            if issubclass(w.category, cls):                return self._list.pop(i)            if w.category == cls:                return self._list.pop(i)  # exact match, stop looking            if issubclass(w.category, cls) and (                best_idx is None                or not issubclass(w.category, self._list[best_idx].category)            ):                best_idx = i        if best_idx is not None:            return self._list.pop(best_idx)         __tracebackhide__ = True         raise AssertionError(f"{cls!r} not found in warning list")


Question: fails with When using to test float and one of the objects in the statement contain I see the following TypeError: TypeError: unsupported operand type(s) for -: 'float' and 'NoneType'. macOS 12.6.3 python 3.10.4 pytest 7.2.1

approx_side_as_map.items(), other_side.values()         ):             if approx_value != other_value:                max_abs_diff = max(                    max_abs_diff, abs(approx_value.expected - other_value)                )                if approx_value.expected == 0.0:                    max_rel_diff = math.inf                else:                    max_rel_diff = max(                        max_rel_diff,                        abs(                            (approx_value.expected - other_value)                            / approx_value.expected                        ),                if approx_value.expected is not None and other_value is not None:                    max_abs_diff = max(                        max_abs_diff, abs(approx_value.expected - other_value)                     )                    if approx_value.expected == 0.0:                        max_rel_diff = math.inf                    else:                        max_rel_diff = max(                            max_rel_diff,                            abs(                                (approx_value.expected - other_value)                                / approx_value.expected                            ),                        )                 different_ids.append(approx_key)          message_data = [


Question: fixtures: show test as skip location if skipped from an xunit setup function PR made it so that if a fixture calls , the skip location is shown as the test function, not the fixture. But it excluded xunit setup fixtures from this. I suspect this was done to make a pre-existing test pass, however I think that the same reason for fixtures applies to xunit fixtures just as well, so we shouldn't exclude it. Would also remove a string-hack that was used to implement this exclusion...

try:         result = call_fixture_func(fixturefunc, request, kwargs)     except TEST_OUTCOME as e:        if isinstance(e, skip.Exception) and not fixturefunc.__name__.startswith(            "xunit_setup"        ):        if isinstance(e, skip.Exception):            # The test requested a fixture which caused a skip.            # Don't show the fixture as the skip location, as then the user            # wouldn't know which test skipped.             e._use_item_location = True         fixturedef.cached_result = (None, my_cache_key, e)         raise


Question: Unroll the iterable for all/any calls to get better reports Sometime I need to assert some predicate on all of an iterable, and for that the builtin functions / are great - but the failure messages aren't useful at all! For example - the same test written in three ways: A generator expression A list comprehension A for loop The only one that gives a meaningful report is the for loop - but it's way more wordy, and asserts don't translate to a for loop nicely (I'll have to write a or a helper function - yuck) I propose the assertion re-writer "unrolls" the iterator to the third form, and then uses the already existing reports. [x] Include a detailed description of the bug or suggestion [x] of the virtual environment you are using [x] pytest and operating system versions [x] Minimal example if possible

"""         visit `ast.Call` nodes on Python3.5 and after         """<ins>        if isinstance(call.func, ast.Name) and call.func.id == "all":            return self._visit_all(call)</ins>         new_func, func_expl = self.visit(call.func)         arg_expls = []         new_args = []


Question: Unroll the iterable for all/any calls to get better reports Sometime I need to assert some predicate on all of an iterable, and for that the builtin functions / are great - but the failure messages aren't useful at all! For example - the same test written in three ways: A generator expression A list comprehension A for loop The only one that gives a meaningful report is the for loop - but it's way more wordy, and asserts don't translate to a for loop nicely (I'll have to write a or a helper function - yuck) I propose the assertion re-writer "unrolls" the iterator to the third form, and then uses the already existing reports. [x] Include a detailed description of the bug or suggestion [x] of the virtual environment you are using [x] pytest and operating system versions [x] Minimal example if possible

outer_expl = "%s\n{%s = %s\n}" % (res_expl, res_expl, expl)         return res, outer_expl <ins>    def _visit_all(self, call):        """Special rewrite for the builtin all function, see #5062"""        if not isinstance(call.args[0], (ast.GeneratorExp, ast.ListComp)):            return        gen_exp = call.args[0]        assertion_module = ast.Module(            body=[ast.Assert(test=gen_exp.elt, lineno=1, msg="", col_offset=1)]        )        AssertionRewriter(module_path=None, config=None).run(assertion_module)        for_loop = ast.For(            iter=gen_exp.generators[0].iter,            target=gen_exp.generators[0].target,            body=assertion_module.body,            orelse=[],        )        self.statements.append(for_loop)        return (            ast.Num(n=1),            "",        )  # Return an empty expression, all the asserts are in the for_loop</ins>     def visit_Starred(self, starred):         # From Python 3.5, a Starred node can appear in a function call         res, expl = self.visit(starred.value)


Question: Unroll the iterable for all/any calls to get better reports Sometime I need to assert some predicate on all of an iterable, and for that the builtin functions / are great - but the failure messages aren't useful at all! For example - the same test written in three ways: A generator expression A list comprehension A for loop The only one that gives a meaningful report is the for loop - but it's way more wordy, and asserts don't translate to a for loop nicely (I'll have to write a or a helper function - yuck) I propose the assertion re-writer "unrolls" the iterator to the third form, and then uses the already existing reports. [x] Include a detailed description of the bug or suggestion [x] of the virtual environment you are using [x] pytest and operating system versions [x] Minimal example if possible

"""         visit `ast.Call nodes on 3.4 and below`         """<ins>        if isinstance(call.func, ast.Name) and call.func.id == "all":            return self._visit_all(call)</ins>         new_func, func_expl = self.visit(call.func)         arg_expls = []         new_args = []


Question: Invalid XML schema for <propertiestags in JUnit reports The problem: JUnit breaks when it reads an XML generated by pytest if plugins make use of . This behavior happens with newer versions of hypothesis (). In fact, as already mentioned in , is adding inside which seems to be wrong (it should be inside ). See: . It happens with all junit families. Reproducing: I was trying to create a PR to fix this, but when I saw code I realized that what is needed to do could have more implications that I though. I think that nobody uses this feature with JUnit (as it breaks) and removing that is something to think about.

return attr_func  <ins>def _check_record_param_type(param, v):    """Used by record_testsuite_property to check that the given parameter name is of the proper    type"""    __tracebackhide__ = True    if not isinstance(v, six.string_types):        msg = "{param} parameter needs to be a string, but {g} given"        raise TypeError(msg.format(param=param, g=type(v).__name__))@pytest.fixture(scope="session")def record_testsuite_property(request):    """    Records a new ``<property>`` tag as child of the root ``<testsuite>``. This is suitable to    writing global information regarding the entire test suite, and is compatible with ``xunit2`` JUnit family.    This is a ``session``-scoped fixture which is called with ``(name, value)``. Example:    .. code-block:: python        def test_foo(record_testsuite_property):            record_testsuite_property("ARCH", "PPC")            record_testsuite_property("STORAGE_TYPE", "CEPH")    ``name`` must be a string, ``value`` will be converted to a string and properly xml-escaped.    """    __tracebackhide__ = True    def record_func(name, value):        """noop function in case --junitxml was not passed in the command-line"""        __tracebackhide__ = True        _check_record_param_type("name", name)    xml = getattr(request.config, "_xml", None)    if xml is not None:        record_func = xml.add_global_property  # noqa    return record_func</ins> def pytest_addoption(parser):     group = parser.getgroup("terminal reporting")     group.addoption(


Question: Invalid XML schema for <propertiestags in JUnit reports The problem: JUnit breaks when it reads an XML generated by pytest if plugins make use of . This behavior happens with newer versions of hypothesis (). In fact, as already mentioned in , is adding inside which seems to be wrong (it should be inside ). See: . It happens with all junit families. Reproducing: I was trying to create a PR to fix this, but when I saw code I realized that what is needed to do could have more implications that I though. I think that nobody uses this feature with JUnit (as it breaks) and removing that is something to think about.

self.node_reporters = {}  # nodeid -> _NodeReporter         self.node_reporters_ordered = []         self.global_properties = []<ins></ins>         # List of reports that failed on call but teardown is pending.         self.open_reports = []         self.cnt_double_fail_tests = 0


Question: Invalid XML schema for <propertiestags in JUnit reports The problem: JUnit breaks when it reads an XML generated by pytest if plugins make use of . This behavior happens with newer versions of hypothesis (). In fact, as already mentioned in , is adding inside which seems to be wrong (it should be inside ). See: . It happens with all junit families. Reproducing: I was trying to create a PR to fix this, but when I saw code I realized that what is needed to do could have more implications that I though. I think that nobody uses this feature with JUnit (as it breaks) and removing that is something to think about.

terminalreporter.write_sep("-", "generated xml file: %s" % (self.logfile))      def add_global_property(self, name, value):        self.global_properties.append((str(name), bin_xml_escape(value)))        __tracebackhide__ = True        _check_record_param_type("name", name)        self.global_properties.append((name, bin_xml_escape(value)))      def _get_global_properties_node(self):         """Return a Junit node containing custom properties, if any.


Question: Display fixture scope with It would be useful to show fixture scopes with ; currently the only way to learn the scope of a fixture is look at the docs (when that is documented) or at the source code.

currentmodule = module         if verbose <= 0 and argname[0] == "_":             continue        tw.write(argname, green=True)        if fixturedef.scope != "function":            tw.write(" [%s scope]" % fixturedef.scope, cyan=True)         if verbose > 0:            funcargspec = "%s -- %s" % (argname, bestrel)        else:            funcargspec = argname        tw.line(funcargspec, green=True)            tw.write(" -- %s" % bestrel, yellow=True)        tw.write("\n")         loc = getlocation(fixturedef.func, curdir)         doc = fixturedef.func.__doc__ or ""         if doc:             write_docstring(tw, doc)         else:             tw.line("    %s: no docstring available" % (loc,), red=True)        tw.line()   def write_docstring(tw, doc, indent="    "):


Question: Improve default logging format Currently it is: I think (module name) would be very useful here, instead of just the base filename. (It might also be good to have the relative path there (maybe at the end), but it is usually still very long (but e.g. could be substituted therein)) Currently it would look like this: Using instead:

from _pytest.config import create_terminal_writer from _pytest.pathlib import Path DEFAULT_LOG_FORMAT = "%(filename)-25s %(lineno)4d %(levelname)-8s %(message)s"DEFAULT_LOG_FORMAT = "%(levelname)-8s %(name)s:%(filename)s:%(lineno)d %(message)s" DEFAULT_LOG_DATE_FORMAT = "%H:%M:%S"


Question: does not correctly hide fixtures of the same name (it misses its dependencies) From This works: the parameter in the test correctly hides the fixture so the unique pytest node has id (instead of there being two nodes because of the fixture). However if the fixture that is hidden by the parameter depends on another fixture, that other fixture is mistakenly kept in the fixtures closure, even if it is not needed anymore. Therefore the test fails:

self._nodeid_and_autousenames = [("", self.config.getini("usefixtures"))]         session.config.pluginmanager.register(self, "funcmanage")     def _get_direct_parametrize_args(self, node):        """This function returns all the direct parametrization        arguments of a node, so we don't mistake them for fixtures        Check https://github.com/pytest-dev/pytest/issues/5036        This things are done later as well when dealing with parametrization        so this could be improved        """        from _pytest.mark import ParameterSet        parametrize_argnames = []        for marker in node.iter_markers(name="parametrize"):            if not marker.kwargs.get("indirect", False):                p_argnames, _ = ParameterSet._parse_parametrize_args(                    *marker.args, **marker.kwargs                )                parametrize_argnames.extend(p_argnames)        return parametrize_argnames     def getfixtureinfo(self, node, func, cls, funcargs=True):         if funcargs and not getattr(node, "nofuncargs", False):             argnames = getfuncargnames(func, cls=cls)         else:             argnames = ()         usefixtures = itertools.chain.from_iterable(             mark.args for mark in node.iter_markers(name="usefixtures")         )         initialnames = tuple(usefixtures) + argnames         fm = node.session._fixturemanager         initialnames, names_closure, arg2fixturedefs = fm.getfixtureclosure(            initialnames, node            initialnames, node, ignore_args=self._get_direct_parametrize_args(node)         )         return FuncFixtureInfo(argnames, initialnames, names_closure, arg2fixturedefs)


Question: does not correctly hide fixtures of the same name (it misses its dependencies) From This works: the parameter in the test correctly hides the fixture so the unique pytest node has id (instead of there being two nodes because of the fixture). However if the fixture that is hidden by the parameter depends on another fixture, that other fixture is mistakenly kept in the fixtures closure, even if it is not needed anymore. Therefore the test fails:

autousenames.extend(basenames)         return autousenames     def getfixtureclosure(self, fixturenames, parentnode):    def getfixtureclosure(self, fixturenames, parentnode, ignore_args=()):         # collect the closure of all fixtures , starting with the given         # fixturenames as the initial set.  As we have to visit all         # factory definitions anyway, we also return an arg2fixturedefs


Question: does not correctly hide fixtures of the same name (it misses its dependencies) From This works: the parameter in the test correctly hides the fixture so the unique pytest node has id (instead of there being two nodes because of the fixture). However if the fixture that is hidden by the parameter depends on another fixture, that other fixture is mistakenly kept in the fixtures closure, even if it is not needed anymore. Therefore the test fails:

while lastlen != len(fixturenames_closure):             lastlen = len(fixturenames_closure)             for argname in fixturenames_closure:                if argname in ignore_args:                    continue                 if argname in arg2fixturedefs:                     continue                 fixturedefs = self.getfixturedefs(argname, parentid)diff --git a/src/_pytest/mark/structures.py b/src/_pytest/mark/structures.py-- a/src/_pytest/mark/structures.py++ b/src/_pytest/mark/structures.py


Question: does not correctly hide fixtures of the same name (it misses its dependencies) From This works: the parameter in the test correctly hides the fixture so the unique pytest node has id (instead of there being two nodes because of the fixture). However if the fixture that is hidden by the parameter depends on another fixture, that other fixture is mistakenly kept in the fixtures closure, even if it is not needed anymore. Therefore the test fails:

else:             return cls(parameterset, marks=[], id=None)     @classmethod    def _for_parametrize(cls, argnames, argvalues, func, config, function_definition):    @staticmethod    def _parse_parametrize_args(argnames, argvalues, **_):        """It receives an ignored _ (kwargs) argument so this function can        take also calls from parametrize ignoring scope, indirect, and other        arguments..."""         if not isinstance(argnames, (tuple, list)):             argnames = [x.strip() for x in argnames.split(",") if x.strip()]             force_tuple = len(argnames) == 1


Question: does not correctly hide fixtures of the same name (it misses its dependencies) From This works: the parameter in the test correctly hides the fixture so the unique pytest node has id (instead of there being two nodes because of the fixture). However if the fixture that is hidden by the parameter depends on another fixture, that other fixture is mistakenly kept in the fixtures closure, even if it is not needed anymore. Therefore the test fails:

parameters = [             ParameterSet.extract_from(x, force_tuple=force_tuple) for x in argvalues         ]<ins>        return argnames, parameters    @classmethod    def _for_parametrize(cls, argnames, argvalues, func, config, function_definition):        argnames, parameters = cls._parse_parametrize_args(argnames, argvalues)</ins>         del argvalues          if parameters:


Question: pytest.capture.EncodedFile mode should not include (binary) <!-- Thanks for submitting an issue! Here's a quick checklist for what to provide: --- [x] a detailed description of the bug or suggestion Exception when youtube-dl logs to pytest captured output. Youtube-dl looks for in to decide whether to writes or . incorrectly advertises , the mode of the underlying stream. Its method raises an exception when passed . [x] output of from the virtual environment you are using [x] pytest and operating system versions [x] minimal example if possible

"""Ensure that file.name is a string."""         return repr(self.buffer) <ins>    @property    def mode(self):        return self.buffer.mode.replace("b", "")</ins>     def __getattr__(self, name):         return getattr(object.__getattribute__(self, "buffer"), name)


Question: Invalid unicode in with Jython With: Jython 2.7.1 and pytest 4.5.0, I'm having the error below: The error happens because has the following unicode literal: . I'm not sure about the proper fix... in that function seems to be doing a and later does , so, I'm not even sure if we're dealing with or there on Python 2 because it's mixed (my guess is bytes, but I'm not really sure). If it's bytes, doing it an actual literal instead of a literal -- i.e.: remove the -- does make Jython happy (would that be an appropriate solution?)

"""Ensure that file.name is a string."""         return repr(self.buffer)     @property    def mode(self):        return self.buffer.mode.replace("b", "")     def __getattr__(self, name):         return getattr(object.__getattribute__(self, "buffer"), name) diff --git a/src/_pytest/terminal.py b/src/_pytest/terminal.py-- a/src/_pytest/terminal.py++ b/src/_pytest/terminal.py


Question: Invalid unicode in with Jython With: Jython 2.7.1 and pytest 4.5.0, I'm having the error below: The error happens because has the following unicode literal: . I'm not sure about the proper fix... in that function seems to be doing a and later does , so, I'm not even sure if we're dealing with or there on Python 2 because it's mixed (my guess is bytes, but I'm not really sure). If it's bytes, doing it an actual literal instead of a literal -- i.e.: remove the -- does make Jython happy (would that be an appropriate solution?)

# u'😄' will result in a High Surrogate (U+D83D) character, which is                     # rendered as u'�'; in this case we just strip that character out as it                     # serves no purpose being rendered                    msg = msg.rstrip(u"\uD83D")                    try:                        surrogate = six.unichr(0xD83D)                        msg = msg.rstrip(surrogate)                    except ValueError:  # pragma: no cover                        # Jython cannot represent this lone surrogate at all (#5256):                        # ValueError: unichr() arg is a lone surrogate in range                        #     (0xD800, 0xDFFF) (Jython UTF-16 encoding)                        # ignore this case as it shouldn't appear in the string anyway                        pass                 msg += ellipsis             line += sep + msg     return line


Question: Version 4.6.0 skips tests without apparent reason Since version 4.6.0 pytest skips tests without apparent reason: https://travis- [x] pytest and operating system versions: pytest 4.6.0 on Ubuntu Xenial @ Travis CI [x] minimal example if possible: link above I can't understand why it happens, so I had to immediately rollback to 4.5.0 and fix this version in dev dependencies.

force_tuple = len(argnames) == 1         else:             force_tuple = False        parameters = [        return argnames, force_tuple    @staticmethod    def _parse_parametrize_parameters(argvalues, force_tuple):        return [             ParameterSet.extract_from(x, force_tuple=force_tuple) for x in argvalues         ]        return argnames, parameters      @classmethod     def _for_parametrize(cls, argnames, argvalues, func, config, function_definition):        argnames, parameters = cls._parse_parametrize_args(argnames, argvalues)        argnames, force_tuple = cls._parse_parametrize_args(argnames, argvalues)        parameters = cls._parse_parametrize_parameters(argvalues, force_tuple)         del argvalues          if parameters:


Question: KeyError: 'wrapped' with from xxx import yyy [X] Include a detailed description of the bug or suggestion [ ] of the virtual environment you are using [X] pytest and operating system versions [X] Minimal example if possible I implemented and for automated testing. When I run the , I get a when I perform a . In the example I included, I do not get the KeyError if I comment out the line: ... from sty import fg ... No virtual environment used. Python: 3.6.5 & 3.7.1 PyTest: 4.4.0 OS: MacOS Mojave 10.14.4 I created a very simple . If I clone the repo and call either or in the root directory, I get the error. My apologies if this bug is obvious or I am doing something wrong.

import platform import sys import traceback<ins>import warnings</ins> from contextlib import contextmanager  import pytest


Question: KeyError: 'wrapped' with from xxx import yyy [X] Include a detailed description of the bug or suggestion [ ] of the virtual environment you are using [X] pytest and operating system versions [X] Minimal example if possible I implemented and for automated testing. When I run the , I get a when I perform a . In the example I included, I do not get the KeyError if I comment out the line: ... from sty import fg ... No virtual environment used. Python: 3.6.5 & 3.7.1 PyTest: 4.4.0 OS: MacOS Mojave 10.14.4 I created a very simple . If I clone the repo and call either or in the root directory, I get the error. My apologies if this bug is obvious or I am doing something wrong.

from _pytest.compat import safe_getattr from _pytest.fixtures import FixtureRequest from _pytest.outcomes import Skipped<ins>from _pytest.warning_types import PytestWarning</ins>  DOCTEST_REPORT_CHOICE_NONE = "none" DOCTEST_REPORT_CHOICE_CDIFF = "cdiff"


Question: KeyError: 'wrapped' with from xxx import yyy [X] Include a detailed description of the bug or suggestion [ ] of the virtual environment you are using [X] pytest and operating system versions [X] Minimal example if possible I implemented and for automated testing. When I run the , I get a when I perform a . In the example I included, I do not get the KeyError if I comment out the line: ... from sty import fg ... No virtual environment used. Python: 3.6.5 & 3.7.1 PyTest: 4.4.0 OS: MacOS Mojave 10.14.4 I created a very simple . If I clone the repo and call either or in the root directory, I get the error. My apologies if this bug is obvious or I am doing something wrong.

else:          def _mock_aware_unwrap(obj, stop=None):            if stop is None:                return real_unwrap(obj, stop=_is_mocked)            else:            try:                if stop is None or stop is _is_mocked:                    return real_unwrap(obj, stop=_is_mocked)                 return real_unwrap(obj, stop=lambda obj: _is_mocked(obj) or stop(obj))            except Exception as e:                warnings.warn(                    "Got %r when unwrapping %r.  This is usually caused "                    "by a violation of Python's object protocol; see e.g. "                    "https://github.com/pytest-dev/pytest/issues/5080" % (e, obj),                    PytestWarning,                )                raise          inspect.unwrap = _mock_aware_unwrap         try:


Question: str() on the context variable doesn't behave same as normal exception catch Pytest 4.6.2, macOS 10.14.5 prints But prints In order to get the full error message, one must do , which is documented, but this is a different interaction. Any chance the behavior could be changed to eliminate this gotcha? Pip list gives

)         return fmt.repr_excinfo(self) <del>    def __str__(self):        if self._excinfo is None:            return repr(self)        entry = self.traceback[-1]        loc = ReprFileLocation(entry.path, entry.lineno + 1, self.exconly())        return str(loc)</del>     def match(self, regexp):         """         Check whether the regular expression 'regexp' is found in the string


Question: Confusing assertion rewriting message with byte strings The comparison with assertion rewriting for byte strings is confusing: 52 is the ASCII ordinal of "4" here. It became clear to me when using another example: Not sure what should/could be done here.

def _compare_eq_sequence(left, right, verbose=0):    comparing_bytes = isinstance(left, bytes) and isinstance(right, bytes)     explanation = []     len_left = len(left)     len_right = len(right)     for i in range(min(len_left, len_right)):         if left[i] != right[i]:            if comparing_bytes:                # when comparing bytes, we want to see their ascii representation                # instead of their numeric values (#5260)                # using a slice gives us the ascii representation:                # >>> s = b'foo'                # >>> s[0]                # 102                # >>> s[0:1]                # b'f'                left_value = left[i : i + 1]                right_value = right[i : i + 1]            else:                left_value = left[i]                right_value = right[i]             explanation += [                "At index {} diff: {!r} != {!r}".format(i, left[i], right[i])                "At index {} diff: {!r} != {!r}".format(i, left_value, right_value)             ]             break    len_diff = len_left - len_right     if comparing_bytes:        # when comparing bytes, it doesn't help to show the "sides contain one or more items"        # longer explanation, so skip it        return explanation    len_diff = len_left - len_right     if len_diff:         if len_diff > 0:             dir_with_more = "Left"


Question: xunit2 format does not contain a root <testsuitestag junitfamily=xunit2 option still generates an old xml format tests report. junitfamily=xunit2 creates the .xml file in the legacy formatOS: MAC OS Mojave == 10.14.5 Sample output from the tests by running:

)         logfile.write('<?xml version="1.0" encoding="utf-8"?>')         logfile.write(            Junit.testsuite(                self._get_global_properties_node(),                [x.to_xml() for x in self.node_reporters_ordered],                name=self.suite_name,                errors=self.stats["error"],                failures=self.stats["failure"],                skipped=self.stats["skipped"],                tests=numtests,                time="%.3f" % suite_time_delta,            ).unicode(indent=0)        suite_node = Junit.testsuite(            self._get_global_properties_node(),            [x.to_xml() for x in self.node_reporters_ordered],            name=self.suite_name,            errors=self.stats["error"],            failures=self.stats["failure"],            skipped=self.stats["skipped"],            tests=numtests,            time="%.3f" % suite_time_delta,         )        logfile.write(Junit.testsuites([suite_node]).unicode(indent=0))         logfile.close()      def pytest_terminal_summary(self, terminalreporter):


Question: pytest stepwise doesn't work with xfail strict failures recommended pytest-runner in setuprequires means packages fail to install often The recommendation to add to means that all users of that package end up with an unnecessary pytest-runner package installed. This is bad because it bypasses pip hashes and

def pytest_collect_file(parent, path):    if path.ext == ".yml" and path.basename.startswith("test"):    if path.ext == ".yaml" and path.basename.startswith("test"):         return YamlFile(path, parent)  diff --git a/src/_pytest/_code/code.py b/src/_pytest/_code/code.py-- a/src/_pytest/_code/code.py++ b/src/_pytest/_code/code.py


Question: pytest stepwise doesn't work with xfail strict failures recommended pytest-runner in setuprequires means packages fail to install often The recommendation to add to means that all users of that package end up with an unnecessary pytest-runner package installed. This is bad because it bypasses pip hashes and

"""         __tracebackhide__ = True         if not re.search(regexp, str(self.value)):            assert 0, "Pattern '{!s}' not found in '{!s}'".format(regexp, self.value)            assert 0, "Pattern {!r} not found in {!r}".format(regexp, str(self.value))         return True  diff --git a/src/_pytest/stepwise.py b/src/_pytest/stepwise.py-- a/src/_pytest/stepwise.py++ b/src/_pytest/stepwise.py


Question: pytest stepwise doesn't work with xfail strict failures recommended pytest-runner in setuprequires means packages fail to install often The recommendation to add to means that all users of that package end up with an unnecessary pytest-runner package installed. This is bad because it bypasses pip hashes and

def pytest_runtest_logreport(self, report):         # Skip this hook if plugin is not active or the test is xfailed.        if not self.active or "xfail" in report.keywords:        if not self.active:             return          if report.failed:


Question: ValueError when collecting tests that patch an array <!-- Thanks for submitting an issue! Here's a quick checklist for what to provide: --I'm trying to run pytest with a test file that contains patch where "new" is an array, for example: from import patch ([-5.5, 3.0])) ... This works fine with pytest 3.1.3, but when using pytest 3.6.0 the following error is received upon collection: Seems like a bug, that was introduced by the following fix: when using like: ([-5.5, 3.0])), p.new is an array and the check: "p.new in sentinels" returns an array of booleans instead of a boolean which causes the ValueError.

patchings = getattr(function, "patchings", None)     if not patchings:         return 0    mock_modules = [sys.modules.get("mock"), sys.modules.get("unittest.mock")]    if any(mock_modules):        sentinels = [m.DEFAULT for m in mock_modules if m is not None]        return len(            [p for p in patchings if not p.attribute_name and p.new in sentinels]        )    return len(patchings)    mock_sentinel = getattr(sys.modules.get("mock"), "DEFAULT", object())    ut_mock_sentinel = getattr(sys.modules.get("unittest.mock"), "DEFAULT", object())    return len(        [            p            for p in patchings            if not p.attribute_name            and (p.new is mock_sentinel or p.new is ut_mock_sentinel)        ]    )   def getfuncargnames(function, is_method=False, cls=None):


Question: Hostname and timestamp properties in generated JUnit XML reports Pytest enables generating JUnit XML reports of the tests. However, there are some properties missing, specifically and from the XML element. Is there an option to include them? Example of a pytest XML report: Example of a junit XML report:

""" import functools import osimport platform import re import sys import timefrom datetime import datetime  import py


Question: Hostname and timestamp properties in generated JUnit XML reports Pytest enables generating JUnit XML reports of the tests. However, there are some properties missing, specifically and from the XML element. Is there an option to include them? Example of a pytest XML report: Example of a junit XML report:

skipped=self.stats["skipped"],             tests=numtests,             time="%.3f" % suite_time_delta,<ins>            timestamp=datetime.fromtimestamp(self.suite_start_time).isoformat(),            hostname=platform.node(),</ins>         )         logfile.write(Junit.testsuites([suite_node]).unicode(indent=0))         logfile.close()


Question: exception serialization should include chained exceptions given some simple tests: when run without xdist it displays whole exception trace nicely : but when run with xdist (), it just displays the last one: my setup:

import py <ins>from _pytest._code.code import ExceptionChainRepr</ins> from _pytest._code.code import ExceptionInfo from _pytest._code.code import ReprEntry from _pytest._code.code import ReprEntryNative


Question: exception serialization should include chained exceptions given some simple tests: when run without xdist it displays whole exception trace nicely : but when run with xdist (), it just displays the last one: my setup:

Experimental method.         """        def disassembled_report(rep):            reprtraceback = rep.longrepr.reprtraceback.__dict__.copy()            reprcrash = rep.longrepr.reprcrash.__dict__.copy()            new_entries = []            for entry in reprtraceback["reprentries"]:                entry_data = {                    "type": type(entry).__name__,                    "data": entry.__dict__.copy(),                }                for key, value in entry_data["data"].items():                    if hasattr(value, "__dict__"):                        entry_data["data"][key] = value.__dict__.copy()                new_entries.append(entry_data)            reprtraceback["reprentries"] = new_entries            return {                "reprcrash": reprcrash,                "reprtraceback": reprtraceback,                "sections": rep.longrepr.sections,            }        d = self.__dict__.copy()        if hasattr(self.longrepr, "toterminal"):            if hasattr(self.longrepr, "reprtraceback") and hasattr(                self.longrepr, "reprcrash"            ):                d["longrepr"] = disassembled_report(self)            else:                d["longrepr"] = str(self.longrepr)        else:            d["longrepr"] = self.longrepr        for name in d:            if isinstance(d[name], (py.path.local, Path)):                d[name] = str(d[name])            elif name == "result":                d[name] = None  # for now        return d        return _report_to_json(self)      @classmethod     def _from_json(cls, reportdict):


Question: exception serialization should include chained exceptions given some simple tests: when run without xdist it displays whole exception trace nicely : but when run with xdist (), it just displays the last one: my setup:

Experimental method.         """        if reportdict["longrepr"]:            if (                "reprcrash" in reportdict["longrepr"]                and "reprtraceback" in reportdict["longrepr"]            ):                reprtraceback = reportdict["longrepr"]["reprtraceback"]                reprcrash = reportdict["longrepr"]["reprcrash"]                unserialized_entries = []                reprentry = None                for entry_data in reprtraceback["reprentries"]:                    data = entry_data["data"]                    entry_type = entry_data["type"]                    if entry_type == "ReprEntry":                        reprfuncargs = None                        reprfileloc = None                        reprlocals = None                        if data["reprfuncargs"]:                            reprfuncargs = ReprFuncArgs(**data["reprfuncargs"])                        if data["reprfileloc"]:                            reprfileloc = ReprFileLocation(**data["reprfileloc"])                        if data["reprlocals"]:                            reprlocals = ReprLocals(data["reprlocals"]["lines"])                        reprentry = ReprEntry(                            lines=data["lines"],                            reprfuncargs=reprfuncargs,                            reprlocals=reprlocals,                            filelocrepr=reprfileloc,                            style=data["style"],                        )                    elif entry_type == "ReprEntryNative":                        reprentry = ReprEntryNative(data["lines"])                    else:                        _report_unserialization_failure(entry_type, cls, reportdict)                    unserialized_entries.append(reprentry)                reprtraceback["reprentries"] = unserialized_entries                exception_info = ReprExceptionInfo(                    reprtraceback=ReprTraceback(**reprtraceback),                    reprcrash=ReprFileLocation(**reprcrash),                )                for section in reportdict["longrepr"]["sections"]:                    exception_info.addsection(*section)                reportdict["longrepr"] = exception_info        return cls(**reportdict)        kwargs = _report_kwargs_from_json(reportdict)        return cls(**kwargs)   def _report_unserialization_failure(type_name, report_class, reportdict):


Question: exception serialization should include chained exceptions given some simple tests: when run without xdist it displays whole exception trace nicely : but when run with xdist (), it just displays the last one: my setup:

assert False, "Unknown report_type unserialize data: {}".format(             data["_report_type"]         )<ins>def _report_to_json(report):    """    This was originally the serialize_report() function from xdist (ca03269).    Returns the contents of this report as a dict of builtin entries, suitable for    serialization.    """    def serialize_repr_entry(entry):        entry_data = {"type": type(entry).__name__, "data": entry.__dict__.copy()}        for key, value in entry_data["data"].items():            if hasattr(value, "__dict__"):                entry_data["data"][key] = value.__dict__.copy()        return entry_data    def serialize_repr_traceback(reprtraceback):        result = reprtraceback.__dict__.copy()        result["reprentries"] = [            serialize_repr_entry(x) for x in reprtraceback.reprentries        ]        return result    def serialize_repr_crash(reprcrash):        return reprcrash.__dict__.copy()    def serialize_longrepr(rep):        result = {            "reprcrash": serialize_repr_crash(rep.longrepr.reprcrash),            "reprtraceback": serialize_repr_traceback(rep.longrepr.reprtraceback),            "sections": rep.longrepr.sections,        }        if isinstance(rep.longrepr, ExceptionChainRepr):            result["chain"] = []            for repr_traceback, repr_crash, description in rep.longrepr.chain:                result["chain"].append(                    (                        serialize_repr_traceback(repr_traceback),                        serialize_repr_crash(repr_crash),                        description,                    )                )        else:            result["chain"] = None        return result    d = report.__dict__.copy()    if hasattr(report.longrepr, "toterminal"):        if hasattr(report.longrepr, "reprtraceback") and hasattr(            report.longrepr, "reprcrash"        ):            d["longrepr"] = serialize_longrepr(report)        else:            d["longrepr"] = str(report.longrepr)    else:        d["longrepr"] = report.longrepr    for name in d:        if isinstance(d[name], (py.path.local, Path)):            d[name] = str(d[name])        elif name == "result":            d[name] = None  # for now    return ddef _report_kwargs_from_json(reportdict):    """    This was originally the serialize_report() function from xdist (ca03269).    Returns **kwargs that can be used to construct a TestReport or CollectReport instance.    """    def deserialize_repr_entry(entry_data):        data = entry_data["data"]        entry_type = entry_data["type"]        if entry_type == "ReprEntry":            reprfuncargs = None            reprfileloc = None            reprlocals = None            if data["reprfuncargs"]:                reprfuncargs = ReprFuncArgs(**data["reprfuncargs"])            if data["reprfileloc"]:                reprfileloc = ReprFileLocation(**data["reprfileloc"])            if data["reprlocals"]:                reprlocals = ReprLocals(data["reprlocals"]["lines"])            reprentry = ReprEntry(                lines=data["lines"],                reprfuncargs=reprfuncargs,                reprlocals=reprlocals,                filelocrepr=reprfileloc,                style=data["style"],            )        elif entry_type == "ReprEntryNative":            reprentry = ReprEntryNative(data["lines"])        else:            _report_unserialization_failure(entry_type, TestReport, reportdict)        return reprentry    def deserialize_repr_traceback(repr_traceback_dict):        repr_traceback_dict["reprentries"] = [            deserialize_repr_entry(x) for x in repr_traceback_dict["reprentries"]        ]        return ReprTraceback(**repr_traceback_dict)    def deserialize_repr_crash(repr_crash_dict):        return ReprFileLocation(**repr_crash_dict)    if (        reportdict["longrepr"]        and "reprcrash" in reportdict["longrepr"]        and "reprtraceback" in reportdict["longrepr"]    ):        reprtraceback = deserialize_repr_traceback(            reportdict["longrepr"]["reprtraceback"]        )        reprcrash = deserialize_repr_crash(reportdict["longrepr"]["reprcrash"])        if reportdict["longrepr"]["chain"]:            chain = []            for repr_traceback_data, repr_crash_data, description in reportdict[                "longrepr"            ]["chain"]:                chain.append(                    (                        deserialize_repr_traceback(repr_traceback_data),                        deserialize_repr_crash(repr_crash_data),                        description,                    )                )            exception_info = ExceptionChainRepr(chain)        else:            exception_info = ReprExceptionInfo(reprtraceback, reprcrash)        for section in reportdict["longrepr"]["sections"]:            exception_info.addsection(*section)        reportdict["longrepr"] = exception_info    return reportdict</ins>


Question: Lexer "python3" in --pastebin feature causes HTTP errors The option currently submits the output of to using : For some , this will raise a "HTTP Error 400: Bad Request". As an example: with the attached . This is the underlying cause for the problems mentioned in . The call goes through fine if is changed from to . This would seem like the right thing to do in any case: the console output of a run that is being uploaded is not Python code, but arbitrary text.

from urllib.request import urlopen     from urllib.parse import urlencode     params = {"code": contents, "lexer": "python3", "expiry": "1week"}    params = {"code": contents, "lexer": "text", "expiry": "1week"}     url = "https://bpaste.net"     try:         response = (


Question: Lexer "python3" in --pastebin feature causes HTTP errors The option currently submits the output of to using : For some , this will raise a "HTTP Error 400: Bad Request". As an example: with the attached . This is the underlying cause for the problems mentioned in . The call goes through fine if is changed from to . This would seem like the right thing to do in any case: the console output of a run that is being uploaded is not Python code, but arbitrary text.

from urllib.request import urlopen         from urllib.parse import urlencode     params = {        "code": contents,        "lexer": "python3" if sys.version_info[0] >= 3 else "python",        "expiry": "1week",    }    params = {"code": contents, "lexer": "text", "expiry": "1week"}     url = "https://bpaste.net"     response = urlopen(url, data=urlencode(params).encode("ascii")).read()     m = re.search(r'href="/raw/(\w+)"', response.decode("utf-8"))


Question: 2 ImportError while loading conftest (windows import folder casing issues) 1 works fine. after upgrade to 5.1.2, the path was converted to lower case

from _pytest.compat import importlib_metadata from _pytest.outcomes import fail from _pytest.outcomes import Skipped<del>from _pytest.pathlib import unique_path</del> from _pytest.warning_types import PytestConfigWarning  hookimpl = HookimplMarker("pytest")


Question: 2 ImportError while loading conftest (windows import folder casing issues) 1 works fine. after upgrade to 5.1.2, the path was converted to lower case

"""         current = py.path.local()         self._confcutdir = (            unique_path(current.join(namespace.confcutdir, abs=True))            current.join(namespace.confcutdir, abs=True)             if namespace.confcutdir             else None         )


Question: 2 ImportError while loading conftest (windows import folder casing issues) 1 works fine. after upgrade to 5.1.2, the path was converted to lower case

else:             directory = path         directory = unique_path(directory)         # XXX these days we may rather want to use config.rootdir         # and allow users to opt into looking into the rootdir parent         # directories instead of requiring to specify confcutdir         clist = []        for parent in directory.parts():        for parent in directory.realpath().parts():             if self._confcutdir and self._confcutdir.relto(parent):                 continue             conftestpath = parent.join("conftest.py")


Question: 2 ImportError while loading conftest (windows import folder casing issues) 1 works fine. after upgrade to 5.1.2, the path was converted to lower case

raise KeyError(name)      def _importconftest(self, conftestpath):        # Use realpath to avoid loading the same conftest twice        # Use a resolved Path object as key to avoid loading the same conftest twice         # with build systems that create build directories containing         # symlinks to actual files.        conftestpath = unique_path(conftestpath)        # Using Path().resolve() is better than py.path.realpath because        # it resolves to the correct path/drive in case-insensitive file systems (#5792)        key = Path(str(conftestpath)).resolve()         try:            return self._conftestpath2mod[conftestpath]            return self._conftestpath2mod[key]         except KeyError:             pkgpath = conftestpath.pypkgpath()             if pkgpath is None:


Question: 2 ImportError while loading conftest (windows import folder casing issues) 1 works fine. after upgrade to 5.1.2, the path was converted to lower case

raise ConftestImportFailure(conftestpath, sys.exc_info())              self._conftest_plugins.add(mod)            self._conftestpath2mod[conftestpath] = mod            self._conftestpath2mod[key] = mod             dirpath = conftestpath.dirpath()             if dirpath in self._dirpath2confmods:                 for path, mods in self._dirpath2confmods.items():diff --git a/src/_pytest/pathlib.py b/src/_pytest/pathlib.py-- a/src/_pytest/pathlib.py++ b/src/_pytest/pathlib.py


Question: 2 ImportError while loading conftest (windows import folder casing issues) 1 works fine. after upgrade to 5.1.2, the path was converted to lower case

from os.path import expanduser from os.path import expandvars from os.path import isabs<del>from os.path import normcase</del> from os.path import sep from posixpath import sep as posix_sep


Question: 2 ImportError while loading conftest (windows import folder casing issues) 1 works fine. after upgrade to 5.1.2, the path was converted to lower case

def parts(s):     parts = s.split(sep)     return {sep.join(parts[: i + 1]) or sep for i in range(len(parts))}<del>def unique_path(path):    """Returns a unique path in case-insensitive (but case-preserving) file    systems such as Windows.    This is needed only for ``py.path.local``; ``pathlib.Path`` handles this    natively with ``resolve()``."""    return type(path)(normcase(str(path.realpath())))</del>


Question: Provide an alternative to --result-log After discussion in , mentions he would like to provide a replacement to in the core before removing it (). This potentially is an easy contribution given that we have the plugin already which can be used as a starting point. I would like for us to discuss how that "log file" will look like in this issue. I understand the rationale is to provide a line-based log file, which can be parsed using standard tools. I have used a log file in the past where each line was a JSON object, something like: pytest would then write each line to the file during , like does now. I suppose we also want to add an option to replay the tests in a log file, so users can reproduce a previous run that was saved to a log? you also mentioned that would not be an appropriate replacement, can you elaborate on why?

"assertion",     "junitxml",     "resultlog",    "report_log",     "doctest",     "cacheprovider",     "freeze_support",diff --git a/src/_pytest/hookspec.py b/src/_pytest/hookspec.py-- a/src/_pytest/hookspec.py++ b/src/_pytest/hookspec.py


Question: Provide an alternative to --result-log After discussion in , mentions he would like to provide a replacement to in the core before removing it (). This potentially is an easy contribution given that we have the plugin already which can be used as a starting point. I would like for us to discuss how that "log file" will look like in this issue. I understand the rationale is to provide a line-based log file, which can be parsed using standard tools. I have used a log file in the past where each line was a JSON object, something like: pytest would then write each line to the file during , like does now. I suppose we also want to add an option to replay the tests in a log file, so users can reproduce a previous run that was saved to a log? you also mentioned that would not be an appropriate replacement, can you elaborate on why?

@hookspec(firstresult=True) def pytest_report_to_serializable(config, report):     """<del>    .. warning::        This hook is experimental and subject to change between pytest releases, even        bug fixes.        The intent is for this to be used by plugins maintained by the core-devs, such        as ``pytest-xdist``, ``pytest-subtests``, and as a replacement for the internal        'resultlog' plugin.        In the future it might become part of the public hook API.</del>     Serializes the given report object into a data structure suitable for sending     over the wire, e.g. converted to JSON.     """


Question: Provide an alternative to --result-log After discussion in , mentions he would like to provide a replacement to in the core before removing it (). This potentially is an easy contribution given that we have the plugin already which can be used as a starting point. I would like for us to discuss how that "log file" will look like in this issue. I understand the rationale is to provide a line-based log file, which can be parsed using standard tools. I have used a log file in the past where each line was a JSON object, something like: pytest would then write each line to the file during , like does now. I suppose we also want to add an option to replay the tests in a log file, so users can reproduce a previous run that was saved to a log? you also mentioned that would not be an appropriate replacement, can you elaborate on why?

@hookspec(firstresult=True) def pytest_report_from_serializable(config, data):     """    .. warning::        This hook is experimental and subject to change between pytest releases, even        bug fixes.        The intent is for this to be used by plugins maintained by the core-devs, such        as ``pytest-xdist``, ``pytest-subtests``, and as a replacement for the internal        'resultlog' plugin.        In the future it might become part of the public hook API.     Restores a report object previously serialized with pytest_report_to_serializable().     """ diff --git a/src/_pytest/report_log.py b/src/_pytest/report_log.pynew file mode 100644-- /dev/null++ b/src/_pytest/report_log.py


Question: Provide an alternative to --result-log After discussion in , mentions he would like to provide a replacement to in the core before removing it (). This potentially is an easy contribution given that we have the plugin already which can be used as a starting point. I would like for us to discuss how that "log file" will look like in this issue. I understand the rationale is to provide a line-based log file, which can be parsed using standard tools. I have used a log file in the past where each line was a JSON object, something like: pytest would then write each line to the file during , like does now. I suppose we also want to add an option to replay the tests in a log file, so users can reproduce a previous run that was saved to a log? you also mentioned that would not be an appropriate replacement, can you elaborate on why?

import jsonfrom pathlib import Pathimport pytestdef pytest_addoption(parser):    group = parser.getgroup("terminal reporting", "report-log plugin options")    group.addoption(        "--report-log",        action="store",        metavar="path",        default=None,        help="Path to line-based json objects of test session events.",    )def pytest_configure(config):    report_log = config.option.report_log    if report_log and not hasattr(config, "slaveinput"):        config._report_log_plugin = ReportLogPlugin(config, Path(report_log))        config.pluginmanager.register(config._report_log_plugin)def pytest_unconfigure(config):    report_log_plugin = getattr(config, "_report_log_plugin", None)    if report_log_plugin:        report_log_plugin.close()        del config._report_log_pluginclass ReportLogPlugin:    def __init__(self, config, log_path: Path):        self._config = config        self._log_path = log_path        log_path.parent.mkdir(parents=True, exist_ok=True)        self._file = log_path.open("w", buffering=1, encoding="UTF-8")    def close(self):        if self._file is not None:            self._file.close()            self._file = None    def _write_json_data(self, data):        self._file.write(json.dumps(data) + "\n")        self._file.flush()    def pytest_sessionstart(self):        data = {"pytest_version": pytest.__version__, "$report_type": "SessionStart"}        self._write_json_data(data)    def pytest_sessionfinish(self, exitstatus):        data = {"exitstatus": exitstatus, "$report_type": "SessionFinish"}        self._write_json_data(data)    def pytest_runtest_logreport(self, report):        data = self._config.hook.pytest_report_to_serializable(            config=self._config, report=report        )        self._write_json_data(data)    def pytest_collectreport(self, report):        data = self._config.hook.pytest_report_to_serializable(            config=self._config, report=report        )        self._write_json_data(data)    def pytest_terminal_summary(self, terminalreporter):        terminalreporter.write_sep(            "-", "generated report log file: {}".format(self._log_path)        )diff --git a/src/_pytest/reports.py b/src/_pytest/reports.py-- a/src/_pytest/reports.py++ b/src/_pytest/reports.py


Question: Provide an alternative to --result-log After discussion in , mentions he would like to provide a replacement to in the core before removing it (). This potentially is an easy contribution given that we have the plugin already which can be used as a starting point. I would like for us to discuss how that "log file" will look like in this issue. I understand the rationale is to provide a line-based log file, which can be parsed using standard tools. I have used a log file in the past where each line was a JSON object, something like: pytest would then write each line to the file during , like does now. I suppose we also want to add an option to replay the tests in a log file, so users can reproduce a previous run that was saved to a log? you also mentioned that would not be an appropriate replacement, can you elaborate on why?

def pytest_report_to_serializable(report):     if isinstance(report, (TestReport, CollectReport)):         data = report._to_json()        data["_report_type"] = report.__class__.__name__        data["$report_type"] = report.__class__.__name__         return data   def pytest_report_from_serializable(data):    if "_report_type" in data:        if data["_report_type"] == "TestReport":    if "$report_type" in data:        if data["$report_type"] == "TestReport":             return TestReport._from_json(data)        elif data["_report_type"] == "CollectReport":        elif data["$report_type"] == "CollectReport":             return CollectReport._from_json(data)         assert False, "Unknown report_type unserialize data: {}".format(            data["_report_type"]            data["$report_type"]         )


Question: pytest --collect-only needs a one char shortcut command I find myself needing to run very often and that cli argument is a very long to type one. I do think that it would be great to allocate a character for it, not sure which one yet. Please use up/down thumbs to vote if you would find it useful or not and eventually proposing which char should be used. Clearly this is a change very easy to implement but first I want to see if others would find it useful or not. pytest --collect-only needs a one char shortcut command I find myself needing to run very often and that cli argument is a very long to type one. I do think that it would be great to allocate a character for it, not sure which one yet. Please use up/down thumbs to vote if you would find it useful or not and eventually proposing which char should be used. Clearly this is a change very easy to implement but first I want to see if others would find it useful or not.

group.addoption(         "--collectonly",         "--collect-only",<ins>        "--co",</ins>         action="store_true",         help="only collect tests, don't execute them.",     ),


Question: Show deprecation warning if junitfamily is not set Show a deprecation warning if the user has not configured ()

"Passing arguments to pytest.fixture() as positional arguments is deprecated - pass them "     "as a keyword argument instead." )JUNIT_XML_DEFAULT_FAMILY = PytestDeprecationWarning(    "The 'junit_family' default value will change to 'xunit2' in pytest 6.0.\n"    "Add 'junit_family=legacy' to your pytest.ini file to silence this warning and make your suite compatible.")diff --git a/src/_pytest/junitxml.py b/src/_pytest/junitxml.py-- a/src/_pytest/junitxml.py++ b/src/_pytest/junitxml.py


Question: Show deprecation warning if junitfamily is not set Show a deprecation warning if the user has not configured ()

import py  import pytestfrom _pytest import deprecated from _pytest import nodes from _pytest.config import filename_argfrom _pytest.warnings import _issue_warning_captured   class Junit(py.xml.Namespace):