Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Mock - Mocking and Testing Library, A Lightening Talk

Mock - Mocking and Testing Library, A Lightening Talk

This is a simple presentation on mock. Its meant to be a quick introduction to using mock in when writing your unit tests.

Burton Williams

February 10, 2014
Tweet

More Decks by Burton Williams

Other Decks in Programming

Transcript

  1. About me { “name”: “Burton Williams”, “title”: “Software Engineer Contractor”,

    “email” : “[email protected]”, “github” : “ikiini”, “country”: “St Vincent and the Grenadines” }
  2. What is Mock? “Mock is a library for testing in

    Python. It allows you to replace parts of your system under test with mock objects and make assertions about how they have been used”
  3. How do I use my mock object? >>> instance_of_my_mock =

    my_mock_object() Or >>> instance_of_my_mock = \ my_mock_object.return_value
  4. How do I use my mock object? >>> import db

    >>> class MyMarvelousClass(object): ... def sum_transactions(self): ... total = 0 ... for transaction in db.transactions.find({},{'total':1}): ... total += transaction['total'] ... return total >>> class MyMarvelousClassTestCase(unittest.TestCase): ... def test_add(self): ... mock_db = Mock() ... mock_db_instance = mock_db() # or mock_db.return_value ... mock_db_instance.transactions.find.return_value = [{'total' :1}, {'total' :2}, {'total' :5}] ... marvelous = MyMarvelousClass() ... marvelous.db = mock_db_instance ... result = class.sum_transactions() ... self.assertEqual(result, 8)
  5. How do I use my mock object? >>>@patch.object('module_name.object_to_replace_with_mock') ... class

    MyMarvelousClassTestCase(unittest.TestCase): ... def test_add(self, mock_db): ... marvelous = MyMarvelousClass() ... mock_db_instance = mock_db.return_value ... mock_db_instance.transactions.find.return_value = [{'total' :1}, {'total' :2}, {'total' :5}] ... marvelous.db = mock_db_instance ... result = class.sum_transactions() ... self.assertEqual(result, 8) ... def test_add(self, mock_db): ... instance = mock_db.return_value
  6. Other things you can do with Mock • side_effect –

    Return different values, either controlled or varied by writing a function and assigning it to side_effect variable of mock instance. • mock_calls – Assert what methods were called.