Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock Python's built in print function

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?

like image 746
aychedee Avatar asked Oct 21 '12 14:10

aychedee


People also ask

What is mock print?

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 you mock a function in Python?

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 .

What is the difference between mock and MagicMock?

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.

How do you print text in Python?

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).


1 Answers

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!

like image 61
Krzysztof Czeronko Avatar answered Sep 16 '22 11:09

Krzysztof Czeronko