using System;
using System.IO;
using NUnit.Framework;
using Python.Runtime;
namespace Python.EmbeddingTest
{
///
/// Test Import unittests and regressions
///
///
/// Keeping in old-style SetUp/TearDown due to required SetUp.
/// The required directory structure was added to .\pythonnet\src\embed_tests\fixtures\ directory:
/// + PyImportTest/
/// | - __init__.py
/// | + test/
/// | | - __init__.py
/// | | - one.py
///
public class PyImportTest
{
private IntPtr _gs;
[SetUp]
public void SetUp()
{
PythonEngine.Initialize();
_gs = PythonEngine.AcquireLock();
/* Append the tests directory to sys.path
* using reflection to circumvent the private
* modifiers placed on most Runtime methods. */
string testPath = Path.Combine(TestContext.CurrentContext.TestDirectory, "fixtures");
TestContext.Out.WriteLine(testPath);
IntPtr str = Runtime.Runtime.PyString_FromString(testPath);
BorrowedReference path = Runtime.Runtime.PySys_GetObject("path");
Runtime.Runtime.PyList_Append(path, str);
Runtime.Runtime.XDecref(str);
}
[TearDown]
public void Dispose()
{
PythonEngine.ReleaseLock(_gs);
PythonEngine.Shutdown();
}
///
/// Test subdirectory import
///
[Test]
public void TestDottedName()
{
PyObject module = PythonEngine.ImportModule("PyImportTest.test.one");
Assert.IsNotNull(module);
}
///
/// Tests that sys.args is set. If it wasn't exception would be raised.
///
[Test]
public void TestSysArgsImportException()
{
PyObject module = PythonEngine.ImportModule("PyImportTest.sysargv");
Assert.IsNotNull(module);
}
///
/// Test Global Variable casting. GH#420
///
[Test]
public void TestCastGlobalVar()
{
dynamic foo = Py.Import("PyImportTest.cast_global_var");
Assert.AreEqual("1", foo.FOO.ToString());
Assert.AreEqual("1", foo.test_foo().ToString());
foo.FOO = 2;
Assert.AreEqual("2", foo.FOO.ToString());
Assert.AreEqual("2", foo.test_foo().ToString());
}
[Test]
public void BadAssembly()
{
string path;
if (Python.Runtime.Runtime.IsWindows)
{
path = @"C:\Windows\System32\kernel32.dll";
}
else
{
Assert.Pass("TODO: add bad assembly location for other platforms");
return;
}
string code = $@"
import clr
clr.AddReference('{path}')
";
var error = Assert.Throws(() => PythonEngine.Exec(code));
Assert.AreEqual(nameof(FileLoadException), error.PythonTypeName);
}
}
}