python - How to patch method io.RawIOBase.read with unittest? -
i've learned unittest.monkey.patch
, variants, , i'd use unit test atomicity of file read function. however, patch doesn't seem have effect.
here's set-up. method under scrutiny (abriged):
#local_storage.py def read(uri): open(path, "rb") file_handle: result = file_handle.read() return result
and module performs unit tests (also abriged):
#test/test_local_storage.py import unittest.mock import local_storage def _read_while_writing(io_handle, size=-1): """ patch function, replace io.rawiobase.read. """ _write_something_to(testlocalstorage._unsafe_target_file) #appends "12". result = io_handle.read(size) #should call actual read. _write_something_to(testlocalstorage._unsafe_target_file) #appends "34". class testlocalstorage(unittest.testcase): _unsafe_target_file = "test.txt" def test_read_atomicity(self): open(self._unsafe_target_file, "wb") unsafe_file_handle: unsafe_file_handle.write(b"test") unittest.mock.patch("io.rawiobase.read", _read_while_writing): # <--- doesn't work! result = local_storage.read(testlocalstorage._unsafe_target_file) #the actual test. self.assertin(result, [b"test", b"test1234"], "read not atomic.")
this way, patch should ensure every time try read it, file gets modified before , after actual read, if happens concurrently, testing atomicity of our read.
the unit test succeeds, i've verified print statements patch function doesn't called, file never gets additional writes (it says "test"). i've modified code non-atomic on purpose.
so question: how can patch read
function of io handle inside local_storage module? i've read elsewhere people tend replace open() function return stringio
, don't see how fix problem.
i need support python 3.4 , up.
i've found solution myself.
the problem mock
can't mock methods of objects written in c. 1 of these rawiobase
encountering.
so indeed solution mock open
return wrapper around rawiobase
. couldn't mock
produce wrapper me, implemented myself.
there 1 pre-defined file that's considered "unsafe". wrapper writes "unsafe" file every time call made wrapper. allows testing atomicity of file writes, since writes additional things unsafe file while writing. implementation prevents writing temporary ("safe") file , moving file on target file.
the wrapper has special case read
function, because test atomicity needs write file during read. reads first halfway through file, stops , writes something, , reads on. solution semi-hardcoded (in how far halfway), i'll find way improve that.
you can see solution here: https://github.com/ghostkeeper/luna/blob/0e88841d19737fb1f4606917f86e3de9b5b9f29b/plugins/storage/localstorage/test/test_local_storage.py
Comments
Post a Comment