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

Unit Tests and Mocks: Testing in Python

Unit Tests and Mocks: Testing in Python

Ayla Khan

May 16, 2018
Tweet

More Decks by Ayla Khan

Other Decks in Technology

Transcript

  1. What is a Unit Test? • Test individual software units

    • By devs for devs • Is my code doing things right?
  2. Good Unit Tests • Thorough • Fast • Stable •

    Few The Magic Tricks of Testing by Sandi Metz (http://bit.ly/2rLW5w8)
  3. Mocks • Object double • Mocks aren’t stubs! • Mocks

    use behavior verification • Mocks have expectations Mocks Aren't Stubs by Martin Fowler (http://bit.ly/2luLoeC)
  4. Why mock? • Avoid integration testing • Avoid system calls

    • Avoid using expensive resources • Avoid network requests
  5. unittest.mock class • unittest mocking base class • Simplest mocking

    implementation • Requires manual setup for doubled object attributes and methods
  6. Mock spec • Mock from object attributes and methods ◦

    dir(object) • Object spec from dir(object) • Can generate automatically ◦ Prevent API drift
  7. Mock autospec from unittest.mock import create_autospec def my_function(a, b): pass

    mock_function = create_autospec(my_function, return_value=None) mock_function(1, 2) mock_function.assert_called_once_with(1, 2)
  8. Patch decorator from unittest.mock import patch ... @patch(“myapp.Car.get_make”, autospec=True) def

    test_method(self, mock_function): myapp.Car.get_make() mock_function.assert_called()
  9. Successful Mocking • Keep in sync with API • Keep

    mocks simple • Generate specs automatically
  10. Useful Links • The Magic Tricks of Testing by Sandi

    Metz (http://bit.ly/2rLW5w8) • Mocks Aren't Stubs by Martin Fowler (http://bit.ly/2luLoeC) • Simple Smalltalk Testing: With Patterns by Kent Beck (http://bit.ly/2sEYA1F) • Python Mocks: A Gentle Introduction by Leonardo Giodani (http://bit.ly/2rCHeE5)