From aa95a425d7708d80fc887b1825662daf3a624ba7 Mon Sep 17 00:00:00 2001 From: Bruno Oliveira Date: Wed, 11 Apr 2018 19:41:10 -0300 Subject: Attempt to solve race-condition which corrupts .pyc files on Windows This uses of the `atomicwrites` library. This is very hard to create a reliable test for. Fix #3008 --- _pytest/assertion/rewrite.py | 41 ++++++++++++++--------------------------- 1 file changed, 14 insertions(+), 27 deletions(-) (limited to '_pytest') diff --git a/_pytest/assertion/rewrite.py b/_pytest/assertion/rewrite.py index db3674930..0499a792f 100644 --- a/_pytest/assertion/rewrite.py +++ b/_pytest/assertion/rewrite.py @@ -12,7 +12,9 @@ import struct import sys import types +import atomicwrites import py + from _pytest.assertion import util @@ -140,7 +142,7 @@ class AssertionRewritingHook(object): # Probably a SyntaxError in the test. return None if write: - _make_rewritten_pyc(state, source_stat, pyc, co) + _write_pyc(state, co, source_stat, pyc) else: state.trace("found cached rewritten pyc for %r" % (fn,)) self.modules[name] = co, pyc @@ -258,22 +260,21 @@ def _write_pyc(state, co, source_stat, pyc): # sometime to be able to use imp.load_compiled to load them. (See # the comment in load_module above.) try: - fp = open(pyc, "wb") - except IOError: - err = sys.exc_info()[1].errno - state.trace("error writing pyc file at %s: errno=%s" % (pyc, err)) + with atomicwrites.atomic_write(pyc, mode="wb", overwrite=True) as fp: + fp.write(imp.get_magic()) + mtime = int(source_stat.mtime) + size = source_stat.size & 0xFFFFFFFF + fp.write(struct.pack("