How to change the message in a Python AssertionError?

assert expression, info For instance, >>> assert False, “Oopsie” Traceback (most recent call last): File “<stdin>”, line 1, in <module> AssertionError: Oopsie From the docs: Assert statements are a convenient way to insert debugging assertions into a program: assert_stmt ::= “assert” expression [“,” expression] The simple form, assert expression, is equivalent to if __debug__: if … Read more

Scrapy Unit Testing

The way I’ve done it is create fake responses, this way you can test the parse function offline. But you get the real situation by using real HTML. A problem with this approach is that your local HTML file may not reflect the latest state online. So if the HTML changes online you may have … Read more

nose vs pytest – what are the (subjective) differences that should make me pick either? [closed]

I used to use Nose because it was the default with Pylons. I didn’t like it at all. It had configuration tendrils in multiple places, virtually everything seemed to be done with an underdocumented plugin which made it all even more indirect and confusing, and because it did unittest tests by default, it regularly broke … Read more

Mocking two functions with patch for a unit test

You can simplify your test by using the patch decorator and nesting them like so (they are MagicMock objects by default): from unittest.mock import patch @patch(‘cPickle.dump’) @patch(‘__builtin__.open’) def test_write_out(mock_open, mock_pickle): path=”~/collection” f = mock_open.return_value f.method.return_value = path write_out(path, ‘data’) mock_open.assert_called_once_with(‘~/collection’, ‘wb’) mock_pickle.assert_called_once_with(‘data’, f) f.close.assert_any_call() Calls to a MagicMock instance return a new MagicMock instance, so … Read more

How should I verify a log message when testing Python code under nose?

From python 3.4 on, the standard unittest library offers a new test assertion context manager, assertLogs. From the docs: with self.assertLogs(‘foo’, level=”INFO”) as cm: logging.getLogger(‘foo’).info(‘first message’) logging.getLogger(‘foo.bar’).error(‘second message’) self.assertEqual(cm.output, [‘INFO:foo:first message’, ‘ERROR:foo.bar:second message’])

Python Nose Import Error

You’ve got an __init__.py in your top level directory. That makes it a package. If you remove it, your nosetests should work. If you don’t remove it, you’ll have to change your import to import dir.foo, where dir is the name of your directory.