Reputation: 1800
My bazel py_test rule seems to be able to import files in the same folder for which there was no dependency declared. Is there a way to prevent this? I am running bazel 3.7.2 on linux. Here is an example:
# Note that foo_test doesn't declare :foo as a dependency
$ cat BUILD
py_library(
name = "foo",
srcs = ["foo.py"],
)
py_test(
name = "foo_test",
srcs = ["foo_test.py"],
)
$ cat foo.py
def foo():
print("hello")
# However, I can still import and use the library
$ cat foo_test.py
import foo
foo.foo()
$ bazel-3.7.2-linux-x86_64 test :foo_test
<snip>
//:foo_test PASSED in 0.3s
Is there a configuration option that would prevent the foo_test
rule from implicitly picking up foo.py
?
Upvotes: 1
Views: 1507
Reputation: 1940
This is a know issue with rules_python, with a prior solution that is, unfortunately, currently broken.
A simple workaround is to just repeat the fix from the python_stub, i.e. make the file content
import sys
sys.path.pop(0)
import foo
foo.foo()
and then bazel test //:foo_test --test_output=all
will fail with ModuleNotFoundError: No module named 'foo'
as expected, until you add :foo
as dep in the BUILD.
Another workaround is to move your test file to a tests/
subdir so that the script dir (that the Python interpreter will always add to the sys.path) will not contain any (spurious) dependencies.
Upvotes: 2