testing/python/collect: replace use of deprecated/removed `imp` module

This commit is contained in:
Ran Benita 2023-05-26 20:28:21 +03:00
parent 7d5207a736
commit 4059000834
1 changed files with 15 additions and 11 deletions

View File

@ -897,25 +897,29 @@ class TestConftestCustomization:
def test_issue2369_collect_module_fileext(self, pytester: Pytester) -> None: def test_issue2369_collect_module_fileext(self, pytester: Pytester) -> None:
"""Ensure we can collect files with weird file extensions as Python """Ensure we can collect files with weird file extensions as Python
modules (#2369)""" modules (#2369)"""
# We'll implement a little finder and loader to import files containing # Implement a little meta path finder to import files containing
# Python source code whose file extension is ".narf". # Python source code whose file extension is ".narf".
pytester.makeconftest( pytester.makeconftest(
""" """
import sys, os, imp import sys
import os.path
from importlib.util import spec_from_loader
from importlib.machinery import SourceFileLoader
from _pytest.python import Module from _pytest.python import Module
class Loader(object): class MetaPathFinder:
def load_module(self, name): def find_spec(self, fullname, path, target=None):
return imp.load_source(name, name + ".narf") if os.path.exists(fullname + ".narf"):
class Finder(object): return spec_from_loader(
def find_module(self, name, path=None): fullname,
if os.path.exists(name + ".narf"): SourceFileLoader(fullname, fullname + ".narf"),
return Loader() )
sys.meta_path.append(Finder()) sys.meta_path.append(MetaPathFinder())
def pytest_collect_file(file_path, parent): def pytest_collect_file(file_path, parent):
if file_path.suffix == ".narf": if file_path.suffix == ".narf":
return Module.from_parent(path=file_path, parent=parent)""" return Module.from_parent(path=file_path, parent=parent)
"""
) )
pytester.makefile( pytester.makefile(
".narf", ".narf",