EditorPythonBindingsTest.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  1. /*
  2. * Copyright (c) Contributors to the Open 3D Engine Project.
  3. * For complete copyright and license terms please see the LICENSE at the root of this distribution.
  4. *
  5. * SPDX-License-Identifier: Apache-2.0 OR MIT
  6. *
  7. */
  8. #include <EditorPythonBindings/PythonCommon.h>
  9. #include <pybind11/pybind11.h>
  10. #include "PythonTraceMessageSink.h"
  11. #include "PythonTestingUtility.h"
  12. #include <Source/PythonSystemComponent.h>
  13. #include <EditorPythonBindings/EditorPythonBindingsBus.h>
  14. #include <AzCore/Debug/TraceMessageBus.h>
  15. #include <AzCore/Settings/SettingsRegistryMergeUtils.h>
  16. #include <AzFramework/StringFunc/StringFunc.h>
  17. #include <AzToolsFramework/API/EditorPythonRunnerRequestsBus.h>
  18. namespace UnitTest
  19. {
  20. struct EditorPythonBindingsNotificationBusSink final
  21. : public EditorPythonBindings::EditorPythonBindingsNotificationBus::Handler
  22. {
  23. EditorPythonBindingsNotificationBusSink()
  24. {
  25. EditorPythonBindings::EditorPythonBindingsNotificationBus::Handler::BusConnect();
  26. }
  27. ~EditorPythonBindingsNotificationBusSink()
  28. {
  29. EditorPythonBindings::EditorPythonBindingsNotificationBus::Handler::BusDisconnect();
  30. }
  31. //////////////////////////////////////////////////////////////////////////
  32. // handles EditorPythonBindingsNotificationBus
  33. int m_OnPreInitializeCount = 0;
  34. int m_OnPostInitializeCount = 0;
  35. int m_OnPreFinalizeCount = 0;
  36. int m_OnPostFinalizeCount = 0;
  37. void OnPreInitialize() override { m_OnPreInitializeCount++; }
  38. void OnPostInitialize() override { m_OnPostInitializeCount++; }
  39. void OnPreFinalize() override { m_OnPreFinalizeCount++; }
  40. void OnPostFinalize() override { m_OnPostFinalizeCount++; }
  41. };
  42. class EditorPythonBindingsTest
  43. : public PythonTestingFixture
  44. {
  45. public:
  46. PythonTraceMessageSink m_testSink;
  47. EditorPythonBindingsNotificationBusSink m_notificationSink;
  48. void SetUp() override
  49. {
  50. PythonTestingFixture::SetUp();
  51. m_app.RegisterComponentDescriptor(EditorPythonBindings::PythonSystemComponent::CreateDescriptor());
  52. }
  53. void TearDown() override
  54. {
  55. // clearing up memory
  56. m_notificationSink = EditorPythonBindingsNotificationBusSink();
  57. m_testSink.CleanUp();
  58. // shutdown time!
  59. PythonTestingFixture::TearDown();
  60. }
  61. };
  62. TEST_F(EditorPythonBindingsTest, FireUpPythonVM)
  63. {
  64. enum class LogTypes
  65. {
  66. Skip = 0,
  67. General,
  68. RedirectOutputInstalled
  69. };
  70. m_testSink.m_evaluateMessage = [](const char* window, const char* message) -> int
  71. {
  72. if (AzFramework::StringFunc::Equal(window, "python"))
  73. {
  74. if (AzFramework::StringFunc::Equal(message, "RedirectOutput installed"))
  75. {
  76. return static_cast<int>(LogTypes::RedirectOutputInstalled);
  77. }
  78. return static_cast<int>(LogTypes::General);
  79. }
  80. return static_cast<int>(LogTypes::Skip);
  81. };
  82. AZ::Entity e;
  83. e.CreateComponent<EditorPythonBindings::PythonSystemComponent>();
  84. e.Init();
  85. e.Activate();
  86. SimulateEditorBecomingInitialized();
  87. e.Deactivate();
  88. EXPECT_GT(m_testSink.m_evaluationMap[(int)LogTypes::General], 0);
  89. EXPECT_EQ(m_testSink.m_evaluationMap[(int)LogTypes::RedirectOutputInstalled], 1);
  90. EXPECT_EQ(m_notificationSink.m_OnPreInitializeCount, 1);
  91. EXPECT_EQ(m_notificationSink.m_OnPostFinalizeCount, 1);
  92. EXPECT_EQ(m_notificationSink.m_OnPreFinalizeCount, 1);
  93. EXPECT_EQ(m_notificationSink.m_OnPostFinalizeCount, 1);
  94. }
  95. TEST_F(EditorPythonBindingsTest, RunScriptTextBuffer)
  96. {
  97. enum class LogTypes
  98. {
  99. Skip = 0,
  100. ScriptWorked
  101. };
  102. m_testSink.m_evaluateMessage = [](const char* window, const char* message) -> int
  103. {
  104. if (AzFramework::StringFunc::Equal(window, "python"))
  105. {
  106. if (AzFramework::StringFunc::Equal(message, "EditorPythonBindingsTest_RunScriptTextBuffer"))
  107. {
  108. return static_cast<int>(LogTypes::ScriptWorked);
  109. }
  110. }
  111. return static_cast<int>(LogTypes::Skip);
  112. };
  113. AZ::Entity e;
  114. e.CreateComponent<EditorPythonBindings::PythonSystemComponent>();
  115. e.Init();
  116. e.Activate();
  117. SimulateEditorBecomingInitialized();
  118. const char* script =
  119. R"(
  120. import sys
  121. print ('EditorPythonBindingsTest_RunScriptTextBuffer')
  122. )";
  123. AzToolsFramework::EditorPythonRunnerRequestBus::Broadcast(&AzToolsFramework::EditorPythonRunnerRequestBus::Events::ExecuteByString, script, false);
  124. e.Deactivate();
  125. EXPECT_EQ(m_testSink.m_evaluationMap[(int)LogTypes::ScriptWorked], 1);
  126. }
  127. TEST_F(EditorPythonBindingsTest, RunScriptTextBufferAndPrint)
  128. {
  129. AZ::Entity e;
  130. e.CreateComponent<EditorPythonBindings::PythonSystemComponent>();
  131. e.Init();
  132. e.Activate();
  133. SimulateEditorBecomingInitialized();
  134. AZStd::string capturedOutput;
  135. m_testSink.m_evaluateMessage = [&capturedOutput](const char* window, const char* message) -> int
  136. {
  137. if (AzFramework::StringFunc::Equal(window, "python"))
  138. {
  139. capturedOutput.append(message);
  140. }
  141. return 0;
  142. };
  143. // Expressions should log their result
  144. // Any other statement shouldn't log anything
  145. capturedOutput.clear();
  146. const char* script = "5+5";
  147. AzToolsFramework::EditorPythonRunnerRequestBus::Broadcast(&AzToolsFramework::EditorPythonRunnerRequestBus::Events::ExecuteByString, script, true);
  148. EXPECT_EQ(capturedOutput, "10\n");
  149. capturedOutput.clear();
  150. script =
  151. R"(
  152. import sys
  153. sys.version
  154. )";
  155. AzToolsFramework::EditorPythonRunnerRequestBus::Broadcast(&AzToolsFramework::EditorPythonRunnerRequestBus::Events::ExecuteByString, script, true);
  156. EXPECT_EQ(capturedOutput, "");
  157. capturedOutput.clear();
  158. script = "variable = 'test'";
  159. AzToolsFramework::EditorPythonRunnerRequestBus::Broadcast(&AzToolsFramework::EditorPythonRunnerRequestBus::Events::ExecuteByString, script, true);
  160. EXPECT_EQ(capturedOutput, "");
  161. capturedOutput.clear();
  162. script = "variable";
  163. AzToolsFramework::EditorPythonRunnerRequestBus::Broadcast(&AzToolsFramework::EditorPythonRunnerRequestBus::Events::ExecuteByString, script, true);
  164. EXPECT_EQ(capturedOutput, "test\n");
  165. }
  166. TEST_F(EditorPythonBindingsTest, RunScriptFile)
  167. {
  168. enum class LogTypes
  169. {
  170. Skip = 0,
  171. RanFromFile
  172. };
  173. m_testSink.m_evaluateMessage = [](const char* window, const char* message) -> int
  174. {
  175. if (AzFramework::StringFunc::Equal(window, "python"))
  176. {
  177. AZStd::string_view m(message);
  178. if (AzFramework::StringFunc::Equal(message, "EditorPythonBindingsTest_RunScriptFile"))
  179. {
  180. return static_cast<int>(LogTypes::RanFromFile);
  181. }
  182. }
  183. return static_cast<int>(LogTypes::Skip);
  184. };
  185. AZ::IO::Path filename = AZ::IO::PathView(m_engineRoot / "Gems" / "EditorPythonBindings" / "Code" / "Tests" / "EditorPythonBindingsTest.py");
  186. AZ::Entity e;
  187. e.CreateComponent<EditorPythonBindings::PythonSystemComponent>();
  188. e.Init();
  189. e.Activate();
  190. SimulateEditorBecomingInitialized();
  191. AzToolsFramework::EditorPythonRunnerRequestBus::Broadcast(&AzToolsFramework::EditorPythonRunnerRequestBus::Events::ExecuteByFilename, filename.c_str());
  192. e.Deactivate();
  193. EXPECT_EQ(m_testSink.m_evaluationMap[(int)LogTypes::RanFromFile], 1);
  194. }
  195. TEST_F(EditorPythonBindingsTest, RunScriptFileWithArgs)
  196. {
  197. enum class LogTypes
  198. {
  199. Skip = 0,
  200. RanFromFile,
  201. NumArgsCorrect,
  202. ScriptNameCorrect,
  203. Arg1Correct,
  204. Arg2Correct,
  205. Arg3Correct
  206. };
  207. m_testSink.m_evaluateMessage = [](const char* window, const char* message) -> int
  208. {
  209. if (AzFramework::StringFunc::Equal(window, "python"))
  210. {
  211. AZStd::string_view m(message);
  212. if (AzFramework::StringFunc::Equal(message, "EditorPythonBindingsTestWithArgs_RunScriptFile"))
  213. {
  214. return static_cast<int>(LogTypes::RanFromFile);
  215. }
  216. else if (AzFramework::StringFunc::Equal(message, "num args: 4"))
  217. {
  218. return static_cast<int>(LogTypes::NumArgsCorrect);
  219. }
  220. else if (AzFramework::StringFunc::Equal(message, "script name: EditorPythonBindingsTestWithArgs.py"))
  221. {
  222. return static_cast<int>(LogTypes::ScriptNameCorrect);
  223. }
  224. else if (AzFramework::StringFunc::Equal(message, "arg 1: arg1"))
  225. {
  226. return static_cast<int>(LogTypes::Arg1Correct);
  227. }
  228. else if (AzFramework::StringFunc::Equal(message, "arg 2: 2"))
  229. {
  230. return static_cast<int>(LogTypes::Arg2Correct);
  231. }
  232. else if (AzFramework::StringFunc::Equal(message, "arg 3: arg3"))
  233. {
  234. return static_cast<int>(LogTypes::Arg3Correct);
  235. }
  236. }
  237. return static_cast<int>(LogTypes::Skip);
  238. };
  239. AZ::IO::Path filename = AZ::IO::PathView(m_engineRoot / "Gems" / "EditorPythonBindings" / "Code" / "Tests" / "EditorPythonBindingsTestWithArgs.py");
  240. AZ::Entity e;
  241. e.CreateComponent<EditorPythonBindings::PythonSystemComponent>();
  242. e.Init();
  243. e.Activate();
  244. SimulateEditorBecomingInitialized();
  245. AZStd::vector<AZStd::string_view> args;
  246. args.push_back("arg1");
  247. args.push_back("2");
  248. args.push_back("arg3");
  249. AzToolsFramework::EditorPythonRunnerRequestBus::Broadcast(&AzToolsFramework::EditorPythonRunnerRequestBus::Events::ExecuteByFilenameWithArgs, filename.c_str(), args);
  250. e.Deactivate();
  251. EXPECT_EQ(m_testSink.m_evaluationMap[(int)LogTypes::RanFromFile], 1);
  252. EXPECT_EQ(m_testSink.m_evaluationMap[(int)LogTypes::NumArgsCorrect], 1);
  253. EXPECT_EQ(m_testSink.m_evaluationMap[(int)LogTypes::ScriptNameCorrect], 1);
  254. EXPECT_EQ(m_testSink.m_evaluationMap[(int)LogTypes::Arg1Correct], 1);
  255. EXPECT_EQ(m_testSink.m_evaluationMap[(int)LogTypes::Arg2Correct], 1);
  256. EXPECT_EQ(m_testSink.m_evaluationMap[(int)LogTypes::Arg3Correct], 1);
  257. }
  258. //
  259. // Tests that makes sure that basic Python libraries can be loaded
  260. //
  261. class EditorPythonBindingsLibraryTest
  262. : public PythonTestingFixture
  263. {
  264. public:
  265. PythonTraceMessageSink m_testSink;
  266. EditorPythonBindingsNotificationBusSink m_notificationSink;
  267. void SetUp() override
  268. {
  269. PythonTestingFixture::SetUp();
  270. auto registry = AZ::SettingsRegistry::Get();
  271. auto projectPathKey = AZ::SettingsRegistryInterface::FixedValueString(AZ::SettingsRegistryMergeUtils::BootstrapSettingsRootKey)
  272. + "/project_path";
  273. AZ::IO::FixedMaxPath enginePath;
  274. registry->Get(enginePath.Native(), AZ::SettingsRegistryMergeUtils::FilePathKey_EngineRootFolder);
  275. registry->Set(projectPathKey, (enginePath / "AutomatedTesting").Native());
  276. AZ::SettingsRegistryMergeUtils::MergeSettingsToRegistry_AddRuntimeFilePaths(*registry);
  277. m_app.RegisterComponentDescriptor(EditorPythonBindings::PythonSystemComponent::CreateDescriptor());
  278. }
  279. void TearDown() override
  280. {
  281. // clearing up memory
  282. m_notificationSink = EditorPythonBindingsNotificationBusSink();
  283. m_testSink.CleanUp();
  284. // shutdown time!
  285. PythonTestingFixture::TearDown();
  286. }
  287. void DoLibraryTest(const char* libName)
  288. {
  289. bool executedLine = false;
  290. m_testSink.m_evaluateMessage = [&executedLine](const char* window, const char* message)
  291. {
  292. if (AzFramework::StringFunc::Equal(window, "python"))
  293. {
  294. if (AzFramework::StringFunc::Equal(message, "python_vm_loaded_lib"))
  295. {
  296. executedLine = true;
  297. }
  298. }
  299. return false;
  300. };
  301. AZ::Entity e;
  302. e.CreateComponent<EditorPythonBindings::PythonSystemComponent>();
  303. e.Init();
  304. e.Activate();
  305. try
  306. {
  307. SimulateEditorBecomingInitialized();
  308. const bool printResult = false;
  309. AZStd::string script(AZStd::string::format("import %s\nprint ('python_vm_loaded_lib')", libName));
  310. AzToolsFramework::EditorPythonRunnerRequestBus::Broadcast(
  311. &AzToolsFramework::EditorPythonRunnerRequestBus::Events::ExecuteByString,
  312. script.c_str(),
  313. printResult);
  314. }
  315. catch ([[maybe_unused]] const std::exception& e)
  316. {
  317. AZ_Error("UnitTest", false, "Failed on with Python exception: %s", e.what());
  318. }
  319. e.Deactivate();
  320. EXPECT_TRUE(executedLine);
  321. }
  322. };
  323. // This test makes sure that some of the expected built-in libraries
  324. // Are present in the version of python we are using (the ones most problematic for building)
  325. TEST_F(EditorPythonBindingsTest, VerifyExpectedLibrariesPresent)
  326. {
  327. enum class LogTypes
  328. {
  329. Skip = 0,
  330. ScriptWorked
  331. };
  332. m_testSink.m_evaluateMessage = [](const char* window, const char* message) -> int
  333. {
  334. if (AzFramework::StringFunc::Equal(window, "python"))
  335. {
  336. if (AzFramework::StringFunc::Equal(message, "EditorPythonBindingsTest_VerifyExpectedLibrariesPresent"))
  337. {
  338. return static_cast<int>(LogTypes::ScriptWorked);
  339. }
  340. }
  341. return static_cast<int>(LogTypes::Skip);
  342. };
  343. AZ::Entity e;
  344. e.CreateComponent<EditorPythonBindings::PythonSystemComponent>();
  345. e.Init();
  346. e.Activate();
  347. SimulateEditorBecomingInitialized();
  348. const char* script =
  349. R"(
  350. import sys
  351. import sqlite3
  352. import ssl
  353. print ('EditorPythonBindingsTest_VerifyExpectedLibrariesPresent')
  354. )";
  355. AzToolsFramework::EditorPythonRunnerRequestBus::Broadcast(&AzToolsFramework::EditorPythonRunnerRequestBus::Events::ExecuteByString, script, true);
  356. e.Deactivate();
  357. EXPECT_EQ(m_testSink.m_evaluationMap[(int)LogTypes::ScriptWorked], 1);
  358. }
  359. TEST_F(EditorPythonBindingsLibraryTest, PythonVMLoads_sys_Works)
  360. {
  361. DoLibraryTest("sys");
  362. }
  363. TEST_F(EditorPythonBindingsLibraryTest, PythonVMLoads_ctypes_Works)
  364. {
  365. DoLibraryTest("ctypes");
  366. }
  367. TEST_F(EditorPythonBindingsLibraryTest, PythonVMLoads_bz2_Works)
  368. {
  369. DoLibraryTest("bz2");
  370. }
  371. TEST_F(EditorPythonBindingsLibraryTest, PythonVMLoads_lzma_Works)
  372. {
  373. DoLibraryTest("lzma");
  374. }
  375. TEST_F(EditorPythonBindingsLibraryTest, PythonVMLoads_socket_Works)
  376. {
  377. DoLibraryTest("socket");
  378. }
  379. TEST_F(EditorPythonBindingsLibraryTest, PythonVMLoads_sqlite3_Works)
  380. {
  381. DoLibraryTest("sqlite3");
  382. }
  383. TEST_F(EditorPythonBindingsLibraryTest, PythonVMLoads_ssl_Works)
  384. {
  385. DoLibraryTest("ssl");
  386. }
  387. // This library lives in Editor/Scripts. We're testing that our sys.path extension code in ExtendSysPath works as expected
  388. TEST_F(EditorPythonBindingsLibraryTest, PythonVMLoads_SysPathExtendedToGemScripts_EditorPythonBindingsValidaitonFound)
  389. {
  390. DoLibraryTest("editor_script_validation");
  391. }
  392. }
  393. AZ_UNIT_TEST_HOOK(DEFAULT_UNIT_TEST_ENV);