A short tutorial showing you a clever way to mock out some writes during your unit testing.
I had a small feature in my open-source
project yapconf that I wanted to solve.
Basically, I wanted to confirm that what I wrote to
STDOUT was what I expected to write. So I
turned to the Mock library for python.
Here is the basic code I wanted to test (some parts are omitted for brevity)
Pretty simple code, we are just converting the Box over to a dictionary before dumping. You can
see that we should be streaming the result out to
I wanted to test this code was actually going to write out what I thought it was going to write out. After all, that’s why I was writing this new feature. So let’s create a unit test:
The code above uses a pytest fixture. If you
haven’t heard of either, a highly suggest you go check them out. Either way, we are taking in
ascii_data into our test function
At the beginning of the function, we construct the string we expect to receive. In this case, we
are dumping yaml, so we would expect to see a yaml formatted string. We also use the
to make sure that our line separators will work cross-platform.
Next, we create a
data object that is initialized at the function scope. We create a new
mock_write that will modify this
data variable. That way we get a pseudo-global
variable that we can play with.
Next, we use
patch to actually mock out the
sys.stdout.write call. The next argument to
patch is the new method we are sending it to.
Finally, we call our
assert that the value is correct.
Thanks for reading! If you have a better way to do it, feel free to comment or hit me up on twitter @loganasherjones