Skip to content

Instantly share code, notes, and snippets.

@acherrera
Created August 19, 2020 14:11
Show Gist options
  • Save acherrera/231049fe26c2883ead074d5ca67080a2 to your computer and use it in GitHub Desktop.
Save acherrera/231049fe26c2883ead074d5ca67080a2 to your computer and use it in GitHub Desktop.
Python Unittest Basic Setup
"""
I can't remember the basic setup, so here it is. This file may or may not run, it is mainly to show the pattern of
testing and set up.
"""
import unittest
from unittest.mock import patch
# Also import all the thing you want to test here
def fake_func():
# Ignore this - just using to have something to test against
return None
class TestExample(unittest.TestCase):
def setUp(self):
# All tests will have these available - runs at beginning of each test
patcher1 = patch('package.module.Class')
patcher2 = patch('package.module.OtherClass')
self.MockClass = patcher1.start()
self.MockOtherClass = patcher2.start()
self.addCleanup(patcher1.stop)
self.addCleanup(patcher2.stop)
@patch('package.module.ThirdClass') # Only available to this test
def test_runs_well(self, MockThirdClass):
# Can add custom mock returns here if you'd like.
outval = fake_func()
self.assertNone(outval)
self.MockClass.assert_not_called()
self.MockOtherClass.assert_not_called()
MockThirdClass.assert_called_once()
if __name_ == "__main__":
# Just in case we want to run this file directly
unittest.main(failfast=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment