1

I am trying to use Bazel for my new project, and for some reason I can only get bazel 0.26.1. However, when I am trying to write a test case using py_test, it seems that bazel is always using Python 2 to test my program. Is there any way to prevent this behavior?

To reproduce:

file test_a.py:

# Works on Python 3
# SyntaxError on Python 2
print(print('Good'))

file WORKSPACE:

load("@bazel_tools//tools/build_defs/repo:git.bzl", "git_repository")

git_repository(
    name = "rules_python",
    commit = "54d1cb35cd54318d59bf38e52df3e628c07d4bbc",
    remote = "https://github.com/bazelbuild/rules_python.git",
)

file BUILD:

load("@rules_python//python:defs.bzl", "py_test")

py_test(
    name = "test_a",
    size = "small",
    srcs = ["test_a.py"],
    deps = [],
)

My shell looks like (... is a path in ~/.cache/)

$ bazel version | head -n 1
Build label: 0.26.1
$ bazel test test_a
//:test_a                           FAILED in 0.1s
  .../test.log

INFO: Build completed, 1 test FAILED, 2 total actions
$ cat .../test.log
exec ${PAGER:-/usr/bin/less} "$0" || exit 1
Executing tests from //:test_a
-----------------------------------------------------------------------------
  File ".../test_a.py", line 1
    print(print('Good'))
              ^
SyntaxError: invalid syntax
$ 
Eric Stdlib
  • 1,292
  • 1
  • 18
  • 32

1 Answers1

0

According to a note in the documentation of the python_version flag for py_test there is a bug (#4815) where the script may still invoke the wrong interpreter version at runtime.

The suggested workaround is to define a py_runtime rule using select() and point to that py_runtime with the --python_top flag (see issue for more details):

py_runtime(
    name = "myruntime",
    interpreter_path = select({
        # Update paths as appropriate for your system.
        "@bazel_tools//tools/python:PY2": "/usr/bin/python2",
        "@bazel_tools//tools/python:PY3": "/usr/bin/python3",
    }),
    files = [],
)
> bazel test :test_a --python_top=//path/to:myruntime.

The issue appears to have been fixed in 0.27.0

dms
  • 1,260
  • 7
  • 12