Skip to content

Testing

Fullfinity includes a built-in test framework for testing models, actions, and business logic. Tests run against a real database with the full ORM and environment available.

Tests are run via the CLI. You don’t need to create or name a database — the test command spins up a fresh, self-cleaning one for the run (see Test Database):

Terminal window
# Run the ENTIRE suite (every module that has tests, in one database)
fullfinity-server --config config.yaml test
# Run tests for a specific module only
fullfinity-server --config config.yaml test --module invoicing
# Run with verbose output
fullfinity-server --config config.yaml test -v
# Run only tests matching a pattern (file, class or method name)
fullfinity-server --config config.yaml test -k test_create
# Any level works, and commas mean "either"
fullfinity-server --config config.yaml test -k TestInvoicePosting
fullfinity-server --config config.yaml test -k test_credit_note.py
fullfinity-server --config config.yaml test -k "credit_note,refund"

Omitting --module installs every module into one database and runs all their tests. Scoping with --module is a filter that installs just that module’s dependency graph.

Checking that a module installs on its own dependencies

Section titled “Checking that a module installs on its own dependencies”
Terminal window
# Install the module (and its declared dependencies) into a fresh database, run no tests
fullfinity-server --config config.yaml test --module my_module --install-only

--install-only answers a different question from a test run: does this module compose and install on the dependencies it declares? A view, ACL or menu that references a field or model some other module contributes still resolves when everything is installed together, so the break only shows when the module is installed alone. The run exits 0 when the install succeeded and non-zero on any composition or install error — no tests are collected, so a module with no tests/ directory is checked exactly like one that has them.

The full suite passes run all-at-once, so a no---module run is the way to validate a change: a failure in it is a real failure. --module is a faster scoped run while you iterate on one module.

Terminal window
# Four shards, each in its own terminal or CI job — together they run the whole suite
fullfinity-server --config config.yaml test --shard 1/4
fullfinity-server --config config.yaml test --shard 2/4
fullfinity-server --config config.yaml test --shard 3/4
fullfinity-server --config config.yaml test --shard 4/4

--shard INDEX/TOTAL runs one slice of the test files. Every shard installs the same modules a full run does — only the files executed are divided — so a test sees the same database in its shard as in the full suite. Each shard creates its own ephemeral database, so shards can run at the same time on one machine. Every file lands in exactly one shard, and the split is the same on every machine, so a failure in shard 3 reproduces with --shard 3/4.

Each test is rolled back to a savepoint, so a test cannot depend on another having run first. State outside the transaction — a database sequence, a key-value entry, a file in the filestore — survives that rollback, though, and a test that quietly relied on an earlier test leaving it behind will fail once the two land in different shards. That failure is a real hidden dependency in the test, not a sharding problem.

The schema window (Env.schema_window(db), which an upgrade opens so reads and writes tolerate columns not added yet) is process state no rollback reaches, so the runner checks it instead: a test that leaves the window open or closed differently from how it found it fails, with a message saying so, and the window is put back for the next test. Open it with with so it always closes.

It combines with --module, which narrows the files before they are split, and with -k, which then filters the tests inside each shard. The install is paid once per shard, so sharding pays off for long runs, not short filtered ones.

OptionDescription
--module, -mOnly run tests for the specified module (omit to run all modules)
--verbose, -vShow detailed output for each test
-k PATTERNOnly run tests whose file, class or method name contains the pattern (case-insensitive substring). Comma-separated patterns mean “either”: -k "kit,uom"
--shard INDEX/TOTALRun one slice of the test files, e.g. --shard 2/4; see Splitting the suite
--json-summary FILEWrite the results as JSON to FILE: counts, then every test with its status, duration, message and (for a failure) traceback
--install-onlyInstall --module and its declared dependencies, then stop without running tests

Create test files in your module’s tests/ directory with the test_ prefix:

modules/mymodule/
├── models/
│ └── my_model.py
├── tests/ # Tests directory
│ ├── test_my_model.py # Test files start with test_
│ └── test_actions.py
└── manifest.yaml

Test classes inherit from TestCase and contain async test methods:

from fullfinity.engine.testing import TestCase
class TestMyModel(TestCase):
"""Test MyModel CRUD operations."""
async def test_create_record(self):
"""Test creating a record."""
MyModel = get_model("MyModel")
record = await MyModel.create(
name="Test Record",
value=100,
)
self.assertIsNotNone(record.id)
self.assertEqual(record.name, "Test Record")
self.assertEqual(record.value, 100)
async def test_update_record(self):
"""Test updating a record."""
MyModel = get_model("MyModel")
record = await MyModel.create(name="Original")
await record.update(name="Updated")
# Reload from database to verify
reloaded = await MyModel.filter(id=record.id).first()
self.assertEqual(reloaded.name, "Updated")
async def test_delete_record(self):
"""Test deleting a record."""
MyModel = get_model("MyModel")
record = await MyModel.create(name="To Delete")
record_id = record.id
await record.delete()
# Verify deletion
deleted = await MyModel.filter(id=record_id).first()
self.assertIsNone(deleted)

Use get_model("ModelName") to get model classes:

async def test_with_multiple_models(self):
Contact = get_model("Contact")
Order = get_model("Order")
Product = get_model("Product")
# Create related records
contact = await Contact.create(name="Customer")
product = await Product.create(name="Widget", price=9.99)
order = await Order.create(
contact=contact,
lines=[["create", {"product": product.id, "quantity": 2}]]
)
self.assertEqual(order.contact.id, contact.id)
MethodDescription
assertEqual(a, b, msg=None)Assert a == b
assertNotEqual(a, b, msg=None)Assert a != b
assertTrue(x, msg=None)Assert x is True
assertFalse(x, msg=None)Assert x is False
assertIsNone(x, msg=None)Assert x is None
assertIsNotNone(x, msg=None)Assert x is not None
MethodDescription
assertIn(a, b, msg=None)Assert a in b
assertNotIn(a, b, msg=None)Assert a not in b
assertEmpty(obj, msg=None)Assert len(obj) == 0
assertNotEmpty(obj, msg=None)Assert len(obj) > 0
MethodDescription
assertGreater(a, b, msg=None)Assert a > b
assertGreaterEqual(a, b, msg=None)Assert a >= b
assertLess(a, b, msg=None)Assert a < b
assertLessEqual(a, b, msg=None)Assert a <= b
assertAlmostEqual(a, b, places=7, msg=None)Assert a ≈ b within decimal places
MethodDescription
assertIsInstance(obj, cls, msg=None)Assert isinstance(obj, cls)

Use assertRaises as a context manager:

async def test_validation_error(self):
MyModel = get_model("MyModel")
with self.assertRaises(UserError):
await MyModel.create(value=-1) # Should raise UserError
async def test_exception_message(self):
with self.assertRaises(UserError) as ctx:
await self.do_invalid_operation()
# Access the exception
self.assertIn("invalid", str(ctx.exception))

Assert that records match expected field values:

async def test_record_values(self):
Order = get_model("Order")
orders = await Order.filter(state="Posted").all()
self.assertRecordValues(orders, [
{"name": "SO-001", "state": "Posted", "total": 100.0},
{"name": "SO-002", "state": "Posted", "total": 250.0},
])

Methods called before/after each test:

class TestWithSetup(TestCase):
async def setUp(self):
"""Called before each test method."""
# Create test data
Contact = get_model("Contact")
self.test_contact = await Contact.create(name="Test Contact")
async def tearDown(self):
"""Called after each test method."""
# Clean up (optional - tests run in isolation)
if self.test_contact:
await self.test_contact.delete()
async def test_using_fixture(self):
"""Test that uses the setUp fixture."""
self.assertIsNotNone(self.test_contact.id)

Class-level setup called once for all tests:

class TestWithClassSetup(TestCase):
@classmethod
async def setUpClass(cls):
"""Called once before all tests in the class."""
# Create shared fixtures
Category = get_model("Category")
cls.category = await Category.create(name="Shared Category")
@classmethod
async def tearDownClass(cls):
"""Called once after all tests in the class."""
if cls.category:
await cls.category.delete()
async def test_using_shared_fixture(self):
"""All tests can use cls.category."""
self.assertIsNotNone(self.category.id)

Tests that need another module: requires_modules

Section titled “Tests that need another module: requires_modules”

A test run installs the modules whose tests it runs, with their dependencies. When a class also needs a module its own module does not depend on (a payment test that pays for a sale order, say), declare it on the class:

class TestPaymentForAnOrder(TestCase):
requires_modules = ["sales"]

The runner installs every declared module together with the rest, before any test starts. It reads the list from the file’s source without importing it, so it must be a literal list of strings. "contributes:<DataType>" names every module whose views declare a record of that type — requires_modules = ["contributes:PortalAction"] installs every module with a portal page, and a newly added one is covered automatically. A base class’s declaration applies to its subclasses, including subclasses in other test files that import it.

Do not install from setUpClass: it runs inside the run’s test transaction, so the install is rolled back with the class while the module is still recorded as installed, and every class after it fails on a table that does not exist. The runner refuses such an install and names the requires_modules line to add instead.

The same goes for any real module install or uninstall inside a test or setUpClass, however it is reached — including indirectly, such as moving a company to a country whose localization package then installs. An install rebuilds caches the whole run shares, which the rollback cannot undo, so tests in other modules start failing far from the cause. It raises InternalError instead. To test code that installs modules, patch the operation (patch.object(Module, "install_modules", ...)) and assert what it was asked to do; to test something that merely happens to trigger an install, reach it another way (a country with no localization package).

Register cleanup functions to run after a test:

async def test_with_cleanup(self):
record = await self.create_temporary_record()
# Register cleanup - runs even if test fails
self.addCleanup(record.delete)
# Test logic...
self.assertIsNotNone(record.id)
class TestSkipping(TestCase):
@TestCase.skip("Feature not implemented yet")
async def test_future_feature(self):
"""This test will be skipped."""
pass
@TestCase.skipIf(not HAS_FEATURE, "Requires feature X")
async def test_optional_feature(self):
"""Skipped if condition is True."""
pass

The test command is self-cleaning — you don’t create, name, or clean up a database:

  • It creates a fresh, ephemeral database for the run, installs the modules that have tests (plus their dependencies) with demo data, and runs against the real ORM.
  • Each test’s data is wrapped in a transaction that is rolled back, so tests don’t see each other’s data and nothing leaks between runs.
  • The run’s clock is UTC, whatever the machine’s own time zone, so date.today() in a fixture and company_today() in the code agree at any hour. To test behaviour across time zones, give a company a named timezone rather than relying on when the suite runs.
  • When the run finishes it drops the database and its filestore — also when it fails or is stopped (Ctrl-C, SIGTERM) while the database is still being installed. A run killed outright (SIGKILL) is cleaned up by the next run, which reaps the database and filestore of any run idle for over an hour. Your real/development databases are never touched.

So there is nothing to set up or tear down — just run test. (Because the whole suite installs into one database, a single view or model that fails to load anywhere in the dependency graph will fail the install and stop the run before any test executes; run a single --module to isolate which one.)

Test files in tests/ directories are not auto-loaded by the module system. They are only discovered and executed when you run the test command.

Each test should be independent and not rely on state from other tests:

# Good - creates its own data
async def test_order_total(self):
order = await self.create_test_order()
self.assertEqual(order.total, 100.0)
# Bad - relies on data from another test
async def test_order_total(self):
order = await Order.filter(name="SO-001").first() # May not exist
self.assertEqual(order.total, 100.0)

Use descriptive test names that explain what’s being tested:

# Good
async def test_order_total_includes_tax(self):
...
async def test_invoice_rejects_negative_amounts(self):
...
# Bad
async def test_order(self):
...
async def test_1(self):
...

Each test should verify one specific behavior:

# Good - focused tests
async def test_order_creation(self):
order = await Order.create(...)
self.assertIsNotNone(order.id)
async def test_order_line_subtotal(self):
line = await OrderLine.create(...)
self.assertEqual(line.subtotal, 50.0)
# Bad - testing too much
async def test_order_everything(self):
order = await Order.create(...)
self.assertIsNotNone(order.id)
self.assertEqual(order.state, "Draft")
await order.action_confirm()
self.assertEqual(order.state, "Confirmed")
# ... 50 more assertions

Create helper methods for commonly needed test data:

class TestOrder(TestCase):
async def create_test_product(self, **kwargs):
"""Helper to create a product for testing."""
Product = get_model("Product")
defaults = {"name": "Test Product", "price": 10.0}
defaults.update(kwargs)
return await Product.create(**defaults)
async def create_test_order(self, **kwargs):
"""Helper to create an order for testing."""
contact = await self.create_test_contact()
product = await self.create_test_product()
Order = get_model("Order")
return await Order.create(
contact=contact,
lines=[["create", {"product": product.id, "quantity": 1}]],
**kwargs
)
async def test_order_workflow(self):
order = await self.create_test_order()
# Test with clean, isolated data

A test never reaches a paid AI API. During a test run the Anthropic SDK’s clients (anthropic.AsyncAnthropic, anthropic.Anthropic) raise as soon as anything constructs one, so code that calls a model must be given a fake answer by the test.

Patch the function that makes the call, and patch every loaded copy of the module that holds it. A helper module imported relatively by a model (from .. import _helper) and imported by absolute path in a test (from custom.my_module import _helper) can be two separate module objects; patching only the test’s copy leaves the model calling the real function. On a machine with a real API key that used to mean a billed call and a passing test. Now it means a failure that names the cause.

import sys
from contextlib import ExitStack
from unittest import mock
def _patch_everywhere(suffix, name, replacement):
stack = ExitStack()
for module_name, module in list(sys.modules.items()):
if module_name.endswith(suffix):
stack.enter_context(mock.patch.object(module, name, replacement))
return stack
async def test_the_summary_is_stored(self):
async def fake(messages):
return {"summary": "Three open tickets."}
with _patch_everywhere("my_module._summarizer", "_call_model", fake):
record = await get_model("MyRecord").summarize_today()
self.assertEqual(record.summary, "Three open tickets.")
"""
Tests for the Invoice model.
Run with:
fullfinity-server --config config.yaml test --module invoicing
"""
from fullfinity.engine.base import ValidationError, get_model
from fullfinity.engine.testing import TestCase
class TestInvoice(TestCase):
"""Test Invoice model operations."""
async def create_test_contact(self):
"""Create a test customer."""
Contact = get_model("Contact")
return await Contact.create(
name="Test Customer",
is_customer=True,
)
async def create_test_invoice(self, **kwargs):
"""Create a test invoice with defaults."""
Invoice = get_model("FinancialDocument")
contact = kwargs.pop("contact", None) or await self.create_test_contact()
return await Invoice.create(
type="Customer Invoice",
contact=contact,
**kwargs
)
async def add_line(self, invoice, quantity, unit_price):
"""Add one line booked to the company's default income account."""
income = await get_model("Account").resolve_role(
"default_income", company_id=invoice.company_id, required=True
)
await invoice.update(lines=[["create", {
"description": "Consulting",
"quantity": quantity,
"unit_price": unit_price,
"account": income.id,
}]])
async def test_create_draft_invoice(self):
"""Test creating a draft invoice."""
invoice = await self.create_test_invoice()
self.assertIsNotNone(invoice.id)
self.assertEqual(invoice.state, "Draft")
self.assertEqual(invoice.type, "Customer Invoice")
async def test_invoice_requires_contact(self):
"""Test that invoice requires a contact."""
Invoice = get_model("FinancialDocument")
with self.assertRaises(ValidationError): # a required field left blank
await Invoice.create(type="Customer Invoice")
async def test_post_invoice(self):
"""Test posting an invoice."""
invoice = await self.create_test_invoice()
await self.add_line(invoice, quantity=1, unit_price=50.0) # posting needs a line
self.assertEqual(invoice.state, "Draft")
await invoice.post()
self.assertEqual(invoice.state, "Posted")
self.assertIsNotNone(invoice.number) # Should have sequence number
async def test_invoice_total_computation(self):
"""Test that invoice total is computed correctly."""
invoice = await self.create_test_invoice()
await self.add_line(invoice, quantity=4, unit_price=25.0)
self.assertEqual(invoice.subtotal, 100.0)
class TestInvoicePayment(TestCase):
"""Test invoice payment operations."""
@TestCase.skip("Payment module integration pending")
async def test_register_payment(self):
"""Test registering a payment against an invoice."""
pass