forked from microsoft/vscode-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtestHelpers.tsx
More file actions
780 lines (691 loc) · 26.5 KB
/
testHelpers.tsx
File metadata and controls
780 lines (691 loc) · 26.5 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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
'use strict';
import * as assert from 'assert';
import { mount, ReactWrapper } from 'enzyme';
import { min } from 'lodash';
import * as path from 'path';
import * as React from 'react';
import { Provider } from 'react-redux';
import { isString } from 'util';
import { CancellationToken } from 'vscode';
import { EXTENSION_ROOT_DIR } from '../../client/common/constants';
import { traceInfo } from '../../client/common/logger';
import { createDeferred } from '../../client/common/utils/async';
import { InteractiveWindowMessages } from '../../client/datascience/interactive-common/interactiveWindowTypes';
import { IJupyterExecution } from '../../client/datascience/types';
import { getConnectedInteractiveEditor } from '../../datascience-ui/history-react/interactivePanel';
import * as InteractiveStore from '../../datascience-ui/history-react/redux/store';
import { getConnectedNativeEditor } from '../../datascience-ui/native-editor/nativeEditor';
import * as NativeStore from '../../datascience-ui/native-editor/redux/store';
import { IKeyboardEvent } from '../../datascience-ui/react-common/event';
import { ImageButton } from '../../datascience-ui/react-common/imageButton';
import { MonacoEditor } from '../../datascience-ui/react-common/monacoEditor';
import { noop } from '../core';
import { DataScienceIocContainer } from './dataScienceIocContainer';
import { createInputEvent, createKeyboardEvent } from './reactHelpers';
//tslint:disable:trailing-comma no-any no-multiline-string
export enum CellInputState {
Hidden,
Visible,
Collapsed,
Expanded
}
export enum CellPosition {
First = 'first',
Last = 'last'
}
type WaitForMessageOptions = {
/**
* Timeout for waiting for message.
* Defaults to 65_000ms.
*
* @type {number}
*/
timeoutMs?: number;
/**
* Number of times the message should be received.
* Defaults to 1.
*
* @type {number}
*/
numberOfTimes?: number;
};
/**
*
*
* @export
* @param {DataScienceIocContainer} ioc
* @param {string} message
* @param {number} [timeoutMs=65000] defaults to 65_000ms.
* @returns {Promise<void>}
*/
// tslint:disable-next-line: unified-signatures
export function waitForMessage(
ioc: DataScienceIocContainer,
message: string,
options?: WaitForMessageOptions
): Promise<void> {
const timeoutMs = options && options.timeoutMs ? options.timeoutMs : undefined;
const numberOfTimes = options && options.numberOfTimes ? options.numberOfTimes : 1;
// Wait for the mounted web panel to send a message back to the data explorer
const promise = createDeferred<void>();
traceInfo(`Waiting for message ${message} with timeout of ${timeoutMs}`);
let handler: (m: string, p: any) => void;
const timer = timeoutMs
? setTimeout(() => {
if (!promise.resolved) {
promise.reject(new Error(`Waiting for ${message} timed out`));
}
}, timeoutMs)
: undefined;
let timesMessageReceived = 0;
const dispatchedAction = `DISPATCHED_ACTION_${message}`;
handler = (m: string, _p: any) => {
if (m === message || m === dispatchedAction) {
timesMessageReceived += 1;
if (timesMessageReceived < numberOfTimes) {
return;
}
if (timer) {
clearTimeout(timer);
}
ioc.removeMessageListener(handler);
// Make sure to rerender current state.
if (ioc.wrapper) {
ioc.wrapper.update();
}
if (m === message) {
promise.resolve();
} else {
// It could a redux dispatched message.
// Wait for 10ms, wait for other stuff to finish.
// We can wait for 100ms or 1s. But thats too long.
// The assumption is that currently we do not have any setTimeouts
// in UI code that's in the magnitude of 100ms or more.
// We do have a couple of setTiemout's, but they wait for 1ms, not 100ms.
// 10ms more than sufficient for all the UI timeouts.
setTimeout(() => promise.resolve(), 10);
}
}
};
ioc.addMessageListener(handler);
return promise.promise;
}
export async function waitForMessageResponse(ioc: DataScienceIocContainer, action: () => void): Promise<void> {
ioc.wrapperCreatedPromise = createDeferred<boolean>();
action();
await ioc.wrapperCreatedPromise.promise;
ioc.wrapperCreatedPromise = undefined;
}
async function testInnerLoop(
name: string,
mountFunc: (ioc: DataScienceIocContainer) => ReactWrapper<any, Readonly<{}>, React.Component>,
testFunc: (wrapper: ReactWrapper<any, Readonly<{}>, React.Component>) => Promise<void>,
getIOC: () => DataScienceIocContainer
) {
const ioc = getIOC();
const jupyterExecution = ioc.get<IJupyterExecution>(IJupyterExecution);
if (await jupyterExecution.isNotebookSupported()) {
addMockData(ioc, 'a=1\na', 1);
const wrapper = mountFunc(ioc);
await testFunc(wrapper);
} else {
// tslint:disable-next-line:no-console
console.log(`${name} skipped, no Jupyter installed.`);
}
}
export function runDoubleTest(
name: string,
testFunc: (wrapper: ReactWrapper<any, Readonly<{}>, React.Component>) => Promise<void>,
getIOC: () => DataScienceIocContainer
) {
// Just run the test twice. Originally mounted twice, but too hard trying to figure out disposing.
test(`${name} (interactive)`, async () =>
testInnerLoop(name, ioc => mountWebView(ioc, 'interactive'), testFunc, getIOC));
test(`${name} (native)`, async () => testInnerLoop(name, ioc => mountWebView(ioc, 'native'), testFunc, getIOC));
}
export function mountWebView(
ioc: DataScienceIocContainer,
type: 'native' | 'interactive'
): ReactWrapper<any, Readonly<{}>, React.Component> {
// Setup our webview panel
ioc.createWebView(() => mountConnectedMainPanel(type));
return ioc.wrapper!;
}
export function addMockData(
ioc: DataScienceIocContainer,
code: string,
result: string | number | undefined | string[],
mimeType?: string | string[],
cellType?: string
) {
if (ioc.mockJupyter) {
if (cellType && cellType === 'error') {
ioc.mockJupyter.addError(code, result ? result.toString() : '');
} else {
if (result) {
ioc.mockJupyter.addCell(code, result, mimeType);
} else {
ioc.mockJupyter.addCell(code);
}
}
}
}
export function addInputMockData(
ioc: DataScienceIocContainer,
code: string,
result: string | number | undefined,
mimeType?: string,
cellType?: string
) {
if (ioc.mockJupyter) {
if (cellType && cellType === 'error') {
ioc.mockJupyter.addError(code, result ? result.toString() : '');
} else {
if (result) {
ioc.mockJupyter.addInputCell(code, result, mimeType);
} else {
ioc.mockJupyter.addInputCell(code);
}
}
}
}
export function addContinuousMockData(
ioc: DataScienceIocContainer,
code: string,
resultGenerator: (c: CancellationToken) => Promise<{ result: string; haveMore: boolean }>
) {
if (ioc.mockJupyter) {
ioc.mockJupyter.addContinuousOutputCell(code, resultGenerator);
}
}
export function getOutputCell(
wrapper: ReactWrapper<any, Readonly<{}>, React.Component>,
cellType: string,
cellIndex: number | CellPosition
): ReactWrapper<any, Readonly<{}>, React.Component> | undefined {
const foundResult = wrapper.find(cellType);
let targetCell: ReactWrapper | undefined;
// Get the correct result that we are dealing with
if (typeof cellIndex === 'number') {
if (cellIndex >= 0 && cellIndex <= foundResult.length - 1) {
targetCell = foundResult.at(cellIndex);
}
} else if (typeof cellIndex === 'string') {
switch (cellIndex) {
case CellPosition.First:
targetCell = foundResult.first();
break;
case CellPosition.Last:
// Skip the input cell on these checks.
targetCell = getLastOutputCell(wrapper, cellType);
break;
default:
// Fall through, targetCell check will fail out
break;
}
}
return targetCell;
}
export function getLastOutputCell(
wrapper: ReactWrapper<any, Readonly<{}>, React.Component>,
cellType: string
): ReactWrapper<any, Readonly<{}>, React.Component> {
// Skip the edit cell if in the interactive window
const count = cellType === 'InteractiveCell' ? 2 : 1;
wrapper.update();
const foundResult = wrapper.find(cellType);
return getOutputCell(wrapper, cellType, foundResult.length - count)!;
}
export function verifyHtmlOnCell(
wrapper: ReactWrapper<any, Readonly<{}>, React.Component>,
cellType: string,
html: string | undefined | RegExp,
cellIndex: number | CellPosition
) {
wrapper.update();
const foundResult = wrapper.find(cellType);
assert.ok(foundResult.length >= 1, "Didn't find any cells being rendered");
let targetCell: ReactWrapper;
// Get the correct result that we are dealing with
if (typeof cellIndex === 'number') {
if (cellIndex >= 0 && cellIndex <= foundResult.length - 1) {
targetCell = foundResult.at(cellIndex);
}
} else if (typeof cellIndex === 'string') {
switch (cellIndex) {
case CellPosition.First:
targetCell = foundResult.first();
break;
case CellPosition.Last:
// Skip the input cell on these checks.
targetCell = getLastOutputCell(wrapper, cellType);
break;
default:
// Fall through, targetCell check will fail out
break;
}
}
// ! is ok here to get rid of undefined type check as we want a fail here if we have not initialized targetCell
assert.ok(targetCell!, "Target cell doesn't exist");
// If html is specified, check it
let output = targetCell!.find('div.cell-output');
if (output.length <= 0) {
output = targetCell!.find('div.markdown-cell-output');
}
const outputHtml = output.length > 0 ? output.html() : undefined;
if (html && isString(html)) {
// Extract only the first 100 chars from the input string
const sliced = html.substr(0, min([html.length, 100]));
assert.ok(output.length > 0, 'No output cell found');
assert.ok(outputHtml?.includes(sliced), `${outputHtml} does not contain ${sliced}`);
} else if (html && outputHtml) {
const regex = html as RegExp;
assert.ok(regex.test(outputHtml), `${outputHtml} does not match ${html}`);
} else {
// html not specified, look for an empty render
assert.ok(
targetCell!.isEmptyRender() || outputHtml === undefined,
`Target cell is not empty render, got this instead: ${outputHtml}`
);
}
}
/**
* Creates a keyboard event for a cells.
*
* @export
* @param {(Partial<IKeyboardEvent> & { code: string })} event
* @returns
*/
export function createKeyboardEventForCell(event: Partial<IKeyboardEvent> & { code: string }) {
const defaultKeyboardEvent: IKeyboardEvent = {
altKey: false,
code: '',
ctrlKey: false,
editorInfo: {
contents: '',
isDirty: false,
isFirstLine: false,
isLastLine: false,
isSuggesting: false,
clear: noop
},
metaKey: false,
preventDefault: noop,
shiftKey: false,
stopPropagation: noop,
target: {} as any
};
const defaultEditorInfo = defaultKeyboardEvent.editorInfo!;
const providedEditorInfo = event.editorInfo || {};
return {
...defaultKeyboardEvent,
...event,
editorInfo: {
...defaultEditorInfo,
...providedEditorInfo
}
};
}
export function isCellSelected(
wrapper: ReactWrapper<any, Readonly<{}>, React.Component>,
cellType: string,
cellIndex: number | CellPosition
): boolean {
try {
verifyCell(wrapper, cellType, { selector: '.cell-wrapper-selected' }, cellIndex);
return true;
} catch {
return false;
}
}
export function isCellFocused(
wrapper: ReactWrapper<any, Readonly<{}>, React.Component>,
cellType: string,
cellIndex: number | CellPosition
): boolean {
try {
verifyCell(wrapper, cellType, { selector: '.cell-wrapper-focused' }, cellIndex);
return true;
} catch {
return false;
}
}
export function isCellMarkdown(
wrapper: ReactWrapper<any, Readonly<{}>, React.Component>,
cellType: string,
cellIndex: number | CellPosition
): boolean {
const cell = getOutputCell(wrapper, cellType, cellIndex);
assert.ok(cell, 'Could not find output cell');
return cell!.props().cellVM.cell.data.cell_type === 'markdown';
}
export function verifyCellIndex(
wrapper: ReactWrapper<any, Readonly<{}>, React.Component>,
cellId: string,
expectedCellIndex: number
) {
const nativeCell = wrapper
.find(cellId)
.first()
.find('NativeCell');
const secondCell = wrapper.find('NativeCell').at(expectedCellIndex);
assert.equal(nativeCell.html(), secondCell.html());
}
function verifyCell(
wrapper: ReactWrapper<any, Readonly<{}>, React.Component>,
cellType: string,
options: { selector: string; shouldNotExist?: boolean },
cellIndex: number | CellPosition
) {
wrapper.update();
const foundResult = wrapper.find(cellType);
assert.ok(foundResult.length >= 1, "Didn't find any cells being rendered");
let targetCell: ReactWrapper;
// Get the correct result that we are dealing with
if (typeof cellIndex === 'number') {
if (cellIndex >= 0 && cellIndex <= foundResult.length - 1) {
targetCell = foundResult.at(cellIndex);
}
} else if (typeof cellIndex === 'string') {
switch (cellIndex) {
case CellPosition.First:
targetCell = foundResult.first();
break;
case CellPosition.Last:
// Skip the input cell on these checks.
targetCell = getLastOutputCell(wrapper, cellType);
break;
default:
// Fall through, targetCell check will fail out
break;
}
}
// ! is ok here to get rid of undefined type check as we want a fail here if we have not initialized targetCell
assert.ok(targetCell!, "Target cell doesn't exist");
if (options.shouldNotExist) {
assert.ok(
targetCell!.find(options.selector).length === 0,
`Found cells with the matching selector '${options.selector}'`
);
} else {
assert.ok(
targetCell!.find(options.selector).length >= 1,
`Didn't find any cells with the matching selector '${options.selector}'`
);
}
}
export function verifyLastCellInputState(
wrapper: ReactWrapper<any, Readonly<{}>, React.Component>,
cellType: string,
state: CellInputState
) {
const lastCell = getLastOutputCell(wrapper, cellType);
assert.ok(lastCell, "Last cell doesn't exist");
const inputBlock = lastCell.find('div.cell-input');
const toggleButton = lastCell.find('polygon.collapse-input-svg');
switch (state) {
case CellInputState.Hidden:
assert.ok(inputBlock.length === 0, 'Cell input not hidden');
break;
case CellInputState.Visible:
assert.ok(inputBlock.length === 1, 'Cell input not visible');
break;
case CellInputState.Expanded:
assert.ok(toggleButton.html().includes('collapse-input-svg-rotate'), 'Cell input toggle not expanded');
break;
case CellInputState.Collapsed:
assert.ok(!toggleButton.html().includes('collapse-input-svg-rotate'), 'Cell input toggle not collapsed');
break;
default:
assert.fail('Unknown cellInputStat');
break;
}
}
export async function getCellResults(
ioc: DataScienceIocContainer,
wrapper: ReactWrapper<any, Readonly<{}>, React.Component>,
cellType: string,
updater: () => Promise<void>,
renderPromiseGenerator?: () => Promise<void>
): Promise<ReactWrapper<any, Readonly<{}>, React.Component>> {
// Get a render promise with the expected number of renders
const renderPromise = renderPromiseGenerator
? renderPromiseGenerator()
: waitForMessage(ioc, InteractiveWindowMessages.ExecutionRendered);
// Call our function to update the react control
await updater();
// Wait for all of the renders to go through
await renderPromise;
// Update wrapper so that it gets the latest values.
wrapper.update();
// Return the result
return wrapper.find(cellType);
}
export function simulateKey(
domNode: HTMLTextAreaElement,
key: string,
shiftDown?: boolean,
ctrlKey?: boolean,
altKey?: boolean,
metaKey?: boolean
) {
// Submit a keypress into the textarea. Simulate doesn't work here because the keydown
// handler is not registered in any react code. It's being handled with DOM events
// Save current selection start so we move appropriately after the event
const selectionStart = domNode.selectionStart;
// According to this:
// https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Usage_notes
// The normal events are
// 1) keydown
// 2) keypress
// 3) keyup
let event = createKeyboardEvent('keydown', { key, code: key, shiftKey: shiftDown, ctrlKey, altKey, metaKey });
// Dispatch. Result can be swallowed. If so skip the next event.
let result = domNode.dispatchEvent(event);
if (result) {
event = createKeyboardEvent('keypress', { key, code: key, shiftKey: shiftDown, ctrlKey, altKey, metaKey });
result = domNode.dispatchEvent(event);
if (result) {
event = createKeyboardEvent('keyup', { key, code: key, shiftKey: shiftDown, ctrlKey, altKey, metaKey });
domNode.dispatchEvent(event);
// Update our value. This will reset selection to zero.
const before = domNode.value.slice(0, selectionStart);
const after = domNode.value.slice(selectionStart);
const keyText = key === 'Enter' ? '\n' : key;
domNode.value = `${before}${keyText}${after}`;
// Tell the dom node its selection start has changed. Monaco
// reads this to determine where the character went.
domNode.selectionEnd = selectionStart + 1;
domNode.selectionStart = selectionStart + 1;
// Dispatch an input event so we update the textarea
domNode.dispatchEvent(createInputEvent());
}
}
}
export async function submitInput(ioc: DataScienceIocContainer, textArea: HTMLTextAreaElement): Promise<void> {
// Get a render promise with the expected number of renders (how many updates a the shift + enter will cause)
// Should be 6 - 1 for the shift+enter and 5 for the new cell.
const renderPromise = waitForMessage(ioc, InteractiveWindowMessages.ExecutionRendered);
// Submit a keypress into the textarea
simulateKey(textArea, 'Enter', true);
return renderPromise;
}
function enterKey(
textArea: HTMLTextAreaElement,
key: string,
shiftDown?: boolean,
ctrlKey?: boolean,
altKey?: boolean,
metaKey?: boolean
) {
// Simulate a key press
simulateKey(textArea, key, shiftDown, ctrlKey, altKey, metaKey);
}
export function getInteractiveEditor(
wrapper: ReactWrapper<any, Readonly<{}>, React.Component>
): ReactWrapper<any, Readonly<{}>, React.Component> {
wrapper.update();
// Find the last cell. It should have a monacoEditor object
const cells = wrapper.find('InteractiveCell');
const lastCell = cells.last();
return lastCell.find('MonacoEditor');
}
export function getNativeEditor(
wrapper: ReactWrapper<any, Readonly<{}>, React.Component>,
index: number
): ReactWrapper<any, Readonly<{}>, React.Component> | undefined {
// Find the last cell. It should have a monacoEditor object
const cells = wrapper.find('NativeCell');
const lastCell = index < cells.length ? cells.at(index) : undefined;
return lastCell ? lastCell.find('MonacoEditor') : undefined;
}
export function getNativeFocusedEditor(
wrapper: ReactWrapper<any, Readonly<{}>, React.Component>
): ReactWrapper<any, Readonly<{}>, React.Component> | undefined {
// Find the last cell. It should have a monacoEditor object
wrapper.update();
const cells = wrapper.find('NativeCell');
const focusedCell = cells.find('.cell-wrapper-focused');
return focusedCell.length > 0 ? focusedCell.find('MonacoEditor') : undefined;
}
export function injectCode(
editorControl: ReactWrapper<any, Readonly<{}>, React.Component> | undefined,
code: string
): HTMLTextAreaElement | null {
assert.ok(editorControl, 'Editor undefined for injecting code');
const ecDom = editorControl!.getDOMNode();
assert.ok(ecDom, 'ec DOM object not found');
const textArea = ecDom!.querySelector('.overflow-guard')!.querySelector('textarea');
assert.ok(textArea!, 'Cannot find the textarea inside the monaco editor');
textArea!.focus();
// Just stick directly into the model.
const editor = editorControl!.instance() as MonacoEditor;
assert.ok(editor, 'MonacoEditor not found');
const monaco = editor.state.editor;
assert.ok(monaco, 'Monaco control not found');
const model = monaco!.getModel();
assert.ok(model, 'Monaco model not found');
model!.setValue(code);
return textArea;
}
export function enterEditorKey(
editorControl: ReactWrapper<any, Readonly<{}>, React.Component> | undefined,
keyboardEvent: Partial<IKeyboardEvent> & { code: string }
): HTMLTextAreaElement | null {
const textArea = getTextArea(editorControl);
assert.ok(textArea!, 'Cannot find the textarea inside the monaco editor');
textArea!.focus();
enterKey(
textArea!,
keyboardEvent.code,
keyboardEvent.shiftKey,
keyboardEvent.ctrlKey,
keyboardEvent.altKey,
keyboardEvent.metaKey
);
return textArea;
}
export function typeCode(
editorControl: ReactWrapper<any, Readonly<{}>, React.Component> | undefined,
code: string
): HTMLTextAreaElement | null {
const textArea = getTextArea(editorControl);
assert.ok(textArea!, 'Cannot find the textarea inside the monaco editor');
textArea!.focus();
// Now simulate entering all of the keys
for (let i = 0; i < code.length; i += 1) {
let keyCode = code.charAt(i);
if (keyCode === '\n') {
keyCode = 'Enter';
}
enterKey(textArea!, keyCode);
}
return textArea;
}
function getTextArea(
editorControl: ReactWrapper<any, Readonly<{}>, React.Component> | undefined
): HTMLTextAreaElement | null {
// Find the last cell. It should have a monacoEditor object. We need to search
// through its DOM to find the actual textarea to send input to
// (we can't actually find it with the enzyme wrappers because they only search
// React accessible nodes and the monaco html is not react)
assert.ok(editorControl, 'Editor not defined in order to type code into');
let ecDom = editorControl!.getDOMNode();
if ((ecDom as any).length) {
ecDom = (ecDom as any)[0];
}
assert.ok(ecDom, 'ec DOM object not found');
return ecDom!.querySelector('.overflow-guard')!.querySelector('textarea');
}
export async function enterInput(
wrapper: ReactWrapper<any, Readonly<{}>, React.Component>,
ioc: DataScienceIocContainer,
code: string,
resultClass: string
): Promise<ReactWrapper<any, Readonly<{}>, React.Component>> {
const editor = resultClass === 'InteractiveCell' ? getInteractiveEditor(wrapper) : getNativeFocusedEditor(wrapper);
// First we have to type the code into the input box
const textArea = typeCode(editor, code);
// Now simulate a shift enter. This should cause a new cell to be added
await submitInput(ioc, textArea!);
// Return the result
return wrapper.find(resultClass);
}
export function findButton(
wrapper: ReactWrapper<any, Readonly<{}>, React.Component>,
mainClass: React.ComponentClass<any>,
index: number
): ReactWrapper<any, Readonly<{}>, React.Component> | undefined {
const mainObj = wrapper.find(mainClass);
if (mainObj) {
const buttons = mainObj.find(ImageButton);
if (buttons) {
return buttons.at(index);
}
}
}
export function getMainPanel<P>(
wrapper: ReactWrapper<any, Readonly<{}>>,
mainClass: React.ComponentClass<any>
): P | undefined {
const mainObj = wrapper.find(mainClass);
if (mainObj) {
return (mainObj.instance() as any) as P;
}
return undefined;
}
export function toggleCellExpansion(wrapper: ReactWrapper<any, Readonly<{}>, React.Component>, cellType: string) {
// Find the last cell added
const lastCell = getLastOutputCell(wrapper, cellType);
assert.ok(lastCell, "Last call doesn't exist");
const toggleButton = lastCell.find('button.collapse-input');
assert.ok(toggleButton);
toggleButton.simulate('click');
}
export function escapePath(p: string) {
return p.replace(/\\/g, '\\\\');
}
export function srcDirectory() {
return path.join(EXTENSION_ROOT_DIR, 'src', 'test', 'datascience');
}
export function mountConnectedMainPanel(type: 'native' | 'interactive') {
const ConnectedMainPanel = type === 'native' ? getConnectedNativeEditor() : getConnectedInteractiveEditor();
// Create the redux store in test mode.
const createStore = type === 'native' ? NativeStore.createStore : InteractiveStore.createStore;
const store = createStore(true, 'vs-light', true);
// Mount this with a react redux provider
return mount(
<Provider store={store}>
<ConnectedMainPanel />
</Provider>
);
}
export function mountComponent<P>(type: 'native' | 'interactive', Component: React.ReactElement<P>) {
// Create the redux store in test mode.
const createStore = type === 'native' ? NativeStore.createStore : InteractiveStore.createStore;
const store = createStore(true, 'vs-light', true);
// Mount this with a react redux provider
return mount(<Provider store={store}>{Component}</Provider>);
}