- Notifications
You must be signed in to change notification settings - Fork905
refactor: redefine useAgentLogs tests as unit tests#18019
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.
Already on GitHub?Sign in to your account
base:main
Are you sure you want to change the base?
Changes fromall commits
d6e00c3
43d0ca8
727bddd
d46d144
91a6fc1
ecbe7b0
d13bcdc
File filter
Filter by extension
Conversations
Uh oh!
There was an error while loading.Please reload this page.
Jump to
Uh oh!
There was an error while loading.Please reload this page.
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,60 +1,114 @@ | ||
import { renderHook, waitFor } from "@testing-library/react"; | ||
import type { WorkspaceAgentLog } from "api/typesGenerated"; | ||
import { MockWorkspaceAgent } from "testHelpers/entities"; | ||
import { | ||
type MockWebSocketPublisher, | ||
createMockWebSocket, | ||
} from "testHelpers/websockets"; | ||
import { OneWayWebSocket } from "utils/OneWayWebSocket"; | ||
import { createUseAgentLogs } from "./useAgentLogs"; | ||
const millisecondsInOneMinute = 60_000; | ||
function generateMockLogs( | ||
logCount: number, | ||
baseDate = new Date(), | ||
): readonly WorkspaceAgentLog[] { | ||
return Array.from({ length: logCount }, (_, i) => { | ||
// Make sure that the logs generated each have unique timestamps, so | ||
// that we can test whether they're being sorted properly before being | ||
// returned by the hook | ||
const logDate = new Date(baseDate.getTime() + i * millisecondsInOneMinute); | ||
return { | ||
Comment on lines +18 to +22 MemberAuthor
| ||
id: i, | ||
created_at: logDate.toISOString(), | ||
level: "info", | ||
output: `Log ${i}`, | ||
source_id: "", | ||
}; | ||
}); | ||
} | ||
// A mutable object holding the most recent mock WebSocket publisher. The inner | ||
// value will change as the hook opens/closes new connections | ||
type PublisherResult = { | ||
current: MockWebSocketPublisher; | ||
}; | ||
type MountHookResult = Readonly<{ | ||
// Note: the value of `current` should be readonly, but the `current` | ||
// property itself should be mutable | ||
hookResult: { | ||
current: readonly WorkspaceAgentLog[]; | ||
}; | ||
rerender: (props: { enabled: boolean }) => void; | ||
publisherResult: PublisherResult; | ||
}>; | ||
function mountHook(): MountHookResult { | ||
// Have to cheat the types a little bit to avoid a chicken-and-the-egg | ||
// scenario. publisherResult will be initialized with an undefined current | ||
// value, but it'll be guaranteed not to be undefined by the time this | ||
// function returns. | ||
const publisherResult: Partial<PublisherResult> = { current: undefined }; | ||
const useAgentLogs = createUseAgentLogs((agentId, params) => { | ||
return new OneWayWebSocket({ | ||
apiRoute: `/api/v2/workspaceagents/${agentId}/logs`, | ||
searchParams: new URLSearchParams({ | ||
follow: "true", | ||
after: params?.after?.toString() || "0", | ||
}), | ||
websocketInit: (url) => { | ||
const [mockSocket, mockPublisher] = createMockWebSocket(url); | ||
publisherResult.current = mockPublisher; | ||
return mockSocket; | ||
}, | ||
}); | ||
}); | ||
const { result, rerender } = renderHook( | ||
({ enabled }) => useAgentLogs(MockWorkspaceAgent, enabled), | ||
{ initialProps: { enabled: true } }, | ||
); | ||
return { | ||
rerender, | ||
hookResult: result, | ||
publisherResult: publisherResult as PublisherResult, | ||
}; | ||
} | ||
describe("useAgentLogs", () => { | ||
it("clears logs when hook becomes disabled (protection to avoid duplicate logs when hook goes back to being re-enabled)", async () => { | ||
const { hookResult, publisherResult, rerender } = mountHook(); | ||
// Verify that logs can be received after mount | ||
const initialLogs = generateMockLogs(3, new Date("april 5, 1997")); | ||
const initialEvent = new MessageEvent<string>("message", { | ||
data: JSON.stringify(initialLogs), | ||
}); | ||
publisherResult.current.publishMessage(initialEvent); | ||
await waitFor(() => { | ||
// Using expect.arrayContaining to account for the fact that we're | ||
// not guaranteed to receive WebSocket events in order | ||
expect(hookResult.current).toEqual(expect.arrayContaining(initialLogs)); | ||
}); | ||
// Disable the hook (and have the hook close the connection behind the | ||
// scenes) | ||
rerender({ enabled: false }); | ||
await waitFor(() => expect(hookResult.current).toHaveLength(0)); | ||
// Re-enable the hook (creating an entirely new connection), and send | ||
// new logs | ||
rerender({ enabled: true }); | ||
const newLogs = generateMockLogs(3, new Date("october 3, 2005")); | ||
const newEvent = new MessageEvent<string>("message", { | ||
data: JSON.stringify(newLogs), | ||
}); | ||
publisherResult.current.publishMessage(newEvent); | ||
await waitFor(() => { | ||
expect(hookResult.current).toEqual(expect.arrayContaining(newLogs)); | ||
}); | ||
}); | ||
}); | ||
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,135 @@ | ||
import type { WebSocketEventType } from "utils/OneWayWebSocket"; | ||
export type MockWebSocketPublisher = Readonly<{ | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others.Learn more. The entire contents of the file were basically copy-pasted from the other test file. The only change was that the publisher type is now exported and was renamed to be a little more clear | ||
publishMessage: (event: MessageEvent<string>) => void; | ||
publishError: (event: ErrorEvent) => void; | ||
publishClose: (event: CloseEvent) => void; | ||
publishOpen: (event: Event) => void; | ||
}>; | ||
export function createMockWebSocket( | ||
url: string, | ||
protocols?: string | string[], | ||
): readonly [WebSocket, MockWebSocketPublisher] { | ||
type EventMap = { | ||
message: MessageEvent<string>; | ||
error: ErrorEvent; | ||
close: CloseEvent; | ||
open: Event; | ||
}; | ||
type CallbackStore = { | ||
[K in keyof EventMap]: ((event: EventMap[K]) => void)[]; | ||
}; | ||
let activeProtocol: string; | ||
if (Array.isArray(protocols)) { | ||
activeProtocol = protocols[0] ?? ""; | ||
} else if (typeof protocols === "string") { | ||
activeProtocol = protocols; | ||
} else { | ||
activeProtocol = ""; | ||
} | ||
let closed = false; | ||
const store: CallbackStore = { | ||
message: [], | ||
error: [], | ||
close: [], | ||
open: [], | ||
}; | ||
const mockSocket: WebSocket = { | ||
CONNECTING: 0, | ||
OPEN: 1, | ||
CLOSING: 2, | ||
CLOSED: 3, | ||
url, | ||
protocol: activeProtocol, | ||
readyState: 1, | ||
binaryType: "blob", | ||
bufferedAmount: 0, | ||
extensions: "", | ||
onclose: null, | ||
onerror: null, | ||
onmessage: null, | ||
onopen: null, | ||
send: jest.fn(), | ||
dispatchEvent: jest.fn(), | ||
addEventListener: <E extends WebSocketEventType>( | ||
eventType: E, | ||
callback: WebSocketEventMap[E], | ||
) => { | ||
if (closed) { | ||
return; | ||
} | ||
const subscribers = store[eventType]; | ||
const cb = callback as unknown as CallbackStore[E][0]; | ||
if (!subscribers.includes(cb)) { | ||
subscribers.push(cb); | ||
} | ||
}, | ||
removeEventListener: <E extends WebSocketEventType>( | ||
eventType: E, | ||
callback: WebSocketEventMap[E], | ||
) => { | ||
if (closed) { | ||
return; | ||
} | ||
const subscribers = store[eventType]; | ||
const cb = callback as unknown as CallbackStore[E][0]; | ||
if (subscribers.includes(cb)) { | ||
const updated = store[eventType].filter((c) => c !== cb); | ||
store[eventType] = updated as unknown as CallbackStore[E]; | ||
} | ||
}, | ||
close: () => { | ||
closed = true; | ||
}, | ||
}; | ||
const publisher: MockWebSocketPublisher = { | ||
publishOpen: (event) => { | ||
if (closed) { | ||
return; | ||
} | ||
for (const sub of store.open) { | ||
sub(event); | ||
} | ||
}, | ||
publishError: (event) => { | ||
if (closed) { | ||
return; | ||
} | ||
for (const sub of store.error) { | ||
sub(event); | ||
} | ||
}, | ||
publishMessage: (event) => { | ||
if (closed) { | ||
return; | ||
} | ||
for (const sub of store.message) { | ||
sub(event); | ||
} | ||
}, | ||
publishClose: (event) => { | ||
if (closed) { | ||
return; | ||
} | ||
for (const sub of store.close) { | ||
sub(event); | ||
} | ||
}, | ||
}; | ||
return [mockSocket, publisher] as const; | ||
} |
Uh oh!
There was an error while loading.Please reload this page.
Uh oh!
There was an error while loading.Please reload this page.