What should tests cover?


Python clean test tip:

For the most part, the tests you write should cover:

  • all happy paths
  • edge/corner/boundary cases
  • negative test cases
  • security and illegal issues

👇

import uuid
from dataclasses import dataclass
from typing import Optional


@dataclass
class User:
    username: str


class InMemoryUserRepository:
    def __init__(self):
        self._users = []

    def add(self, user: User) -> None:
        self._users.append(user)

    def search(self, query: Optional[str] = None) -> list[User]:
        if query is None:
            return self._users
        else:
            return [
                user
                for user in self._users
                if query in user.username
            ]


# happy path
def test_search_users_without_query_lists_all_users():
    user1 = User(username="[email protected]")
    user2 = User(username="[email protected]")
    repository = InMemoryUserRepository()
    repository.add(user1)
    repository.add(user2)

    assert repository.search() == [user1, user2]


# happy path
def test_search_users_with_email_part_lists_all_matching_users():
    user1 = User(username="[email protected]")
    user2 = User(username="[email protected]")
    user3 = User(username="[email protected]")
    repository = InMemoryUserRepository()
    repository.add(user1)
    repository.add(user2)
    repository.add(user3)

    assert repository.search("doe") == [user1, user3]


# edge test case
def test_search_users_with_empty_query_lists_all_users():
    user1 = User(username="[email protected]")
    user2 = User(username="[email protected]")
    repository = InMemoryUserRepository()
    repository.add(user1)
    repository.add(user2)

    assert repository.search("") == [user1, user2]


# negative test case
def test_search_users_with_random_query_lists_zero_users():
    user1 = User(username="[email protected]")
    repository = InMemoryUserRepository()
    repository.add(user1)

    assert repository.search(str(uuid.uuid4())) == []


# security test
def test_search_users_with_sql_injection_has_no_effect():
    user1 = User(username="[email protected]")
    repository = InMemoryUserRepository()
    repository.add(user1)

    repository.search("DELETE FROM USERS;")
    assert repository.search() == [user1]