Skip to content

Calling pytest.main() without arguments unpredictably reads arguments from the command line #11183

@antosikv

Description

@antosikv

In my opinion, it would be quite reasonable to assume that running

pytest.main()

would be equivalent to simply executing pytest from the command line with no arguments. The documentation even seems to suggest that this should be the case:

You can invoke pytest from Python code directly:

retcode = pytest.main()

this acts as if you would call “pytest” from the command line.

Instead, the default value of args passed into the function is None, in which case we end up reading arguments from the command line. That seems to be a fairly weird choice for the "default" behavior, since we are now trying to use arguments passed to a completely different program. At best, this can easily lead to complaints about unrecognized options and at worst, if we happen to share some options with the calling script, possible misinterpretation of those options and subsequent unexpected behavior.

It seems to me that automatically reading arguments directly from the command line would only be reasonable and expected when pytest is executed directly from the command line. When called programmatically from a script, it would probably be more predictable to just assume having no arguments unless explicitly specified otherwise.

This would obviously introduce a breaking change for those relying on main() silently reading arguments from the command line but that frankly does not seem like a good practice anyway. And considering that it would be a trivial single-line change of using main(sys.argv[1:]) instead, it definitely seems like a good idea to be explicit about it.

Anyway, if introducing a breaking change would be unacceptable, despite the arguably more predictable default behavior, it would probably be a good idea to at least amend the documentation and add an explicit warning about this behavior.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions