Created
March 18, 2024 17:24
-
-
Save jangia/3b75f4ef4560e3301a4d966f918ffcc0 to your computer and use it in GitHub Desktop.
Testing behavior, not implementation details – Testing Behavior
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
# behavior/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
# behavior/store.py | |
import sqlite3 | |
from abc import ABC | |
from behavior.models import Task, TaskStatus | |
class TaskStore(ABC): | |
def add_task(self, task: Task) -> None: | |
raise NotImplementedError | |
def list_tasks(self) -> list[Task]: | |
raise NotImplementedError | |
class TaskStoreSQLite(TaskStore): | |
def __init__(self, connection: sqlite3.Connection): | |
self._connection = connection | |
def add_task(self, task: Task) -> None: | |
self._connection.execute( | |
"INSERT INTO tasks (title, status) VALUES (?, ?)", | |
(task.title, task.status.name), | |
) | |
def list_tasks(self) -> list[Task]: | |
cursor = self._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
# behavior/tests.py | |
import sqlite3 | |
import pytest | |
from behavior.models import Task, TaskStatus | |
from behavior.store import TaskStoreInMemory, TaskStoreSQLite | |
@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 | |
@pytest.fixture | |
def store(connection) -> TaskStoreSQLite: | |
return TaskStoreSQLite(connection) | |
def test_added_task_listed(store: TaskStoreSQLite): | |
task = Task(title="Do the dishes", status=TaskStatus.OPEN) | |
store.add_task(task) | |
assert store.list_tasks() == [task] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment