Skip to content

pytest support #240

Closed
Closed

Description

@verhovsky

py_test is a Bazel rule and pytest is a Python library for writing and running tests

https://docs.pytest.org
https://github.com/pytest-dev/pytest

I've found two third-party Bazel rules for running tests written with pytest bazel_rules_pex and rules_pyz, but both projects are unmaintaned and don't work anymore. Edit 2020-01-15: see https://github.com/ali5h/rules_pip/blob/b4e94d0ddc95367217b7059bcdb926c159d28602/defs.bzl#L139 as well.

pytest has been mentioned a few times on the bazel mailing list https://groups.google.com/forum/?nomobile=true#!searchin/bazel-discuss/pytest%7Csort:date

I'm not sure what the correct way to add support for it would be. Probably another rule but I don't know what it should be called, because the names are so similar. pytest pytest_py_test py_test_pytest all seem pretty funny. Or maybe it could be an option for py_test or a global one in WORKSPACE.

pytest can run tests written with unittest (and has nicer output when a test fails), so theoretically you could just change the py_test rule to run tests with pytest but that's obviously not happening.

Activity

  1. groodt commented on Oct 10, 2019

    @groodt
    Contributor

    It is already possible to use pytest with py_test.

    py_test(
        name = "unit_test",
        srcs = ["test.py"],
        main = "test.py",
        python_version = "PY3",
        srcs_version = "PY3",
        deps = TEST_DEPS,
    )
    

    test.py

    import sys
    
    import pytest
    
    
    def test_aws_login_without_aws_profile():
        assert True
    
    
    if __name__ == "__main__":
        sys.exit(pytest.main([__file__]))
    
  2. verhovsky commented on Oct 11, 2019

    @verhovsky
    Author

    Thanks for the quick reply. I saw someone mention this trick on the mailing list https://groups.google.com/forum/?nomobile=true#!searchin/bazel-discuss/pytest|sort:date/bazel-discuss/d1RKUmyve_Q/hm_Dc3XYCAAJ

    If you forget the sys.exit like the person in that mailing list post, Bazel will never know if the tests in that file fail. It would also just be nice if you didn't need 3-4 cryptic lines of boiler plate for every test file.

  3. pstradomski commented on Oct 11, 2019

    @pstradomski
    Contributor

    @brandjon: it's something I have in my fork of rules_python, using a genrule to create a snippet similar to the one in @groodt comment above.

    Do you think it makes sense to add it to experimental/ ?

  4. ali5h commented on Oct 20, 2019

    @ali5h
  5. pstradomski commented on Oct 21, 2019

    @pstradomski
    Contributor

    i added a sample macro for pytest here https://github.com/ali5h/rules_pip/blob/master/defs.bzl#L116

    PTAL at pull request #243. It takes a slightly different approach. In particular, it does not pull dependency on pytest on its own, to give users more freedom (e.g. whether to use requirements.txt, virtualenv or vendor pytest in repository).

  6. ali5h commented on Oct 21, 2019

    @ali5h

    i added that as a sample. there is no need to load the pytest explicitly, updated the sample to show this

  7. dayfine commented on Mar 11, 2020

    @dayfine

    Suppose defining your own BUILD rule is the right solution: semantically it would belong to /contrib (though there isn't one), instead of /experimental, which is more for things that might become official in the future.

    This issue specifically is a pytest 'problem', in the sense that the framework that does 'a lot' (and maybe too much in a sense). From the viewpoint of the build system, py_test rule would not make any assumption about the existence of pytest or another custom testing framework.

    Personally I think having a 10-line main file as @ali5h did is most straightforward and I probably won't even create any custom BUILD rule:

    py_test(
      name = 'my_target',
      srcs = [
        ...
        "//path/to:pytest_main",
      ] ,
      main = "//path/to:pytest_main",
      ...
    )
    
  8. doubler commented on Jun 4, 2020

    @doubler

    If the test.py has relative import code like from .module import xx, then bazel test would fail.
    ModuleNotFoundError: No module named '__main__.module'; '__main__' is not a package

  9. thundergolfer commented on Jun 4, 2020

    @thundergolfer

    We don't use relative imports anywhere in our Bazel workspace. They're not worth the trouble imo, and I wouldn't be surprised at all if implementation details in Python rules made them not work correctly.

  10. doubler commented on Jun 8, 2020

    @doubler
  11. thundergolfer commented on Jun 15, 2020

    @thundergolfer

    @doubler We used to use that imports attr but I think it's a code-smell. For our use cases we've been able to move to absolute imports and remove all use of imports = [] in our BUILD files.

  12. jxramos commented on Jul 30, 2020

    @jxramos

    @dayfine makes a solid point, py_test strictly operates off return codes and the absence of segfaults or something like that taking place during test execution. That the phonetics are identical to pytest makes the concepts crowd into each other somewhat unavoidably but they are very distinct.

    There's also the more generalized approach from what @groodt shares above, that includes the passing of arguments from bazel py_test targets into pytest via the args attribute. I've used that with great success rendering additional debug detail on failures and even to factor out deep dependency graph test cases lumped into a parametrized pytest case such that each parameter value becomes its own py_test target in the BUILD file via a list comp. Where pytest would normally iterate over all test cases (even those that aren't implicated in the the current diff to the repo) bazel is more nimble to only run those test parameters that are implicated by a particular change. That saves a great deal of test execution runtime by leaning on the remote cache for test results.

    BUILD

    py_test(
        name = "test_foo",
        srcs = [
            "test_foo.py",
        ],
        args = [
            "--junit-xml=test_foo_results.xml",
        ],
        deps = [
            "pytest",
        ],
    )

    test_foo.py

    import pytest
    import sys
    ...
    
    if __name__ == "__main__":
        # if using 'bazel test ...'
        args = sys.argv[1:]
        ret_code = pytest.main([__file__, "--verbose"] + args)
    
        # Print relevant debug logs or other artifacts for CI job to have richer context
        if ret_code != 0:
            print_debug_stuff(args)
    
        # Exit with return code
        sys.exit(ret_code)
  13. jxramos commented on Nov 24, 2020

    @jxramos

    Actually now we're hitting the case that @double mentioned above...

    If the test.py has relative import code like from .module import xx, then bazel test would fail.
    ModuleNotFoundError: No module named '__main__.module'; '__main__' is not a package

    The use case hoping to have supported for us is to be able to execute test runs from either the bazel process as well as the pytest process. Being able to run from pytest is a convenience for development with respect to debugging and site-packages package development work. It can also be achieved through bazel but one has to do all the folder path hunting and PYTHONPATH setup around the bazel cache I believe.

    With pytest I can drop pdb breakpoints, but from bazel something forces the debug session to quit

    import pdb
    pdb.set_trace()
    (Pdb) 
    Traceback (most recent call last):
      File ...
      File "/usr/lib/python3.6/bdb.py", line 51, in trace_dispatch
        return self.dispatch_line(frame)
      File "/usr/lib/python3.6/bdb.py", line 70, in dispatch_line
        if self.quitting: raise BdbQuit
    bdb.BdbQuit
    
  14. thundergolfer commented on Mar 30, 2021

    @thundergolfer

    @jxramos RE the "forces the debug session to quit" I've copied below a workaround:

    ... Unfortunately, this does not work so simply for bazel test and py_test targets. If you add a breakpoint using pdb and run a test that will trigger that breakpoint, you won't be dropped into a REPL the process will crash. As a workaround, change your py_test target to py_binary and do bazel run on it instead of bazel test. Your test code will run and you’ll be dropped into the pdb debugger:

  15. pstradomski commented on Apr 1, 2021

    @pstradomski
    Contributor
  16. 9 remaining items

  17. github-actions commented on Jul 17, 2022

    @github-actions
    Contributor

    This issue has been automatically marked as stale because it has not had any activity for 180 days. It will be closed if no further activity occurs in 30 days.
    Collaborators can add an assignee to keep this open indefinitely. Thanks for your contributions to rules_python!

  18. verhovsky commented on Jul 18, 2022

    @verhovsky
    Author

    *activities*

  19. betaboon commented on Aug 9, 2022

    @betaboon
    Contributor
  20. github-actions commented on Feb 5, 2023

    @github-actions
    Contributor

    This issue has been automatically marked as stale because it has not had any activity for 180 days. It will be closed if no further activity occurs in 30 days.
    Collaborators can add an assignee to keep this open indefinitely. Thanks for your contributions to rules_python!

  21. arrdem commented on Feb 6, 2023

    @arrdem
    Contributor
  22. removed
    Can Close?Will close in 30 days if there is no new activity
    on Feb 6, 2023
  23. chrislovecnm commented on Jul 11, 2023

    @chrislovecnm
    Contributor

    Closing. @arrdem if you want to do a PR with the support I would love to take a look at it.

  24. arrdem commented on Jul 11, 2023

    @arrdem
    Contributor

    https://github.com/caseyduquettesc/rules_python_pytest this came up in the slack yesterday, leaving it here for posterity. I note with some amusement it's almost line-for-line what I invented for my repo and what we're now using at Abnormal.

    I think this comment https://github.com/caseyduquettesc/rules_python_pytest/blob/main/python_pytest/defs.bzl#L34 captures why having "in the box" support would be hard.

    Maybe you could do the same dance as aignas@6b54226, but sideloading in requirements alongside user code with potential for requirements conflicts seems like trouble. It'd be better to find a way to configure the Python toolchain with a requirement function/macro but dunno if we can do that.

  25. alexeagle commented on Jul 31, 2023

    @alexeagle
    Contributor

    Another 3p pointer: https://docs.aspect.build/rules/aspect_rules_py/docs/rules#py_pytest_main provides missing glue for pytest, thanks to @mattem and @f0rmiga

  26. unpinned this issue on Aug 1, 2023
  27. aignas commented on Sep 27, 2024

    @aignas
    Collaborator

    Another project that provides pytest integration is here:
    https://github.com/aignas/pytest-bazel

    See the doc links in the repo for usage.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions