-
Notifications
You must be signed in to change notification settings - Fork 793
Expand file tree
/
Copy pathinline.test.ts
More file actions
244 lines (214 loc) · 9.84 KB
/
inline.test.ts
File metadata and controls
244 lines (214 loc) · 9.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
/*!
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
import * as vscode from 'vscode'
import assert from 'assert'
import {
closeAllEditors,
getTestWindow,
registerAuthHook,
resetCodeWhispererGlobalVariables,
TestFolder,
toTextEditor,
using,
} from 'aws-core-vscode/test'
import { RecommendationHandler, RecommendationService, session } from 'aws-core-vscode/codewhisperer'
import { Commands, globals, sleep, waitUntil, collectionUtil } from 'aws-core-vscode/shared'
import { loginToIdC } from '../amazonq/utils/setup'
describe.skip('Amazon Q Inline', async function () {
const retries = 3
this.retries(retries)
let tempFolder: string
const waitOptions = {
interval: 500,
timeout: 10000,
retryOnFail: false,
}
before(async function () {
await using(registerAuthHook('amazonq-test-account'), async () => {
await loginToIdC()
})
})
beforeEach(async function () {
registerAuthHook('amazonq-test-account')
const folder = await TestFolder.create()
tempFolder = folder.path
await closeAllEditors()
await resetCodeWhispererGlobalVariables()
})
afterEach(async function () {
await closeAllEditors()
if (this.currentTest?.state === undefined || this.currentTest?.isFailed() || this.currentTest?.isPending()) {
logUserDecisionStatus()
}
})
function logUserDecisionStatus() {
const events = getUserTriggerDecision()
console.table({
'telemetry events': JSON.stringify(events),
'recommendation service status': RecommendationService.instance.isRunning,
})
}
async function setupEditor({ name, contents }: { name?: string; contents?: string } = {}) {
const fileName = name ?? 'test.ts'
const textContents =
contents ??
`function fib() {
}`
await toTextEditor(textContents, fileName, tempFolder, {
selection: new vscode.Range(new vscode.Position(1, 4), new vscode.Position(1, 4)),
})
}
async function waitForRecommendations() {
const suggestionShown = await waitUntil(async () => session.getSuggestionState(0) === 'Showed', waitOptions)
if (!suggestionShown) {
throw new Error(`Suggestion did not show. Suggestion States: ${JSON.stringify(session.suggestionStates)}`)
}
const suggestionVisible = await waitUntil(
async () => RecommendationHandler.instance.isSuggestionVisible(),
waitOptions
)
if (!suggestionVisible) {
throw new Error(
`Suggestions failed to become visible. Suggestion States: ${JSON.stringify(session.suggestionStates)}`
)
}
console.table({
'suggestions states': JSON.stringify(session.suggestionStates),
'valid recommendation': RecommendationHandler.instance.isValidResponse(),
'recommendation service status': RecommendationService.instance.isRunning,
recommendations: session.recommendations,
})
if (!RecommendationHandler.instance.isValidResponse()) {
throw new Error('Did not find a valid response')
}
}
/**
* Waits for a specific telemetry event to be emitted with the expected suggestion state.
* It looks like there might be a potential race condition in codewhisperer causing telemetry
* events to be emitted in different orders
*/
async function waitForTelemetry(metricName: string, suggestionState: string) {
const ok = await waitUntil(async () => {
const events = globals.telemetry.logger.query({
metricName,
})
return events.some((event) => event.codewhispererSuggestionState === suggestionState)
}, waitOptions)
if (!ok) {
assert.fail(`Telemetry for ${metricName} with suggestionState ${suggestionState} was not emitted`)
}
const events = getUserTriggerDecision()
if (events.length > 1 && events[events.length - 1].codewhispererSuggestionState !== suggestionState) {
assert.fail(`Telemetry events were emitted in the wrong order`)
}
}
function getUserTriggerDecision() {
return globals.telemetry.logger
.query({
metricName: 'codewhisperer_userTriggerDecision',
})
.map((e) => collectionUtil.partialClone(e, 3, ['credentialStartUrl'], { replacement: '[omitted]' }))
}
for (const [name, invokeCompletion] of [
['automatic', async () => await vscode.commands.executeCommand('type', { text: '\n' })],
['manual', async () => Commands.tryExecute('aws.amazonq.invokeInlineCompletion')],
] as const) {
describe(`${name} invoke`, async function () {
let originalEditorContents: string | undefined
describe('supported filetypes', () => {
async function setup() {
await setupEditor()
/**
* Allow some time between when the editor is opened and when we start typing.
* If we don't do this then the time between the initial editor selection
* and invoking the "type" command is too low, causing completion to never
* activate. AFAICT there isn't anything we can use waitUntil on here.
*
* note: this number is entirely arbitrary
**/
await sleep(1000)
await invokeCompletion()
originalEditorContents = vscode.window.activeTextEditor?.document.getText()
// wait until the ghost text appears
await waitForRecommendations()
}
beforeEach(async () => {
/**
* Every once and a while the backend won't respond with any recommendations.
* In those cases, re-try the setup up-to ${retries} times
*/
let attempt = 0
while (attempt < retries) {
try {
await setup()
console.log(`test run ${attempt} succeeded`)
logUserDecisionStatus()
break
} catch (e) {
console.log(`test run ${attempt} failed`)
console.log(e)
logUserDecisionStatus()
attempt++
await resetCodeWhispererGlobalVariables()
}
}
if (attempt === retries) {
assert.fail(`Failed to invoke ${name} tests after ${attempt} attempts`)
}
})
it(`${name} invoke accept`, async function () {
/**
* keep accepting the suggestion until the text contents change
* this is required because we have no access to the inlineSuggest panel
**/
const suggestionAccepted = await waitUntil(async () => {
// Accept the suggestion
await vscode.commands.executeCommand('editor.action.inlineSuggest.commit')
return vscode.window.activeTextEditor?.document.getText() !== originalEditorContents
}, waitOptions)
assert.ok(suggestionAccepted, 'Editor contents should have changed')
await waitForTelemetry('codewhisperer_userTriggerDecision', 'Accept')
})
it(`${name} invoke reject`, async function () {
// Reject the suggestion
await vscode.commands.executeCommand('aws.amazonq.rejectCodeSuggestion')
// Contents haven't changed
assert.deepStrictEqual(vscode.window.activeTextEditor?.document.getText(), originalEditorContents)
await waitForTelemetry('codewhisperer_userTriggerDecision', 'Reject')
})
it(`${name} invoke discard`, async function () {
// Discard the suggestion by moving it back to the original position
const position = new vscode.Position(1, 4)
const editor = vscode.window.activeTextEditor
if (!editor) {
assert.fail('Could not find text editor')
}
editor.selection = new vscode.Selection(position, position)
// Contents are the same
assert.deepStrictEqual(vscode.window.activeTextEditor?.document.getText(), originalEditorContents)
})
})
it(`${name} invoke on unsupported filetype`, async function () {
await setupEditor({
name: 'test.zig',
contents: `fn doSomething() void {
}`,
})
/**
* Add delay between editor loading and invoking completion
* @see beforeEach in supported filetypes for more information
*/
await sleep(1000)
await invokeCompletion()
if (name === 'automatic') {
// It should never get triggered since its not a supported file type
assert.deepStrictEqual(RecommendationService.instance.isRunning, false)
} else {
await getTestWindow().waitForMessage('currently not supported by Amazon Q inline suggestions')
}
})
})
}
})