[Concept,10/19] test: py: Fix PersistentFileHelperCtxMgr with stale .pyc

Message ID 20260314231618.338113-11-sjg@u-boot.org
State New
Headers
Series test: Fix pytest inter-test side effects |

Commit Message

Simon Glass March 14, 2026, 11:16 p.m. UTC
  From: Simon Glass <sjg@chromium.org>

inspect.getmodule() returns None when the .pyc file is compiled with a
different source path, e.g. when running tests inside a container after
building outside it, or vice versa. This causes an AttributeError on
module.__file__ in PersistentFileHelperCtxMgr

Fall back to the caller's filename from the stack frame when the module
cannot be resolved.

Signed-off-by: Simon Glass <sjg@chromium.org>
---

 test/py/utils.py | 13 +++++++++++--
 1 file changed, 11 insertions(+), 2 deletions(-)
  

Patch

diff --git a/test/py/utils.py b/test/py/utils.py
index 7812b2a201b..083a3feddc2 100644
--- a/test/py/utils.py
+++ b/test/py/utils.py
@@ -303,8 +303,17 @@  class PersistentFileHelperCtxMgr(object):
     def __enter__(self):
         frame = inspect.stack()[1]
         module = inspect.getmodule(frame[0])
-        self.module_filename = module.__file__
-        self.module_timestamp = os.path.getmtime(self.module_filename)
+        if module is not None:
+            self.module_filename = module.__file__
+        else:
+            self.module_filename = frame[1]
+
+        if os.path.exists(self.module_filename):
+            self.module_timestamp = os.path.getmtime(self.module_filename)
+        else:
+            # The .pyc was compiled with a different source path
+            # (e.g. inside/outside a container). Skip staleness check.
+            self.module_timestamp = 0
 
         if os.path.exists(self.filename):
             filename_timestamp = os.path.getmtime(self.filename)