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.).
Asked
Active
Viewed 167 times
1

FluidMechanics Potential Flows
- 594
- 10
- 23
1 Answers
1
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.

duthils
- 1,181
- 3
- 7
-
I'm not sure I understand the notion of `hook`? – FluidMechanics Potential Flows Sep 11 '22 at 12:16
-
1Basically, it's an extension point of Pytest, that allows Pytest plugins to add behavior when some event occurs, in this case, when Pytest is invoked. See also [this SO question](https://stackoverflow.com/questions/467557/what-is-meant-by-the-term-hook-in-programming). – duthils Sep 11 '22 at 15:45
-
Thank you. And the example you mentioned is one of the many hooks that could be run when Pytest is invoked? – FluidMechanics Potential Flows Sep 11 '22 at 16:22
-
1Exactly. However, `pytest_cmdline_main` is the only hook that can directly influence the return code of Pytest. Other hooks are triggered by other events, such as ["CTRL-C" was pressed](https://docs.pytest.org/en/7.1.x/reference/reference.html#pytest.hookspec.pytest_keyboard_interrupt) or [a warning was encountered](https://docs.pytest.org/en/7.1.x/reference/reference.html#pytest.hookspec.pytest_warning_recorded) – duthils Sep 13 '22 at 01:10
-
So when creating pytest plugins, people can change the behaviour by changing what pytest_cmdline_main does basically? Just making sure I got it right. – FluidMechanics Potential Flows Sep 13 '22 at 08:57
-
1That's right: a plugin that implements its own `pytest_cmdline_main` can, among other things, add new flags or commands in Pytest and return arbitrary exit codes. I'm no expert, but that is what I understood from the code. – duthils Sep 14 '22 at 00:08