1
1
# Copyright (c) Microsoft Corporation. All rights reserved.
2
2
# Licensed under the MIT License.
3
3
4
- import importlib .util
5
4
import os
6
5
import pathlib
7
6
import subprocess
8
7
import sys
9
8
from contextlib import contextmanager , suppress
10
- from typing import TYPE_CHECKING , Generator , List
11
-
12
- if TYPE_CHECKING :
13
- from importlib .machinery import ModuleSpec
14
-
9
+ from typing import Generator , List
15
10
16
11
script_dir = pathlib .Path (__file__ ).parent
17
12
sys .path .append (os .fspath (script_dir ))
@@ -75,8 +70,9 @@ def django_discovery_runner(manage_py_path: str, args: List[str]) -> None:
75
70
76
71
77
72
def django_execution_runner (manage_py_path : str , test_ids : List [str ], args : List [str ]) -> None :
73
+ manage_path : pathlib .Path = pathlib .Path (manage_py_path )
78
74
# Attempt a small amount of validation on the manage.py path.
79
- if not pathlib . Path ( manage_py_path ) .exists ():
75
+ if not manage_path .exists ():
80
76
raise VSCodeUnittestError ("Error running Django, manage.py path does not exist." )
81
77
82
78
try :
@@ -89,28 +85,27 @@ def django_execution_runner(manage_py_path: str, test_ids: List[str], args: List
89
85
else :
90
86
env ["PYTHONPATH" ] = os .fspath (custom_test_runner_dir )
91
87
92
- django_project_dir : pathlib .Path = pathlib . Path ( manage_py_path ) .parent
88
+ django_project_dir : pathlib .Path = manage_path .parent
93
89
sys .path .insert (0 , os .fspath (django_project_dir ))
94
90
print (f"Django project directory: { django_project_dir } " )
95
91
96
- manage_spec : ModuleSpec | None = importlib .util .spec_from_file_location (
97
- "manage" , manage_py_path
98
- )
99
- if manage_spec is None or manage_spec .loader is None :
100
- raise VSCodeUnittestError ("Error importing manage.py when running Django testing." )
101
- manage_module = importlib .util .module_from_spec (manage_spec )
102
- manage_spec .loader .exec_module (manage_module )
103
-
104
92
manage_argv : List [str ] = [
105
- manage_py_path ,
93
+ str ( manage_path ) ,
106
94
"test" ,
107
95
"--testrunner=django_test_runner.CustomExecutionTestRunner" ,
108
96
* args ,
109
97
* test_ids ,
110
98
]
111
99
print (f"Django manage.py arguments: { manage_argv } " )
112
100
113
- with override_argv (manage_argv ), suppress (SystemExit ):
114
- manage_module .main ()
101
+ try :
102
+ argv_context = override_argv (manage_argv )
103
+ suppress_context = suppress (SystemExit )
104
+ manage_file = manage_path .open ()
105
+ with argv_context , suppress_context , manage_file :
106
+ manage_code = manage_file .read ()
107
+ exec (manage_code , {"__name__" : "__main__" })
108
+ except OSError as e :
109
+ raise VSCodeUnittestError ("Error running Django, unable to read manage.py" ) from e
115
110
except Exception as e :
116
111
print (f"Error during Django test execution: { e } " , file = sys .stderr )
0 commit comments