Compare commits
23 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
87825d13d6 | ||
| 21a6a796cf | |||
|
|
ecd0a73bc8 | ||
|
|
39d61dc7ad | ||
|
|
43491359d9 | ||
| 5ed2cea7e9 | |||
|
|
cbb16a8d52 | ||
| 70e94a6ce0 | |||
|
|
b61a00003a | ||
| 52dba6f890 | |||
| 4242678aab | |||
|
|
b2e086d5ba | ||
| 07a9787570 | |||
|
|
4bf5dc3d58 | ||
| be3d269928 | |||
|
|
80a53fae94 | ||
| e15d2b6c2f | |||
|
|
7a52bf499e | ||
| 2489ec8d2d | |||
|
|
4a4f349805 | ||
| 517a268307 | |||
|
|
a94b2a97b1 | ||
| 542cdfbb82 |
@@ -151,6 +151,9 @@ jobs:
|
||||
--coverage.exclude='src/db/**' \
|
||||
--coverage.exclude='src/lib/**' \
|
||||
--coverage.exclude='src/types/**' \
|
||||
--coverage.exclude='**/index.tsx' \
|
||||
--coverage.exclude='**/vite-env.d.ts' \
|
||||
--coverage.exclude='**/vitest.setup.ts' \
|
||||
--reporter=verbose --includeTaskLocation --testTimeout=10000 --silent=passed-only --no-file-parallelism || true
|
||||
|
||||
echo "--- Running Integration Tests ---"
|
||||
@@ -162,6 +165,9 @@ jobs:
|
||||
--coverage.exclude='src/db/**' \
|
||||
--coverage.exclude='src/lib/**' \
|
||||
--coverage.exclude='src/types/**' \
|
||||
--coverage.exclude='**/index.tsx' \
|
||||
--coverage.exclude='**/vite-env.d.ts' \
|
||||
--coverage.exclude='**/vitest.setup.ts' \
|
||||
--reporter=verbose --includeTaskLocation --testTimeout=10000 --silent=passed-only || true
|
||||
|
||||
echo "--- Running E2E Tests ---"
|
||||
@@ -175,6 +181,9 @@ jobs:
|
||||
--coverage.exclude='src/db/**' \
|
||||
--coverage.exclude='src/lib/**' \
|
||||
--coverage.exclude='src/types/**' \
|
||||
--coverage.exclude='**/index.tsx' \
|
||||
--coverage.exclude='**/vite-env.d.ts' \
|
||||
--coverage.exclude='**/vitest.setup.ts' \
|
||||
--reporter=verbose --no-file-parallelism || true
|
||||
|
||||
# Re-enable secret masking for subsequent steps.
|
||||
@@ -246,7 +255,10 @@ jobs:
|
||||
--temp-dir "$NYC_SOURCE_DIR" \
|
||||
--exclude "**/*.test.ts" \
|
||||
--exclude "**/tests/**" \
|
||||
--exclude "**/mocks/**"
|
||||
--exclude "**/mocks/**" \
|
||||
--exclude "**/index.tsx" \
|
||||
--exclude "**/vite-env.d.ts" \
|
||||
--exclude "**/vitest.setup.ts"
|
||||
|
||||
# Re-enable secret masking for subsequent steps.
|
||||
echo "::secret-masking::"
|
||||
@@ -259,16 +271,6 @@ jobs:
|
||||
if: always() # This step runs even if the previous test or coverage steps failed.
|
||||
run: echo "Skipping test artifact cleanup on runner; this is handled on the server."
|
||||
|
||||
- name: Deploy Coverage Report to Public URL
|
||||
if: always()
|
||||
run: |
|
||||
TARGET_DIR="/var/www/flyer-crawler-test.projectium.com/coverage"
|
||||
echo "Deploying HTML coverage report to $TARGET_DIR..."
|
||||
mkdir -p "$TARGET_DIR"
|
||||
rm -rf "$TARGET_DIR"/*
|
||||
cp -r .coverage/* "$TARGET_DIR/"
|
||||
echo "✅ Coverage report deployed to https://flyer-crawler-test.projectium.com/coverage"
|
||||
|
||||
- name: Archive Code Coverage Report
|
||||
# This action saves the generated HTML coverage report as a downloadable artifact.
|
||||
uses: actions/upload-artifact@v3
|
||||
@@ -358,6 +360,17 @@ jobs:
|
||||
rsync -avz dist/ "$APP_PATH"
|
||||
echo "Application deployment complete."
|
||||
|
||||
- name: Deploy Coverage Report to Public URL
|
||||
if: always()
|
||||
run: |
|
||||
TARGET_DIR="/var/www/flyer-crawler-test.projectium.com/coverage"
|
||||
echo "Deploying HTML coverage report to $TARGET_DIR..."
|
||||
mkdir -p "$TARGET_DIR"
|
||||
rm -rf "$TARGET_DIR"/*
|
||||
# The merged nyc report is generated in the .coverage directory. We copy its contents.
|
||||
cp -r .coverage/* "$TARGET_DIR/"
|
||||
echo "✅ Coverage report deployed to https://flyer-crawler-test.projectium.com/coverage"
|
||||
|
||||
- name: Install Backend Dependencies and Restart Test Server
|
||||
env:
|
||||
# --- Test Secrets Injection ---
|
||||
|
||||
4
package-lock.json
generated
4
package-lock.json
generated
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "flyer-crawler",
|
||||
"version": "0.2.28",
|
||||
"version": "0.4.1",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "flyer-crawler",
|
||||
"version": "0.2.28",
|
||||
"version": "0.4.1",
|
||||
"dependencies": {
|
||||
"@bull-board/api": "^6.14.2",
|
||||
"@bull-board/express": "^6.14.2",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "flyer-crawler",
|
||||
"private": true,
|
||||
"version": "0.2.28",
|
||||
"version": "0.4.1",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "concurrently \"npm:start:dev\" \"vite\"",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// src/features/flyer/FlyerList.test.tsx
|
||||
import React from 'react';
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
|
||||
import { describe, it, expect, vi, beforeEach, type Mocked } from 'vitest';
|
||||
import { describe, it, expect, vi, beforeEach, afterEach, type Mocked } from 'vitest';
|
||||
import { FlyerList } from './FlyerList';
|
||||
import { formatShortDate } from './dateUtils';
|
||||
import type { Flyer, UserProfile } from '../../types';
|
||||
@@ -257,6 +257,73 @@ describe('FlyerList', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('Expiration Status Logic', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('should show "Expired" for past dates', () => {
|
||||
// Flyer 1 valid_to is 2023-10-11
|
||||
vi.setSystemTime(new Date('2023-10-12T12:00:00Z'));
|
||||
render(
|
||||
<FlyerList
|
||||
flyers={[mockFlyers[0]]}
|
||||
onFlyerSelect={mockOnFlyerSelect}
|
||||
selectedFlyerId={null}
|
||||
profile={mockProfile}
|
||||
/>,
|
||||
);
|
||||
expect(screen.getByText('Expired')).toBeInTheDocument();
|
||||
expect(screen.getByText('Expired')).toHaveClass('text-red-500');
|
||||
});
|
||||
|
||||
it('should show "Expires today" when valid_to is today', () => {
|
||||
vi.setSystemTime(new Date('2023-10-11T12:00:00Z'));
|
||||
render(
|
||||
<FlyerList
|
||||
flyers={[mockFlyers[0]]}
|
||||
onFlyerSelect={mockOnFlyerSelect}
|
||||
selectedFlyerId={null}
|
||||
profile={mockProfile}
|
||||
/>,
|
||||
);
|
||||
expect(screen.getByText('Expires today')).toBeInTheDocument();
|
||||
expect(screen.getByText('Expires today')).toHaveClass('text-orange-500');
|
||||
});
|
||||
|
||||
it('should show "Expires in X days" (orange) for <= 3 days', () => {
|
||||
vi.setSystemTime(new Date('2023-10-09T12:00:00Z')); // 2 days left
|
||||
render(
|
||||
<FlyerList
|
||||
flyers={[mockFlyers[0]]}
|
||||
onFlyerSelect={mockOnFlyerSelect}
|
||||
selectedFlyerId={null}
|
||||
profile={mockProfile}
|
||||
/>,
|
||||
);
|
||||
expect(screen.getByText('Expires in 2 days')).toBeInTheDocument();
|
||||
expect(screen.getByText('Expires in 2 days')).toHaveClass('text-orange-500');
|
||||
});
|
||||
|
||||
it('should show "Expires in X days" (green) for > 3 days', () => {
|
||||
vi.setSystemTime(new Date('2023-10-05T12:00:00Z')); // 6 days left
|
||||
render(
|
||||
<FlyerList
|
||||
flyers={[mockFlyers[0]]}
|
||||
onFlyerSelect={mockOnFlyerSelect}
|
||||
selectedFlyerId={null}
|
||||
profile={mockProfile}
|
||||
/>,
|
||||
);
|
||||
expect(screen.getByText('Expires in 6 days')).toBeInTheDocument();
|
||||
expect(screen.getByText('Expires in 6 days')).toHaveClass('text-green-600');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Admin Functionality', () => {
|
||||
const adminProfile: UserProfile = createMockUserProfile({
|
||||
user: { user_id: 'admin-1', email: 'admin@example.com' },
|
||||
|
||||
@@ -223,14 +223,10 @@ describe('FlyerUploader', () => {
|
||||
it('should handle a failed job', async () => {
|
||||
console.log('--- [TEST LOG] ---: 1. Setting up mocks for a failed job.');
|
||||
mockedAiApiClient.uploadAndProcessFlyer.mockResolvedValue({ jobId: 'job-fail' });
|
||||
mockedAiApiClient.getJobStatus.mockResolvedValue({
|
||||
state: 'failed',
|
||||
progress: {
|
||||
errorCode: 'UNKNOWN_ERROR',
|
||||
message: 'AI model exploded',
|
||||
},
|
||||
failedReason: 'This is the raw error message.', // The UI should prefer the progress message.
|
||||
});
|
||||
// The getJobStatus function throws a specific error when the job fails,
|
||||
// which is then caught by react-query and placed in the `error` state.
|
||||
const jobFailedError = new aiApiClientModule.JobFailedError('AI model exploded', 'UNKNOWN_ERROR');
|
||||
mockedAiApiClient.getJobStatus.mockRejectedValue(jobFailedError);
|
||||
|
||||
console.log('--- [TEST LOG] ---: 2. Rendering and uploading.');
|
||||
renderComponent();
|
||||
@@ -243,7 +239,8 @@ describe('FlyerUploader', () => {
|
||||
|
||||
try {
|
||||
console.log('--- [TEST LOG] ---: 4. AWAITING failure message...');
|
||||
expect(await screen.findByText(/Processing failed: AI model exploded/i)).toBeInTheDocument();
|
||||
// The UI should now display the error from the `pollError` state, which includes the "Polling failed" prefix.
|
||||
expect(await screen.findByText(/Polling failed: AI model exploded/i)).toBeInTheDocument();
|
||||
console.log('--- [TEST LOG] ---: 5. SUCCESS: Failure message found.');
|
||||
} catch (error) {
|
||||
console.error('--- [TEST LOG] ---: 5. ERROR: findByText for failure message timed out.');
|
||||
@@ -262,13 +259,10 @@ describe('FlyerUploader', () => {
|
||||
mockedAiApiClient.uploadAndProcessFlyer.mockResolvedValue({ jobId: 'job-fail-timeout' });
|
||||
|
||||
// We need at least one 'active' response to establish a timeout loop so we have something to clear
|
||||
// The second call should be a rejection, as this is how getJobStatus signals a failure.
|
||||
mockedAiApiClient.getJobStatus
|
||||
.mockResolvedValueOnce({ state: 'active', progress: { message: 'Working...' } })
|
||||
.mockResolvedValueOnce({
|
||||
state: 'failed',
|
||||
progress: { errorCode: 'UNKNOWN_ERROR', message: 'Fatal Error' },
|
||||
failedReason: 'Fatal Error',
|
||||
});
|
||||
.mockRejectedValueOnce(new aiApiClientModule.JobFailedError('Fatal Error', 'UNKNOWN_ERROR'));
|
||||
|
||||
renderComponent();
|
||||
const file = new File(['content'], 'flyer.pdf', { type: 'application/pdf' });
|
||||
@@ -280,7 +274,7 @@ describe('FlyerUploader', () => {
|
||||
await screen.findByText('Working...');
|
||||
|
||||
// Wait for the failure UI
|
||||
await waitFor(() => expect(screen.getByText(/Processing failed: Fatal Error/i)).toBeInTheDocument(), { timeout: 4000 });
|
||||
await waitFor(() => expect(screen.getByText(/Polling failed: Fatal Error/i)).toBeInTheDocument(), { timeout: 4000 });
|
||||
|
||||
// Verify clearTimeout was called
|
||||
expect(clearTimeoutSpy).toHaveBeenCalled();
|
||||
|
||||
@@ -236,6 +236,24 @@ describe('ShoppingListComponent (in shopping feature)', () => {
|
||||
alertSpy.mockRestore();
|
||||
});
|
||||
|
||||
it('should show a generic alert if reading aloud fails with a non-Error object', async () => {
|
||||
const alertSpy = vi.spyOn(window, 'alert').mockImplementation(() => {});
|
||||
vi.spyOn(aiApiClient, 'generateSpeechFromText').mockRejectedValue('A string error');
|
||||
|
||||
render(<ShoppingListComponent {...defaultProps} />);
|
||||
const readAloudButton = screen.getByTitle(/read list aloud/i);
|
||||
|
||||
fireEvent.click(readAloudButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(alertSpy).toHaveBeenCalledWith(
|
||||
'Could not read list aloud: An unknown error occurred while generating audio.',
|
||||
);
|
||||
});
|
||||
|
||||
alertSpy.mockRestore();
|
||||
});
|
||||
|
||||
it('should handle interactions with purchased items', () => {
|
||||
render(<ShoppingListComponent {...defaultProps} />);
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// src/features/shopping/ShoppingList.tsx
|
||||
import React, { useState, useMemo, useCallback, useEffect } from 'react';
|
||||
import React, { useState, useMemo, useCallback } from 'react';
|
||||
import type { ShoppingList, ShoppingListItem, User } from '../../types';
|
||||
import { UserIcon } from '../../components/icons/UserIcon';
|
||||
import { ListBulletIcon } from '../../components/icons/ListBulletIcon';
|
||||
@@ -56,28 +56,6 @@ export const ShoppingListComponent: React.FC<ShoppingListComponentProps> = ({
|
||||
return { neededItems, purchasedItems };
|
||||
}, [activeList]);
|
||||
|
||||
useEffect(() => {
|
||||
if (activeList) {
|
||||
console.log('ShoppingList Debug: Active List:', activeList.name);
|
||||
console.log(
|
||||
'ShoppingList Debug: Needed Items:',
|
||||
neededItems.map((i) => ({
|
||||
id: i.shopping_list_item_id,
|
||||
name: i.custom_item_name || i.master_item?.name,
|
||||
raw: i,
|
||||
})),
|
||||
);
|
||||
console.log(
|
||||
'ShoppingList Debug: Purchased Items:',
|
||||
purchasedItems.map((i) => ({
|
||||
id: i.shopping_list_item_id,
|
||||
name: i.custom_item_name || i.master_item?.name,
|
||||
raw: i,
|
||||
})),
|
||||
);
|
||||
}
|
||||
}, [activeList, neededItems, purchasedItems]);
|
||||
|
||||
const handleCreateList = async () => {
|
||||
const name = prompt('Enter a name for your new shopping list:');
|
||||
if (name && name.trim()) {
|
||||
|
||||
@@ -164,6 +164,15 @@ describe('WatchedItemsList (in shopping feature)', () => {
|
||||
expect(itemsDesc[1]).toHaveTextContent('Eggs');
|
||||
expect(itemsDesc[2]).toHaveTextContent('Bread');
|
||||
expect(itemsDesc[3]).toHaveTextContent('Apples');
|
||||
|
||||
// Click again to sort ascending
|
||||
fireEvent.click(sortButton);
|
||||
|
||||
const itemsAscAgain = screen.getAllByRole('listitem');
|
||||
expect(itemsAscAgain[0]).toHaveTextContent('Apples');
|
||||
expect(itemsAscAgain[1]).toHaveTextContent('Bread');
|
||||
expect(itemsAscAgain[2]).toHaveTextContent('Eggs');
|
||||
expect(itemsAscAgain[3]).toHaveTextContent('Milk');
|
||||
});
|
||||
|
||||
it('should call onAddItemToList when plus icon is clicked', () => {
|
||||
@@ -222,6 +231,18 @@ describe('WatchedItemsList (in shopping feature)', () => {
|
||||
fireEvent.change(nameInput, { target: { value: 'Grapes' } });
|
||||
expect(addButton).toBeDisabled();
|
||||
});
|
||||
|
||||
it('should not submit if form is submitted with invalid data', () => {
|
||||
render(<WatchedItemsList {...defaultProps} />);
|
||||
const nameInput = screen.getByPlaceholderText(/add item/i);
|
||||
const form = nameInput.closest('form')!;
|
||||
const categorySelect = screen.getByDisplayValue('Select a category');
|
||||
fireEvent.change(categorySelect, { target: { value: 'Dairy & Eggs' } });
|
||||
|
||||
fireEvent.change(nameInput, { target: { value: ' ' } });
|
||||
fireEvent.submit(form);
|
||||
expect(mockOnAddItem).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Error Handling', () => {
|
||||
|
||||
@@ -44,11 +44,16 @@ export const useFlyerUploader = () => {
|
||||
enabled: !!jobId,
|
||||
// Polling logic: react-query handles the interval
|
||||
refetchInterval: (query) => {
|
||||
const data = query.state.data;
|
||||
const data = query.state.data as JobStatus | undefined;
|
||||
// Stop polling if the job is completed or has failed
|
||||
if (data?.state === 'completed' || data?.state === 'failed') {
|
||||
return false;
|
||||
}
|
||||
// Also stop polling if the query itself has errored (e.g. network error, or JobFailedError thrown from getJobStatus)
|
||||
if (query.state.status === 'error') {
|
||||
logger.warn('[useFlyerUploader] Polling stopped due to query error state.');
|
||||
return false;
|
||||
}
|
||||
// Otherwise, poll every 3 seconds
|
||||
return 3000;
|
||||
},
|
||||
|
||||
@@ -495,6 +495,22 @@ describe('useShoppingLists Hook', () => {
|
||||
expect(currentLists[0].items).toHaveLength(1); // Length should remain 1
|
||||
console.log(' LOG: SUCCESS! Duplicate was not added and API was not called.');
|
||||
});
|
||||
|
||||
it('should log an error and not call the API if the listId does not exist', async () => {
|
||||
const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
const { result } = renderHook(() => useShoppingLists());
|
||||
|
||||
await act(async () => {
|
||||
// Call with a non-existent list ID (mock lists have IDs 1 and 2)
|
||||
await result.current.addItemToList(999, { customItemName: 'Wont be added' });
|
||||
});
|
||||
|
||||
// The API should not have been called because the list was not found.
|
||||
expect(mockAddItemApi).not.toHaveBeenCalled();
|
||||
expect(consoleErrorSpy).toHaveBeenCalledWith('useShoppingLists: List with ID 999 not found.');
|
||||
|
||||
consoleErrorSpy.mockRestore();
|
||||
});
|
||||
});
|
||||
|
||||
describe('updateItemInList', () => {
|
||||
@@ -689,11 +705,21 @@ describe('useShoppingLists Hook', () => {
|
||||
setupApiMocks(apiMocksWithError);
|
||||
apiMock.mockRejectedValue(new Error(errorMessage));
|
||||
|
||||
// Spy on console.error to ensure the catch block is executed for logging
|
||||
const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
|
||||
const { result } = renderHook(() => useShoppingLists());
|
||||
await act(async () => {
|
||||
await action(result.current);
|
||||
});
|
||||
await waitFor(() => expect(result.current.error).toBe(errorMessage));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.error).toBe(errorMessage);
|
||||
// Verify that our custom logging within the catch block was called
|
||||
expect(consoleErrorSpy).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
consoleErrorSpy.mockRestore();
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
@@ -113,13 +113,14 @@ describe('errorHandler Middleware', () => {
|
||||
expect(response.body.message).toBe('A generic server error occurred.');
|
||||
expect(response.body.stack).toBeDefined();
|
||||
expect(response.body.errorId).toEqual(expect.any(String));
|
||||
console.log('[DEBUG] errorHandler.test.ts: Received 500 error response with ID:', response.body.errorId);
|
||||
expect(mockLogger.error).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
err: expect.any(Error),
|
||||
errorId: expect.any(String),
|
||||
req: expect.objectContaining({ method: 'GET', url: '/generic-error' }),
|
||||
}),
|
||||
expect.stringMatching(/Unhandled API Error \(ID: \w+\)/),
|
||||
expect.stringMatching(/Unhandled API Error \(ID: [\w-]+\)/),
|
||||
);
|
||||
expect(consoleErrorSpy).toHaveBeenCalledWith(
|
||||
expect.stringMatching(/--- \[TEST\] UNHANDLED ERROR \(ID: \w+\) ---/),
|
||||
@@ -226,7 +227,7 @@ describe('errorHandler Middleware', () => {
|
||||
errorId: expect.any(String),
|
||||
req: expect.objectContaining({ method: 'GET', url: '/db-error-500' }),
|
||||
}),
|
||||
expect.stringMatching(/Unhandled API Error \(ID: \w+\)/),
|
||||
expect.stringMatching(/Unhandled API Error \(ID: [\w-]+\)/),
|
||||
);
|
||||
expect(consoleErrorSpy).toHaveBeenCalledWith(
|
||||
expect.stringMatching(/--- \[TEST\] UNHANDLED ERROR \(ID: \w+\) ---/),
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
// src/middleware/multer.middleware.test.ts
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import multer from 'multer';
|
||||
import type { Request, Response, NextFunction } from 'express';
|
||||
import { createUploadMiddleware, handleMulterError } from './multer.middleware';
|
||||
import { createMockUserProfile } from '../tests/utils/mockFactories';
|
||||
|
||||
// 1. Hoist the mocks so they can be referenced inside vi.mock factories.
|
||||
const mocks = vi.hoisted(() => ({
|
||||
@@ -28,10 +32,12 @@ vi.mock('../services/logger.server', () => ({
|
||||
// 4. Mock multer to prevent it from doing anything during import.
|
||||
vi.mock('multer', () => ({
|
||||
default: vi.fn(() => ({
|
||||
single: vi.fn(),
|
||||
array: vi.fn(),
|
||||
single: vi.fn().mockImplementation(() => (req: Request, res: Response, next: NextFunction) => next()),
|
||||
array: vi.fn().mockImplementation(() => (req: Request, res: Response, next: NextFunction) => next()),
|
||||
})),
|
||||
diskStorage: vi.fn(),
|
||||
// We mock diskStorage to capture the options passed to it, but let it return a plain object.
|
||||
// The actual storage logic is what we want to test.
|
||||
diskStorage: vi.fn((options) => options),
|
||||
}));
|
||||
|
||||
describe('Multer Middleware Directory Creation', () => {
|
||||
@@ -71,4 +77,163 @@ describe('Multer Middleware Directory Creation', () => {
|
||||
'Failed to create multer storage directories on startup.',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('createUploadMiddleware', () => {
|
||||
const mockFile = { originalname: 'test.png' } as Express.Multer.File;
|
||||
const mockUser = createMockUserProfile({ user: { user_id: 'user-123', email: 'test@user.com' } });
|
||||
let originalNodeEnv: string | undefined;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
originalNodeEnv = process.env.NODE_ENV;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
process.env.NODE_ENV = originalNodeEnv;
|
||||
});
|
||||
|
||||
describe('Avatar Storage', () => {
|
||||
it('should generate a unique filename for an authenticated user', () => {
|
||||
createUploadMiddleware({ storageType: 'avatar' });
|
||||
const storageOptions = vi.mocked(multer.diskStorage).mock.calls[0][0];
|
||||
const cb = vi.fn();
|
||||
const mockReq = { user: mockUser } as unknown as Request;
|
||||
|
||||
storageOptions.filename!(mockReq, mockFile, cb);
|
||||
|
||||
expect(cb).toHaveBeenCalledWith(null, expect.stringContaining('user-123-'));
|
||||
expect(cb).toHaveBeenCalledWith(null, expect.stringContaining('.png'));
|
||||
});
|
||||
|
||||
it('should call the callback with an error for an unauthenticated user', () => {
|
||||
// This test covers line 37
|
||||
createUploadMiddleware({ storageType: 'avatar' });
|
||||
const storageOptions = vi.mocked(multer.diskStorage).mock.calls[0][0];
|
||||
const cb = vi.fn();
|
||||
const mockReq = {} as Request; // No user on request
|
||||
|
||||
storageOptions.filename!(mockReq, mockFile, cb);
|
||||
|
||||
expect(cb).toHaveBeenCalledWith(
|
||||
new Error('User not authenticated for avatar upload'),
|
||||
expect.any(String),
|
||||
);
|
||||
});
|
||||
|
||||
it('should use a predictable filename in test environment', () => {
|
||||
process.env.NODE_ENV = 'test';
|
||||
createUploadMiddleware({ storageType: 'avatar' });
|
||||
const storageOptions = vi.mocked(multer.diskStorage).mock.calls[0][0];
|
||||
const cb = vi.fn();
|
||||
const mockReq = { user: mockUser } as unknown as Request;
|
||||
|
||||
storageOptions.filename!(mockReq, mockFile, cb);
|
||||
|
||||
expect(cb).toHaveBeenCalledWith(null, 'test-avatar.png');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Flyer Storage', () => {
|
||||
it('should generate a unique, sanitized filename in production environment', () => {
|
||||
process.env.NODE_ENV = 'production';
|
||||
const mockFlyerFile = {
|
||||
fieldname: 'flyerFile',
|
||||
originalname: 'My Flyer (Special!).pdf',
|
||||
} as Express.Multer.File;
|
||||
createUploadMiddleware({ storageType: 'flyer' });
|
||||
const storageOptions = vi.mocked(multer.diskStorage).mock.calls[0][0];
|
||||
const cb = vi.fn();
|
||||
const mockReq = {} as Request;
|
||||
|
||||
storageOptions.filename!(mockReq, mockFlyerFile, cb);
|
||||
|
||||
expect(cb).toHaveBeenCalledWith(
|
||||
null,
|
||||
expect.stringMatching(/^flyerFile-\d+-\d+-my-flyer-special.pdf$/),
|
||||
);
|
||||
});
|
||||
|
||||
it('should generate a predictable filename in test environment', () => {
|
||||
// This test covers lines 43-46
|
||||
process.env.NODE_ENV = 'test';
|
||||
const mockFlyerFile = {
|
||||
fieldname: 'flyerFile',
|
||||
originalname: 'test-flyer.jpg',
|
||||
} as Express.Multer.File;
|
||||
createUploadMiddleware({ storageType: 'flyer' });
|
||||
const storageOptions = vi.mocked(multer.diskStorage).mock.calls[0][0];
|
||||
const cb = vi.fn();
|
||||
const mockReq = {} as Request;
|
||||
|
||||
storageOptions.filename!(mockReq, mockFlyerFile, cb);
|
||||
|
||||
expect(cb).toHaveBeenCalledWith(null, 'flyerFile-test-flyer-image.jpg');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Image File Filter', () => {
|
||||
it('should accept files with an image mimetype', () => {
|
||||
createUploadMiddleware({ storageType: 'flyer', fileFilter: 'image' });
|
||||
const multerOptions = vi.mocked(multer).mock.calls[0][0];
|
||||
const cb = vi.fn();
|
||||
const mockImageFile = { mimetype: 'image/png' } as Express.Multer.File;
|
||||
|
||||
multerOptions!.fileFilter!({} as Request, mockImageFile, cb);
|
||||
|
||||
expect(cb).toHaveBeenCalledWith(null, true);
|
||||
});
|
||||
|
||||
it('should reject files without an image mimetype', () => {
|
||||
createUploadMiddleware({ storageType: 'flyer', fileFilter: 'image' });
|
||||
const multerOptions = vi.mocked(multer).mock.calls[0][0];
|
||||
const cb = vi.fn();
|
||||
const mockTextFile = { mimetype: 'text/plain' } as Express.Multer.File;
|
||||
|
||||
multerOptions!.fileFilter!({} as Request, mockTextFile, cb);
|
||||
|
||||
expect(cb).toHaveBeenCalledWith(new Error('Only image files are allowed!'));
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('handleMulterError Middleware', () => {
|
||||
let mockRequest: Partial<Request>;
|
||||
let mockResponse: Partial<Response>;
|
||||
let mockNext: NextFunction;
|
||||
|
||||
beforeEach(() => {
|
||||
mockRequest = {};
|
||||
mockResponse = {
|
||||
status: vi.fn().mockReturnThis(),
|
||||
json: vi.fn(),
|
||||
};
|
||||
mockNext = vi.fn();
|
||||
});
|
||||
|
||||
it('should handle a MulterError (e.g., file too large)', () => {
|
||||
const err = new multer.MulterError('LIMIT_FILE_SIZE');
|
||||
handleMulterError(err, mockRequest as Request, mockResponse as Response, mockNext);
|
||||
expect(mockResponse.status).toHaveBeenCalledWith(400);
|
||||
expect(mockResponse.json).toHaveBeenCalledWith({
|
||||
message: 'File upload error: File too large',
|
||||
});
|
||||
expect(mockNext).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should handle the custom image file filter error', () => {
|
||||
// This test covers lines 59-61
|
||||
const err = new Error('Only image files are allowed!');
|
||||
handleMulterError(err, mockRequest as Request, mockResponse as Response, mockNext);
|
||||
expect(mockResponse.status).toHaveBeenCalledWith(400);
|
||||
expect(mockResponse.json).toHaveBeenCalledWith({ message: 'Only image files are allowed!' });
|
||||
expect(mockNext).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should pass on non-multer errors to the next error handler', () => {
|
||||
const err = new Error('A generic error');
|
||||
handleMulterError(err, mockRequest as Request, mockResponse as Response, mockNext);
|
||||
expect(mockNext).toHaveBeenCalledWith(err);
|
||||
expect(mockResponse.status).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import { render, screen, waitFor } from '@testing-library/react';
|
||||
import { render, screen, waitFor, within } from '@testing-library/react';
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { FlyerReviewPage } from './FlyerReviewPage';
|
||||
import { MemoryRouter } from 'react-router-dom';
|
||||
@@ -74,6 +74,13 @@ describe('FlyerReviewPage', () => {
|
||||
store: { name: 'Store B' },
|
||||
icon_url: 'icon2.jpg',
|
||||
},
|
||||
{
|
||||
flyer_id: 3,
|
||||
file_name: 'flyer3.jpg',
|
||||
created_at: '2023-01-03T00:00:00Z',
|
||||
store: null,
|
||||
icon_url: null,
|
||||
},
|
||||
];
|
||||
|
||||
vi.mocked(apiClient.getFlyersForReview).mockResolvedValue({
|
||||
@@ -95,6 +102,14 @@ describe('FlyerReviewPage', () => {
|
||||
expect(screen.getByText('flyer1.jpg')).toBeInTheDocument();
|
||||
expect(screen.getByText('Store B')).toBeInTheDocument();
|
||||
expect(screen.getByText('flyer2.jpg')).toBeInTheDocument();
|
||||
|
||||
// Test fallback for null store and icon_url
|
||||
expect(screen.getByText('Unknown Store')).toBeInTheDocument();
|
||||
expect(screen.getByText('flyer3.jpg')).toBeInTheDocument();
|
||||
const unknownStoreItem = screen.getByText('Unknown Store').closest('li');
|
||||
const unknownStoreImage = within(unknownStoreItem!).getByRole('img');
|
||||
expect(unknownStoreImage).toHaveAttribute('src', '');
|
||||
expect(unknownStoreImage).not.toHaveAttribute('alt');
|
||||
});
|
||||
|
||||
it('renders error message when API response is not ok', async () => {
|
||||
@@ -140,4 +155,24 @@ describe('FlyerReviewPage', () => {
|
||||
'Failed to fetch flyers for review'
|
||||
);
|
||||
});
|
||||
|
||||
it('renders a generic error for non-Error rejections', async () => {
|
||||
const nonErrorRejection = { message: 'This is not an Error object' };
|
||||
vi.mocked(apiClient.getFlyersForReview).mockRejectedValue(nonErrorRejection);
|
||||
|
||||
render(
|
||||
<MemoryRouter>
|
||||
<FlyerReviewPage />
|
||||
</MemoryRouter>,
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('An unknown error occurred while fetching data.')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
expect(logger.error).toHaveBeenCalledWith(
|
||||
{ err: nonErrorRejection },
|
||||
'Failed to fetch flyers for review',
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
createMockSuggestedCorrection,
|
||||
createMockBrand,
|
||||
createMockRecipe,
|
||||
createMockFlyer,
|
||||
createMockRecipeComment,
|
||||
createMockUnmatchedFlyerItem,
|
||||
} from '../tests/utils/mockFactories';
|
||||
@@ -38,9 +39,11 @@ const { mockedDb } = vi.hoisted(() => {
|
||||
rejectCorrection: vi.fn(),
|
||||
updateSuggestedCorrection: vi.fn(),
|
||||
getUnmatchedFlyerItems: vi.fn(),
|
||||
getFlyersForReview: vi.fn(), // Added for flyer review tests
|
||||
updateRecipeStatus: vi.fn(),
|
||||
updateRecipeCommentStatus: vi.fn(),
|
||||
updateBrandLogo: vi.fn(),
|
||||
getApplicationStats: vi.fn(),
|
||||
},
|
||||
flyerRepo: {
|
||||
getAllBrands: vi.fn(),
|
||||
@@ -225,6 +228,39 @@ describe('Admin Content Management Routes (/api/admin)', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('Flyer Review Routes', () => {
|
||||
it('GET /review/flyers should return flyers for review', async () => {
|
||||
const mockFlyers = [
|
||||
createMockFlyer({ flyer_id: 1, status: 'needs_review' }),
|
||||
createMockFlyer({ flyer_id: 2, status: 'needs_review' }),
|
||||
];
|
||||
vi.mocked(mockedDb.adminRepo.getFlyersForReview).mockResolvedValue(mockFlyers);
|
||||
const response = await supertest(app).get('/api/admin/review/flyers');
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body).toEqual(mockFlyers);
|
||||
expect(vi.mocked(mockedDb.adminRepo.getFlyersForReview)).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
);
|
||||
});
|
||||
|
||||
it('GET /review/flyers should return 500 on DB error', async () => {
|
||||
vi.mocked(mockedDb.adminRepo.getFlyersForReview).mockRejectedValue(new Error('DB Error'));
|
||||
const response = await supertest(app).get('/api/admin/review/flyers');
|
||||
expect(response.status).toBe(500);
|
||||
expect(response.body.message).toBe('DB Error');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Stats Routes', () => {
|
||||
// This test covers the error path for GET /stats
|
||||
it('GET /stats should return 500 on DB error', async () => {
|
||||
vi.mocked(mockedDb.adminRepo.getApplicationStats).mockRejectedValue(new Error('DB Error'));
|
||||
const response = await supertest(app).get('/api/admin/stats');
|
||||
expect(response.status).toBe(500);
|
||||
expect(response.body.message).toBe('DB Error');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Brand Routes', () => {
|
||||
it('GET /brands should return a list of all brands', async () => {
|
||||
const mockBrands: Brand[] = [createMockBrand({ brand_id: 1, name: 'Brand A' })];
|
||||
@@ -282,6 +318,16 @@ describe('Admin Content Management Routes (/api/admin)', () => {
|
||||
expect(fs.unlink).toHaveBeenCalledWith(expect.stringContaining('logoImage-'));
|
||||
});
|
||||
|
||||
it('POST /brands/:id/logo should return 400 if a non-image file is uploaded', async () => {
|
||||
const brandId = 55;
|
||||
const response = await supertest(app)
|
||||
.post(`/api/admin/brands/${brandId}/logo`)
|
||||
.attach('logoImage', Buffer.from('this is not an image'), 'document.txt');
|
||||
expect(response.status).toBe(400);
|
||||
// This message comes from the handleMulterError middleware for the imageFileFilter
|
||||
expect(response.body.message).toBe('File upload error: Only image files are allowed!');
|
||||
});
|
||||
|
||||
it('POST /brands/:id/logo should return 400 for an invalid brand ID', async () => {
|
||||
const response = await supertest(app)
|
||||
.post('/api/admin/brands/abc/logo')
|
||||
|
||||
@@ -4,7 +4,7 @@ import supertest from 'supertest';
|
||||
import type { Request, Response, NextFunction } from 'express';
|
||||
import { createMockUserProfile, createMockAdminUserView } from '../tests/utils/mockFactories';
|
||||
import type { UserProfile, Profile } from '../types';
|
||||
import { NotFoundError } from '../services/db/errors.db';
|
||||
import { NotFoundError, ValidationError } from '../services/db/errors.db';
|
||||
import { createTestApp } from '../tests/utils/createTestApp';
|
||||
|
||||
vi.mock('../services/db/index.db', () => ({
|
||||
@@ -22,6 +22,12 @@ vi.mock('../services/db/index.db', () => ({
|
||||
notificationRepo: {},
|
||||
}));
|
||||
|
||||
vi.mock('../services/userService', () => ({
|
||||
userService: {
|
||||
deleteUserAsAdmin: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
// Mock other dependencies that are not directly tested but are part of the adminRouter setup
|
||||
vi.mock('../services/db/flyer.db');
|
||||
vi.mock('../services/db/recipe.db');
|
||||
@@ -53,6 +59,7 @@ import adminRouter from './admin.routes';
|
||||
|
||||
// Import the mocked repos to control them in tests
|
||||
import { adminRepo, userRepo } from '../services/db/index.db';
|
||||
import { userService } from '../services/userService';
|
||||
|
||||
// Mock the passport middleware
|
||||
vi.mock('./passport.routes', () => ({
|
||||
@@ -191,22 +198,28 @@ describe('Admin User Management Routes (/api/admin/users)', () => {
|
||||
it('should successfully delete a user', async () => {
|
||||
const targetId = '123e4567-e89b-12d3-a456-426614174999';
|
||||
vi.mocked(userRepo.deleteUserById).mockResolvedValue(undefined);
|
||||
vi.mocked(userService.deleteUserAsAdmin).mockResolvedValue(undefined);
|
||||
const response = await supertest(app).delete(`/api/admin/users/${targetId}`);
|
||||
expect(response.status).toBe(204);
|
||||
expect(userRepo.deleteUserById).toHaveBeenCalledWith(targetId, expect.any(Object));
|
||||
expect(userService.deleteUserAsAdmin).toHaveBeenCalledWith(adminId, targetId, expect.any(Object));
|
||||
});
|
||||
|
||||
it('should prevent an admin from deleting their own account', async () => {
|
||||
const validationError = new ValidationError([], 'Admins cannot delete their own account.');
|
||||
vi.mocked(userService.deleteUserAsAdmin).mockRejectedValue(validationError);
|
||||
const response = await supertest(app).delete(`/api/admin/users/${adminId}`);
|
||||
expect(response.status).toBe(400);
|
||||
expect(response.body.message).toMatch(/Admins cannot delete their own account/);
|
||||
expect(userRepo.deleteUserById).not.toHaveBeenCalled();
|
||||
expect(userService.deleteUserAsAdmin).toHaveBeenCalledWith(adminId, adminId, expect.any(Object));
|
||||
});
|
||||
|
||||
it('should return 500 on a generic database error', async () => {
|
||||
const targetId = '123e4567-e89b-12d3-a456-426614174999';
|
||||
const dbError = new Error('DB Error');
|
||||
vi.mocked(userRepo.deleteUserById).mockRejectedValue(dbError);
|
||||
vi.mocked(userService.deleteUserAsAdmin).mockRejectedValue(dbError);
|
||||
const response = await supertest(app).delete(`/api/admin/users/${targetId}`);
|
||||
expect(response.status).toBe(500);
|
||||
});
|
||||
|
||||
@@ -164,11 +164,12 @@ describe('Health Routes (/api/health)', () => {
|
||||
expect(response.body.message).toBe('DB connection failed'); // This is the message from the original error
|
||||
expect(response.body.stack).toBeDefined();
|
||||
expect(response.body.errorId).toEqual(expect.any(String));
|
||||
console.log('[DEBUG] health.routes.test.ts: Verifying logger.error for DB schema check failure');
|
||||
expect(mockLogger.error).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
err: expect.any(Error),
|
||||
}),
|
||||
expect.stringMatching(/Unhandled API Error \(ID: \w+\)/),
|
||||
expect.stringMatching(/Unhandled API Error \(ID: [\w-]+\)/),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -186,7 +187,7 @@ describe('Health Routes (/api/health)', () => {
|
||||
expect.objectContaining({
|
||||
err: expect.objectContaining({ message: 'DB connection failed' }),
|
||||
}),
|
||||
expect.stringMatching(/Unhandled API Error \(ID: \w+\)/),
|
||||
expect.stringMatching(/Unhandled API Error \(ID: [\w-]+\)/),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -220,7 +221,7 @@ describe('Health Routes (/api/health)', () => {
|
||||
expect.objectContaining({
|
||||
err: expect.any(Error),
|
||||
}),
|
||||
expect.stringMatching(/Unhandled API Error \(ID: \w+\)/),
|
||||
expect.stringMatching(/Unhandled API Error \(ID: [\w-]+\)/),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -239,7 +240,7 @@ describe('Health Routes (/api/health)', () => {
|
||||
expect.objectContaining({
|
||||
err: expect.any(Error),
|
||||
}),
|
||||
expect.stringMatching(/Unhandled API Error \(ID: \w+\)/),
|
||||
expect.stringMatching(/Unhandled API Error \(ID: [\w-]+\)/),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -300,7 +301,7 @@ describe('Health Routes (/api/health)', () => {
|
||||
expect.objectContaining({
|
||||
err: expect.any(Error),
|
||||
}),
|
||||
expect.stringMatching(/Unhandled API Error \(ID: \w+\)/),
|
||||
expect.stringMatching(/Unhandled API Error \(ID: [\w-]+\)/),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -321,7 +322,7 @@ describe('Health Routes (/api/health)', () => {
|
||||
expect.objectContaining({
|
||||
err: expect.objectContaining({ message: 'Pool is not initialized' }),
|
||||
}),
|
||||
expect.stringMatching(/Unhandled API Error \(ID: \w+\)/),
|
||||
expect.stringMatching(/Unhandled API Error \(ID: [\w-]+\)/),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -336,11 +337,12 @@ describe('Health Routes (/api/health)', () => {
|
||||
expect(response.body.message).toBe('Connection timed out');
|
||||
expect(response.body.stack).toBeDefined();
|
||||
expect(response.body.errorId).toEqual(expect.any(String));
|
||||
console.log('[DEBUG] health.routes.test.ts: Checking if logger.error was called with the correct pattern');
|
||||
expect(mockLogger.error).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
err: expect.any(Error),
|
||||
}),
|
||||
expect.stringMatching(/Unhandled API Error \(ID: \w+\)/),
|
||||
expect.stringMatching(/Unhandled API Error \(ID: [\w-]+\)/),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -357,7 +359,7 @@ describe('Health Routes (/api/health)', () => {
|
||||
expect.objectContaining({
|
||||
err: expect.any(Error),
|
||||
}),
|
||||
expect.stringMatching(/Unhandled API Error \(ID: \w+\)/),
|
||||
expect.stringMatching(/Unhandled API Error \(ID: [\w-]+\)/),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,51 +1,15 @@
|
||||
// src/routes/system.routes.test.ts
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import supertest from 'supertest';
|
||||
import { exec, type ExecException, type ExecOptions } from 'child_process';
|
||||
import { geocodingService } from '../services/geocodingService.server';
|
||||
import { createTestApp } from '../tests/utils/createTestApp';
|
||||
|
||||
// FIX: Mock util.promisify to correctly handle child_process.exec's (err, stdout, stderr) signature.
|
||||
// This is required because the standard util.promisify relies on internal symbols on the real exec function,
|
||||
// which are missing on our Vitest mock. Without this, promisify(mockExec) drops the stdout/stderr arguments.
|
||||
vi.mock('util', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('util')>();
|
||||
return {
|
||||
...actual,
|
||||
default: actual,
|
||||
promisify: (fn: Function) => {
|
||||
return (...args: any[]) => {
|
||||
return new Promise((resolve, reject) => {
|
||||
fn(...args, (err: Error | null, stdout: unknown, stderr: unknown) => {
|
||||
if (err) {
|
||||
// Attach stdout/stderr to the error object to mimic child_process.exec behavior
|
||||
Object.assign(err, { stdout, stderr });
|
||||
reject(err);
|
||||
} else {
|
||||
resolve({ stdout, stderr });
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
// FIX: Use the simple factory pattern for child_process to avoid default export issues
|
||||
vi.mock('child_process', () => {
|
||||
const mockExec = vi.fn((command, callback) => {
|
||||
if (typeof callback === 'function') {
|
||||
callback(null, 'PM2 OK', '');
|
||||
}
|
||||
return { unref: () => {} };
|
||||
});
|
||||
|
||||
return {
|
||||
default: { exec: mockExec },
|
||||
exec: mockExec,
|
||||
};
|
||||
});
|
||||
|
||||
// 1. Mock the Service Layer
|
||||
// This decouples the route test from the service's implementation details.
|
||||
vi.mock('../services/systemService', () => ({
|
||||
systemService: {
|
||||
getPm2Status: vi.fn(),
|
||||
},
|
||||
}));
|
||||
// 2. Mock Geocoding
|
||||
vi.mock('../services/geocodingService.server', () => ({
|
||||
geocodingService: {
|
||||
@@ -65,46 +29,24 @@ vi.mock('../services/logger.server', () => ({
|
||||
}));
|
||||
|
||||
// Import the router AFTER all mocks are defined to ensure systemService picks up the mocked util.promisify
|
||||
import { systemService } from '../services/systemService';
|
||||
import systemRouter from './system.routes';
|
||||
import { geocodingService } from '../services/geocodingService.server';
|
||||
|
||||
describe('System Routes (/api/system)', () => {
|
||||
const app = createTestApp({ router: systemRouter, basePath: '/api/system' });
|
||||
|
||||
beforeEach(() => {
|
||||
// We cast here to get type-safe access to mock functions like .mockImplementation
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('GET /pm2-status', () => {
|
||||
it('should return success: true when pm2 process is online', async () => {
|
||||
// Arrange: Simulate a successful `pm2 describe` output for an online process.
|
||||
const pm2OnlineOutput = `
|
||||
┌─ PM2 info ────────────────┐
|
||||
│ status │ online │
|
||||
└───────────┴───────────┘
|
||||
`;
|
||||
|
||||
type ExecCallback = (error: ExecException | null, stdout: string, stderr: string) => void;
|
||||
|
||||
// A robust mock for `exec` that handles its multiple overloads.
|
||||
// This avoids the complex and error-prone `...args` signature.
|
||||
vi.mocked(exec).mockImplementation(
|
||||
(
|
||||
command: string,
|
||||
options?: ExecOptions | ExecCallback | null,
|
||||
callback?: ExecCallback | null,
|
||||
) => {
|
||||
// The actual callback can be the second or third argument.
|
||||
const actualCallback = (
|
||||
typeof options === 'function' ? options : callback
|
||||
) as ExecCallback;
|
||||
if (actualCallback) {
|
||||
actualCallback(null, pm2OnlineOutput, '');
|
||||
}
|
||||
// Return a minimal object that satisfies the ChildProcess type for .unref()
|
||||
return { unref: () => {} } as ReturnType<typeof exec>;
|
||||
},
|
||||
);
|
||||
vi.mocked(systemService.getPm2Status).mockResolvedValue({
|
||||
success: true,
|
||||
message: 'Application is online and running under PM2.',
|
||||
});
|
||||
|
||||
// Act
|
||||
const response = await supertest(app).get('/api/system/pm2-status');
|
||||
@@ -118,28 +60,10 @@ describe('System Routes (/api/system)', () => {
|
||||
});
|
||||
|
||||
it('should return success: false when pm2 process is stopped or errored', async () => {
|
||||
const pm2StoppedOutput = `│ status │ stopped │`;
|
||||
|
||||
vi.mocked(exec).mockImplementation(
|
||||
(
|
||||
command: string,
|
||||
options?:
|
||||
| ExecOptions
|
||||
| ((error: ExecException | null, stdout: string, stderr: string) => void)
|
||||
| null,
|
||||
callback?: ((error: ExecException | null, stdout: string, stderr: string) => void) | null,
|
||||
) => {
|
||||
const actualCallback = (typeof options === 'function' ? options : callback) as (
|
||||
error: ExecException | null,
|
||||
stdout: string,
|
||||
stderr: string,
|
||||
) => void;
|
||||
if (actualCallback) {
|
||||
actualCallback(null, pm2StoppedOutput, '');
|
||||
}
|
||||
return { unref: () => {} } as ReturnType<typeof exec>;
|
||||
},
|
||||
);
|
||||
vi.mocked(systemService.getPm2Status).mockResolvedValue({
|
||||
success: false,
|
||||
message: 'Application process exists but is not online.',
|
||||
});
|
||||
|
||||
const response = await supertest(app).get('/api/system/pm2-status');
|
||||
|
||||
@@ -150,33 +74,10 @@ describe('System Routes (/api/system)', () => {
|
||||
|
||||
it('should return success: false when pm2 process does not exist', async () => {
|
||||
// Arrange: Simulate `pm2 describe` failing because the process isn't found.
|
||||
const processNotFoundOutput =
|
||||
"[PM2][ERROR] Process or Namespace flyer-crawler-api doesn't exist";
|
||||
const processNotFoundError = new Error(
|
||||
'Command failed: pm2 describe flyer-crawler-api',
|
||||
) as ExecException;
|
||||
processNotFoundError.code = 1;
|
||||
|
||||
vi.mocked(exec).mockImplementation(
|
||||
(
|
||||
command: string,
|
||||
options?:
|
||||
| ExecOptions
|
||||
| ((error: ExecException | null, stdout: string, stderr: string) => void)
|
||||
| null,
|
||||
callback?: ((error: ExecException | null, stdout: string, stderr: string) => void) | null,
|
||||
) => {
|
||||
const actualCallback = (typeof options === 'function' ? options : callback) as (
|
||||
error: ExecException | null,
|
||||
stdout: string,
|
||||
stderr: string,
|
||||
) => void;
|
||||
if (actualCallback) {
|
||||
actualCallback(processNotFoundError, processNotFoundOutput, '');
|
||||
}
|
||||
return { unref: () => {} } as ReturnType<typeof exec>;
|
||||
},
|
||||
);
|
||||
vi.mocked(systemService.getPm2Status).mockResolvedValue({
|
||||
success: false,
|
||||
message: 'Application process is not running under PM2.',
|
||||
});
|
||||
|
||||
// Act
|
||||
const response = await supertest(app).get('/api/system/pm2-status');
|
||||
@@ -191,55 +92,17 @@ describe('System Routes (/api/system)', () => {
|
||||
|
||||
it('should return 500 if pm2 command produces stderr output', async () => {
|
||||
// Arrange: Simulate a successful exit code but with content in stderr.
|
||||
const stderrOutput = 'A non-fatal warning occurred.';
|
||||
|
||||
vi.mocked(exec).mockImplementation(
|
||||
(
|
||||
command: string,
|
||||
options?:
|
||||
| ExecOptions
|
||||
| ((error: ExecException | null, stdout: string, stderr: string) => void)
|
||||
| null,
|
||||
callback?: ((error: ExecException | null, stdout: string, stderr: string) => void) | null,
|
||||
) => {
|
||||
const actualCallback = (typeof options === 'function' ? options : callback) as (
|
||||
error: ExecException | null,
|
||||
stdout: string,
|
||||
stderr: string,
|
||||
) => void;
|
||||
if (actualCallback) {
|
||||
actualCallback(null, 'Some stdout', stderrOutput);
|
||||
}
|
||||
return { unref: () => {} } as ReturnType<typeof exec>;
|
||||
},
|
||||
);
|
||||
const serviceError = new Error('PM2 command produced an error: A non-fatal warning occurred.');
|
||||
vi.mocked(systemService.getPm2Status).mockRejectedValue(serviceError);
|
||||
|
||||
const response = await supertest(app).get('/api/system/pm2-status');
|
||||
expect(response.status).toBe(500);
|
||||
expect(response.body.message).toBe(`PM2 command produced an error: ${stderrOutput}`);
|
||||
expect(response.body.message).toBe(serviceError.message);
|
||||
});
|
||||
|
||||
it('should return 500 on a generic exec error', async () => {
|
||||
vi.mocked(exec).mockImplementation(
|
||||
(
|
||||
command: string,
|
||||
options?:
|
||||
| ExecOptions
|
||||
| ((error: ExecException | null, stdout: string, stderr: string) => void)
|
||||
| null,
|
||||
callback?: ((error: ExecException | null, stdout: string, stderr: string) => void) | null,
|
||||
) => {
|
||||
const actualCallback = (typeof options === 'function' ? options : callback) as (
|
||||
error: ExecException | null,
|
||||
stdout: string,
|
||||
stderr: string,
|
||||
) => void;
|
||||
if (actualCallback) {
|
||||
actualCallback(new Error('System error') as ExecException, '', 'stderr output');
|
||||
}
|
||||
return { unref: () => {} } as ReturnType<typeof exec>;
|
||||
},
|
||||
);
|
||||
const serviceError = new Error('System error');
|
||||
vi.mocked(systemService.getPm2Status).mockRejectedValue(serviceError);
|
||||
|
||||
// Act
|
||||
const response = await supertest(app).get('/api/system/pm2-status');
|
||||
|
||||
@@ -109,7 +109,10 @@ export class AIService {
|
||||
private fs: IFileSystem;
|
||||
private rateLimiter: <T>(fn: () => Promise<T>) => Promise<T>;
|
||||
private logger: Logger;
|
||||
private readonly models = ['gemini-2.5-flash', 'gemini-3-flash', 'gemini-2.5-flash-lite'];
|
||||
// The fallback list is ordered by preference (speed/cost vs. power).
|
||||
// We try the fastest models first, then the more powerful 'pro' model as a high-quality fallback,
|
||||
// and finally the 'lite' model as a last resort.
|
||||
private readonly models = [ 'gemini-3-flash-preview', 'gemini-2.5-flash', 'gemini-2.5-flash-lite'];
|
||||
|
||||
constructor(logger: Logger, aiClient?: IAiClient, fs?: IFileSystem) {
|
||||
this.logger = logger;
|
||||
@@ -230,7 +233,8 @@ export class AIService {
|
||||
errorMessage.includes('quota') ||
|
||||
errorMessage.includes('429') || // HTTP 429 Too Many Requests
|
||||
errorMessage.includes('resource_exhausted') || // Make case-insensitive
|
||||
errorMessage.includes('model is overloaded')
|
||||
errorMessage.includes('model is overloaded') ||
|
||||
errorMessage.includes('not found') // Also retry if model is not found (e.g., regional availability or API version issue)
|
||||
) {
|
||||
this.logger.warn(
|
||||
`[AIService Adapter] Model '${modelName}' failed due to quota/rate limit. Trying next model. Error: ${errorMessage}`,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
// src/services/analyticsService.server.test.ts
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { AnalyticsService } from './analyticsService.server';
|
||||
import { logger } from './logger.server';
|
||||
@@ -127,12 +128,19 @@ describe('AnalyticsService', () => {
|
||||
throw new Error('Processing failed');
|
||||
}); // "Successfully generated..."
|
||||
|
||||
// Get the promise from the service method.
|
||||
const promise = service.processWeeklyReportJob(job);
|
||||
|
||||
// Capture the expectation promise BEFORE triggering the rejection.
|
||||
const expectation = expect(promise).rejects.toThrow('Processing failed');
|
||||
|
||||
// Advance timers to trigger the part of the code that throws.
|
||||
await vi.advanceTimersByTimeAsync(30000);
|
||||
|
||||
await expect(promise).rejects.toThrow('Processing failed');
|
||||
// Await the expectation to ensure assertions ran.
|
||||
await expectation;
|
||||
|
||||
// Verify the side effect (error logging) after the rejection is confirmed.
|
||||
expect(mockLoggerInstance.error).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
err: expect.any(Error),
|
||||
|
||||
@@ -1,70 +1,17 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
|
||||
// Set environment variables before importing the service
|
||||
process.env.JWT_SECRET = 'test-secret';
|
||||
process.env.FRONTEND_URL = 'http://localhost:3000';
|
||||
|
||||
import { authService } from './authService';
|
||||
import * as bcrypt from 'bcrypt';
|
||||
import jwt from 'jsonwebtoken';
|
||||
import crypto from 'crypto';
|
||||
import { userRepo, adminRepo } from './db/index.db';
|
||||
import { UniqueConstraintError } from './db/errors.db';
|
||||
import { logger } from './logger.server';
|
||||
import { sendPasswordResetEmail } from './emailService.server';
|
||||
import type { UserProfile } from '../types';
|
||||
|
||||
// Mock dependencies
|
||||
vi.mock('bcrypt');
|
||||
vi.mock('jsonwebtoken');
|
||||
vi.mock('crypto', () => ({
|
||||
default: {
|
||||
randomBytes: vi.fn().mockReturnValue({
|
||||
toString: vi.fn().mockReturnValue('mocked-random-string'),
|
||||
}),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('./db/index.db', () => ({
|
||||
userRepo: {
|
||||
createUser: vi.fn(),
|
||||
saveRefreshToken: vi.fn(),
|
||||
findUserByEmail: vi.fn(),
|
||||
createPasswordResetToken: vi.fn(),
|
||||
getValidResetTokens: vi.fn(),
|
||||
updateUserPassword: vi.fn(),
|
||||
deleteResetToken: vi.fn(),
|
||||
findUserByRefreshToken: vi.fn(),
|
||||
findUserProfileById: vi.fn(),
|
||||
deleteRefreshToken: vi.fn(),
|
||||
},
|
||||
adminRepo: {
|
||||
logActivity: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('./logger.server', () => ({
|
||||
logger: {
|
||||
info: vi.fn(),
|
||||
error: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
debug: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('./emailService.server', () => ({
|
||||
sendPasswordResetEmail: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('./db/connection.db', () => ({
|
||||
getPool: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../utils/authUtils', () => ({
|
||||
validatePasswordStrength: vi.fn(),
|
||||
}));
|
||||
import type * as jsonwebtoken from 'jsonwebtoken';
|
||||
|
||||
describe('AuthService', () => {
|
||||
let authService: typeof import('./authService').authService;
|
||||
let bcrypt: typeof import('bcrypt');
|
||||
let jwt: typeof jsonwebtoken & { default: typeof jsonwebtoken };
|
||||
let userRepo: typeof import('./db/index.db').userRepo;
|
||||
let adminRepo: typeof import('./db/index.db').adminRepo;
|
||||
let logger: typeof import('./logger.server').logger;
|
||||
let sendPasswordResetEmail: typeof import('./emailService.server').sendPasswordResetEmail;
|
||||
let UniqueConstraintError: typeof import('./db/errors.db').UniqueConstraintError;
|
||||
|
||||
const reqLog = {}; // Mock request logger object
|
||||
const mockUser = {
|
||||
user_id: 'user-123',
|
||||
@@ -76,8 +23,53 @@ describe('AuthService', () => {
|
||||
role: 'user',
|
||||
} as unknown as UserProfile;
|
||||
|
||||
beforeEach(() => {
|
||||
beforeEach(async () => {
|
||||
vi.clearAllMocks();
|
||||
vi.resetModules();
|
||||
|
||||
// Set environment variables before any modules are imported
|
||||
process.env.JWT_SECRET = 'test-secret';
|
||||
process.env.FRONTEND_URL = 'http://localhost:3000';
|
||||
|
||||
// Mock all dependencies before dynamically importing the service
|
||||
// Core modules like bcrypt, jsonwebtoken, and crypto are now mocked globally in tests-setup-unit.ts
|
||||
vi.mock('bcrypt');
|
||||
vi.mock('./db/index.db', () => ({
|
||||
userRepo: {
|
||||
createUser: vi.fn(),
|
||||
saveRefreshToken: vi.fn(),
|
||||
findUserByEmail: vi.fn(),
|
||||
createPasswordResetToken: vi.fn(),
|
||||
getValidResetTokens: vi.fn(),
|
||||
updateUserPassword: vi.fn(),
|
||||
deleteResetToken: vi.fn(),
|
||||
findUserByRefreshToken: vi.fn(),
|
||||
findUserProfileById: vi.fn(),
|
||||
deleteRefreshToken: vi.fn(),
|
||||
},
|
||||
adminRepo: {
|
||||
logActivity: vi.fn(),
|
||||
},
|
||||
}));
|
||||
vi.mock('./logger.server', () => ({
|
||||
logger: { info: vi.fn(), error: vi.fn(), warn: vi.fn(), debug: vi.fn() },
|
||||
}));
|
||||
vi.mock('./emailService.server', () => ({
|
||||
sendPasswordResetEmail: vi.fn(),
|
||||
}));
|
||||
vi.mock('./db/connection.db', () => ({ getPool: vi.fn() }));
|
||||
vi.mock('../utils/authUtils', () => ({ validatePasswordStrength: vi.fn() }));
|
||||
|
||||
// Dynamically import modules to get the mocked versions and the service instance
|
||||
authService = (await import('./authService')).authService;
|
||||
bcrypt = await import('bcrypt');
|
||||
jwt = (await import('jsonwebtoken')) as typeof jwt;
|
||||
const dbModule = await import('./db/index.db');
|
||||
userRepo = dbModule.userRepo;
|
||||
adminRepo = dbModule.adminRepo;
|
||||
logger = (await import('./logger.server')).logger;
|
||||
sendPasswordResetEmail = (await import('./emailService.server')).sendPasswordResetEmail;
|
||||
UniqueConstraintError = (await import('./db/errors.db')).UniqueConstraintError;
|
||||
});
|
||||
|
||||
describe('registerUser', () => {
|
||||
@@ -140,7 +132,10 @@ describe('AuthService', () => {
|
||||
// Mock registerUser logic (since we can't easily spy on the same class instance method without prototype spying, we rely on the underlying calls)
|
||||
vi.mocked(bcrypt.hash).mockImplementation(async () => 'hashed-password');
|
||||
vi.mocked(userRepo.createUser).mockResolvedValue(mockUserProfile);
|
||||
vi.mocked(jwt.sign).mockImplementation(() => 'access-token' as any);
|
||||
// FIX: The global mock for jsonwebtoken provides a `default` export.
|
||||
// The code under test (`authService`) uses `import jwt from 'jsonwebtoken'`, so it gets the default export.
|
||||
// We must mock `jwt.default.sign` to affect the code under test.
|
||||
vi.mocked(jwt.default.sign).mockImplementation(() => 'access-token');
|
||||
|
||||
const result = await authService.registerAndLoginUser(
|
||||
'test@example.com',
|
||||
@@ -153,11 +148,11 @@ describe('AuthService', () => {
|
||||
expect(result).toEqual({
|
||||
newUserProfile: mockUserProfile,
|
||||
accessToken: 'access-token',
|
||||
refreshToken: 'mocked-random-string',
|
||||
refreshToken: 'mocked_random_id',
|
||||
});
|
||||
expect(userRepo.saveRefreshToken).toHaveBeenCalledWith(
|
||||
'user-123',
|
||||
'mocked-random-string',
|
||||
'mocked_random_id',
|
||||
reqLog,
|
||||
);
|
||||
});
|
||||
@@ -165,11 +160,14 @@ describe('AuthService', () => {
|
||||
|
||||
describe('generateAuthTokens', () => {
|
||||
it('should generate access and refresh tokens', () => {
|
||||
vi.mocked(jwt.sign).mockImplementation(() => 'access-token' as any);
|
||||
// FIX: The global mock for jsonwebtoken provides a `default` export.
|
||||
// The code under test (`authService`) uses `import jwt from 'jsonwebtoken'`, so it gets the default export.
|
||||
// We must mock `jwt.default.sign` to affect the code under test.
|
||||
vi.mocked(jwt.default.sign).mockImplementation(() => 'access-token');
|
||||
|
||||
const result = authService.generateAuthTokens(mockUserProfile);
|
||||
|
||||
expect(jwt.sign).toHaveBeenCalledWith(
|
||||
expect(vi.mocked(jwt.default.sign)).toHaveBeenCalledWith(
|
||||
{
|
||||
user_id: 'user-123',
|
||||
email: 'test@example.com',
|
||||
@@ -180,7 +178,7 @@ describe('AuthService', () => {
|
||||
);
|
||||
expect(result).toEqual({
|
||||
accessToken: 'access-token',
|
||||
refreshToken: 'mocked-random-string',
|
||||
refreshToken: 'mocked_random_id',
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -220,14 +218,14 @@ describe('AuthService', () => {
|
||||
);
|
||||
expect(sendPasswordResetEmail).toHaveBeenCalledWith(
|
||||
'test@example.com',
|
||||
expect.stringContaining('/reset-password/mocked-random-string'),
|
||||
expect.stringContaining('/reset-password/mocked_random_id'),
|
||||
reqLog,
|
||||
);
|
||||
expect(result).toBe('mocked-random-string');
|
||||
expect(result).toBe('mocked_random_id');
|
||||
});
|
||||
|
||||
it('should log warning and return undefined for non-existent user', async () => {
|
||||
vi.mocked(userRepo.findUserByEmail).mockResolvedValue(null);
|
||||
vi.mocked(userRepo.findUserByEmail).mockResolvedValue(undefined);
|
||||
|
||||
const result = await authService.resetPassword('unknown@example.com', reqLog);
|
||||
|
||||
@@ -295,7 +293,7 @@ describe('AuthService', () => {
|
||||
});
|
||||
|
||||
it('should return null if token not found', async () => {
|
||||
vi.mocked(userRepo.findUserByRefreshToken).mockResolvedValue(null);
|
||||
vi.mocked(userRepo.findUserByRefreshToken).mockResolvedValue(undefined);
|
||||
|
||||
const result = await authService.getUserByRefreshToken('invalid-token', reqLog);
|
||||
|
||||
@@ -322,7 +320,10 @@ describe('AuthService', () => {
|
||||
it('should return new access token if user found', async () => {
|
||||
vi.mocked(userRepo.findUserByRefreshToken).mockResolvedValue({ user_id: 'user-123' } as any);
|
||||
vi.mocked(userRepo.findUserProfileById).mockResolvedValue(mockUserProfile);
|
||||
vi.mocked(jwt.sign).mockImplementation(() => 'new-access-token' as any);
|
||||
// FIX: The global mock for jsonwebtoken provides a `default` export.
|
||||
// The code under test (`authService`) uses `import jwt from 'jsonwebtoken'`, so it gets the default export.
|
||||
// We must mock `jwt.default.sign` to affect the code under test.
|
||||
vi.mocked(jwt.default.sign).mockImplementation(() => 'new-access-token');
|
||||
|
||||
const result = await authService.refreshAccessToken('valid-token', reqLog);
|
||||
|
||||
@@ -330,7 +331,7 @@ describe('AuthService', () => {
|
||||
});
|
||||
|
||||
it('should return null if user not found', async () => {
|
||||
vi.mocked(userRepo.findUserByRefreshToken).mockResolvedValue(null);
|
||||
vi.mocked(userRepo.findUserByRefreshToken).mockResolvedValue(undefined);
|
||||
const result = await authService.refreshAccessToken('invalid-token', reqLog);
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
@@ -409,24 +409,18 @@ describe('FlyerProcessingService', () => {
|
||||
mockFileHandler.prepareImageInputs.mockRejectedValue(fileTypeError);
|
||||
const { logger } = await import('./logger.server');
|
||||
|
||||
const reportErrorSpy = vi.spyOn(service as any, '_reportErrorAndThrow');
|
||||
|
||||
await expect(service.processJob(job)).rejects.toThrow(UnsupportedFileTypeError);
|
||||
expect(job.updateProgress).toHaveBeenCalledWith({
|
||||
errorCode: 'UNSUPPORTED_FILE_TYPE',
|
||||
message: 'Unsupported file type: .txt. Supported types are PDF, JPG, PNG, WEBP, HEIC, HEIF, GIF, TIFF, SVG, BMP.',
|
||||
stages: [
|
||||
{ name: 'Preparing Inputs', status: 'failed', critical: true, detail: 'Unsupported file type: .txt. Supported types are PDF, JPG, PNG, WEBP, HEIC, HEIF, GIF, TIFF, SVG, BMP.' },
|
||||
{ name: 'Extracting Data with AI', status: 'skipped', critical: true, detail: 'Communicating with AI model...' },
|
||||
{ name: 'Transforming AI Data', status: 'skipped', critical: true },
|
||||
{ name: 'Saving to Database', status: 'skipped', critical: true },
|
||||
],
|
||||
});
|
||||
|
||||
expect(reportErrorSpy).toHaveBeenCalledWith(fileTypeError, job, expect.any(Object), expect.any(Array));
|
||||
expect(mockCleanupQueue.add).not.toHaveBeenCalled();
|
||||
expect(logger.warn).toHaveBeenCalledWith(
|
||||
'Job failed. Temporary files will NOT be cleaned up to allow for manual inspection.',
|
||||
);
|
||||
});
|
||||
|
||||
it('should throw an error and not enqueue cleanup if icon generation fails', async () => {
|
||||
it('should delegate to _reportErrorAndThrow if icon generation fails', async () => {
|
||||
const job = createMockJob({});
|
||||
const { logger } = await import('./logger.server');
|
||||
const iconError = new Error('Icon generation failed.');
|
||||
@@ -435,18 +429,11 @@ describe('FlyerProcessingService', () => {
|
||||
// bubbling up from the icon generation step.
|
||||
vi.spyOn(FlyerDataTransformer.prototype, 'transform').mockRejectedValue(iconError);
|
||||
|
||||
const reportErrorSpy = vi.spyOn(service as any, '_reportErrorAndThrow');
|
||||
|
||||
await expect(service.processJob(job)).rejects.toThrow('Icon generation failed.');
|
||||
|
||||
expect(job.updateProgress).toHaveBeenCalledWith({
|
||||
errorCode: 'UNKNOWN_ERROR',
|
||||
message: 'Icon generation failed.',
|
||||
stages: [
|
||||
{ name: 'Preparing Inputs', status: 'completed', critical: true, detail: '1 page(s) ready for AI.' },
|
||||
{ name: 'Extracting Data with AI', status: 'completed', critical: true, detail: 'Communicating with AI model...' },
|
||||
{ name: 'Transforming AI Data', status: 'failed', critical: true, detail: 'Icon generation failed.' },
|
||||
{ name: 'Saving to Database', status: 'skipped', critical: true },
|
||||
],
|
||||
}); // This was a duplicate, fixed.
|
||||
expect(reportErrorSpy).toHaveBeenCalledWith(iconError, job, expect.any(Object), expect.any(Array));
|
||||
expect(mockCleanupQueue.add).not.toHaveBeenCalled();
|
||||
expect(logger.warn).toHaveBeenCalledWith(
|
||||
'Job failed. Temporary files will NOT be cleaned up to allow for manual inspection.',
|
||||
@@ -454,8 +441,58 @@ describe('FlyerProcessingService', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('_reportErrorAndThrow (private method)', () => {
|
||||
it('should update progress and throw UnrecoverableError for quota messages', async () => {
|
||||
describe('_reportErrorAndThrow (Error Reporting Logic)', () => {
|
||||
it('should update progress with a generic error and re-throw', async () => {
|
||||
const { logger } = await import('./logger.server');
|
||||
const job = createMockJob({});
|
||||
const genericError = new Error('A standard failure');
|
||||
const initialStages = [
|
||||
{ name: 'Stage 1', status: 'completed', critical: true, detail: 'Done' },
|
||||
{ name: 'Stage 2', status: 'in-progress', critical: true, detail: 'Working...' },
|
||||
{ name: 'Stage 3', status: 'pending', critical: true, detail: 'Waiting...' },
|
||||
];
|
||||
const privateMethod = (service as any)._reportErrorAndThrow;
|
||||
|
||||
await expect(privateMethod(genericError, job, logger, initialStages)).rejects.toThrow(genericError);
|
||||
|
||||
expect(job.updateProgress).toHaveBeenCalledWith({
|
||||
errorCode: 'UNKNOWN_ERROR',
|
||||
message: 'A standard failure',
|
||||
stages: [
|
||||
{ name: 'Stage 1', status: 'completed', critical: true, detail: 'Done' },
|
||||
{ name: 'Stage 2', status: 'failed', critical: true, detail: 'A standard failure' },
|
||||
{ name: 'Stage 3', status: 'skipped', critical: true },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it('should use toErrorPayload for FlyerProcessingError instances', async () => {
|
||||
const { logger } = await import('./logger.server');
|
||||
const job = createMockJob({});
|
||||
const validationError = new AiDataValidationError(
|
||||
'Validation failed',
|
||||
{ foo: 'bar' },
|
||||
{ raw: 'data' },
|
||||
);
|
||||
const initialStages = [
|
||||
{ name: 'Extracting Data with AI', status: 'in-progress', critical: true, detail: '...' },
|
||||
];
|
||||
const privateMethod = (service as any)._reportErrorAndThrow;
|
||||
|
||||
await expect(privateMethod(validationError, job, logger, initialStages)).rejects.toThrow(validationError);
|
||||
|
||||
expect(job.updateProgress).toHaveBeenCalledWith({
|
||||
errorCode: 'AI_VALIDATION_FAILED',
|
||||
message: "The AI couldn't read the flyer's format. Please try a clearer image or a different flyer.",
|
||||
validationErrors: { foo: 'bar' },
|
||||
rawData: { raw: 'data' },
|
||||
stages: [
|
||||
{ name: 'Extracting Data with AI', status: 'failed', critical: true, detail: "The AI couldn't read the flyer's format. Please try a clearer image or a different flyer." },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it('should throw UnrecoverableError for quota messages', async () => {
|
||||
const { logger } = await import('./logger.server');
|
||||
const job = createMockJob({});
|
||||
const quotaError = new Error('RESOURCE_EXHAUSTED');
|
||||
@@ -472,53 +509,35 @@ describe('FlyerProcessingService', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('should use toErrorPayload for FlyerProcessingError instances', async () => {
|
||||
const { logger } = await import('./logger.server');
|
||||
const job = createMockJob({});
|
||||
const validationError = new AiDataValidationError(
|
||||
'Validation failed',
|
||||
{ foo: 'bar' },
|
||||
{ raw: 'data' },
|
||||
);
|
||||
const privateMethod = (service as any)._reportErrorAndThrow;
|
||||
|
||||
await expect(privateMethod(validationError, job, logger, [])).rejects.toThrow(
|
||||
validationError,
|
||||
);
|
||||
|
||||
// The payload should now come from the error's `toErrorPayload` method
|
||||
expect(job.updateProgress).toHaveBeenCalledWith({
|
||||
errorCode: 'AI_VALIDATION_FAILED',
|
||||
message:
|
||||
"The AI couldn't read the flyer's format. Please try a clearer image or a different flyer.",
|
||||
validationErrors: { foo: 'bar' },
|
||||
rawData: { raw: 'data' },
|
||||
stages: [],
|
||||
});
|
||||
});
|
||||
|
||||
it('should update progress and re-throw standard errors', async () => {
|
||||
const { logger } = await import('./logger.server');
|
||||
const job = createMockJob({});
|
||||
const genericError = new Error('A standard failure');
|
||||
const privateMethod = (service as any)._reportErrorAndThrow;
|
||||
|
||||
await expect(privateMethod(genericError, job, logger, [])).rejects.toThrow(genericError);
|
||||
|
||||
expect(job.updateProgress).toHaveBeenCalledWith({
|
||||
errorCode: 'UNKNOWN_ERROR',
|
||||
message: 'A standard failure', // This was a duplicate, fixed.
|
||||
stages: [],
|
||||
});
|
||||
});
|
||||
|
||||
it('should wrap and throw non-Error objects', async () => {
|
||||
const { logger } = await import('./logger.server');
|
||||
const job = createMockJob({});
|
||||
const nonError = 'just a string error';
|
||||
const privateMethod = (service as any)._reportErrorAndThrow;
|
||||
|
||||
await expect(privateMethod(nonError, job, logger, [])).rejects.toThrow('just a string error');
|
||||
await expect(privateMethod(nonError, job, logger, [])).rejects.toThrow(
|
||||
'just a string error',
|
||||
);
|
||||
});
|
||||
|
||||
it('should correctly identify the failed stage based on error code', async () => {
|
||||
const { logger } = await import('./logger.server');
|
||||
const job = createMockJob({});
|
||||
const pdfError = new PdfConversionError('PDF failed');
|
||||
const initialStages = [
|
||||
{ name: 'Preparing Inputs', status: 'in-progress', critical: true, detail: '...' },
|
||||
{ name: 'Extracting Data with AI', status: 'pending', critical: true, detail: '...' },
|
||||
];
|
||||
const privateMethod = (service as any)._reportErrorAndThrow;
|
||||
|
||||
await expect(privateMethod(pdfError, job, logger, initialStages)).rejects.toThrow(pdfError);
|
||||
|
||||
expect(job.updateProgress).toHaveBeenCalledWith(expect.objectContaining({
|
||||
stages: [
|
||||
{ name: 'Preparing Inputs', status: 'failed', critical: true, detail: expect.any(String) },
|
||||
{ name: 'Extracting Data with AI', status: 'skipped', critical: true },
|
||||
],
|
||||
}));
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -242,7 +242,10 @@ export class FlyerProcessingService {
|
||||
// Mark subsequent critical stages as skipped
|
||||
for (let i = errorStageIndex + 1; i < stagesToReport.length; i++) {
|
||||
if (stagesToReport[i].critical) {
|
||||
stagesToReport[i] = { ...stagesToReport[i], status: 'skipped' };
|
||||
// When a stage is skipped, we don't need its previous 'detail' property.
|
||||
// This creates a clean 'skipped' state object by removing `detail` and keeping the rest.
|
||||
const { detail, ...restOfStage } = stagesToReport[i];
|
||||
stagesToReport[i] = { ...restOfStage, status: 'skipped' };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -190,7 +190,10 @@ describe('Worker Service Lifecycle', () => {
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
processExitSpy.mockRestore();
|
||||
if (processExitSpy && typeof processExitSpy.mockRestore === 'function') {
|
||||
console.log('[DEBUG] queueService.server.test.ts: Restoring process.exit spy');
|
||||
processExitSpy.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it('should close all workers, queues, the redis connection, and exit the process', async () => {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { exec, type ExecException } from 'child_process';
|
||||
// src/services/systemService.test.ts
|
||||
import { describe, it, expect, vi, beforeEach, Mock } from 'vitest';
|
||||
import { logger } from './logger.server';
|
||||
import type { ExecException } from 'child_process';
|
||||
|
||||
// Mock logger
|
||||
vi.mock('./logger.server', () => ({
|
||||
@@ -11,58 +12,28 @@ vi.mock('./logger.server', () => ({
|
||||
},
|
||||
}));
|
||||
|
||||
// Mock util.promisify to handle child_process.exec signature
|
||||
vi.mock('util', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('util')>();
|
||||
return {
|
||||
...actual,
|
||||
promisify: (fn: Function) => {
|
||||
return (...args: any[]) => {
|
||||
return new Promise((resolve, reject) => {
|
||||
fn(...args, (err: Error | null, stdout: string, stderr: string) => {
|
||||
if (err) {
|
||||
// Attach stdout/stderr to error for the catch block in service
|
||||
Object.assign(err, { stdout, stderr });
|
||||
reject(err);
|
||||
} else {
|
||||
resolve({ stdout, stderr });
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
// Mock child_process
|
||||
vi.mock('child_process', () => {
|
||||
const mockExec = vi.fn();
|
||||
return {
|
||||
exec: mockExec,
|
||||
};
|
||||
});
|
||||
|
||||
// Import service AFTER mocks to ensure top-level promisify uses the mock
|
||||
import { systemService } from './systemService';
|
||||
// Import the class, not the singleton instance, to apply Dependency Injection
|
||||
import { SystemService } from './systemService';
|
||||
|
||||
describe('SystemService', () => {
|
||||
let systemService: SystemService;
|
||||
let mockExecAsync: Mock;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
// Create a mock function for our dependency
|
||||
mockExecAsync = vi.fn();
|
||||
// Instantiate the service with the mock dependency
|
||||
systemService = new SystemService(mockExecAsync);
|
||||
});
|
||||
|
||||
describe('getPm2Status', () => {
|
||||
it('should return success: true when process is online', async () => {
|
||||
const stdout = `
|
||||
┌────┬──────────────────────┬──────────┐
|
||||
│ id │ name │ status │
|
||||
├────┼──────────────────────┼──────────┤
|
||||
│ 0 │ flyer-crawler-api │ online │
|
||||
└────┴──────────────────────┴──────────┘
|
||||
`;
|
||||
vi.mocked(exec).mockImplementation((cmd, callback: any) => {
|
||||
callback(null, stdout, '');
|
||||
return {} as any;
|
||||
});
|
||||
// This stdout mimics the output of `pm2 describe <app_name>`
|
||||
const stdout = `Describing process with id 0 - name flyer-crawler-api
|
||||
│ status │ online │
|
||||
│ name │ flyer-crawler-api │`;
|
||||
mockExecAsync.mockResolvedValue({ stdout, stderr: '' });
|
||||
|
||||
const result = await systemService.getPm2Status();
|
||||
|
||||
@@ -73,17 +44,10 @@ describe('SystemService', () => {
|
||||
});
|
||||
|
||||
it('should return success: false when process is stopped', async () => {
|
||||
const stdout = `
|
||||
┌────┬──────────────────────┬──────────┐
|
||||
│ id │ name │ status │
|
||||
├────┼──────────────────────┼──────────┤
|
||||
│ 0 │ flyer-crawler-api │ stopped │
|
||||
└────┴──────────────────────┴──────────┘
|
||||
`;
|
||||
vi.mocked(exec).mockImplementation((cmd, callback: any) => {
|
||||
callback(null, stdout, '');
|
||||
return {} as any;
|
||||
});
|
||||
const stdout = `Describing process with id 0 - name flyer-crawler-api
|
||||
│ status │ stopped │
|
||||
│ name │ flyer-crawler-api │`;
|
||||
mockExecAsync.mockResolvedValue({ stdout, stderr: '' });
|
||||
|
||||
const result = await systemService.getPm2Status();
|
||||
|
||||
@@ -94,12 +58,11 @@ describe('SystemService', () => {
|
||||
});
|
||||
|
||||
it('should throw error if stderr has content', async () => {
|
||||
vi.mocked(exec).mockImplementation((cmd, callback: any) => {
|
||||
callback(null, 'some stdout', 'some stderr warning');
|
||||
return {} as any;
|
||||
});
|
||||
mockExecAsync.mockResolvedValue({ stdout: 'some stdout', stderr: 'some stderr warning' });
|
||||
|
||||
await expect(systemService.getPm2Status()).rejects.toThrow('PM2 command produced an error: some stderr warning');
|
||||
await expect(systemService.getPm2Status()).rejects.toThrow(
|
||||
'PM2 command produced an error: some stderr warning',
|
||||
);
|
||||
});
|
||||
|
||||
it('should return success: false when process does not exist', async () => {
|
||||
@@ -107,10 +70,7 @@ describe('SystemService', () => {
|
||||
error.code = 1;
|
||||
error.stderr = "[PM2][ERROR] Process or Namespace flyer-crawler-api doesn't exist";
|
||||
|
||||
vi.mocked(exec).mockImplementation((cmd, callback: any) => {
|
||||
callback(error, '', error.stderr);
|
||||
return {} as any;
|
||||
});
|
||||
mockExecAsync.mockRejectedValue(error);
|
||||
|
||||
const result = await systemService.getPm2Status();
|
||||
|
||||
@@ -119,7 +79,7 @@ describe('SystemService', () => {
|
||||
message: 'Application process is not running under PM2.',
|
||||
});
|
||||
expect(logger.warn).toHaveBeenCalledWith(
|
||||
expect.stringContaining('PM2 process "flyer-crawler-api" not found')
|
||||
expect.stringContaining('PM2 process "flyer-crawler-api" not found'),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,14 +1,24 @@
|
||||
// src/services/systemService.ts
|
||||
import { exec } from 'child_process';
|
||||
import { exec as nodeExec, type ExecException } from 'child_process';
|
||||
import { promisify } from 'util';
|
||||
import { logger } from './logger.server';
|
||||
|
||||
const execAsync = promisify(exec);
|
||||
// Define a type for the exec function for better type safety and testability.
|
||||
// It matches the signature of a promisified child_process.exec.
|
||||
export type ExecAsync = (
|
||||
command: string,
|
||||
) => Promise<{ stdout: string; stderr: string }>;
|
||||
|
||||
export class SystemService {
|
||||
private execAsync: ExecAsync;
|
||||
|
||||
constructor(execAsync: ExecAsync) {
|
||||
this.execAsync = execAsync;
|
||||
}
|
||||
|
||||
class SystemService {
|
||||
async getPm2Status(): Promise<{ success: boolean; message: string }> {
|
||||
try {
|
||||
const { stdout, stderr } = await execAsync('pm2 describe flyer-crawler-api');
|
||||
const { stdout, stderr } = await this.execAsync('pm2 describe flyer-crawler-api');
|
||||
|
||||
// If the command runs but produces output on stderr, treat it as an error.
|
||||
// This handles cases where pm2 might issue warnings but still exit 0.
|
||||
@@ -21,7 +31,7 @@ class SystemService {
|
||||
? 'Application is online and running under PM2.'
|
||||
: 'Application process exists but is not online.';
|
||||
return { success: isOnline, message };
|
||||
} catch (error: any) {
|
||||
} catch (error: ExecException | any) {
|
||||
// If the command fails (non-zero exit code), check if it's because the process doesn't exist.
|
||||
// This is a normal "not found" case, not a system error.
|
||||
// The error message can be in stdout or stderr depending on the pm2 version.
|
||||
@@ -40,4 +50,6 @@ class SystemService {
|
||||
}
|
||||
}
|
||||
|
||||
export const systemService = new SystemService();
|
||||
// Instantiate the service with the real dependency for the application
|
||||
const realExecAsync = promisify(nodeExec);
|
||||
export const systemService = new SystemService(realExecAsync);
|
||||
@@ -116,6 +116,65 @@ afterEach(cleanup);
|
||||
// By placing mocks here, they are guaranteed to be hoisted and applied
|
||||
// before any test files are executed, preventing initialization errors.
|
||||
|
||||
// --- Centralized Core Node/NPM Module Mocks ---
|
||||
|
||||
// Mock 'util' to correctly handle the (err, stdout, stderr) signature of child_process.exec
|
||||
// when it's promisified. The standard util.promisify doesn't work on a simple vi.fn() mock.
|
||||
vi.mock('util', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('util')>();
|
||||
const mocked = {
|
||||
...actual,
|
||||
promisify: (fn: Function) => {
|
||||
return (...args: any[]) => {
|
||||
return new Promise((resolve, reject) => {
|
||||
fn(...args, (err: Error | null, stdout: string, stderr: string) => {
|
||||
if (err) {
|
||||
// Attach stdout/stderr to the error object to mimic child_process.exec behavior
|
||||
Object.assign(err, { stdout, stderr });
|
||||
reject(err);
|
||||
} else {
|
||||
resolve({ stdout, stderr });
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
},
|
||||
};
|
||||
return {
|
||||
...mocked,
|
||||
default: mocked,
|
||||
};
|
||||
});
|
||||
|
||||
// Mock 'jsonwebtoken'. The `default` key is crucial because the code under test
|
||||
// uses `import jwt from 'jsonwebtoken'`, which imports the default export.
|
||||
vi.mock('jsonwebtoken', () => ({
|
||||
default: {
|
||||
sign: vi.fn(),
|
||||
verify: vi.fn(),
|
||||
},
|
||||
// Also mock named exports for completeness.
|
||||
sign: vi.fn(),
|
||||
verify: vi.fn(),
|
||||
}));
|
||||
|
||||
// Mock 'bcrypt'. The service uses `import * as bcrypt from 'bcrypt'`.
|
||||
vi.mock('bcrypt');
|
||||
|
||||
// Mock 'crypto'. The service uses `import crypto from 'crypto'`.
|
||||
vi.mock('crypto', () => ({
|
||||
default: {
|
||||
randomBytes: vi.fn().mockReturnValue({
|
||||
toString: vi.fn().mockImplementation((encoding) => {
|
||||
const id = 'mocked_random_id';
|
||||
console.log(`[DEBUG] tests-setup-unit.ts: crypto.randomBytes mock returning "${id}" for encoding "${encoding}"`);
|
||||
return id;
|
||||
}),
|
||||
}),
|
||||
randomUUID: vi.fn().mockReturnValue('mocked_random_id'),
|
||||
},
|
||||
}));
|
||||
|
||||
// --- Global Mocks ---
|
||||
|
||||
// 1. Define the mock pool instance logic OUTSIDE the factory so it can be used
|
||||
|
||||
Reference in New Issue
Block a user