Skip to content

Testing

This guide explains how to write unit and integration tests for Kirak applications, and how the Kirak test suite is structured.


Install pytest and async test extensions:

Terminal window
pip install pytest pytest-asyncio

Configure pytest for asyncio in pyproject.toml:

[tool.pytest.ini_options]
asyncio_mode = "auto"

Or in pytest.ini:

[pytest]
asyncio_mode = auto

Kirak reads environment variables at startup. Use monkeypatch to set test configuration safely in tests/conftest.py:

import pytest
@pytest.fixture(autouse=True)
def set_test_env(monkeypatch):
monkeypatch.setenv("KIRAK_AUTH_JWT_SECRET_KEY", "test-secret-key-must-be-at-least-32-bytes!!")
monkeypatch.setenv("KIRAK_AUTH_VERIFICATION_KEY", "")

[!NOTE] Environment variables configure secrets and connection endpoints. Settings such as token TTLs and auth behavior toggles reside in kirak.json. To override those during testing, inject a mock configuration object into the test module.


Kirak operations are plain async functions that can be tested directly without starting an ASGI HTTP server.

class MockDialect:
def placeholder(self, index):
return "%s"
class MockCursor:
def __init__(self, fetchone_result=None):
self.fetchone_result = fetchone_result
self.executed = []
async def execute(self, query, params=None):
self.executed.append((query, params))
async def fetchone(self):
return self.fetchone_result
async def __aenter__(self):
return self
async def __aexit__(self, *args):
pass
class MockConnection:
def __init__(self, cursor):
self._cursor = cursor
def cursor(self):
return self._cursor
def transaction(self):
return MockTransaction()
async def __aenter__(self):
return self
async def __aexit__(self, *args):
pass
class MockTransaction:
async def __aenter__(self):
return None
async def __aexit__(self, *args):
pass
class MockDB:
dialect = MockDialect()
def __init__(self, fetchone_result=None):
self._cursor = MockCursor(fetchone_result)
self._conn = MockConnection(self._cursor)
def acquire(self):
return self._conn
@pytest.fixture()
def mock_db():
return MockDB()
import pytest
from kirak.auth.operations.login import _login
from kirak.core.exceptions import ValidationError, AuthenticationError
class TestLogin:
async def test_missing_email_raises_validation_error(self, mock_auth):
with pytest.raises(ValidationError, match="Email and password are required"):
await _login(mock_auth, "users", {"password": "password123"})
async def test_nonexistent_user_raises_authentication_error(self, mock_auth):
mock_auth.kirak.configure("fetch:users", {"statusCode": 200, "data": []})
with pytest.raises(AuthenticationError):
await _login(mock_auth, "users", {
"email": "nonexistent@example.com",
"password": "password123",
})
async def test_valid_login_returns_tokens(self, mock_auth, sample_user):
mock_auth.kirak.configure("fetch:users", {"statusCode": 200, "data": [sample_user]})
result = await _login(mock_auth, "users", {
"email": "test@example.com",
"password": "password123",
})
assert result["status"] == "success"
assert "accessToken" in result["data"]
assert "refreshToken" in result["data"]
assert "password" not in result["data"]["user"]

[!TIP] Kirak operations raise explicit KirakException subclasses (ValidationError, AuthenticationError, PermissionDenied) rather than returning error dictionaries. Test for the exception types directly at the unit level.


Bcrypt hashing at production cost (rounds=12) is deliberately slow and can drastically increase test suite runtimes. Use cost rounds=4 in test fixtures:

import bcrypt
import pytest
_TEST_PASSWORD = "password123"
_TEST_BCRYPT_HASH = bcrypt.hashpw(
_TEST_PASSWORD.encode(), bcrypt.gensalt(rounds=4)
).decode()
@pytest.fixture()
def sample_user():
return {
"id": 1,
"email": "test@example.com",
"password": _TEST_BCRYPT_HASH,
"role": "user",
"is_active": True,
"is_verified": True,
}

Test hooks as isolated async functions:

async def test_after_create_hook_enriches_result():
from myapp.hooks import add_order_total
mock_result = {
"statusCode": 200,
"status": "success",
"message": "orders created successfully",
"data": {"id": 42, "status": "pending"},
}
enriched = await add_order_total(mock_result)
assert "total" in enriched["data"]

Mock provider signature verification libraries directly:

from unittest.mock import patch
import pytest
from kirak.core.exceptions import KirakException
stripe = pytest.importorskip("stripe")
async def test_valid_stripe_webhook(stripe_provider):
fake_event = {
"type": "checkout.session.completed",
"data": {"object": {"id": "cs_test_123"}},
}
with patch("stripe.Webhook.construct_event", return_value=fake_event):
result = await stripe_provider._verify_webhook(b'{"type":"test"}', "valid_sig")
assert result["event"] == fake_event

Integration tests run against live database instances and are gated by KIRAK_INTEGRATION=1:

Terminal window
# Start test database containers
docker compose -f tests/docker-compose.yml up -d
# Run integration tests
KIRAK_INTEGRATION=1 pytest tests/test_core/ -v -m integration
# Run unit tests only
pytest tests/ -v -m "not integration"

Test databases run on isolated ports to prevent conflicts with local services:

Database Host Port User Password Database
MySQL 127.0.0.1 3307 kirak kirak_test_pw kirak_test
PostgreSQL 127.0.0.1 5433 kirak kirak_test_pw kirak_test

tests/
conftest.py # Shared fixtures (mock_db, mock_auth, test env)
test_auth/ # Unit tests per auth operation
test_core/ # Integration tests (mysql_db, postgres_db, engines)
test_crud_integration.py
test_graphql.py
test_payments/ # Webhook verification and provider tests
test_scheduler/ # Scheduler queue and cron tests
test_storage/ # Storage upload and signed URL tests