Home Projects Portfolio Dashboard Export PDF Log in

Ensuring Robust Data Operations: Comprehensive Execution Tests for Voice Worker Capabilities

The ROMEROLUIS15/cronix project, focused on robust backend services, has significantly upgraded its voice-worker component's reliability. This critical worker handles various voice-driven commands that interact directly with our Supabase database. Historically, the voice-worker relied primarily on "fast-path" detection tests, which verified that the system correctly identified commands but didn't fully validate how these commands executed their core logic against the database.

The Need for Deeper Validation

The previous testing approach left a gap: while a command like "schedule appointment" might be correctly recognized, there was no comprehensive test verifying that it actually performed the correct INSERT operation into the appointments table with the right status, or that a "cancel appointment" command correctly issued an UPDATE to change a record's status. Such gaps can lead to subtle but critical bugs in data integrity and system behavior.

Implementing Comprehensive Execution Tests

To close this gap, a new suite of execution tests has been introduced, covering all 11 core capabilities of the voice-worker. These tests, built using Vitest, focus specifically on the execute() method of each capability, asserting its real-world impact on the database. This involved:

  1. Chainable Supabase Mocking: A sophisticated, chainable Supabase mock was developed. This mock allows tests to simulate database interactions precisely, from from() clauses to insert(), update(), select(), eq(), and more, without actually hitting the live database.
  2. Capability-Specific Assertions: Each capability now has dedicated tests verifying its specific database operation:
    • schedule: Verifies INSERT of a new appointment with status=pending.
    • reschedule: Checks for UPDATE of start_at and end_at for a matched appointment.
    • cancel: Confirms UPDATE of status=cancelled.
    • last-visit: Asserts SELECT for past ATTENDED history (completed/confirmed/pending).
    • list-appointments: Validates SELECT for the current day, excluding cancelled entries.
    • next-appointment: Verifies SELECT for the nearest future pending/confirmed appointment.
    • search-clients: Asserts SELECT returning a client's phone number.
    • get-services: Confirms SELECT listing active services.
    • create-client: Validates INSERT of a new client record.
    • delete-client: Checks for a soft-delete (UPDATE deleted_at) for clients with no future appointments.
    • available-slots: Verifies SELECT for free slots and asserts correct localToUTC conversion, guarding against a critical regression.

Enforcing Business Rules and Contracts

Beyond basic CRUD operations, these tests also rigorously enforce crucial business rules:

  • Business ID Scoping: Every operation is verified to be scoped by business_id (a key architectural constraint, referred to as "constitution section 4"), preventing cross-business data leakage.
  • Success/Error Contract: Tests confirm that each capability adheres to the { success: boolean, error?: string } contract (constitution section 2), ensuring consistent and predictable responses from the worker.

Illustrative Example: Testing a Schedule Capability

Here’s a simplified example demonstrating how a Supabase mock is used with Vitest to test an insert operation within a capability:

import { expect, test, vi } from 'vitest';
import { SupabaseClient } from '@supabase/supabase-js';

// Mock the Supabase client and its chainable methods
const mockSupabase = {
  from: vi.fn(() => mockSupabase),
  insert: vi.fn(() => mockSupabase),
  select: vi.fn(() => mockSupabase),
  update: vi.fn(() => mockSupabase),
  eq: vi.fn(() => mockSupabase),
  // Simulate a successful insertion result
  data: [],
  error: null
};

// A hypothetical ScheduleAppointment capability class
class ScheduleAppointment {
  constructor(private db: SupabaseClient) {}

  async execute(businessId: string, details: any): Promise<{ success: boolean; error?: string }> {
    try {
      const { data, error } = await this.db
        .from('appointments')
        .insert({
          business_id: businessId,
          client_id: details.clientId,
          service_id: details.serviceId,
          start_at: details.startAt,
          status: 'pending'
        });

      if (error) {
        return { success: false, error: error.message };
      }
      return { success: true };
    } catch (e: any) {
      return { success: false, error: e.message };
    }
  }
}

test('schedule capability inserts a pending appointment', async () => {
  const supabase = mockSupabase as unknown as SupabaseClient;
  const capability = new ScheduleAppointment(supabase);
  const businessId = 'org-123';
  const appointmentDetails = {
    clientId: 'user-abc',
    serviceId: 'service-xyz',
    startAt: '2024-07-25T09:00:00Z'
  };

  mockSupabase.insert.mockResolvedValueOnce({ data: [{ id: 'new-appt-id' }], error: null });

  const result = await capability.execute(businessId, appointmentDetails);

  expect(result.success).toBe(true);
  expect(mockSupabase.from).toHaveBeenCalledWith('appointments');
  expect(mockSupabase.insert).toHaveBeenCalledWith(expect.objectContaining({
    business_id: businessId,
    client_id: appointmentDetails.clientId,
    service_id: appointmentDetails.serviceId,
    status: 'pending'
  }));
});

This example demonstrates how the mock is configured to simulate the database response, allowing the test to verify both the call to insert with the correct payload and the expected success return value from the execute method.

Conclusion

The addition of these comprehensive execution tests for the voice-worker represents a significant leap in the stability and reliability of the cronix project. By rigorously validating every database interaction and enforcing critical business rules, we've increased confidence in our system's behavior and drastically reduced the risk of regressions. This approach ensures that our voice-driven commands not only perform their intended actions but do so correctly and securely.

Next Steps

Adopt a similar strategy for other critical components that interact heavily with external services or databases. Focus on creating robust mocks that allow for isolated, high-fidelity testing of these interactions, ensuring your system's core business logic is bulletproof.


Generated with Gitvlg.com

Ensuring Robust Data Operations: Comprehensive Execution Tests for Voice Worker Capabilities
Luis Romero

Luis Romero

Author

Share: