1
+ import os
2
+ import pathlib
3
+ import py_compile
4
+ import shutil
1
5
import textwrap
2
6
import unittest
3
7
import warnings
7
11
import importlib_resources as resources
8
12
from ..abc import Traversable
9
13
from . import util
14
+ from .compat .py39 import os_helper , import_helper
10
15
11
16
12
17
@contextlib .contextmanager
@@ -97,8 +102,8 @@ class ModuleFilesZipTests(DirectSpec, util.ZipSetup, ModulesFiles, unittest.Test
97
102
98
103
class ImplicitContextFiles :
99
104
set_val = textwrap .dedent (
100
- """
101
- import importlib_resources as res
105
+ f """
106
+ import { resources . __name__ } as res
102
107
val = res.files().joinpath('res.txt').read_text(encoding='utf-8')
103
108
"""
104
109
)
@@ -108,6 +113,10 @@ class ImplicitContextFiles:
108
113
'submod.py' : set_val ,
109
114
'res.txt' : 'resources are the best' ,
110
115
},
116
+ 'frozenpkg' : {
117
+ '__init__.py' : set_val .replace (resources .__name__ , 'c_resources' ),
118
+ 'res.txt' : 'resources are the best' ,
119
+ },
111
120
}
112
121
113
122
def test_implicit_files_package (self ):
@@ -122,6 +131,32 @@ def test_implicit_files_submodule(self):
122
131
"""
123
132
assert importlib .import_module ('somepkg.submod' ).val == 'resources are the best'
124
133
134
+ def _compile_importlib (self ):
135
+ """
136
+ Make a compiled-only copy of the importlib resources package.
137
+ """
138
+ bin_site = self .fixtures .enter_context (os_helper .temp_dir ())
139
+ c_resources = pathlib .Path (bin_site , 'c_resources' )
140
+ sources = pathlib .Path (resources .__file__ ).parent
141
+ shutil .copytree (sources , c_resources , ignore = lambda * _ : ['__pycache__' ])
142
+
143
+ for dirpath , _ , filenames in os .walk (c_resources ):
144
+ for filename in filenames :
145
+ source_path = pathlib .Path (dirpath ) / filename
146
+ cfile = source_path .with_suffix ('.pyc' )
147
+ py_compile .compile (source_path , cfile )
148
+ pathlib .Path .unlink (source_path )
149
+ self .fixtures .enter_context (import_helper .DirsOnSysPath (bin_site ))
150
+
151
+ def test_implicit_files_with_compiled_importlib (self ):
152
+ """
153
+ Caller detection works for compiled-only resources module.
154
+
155
+ python/cpython#123085
156
+ """
157
+ self ._compile_importlib ()
158
+ assert importlib .import_module ('frozenpkg' ).val == 'resources are the best'
159
+
125
160
126
161
class ImplicitContextFilesDiskTests (
127
162
DirectSpec , util .DiskSetup , ImplicitContextFiles , unittest .TestCase
0 commit comments