Skip to content

Instantly share code, notes, and snippets.

@carlosble
Created July 8, 2020 17:03
Show Gist options
  • Save carlosble/f8f851199c01e64a083c9c3c0b9d59b9 to your computer and use it in GitHub Desktop.
Save carlosble/f8f851199c01e64a083c9c3c0b9d59b9 to your computer and use it in GitHub Desktop.
import unittest
from camera import Controller, Sensor, Recorder
class MockMovementSensor(Sensor):
def is_detecting_movement(self) -> bool:
return True
class MockNoMovementSensor(Sensor):
def is_detecting_movement(self) -> bool:
return False
class MockRecorder(Recorder):
start_called = False
start_call_count = 0
stop_called = False
stop_call_count = 0
def start_recording(self):
self.start_called = True
self.start_call_count += 1
def stop_recording(self):
self.stop_called = True
self.stop_call_count += 1
class CameraTestsUsingInheritanceMocks(unittest.TestCase):
def test_asks_the_recorder_to_stop_recording_when_no_information_received_from_sensor(self):
sensor = MockNoMovementSensor()
recorder = MockRecorder()
controller = Controller(sensor, recorder)
controller.record_movement()
self.assertTrue(recorder.stop_called)
def test_asks_the_recorder_to_start_recording_when_no_sensor_detects_movement(self):
sensor = MockMovementSensor()
recorder = MockRecorder()
controller = Controller(sensor, recorder)
controller.record_movement()
self.assertTrue(recorder.start_called)
class CameraTestsUsingMonkeyPatchingForMocks(unittest.TestCase):
sensor: Sensor
recorder: Recorder
controller: Controller
def setUp(self) -> None:
self.sensor = Sensor() # mocks
self.recorder = Recorder() # mocks
self.controller = Controller(self.sensor, self.recorder)
self.called = False
def test_asks_the_recorder_to_stop_recording_when_no_information_received_from_sensor(self):
self.sensor.is_detecting_movement = lambda: False
self.recorder.stop_recording = self.save_call
self.controller.record_movement()
self.assertTrue(self.called)
def test_asks_the_recorder_to_start_recording_when_no_sensor_detects_movement(self):
self.sensor.is_detecting_movement = lambda: True
self.recorder.start_recording = self.save_call
self.controller.record_movement()
self.assertTrue(self.called)
def save_call(self):
self.called = True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment