Hi, general question about `pants`/`pex`. Is there...
# general
b
Hi, general question about `pants`/`pex`. Is there an easy way of building a pex_binary containing tests (written using pytest) that executes the tests when the binary is run. The plan is to use this binary to run integration tests on different environments during CI. My solution so far is to add a small
main.py
shim to call
pytest.main()
on the tests within the pex. Thank you very much in advance for any guidance on this topic!
e
Lots of devils and details depending on your use of pytest, but, for example:
Copy code
jsirois@Gill-Windows:/tmp/JakeStacey $ cat src/foo.py
SPAM = 42

jsirois@Gill-Windows:/tmp/JakeStacey $ cat tests/foo_test.py
import foo


def test_foo() -> None:
    assert 42 == foo.SPAM

jsirois@Gill-Windows:/tmp/JakeStacey $ pex -D src/ -D tests/ pytest -c pytest --inject-args="--pyargs foo_test -vvs" -o self_contained_test_machine.pex
jsirois@Gill-Windows:/tmp/JakeStacey $ ./self_contained_test_machine.pex
============================================================================================== test session starts ===============================================================================================
platform linux -- Python 3.10.6, pytest-7.2.0, pluggy-1.0.0 -- /usr/bin/python3.10
cachedir: .pytest_cache
rootdir: /tmp/JakeStacey
collected 1 item

::test_foo <- ../../home/jsirois/.pex/unzipped_pexes/6a2eed1970bba27bb436991fbe4e7c742865da9e/foo_test.py PASSED

=============================================================================================== 1 passed in 0.00s ================================================================================================
There the key bits are: 1. Your sources and tests are added with -D 2. The executable is pytest (
pytest -c pytest
is the pytest requirement with no specifier and then the
pytest
console script entrypoint). 3. We seal in some command line args to pass to pytest, namely
--pyargs ...
which has pytest discover tests not by file or directory but by package / module name.
b
Great, thank you - I’ll give it a try
Awesome, works for me too! Thank you very much for looking at this. Do you know if there is a way to make this work within pants? I couldn’t find any reference to
--inject-args
on the
pex_binary
target.
e
Only on main https://github.com/pantsbuild/pants/pull/17905 The 1st release containing that will be 2.16.0.dev5 - hopefully later today. This weeks release work has been rocky.
b
Perfect, thank you