Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

🔇 refactor: Quiet Framework Logging in Unit Tests (#15363)

Danny Aviladc77b78d3e86
diff --git a/.env.example b/.env.example
index 514d4bbd50..a4b018bf50 100644
--- a/.env.example
+++ b/.env.example
@@ -192,6 +192,9 @@ CONSOLE_JSON=false
DEBUG_LOGGING=true
DEBUG_CONSOLE=false
+# Console verbosity: error, warn, info, http, verbose, debug, activity, silly, or
+# `silent` to turn console output off entirely. Defaults to `info`.
+# CONSOLE_LOG_LEVEL=info
# Set to false to disable file-backed Winston transports.
LOG_TO_FILE=true
# Set to true to enable agent debug logging
diff --git a/client/src/components/Appearance/LangSelector.spec.tsx b/client/src/components/Appearance/LangSelector.spec.tsx
index 012a6194aa..7640aa6169 100644
--- a/client/src/components/Appearance/LangSelector.spec.tsx
+++ b/client/src/components/Appearance/LangSelector.spec.tsx
@@ -1,6 +1,7 @@
import 'test/matchMedia.mock';
import React from 'react';
-import { render, fireEvent, waitFor } from '@testing-library/react';
+import { render, waitFor } from '@testing-library/react';
+import { clickDropdown, flushDropdownEffects } from 'test/dropdown';
import '@testing-library/jest-dom/extend-expect';
import { RecoilRoot } from 'recoil';
import { LangSelector } from './Selectors';
@@ -13,7 +14,7 @@ describe('LangSelector', () => {
mockOnChange = jest.fn();
});
- it('renders correctly', () => {
+ it('renders correctly', async () => {
global.ResizeObserver = class MockedResizeObserver {
observe = jest.fn();
unobserve = jest.fn();
@@ -28,6 +29,8 @@ describe('LangSelector', () => {
expect(getByText('Language')).toBeInTheDocument();
const dropdownButton = getByRole('combobox');
expect(dropdownButton).toHaveTextContent('English');
+
+ await flushDropdownEffects();
});
it('calls onChange when the select value changes', async () => {
@@ -46,10 +49,10 @@ describe('LangSelector', () => {
const dropdownButton = getByTestId('dropdown-menu');
- fireEvent.click(dropdownButton);
+ await clickDropdown(dropdownButton);
const italianOption = getByRole('option', { name: 'Italiano' });
- fireEvent.click(italianOption);
+ await clickDropdown(italianOption);
await waitFor(() => {
expect(mockOnChange).toHaveBeenCalledWith('it-IT');
diff --git a/client/src/components/Appearance/ThemeSelector.spec.tsx b/client/src/components/Appearance/ThemeSelector.spec.tsx
index 9fc0130807..ebb54c6978 100644
--- a/client/src/components/Appearance/ThemeSelector.spec.tsx
+++ b/client/src/components/Appearance/ThemeSelector.spec.tsx
@@ -1,7 +1,8 @@
// ThemeSelector.spec.tsx
import 'test/matchMedia.mock';
import React from 'react';
-import { render, fireEvent, waitFor } from '@testing-library/react';
+import { render, waitFor } from '@testing-library/react';
+import { clickDropdown, flushDropdownEffects } from 'test/dropdown';
import '@testing-library/jest-dom/extend-expect';
import { RecoilRoot } from 'recoil';
import { ThemeSelector } from './Selectors';
@@ -13,7 +14,7 @@ describe('ThemeSelector', () => {
mockOnChange = jest.fn();
});
- it('renders correctly', () => {
+ it('renders correctly', async () => {
global.ResizeObserver = class MockedResizeObserver {
observe = jest.fn();
unobserve = jest.fn();
@@ -28,6 +29,8 @@ describe('ThemeSelector', () => {
expect(getByText('Theme')).toBeInTheDocument();
const dropdownButton = getByRole('combobox');
expect(dropdownButton).toHaveTextContent('System');
+
+ await flushDropdownEffects();
});
it('calls onChange when the select value changes', async () => {
@@ -46,10 +49,10 @@ describe('ThemeSelector', () => {
const dropdownButton = getByTestId('theme-selector');
- fireEvent.click(dropdownButton);
+ await clickDropdown(dropdownButton);
const darkOption = getByText('Dark');
- fireEvent.click(darkOption);
+ await clickDropdown(darkOption);
await waitFor(() => {
expect(mockOnChange).toHaveBeenCalledWith('dark');
diff --git a/client/src/components/Chat/Messages/Content/__tests__/ContentParts.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/ContentParts.test.tsx
index 4bb8089aba..4930e7d8c6 100644
--- a/client/src/components/Chat/Messages/Content/__tests__/ContentParts.test.tsx
+++ b/client/src/components/Chat/Messages/Content/__tests__/ContentParts.test.tsx
@@ -29,6 +29,10 @@ jest.mock('~/Providers', () => {
SearchContext: {
Provider: ({ children }: { children: React.ReactNode }) => <>{children}</>,
},
+ /** `WebSearch` reads this; leaving it off the mock threw inside the render and
+ * the component's own catch swallowed it, so the sources path was dead here
+ * while the suite still passed. */
+ useSearchContext: () => ({ searchResults: undefined }),
};
});
diff --git a/client/src/components/Chat/Messages/Content/__tests__/MarkdownBlocks.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/MarkdownBlocks.test.tsx
index b681bc109a..835b24ee8a 100644
--- a/client/src/components/Chat/Messages/Content/__tests__/MarkdownBlocks.test.tsx
+++ b/client/src/components/Chat/Messages/Content/__tests__/MarkdownBlocks.test.tsx
@@ -1,12 +1,36 @@
import React from 'react';
import { RecoilRoot } from 'recoil';
import ReactMarkdown from 'react-markdown';
+import { MemoryRouter } from 'react-router-dom';
import { render, screen } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { getRemarkPlugins, getRehypePlugins, getMarkdownComponents } from '../markdownConfig';
import { ArtifactProvider, CodeBlockProvider } from '~/Providers';
import Markdown from '../Markdown';
+/**
+ * Mermaid blocks in the fixtures reach `useLocation`, so the markdown tree needs a
+ * router the same way it has one in the app — without it the diagram throws into its
+ * error boundary and the assertions compare two fallbacks instead of two renderers.
+ */
+const TestProviders = ({ children }: { children: React.ReactNode }) => (
+ <MemoryRouter>
+ <RecoilRoot>{children}</RecoilRoot>
+ </MemoryRouter>
+);
+
+/**
+ * `mermaid` ships ESM that this suite's transform does not cover, so the real
+ * component only ever reaches its error boundary here. Stub it — these cases
+ * assert code-block indices, and a fallback on both sides of the comparison
+ * would hide a genuine divergence between the two renderers.
+ */
+jest.mock('~/components/Messages/Content/Mermaid', () => ({
+ __esModule: true,
+ default: ({ id }: { id?: string }) => <div data-testid="mermaid" data-id={String(id)} />,
+ MermaidErrorBoundary: ({ children }: { children: React.ReactNode }) => <>{children}</>,
+}));
+
/**
* Stub CodeBlock so we can read the blockIndex each executable code block
* receives, while still exercising the real `code` override's skip/single-line
@@ -57,15 +81,15 @@ const streamThrough = (
): HTMLElement => {
const lines = content.split('\n');
const { container, rerender } = render(
- <RecoilRoot>
+ <TestProviders>
<Component content={lines[0]} />
- </RecoilRoot>,
+ </TestProviders>,
);
for (let i = 2; i <= lines.length; i += 1) {
rerender(
- <RecoilRoot>
+ <TestProviders>
<Component content={lines.slice(0, i).join('\n')} />
- </RecoilRoot>,
+ </TestProviders>,
);
}
return container;
@@ -118,14 +142,14 @@ const NewMarkdown = ({ content }: { content: string }) => (
describe('MarkdownBlocks code-block index parity', () => {
it('assigns document-order indices on a direct render (matches whole-message renderer)', () => {
const { container: oldC } = render(
- <RecoilRoot>
+ <TestProviders>
<OldMarkdown content={MIXED} />
- </RecoilRoot>,
+ </TestProviders>,
);
const { container: newC } = render(
- <RecoilRoot>
+ <TestProviders>
<Markdown content={MIXED} isLatestMessage={false} />
- </RecoilRoot>,
+ </TestProviders>,
);
expect(indicesIn(oldC)).toEqual(EXPECTED);
@@ -143,9 +167,9 @@ describe('MarkdownBlocks code-block index parity', () => {
it('streamed indices match a fresh direct render (stable for stored execution results)', () => {
const streamed = streamThrough(NewMarkdown, MIXED);
const { container: fresh } = render(
- <RecoilRoot>
+ <TestProviders>
<Markdown content={MIXED} isLatestMessage={false} />
- </RecoilRoot>,
+ </TestProviders>,
);
expect(indicesIn(streamed)).toEqual(indicesIn(fresh));
});
@@ -154,16 +178,16 @@ describe('MarkdownBlocks code-block index parity', () => {
const before = 'intro\n\n```js\na\n```';
const after = '```py\nx\n```\n\n```js\na\n```';
const { container, rerender } = render(
- <RecoilRoot>
+ <TestProviders>
<Markdown content={before} isLatestMessage={false} />
- </RecoilRoot>,
+ </TestProviders>,
);
expect(indicesIn(container)).toEqual([{ idx: '0', lang: 'js' }]);
rerender(
- <RecoilRoot>
+ <TestProviders>
<Markdown content={after} isLatestMessage={false} />
- </RecoilRoot>,
+ </TestProviders>,
);
// The js block's base shifted 0 -> 1; without forcing a remount its ref-cached
// index would stay 0 (duplicating py). It must become 1.
@@ -188,14 +212,14 @@ describe('MarkdownBlocks DOM equivalence (non-code blocks)', () => {
it.each(cases)('renders identical DOM to the whole-message renderer: %s', (_label, content) => {
const { container: oldC } = render(
- <RecoilRoot>
+ <TestProviders>
<OldMarkdown content={content} />
- </RecoilRoot>,
+ </TestProviders>,
);
const { container: newC } = render(
- <RecoilRoot>
+ <TestProviders>
<Markdown content={content} isLatestMessage={false} />
- </RecoilRoot>,
+ </TestProviders>,
);
expect(normalizeHtml(newC.innerHTML)).toBe(normalizeHtml(oldC.innerHTML));
});
@@ -204,18 +228,18 @@ describe('MarkdownBlocks DOM equivalence (non-code blocks)', () => {
describe('MarkdownBlocks rendering smoke', () => {
it('renders an empty cursor placeholder while initializing', () => {
const { container } = render(
- <RecoilRoot>
+ <TestProviders>
<Markdown content="" isLatestMessage={true} />
- </RecoilRoot>,
+ </TestProviders>,
);
expect(container.querySelector('.result-thinking')).not.toBeNull();
});
it('renders executable code blocks for a multi-code message', () => {
render(
- <RecoilRoot>
+ <TestProviders>
<Markdown content={MIXED} isLatestMessage={false} />
- </RecoilRoot>,
+ </TestProviders>,
);
expect(screen.getAllByTestId('cb')).toHaveLength(4);
});
@@ -227,9 +251,9 @@ describe('MarkdownBlocks document-level definitions', () => {
const content = 'See [docs][d] for details.\n\n[d]: https://example.com/docs';
render(
<QueryClientProvider client={queryClient}>
- <RecoilRoot>
+ <TestProviders>
<Markdown content={content} isLatestMessage={false} />
- </RecoilRoot>
+ </TestProviders>
</QueryClientProvider>,
);
expect(screen.getByRole('link', { name: 'docs' })).toHaveAttribute(
diff --git a/client/src/components/Chat/Messages/__tests__/MessageNav.spec.tsx b/client/src/components/Chat/Messages/__tests__/MessageNav.spec.tsx
index 73848f7d86..c71a422f16 100644
--- a/client/src/components/Chat/Messages/__tests__/MessageNav.spec.tsx
+++ b/client/src/components/Chat/Messages/__tests__/MessageNav.spec.tsx
@@ -1182,6 +1182,11 @@ describe('MessageNav', () => {
});
});
+ /** The tooltip anchors off the column's `left`, so a rect stub without one makes
+ * the computed `right` NaN and React rejects the style write. Keep the stub a
+ * complete rect. */
+ const COLUMN_RECT = { top: 0, bottom: 50, height: 50, left: 0, right: 0 } as DOMRect;
+
describe('click to jump', () => {
it('jumps to the hovered (focused) message when the column is clicked off a rib line', () => {
const messages = [
@@ -1191,7 +1196,7 @@ describe('MessageNav', () => {
];
const { container, scrollable } = renderNav(messages);
const column = getColumn(container);
- column.getBoundingClientRect = () => ({ top: 0, bottom: 50, height: 50 }) as DOMRect;
+ column.getBoundingClientRect = () => COLUMN_RECT;
const writes: number[] = [];
Object.defineProperty(scrollable, 'scrollTop', {
@@ -1221,7 +1226,7 @@ describe('MessageNav', () => {
];
const { container } = renderNav(messages);
const column = getColumn(container);
- column.getBoundingClientRect = () => ({ top: 0, bottom: 50, height: 50 }) as DOMRect;
+ column.getBoundingClientRect = () => COLUMN_RECT;
act(() => {
fireEvent.pointerMove(column, { pointerId: 1, clientY: 5 });
@@ -1246,7 +1251,7 @@ describe('MessageNav', () => {
];
const result = renderNav(messages);
const column = getColumn(result.container);
- column.getBoundingClientRect = () => ({ top: 0, bottom: 50, height: 50 }) as DOMRect;
+ column.getBoundingClientRect = () => COLUMN_RECT;
return { ...result, column };
}
@@ -1301,7 +1306,7 @@ describe('MessageNav', () => {
];
const { container } = renderNav(messages);
const column = getColumn(container);
- column.getBoundingClientRect = () => ({ top: 0, bottom: 50, height: 50 }) as DOMRect;
+ column.getBoundingClientRect = () => COLUMN_RECT;
act(() => {
fireEvent.pointerMove(column, { pointerId: 1, clientY: 5 });
@@ -1370,7 +1375,7 @@ describe('MessageNav', () => {
const restoreLayout = stubRibLayout(messages.map((m) => m.messageId));
const result = renderNav(messages);
const column = getColumn(result.container);
- column.getBoundingClientRect = () => ({ top: 0, bottom: 50, height: 50 }) as DOMRect;
+ column.getBoundingClientRect = () => COLUMN_RECT;
const ribs = Array.from(column.querySelectorAll('[data-msg-id]')) as HTMLElement[];
@@ -1861,7 +1866,7 @@ describe('MessageNav', () => {
const restoreLayout = stubRibLayout(messages.map((m) => m.messageId));
const { container } = renderNavWithEnd(messages);
const column = getColumn(container);
- column.getBoundingClientRect = () => ({ top: 0, bottom: 50, height: 50 }) as DOMRect;
+ column.getBoundingClientRect = () => COLUMN_RECT;
const getById = jest.spyOn(document, 'getElementById');
act(() => {
@@ -1885,7 +1890,13 @@ describe('MessageNav', () => {
const { container } = renderNavWithEnd(messages);
const column = getColumn(container);
column.getBoundingClientRect = () =>
- ({ top: 0, bottom: messages.length * 12, height: messages.length * 12 }) as DOMRect;
+ ({
+ top: 0,
+ bottom: messages.length * 12,
+ height: messages.length * 12,
+ left: 0,
+ right: 0,
+ }) as DOMRect;
act(() => {
fireEvent.pointerMove(column, { pointerId: 1, clientY: 3 * 12 + 3 });
@@ -1909,7 +1920,7 @@ describe('MessageNav', () => {
const restoreLayout = stubRibLayout(messages.map((m) => m.messageId));
const { container, scrollable } = renderNavWithEnd(messages);
const column = getColumn(container);
- column.getBoundingClientRect = () => ({ top: 0, bottom: 50, height: 50 }) as DOMRect;
+ column.getBoundingClientRect = () => COLUMN_RECT;
const wrapper = container.querySelector('[data-msg-id="messages-end"]')!
.parentElement as HTMLElement;
const getById = jest.spyOn(document, 'getElementById');
@@ -2089,7 +2100,7 @@ describe('MessageNav', () => {
);
const { container, scrollable } = renderNavWithEnd(messages);
const column = getColumn(container);
- column.getBoundingClientRect = () => ({ top: 0, bottom: 50, height: 50 }) as DOMRect;
+ column.getBoundingClientRect = () => COLUMN_RECT;
const qs = jest.spyOn(scrollable, 'querySelector');
act(() => {
@@ -2172,7 +2183,7 @@ describe('MessageNav', () => {
const restoreLayout = stubRibLayout(messages.map((m) => m.messageId));
const { container } = renderNav(messages);
const column = getColumn(container);
- column.getBoundingClientRect = () => ({ top: 0, bottom: 50, height: 50 }) as DOMRect;
+ column.getBoundingClientRect = () => COLUMN_RECT;
act(() => {
fireEvent.pointerMove(column, { pointerId: 1, clientY: 3 * 12 + 3 });
@@ -2305,7 +2316,9 @@ describe('MessageNav', () => {
const column = getColumn(container);
const ribs = messageRibs(container);
- ribs[0].focus();
+ act(() => {
+ ribs[0].focus();
+ });
act(() => {
fireEvent.keyDown(column, { key: 'ArrowDown' });
});
@@ -2336,7 +2349,9 @@ describe('MessageNav', () => {
const ribs = messageRibs(container);
expect(ribs[0].getAttribute('tabindex')).toBe('0');
- ribs[0].focus();
+ act(() => {
+ ribs[0].focus();
+ });
act(() => {
fireEvent.keyDown(column, { key: 'ArrowDown' });
fireEvent.keyDown(column, { key: 'ArrowDown' });
@@ -2353,7 +2368,9 @@ describe('MessageNav', () => {
const column = getColumn(container);
const ribs = messageRibs(container);
- ribs[0].focus();
+ act(() => {
+ ribs[0].focus();
+ });
act(() => {
fireEvent.keyDown(column, { key: 'End' });
});
@@ -2375,13 +2392,17 @@ describe('MessageNav', () => {
const column = getColumn(container);
const ribs = messageRibs(container);
- ribs[0].focus();
+ act(() => {
+ ribs[0].focus();
+ });
act(() => {
fireEvent.keyDown(column, { key: 'ArrowUp' });
});
expect(document.activeElement).toBe(ribs[0]);
- ribs[ribs.length - 1].focus();
+ act(() => {
+ ribs[ribs.length - 1].focus();
+ });
act(() => {
fireEvent.keyDown(column, { key: 'ArrowDown' });
});
@@ -2399,7 +2420,8 @@ describe('MessageNav', () => {
const restoreLayout = stubRibLayout(messages.map((m) => m.messageId));
const { container } = renderNav(messages);
const column = getColumn(container);
- column.getBoundingClientRect = () => ({ top: 0, bottom: 40, height: 40 }) as DOMRect;
+ column.getBoundingClientRect = () =>
+ ({ top: 0, bottom: 40, height: 40, left: 0, right: 0 }) as DOMRect;
Object.defineProperty(column, 'scrollTop', { value: 0, writable: true, configurable: true });
act(() => {
diff --git a/client/src/components/Nav/SettingsTabs/General/ClockFormatSelector.spec.tsx b/client/src/components/Nav/SettingsTabs/General/ClockFormatSelector.spec.tsx
index e4b2174261..69cef40e9b 100644
--- a/client/src/components/Nav/SettingsTabs/General/ClockFormatSelector.spec.tsx
+++ b/client/src/components/Nav/SettingsTabs/General/ClockFormatSelector.spec.tsx
@@ -1,4 +1,5 @@
-import { render, fireEvent, waitFor } from '@testing-library/react';
+import { render, waitFor } from '@testing-library/react';
+import { clickDropdown, flushDropdownEffects } from 'test/dropdown';
import ClockFormatSelector from './ClockFormatSelector';
jest.mock('~/hooks', () => ({
@@ -15,18 +16,20 @@ describe('ClockFormatSelector', () => {
} as unknown as typeof ResizeObserver;
});
- it('renders with System selected by default', () => {
+ it('renders with System selected by default', async () => {
const { getByText, getByTestId } = render(<ClockFormatSelector />);
expect(getByText('com_nav_clock_format')).toBeInTheDocument();
expect(getByTestId('clock-format-selector')).toHaveTextContent('com_nav_clock_format_system');
+
+ await flushDropdownEffects();
});
it('persists the selected preference to the clockFormat atom', async () => {
const { getByTestId, getByText } = render(<ClockFormatSelector />);
- fireEvent.click(getByTestId('clock-format-selector'));
- fireEvent.click(getByText('com_nav_clock_format_24h'));
+ await clickDropdown(getByTestId('clock-format-selector'));
+ await clickDropdown(getByText('com_nav_clock_format_24h'));
await waitFor(() => {
expect(getByTestId('clock-format-selector')).toHaveTextContent('com_nav_clock_format_24h');
diff --git a/client/src/components/Nav/SettingsTabs/General/WeekStartSelector.spec.tsx b/client/src/components/Nav/SettingsTabs/General/WeekStartSelector.spec.tsx
index cf45fb764f..91fe451a35 100644
--- a/client/src/components/Nav/SettingsTabs/General/WeekStartSelector.spec.tsx
+++ b/client/src/components/Nav/SettingsTabs/General/WeekStartSelector.spec.tsx
@@ -1,4 +1,5 @@
-import { render, fireEvent, waitFor } from '@testing-library/react';
+import { render, waitFor } from '@testing-library/react';
+import { clickDropdown, flushDropdownEffects } from 'test/dropdown';
import WeekStartSelector from './WeekStartSelector';
jest.mock('~/hooks', () => ({
@@ -15,18 +16,20 @@ describe('WeekStartSelector', () => {
} as unknown as typeof ResizeObserver;
});
- it('renders with System selected by default', () => {
+ it('renders with System selected by default', async () => {
const { getByText, getByTestId } = render(<WeekStartSelector />);
expect(getByText('com_nav_week_start')).toBeInTheDocument();
expect(getByTestId('week-start-selector')).toHaveTextContent('com_nav_week_start_system');
+
+ await flushDropdownEffects();
});
it('persists the selected preference to the weekStart atom', async () => {
const { getByTestId, getByText } = render(<WeekStartSelector />);
- fireEvent.click(getByTestId('week-start-selector'));
- fireEvent.click(getByText('com_nav_week_start_monday'));
+ await clickDropdown(getByTestId('week-start-selector'));
+ await clickDropdown(getByText('com_nav_week_start_monday'));
await waitFor(() => {
expect(getByTestId('week-start-selector')).toHaveTextContent('com_nav_week_start_monday');
diff --git a/client/src/hooks/AuthContext.tsx b/client/src/hooks/AuthContext.tsx
index ece55fd0f4..44fa110df4 100644
--- a/client/src/hooks/AuthContext.tsx
+++ b/client/src/hooks/AuthContext.tsx
@@ -207,7 +207,6 @@ const AuthContextProvider = ({
const silentRefresh = useCallback(() => {
if (authConfig?.test === true) {
- console.log('Test mode. Skipping silent refresh.');
return;
}
if (isExternalRedirectRef.current) {
diff --git a/client/src/hooks/Files/useFileDeletion.ts b/client/src/hooks/Files/useFileDeletion.ts
index 8ccab3e7df..4f867a32bb 100644
--- a/client/src/hooks/Files/useFileDeletion.ts
+++ b/client/src/hooks/Files/useFileDeletion.ts
@@ -49,7 +49,6 @@ const useFileDeletion = ({
assistant_id,
tool_resource,
});
- console.log('Deleting files:', filesToDelete, payload);
/** The chips are already gone by the time this runs, so a lost request leaves nothing that
* could rebuild the payload: whatever the server did not delete is kept for the retry pass.
* A resolved request proves nothing on its own, since a failed storage delete is reported
diff --git a/client/src/hooks/Files/useFileHandling.ts b/client/src/hooks/Files/useFileHandling.ts
index 58ded69e44..650cef6fc1 100644
--- a/client/src/hooks/Files/useFileHandling.ts
+++ b/client/src/hooks/Files/useFileHandling.ts
@@ -267,7 +267,6 @@ const useFileHandlingCore = (params: UseFileHandling | undefined, fileState: Fil
const fileId = (body.get('file_id') as string | null) ?? data.temp_file_id;
takeUploadRecovery(fileId)?.onSuccess?.(fileId);
clearUploadTimer(fileId);
- console.log('upload success', data);
if (agent_id) {
queryClient.refetchQueries([QueryKeys.agent, agent_id]);
return;
diff --git a/client/src/utils/timestamps.ts b/client/src/utils/timestamps.ts
index e84b8cc75c..eddf6c4b0d 100644
--- a/client/src/utils/timestamps.ts
+++ b/client/src/utils/timestamps.ts
@@ -109,10 +109,6 @@ export function cleanupTimestampedStorage(): void {
}
keysToRemove.forEach((key) => localStorage.removeItem(key));
-
- if (keysToRemove.length > 0) {
- console.log(`Cleaned up ${keysToRemove.length} old localStorage entries`);
- }
} catch (error) {
console.error('Error during cleanup of timestamped storage:', error);
}
diff --git a/client/test/dropdown.ts b/client/test/dropdown.ts
new file mode 100644
index 0000000000..bd2d5a0c2f
--- /dev/null
+++ b/client/test/dropdown.ts
@@ -0,0 +1,15 @@
+import { act, fireEvent } from '@testing-library/react';
+
+/**
+ * Ariakit's select popover registers and positions itself an effect after the
+ * event that triggered it, so a bare `render` or `fireEvent.click` leaves that
+ * update to land after the test body returns — which React reports as an
+ * unacted update. These helpers settle it inside `act` instead.
+ */
+export const flushDropdownEffects = (): Promise<void> => act(async () => {});
+
+export const clickDropdown = async (element: HTMLElement): Promise<void> => {
+ await act(async () => {
+ fireEvent.click(element);
+ });
+};
diff --git a/config/jest.setup.logging.cjs b/config/jest.setup.logging.cjs
new file mode 100644
index 0000000000..ed8502590f
--- /dev/null
+++ b/config/jest.setup.logging.cjs
@@ -0,0 +1,14 @@
+/**
+ * Quiet framework logging in unit tests, shared by every backend workspace.
+ *
+ * Sets env only — each logger reads these at first module load inside a test
+ * file, so nothing is eagerly required here. Requiring the logger from a setup
+ * file would freeze env-dependent module state (e.g. `CREDS_KEY`) before a spec
+ * gets to set it.
+ *
+ * Set TEST_VERBOSE_LOGS=true to get the logs back while debugging locally.
+ */
+if (process.env.TEST_VERBOSE_LOGS !== 'true') {
+ process.env.CONSOLE_LOG_LEVEL = 'silent';
+ process.env.LOG_TO_FILE = 'false';
+}
diff --git a/packages/api/jest.config.mjs b/packages/api/jest.config.mjs
index 0b8330a374..0aa27c9cf3 100644
--- a/packages/api/jest.config.mjs
+++ b/packages/api/jest.config.mjs
@@ -51,7 +51,7 @@ export default {
// lines: 57,
// },
// },
- setupFiles: ['<rootDir>/jest.setup.cjs'],
+ setupFiles: ['<rootDir>/jest.setup.cjs', '<rootDir>/../../config/jest.setup.logging.cjs'],
maxWorkers: '50%',
restoreMocks: true,
testTimeout: 15000,
diff --git a/packages/api/src/stream/__tests__/startup.spec.ts b/packages/api/src/stream/__tests__/startup.spec.ts
index 21e9c06f71..03db5643eb 100644
--- a/packages/api/src/stream/__tests__/startup.spec.ts
+++ b/packages/api/src/stream/__tests__/startup.spec.ts
@@ -1641,6 +1641,10 @@ describe('GenerationJobManager startup telemetry', () => {
expect(onError).not.toHaveBeenCalledWith(TERMINAL_PUBLICATION_RECONNECT_ERROR);
expect(manager.getRuntimeStats().fencedRuntimeRetirements).toBe(0);
+ /** Shutdown finishes cancelling on the tick after `destroy()` resolves, so settle the
+ * queue before counting. Without this the count only came back to the baseline when
+ * something else — a console write from the logger — happened to yield first. */
+ await jest.advanceTimersByTimeAsync(0);
expect(jest.getTimerCount()).toBe(timerCountBeforeInitialize);
await jest.advanceTimersByTimeAsync(
diff --git a/packages/data-schemas/jest.config.mjs b/packages/data-schemas/jest.config.mjs
index de247fbc11..ff19e63d2f 100644
--- a/packages/data-schemas/jest.config.mjs
+++ b/packages/data-schemas/jest.config.mjs
@@ -22,6 +22,7 @@ export default {
// Download the in-memory MongoDB binary once, before workers fork: on a cold
// cache the parallel downloads race their final rename and fail whole suites.
globalSetup: '<rootDir>/jest.globalSetup.mjs',
+ setupFiles: ['<rootDir>/../../config/jest.setup.logging.cjs'],
maxWorkers: '50%',
restoreMocks: true,
testTimeout: 15000,
diff --git a/packages/data-schemas/src/config/consoleLevel.spec.ts b/packages/data-schemas/src/config/consoleLevel.spec.ts
new file mode 100644
index 0000000000..ad333f9637
--- /dev/null
+++ b/packages/data-schemas/src/config/consoleLevel.spec.ts
@@ -0,0 +1,68 @@
+import { logLevels, resolveConsoleLevel } from './utils';
+
+describe('resolveConsoleLevel', () => {
+ const original = process.env.CONSOLE_LOG_LEVEL;
+ let warn: jest.SpyInstance;
+
+ beforeEach(() => {
+ warn = jest.spyOn(console, 'warn').mockImplementation(() => {});
+ });
+
+ afterEach(() => {
+ warn.mockRestore();
+ if (original === undefined) {
+ delete process.env.CONSOLE_LOG_LEVEL;
+ return;
+ }
+ process.env.CONSOLE_LOG_LEVEL = original;
+ });
+
+ it('defaults to info and stays audible when unset', () => {
+ delete process.env.CONSOLE_LOG_LEVEL;
+ expect(resolveConsoleLevel()).toEqual({ level: 'info', silent: false });
+ });
+
+ it('treats an empty or whitespace-only value as unset', () => {
+ process.env.CONSOLE_LOG_LEVEL = ' ';
+ expect(resolveConsoleLevel()).toEqual({ level: 'info', silent: false });
+ expect(warn).not.toHaveBeenCalled();
+ });
+
+ it('accepts every level the loggers are built with', () => {
+ for (const name of Object.keys(logLevels)) {
+ process.env.CONSOLE_LOG_LEVEL = name;
+ expect(resolveConsoleLevel()).toEqual({ level: name, silent: false });
+ }
+ expect(warn).not.toHaveBeenCalled();
+ });
+
+ it('normalizes casing and surrounding whitespace', () => {
+ process.env.CONSOLE_LOG_LEVEL = ' WARN ';
+ expect(resolveConsoleLevel()).toEqual({ level: 'warn', silent: false });
+ expect(warn).not.toHaveBeenCalled();
+ });
+
+ it('silences the transport without emitting an invalid winston level', () => {
+ process.env.CONSOLE_LOG_LEVEL = 'silent';
+ const { level, silent } = resolveConsoleLevel();
+ expect(silent).toBe(true);
+ expect(level).toBe('info');
+ });
+
+ it('keeps a caller-supplied fallback when silenced', () => {
+ process.env.CONSOLE_LOG_LEVEL = 'silent';
+ expect(resolveConsoleLevel('error')).toEqual({ level: 'error', silent: true });
+ });
+
+ it('falls back and warns on an unknown level rather than muting every log', () => {
+ process.env.CONSOLE_LOG_LEVEL = 'warning';
+ expect(resolveConsoleLevel()).toEqual({ level: 'info', silent: false });
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('warning'));
+ });
+
+ it('does not treat an inherited Object property as a level', () => {
+ process.env.CONSOLE_LOG_LEVEL = 'constructor';
+ expect(resolveConsoleLevel()).toEqual({ level: 'info', silent: false });
+ expect(warn).toHaveBeenCalled();
+ });
+});
diff --git a/packages/data-schemas/src/config/consoleTransport.spec.ts b/packages/data-schemas/src/config/consoleTransport.spec.ts
new file mode 100644
index 0000000000..84cd81ed6c
--- /dev/null
+++ b/packages/data-schemas/src/config/consoleTransport.spec.ts
@@ -0,0 +1,96 @@
+import type winston from 'winston';
+
+type ConsoleTransport = winston.transport & { silent?: boolean };
+
+/**
+ * The console transport is built once at module load from the environment, so
+ * each case re-imports the logger with the env it is describing.
+ */
+const loadConsoleTransport = async (
+ env: Record<string, string | undefined>,
+): Promise<ConsoleTransport> => {
+ const previous: Record<string, string | undefined> = {};
+ for (const [key, value] of Object.entries(env)) {
+ previous[key] = process.env[key];
+ if (value === undefined) {
+ delete process.env[key];
+ continue;
+ }
+ process.env[key] = value;
+ }
+
+ try {
+ jest.resetModules();
+ const { default: logger } = await import('./winston');
+ return logger.transports.find(
+ (candidate) => candidate.constructor.name === 'Console',
+ ) as ConsoleTransport;
+ } finally {
+ for (const [key, value] of Object.entries(previous)) {
+ if (value === undefined) {
+ delete process.env[key];
+ continue;
+ }
+ process.env[key] = value;
+ }
+ }
+};
+
+describe('console transport level', () => {
+ const baseEnv = { LOG_TO_FILE: 'false', CONSOLE_JSON: undefined, DEBUG_CONSOLE: undefined };
+
+ it('defaults to info when nothing is set', async () => {
+ const transport = await loadConsoleTransport({ ...baseEnv, CONSOLE_LOG_LEVEL: undefined });
+ expect(transport.level).toBe('info');
+ expect(transport.silent).toBeFalsy();
+ });
+
+ it('honors an explicit level', async () => {
+ const transport = await loadConsoleTransport({ ...baseEnv, CONSOLE_LOG_LEVEL: 'error' });
+ expect(transport.level).toBe('error');
+ });
+
+ it('silences the transport without handing winston an invalid level', async () => {
+ const transport = await loadConsoleTransport({ ...baseEnv, CONSOLE_LOG_LEVEL: 'silent' });
+ expect(transport.silent).toBe(true);
+ expect(transport.level).toBe('info');
+ });
+
+ it('still defaults to debug under DEBUG_CONSOLE', async () => {
+ const transport = await loadConsoleTransport({
+ ...baseEnv,
+ DEBUG_CONSOLE: 'true',
+ CONSOLE_LOG_LEVEL: undefined,
+ });
+ expect(transport.level).toBe('debug');
+ });
+
+ it('lets an explicit level win over DEBUG_CONSOLE', async () => {
+ const transport = await loadConsoleTransport({
+ ...baseEnv,
+ DEBUG_CONSOLE: 'true',
+ CONSOLE_LOG_LEVEL: 'error',
+ });
+ expect(transport.level).toBe('error');
+ });
+
+ it('can be silenced under DEBUG_CONSOLE too', async () => {
+ const transport = await loadConsoleTransport({
+ ...baseEnv,
+ DEBUG_CONSOLE: 'true',
+ CONSOLE_LOG_LEVEL: 'silent',
+ });
+ expect(transport.silent).toBe(true);
+ });
+
+ it('falls back to the default rather than muting on an unknown level', async () => {
+ const warn = jest.spyOn(console, 'warn').mockImplementation(() => {});
+ try {
+ const transport = await loadConsoleTransport({ ...baseEnv, CONSOLE_LOG_LEVEL: 'warning' });
+ expect(transport.level).toBe('info');
+ expect(transport.silent).toBeFalsy();
+ } finally {
+ warn.mockRestore();
+ }
+ });
+});
diff --git a/packages/data-schemas/src/config/meiliLogger.ts b/packages/data-schemas/src/config/meiliLogger.ts
index 46cff165fa..d6d623eecd 100644
--- a/packages/data-schemas/src/config/meiliLogger.ts
+++ b/packages/data-schemas/src/config/meiliLogger.ts
@@ -1,6 +1,6 @@
import winston from 'winston';
import 'winston-daily-rotate-file';
-import { getLogDirectory } from './utils';
+import { getLogDirectory, logLevels, resolveConsoleLevel } from './utils';
const { NODE_ENV, DEBUG_LOGGING = 'false', LOG_TO_FILE } = process.env;
@@ -10,17 +10,6 @@ const useDebugLogging =
const useFileLogging = typeof LOG_TO_FILE !== 'string' || LOG_TO_FILE.toLowerCase() !== 'false';
-const levels: winston.config.AbstractConfigSetLevels = {
- error: 0,
- warn: 1,
- info: 2,
- http: 3,
- verbose: 4,
- debug: 5,
- activity: 6,
- silly: 7,
-};
-
winston.addColors({
info: 'green',
warn: 'italic yellow',
@@ -65,16 +54,19 @@ const consoleFormat = winston.format.combine(
winston.format.printf((info) => `${info.timestamp} ${info.level}: ${info.message}`),
);
+const { level: consoleLevel, silent: consoleSilent } = resolveConsoleLevel();
+
transports.push(
new winston.transports.Console({
- level: 'info',
+ level: consoleLevel,
+ silent: consoleSilent,
format: consoleFormat,
}),
);
const logger: winston.Logger = winston.createLogger({
level: level(),
- levels,
+ levels: logLevels,
transports,
});
diff --git a/packages/data-schemas/src/config/utils.ts b/packages/data-schemas/src/config/utils.ts
index 323334207b..db5255db5f 100644
--- a/packages/data-schemas/src/config/utils.ts
+++ b/packages/data-schemas/src/config/utils.ts
@@ -1,5 +1,7 @@
import path from 'path';
+import type winston from 'winston';
+
/**
* Determine the log directory in a cross-compatible way.
* Priority:
@@ -35,3 +37,54 @@ export const getLogDirectory = (): string => {
// Default to logs directory relative to current working directory
return path.join(cwd, 'logs');
};
+
+/**
+ * The level set every logger in this package is built with. Winston resolves a
+ * level name against this map, so a name outside it resolves to `undefined` and
+ * the transport drops every message.
+ */
+export const logLevels: winston.config.AbstractConfigSetLevels = {
+ error: 0,
+ warn: 1,
+ info: 2,
+ http: 3,
+ verbose: 4,
+ debug: 5,
+ activity: 6,
+ silly: 7,
+};
+
+/**
+ * Console verbosity for every winston logger in this package.
+ *
+ * Each logger's Console transport used to hard-code `level: 'info'`, which
+ * silently overrides the logger's own level — winston resolves a transport's
+ * explicit level ahead of its parent's. `CONSOLE_LOG_LEVEL` makes that
+ * verbosity configurable, and `silent` turns console output off entirely.
+ *
+ * An unrecognized name falls back rather than reaching winston: it would
+ * resolve to `undefined` there and silently discard every console log, so a
+ * typo would read as a dead deployment. Say so on the way past — the logger
+ * cannot report its own misconfiguration.
+ */
+export const resolveConsoleLevel = (fallback = 'info'): { level: string; silent: boolean } => {
+ const requested = process.env.CONSOLE_LOG_LEVEL?.trim().toLowerCase();
+
+ if (!requested) {
+ return { level: fallback, silent: false };
+ }
+
+ if (requested === 'silent') {
+ return { level: fallback, silent: true };
+ }
+
+ if (Object.prototype.hasOwnProperty.call(logLevels, requested)) {
+ return { level: requested, silent: false };
+ }
+
+ console.warn(
+ `[logger] Ignoring unknown CONSOLE_LOG_LEVEL "${process.env.CONSOLE_LOG_LEVEL}"; using "${fallback}". ` +
+ `Expected one of: ${Object.keys(logLevels).join(', ')}, silent.`,
+ );
+ return { level: fallback, silent: false };
+};
diff --git a/packages/data-schemas/src/config/winston.ts b/packages/data-schemas/src/config/winston.ts
index 97dab875dc..0cc48470b2 100644
--- a/packages/data-schemas/src/config/winston.ts
+++ b/packages/data-schemas/src/config/winston.ts
@@ -8,7 +8,7 @@ import {
stripHeavyErrorFields,
} from './parsers';
import { appendLogContext, attachRequestContext } from './requestLogContext';
-import { getLogDirectory } from './utils';
+import { getLogDirectory, logLevels, resolveConsoleLevel } from './utils';
const { NODE_ENV, DEBUG_LOGGING, CONSOLE_JSON, DEBUG_CONSOLE, LOG_TO_FILE } = process.env;
@@ -20,17 +20,6 @@ const useDebugLogging = typeof DEBUG_LOGGING === 'string' && DEBUG_LOGGING.toLow
const useFileLogging = typeof LOG_TO_FILE !== 'string' || LOG_TO_FILE.toLowerCase() !== 'false';
-const levels: winston.config.AbstractConfigSetLevels = {
- error: 0,
- warn: 1,
- info: 2,
- http: 3,
- verbose: 4,
- debug: 5,
- activity: 6,
- silly: 7,
-};
-
const requestContextFormat = winston.format(attachRequestContext);
winston.addColors({
@@ -98,16 +87,18 @@ const consoleFormat = winston.format.combine(
}),
);
-let consoleLogLevel: string = 'info';
-if (useDebugConsole) {
- consoleLogLevel = 'debug';
-}
+/** `DEBUG_CONSOLE` still picks the debug *format* below; here it only moves the
+ * default level, so an explicit `CONSOLE_LOG_LEVEL` stays in charge of verbosity. */
+const { level: consoleLogLevel, silent: consoleSilent } = resolveConsoleLevel(
+ useDebugConsole ? 'debug' : 'info',
+);
// Add console transport
if (useDebugConsole) {
transports.push(
new winston.transports.Console({
level: consoleLogLevel,
+ silent: consoleSilent,
format: useConsoleJson
? winston.format.combine(fileFormat, jsonTruncateFormat(), winston.format.json())
: winston.format.combine(fileFormat, debugTraverse),
@@ -117,6 +108,7 @@ if (useDebugConsole) {
transports.push(
new winston.transports.Console({
level: consoleLogLevel,
+ silent: consoleSilent,
format: winston.format.combine(fileFormat, jsonTruncateFormat(), winston.format.json()),
}),
);
@@ -124,6 +116,7 @@ if (useDebugConsole) {
transports.push(
new winston.transports.Console({
level: consoleLogLevel,
+ silent: consoleSilent,
format: consoleFormat,
}),
);
@@ -132,7 +125,7 @@ if (useDebugConsole) {
// Create logger
const logger: winston.Logger = winston.createLogger({
level: level(),
- levels,
+ levels: logLevels,
transports,
});
diff --git a/packages/data-schemas/src/methods/spendTokens.spec.ts b/packages/data-schemas/src/methods/spendTokens.spec.ts
index 549c03212d..7c743a2b95 100644
--- a/packages/data-schemas/src/methods/spendTokens.spec.ts
+++ b/packages/data-schemas/src/methods/spendTokens.spec.ts
@@ -1,12 +1,12 @@
import mongoose from 'mongoose';
import { MongoMemoryServer } from 'mongodb-memory-server';
-import { matchModelName, findMatchingPattern } from './test-helpers';
-import { createModels } from '~/models';
+import type { IBalance } from '..';
+import type { ITransaction } from '~/schema/transaction';
import { createTxMethods, tokenValues, premiumTokenValues } from './tx';
+import { matchModelName, findMatchingPattern } from './test-helpers';
import { createTransactionMethods } from './transaction';
import { createSpendTokensMethods } from './spendTokens';
-import type { ITransaction } from '~/schema/transaction';
-import type { IBalance } from '..';
+import { createModels } from '~/models';
jest.mock('~/config/winston', () => ({
error: jest.fn(),
@@ -300,20 +300,6 @@ describe('spendTokens', () => {
const transactions = await Transaction.find({ user: userId });
expect(transactions).toHaveLength(4); // 2 transactions (prompt+completion) for each call
- // Let's examine the actual transaction records to see what's happening
- const transactionDetails = await Transaction.find({ user: userId }).sort({ createdAt: 1 });
-
- // Log the transaction details for debugging
- console.log('Transaction details:');
- transactionDetails.forEach((tx, i: number) => {
- console.log(`Transaction ${i + 1}:`, {
- tokenType: tx.tokenType,
- rawAmount: tx.rawAmount,
- tokenValue: tx.tokenValue,
- model: tx.model,
- });
- });
-
// Check the return values from Transaction.create directly
// This is to verify that the incrementValue is not becoming positive
const directResult = await createTransaction({
@@ -326,8 +312,6 @@ describe('spendTokens', () => {
balance: { enabled: true },
});
- console.log('Direct Transaction.create result:', directResult);
-
// The completion value should never be positive
expect(directResult!.completion).not.toBeGreaterThan(0);
});
@@ -366,7 +350,6 @@ describe('spendTokens', () => {
// Verify tokenValue is negative for all transactions
transactions.forEach((tx) => {
- console.log(`Model ${model}, Type ${tx.tokenType}: tokenValue = ${tx.tokenValue}`);
expect(tx.tokenValue).toBeLessThan(0);
});
}
@@ -430,23 +413,6 @@ describe('spendTokens', () => {
// Verify all transactions were created
const transactions = await Transaction.find({ user: userId });
expect(transactions).toHaveLength(4); // 2 transactions (prompt+completion) for each call
-
- // Let's examine the actual transaction records to see what's happening
- const transactionDetails = await Transaction.find({ user: userId }).sort({ createdAt: 1 });
-
- // Log the transaction details for debugging
- console.log('Structured transaction details:');
- transactionDetails.forEach((tx, i: number) => {
- console.log(`Transaction ${i + 1}:`, {
- tokenType: tx.tokenType,
- rawAmount: tx.rawAmount,
- tokenValue: tx.tokenValue,
- inputTokens: tx.inputTokens,
- writeTokens: tx.writeTokens,
- readTokens: tx.readTokens,
- model: tx.model,
- });
- });
});
it('should not allow balance to go below zero when spending structured tokens', async () => {
@@ -594,11 +560,6 @@ describe('spendTokens', () => {
// The final balance should be the initial balance minus the expected total spend
const expectedFinalBalance = initialBalance - expectedTotalSpend;
- console.log('Initial balance:', initialBalance);
- console.log('Expected total spend:', expectedTotalSpend);
- console.log('Expected final balance:', expectedFinalBalance);
- console.log('Actual final balance:', finalBalance!.tokenCredits);
-
// Allow for small rounding differences
expect(finalBalance!.tokenCredits).toBeCloseTo(expectedFinalBalance, 0);
@@ -612,20 +573,15 @@ describe('spendTokens', () => {
// Some might be structured, some regular
expect(transactions.length).toBeGreaterThanOrEqual(collectedUsage.length);
- // Log transaction details for debugging
- console.log('Transaction summary:');
let totalTokenValue = 0;
transactions.forEach((tx) => {
- console.log(`${tx.tokenType}: rawAmount=${tx.rawAmount}, tokenValue=${tx.tokenValue}`);
totalTokenValue += tx.tokenValue!;
});
- console.log('Total token value from transactions:', totalTokenValue);
// The difference between expected and actual is significant
// This is likely due to the multipliers being different in the test environment
// Let's adjust our expectation based on the actual transactions
const actualSpend = initialBalance - finalBalance!.tokenCredits;
- console.log('Actual spend:', actualSpend);
// Instead of checking the exact balance, let's verify that:
// 1. The balance was reduced (tokens were spent)
@@ -669,11 +625,6 @@ describe('spendTokens', () => {
// The final balance should be the initial balance plus the sum of all refills
const expectedFinalBalance = initialBalance + numberOfRefills * refillAmount;
- console.log('Initial balance (Increase Test):', initialBalance);
- console.log(`Performed ${numberOfRefills} refills of ${refillAmount} each.`);
- console.log('Expected final balance (Increase Test):', expectedFinalBalance);
- console.log('Actual final balance (Increase Test):', finalBalance!.tokenCredits);
-
// Use toBeCloseTo for safety, though toBe should work for integer math
expect(finalBalance!.tokenCredits).toBeCloseTo(expectedFinalBalance, 0);
@@ -695,7 +646,6 @@ describe('spendTokens', () => {
const r = result as Record<string, Record<string, unknown>>;
return sum + ((r?.transaction?.rawAmount as number) || 0);
}, 0);
- console.log('Total increment reported by results:', totalIncrementReported);
expect(totalIncrementReported).toBe(expectedFinalBalance - initialBalance);
// Optional: Check the sum of tokenValue from saved transactions
@@ -706,7 +656,6 @@ describe('spendTokens', () => {
// If calculation is involved, adjust accordingly
totalTokenValueFromDb += tx.rawAmount!; // Or tx.tokenValue if that holds the increment
});
- console.log('Total rawAmount from DB transactions:', totalTokenValueFromDb);
expect(totalTokenValueFromDb).toBeCloseTo(expectedFinalBalance - initialBalance, 0);
});