1# Copyright 2022 The Bazel Authors. All rights reserved. 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# http://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14 15import os 16import subprocess 17import unittest 18 19 20class TestPythonVersion(unittest.TestCase): 21 @classmethod 22 def setUpClass(cls): 23 os.chdir("%test_location%") 24 rules_python_path = os.path.join(os.environ["TEST_SRCDIR"], "rules_python") 25 26 test_tmpdir = os.environ["TEST_TMPDIR"] 27 if %is_windows%: 28 home = os.path.join(test_tmpdir, "HOME") 29 os.mkdir(home) 30 os.environ["HOME"] = home 31 32 local_app_data = os.path.join(test_tmpdir, "LocalAppData") 33 os.mkdir(local_app_data) 34 os.environ["LocalAppData"] = local_app_data 35 36 # Bazelisk requires a cache directory be set 37 os.environ["XDG_CACHE_HOME"] = os.path.join(test_tmpdir, "xdg-cache-home") 38 39 # Unset this so this works when called by Bazel's latest Bazel build 40 # pipeline. It sets the following combination, which interfere with each other: 41 # * --sandbox_tmpfs_path=/tmp 42 # * --test_env=USE_BAZEL_VERSION 43 # * USE_BAZEL_VERSION=/tmp/<something> 44 os.environ.pop("USE_BAZEL_VERSION", None) 45 46 with open(".bazelrc", "w") as bazelrc: 47 bazelrc.write( 48 os.linesep.join( 49 [ 50 'build --override_repository rules_python="{}"'.format( 51 rules_python_path.replace("\\", "/") 52 ), 53 "build --test_output=errors", 54 ] 55 ) 56 ) 57 58 def test_match_toolchain(self): 59 output = subprocess.check_output( 60 f"bazel run @python//:python3 -- --version", 61 shell = True, # Shell needed to look up via PATH 62 text=True, 63 ).strip() 64 self.assertEqual(output, "Python %python_version%") 65 66 subprocess.run("bazel test //...", shell=True, check=True) 67 68 69if __name__ == "__main__": 70 unittest.main() 71