From a756621118e4494525e8ee95aa21a33e253a7317 Mon Sep 17 00:00:00 2001 From: DimitrisJim Date: Tue, 26 Sep 2023 13:55:16 +0300 Subject: [PATCH] Disallow env vars not being set, clean up minor issues. --- scripts/go-test-all.py | 43 ++++++++++++++++++++++++++++-------------- 1 file changed, 29 insertions(+), 14 deletions(-) diff --git a/scripts/go-test-all.py b/scripts/go-test-all.py index 1c2baadea1a..2ce44e7f455 100755 --- a/scripts/go-test-all.py +++ b/scripts/go-test-all.py @@ -1,15 +1,23 @@ #!/usr/bin/env python3 +""" +The purpose of this script is to run unit tests for all go modules in the current +directory. It works by recursively searching for all go.mod files in the directory and +subdirectories and then running `go test` on each of them. +It is not intended to be run directly, but rather to be called by the Makefile. +""" import os import subprocess -# Get the environment variables given to us by the Makefile -ARGS = os.environ.get('ARGS', '') -EXTRA_ARGS = os.environ.get('EXTRA_ARGS', '') -TEST_PACKAGES = os.environ.get('TEST_PACKAGES', '') -CURRENT_DIR = os.getcwd() +def require_env_var(name): + """ Require an environment variable to be set. """ + value = os.environ.get(name, None) + if value is None: + print(f"Error: {name} environment variable is not set") + exit(1) + return value -def find_go_modules(directory='.'): +def find_go_modules(directory): """ Find all go.mod files in the current directory and subdirectories. """ go_mod_files = [] for root, _, files in os.walk(directory): @@ -17,19 +25,19 @@ def find_go_modules(directory='.'): go_mod_files.append(root) return go_mod_files -def run_tests_for_module(module): +def run_tests_for_module(module, *runargs): """ Run the unit tests for the given module. """ - path = os.path.join(CURRENT_DIR, module) - os.chdir(path) + os.chdir(module) - print(f"Running unit tests for {path}") + print(f"Running unit tests for {module}") - test_command = f'go test -mod=readonly {ARGS} {EXTRA_ARGS} {TEST_PACKAGES} ./...' + # add runargs to test_command + test_command = f'go test -mod=readonly {" ".join(runargs)} ./...' result = subprocess.run(test_command, shell=True) return result.returncode -def run_tests(directory): +def run_tests(directory, *runargs): """ Run the unit tests for all modules in dir. """ print("Starting unit tests") @@ -38,8 +46,15 @@ def run_tests(directory): exit_code = 0 for gomod in sorted(go_modules): - exit_code = run_tests_for_module(gomod) + res = run_tests_for_module(gomod, *runargs) + if res != 0: + exit_code = res exit(exit_code) if __name__ == '__main__': - run_tests(os.getcwd()) + # Get the environment variables given to us by the Makefile + ARGS = require_env_var('ARGS') + EXTRA_ARGS = require_env_var('EXTRA_ARGS') + TEST_PACKAGES = require_env_var('TEST_PACKAGES') + + run_tests(os.getcwd(), ARGS, EXTRA_ARGS, TEST_PACKAGES)