MCPcopy Create free account
hub / github.com/pytest-dev/pytest / exec_module

Method exec_module

src/_pytest/assertion/rewrite.py:131–171  ·  view source on GitHub ↗
(self, module: types.ModuleType)

Source from the content-addressed store, hash-verified

129 return None # default behaviour is fine
130
131 def exec_module(self, module: types.ModuleType) -> None:
132 assert module.__spec__ is not None
133 assert module.__spec__.origin is not None
134 fn = Path(module.__spec__.origin)
135 state = self.config.stash[assertstate_key]
136
137 self._rewritten_names[module.__name__] = fn
138
139 # The requested module looks like a test file, so rewrite it. This is
140 # the most magical part of the process: load the source, rewrite the
141 # asserts, and load the rewritten source. We also cache the rewritten
142 # module code in a special pyc. We must be aware of the possibility of
143 # concurrent pytest processes rewriting and loading pycs. To avoid
144 # tricky race conditions, we maintain the following invariant: The
145 # cached pyc is always a complete, valid pyc. Operations on it must be
146 # atomic. POSIX's atomic rename comes in handy.
147 write = not sys.dont_write_bytecode
148 cache_dir = get_cache_dir(fn)
149 if write:
150 ok = try_makedirs(cache_dir)
151 if not ok:
152 write = False
153 state.trace(f"read only directory: {cache_dir}")
154
155 cache_name = fn.name[:-3] + PYC_TAIL
156 pyc = cache_dir / cache_name
157 # Notice that even if we're in a read-only directory, I'm going
158 # to check for a cached pyc. This may not be optimal...
159 co = _read_pyc(fn, pyc, state.trace)
160 if co is None:
161 state.trace(f"rewriting {fn!r}")
162 source_stat, co = _rewrite_test(fn, self.config)
163 if write:
164 self._writing_pyc = True
165 try:
166 _write_pyc(state, co, source_stat, pyc)
167 finally:
168 self._writing_pyc = False
169 else:
170 state.trace(f"found cached rewritten pyc for {fn}")
171 exec(co, module.__dict__)
172
173 def _early_rewrite_bailout(self, name: str, state: "AssertionState") -> bool:
174 """A fast way to get out of rewriting modules.

Callers 3

import_pathFunction · 0.80

Calls 6

get_cache_dirFunction · 0.85
try_makedirsFunction · 0.85
_read_pycFunction · 0.85
_rewrite_testFunction · 0.85
_write_pycFunction · 0.85
traceMethod · 0.80