Created
October 28, 2022 09:28
-
-
Save arindas/b03b16555c2f7ffd5a5c2bb84a0aecb5 to your computer and use it in GitHub Desktop.
mocking-tdd-demo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import abc | |
| class Source(metaclass=abc.ABCMeta): | |
| @abc.abstractmethod | |
| def read(self) -> int: | |
| raise NotImplementedError() | |
| class Sink(metaclass=abc.ABCMeta): | |
| @abc.abstractmethod | |
| def write(self, integer: int): | |
| raise NotImplementedError() | |
| class BinaryAdder: | |
| def add(self, source_1: Source, source_2: Source, sink: Sink): | |
| sink.write(source_1.read() + source_2.read()) | |
| def test_binary_adder(): | |
| class MockSource(Source): | |
| def __init__(self, value: int): | |
| self.value = value | |
| def read(self) -> int: | |
| return self.value | |
| class MockSink(Sink): | |
| def __init__(self): | |
| self.value = 0 | |
| def write(self, integer: int): | |
| self.value = integer | |
| mock_source_1 = MockSource(123) | |
| mock_source_2 = MockSource(456) | |
| mock_sink = MockSink() | |
| binary_adder = BinaryAdder() | |
| binary_adder.add(mock_source_1, mock_source_2, mock_sink) | |
| assert(mock_sink.value == mock_source_1.value + mock_source_2.value) | |
| test_binary_adder() | |
| def main(): | |
| class ConsoleSource(Source): | |
| def read(self) -> int: | |
| return int(input("Enter integer: ")) | |
| class ConsoleSink(Sink): | |
| def write(self, integer: int): | |
| print(integer) | |
| BinaryAdder().add(ConsoleSource(), ConsoleSource(), ConsoleSink()) | |
| if __name__ == "__main__": | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment