diff --git a/py/private/py_venv/py_venv.bzl b/py/private/py_venv/py_venv.bzl index 91ca506c..616b86ee 100644 --- a/py/private/py_venv/py_venv.bzl +++ b/py/private/py_venv/py_venv.bzl @@ -80,14 +80,6 @@ def _py_venv_base_impl(ctx): "BAZEL_TARGET_NAME": ctx.attr.name, } - passed_env = dict(ctx.attr.env) - for k, v in passed_env.items(): - passed_env[k] = expand_variables( - ctx, - expand_locations(ctx, v, ctx.attr.data), - attribute_name = "env", - ) - ctx.actions.write( output = env_file, content = "\n".join(_dict_to_exports(default_env)).strip(), @@ -235,6 +227,14 @@ def _py_venv_binary_impl(ctx): is_executable = True, ) + passed_env = dict(ctx.attr.env) + for k, v in passed_env.items(): + passed_env[k] = expand_variables( + ctx, + expand_locations(ctx, v, ctx.attr.data), + attribute_name = "env", + ) + return [ DefaultInfo( files = depset([ @@ -243,6 +243,10 @@ def _py_venv_binary_impl(ctx): executable = ctx.outputs.executable, runfiles = rfs, ), + RunEnvironmentInfo( + environment = passed_env, + inherited_environment = getattr(ctx.attr, "env_inherit", []), + ), ] _attrs = dict({ @@ -311,7 +315,6 @@ _binary_attrs = dict({ }) _test_attrs = dict({ - # FIXME: Where does this come from, do we need to keep it? "env_inherit": attr.string_list( doc = "Specifies additional environment variables to inherit from the external environment when the test is executed by bazel test.", default = [], diff --git a/py/tests/py-internal-venv/BUILD.bazel b/py/tests/py-internal-venv/BUILD.bazel index f6716781..2834e4b4 100644 --- a/py/tests/py-internal-venv/BUILD.bazel +++ b/py/tests/py-internal-venv/BUILD.bazel @@ -13,3 +13,16 @@ py_venv_test( "@pypi_cowsay//:pkg", ], ) + +py_venv_test( + name = "test_env_vars", + srcs = ["test_env_vars.py"], + env = { + "ONE": "un", + "TWO": "deux", + "RULEDIR": "$(RULEDIR)", + "LOCATION": "$(location :test_env_vars.py)", + "DEFINE": "$(SOME_VAR)", + }, + main = "test_env_vars.py", +) diff --git a/py/tests/py-internal-venv/test_env_vars.py b/py/tests/py-internal-venv/test_env_vars.py new file mode 100644 index 00000000..0d95a7f6 --- /dev/null +++ b/py/tests/py-internal-venv/test_env_vars.py @@ -0,0 +1,17 @@ +import os + + +def test_env(env, expected): + assert env in os.environ, f"Expected environ to have key '{env}'" + + _actual = os.environ.get(env) + assert _actual == expected, f"Expected environ key '{env}' to equal '{expected}', but got '{_actual}'" + + +test_env('ONE', 'un') +test_env('TWO', 'deux') +test_env('LOCATION', "py/tests/py-internal-venv/test_env_vars.py") +test_env('DEFINE', "SOME_VALUE") +test_env('BAZEL_TARGET', "//py/tests/py-internal-venv:test_env_vars") +test_env('BAZEL_WORKSPACE', "aspect_rules_py") +test_env('BAZEL_TARGET_NAME', "test_env_vars")