Skip to content

Instantly share code, notes, and snippets.

@jangia
Created March 27, 2024 18:48
Show Gist options
  • Save jangia/a6eb4f82d65aefa4a67e2bb53cbf9fc3 to your computer and use it in GitHub Desktop.
Save jangia/a6eb4f82d65aefa4a67e2bb53cbf9fc3 to your computer and use it in GitHub Desktop.
Testing behavior, not implementation details – part 2 (model & store)
from dataclasses import dataclass
from enum import Enum
class TaskStatus(str, Enum):
OPEN = "OPEN"
CLOSED = "CLOSED"
@dataclass
class Task:
title: str
status: TaskStatus
owner: str
import sqlite3
from abc import ABC
from models import Task, TaskStatus
class TaskStore(ABC):
def add_task(self, task: Task) -> None:
raise NotImplementedError
def list_open(self, owner: str) -> 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, owner) VALUES (?, ?, ?)",
(task.title, task.status.name, task.owner),
)
def list_open(self, owner: str) -> list[Task]:
cursor = self._connection.execute(
"SELECT title, status, owner FROM tasks WHERE status = 'OPEN' AND owner = ?",
(owner,),
)
return [
Task(title, TaskStatus(status), owner)
for title, status, owner in cursor.fetchall()
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment