Last active
March 18, 2024 17:22
-
-
Save jangia/55a857777303397faf924ad3fc6920ed to your computer and use it in GitHub Desktop.
Testing behavior, not implementation details – Testing implementation Details
This file contains 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
# implementation_details/models.py | |
from dataclasses import dataclass | |
from enum import Enum | |
class TaskStatus(str, Enum): | |
OPEN = "OPEN" | |
CLOSED = "CLOSED" | |
@dataclass | |
class Task: | |
title: str | |
status: TaskStatus |
This file contains 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
# implementation_details/store.py | |
import sqlite3 | |
from implementation_details.models import Task, TaskStatus | |
class TaskStoreSQLite: | |
def add_task(self, connection: sqlite3.Connection, task): | |
connection.execute( | |
"INSERT INTO tasks (title, status) VALUES (?, ?)", | |
(task.title, task.status.name), | |
) | |
def list_tasks(self, connection: sqlite3.Connection,): | |
cursor = connection.execute("SELECT title, status FROM tasks") | |
return [Task(title, TaskStatus(status)) for title, status in cursor.fetchall()] |
This file contains 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
# implementation_details/tests.py | |
import sqlite3 | |
import pytest | |
from implementation_details.models import Task, TaskStatus | |
from implementation_details.store import TaskStoreSQLite, TaskStoreInMemory | |
@pytest.fixture | |
def connection(tmp_path) -> sqlite3.Connection: | |
connection = sqlite3.connect(tmp_path / "test.db") | |
connection.execute("CREATE TABLE tasks (title TEXT, status TEXT)") | |
return connection | |
def test_add_task(connection: sqlite3.Connection): | |
store = TaskStoreSQLite() | |
task = Task(title="Do the dishes", status=TaskStatus.OPEN) | |
store.add_task(connection, task) | |
task_row = connection.execute("SELECT title, status FROM tasks").fetchone() | |
assert task_row[0] == "Do the dishes" | |
assert task_row[1] == "OPEN" | |
def test_list_tasks(connection: sqlite3.Connection): | |
connection.execute("INSERT INTO tasks (title, status) VALUES ('Do the dishes', 'OPEN')") | |
store = TaskStoreSQLite() | |
assert store.list_tasks(connection) == [Task(title="Do the dishes", status=TaskStatus.OPEN)] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment