Search code examples
pytesttype-hinting

Why does pytest.main returns an int or an exit code


pytest.main is supposedly returning an integer or an ExitCode according to the type-hinting of its source code. I don't understand in what situation would an integer be returned. I only get Exitcodes (ExitCode.OK, etc.). enter image description here


Solution

  • If we take a look at Pytest's source code, we can see that the integers come from this line:

    ret: Union[ExitCode, int] = config.hook.pytest_cmdline_main(config=config)
    

    This is the return code from Pytest plugins: Pytest will try running that hook for all the loaded plugins and return the first non-None result. You can see an example in the help/version hook.

    I'm guessing that an integer was the expected type for this hook in the earliest versions of Pytest, since the ExitCode class dates from Pytest 5. Integers also allow Pytest plugins to return various exit codes without being constrained by Pytest's own ExitCode.

    You can read more on Pytest plugins and the Pytest hook reference.