forked from microsoft/vscode-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexecution.py
More file actions
313 lines (258 loc) · 10.1 KB
/
execution.py
File metadata and controls
313 lines (258 loc) · 10.1 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
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import argparse
import enum
import json
import os
import pathlib
import socket
import sys
import traceback
import unittest
from types import TracebackType
from typing import Dict, List, Optional, Tuple, Type, Union
script_dir = pathlib.Path(__file__).parent.parent
sys.path.append(os.fspath(script_dir))
sys.path.insert(0, os.fspath(script_dir / "lib" / "python"))
from testing_tools import process_json_util, socket_manager
from typing_extensions import NotRequired, TypeAlias, TypedDict
from unittestadapter.utils import parse_unittest_args
DEFAULT_PORT = "45454"
def parse_execution_cli_args(
args: List[str],
) -> Tuple[int, Union[str, None]]:
"""Parse command-line arguments that should be processed by the script.
So far this includes the port number that it needs to connect to, the uuid passed by the TS side,
and the list of test ids to report.
The port is passed to the execution.py script when it is executed, and
defaults to DEFAULT_PORT if it can't be parsed.
The list of test ids is passed to the execution.py script when it is executed, and defaults to an empty list if it can't be parsed.
The uuid should be passed to the execution.py script when it is executed, and defaults to None if it can't be parsed.
If the arguments appear several times, the value returned by parse_cli_args will be the value of the last argument.
"""
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument("--port", default=DEFAULT_PORT)
arg_parser.add_argument("--uuid")
parsed_args, _ = arg_parser.parse_known_args(args)
return (int(parsed_args.port), parsed_args.uuid)
ErrorType = Union[
Tuple[Type[BaseException], BaseException, TracebackType], Tuple[None, None, None]
]
PORT = 0
UUID = 0
START_DIR = ""
class TestOutcomeEnum(str, enum.Enum):
error = "error"
failure = "failure"
success = "success"
skipped = "skipped"
expected_failure = "expected-failure"
unexpected_success = "unexpected-success"
subtest_success = "subtest-success"
subtest_failure = "subtest-failure"
class UnittestTestResult(unittest.TextTestResult):
def __init__(self, *args, **kwargs):
self.formatted: Dict[str, Dict[str, Union[str, None]]] = dict()
super(UnittestTestResult, self).__init__(*args, **kwargs)
def startTest(self, test: unittest.TestCase):
super(UnittestTestResult, self).startTest(test)
def addError(
self,
test: unittest.TestCase,
err: ErrorType,
):
super(UnittestTestResult, self).addError(test, err)
self.formatResult(test, TestOutcomeEnum.error, err)
def addFailure(
self,
test: unittest.TestCase,
err: ErrorType,
):
super(UnittestTestResult, self).addFailure(test, err)
self.formatResult(test, TestOutcomeEnum.failure, err)
def addSuccess(self, test: unittest.TestCase):
super(UnittestTestResult, self).addSuccess(test)
self.formatResult(test, TestOutcomeEnum.success)
def addSkip(self, test: unittest.TestCase, reason: str):
super(UnittestTestResult, self).addSkip(test, reason)
self.formatResult(test, TestOutcomeEnum.skipped)
def addExpectedFailure(self, test: unittest.TestCase, err: ErrorType):
super(UnittestTestResult, self).addExpectedFailure(test, err)
self.formatResult(test, TestOutcomeEnum.expected_failure, err)
def addUnexpectedSuccess(self, test: unittest.TestCase):
super(UnittestTestResult, self).addUnexpectedSuccess(test)
self.formatResult(test, TestOutcomeEnum.unexpected_success)
def addSubTest(
self,
test: unittest.TestCase,
subtest: unittest.TestCase,
err: Union[ErrorType, None],
):
super(UnittestTestResult, self).addSubTest(test, subtest, err)
self.formatResult(
test,
TestOutcomeEnum.subtest_failure if err else TestOutcomeEnum.subtest_success,
err,
subtest,
)
def formatResult(
self,
test: unittest.TestCase,
outcome: str,
error: Union[ErrorType, None] = None,
subtest: Union[unittest.TestCase, None] = None,
):
tb = None
if error and error[2] is not None:
# Format traceback
formatted = traceback.format_exception(*error)
# Remove the 'Traceback (most recent call last)'
formatted = formatted[1:]
tb = "".join(formatted)
if subtest:
test_id = subtest.id()
else:
test_id = test.id()
result = {
"test": test.id(),
"outcome": outcome,
"message": str(error),
"traceback": tb,
"subtest": subtest.id() if subtest else None,
}
self.formatted[test_id] = result
if PORT == 0 or UUID == 0:
print("Error sending response, port or uuid unknown to python server.")
send_run_data(result, PORT, UUID)
class TestExecutionStatus(str, enum.Enum):
error = "error"
success = "success"
TestResultTypeAlias: TypeAlias = Dict[str, Dict[str, Union[str, None]]]
class PayloadDict(TypedDict):
cwd: str
status: TestExecutionStatus
result: Optional[TestResultTypeAlias]
not_found: NotRequired[List[str]]
error: NotRequired[str]
# Args: start_path path to a directory or a file, list of ids that may be empty.
# Edge cases:
# - if tests got deleted since the VS Code side last ran discovery and the current test run,
# return these test ids in the "not_found" entry, and the VS Code side can process them as "unknown";
# - if tests got added since the VS Code side last ran discovery and the current test run, ignore them.
def run_tests(
start_dir: str,
test_ids: List[str],
pattern: str,
top_level_dir: Optional[str],
uuid: Optional[str],
) -> PayloadDict:
cwd = os.path.abspath(start_dir)
status = TestExecutionStatus.error
error = None
payload: PayloadDict = {"cwd": cwd, "status": status, "result": None}
try:
# If it's a file, split path and file name.
start_dir = cwd
if cwd.endswith(".py"):
start_dir = os.path.dirname(cwd)
pattern = os.path.basename(cwd)
# Discover tests at path with the file name as a pattern (if any).
loader = unittest.TestLoader()
args = {
"start_dir": start_dir,
"pattern": pattern,
"top_level_dir": top_level_dir,
}
suite = loader.discover(start_dir, pattern, top_level_dir)
# Run tests.
runner = unittest.TextTestRunner(resultclass=UnittestTestResult)
# lets try to tailer our own suite so we can figure out running only the ones we want
loader = unittest.TestLoader()
tailor: unittest.TestSuite = loader.loadTestsFromNames(test_ids)
result: UnittestTestResult = runner.run(tailor) # type: ignore
payload["result"] = result.formatted
except Exception:
status = TestExecutionStatus.error
error = traceback.format_exc()
if error is not None:
payload["error"] = error
else:
status = TestExecutionStatus.success
payload["status"] = status
return payload
def send_run_data(raw_data, port, uuid):
# Build the request data (it has to be a POST request or the Node side will not process it), and send it.
status = raw_data["outcome"]
cwd = os.path.abspath(START_DIR)
if raw_data["subtest"]:
test_id = raw_data["subtest"]
else:
test_id = raw_data["test"]
test_dict = {}
test_dict[test_id] = raw_data
payload: PayloadDict = {"cwd": cwd, "status": status, "result": test_dict}
addr = ("localhost", port)
data = json.dumps(payload)
request = f"""Content-Length: {len(data)}
Content-Type: application/json
Request-uuid: {uuid}
{data}"""
try:
with socket_manager.SocketManager(addr) as s:
if s.socket is not None:
s.socket.sendall(request.encode("utf-8"))
except Exception as e:
print(f"Error sending response: {e}")
print(f"Request data: {request}")
if __name__ == "__main__":
# Get unittest test execution arguments.
argv = sys.argv[1:]
index = argv.index("--udiscovery")
start_dir, pattern, top_level_dir = parse_unittest_args(argv[index + 1 :])
run_test_ids_port = os.environ.get("RUN_TEST_IDS_PORT")
run_test_ids_port_int = (
int(run_test_ids_port) if run_test_ids_port is not None else 0
)
# get data from socket
test_ids_from_buffer = []
try:
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(("localhost", run_test_ids_port_int))
buffer = b""
while True:
# Receive the data from the client
data = client_socket.recv(1024 * 1024)
if not data:
break
# Append the received data to the buffer
buffer += data
try:
# Try to parse the buffer as JSON
test_ids_from_buffer = process_json_util.process_rpc_json(
buffer.decode("utf-8")
)
# Clear the buffer as complete JSON object is received
buffer = b""
# Process the JSON data
break
except json.JSONDecodeError:
# JSON decoding error, the complete JSON object is not yet received
continue
except socket.error as e:
print(f"Error: Could not connect to runTestIdsPort: {e}")
print("Error: Could not connect to runTestIdsPort")
PORT, UUID = parse_execution_cli_args(argv[:index])
if test_ids_from_buffer:
# Perform test execution.
payload = run_tests(
start_dir, test_ids_from_buffer, pattern, top_level_dir, UUID
)
else:
cwd = os.path.abspath(start_dir)
status = TestExecutionStatus.error
payload: PayloadDict = {
"cwd": cwd,
"status": status,
"error": "No test ids received from buffer",
"result": None,
}