How to mock a BulkWriteException in python?
Question: I need to get the information contained in the exception. This is the code I
use.

    
    
    try:
        result = yield user_collection.insert_many(content, ordered=False)
    except BulkWriteError as e:
        print (e)
    

And in my test when I get into the except with this line,

    
    
    self.insert_mock.side_effect = [BulkWriteError('')]
    

it returns me

> batch op errors occurred

instead of a MagicMock or a Mock.

How can I mock the `BulkWriteError` and give it a default `return_value` and
see it when I use `print(e)`?


Answer: Something like this should allow you to test your print was called correctly.

    
    
    import builtins # mockout print
    
    class BulkWriteErrorStub(BulkWriteError):
      ''' Stub out the exception so you can bypass the constructor. '''
    
      def __str__:
        return 'fake_error'
    
    @mock.patch.object('builtins', 'print')
    def testRaisesBulkWrite(self, mock_print):
      ...
      self.insert_mock.side_effect = [BuilkWriteErrorStub]
      with self.assertRaises(...):
        mock_print.assert_called_once_with('fake_error')
    

I haven't tested this so feel free to edit it if I made a mistake.

