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