I've tried
from mock import Mock import __builtin__ __builtin__.print = Mock()
But that raises a syntax error. I've also tried patching it like so
@patch('__builtin__.print') def test_something_that_performs_lots_of_prints(self, mock_print): # assert stuff
Is there any way to do this?
Printed mock-ups help visualize the layout of the finished piece. In the world of printing, a Physical Mock-Up refers to a representative sample that is created prior to production. Physical mock-ups are used to help evaluate the look, feel and function of an item before any actual printing takes place.
How do we mock in Python? Mocking in Python is done by using patch to hijack an API function or object creation call. When patch intercepts a call, it returns a MagicMock object by default. By setting properties on the MagicMock object, you can mock the API call to return any value you want or raise an Exception .
With Mock you can mock magic methods but you have to define them. MagicMock has "default implementations of most of the magic methods.". If you don't need to test any magic methods, Mock is adequate and doesn't bring a lot of extraneous things into your tests.
Print FunctionThe Python print() function takes in any number of parameters, and prints them out on one line of text. The items are each converted to text form, separated by spaces, and there is a single '\n' at the end (the "newline" char).
I know that there is already an accepted answer but there is simpler solution for that problem - mocking the print in python 2.x. Answer is in the mock library tutorial: http://www.voidspace.org.uk/python/mock/patch.html and it is:
>>> from StringIO import StringIO >>> def foo(): ... print 'Something' ... >>> @patch('sys.stdout', new_callable=StringIO) ... def test(mock_stdout): ... foo() ... assert mock_stdout.getvalue() == 'Something\n' ... >>> test()
Of course you can use also following assertion:
self.assertEqual("Something\n", mock_stdout.getvalue())
I have checked this solution in my unittests and it is working as expected. Hope this helps somebody. Cheers!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With