88using NUnit . Framework ;
99
1010using Python . Runtime ;
11- using Python . Test ;
1211
1312namespace Python . PythonTestsRunner
1413{
1514 public class PythonTestRunner
1615 {
16+ string OriginalDirectory ;
17+
1718 [ OneTimeSetUp ]
1819 public void SetUp ( )
1920 {
2021 PythonEngine . Initialize ( ) ;
22+ OriginalDirectory = Environment . CurrentDirectory ;
23+
24+ var codeDir = File . ReadAllText ( "tests_location.txt" ) . Trim ( ) ;
25+ TestContext . Progress . WriteLine ( $ "Changing working directory to { codeDir } ") ;
26+ Environment . CurrentDirectory = codeDir ;
2127 }
2228
2329 [ OneTimeTearDown ]
2430 public void Dispose ( )
2531 {
2632 PythonEngine . Shutdown ( ) ;
33+ Environment . CurrentDirectory = OriginalDirectory ;
2734 }
2835
2936 /// <summary>
@@ -46,39 +53,15 @@ static IEnumerable<string[]> PythonTestCases()
4653 [ TestCaseSource ( nameof ( PythonTestCases ) ) ]
4754 public void RunPythonTest ( string testFile , string testName )
4855 {
49- // Find the tests directory
50- string folder = typeof ( PythonTestRunner ) . Assembly . Location ;
51- while ( Path . GetFileName ( folder ) != "src" )
56+ using dynamic pytest = Py . Import ( "pytest" ) ;
57+
58+ using var args = new PyList ( ) ;
59+ args . Append ( new PyString ( $ "{ testFile } .py::{ testName } ") ) ;
60+ int res = pytest . main ( args ) ;
61+ if ( res != 0 )
5262 {
53- folder = Path . GetDirectoryName ( folder ) ;
63+ Assert . Fail ( $ "Python test { testFile } . { testName } failed" ) ;
5464 }
55- folder = Path . Combine ( folder , ".." , "tests" ) ;
56- string path = Path . Combine ( folder , testFile + ".py" ) ;
57- if ( ! File . Exists ( path ) ) throw new FileNotFoundException ( "Cannot find test file" , path ) ;
58-
59- // We could use 'import' below, but importlib gives more helpful error messages than 'import'
60- // https://docs.python.org/3/library/importlib.html#importing-a-source-file-directly
61- // Because the Python tests sometimes have relative imports, the module name must be inside the tests package
62- PythonEngine . Exec ( $@ "
63- import sys
64- import os
65- sys.path.append(os.path.dirname(r'{ folder } '))
66- sys.path.append(os.path.join(r'{ folder } ', 'fixtures'))
67- import clr
68- clr.AddReference('Python.Test')
69- import tests
70- module_name = 'tests.{ testFile } '
71- file_path = r'{ path } '
72- import importlib.util
73- spec = importlib.util.spec_from_file_location(module_name, file_path)
74- module = importlib.util.module_from_spec(spec)
75- sys.modules[module_name] = module
76- try:
77- spec.loader.exec_module(module)
78- except ImportError as error:
79- raise ImportError(str(error) + ' when sys.path=' + os.pathsep.join(sys.path))
80- module.{ testName } ()
81- " ) ;
8265 }
8366 }
8467}
0 commit comments