Skip to content

Instantly share code, notes, and snippets.

@bengolder
Last active June 13, 2016 15:15
Show Gist options
  • Save bengolder/83e79f6cf56cb569537cd71045b3ccdd to your computer and use it in GitHub Desktop.
Save bengolder/83e79f6cf56cb569537cd71045b3ccdd to your computer and use it in GitHub Desktop.
How to test a method in isolation from the rest of the class
class ExampleClass:
def __init__(self):
# assume this takes action that you don't want to include in the unit test
self.something = "data from complicated setup that calls other services"
print("accessing", self.something)
from module_deep_in_framework import ExampleClass
import external_module
class SubClass(ExampleClass):
def my_small_method(self):
if "other services" in self.something:
# send data
return external_module.action(
self.something.split(" ")[0])
else:
return external_module.other_action()
from unittest import TestCase, mock
from mymodule import SubClass
class TestMyModule(TestCase):
@mock.patch('mymodule.external_module')
def test_my_small_method(self, external_module):
# case: no other services
doesnt_have_other_services = mock.Mock(something="no services")
SubClass.my_small_method(doesnt_have_other_services)
external_module.other_action.assert_called_once_with()
# case: has other services
has_other_services = mock.Mock(something="data other services")
SubClass.my_small_method(has_other_services)
external_module.action.assert_called_with('data')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment