Harness test data

From Intense-Visions/harness-engineering · View interactive version

Harness test data is an AI agent skill from the GitHub repository Intense-Visions/harness-engineering. > Test factories, fixtures, database seeding, and test data isolation. Establishes patterns for creating realistic, composable test data without coupling tests to specific database states.

How to use this skill

Skill file

Harness Test Data

Test factories, fixtures, database seeding, and test data isolation. Establishes patterns for creating realistic, composable test data without coupling tests to specific database states.

When to Use

Process

Phase 1: DETECT -- Identify Models and Existing Patterns

  1. Catalog domain models. Scan for:
  1. Map model relationships. For each model, identify:
  1. Inventory existing test data patterns. Search for:
  1. Identify test data problems. Flag:
  1. Report findings. Summarize: models found, existing patterns, and specific problems to address.

Phase 2: DESIGN -- Choose Patterns and Plan Structure

  1. Select the factory pattern. Based on the project's language and conventions:
  1. Design the factory API. Each factory must support:
  1. Plan data relationships. Define how factories handle foreign keys:
  1. Design cleanup strategy. Choose based on test infrastructure:
  1. Define seed data tiers. Separate:

Phase 3: SCAFFOLD -- Generate Factories and Seed Scripts

  1. Create the factory directory structure. Follow the project's conventions:
  1. Generate a factory for each domain model. Each factory file contains:
  1. Generate a factory index. Create a barrel file that exports all factories for easy importing:

```

import { UserFactory, ProjectFactory, TaskFactory } from '../factories';

```

  1. Create seed scripts. Generate:
  1. Create cleanup utilities. Generate:
  1. Verify factories produce valid data. Write a smoke test that builds one instance of every factory and validates it against the model schema.

Phase 4: VALIDATE -- Verify Isolation, Composability, and Correctness

  1. Test factory defaults. For each factory, verify:
  1. Test factory composition. Verify:
  1. Test data isolation. Run the test suite with factory-generated data and verify:
  1. Test seed scripts. Verify:
  1. Run harness validate. Confirm the project passes all harness checks with factory infrastructure in place.

Graph Refresh

If a knowledge graph exists at .harness/graph/, refresh it after code changes to keep graph queries accurate:

harness scan [path]

Harness Integration

Success Criteria

Examples

Example: Fishery Factories for a TypeScript Project

SCAFFOLD -- User factory with traits:

// tests/factories/user.factory.ts
import { Factory } from 'fishery';
import { faker } from '@faker-js/faker';
import { User } from '../../src/types/user';

export const UserFactory = Factory.define<User>(({ sequence, params, transientParams }) => ({
  id: `user-${sequence}`,
  email: params.email ?? faker.internet.email(),
  name: params.name ?? faker.person.fullName(),
  role: params.role ?? 'member',
  status: params.status ?? 'active',
  createdAt: params.createdAt ?? faker.date.past(),
  updatedAt: new Date(),
}));

// Traits
export const AdminUser = UserFactory.params({ role: 'admin' });
export const InactiveUser = UserFactory.params({ status: 'inactive' });

SCAFFOLD -- Project factory with association:

// tests/factories/project.factory.ts
import { Factory } from 'fishery';
import { faker } from '@faker-js/faker';
import { Project } from '../../src/types/project';
import { UserFactory } from './user.factory';

export const ProjectFactory = Factory.define<Project>(({ sequence, associations }) => ({
  id: `project-${sequence}`,
  name: faker.commerce.productName(),
  description: faker.lorem.sentence(),
  owner: associations.owner ?? UserFactory.build(),
  ownerId: associations.owner?.id ?? `user-${sequence}`,
  status: 'active',
  createdAt: faker.date.past(),
}));

Example: factory_boy for a Django Project

SCAFFOLD -- Django model factories:

# tests/factories.py
import factory
from factory.django import DjangoModelFactory
from faker import Faker
from myapp.models import User, Organization, Project

fake = Faker()

class OrganizationFactory(DjangoModelFactory):
    class Meta:
        model = Organization

    name = factory.LazyFunction(lambda: fake.company())
    slug = factory.LazyAttribute(lambda o: o.name.lower().replace(' ', '-'))

class UserFactory(DjangoModelFactory):
    class Meta:
        model = User

    email = factory.LazyFunction(lambda: fake.unique.email())
    name = factory.LazyFunction(lambda: fake.name())
    organization = factory.SubFactory(OrganizationFactory)

    class Params:
        admin = factory.Trait(is_staff=True, is_superuser=True)

class ProjectFactory(DjangoModelFactory):
    class Meta:
        model = Project

    name = factory.LazyFunction(lambda: fake.catch_phrase())
    owner = factory.SubFactory(UserFactory)
    organization = factory.LazyAttribute(lambda p: p.owner.organization)

Usage in tests:

def test_project_belongs_to_owner_organization():
    project = ProjectFactory.create()
    assert project.organization == project.owner.organization

def test_admin_can_delete_any_project():
    admin = UserFactory.create(admin=True)
    project = ProjectFactory.create()
    assert admin.has_perm('delete_project', project)

Rationalizations to Reject

| Rationalization | Reality |

| ------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

| "The test only needs one user — I'll just hardcode userId: 1 rather than building a factory." | Hardcoded IDs cause silent test failures when the database is reset, when tests run in parallel, or when another test creates a conflicting record. Factories with sequences or UUIDs exist precisely to avoid this class of failure. One hardcoded ID is how fragile test suites start. |

| "The factory produces objects that are close enough to valid — the test just needs to override two fields anyway." | A factory that requires overrides to produce a valid object has wrong defaults. The factory's zero-override output must pass model validation. If it does not, the factory is documenting the wrong defaults and tests that rely on overrides will break when the model changes. |

| "Cleanup is handled by rolling back the test transaction — I don't need explicit teardown." | Transaction rollback works until it does not: tests that span multiple connections, tests that call external APIs, or tests that write to a queue or file system all escape the transaction. Explicit cleanup is the only strategy that covers all cases, including tests that use features you have not built yet. |

| "We can share the same seeded dataset across all integration tests to avoid the overhead of per-test factories." | Shared mutable data means test A's side effect becomes test B's precondition. When tests fail intermittently based on execution order, the root cause is always shared state. The overhead of per-test factory creation is small compared to the cost of debugging order-dependent failures. |

| "The model only has three fields — writing a factory is more overhead than just constructing the object inline." | Today's three-field model becomes tomorrow's ten-field model with required foreign keys. Inline construction scales linearly with model complexity. A factory written once absorbs all future field additions in one place. The overhead argument inverts as the codebase grows. |

Gates

Escalation

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.