Elffuss BraidHub

kikocis/continue public

71fd2e7d4456 · 5.1 KiBRawPermalink
1import { DevDataLogEvent } from "@continuedev/config-yaml";
2import fs from "fs";
3import path from "path";
4import { IdeInfo, IdeSettings } from "..";
5import { Core } from "../core";
6import { getDevDataFilePath } from "../util/paths";
7import { DataLogger } from "./log";
8
9// Only mock fetch, not fs
10jest.mock("@continuedev/fetch");
11
12const TEST_EVENT: DevDataLogEvent = {
13 name: "tokensGenerated",
14 data: {
15 generatedTokens: 100,
16 model: "gpt-4",
17 promptTokens: 50,
18 provider: "openai",
19 },
20};
21const SCHEMA = "0.2.0";
22
23describe("DataLogger", () => {
24 let dataLogger: DataLogger;
25 const tempDir = path.join(process.cwd(), "temp-test-data");
26 const testFilePath = path.join(tempDir, "tokensGenerated-test.jsonl");
27
28 // Create temp directory for test files
29 beforeAll(() => {
30 if (!fs.existsSync(tempDir)) {
31 fs.mkdirSync(tempDir, { recursive: true });
32 }
33 });
34
35 // Clean up temp directory after tests
36 afterAll(() => {
37 if (fs.existsSync(tempDir)) {
38 fs.rmSync(tempDir, { recursive: true, force: true });
39 }
40 });
41
42 beforeEach(() => {
43 // Reset mocks
44 jest.clearAllMocks();
45
46 // Remove test file if it exists
47 if (fs.existsSync(testFilePath)) {
48 fs.unlinkSync(testFilePath);
49 }
50
51 // Get singleton instance
52 dataLogger = DataLogger.getInstance();
53
54 // Mock core and required promises
55 dataLogger.core = {
56 configHandler: {
57 loadConfig: jest.fn().mockResolvedValue({
58 config: {
59 data: [],
60 },
61 }),
62 currentProfile: {
63 profileDescription: {
64 id: "test-profile-id",
65 },
66 },
67 controlPlaneClient: {
68 getAccessToken: jest.fn().mockResolvedValue("test-access-token"),
69 },
70 },
71 } as unknown as Core;
72
73 dataLogger.ideSettingsPromise = Promise.resolve({
74 userToken: "test-user-token",
75 } as IdeSettings);
76
77 dataLogger.ideInfoPromise = Promise.resolve({
78 name: "VSCode",
79 version: "1.0.0",
80 extensionVersion: "0.1.0",
81 } as IdeInfo);
82 });
83
84 describe("getInstance", () => {
85 it("should return the same instance when called multiple times", () => {
86 const instance1 = DataLogger.getInstance();
87 const instance2 = DataLogger.getInstance();
88 expect(instance1).toBe(instance2);
89 });
90 });
91
92 describe("addBaseValues", () => {
93 it("should add base values to event data based on schema", async () => {
94 const mockZodSchema = {
95 shape: {
96 eventName: true,
97 timestamp: true,
98 schema: true,
99 userAgent: true,
100 selectedProfileId: true,
101 userId: true,
102 },
103 };
104
105 const result = await dataLogger.addBaseValues(
106 { customField: "value" },
107 "testEvent",
108 SCHEMA,
109 mockZodSchema as any,
110 );
111
112 expect(result).toEqual({
113 customField: "value",
114 eventName: "testEvent",
115 timestamp: expect.any(String),
116 schema: SCHEMA,
117 userAgent: "VSCode/1.0.0 (Continue/0.1.0)",
118 selectedProfileId: "test-profile-id",
119 userId: "test-user-token",
120 });
121 });
122
123 it("should not add fields not present in schema shape", async () => {
124 const mockZodSchema = {
125 shape: {
126 eventName: true,
127 // No other fields
128 },
129 };
130
131 const result = await dataLogger.addBaseValues(
132 { customField: "value" },
133 "testEvent",
134 SCHEMA,
135 mockZodSchema as any,
136 );
137
138 expect(result).toEqual({
139 customField: "value",
140 eventName: "testEvent",
141 });
142 });
143 });
144
145 describe("logLocalData", () => {
146 it("should actually write data to the local file", async () => {
147 // Call the method to log data locally
148 await dataLogger.logLocalData(TEST_EVENT);
149
150 // Verify the file was created
151 const filepath = getDevDataFilePath(TEST_EVENT.name, SCHEMA);
152 expect(fs.existsSync(filepath)).toBe(true);
153
154 // Read file contents and verify
155 const fileContent = fs.readFileSync(filepath, "utf8");
156 expect(fileContent).toContain('"generatedTokens":100');
157 expect(fileContent).toContain('"model":"gpt-4"');
158 expect(fileContent).toContain('"eventName":"tokensGenerated"');
159 });
160 });
161
162 describe("logDevData", () => {
163 it("should log data locally and to configured destinations", async () => {
164 // Spy on logLocalData and logToOneDestination
165 const logLocalDataSpy = jest
166 .spyOn(dataLogger, "logLocalData")
167 .mockResolvedValue();
168 const logToOneDestinationSpy = jest
169 .spyOn(dataLogger, "logToOneDestination")
170 .mockResolvedValue();
171
172 // Mock config with multiple data destinations
173 const mockConfig = {
174 config: {
175 data: [
176 { destination: "https://example.com/logs", schema: SCHEMA },
177 { destination: "file:///logs", schema: SCHEMA },
178 ],
179 },
180 };
181
182 dataLogger.core!.configHandler.loadConfig = jest
183 .fn()
184 .mockResolvedValue(mockConfig);
185
186 await dataLogger.logDevData(TEST_EVENT);
187
188 expect(logLocalDataSpy).toHaveBeenCalledWith(TEST_EVENT);
189 expect(logToOneDestinationSpy).toHaveBeenCalledTimes(2);
190 });
191 });
192});