diff --git a/setup.py b/setup.py index 2c02906b0..eee9136f2 100644 --- a/setup.py +++ b/setup.py @@ -20,6 +20,16 @@ find_pkgs_spec.loader.exec_module(find_pkgs) +def render_default_envs(environ): + """Render build-time environment defaults as valid Python source.""" + code = '# Pre-installed environment variables\n' + code += 'persistent_envs = dict()\n' + for name in persistent_env_names: + if name in environ: + code += f'persistent_envs[{name!r}] = {environ[name]!r}\n' + return code + + def get_package_version(): with open(Path(current_dir) / 'deep_ep' / '__init__.py', 'r') as f: version_match = re.search(r'^__version__\s*=\s*(.*)$', f.read(), re.MULTILINE) @@ -61,16 +71,12 @@ def prepare_agent_files(self): shutil.copytree(os.path.join(current_dir, name), dst, ignore=ignore) def generate_default_envs(self): - code = '# Pre-installed environment variables\n' - code += 'persistent_envs = dict()\n' - # noinspection PyShadowingNames - for name in persistent_env_names: - code += f"persistent_envs['{name}'] = '{os.environ[name]}'\n" if name in os.environ else '' + code = render_default_envs(os.environ) # Create temporary build directory build_include_dir = os.path.join(self.build_lib, 'deep_ep') os.makedirs(build_include_dir, exist_ok=True) - with open(os.path.join(self.build_lib, 'deep_ep', 'envs.py'), 'w') as f: + with open(os.path.join(build_include_dir, 'envs.py'), 'w') as f: f.write(code) diff --git a/tests/utils/test_setup_helpers.py b/tests/utils/test_setup_helpers.py new file mode 100644 index 000000000..9885ad0c0 --- /dev/null +++ b/tests/utils/test_setup_helpers.py @@ -0,0 +1,38 @@ +import importlib.util +import unittest +from pathlib import Path + + +def load_setup_module(): + path = Path(__file__).parents[2] / 'setup.py' + spec = importlib.util.spec_from_file_location('deep_ep_setup_under_test', path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +class PersistentEnvironmentTests(unittest.TestCase): + def test_values_round_trip_through_generated_python(self): + setup = load_setup_module() + expected = { + 'EP_JIT_CACHE_DIR': "/tmp/o'neil\\jit-cache", + 'EP_NCCL_ROOT_DIR': '/opt/NCCL dir', + } + + source = setup.render_default_envs(expected) + namespace = {} + exec(compile(source, 'envs.py', 'exec'), namespace) + + self.assertEqual(namespace['persistent_envs'], expected) + + def test_ignores_unrelated_environment_values(self): + setup = load_setup_module() + source = setup.render_default_envs({'UNRELATED': 'value'}) + namespace = {} + exec(compile(source, 'envs.py', 'exec'), namespace) + + self.assertEqual(namespace['persistent_envs'], {}) + + +if __name__ == '__main__': + unittest.main()