summaryrefslogtreecommitdiff
path: root/test/inspector/test-inspector.js
blob: 9d5cf9aa3a4ffaee8a360af52c83c1d73b9f66f9 (plain)
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
'use strict';
const common = require('../common');

common.skipIfInspectorDisabled();

const assert = require('assert');
const helper = require('./inspector-helper.js');

let scopeId;

function checkListResponse(err, response) {
  assert.ifError(err);
  assert.strictEqual(1, response.length);
  assert.ok(response[0]['devtoolsFrontendUrl']);
  assert.ok(
    /ws:\/\/127\.0\.0\.1:\d+\/[0-9A-Fa-f]{8}-/
      .test(response[0]['webSocketDebuggerUrl']));
}

function checkVersion(err, response) {
  assert.ifError(err);
  assert.ok(response);
  const expected = {
    'Browser': `node.js/${process.version}`,
    'Protocol-Version': '1.1',
  };
  assert.strictEqual(JSON.stringify(response),
                     JSON.stringify(expected));
}

function checkBadPath(err, response) {
  assert(err instanceof SyntaxError);
  assert(/Unexpected token/.test(err.message));
  assert(/WebSockets request was expected/.test(err.response));
}

function expectMainScriptSource(result) {
  const expected = helper.mainScriptSource();
  const source = result['scriptSource'];
  assert(source && (source.includes(expected)),
         `Script source is wrong: ${source}`);
}

function setupExpectBreakOnLine(line, url, session, scopeIdCallback) {
  return function(message) {
    if ('Debugger.paused' === message['method']) {
      const callFrame = message['params']['callFrames'][0];
      const location = callFrame['location'];
      assert.strictEqual(url, session.scriptUrlForId(location['scriptId']));
      assert.strictEqual(line, location['lineNumber']);
      scopeIdCallback &&
          scopeIdCallback(callFrame['scopeChain'][0]['object']['objectId']);
      return true;
    }
  };
}

function setupExpectConsoleOutput(type, values) {
  if (!(values instanceof Array))
    values = [ values ];
  return function(message) {
    if ('Runtime.consoleAPICalled' === message['method']) {
      const params = message['params'];
      if (params['type'] === type) {
        let i = 0;
        for (const value of params['args']) {
          if (value['value'] !== values[i++])
            return false;
        }
        return i === values.length;
      }
    }
  };
}

function setupExpectScopeValues(expected) {
  return function(result) {
    for (const actual of result['result']) {
      const value = expected[actual['name']];
      if (value)
        assert.strictEqual(value, actual['value']['value']);
    }
  };
}

function setupExpectValue(value) {
  return function(result) {
    assert.strictEqual(value, result['result']['value']);
  };
}

function setupExpectContextDestroyed(id) {
  return function(message) {
    if ('Runtime.executionContextDestroyed' === message['method'])
      return message['params']['executionContextId'] === id;
  };
}

function testBreakpointOnStart(session) {
  console.log('[test]',
              'Verifying debugger stops on start (--inspect-brk option)');
  const commands = [
    { 'method': 'Runtime.enable' },
    { 'method': 'Debugger.enable' },
    { 'method': 'Debugger.setPauseOnExceptions',
      'params': { 'state': 'none' } },
    { 'method': 'Debugger.setAsyncCallStackDepth',
      'params': { 'maxDepth': 0 } },
    { 'method': 'Profiler.enable' },
    { 'method': 'Profiler.setSamplingInterval',
      'params': { 'interval': 100 } },
    { 'method': 'Debugger.setBlackboxPatterns',
      'params': { 'patterns': [] } },
    { 'method': 'Runtime.runIfWaitingForDebugger' }
  ];

  session
    .sendInspectorCommands(commands)
    .expectMessages(setupExpectBreakOnLine(0, session.mainScriptPath, session));
}

function testSetBreakpointAndResume(session) {
  console.log('[test]', 'Setting a breakpoint and verifying it is hit');
  const commands = [
      { 'method': 'Debugger.setBreakpointByUrl',
        'params': { 'lineNumber': 5,
                    'url': session.mainScriptPath,
                    'columnNumber': 0,
                    'condition': ''
        }
      },
      { 'method': 'Debugger.resume' },
      [ { 'method': 'Debugger.getScriptSource',
          'params': { 'scriptId': session.mainScriptId } },
        expectMainScriptSource ],
  ];
  session
    .sendInspectorCommands(commands)
    .expectMessages([
      setupExpectConsoleOutput('log', ['A message', 5]),
      setupExpectBreakOnLine(5, session.mainScriptPath,
                             session, (id) => scopeId = id),
    ]);
}

function testInspectScope(session) {
  console.log('[test]', 'Verify we can read current application state');
  session.sendInspectorCommands([
    [
      {
        'method': 'Runtime.getProperties',
        'params': {
          'objectId': scopeId,
          'ownProperties': false,
          'accessorPropertiesOnly': false,
          'generatePreview': true
        }
      }, setupExpectScopeValues({ t: 1001, k: 1 })
    ],
    [
      {
        'method': 'Debugger.evaluateOnCallFrame', 'params': {
          'callFrameId': '{"ordinal":0,"injectedScriptId":1}',
          'expression': 'k + t',
          'objectGroup': 'console',
          'includeCommandLineAPI': true,
          'silent': false,
          'returnByValue': false,
          'generatePreview': true
        }
      }, setupExpectValue(1002)
    ],
    [
      {
        'method': 'Runtime.evaluate', 'params': {
          'expression': '5 * 5'
        }
      }, (message) => assert.strictEqual(25, message['result']['value'])
    ],
  ]);
}

function testNoUrlsWhenConnected(session) {
  session.testHttpResponse('/json/list', (err, response) => {
    assert.ifError(err);
    assert.strictEqual(1, response.length);
    assert.ok(!response[0].hasOwnProperty('devtoolsFrontendUrl'));
    assert.ok(!response[0].hasOwnProperty('webSocketDebuggerUrl'));
  });
}

function testI18NCharacters(session) {
  console.log('[test]', 'Verify sending and receiving UTF8 characters');
  const chars = 'טֶ字и';
  session.sendInspectorCommands([
    {
      'method': 'Debugger.evaluateOnCallFrame', 'params': {
        'callFrameId': '{"ordinal":0,"injectedScriptId":1}',
        'expression': `console.log("${chars}")`,
        'objectGroup': 'console',
        'includeCommandLineAPI': true,
        'silent': false,
        'returnByValue': false,
        'generatePreview': true
      }
    }
  ]).expectMessages([
    setupExpectConsoleOutput('log', [chars]),
  ]);
}

function testWaitsForFrontendDisconnect(session, harness) {
  console.log('[test]', 'Verify node waits for the frontend to disconnect');
  session.sendInspectorCommands({ 'method': 'Debugger.resume' })
    .expectMessages(setupExpectContextDestroyed(1))
    .expectStderrOutput('Waiting for the debugger to disconnect...')
    .disconnect(true);
}

function runTests(harness) {
  harness
    .testHttpResponse(null, '/json', checkListResponse)
    .testHttpResponse(null, '/json/list', checkListResponse)
    .testHttpResponse(null, '/json/version', checkVersion)
    .testHttpResponse(null, '/json/activate', checkBadPath)
    .testHttpResponse(null, '/json/activate/boom', checkBadPath)
    .testHttpResponse(null, '/json/badpath', checkBadPath)
    .runFrontendSession([
      testNoUrlsWhenConnected,
      testBreakpointOnStart,
      testSetBreakpointAndResume,
      testInspectScope,
      testI18NCharacters,
      testWaitsForFrontendDisconnect
    ]).expectShutDown(55);
}

helper.startNodeForInspectorTest(runTests);