Skip to content

Commit

Permalink
@include: Only include modules from the current package (#1485)
Browse files Browse the repository at this point in the history
Change method to load module from source files to make sure it never loads code from other packages. Fixes #1483

Signed-off-by: SitiSchu <admin@sitischu.com>
Signed-off-by: Jean-Christophe Morin <jean_christophe_morin@hotmail.com>
Co-authored-by: Jean-Christophe Morin <jean_christophe_morin@hotmail.com>
  • Loading branch information
SitiSchu and JeanChristopheMorinPerso authored Sep 9, 2023
1 parent 1fd1c58 commit c4cdc7e
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 3 deletions.
34 changes: 34 additions & 0 deletions src/rez/tests/test_utils_py23.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# SPDX-License-Identifier: Apache-2.0
# Copyright Contributors to the Rez Project


"""
unit tests for 'utils.py23' module
"""
import os
import sys
import tempfile

from rez.tests.util import TestBase
from rez.utils import py23


class TestLoadModuleFromFile(TestBase):
def test_load_module(self):
"""Ensure that the imported module does not show up in sys.modules"""
# Random chars are used in the module name to ensure that the module name is unique
# and the test won't fail because some other module with the same name
# shows up in sys.modules
module = 'utils_test_7cd3a335'

filename = '{0}.py'.format(module)
tmpdir = tempfile.mkdtemp(prefix="rez_selftest_")

with open(os.path.join(tmpdir, filename), 'w') as fd:
fd.write('')

py23.load_module_from_file(
module,
os.path.join(tmpdir, filename)
)
self.assertEqual(sys.modules.get(module), None, msg='Module was found in sys.modules')
20 changes: 17 additions & 3 deletions src/rez/utils/py23.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
Put any code here that deals with py2/3 interoperability, beyond simple cases
that use (for eg) the six module.
"""
import sys

from rez.vendor.six import six


Expand Down Expand Up @@ -38,8 +40,20 @@ def load_module_from_file(name, filepath):
if six.PY2:
import imp
with open(filepath) as f:
return imp.load_source(name, filepath, f)
module = imp.load_source(name, filepath, f)
# Keep the module out of sys.modules. See comment in the `else:`
# for more info
if name in sys.modules:
del sys.modules[name]
return module

else:
from importlib.machinery import SourceFileLoader
return SourceFileLoader(name, filepath).load_module()
# The below code will import the module _without_ adding it to
# sys.modules. We want this otherwise we can't import multiple
# versions of the same module
# See: https://github.com/AcademySoftwareFoundation/rez/issues/1483
import importlib.util
spec = importlib.util.spec_from_file_location(name, filepath)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module

0 comments on commit c4cdc7e

Please sign in to comment.