@@ -2159,6 +2159,45 @@ def dump(value, stream, **kwargs):
21592159 self .assertEqual (self .read (doc ), {'a' : 1 })
21602160 self .assertEqual (sorted (os .listdir (self .dir )), ['doc.json' , 'patch.json' ])
21612161
2162+ def test_jsonpatch_in_place_cleans_temp_on_fdopen_error (self ):
2163+ for backup in (False , True ):
2164+ with self .subTest (backup = backup ):
2165+ tmp = tempfile .TemporaryDirectory ()
2166+ self .addCleanup (tmp .cleanup )
2167+ self .dir = tmp .name
2168+ doc = self .write ('doc.json' , {'a' : 1 })
2169+ patch = self .write ('patch.json' , [{'op' : 'replace' , 'path' : '/a' , 'value' : 2 }])
2170+ parser = jsonpatch_cli .jsonpatch_parser
2171+ args = parser .parse_args (['-i' , doc , patch ] + (['-b' ] if backup else []))
2172+ self .addCleanup (args .ORIGINAL .close )
2173+ self .addCleanup (args .PATCH .close )
2174+ descriptors = []
2175+
2176+ def close_if_open (fd ):
2177+ try :
2178+ os .close (fd )
2179+ except OSError :
2180+ pass
2181+
2182+ def fail_fdopen (fd , * args , ** kwargs ):
2183+ descriptors .append (fd )
2184+ self .addCleanup (close_if_open , fd )
2185+ raise OSError ('cannot wrap temporary descriptor' )
2186+
2187+ with mock .patch .object (parser , 'parse_args' , return_value = args ), \
2188+ mock .patch ('os.fdopen' , side_effect = fail_fdopen ):
2189+ jsonpatch_cli .patch_files ()
2190+
2191+ self .assertEqual (self .read (doc ), {'a' : 2 })
2192+ if backup :
2193+ self .assertEqual (self .read (doc + '.orig' ), {'a' : 1 })
2194+ with self .assertRaises (OSError ):
2195+ os .fstat (descriptors [0 ])
2196+ expected = ['doc.json' , 'patch.json' ]
2197+ if backup :
2198+ expected .append ('doc.json.orig' )
2199+ self .assertEqual (sorted (os .listdir (self .dir )), sorted (expected ))
2200+
21622201 def test_jsonpatch_in_place_preserves_original_on_replace_error (self ):
21632202 doc = self .write ('doc.json' , {'a' : 1 })
21642203 patch = self .write ('patch.json' , [{'op' : 'replace' , 'path' : '/a' , 'value' : 2 }])
0 commit comments