PythonReflectionComponentTests.cpp 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485
  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/embed.h>
  10. #include <pybind11/pybind11.h>
  11. #include "PythonTraceMessageSink.h"
  12. #include "PythonTestingUtility.h"
  13. #include <Source/PythonSystemComponent.h>
  14. #include <Source/PythonReflectionComponent.h>
  15. #include <Source/PythonMarshalComponent.h>
  16. #include <AzCore/Asset/AssetCommon.h>
  17. #include <AzCore/Math/Vector4.h>
  18. #include <AzCore/RTTI/BehaviorContext.h>
  19. #include <AzFramework/StringFunc/StringFunc.h>
  20. namespace UnitTest
  21. {
  22. //////////////////////////////////////////////////////////////////////////
  23. // test class/struts
  24. struct PythonReflectionTestDoPrint
  25. {
  26. AZ_TYPE_INFO(PythonReflectionTestDoPrint, "{CA1146E1-A2DF-4AE3-A712-5333CE60D65C}");
  27. static const char* DoTest([[maybe_unused]] const char* label)
  28. {
  29. return "proxy_do_test";
  30. }
  31. static void DoPrint([[maybe_unused]] const char* msg)
  32. {
  33. AZ_TracePrintf("python", msg);
  34. }
  35. void Reflect(AZ::ReflectContext* context)
  36. {
  37. if (AZ::BehaviorContext* behaviorContext = azrtti_cast<AZ::BehaviorContext*>(context))
  38. {
  39. behaviorContext->Class<PythonReflectionTestDoPrint>()
  40. ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Automation)
  41. ->Attribute(AZ::Script::Attributes::Module, "legacy.test")
  42. ->Method("do_test", DoTest, nullptr, "Hook to perform a test with the legacy Python hook handler.")
  43. ->Method("do_print", DoPrint, nullptr, "Hook to perform a test print action to a console.")
  44. ;
  45. }
  46. }
  47. };
  48. struct PythonReflectionTestSimple
  49. {
  50. AZ_TYPE_INFO(PythonReflectionTestSimple, "{03277B3D-DEC2-4113-9FCA-D37D527FCE77}");
  51. static void DoWork()
  52. {
  53. AZ_TracePrintf("python", "PythonReflectionTestSimple_DoWork");
  54. }
  55. void Reflect(AZ::ReflectContext* context)
  56. {
  57. if (AZ::BehaviorContext* behaviorContext = azrtti_cast<AZ::BehaviorContext*>(context))
  58. {
  59. behaviorContext->Class<PythonReflectionTestSimple>()
  60. ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Automation)
  61. //AZ::Script::Attributes::Module, "default" //< this is optional; if not there then the BC is placed in the "azlmbr.default" module
  62. ->Method("do_work", DoWork, nullptr, "Test do work.")
  63. ;
  64. }
  65. }
  66. };
  67. struct PythonReflectionContainerSimpleTypes
  68. {
  69. AZ_TYPE_INFO(PythonReflectionContainerSimpleTypes, "{378AD363-467D-4285-BE40-4D1CB1A09A19}");
  70. AZStd::vector<float> m_floatValues{ 1.0, 2.2, 3.3, 4.4 };
  71. AZStd::vector<float>& ReturnVectorOfFloats()
  72. {
  73. return m_floatValues;
  74. }
  75. void AcceptVectorOfFloats(const AZStd::vector<float>& values)
  76. {
  77. m_floatValues.assign(values.begin(), values.end());
  78. }
  79. AZStd::vector<double> m_doubleValues{ 1.0, 2.2, 3.3, 4.4 };
  80. AZStd::vector<double>& ReturnVectorOfDoubles()
  81. {
  82. return m_doubleValues;
  83. }
  84. void AcceptVectorOfDoubles(const AZStd::vector<double>& values)
  85. {
  86. m_doubleValues.assign(values.begin(), values.end());
  87. }
  88. template <typename T>
  89. struct VectorOf
  90. {
  91. AZStd::vector<T> m_values;
  92. explicit VectorOf(std::initializer_list<T> list)
  93. {
  94. m_values = list;
  95. }
  96. const AZStd::vector<T>& ReturnValues() const
  97. {
  98. return m_values;
  99. }
  100. void AcceptValues(const AZStd::vector<T>& values)
  101. {
  102. m_values.assign(values.begin(), values.end());
  103. }
  104. };
  105. VectorOf<AZ::s8> m_s8ValueValues { 4, 5, 6, 7 };
  106. VectorOf<AZ::u8> m_u8ValueValues { 4, 5, 6, 7 };
  107. VectorOf<AZ::s16> m_s16ValueValues { 4, 5, 6, 7 };
  108. VectorOf<AZ::u16> m_u16ValueValues { 4, 5, 6, 7 };
  109. VectorOf<AZ::s32> m_s32ValueValues { 4, 5, 6, 7 };
  110. VectorOf<AZ::u32> m_u32ValueValues { 4, 5, 6, 7 };
  111. VectorOf<AZ::s64> m_s64ValueValues { 4, 5, 6, 7 };
  112. VectorOf<AZ::u64> m_u64ValueValues { 4, 5, 6, 7 };
  113. VectorOf<bool> m_boolValueValues { true, false, false };
  114. void Reflect(AZ::ReflectContext* context)
  115. {
  116. if (AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context))
  117. {
  118. serializeContext->RegisterGenericType<AZStd::vector<bool>>();
  119. serializeContext->RegisterGenericType<AZStd::vector<float>>();
  120. serializeContext->RegisterGenericType<AZStd::vector<double>>();
  121. serializeContext->RegisterGenericType<AZStd::vector<AZ::s8>>();
  122. serializeContext->RegisterGenericType<AZStd::vector<AZ::u8>>();
  123. serializeContext->RegisterGenericType<AZStd::vector<AZ::s16>>();
  124. serializeContext->RegisterGenericType<AZStd::vector<AZ::u16>>();
  125. serializeContext->RegisterGenericType<AZStd::vector<AZ::s32>>();
  126. serializeContext->RegisterGenericType<AZStd::vector<AZ::u32>>();
  127. serializeContext->RegisterGenericType<AZStd::vector<AZ::s64>>();
  128. serializeContext->RegisterGenericType<AZStd::vector<AZ::u64>>();
  129. }
  130. if (AZ::BehaviorContext* behaviorContext = azrtti_cast<AZ::BehaviorContext*>(context))
  131. {
  132. behaviorContext->Class<PythonReflectionContainerSimpleTypes>("PythonReflectionContainerSimpleTypes")
  133. ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Automation)
  134. ->Attribute(AZ::Script::Attributes::Module, "test.containers")
  135. ->Method("return_vector_of_floats", &PythonReflectionContainerSimpleTypes::ReturnVectorOfFloats, nullptr, "")
  136. ->Method("accept_vector_of_floats", &PythonReflectionContainerSimpleTypes::AcceptVectorOfFloats, nullptr, "")
  137. ->Method("return_vector_of_doubles", &PythonReflectionContainerSimpleTypes::ReturnVectorOfDoubles, nullptr, "")
  138. ->Method("accept_vector_of_doubles", &PythonReflectionContainerSimpleTypes::AcceptVectorOfDoubles, nullptr, "")
  139. ->Property("vector_of_s8",
  140. [](PythonReflectionContainerSimpleTypes* self) { return self->m_s8ValueValues.ReturnValues(); },
  141. [](PythonReflectionContainerSimpleTypes* self, const AZStd::vector<AZ::s8>& values) { return self->m_s8ValueValues.AcceptValues(values); })
  142. ->Property("vector_of_u8",
  143. [](PythonReflectionContainerSimpleTypes* self) { return self->m_u8ValueValues.ReturnValues(); },
  144. [](PythonReflectionContainerSimpleTypes* self, const AZStd::vector<AZ::u8>& values) { return self->m_u8ValueValues.AcceptValues(values); })
  145. ->Property("vector_of_s16",
  146. [](PythonReflectionContainerSimpleTypes* self) { return self->m_s16ValueValues.ReturnValues(); },
  147. [](PythonReflectionContainerSimpleTypes* self, const AZStd::vector<AZ::s16>& values) { return self->m_s16ValueValues.AcceptValues(values); })
  148. ->Property("vector_of_u16",
  149. [](PythonReflectionContainerSimpleTypes* self) { return self->m_u16ValueValues.ReturnValues(); },
  150. [](PythonReflectionContainerSimpleTypes* self, const AZStd::vector<AZ::u16>& values) { return self->m_u16ValueValues.AcceptValues(values); })
  151. ->Property("vector_of_s32",
  152. [](PythonReflectionContainerSimpleTypes* self) { return self->m_s32ValueValues.ReturnValues(); },
  153. [](PythonReflectionContainerSimpleTypes* self, const AZStd::vector<AZ::s32>& values) { return self->m_s32ValueValues.AcceptValues(values); })
  154. ->Property("vector_of_u32",
  155. [](PythonReflectionContainerSimpleTypes* self) { return self->m_u32ValueValues.ReturnValues(); },
  156. [](PythonReflectionContainerSimpleTypes* self, const AZStd::vector<AZ::u32>& values) { return self->m_u32ValueValues.AcceptValues(values); })
  157. ->Property("vector_of_s64",
  158. [](PythonReflectionContainerSimpleTypes* self) { return self->m_s64ValueValues.ReturnValues(); },
  159. [](PythonReflectionContainerSimpleTypes* self, const AZStd::vector<AZ::s64>& values) { return self->m_s64ValueValues.AcceptValues(values); })
  160. ->Property("vector_of_u64",
  161. [](PythonReflectionContainerSimpleTypes* self) { return self->m_u64ValueValues.ReturnValues(); },
  162. [](PythonReflectionContainerSimpleTypes* self, const AZStd::vector<AZ::u64>& values) { return self->m_u64ValueValues.AcceptValues(values); })
  163. ->Property("vector_of_bool",
  164. [](PythonReflectionContainerSimpleTypes* self) { return self->m_boolValueValues.ReturnValues(); },
  165. [](PythonReflectionContainerSimpleTypes* self, const AZStd::vector<bool>& values) { return self->m_boolValueValues.AcceptValues(values); })
  166. ;
  167. }
  168. }
  169. };
  170. struct PythonReflectionStringTypes
  171. {
  172. AZ_TYPE_INFO(PythonReflectionStringTypes, "{A6BF24DB-50E2-435B-A896-0192D24974B1}");
  173. static void RawPointerIn([[maybe_unused]] const char* value)
  174. {
  175. AZ_TracePrintf("python", value);
  176. }
  177. static const char* RawPointerOut()
  178. {
  179. return "PythonReflectStringTypes_RawStringOut";
  180. }
  181. static void StringViewIn([[maybe_unused]] AZStd::string_view value)
  182. {
  183. AZ_TracePrintf("python", "%.*s", static_cast<int>(value.size()), value.data());
  184. }
  185. static AZStd::string_view StringViewOut()
  186. {
  187. return { "PythonReflectStringTypes_StringViewOut" };
  188. }
  189. static void AZStdStringIn([[maybe_unused]] const AZStd::string& value)
  190. {
  191. AZ_TracePrintf("python", "%s", value.c_str());
  192. }
  193. static AZStd::string AZStdStringOut()
  194. {
  195. return { "PythonReflectStringTypes_AZStdStringOut" };
  196. }
  197. static AZStd::vector<AZStd::string> OutputStringList()
  198. {
  199. AZStd::vector<AZStd::string> listOfStrings;
  200. listOfStrings.push_back("one");
  201. listOfStrings.push_back("two");
  202. listOfStrings.push_back("three");
  203. return listOfStrings;
  204. }
  205. static bool InputStringList(AZStd::vector<AZStd::string> input)
  206. {
  207. if (input.size() == 3 && input[0] == "1" && input[1] == "2" && input[2] == "3")
  208. {
  209. return true;
  210. }
  211. return false;
  212. }
  213. static AZStd::vector<AZStd::string_view> OutputStringViewList()
  214. {
  215. AZStd::vector<AZStd::string_view> listOfStrings;
  216. listOfStrings.push_back("one");
  217. listOfStrings.push_back("two");
  218. listOfStrings.push_back("three");
  219. return listOfStrings;
  220. }
  221. static bool InputStringViewList(AZStd::vector<AZStd::string_view> input)
  222. {
  223. if (input.size() == 3 && input[0] == "a" && input[1] == "b" && input[2] == "c")
  224. {
  225. return true;
  226. }
  227. return false;
  228. }
  229. static AZStd::string OutputEmptyString()
  230. {
  231. return AZStd::string("");
  232. }
  233. static bool InputEmptyString(AZStd::string emptyString)
  234. {
  235. return emptyString.empty();
  236. }
  237. void Reflect(AZ::ReflectContext* context)
  238. {
  239. if (AZ::BehaviorContext* behaviorContext = azrtti_cast<AZ::BehaviorContext*>(context))
  240. {
  241. behaviorContext->Class<PythonReflectionStringTypes>("Strings")
  242. ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Automation)
  243. ->Attribute(AZ::Script::Attributes::Module, "test.strings")
  244. ->Method("raw_pointer_in", RawPointerIn, nullptr, "")
  245. ->Method("raw_pointer_out", RawPointerOut, nullptr, "")
  246. ->Method("string_view_in", StringViewIn, nullptr, "")
  247. ->Method("string_view_out", StringViewOut, nullptr, "")
  248. ->Method("azstd_string_in", AZStdStringIn, nullptr, "")
  249. ->Method("azstd_string_out", AZStdStringOut, nullptr, "")
  250. ->Method("output_string_list", OutputStringList, nullptr, "")
  251. ->Method("input_string_list", InputStringList, nullptr, "")
  252. ->Method("output_empty_string", OutputEmptyString, nullptr, "")
  253. ->Method("input_empty_string", InputEmptyString, nullptr, "")
  254. ->Method("output_string_view_list", OutputStringViewList, nullptr, "")
  255. ->Method("input_string_view_list", InputStringViewList, nullptr, "")
  256. ;
  257. }
  258. }
  259. };
  260. struct FakeEntityIdType final
  261. {
  262. AZ_TYPE_INFO(FakeEntityIdType, "{33FF7076-50AD-42E7-9DFF-19FA5026264A}");
  263. public:
  264. static const AZ::u64 InvalidEntityId = 0x00000000FFFFFFFFull;
  265. explicit FakeEntityIdType(AZ::u64 id = InvalidEntityId)
  266. : m_id(id)
  267. {}
  268. explicit operator AZ::u64() const
  269. {
  270. return m_id;
  271. }
  272. bool IsValid() const
  273. {
  274. return m_id != InvalidEntityId;
  275. }
  276. void SetInvalid()
  277. {
  278. m_id = InvalidEntityId;
  279. }
  280. AZStd::string ToString() const
  281. {
  282. return AZStd::string::format("[%llu]", m_id);
  283. }
  284. AZ::u64 m_id;
  285. static void Reflect(AZ::ReflectContext* context)
  286. {
  287. if (AZ::BehaviorContext* behaviorContext = azrtti_cast<AZ::BehaviorContext*>(context))
  288. {
  289. behaviorContext->Class<FakeEntityIdType>("FakeEntityId")
  290. ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Common)
  291. ->Attribute(AZ::Script::Attributes::Module, "entity")
  292. ->Method("IsValid", &FakeEntityIdType::IsValid)
  293. ->Method("ToString", &FakeEntityIdType::ToString)
  294. ;
  295. }
  296. }
  297. };
  298. struct PythonReflectionComplexContainer
  299. {
  300. AZ_TYPE_INFO(PythonReflectionComplexContainer, "{A1935F7F-6A22-4CA3-BEE7-A2F8E8D5D35F}");
  301. AZStd::vector<FakeEntityIdType> SendListOfIds() const
  302. {
  303. AZStd::vector<FakeEntityIdType> fakeIds;
  304. fakeIds.push_back(FakeEntityIdType{ 101 });
  305. fakeIds.push_back(FakeEntityIdType{ 202 });
  306. fakeIds.push_back(FakeEntityIdType{ 303 });
  307. return fakeIds;
  308. }
  309. void Reflect(AZ::ReflectContext* context)
  310. {
  311. FakeEntityIdType::Reflect(context);
  312. if (AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context))
  313. {
  314. serializeContext->RegisterGenericType<AZStd::vector<FakeEntityIdType>>();
  315. }
  316. if (AZ::BehaviorContext* behaviorContext = azrtti_cast<AZ::BehaviorContext*>(context))
  317. {
  318. behaviorContext->Class<PythonReflectionComplexContainer>("ComplexContainer")
  319. ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Automation)
  320. ->Attribute(AZ::Script::Attributes::Module, "test")
  321. ->Method("send_list_of_ids", &PythonReflectionComplexContainer::SendListOfIds)
  322. ;
  323. }
  324. }
  325. };
  326. struct PythonReflectionAny
  327. {
  328. AZ_TYPE_INFO(PythonReflectionAny, "{1B6617E1-C259-48A4-A337-232782024B5D}");
  329. AZ::s32 m_intValue = 0;
  330. AZStd::any m_anyValue;
  331. AZ::Data::AssetId m_assetId;
  332. PythonReflectionAny()
  333. {
  334. m_assetId.m_guid = AZ::Uuid::CreateRandom();
  335. }
  336. void ReportMutate(const AZStd::any& value) const
  337. {
  338. if (value.is<PythonReflectionAny>())
  339. {
  340. AZ_TracePrintf("python", "MutateAny");
  341. }
  342. else if (value.is<AZ::Data::AssetId>())
  343. {
  344. AZ_TracePrintf("python", "MutateAssetId");
  345. }
  346. }
  347. void ReportAccess() const
  348. {
  349. if (m_anyValue.is<PythonReflectionAny>())
  350. {
  351. AZ_TracePrintf("python", "AccessAny");
  352. }
  353. else if (m_anyValue.is<AZ::Data::AssetId>())
  354. {
  355. AZ_TracePrintf("python", "AccessAssetId");
  356. }
  357. }
  358. void MutateAnyRef(const AZStd::any& value)
  359. {
  360. ReportMutate(value);
  361. m_anyValue = value;
  362. }
  363. const AZStd::any& AccessAnyRef() const
  364. {
  365. ReportAccess();
  366. return m_anyValue;
  367. }
  368. void MutateAnyValue(AZStd::any value)
  369. {
  370. ReportMutate(value);
  371. m_anyValue = value;
  372. }
  373. AZStd::any AccessAnyValue() const
  374. {
  375. ReportAccess();
  376. return m_anyValue;
  377. }
  378. void MutateAnyPointer(const AZStd::any* value)
  379. {
  380. ReportMutate(*value);
  381. m_anyValue = *value;
  382. }
  383. bool CompareAssetIds(const AZ::Data::AssetId& lhs, const AZ::Data::AssetId& rhs) const
  384. {
  385. return lhs == rhs;
  386. }
  387. AZStd::any m_anySimple;
  388. void MutateAnySimple(const AZStd::any& value)
  389. {
  390. if (value.is<double>())
  391. {
  392. AZ_TracePrintf("python", "MutateAnySimple_double");
  393. }
  394. else if (value.is<AZ::s64>())
  395. {
  396. AZ_TracePrintf("python", "MutateAnySimple_s64");
  397. }
  398. else if (value.is<bool>())
  399. {
  400. AZ_TracePrintf("python", "MutateAnySimple_bool");
  401. }
  402. else if (value.is<AZStd::string_view>())
  403. {
  404. AZ_TracePrintf("python", "MutateAnySimple_string_view");
  405. }
  406. m_anySimple = value;
  407. }
  408. const AZStd::any& AccessAnySimple() const
  409. {
  410. if (m_anySimple.is<double>())
  411. {
  412. AZ_TracePrintf("python", "AccessAnySimple_double");
  413. }
  414. else if (m_anySimple.is<AZ::s64>())
  415. {
  416. AZ_TracePrintf("python", "AccessAnySimple_s64");
  417. }
  418. else if (m_anySimple.is<bool>())
  419. {
  420. AZ_TracePrintf("python", "AccessAnySimple_bool");
  421. }
  422. else if (m_anySimple.is<AZStd::string_view>())
  423. {
  424. AZ_TracePrintf("python", "AccessAnySimple_string_view");
  425. }
  426. return m_anySimple;
  427. }
  428. void Reflect(AZ::ReflectContext* context)
  429. {
  430. if (AZ::BehaviorContext* behaviorContext = azrtti_cast<AZ::BehaviorContext*>(context))
  431. {
  432. behaviorContext->Class<PythonReflectionAny>()
  433. ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Automation)
  434. ->Attribute(AZ::Script::Attributes::Module, "test")
  435. ->Method("mutate_any_ref", &PythonReflectionAny::MutateAnyRef, nullptr, "Mutate any value ref.")
  436. ->Method("access_any_ref", &PythonReflectionAny::AccessAnyRef, nullptr, "Access any value ref.")
  437. ->Method("mutate_any_pointer", &PythonReflectionAny::MutateAnyPointer, nullptr, "Mutate any value ptr.")
  438. ->Method("mutate_any_value", &PythonReflectionAny::MutateAnyValue, nullptr, "Mutate any value by value.")
  439. ->Method("access_any_value", &PythonReflectionAny::AccessAnyValue, nullptr, "Access any value by value.")
  440. ->Property("theInt", BehaviorValueProperty(&PythonReflectionAny::m_intValue))
  441. ->Property("theAsset", BehaviorValueProperty(&PythonReflectionAny::m_assetId))
  442. ->Method("compare_asset_ids", &PythonReflectionAny::CompareAssetIds)
  443. ->Method("mutate_any_simple", &PythonReflectionAny::MutateAnySimple)
  444. ->Method("access_any_simple", &PythonReflectionAny::AccessAnySimple)
  445. ;
  446. }
  447. }
  448. };
  449. //////////////////////////////////////////////////////////////////////////
  450. // fixtures
  451. struct PythonReflectionComponentTests
  452. : public PythonTestingFixture
  453. {
  454. PythonTraceMessageSink m_testSink;
  455. void SetUp() override
  456. {
  457. PythonTestingFixture::SetUp();
  458. PythonTestingFixture::RegisterComponentDescriptors();
  459. }
  460. void TearDown() override
  461. {
  462. // clearing up memory
  463. m_testSink.CleanUp();
  464. PythonTestingFixture::TearDown();
  465. }
  466. };
  467. TEST_F(PythonReflectionComponentTests, InstallingPythonReflectionComponent)
  468. {
  469. AZ::Entity e;
  470. e.CreateComponent<EditorPythonBindings::PythonSystemComponent>();
  471. e.CreateComponent<EditorPythonBindings::PythonReflectionComponent>();
  472. e.CreateComponent<EditorPythonBindings::PythonMarshalComponent>();
  473. e.Init();
  474. EXPECT_EQ(AZ::Entity::State::Init, e.GetState());
  475. e.Activate();
  476. EXPECT_EQ(AZ::Entity::State::Active, e.GetState());
  477. SimulateEditorBecomingInitialized();
  478. e.Deactivate();
  479. }
  480. TEST_F(PythonReflectionComponentTests, MakeSureTheAzlmbrModuleExists)
  481. {
  482. AZ::Entity e;
  483. Activate(e);
  484. SimulateEditorBecomingInitialized();
  485. {
  486. auto m = pybind11::module::import("azlmbr");
  487. EXPECT_TRUE(m);
  488. }
  489. e.Deactivate();
  490. }
  491. TEST_F(PythonReflectionComponentTests, GetProxyCommand)
  492. {
  493. enum class LogTypes
  494. {
  495. Skip = 0,
  496. GotProxyFromPython
  497. };
  498. m_testSink.m_evaluateMessage = [](const char* window, const char* message) -> int
  499. {
  500. if (AzFramework::StringFunc::Equal(window, "python"))
  501. {
  502. if (AzFramework::StringFunc::Equal(message, "proxy_do_test"))
  503. {
  504. return static_cast<int>(LogTypes::GotProxyFromPython);
  505. }
  506. }
  507. return static_cast<int>(LogTypes::Skip);
  508. };
  509. PythonReflectionTestDoPrint handler;
  510. handler.Reflect(m_app.GetBehaviorContext());
  511. AZ::Entity e;
  512. Activate(e);
  513. SimulateEditorBecomingInitialized();
  514. try
  515. {
  516. pybind11::exec(R"(
  517. import azlmbr.legacy.test as test
  518. v = test.PythonReflectionTestDoPrint_do_test('does_not_exist')
  519. test.PythonReflectionTestDoPrint_do_print(str(v))
  520. )");
  521. }
  522. catch ([[maybe_unused]] const std::exception& e)
  523. {
  524. AZ_Warning("UnitTest", false, "Failed on GetProxyCommand with %s", e.what());
  525. FAIL();
  526. }
  527. e.Deactivate();
  528. EXPECT_EQ(1, m_testSink.m_evaluationMap[static_cast<int>(LogTypes::GotProxyFromPython)]);
  529. }
  530. // a non-named 'editor' flagged BehaviorClass methods end up in the 'azlmbr.default' namespace
  531. TEST_F(PythonReflectionComponentTests, DefaultModule)
  532. {
  533. enum class LogTypes
  534. {
  535. Skip = 0,
  536. PythonReflectionTestSimple_DoWork
  537. };
  538. m_testSink.m_evaluateMessage = [](const char* window, const char* message) -> int
  539. {
  540. if (AzFramework::StringFunc::Equal(window, "python"))
  541. {
  542. if (AzFramework::StringFunc::Equal(message, "PythonReflectionTestSimple_DoWork"))
  543. {
  544. return static_cast<int>(LogTypes::PythonReflectionTestSimple_DoWork);
  545. }
  546. }
  547. return static_cast<int>(LogTypes::Skip);
  548. };
  549. PythonReflectionTestSimple handler;
  550. handler.Reflect(m_app.GetBehaviorContext());
  551. AZ::Entity e;
  552. Activate(e);
  553. SimulateEditorBecomingInitialized();
  554. try
  555. {
  556. pybind11::exec(R"(
  557. import azlmbr.default
  558. azlmbr.default.PythonReflectionTestSimple_do_work()
  559. )");
  560. }
  561. catch ([[maybe_unused]] const std::exception& e)
  562. {
  563. AZ_Warning("UnitTest", false, "Failed on DefaultModule with %s", e.what());
  564. FAIL();
  565. }
  566. e.Deactivate();
  567. EXPECT_EQ(1, m_testSink.m_evaluationMap[static_cast<int>(LogTypes::PythonReflectionTestSimple_DoWork)]);
  568. }
  569. // at least 3 deep in a sub module thing like test.that.space
  570. TEST_F(PythonReflectionComponentTests, AtLeast3DeepModules)
  571. {
  572. enum class LogTypes
  573. {
  574. Skip = 0,
  575. PythonReflectionTestSimple_DoWork,
  576. PythonReflection_DoPrint,
  577. };
  578. m_testSink.m_evaluateMessage = [](const char* window, const char* message) -> int
  579. {
  580. if (AzFramework::StringFunc::Equal(window, "python"))
  581. {
  582. if (AzFramework::StringFunc::Equal(message, "PythonReflectionTestSimple_DoWork"))
  583. {
  584. return static_cast<int>(LogTypes::PythonReflectionTestSimple_DoWork);
  585. }
  586. else if (AzFramework::StringFunc::Equal(message, "PythonReflection_DoPrint"))
  587. {
  588. return static_cast<int>(LogTypes::PythonReflection_DoPrint);
  589. }
  590. }
  591. return static_cast<int>(LogTypes::Skip);
  592. };
  593. PythonReflectionTestSimple pythonReflectionTestSimple;
  594. pythonReflectionTestSimple.Reflect(m_app.GetBehaviorContext());
  595. PythonReflectionTestDoPrint pythonReflectionTestDoPrint;
  596. pythonReflectionTestDoPrint.Reflect(m_app.GetBehaviorContext());
  597. AZ::Entity e;
  598. Activate(e);
  599. SimulateEditorBecomingInitialized();
  600. try
  601. {
  602. pybind11::exec(R"(
  603. import azlmbr.default
  604. import azlmbr.legacy.test
  605. azlmbr.default.PythonReflectionTestSimple_do_work()
  606. azlmbr.legacy.test.PythonReflectionTestDoPrint_do_print('PythonReflection_DoPrint')
  607. )");
  608. }
  609. catch ([[maybe_unused]] const std::exception& e)
  610. {
  611. AZ_Warning("UnitTest", false, "Failed on DefaultModule with %s", e.what());
  612. FAIL();
  613. }
  614. e.Deactivate();
  615. EXPECT_EQ(1, m_testSink.m_evaluationMap[static_cast<int>(LogTypes::PythonReflectionTestSimple_DoWork)]);
  616. EXPECT_EQ(1, m_testSink.m_evaluationMap[static_cast<int>(LogTypes::PythonReflection_DoPrint)]);
  617. }
  618. // Access Mutate Any types
  619. TEST_F(PythonReflectionComponentTests, AccessMutateAny)
  620. {
  621. enum class LogTypes
  622. {
  623. Skip = 0,
  624. MutateAny,
  625. AccessAny,
  626. MutateAssetId,
  627. AccessAssetId
  628. };
  629. m_testSink.m_evaluateMessage = [](const char* window, const char* message) -> int
  630. {
  631. if (AzFramework::StringFunc::Equal(window, "python"))
  632. {
  633. if (AzFramework::StringFunc::StartsWith(message, "MutateAny"))
  634. {
  635. return aznumeric_cast<int>(LogTypes::MutateAny);
  636. }
  637. else if (AzFramework::StringFunc::StartsWith(message, "AccessAny"))
  638. {
  639. return aznumeric_cast<int>(LogTypes::AccessAny);
  640. }
  641. else if (AzFramework::StringFunc::StartsWith(message, "MutateAssetId"))
  642. {
  643. return aznumeric_cast<int>(LogTypes::MutateAssetId);
  644. }
  645. else if (AzFramework::StringFunc::StartsWith(message, "AccessAssetId"))
  646. {
  647. return aznumeric_cast<int>(LogTypes::AccessAssetId);
  648. }
  649. }
  650. return aznumeric_cast<int>(LogTypes::Skip);
  651. };
  652. PythonReflectionAny pythonReflectionAny;
  653. pythonReflectionAny.Reflect(m_app.GetBehaviorContext());
  654. AZ::Entity e;
  655. Activate(e);
  656. SimulateEditorBecomingInitialized();
  657. try
  658. {
  659. pybind11::exec(R"(
  660. import azlmbr.test as test
  661. testObject = test.PythonReflectionAny()
  662. # by reference
  663. testObject.theInt = 10
  664. reflectAny = test.PythonReflectionAny()
  665. reflectAny.mutate_any_ref(testObject)
  666. value = reflectAny.access_any_ref()
  667. if( value.theInt == 10 ):
  668. print ('AccessAny')
  669. # by value
  670. testObject.theInt = testObject.theInt + 1
  671. reflectAny = test.PythonReflectionAny()
  672. reflectAny.mutate_any_value(testObject)
  673. value = reflectAny.access_any_value()
  674. if( value.theInt == 11 ):
  675. print ('AccessAny')
  676. # access and mutate using an AssetId
  677. theAsset = testObject.theAsset
  678. reflectAny = test.PythonReflectionAny()
  679. reflectAny.mutate_any_ref(theAsset)
  680. theAsset = reflectAny.access_any_ref()
  681. if( reflectAny.compare_asset_ids(theAsset,testObject.theAsset) ):
  682. print ('MutateAssetId')
  683. )");
  684. }
  685. catch ([[maybe_unused]] const std::exception& e)
  686. {
  687. AZ_Warning("UnitTest", false, "Failed with %s", e.what());
  688. FAIL();
  689. }
  690. e.Deactivate();
  691. EXPECT_EQ(2, m_testSink.m_evaluationMap[aznumeric_cast<int>(LogTypes::MutateAny)]);
  692. EXPECT_EQ(4, m_testSink.m_evaluationMap[aznumeric_cast<int>(LogTypes::AccessAny)]);
  693. EXPECT_EQ(2, m_testSink.m_evaluationMap[aznumeric_cast<int>(LogTypes::MutateAssetId)]);
  694. EXPECT_EQ(1, m_testSink.m_evaluationMap[aznumeric_cast<int>(LogTypes::AccessAssetId)]);
  695. }
  696. TEST_F(PythonReflectionComponentTests, AccessMutateAnySimpleTypes)
  697. {
  698. enum class LogTypes
  699. {
  700. Skip = 0,
  701. MutateAnySimple,
  702. AccessAnySimple,
  703. };
  704. m_testSink.m_evaluateMessage = [](const char* window, const char* message) -> int
  705. {
  706. if (AzFramework::StringFunc::Equal(window, "python"))
  707. {
  708. if (AzFramework::StringFunc::StartsWith(message, "MutateAnySimple"))
  709. {
  710. return aznumeric_cast<int>(LogTypes::MutateAnySimple);
  711. }
  712. else if (AzFramework::StringFunc::StartsWith(message, "AccessAnySimple"))
  713. {
  714. return aznumeric_cast<int>(LogTypes::AccessAnySimple);
  715. }
  716. }
  717. return aznumeric_cast<int>(LogTypes::Skip);
  718. };
  719. PythonReflectionAny pythonReflectionAny;
  720. pythonReflectionAny.Reflect(m_app.GetBehaviorContext());
  721. AZ::Entity e;
  722. Activate(e);
  723. SimulateEditorBecomingInitialized();
  724. try
  725. {
  726. pybind11::exec(R"(
  727. import azlmbr.test as test
  728. import math
  729. # access mutate float
  730. reflectAny = test.PythonReflectionAny()
  731. reflectAny.mutate_any_simple(float(10.0))
  732. if( math.floor(reflectAny.access_any_simple()) == 10.0 ):
  733. print ('AccessAnySimple_double')
  734. # access mutate int
  735. reflectAny = test.PythonReflectionAny()
  736. reflectAny.mutate_any_simple(int(11))
  737. if( reflectAny.access_any_simple() == 11 ):
  738. print ('AccessAnySimple_s64')
  739. # access mutate bool
  740. reflectAny = test.PythonReflectionAny()
  741. reflectAny.mutate_any_simple(False)
  742. if( reflectAny.access_any_simple() is not True ):
  743. print ('AccessAnySimple_bool')
  744. # access mutate string
  745. reflectAny = test.PythonReflectionAny()
  746. reflectAny.mutate_any_simple('a string value')
  747. if( reflectAny.access_any_simple() == 'a string value' ):
  748. print ('AccessAnySimple_string_view')
  749. )");
  750. }
  751. catch ([[maybe_unused]] const std::exception& e)
  752. {
  753. AZ_Warning("UnitTest", false, "Failed with %s", e.what());
  754. FAIL();
  755. }
  756. e.Deactivate();
  757. EXPECT_EQ(4, m_testSink.m_evaluationMap[aznumeric_cast<int>(LogTypes::MutateAnySimple)]);
  758. EXPECT_EQ(8, m_testSink.m_evaluationMap[aznumeric_cast<int>(LogTypes::AccessAnySimple)]);
  759. }
  760. // test for the Python container types like List, Dictionary, Set, and Tuple
  761. TEST_F(PythonReflectionComponentTests, ContainerTypes)
  762. {
  763. enum class LogTypes
  764. {
  765. Skip = 0,
  766. ContainerTypes_Input,
  767. ContainerTypes_Output,
  768. };
  769. m_testSink.m_evaluateMessage = [](const char* window, const char* message) -> int
  770. {
  771. if (AzFramework::StringFunc::Equal(window, "python"))
  772. {
  773. if (AzFramework::StringFunc::StartsWith(message, "ContainerTypes_Input"))
  774. {
  775. return static_cast<int>(LogTypes::ContainerTypes_Input);
  776. }
  777. else if (AzFramework::StringFunc::StartsWith(message, "ContainerTypes_Output"))
  778. {
  779. return static_cast<int>(LogTypes::ContainerTypes_Output);
  780. }
  781. }
  782. return static_cast<int>(LogTypes::Skip);
  783. };
  784. PythonReflectionContainerSimpleTypes PythonReflectionContainerSimpleTypes;
  785. PythonReflectionContainerSimpleTypes.Reflect(m_app.GetSerializeContext());
  786. PythonReflectionContainerSimpleTypes.Reflect(m_app.GetBehaviorContext());
  787. AZ::Entity e;
  788. Activate(e);
  789. SimulateEditorBecomingInitialized();
  790. try
  791. {
  792. pybind11::exec(R"(
  793. import azlmbr.test.containers
  794. import azlmbr.object
  795. def real_number_list_equals(list1, list2):
  796. for a, b in zip(list1, list2):
  797. if abs(a-b) > 0.0001:
  798. return False
  799. return True
  800. def test_vector_of_reals(test, label, get, put, values):
  801. list = test.invoke(get)
  802. if (real_number_list_equals(values, list)):
  803. print ('ContainerTypes_Output{}'.format(label))
  804. list.reverse()
  805. test.invoke(put, list)
  806. list = test.invoke(get)
  807. values.reverse()
  808. if (real_number_list_equals(values, list)):
  809. print ('ContainerTypes_Input{}'.format(label))
  810. def test_vector_of(test, label, values):
  811. list = test.get_property('vector_of_{}'.format(label))
  812. if (list == values):
  813. print ('ContainerTypes_Output{}'.format(label))
  814. list.reverse()
  815. test.set_property('vector_of_{}'.format(label), list)
  816. list = test.get_property('vector_of_{}'.format(label))
  817. values.reverse()
  818. if (list == values):
  819. print ('ContainerTypes_Input{}'.format(label))
  820. test = azlmbr.object.create('PythonReflectionContainerSimpleTypes')
  821. test_vector_of_reals(test, 'doubles', 'return_vector_of_doubles', 'accept_vector_of_doubles', [ 1.0, 2.2, 3.3, 4.4 ])
  822. test_vector_of_reals(test, 'floats', 'return_vector_of_floats', 'accept_vector_of_floats', [ 1.0, 2.2, 3.3, 4.4 ])
  823. test_vector_of(test, 'bool', [True,False,False])
  824. test_vector_of(test, 's8', [4,5,6,7])
  825. test_vector_of(test, 'u8', [4,5,6,7])
  826. test_vector_of(test, 's16', [4,5,6,7])
  827. test_vector_of(test, 'u16', [4,5,6,7])
  828. test_vector_of(test, 's32', [4,5,6,7])
  829. test_vector_of(test, 'u32', [4,5,6,7])
  830. test_vector_of(test, 's64', [4,5,6,7])
  831. test_vector_of(test, 'u64', [4,5,6,7])
  832. )");
  833. }
  834. catch ([[maybe_unused]] const std::exception& e)
  835. {
  836. AZ_Warning("UnitTest", false, "Failed with Python exception of %s", e.what());
  837. FAIL();
  838. }
  839. e.Deactivate();
  840. EXPECT_EQ(11, m_testSink.m_evaluationMap[static_cast<int>(LogTypes::ContainerTypes_Input)]);
  841. EXPECT_EQ(11, m_testSink.m_evaluationMap[static_cast<int>(LogTypes::ContainerTypes_Output)]);
  842. }
  843. // all accepted types tested with this test class
  844. struct PythonReflectionTypesTester
  845. {
  846. AZ_TYPE_INFO(PythonReflectionTypesTester, "{CA1146E2-A2DF-4AE3-A712-5333CE60D65C}");
  847. static AZ::u32 s_returned;
  848. static AZ::u32 s_accepted;
  849. static AZ::u32 s_successCount;
  850. static AZStd::any s_theValue;
  851. template <typename T>
  852. static T ReturnValue()
  853. {
  854. ++s_returned;
  855. return AZStd::any_cast<T>(s_theValue);
  856. }
  857. template <typename T>
  858. static void AcceptValue(T value)
  859. {
  860. s_theValue = value;
  861. ++s_accepted;
  862. }
  863. static void SignalSuccess()
  864. {
  865. ++s_successCount;
  866. }
  867. void Reflect(AZ::ReflectContext* context)
  868. {
  869. PythonReflectionTypesTester::s_accepted = 0;
  870. PythonReflectionTypesTester::s_returned = 0;
  871. PythonReflectionTypesTester::s_successCount = 0;
  872. PythonReflectionTypesTester::s_theValue = AZStd::any();
  873. if (AZ::BehaviorContext* behaviorContext = azrtti_cast<AZ::BehaviorContext*>(context))
  874. {
  875. behaviorContext->Class<PythonReflectionTypesTester>("TypeTests")
  876. ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Automation)
  877. ->Attribute(AZ::Script::Attributes::Module, "test.types")
  878. ->Method("signal_success", &SignalSuccess, nullptr, "")
  879. ->Method("return_bool", &ReturnValue<bool>, nullptr, "")
  880. ->Method("accept_bool", &AcceptValue<bool>, nullptr, "")
  881. ->Method("return_char", &ReturnValue<char>, nullptr, "")
  882. ->Method("accept_char", &AcceptValue<char>, nullptr, "")
  883. ->Method("return_float", &ReturnValue<float>, nullptr, "")
  884. ->Method("accept_float", &AcceptValue<float>, nullptr, "")
  885. ->Method("return_double", &ReturnValue<double>, nullptr, "")
  886. ->Method("accept_double", &AcceptValue<double>, nullptr, "")
  887. ->Method("return_s8", &ReturnValue<AZ::s8>, nullptr, "")
  888. ->Method("accept_s8", &AcceptValue<AZ::s8>, nullptr, "")
  889. ->Method("return_u8", &ReturnValue<AZ::u8>, nullptr, "")
  890. ->Method("accept_u8", &AcceptValue<AZ::u8>, nullptr, "")
  891. ->Method("return_s16", &ReturnValue<AZ::s16>, nullptr, "")
  892. ->Method("accept_s16", &AcceptValue<AZ::s16>, nullptr, "")
  893. ->Method("return_u16", &ReturnValue<AZ::u16>, nullptr, "")
  894. ->Method("accept_u16", &AcceptValue<AZ::u16>, nullptr, "")
  895. ->Method("return_s32", &ReturnValue<AZ::s32>, nullptr, "")
  896. ->Method("accept_s32", &AcceptValue<AZ::s32>, nullptr, "")
  897. ->Method("return_u32", &ReturnValue<AZ::u32>, nullptr, "")
  898. ->Method("accept_u32", &AcceptValue<AZ::u32>, nullptr, "")
  899. ->Method("return_s64", &ReturnValue<AZ::s64>, nullptr, "")
  900. ->Method("accept_s64", &AcceptValue<AZ::s64>, nullptr, "")
  901. ->Method("return_u64", &ReturnValue<AZ::u64>, nullptr, "")
  902. ->Method("accept_u64", &AcceptValue<AZ::u64>, nullptr, "")
  903. ->Method("return_vector4", &ReturnValue<AZ::Vector4>, nullptr, "")
  904. ->Method("accept_vector4", &AcceptValue<AZ::Vector4>, nullptr, "")
  905. ;
  906. }
  907. }
  908. };
  909. AZ::u32 PythonReflectionTypesTester::s_accepted = 0;
  910. AZ::u32 PythonReflectionTypesTester::s_returned = 0;
  911. AZ::u32 PythonReflectionTypesTester::s_successCount = 0;
  912. AZStd::any PythonReflectionTypesTester::s_theValue;
  913. TEST_F(PythonReflectionComponentTests, PythonReflectionTypes)
  914. {
  915. PythonReflectionTypesTester pythonReflectionTypesTester;
  916. pythonReflectionTypesTester.Reflect(m_app.GetBehaviorContext());
  917. AZ::Entity e;
  918. Activate(e);
  919. SimulateEditorBecomingInitialized();
  920. try
  921. {
  922. int testCount = 0;
  923. pybind11::exec(R"(import azlmbr.test.types)");
  924. pybind11::exec(R"(
  925. azlmbr.test.types.TypeTests_accept_bool(False)
  926. azlmbr.test.types.TypeTests_return_bool()
  927. )");
  928. ++testCount;
  929. EXPECT_EQ(testCount, PythonReflectionTypesTester::s_accepted);
  930. EXPECT_EQ(testCount, PythonReflectionTypesTester::s_returned);
  931. pybind11::exec(R"(
  932. azlmbr.test.types.TypeTests_accept_char(chr(97))
  933. azlmbr.test.types.TypeTests_return_char()
  934. )");
  935. ++testCount;
  936. EXPECT_EQ(testCount, PythonReflectionTypesTester::s_accepted);
  937. EXPECT_EQ(testCount, PythonReflectionTypesTester::s_returned);
  938. pybind11::exec(R"(
  939. azlmbr.test.types.TypeTests_accept_float(0.01)
  940. azlmbr.test.types.TypeTests_return_float()
  941. )");
  942. ++testCount;
  943. EXPECT_EQ(testCount, PythonReflectionTypesTester::s_accepted);
  944. EXPECT_EQ(testCount, PythonReflectionTypesTester::s_returned);
  945. pybind11::exec(R"(
  946. azlmbr.test.types.TypeTests_accept_double(0.1234)
  947. azlmbr.test.types.TypeTests_return_double()
  948. )");
  949. ++testCount;
  950. EXPECT_EQ(testCount, PythonReflectionTypesTester::s_accepted);
  951. EXPECT_EQ(testCount, PythonReflectionTypesTester::s_returned);
  952. const char* intTypes[]{ "s8", "u8", "s16", "u16", "s32", "u32", "s64", "u64" };
  953. for (const char* intType : intTypes)
  954. {
  955. AZStd::string intTypeTest = AZStd::string::format("azlmbr.test.types.TypeTests_accept_%s(1) \nazlmbr.test.types.TypeTests_return_%s() \n", intType, intType);
  956. pybind11::exec(intTypeTest.c_str());
  957. ++testCount;
  958. EXPECT_EQ(testCount, PythonReflectionTypesTester::s_accepted);
  959. EXPECT_EQ(testCount, PythonReflectionTypesTester::s_returned);
  960. }
  961. }
  962. catch ([[maybe_unused]] const std::exception& e)
  963. {
  964. AZ_Warning("UnitTest", false, "Failed on with Python exception %s", e.what());
  965. FAIL();
  966. }
  967. e.Deactivate();
  968. }
  969. TEST_F(PythonReflectionComponentTests, PythonReflectStringTypes)
  970. {
  971. if (AZ::SerializeContext* serializeContext = m_app.GetSerializeContext())
  972. {
  973. serializeContext->RegisterGenericType<AZStd::vector<AZStd::string>>();
  974. serializeContext->RegisterGenericType<AZStd::vector<AZStd::string_view>>();
  975. }
  976. PythonReflectionStringTypes pythonReflectionStringTypes;
  977. pythonReflectionStringTypes.Reflect(m_app.GetBehaviorContext());
  978. AZ::Entity e;
  979. Activate(e);
  980. SimulateEditorBecomingInitialized();
  981. enum class LogTypes
  982. {
  983. Skip = 0,
  984. PythonReflectStringTypes_RawStringIn,
  985. PythonReflectStringTypes_RawStringOut,
  986. PythonReflectStringTypes_StringViewIn,
  987. PythonReflectStringTypes_StringViewOut,
  988. PythonReflectStringTypes_AZStdStringIn,
  989. PythonReflectStringTypes_AZStdStringOut,
  990. PythonReflectStringTypes_AZStdVectorStringOut,
  991. PythonReflectStringTypes_AZStdVectorStringIn,
  992. PythonReflectStringTypes_EmptyStringOut,
  993. PythonReflectStringTypes_EmptyStringIn,
  994. PythonReflectStringTypes_AZStdVectorStringViewOut,
  995. PythonReflectStringTypes_AZStdVectorStringViewIn
  996. };
  997. m_testSink.m_evaluateMessage = [](const char* window, const char* message) -> int
  998. {
  999. if (AzFramework::StringFunc::Equal(window, "python"))
  1000. {
  1001. if (AzFramework::StringFunc::Equal(message, "PythonReflectStringTypes_RawStringIn"))
  1002. {
  1003. return static_cast<int>(LogTypes::PythonReflectStringTypes_RawStringIn);
  1004. }
  1005. else if (AzFramework::StringFunc::Equal(message, "PythonReflectStringTypes_RawStringOut"))
  1006. {
  1007. return static_cast<int>(LogTypes::PythonReflectStringTypes_RawStringOut);
  1008. }
  1009. else if (AzFramework::StringFunc::Equal(message, "PythonReflectStringTypes_StringViewIn"))
  1010. {
  1011. return static_cast<int>(LogTypes::PythonReflectStringTypes_StringViewIn);
  1012. }
  1013. else if (AzFramework::StringFunc::Equal(message, "PythonReflectStringTypes_StringViewOut"))
  1014. {
  1015. return static_cast<int>(LogTypes::PythonReflectStringTypes_StringViewOut);
  1016. }
  1017. else if (AzFramework::StringFunc::Equal(message, "PythonReflectStringTypes_AZStdStringIn"))
  1018. {
  1019. return static_cast<int>(LogTypes::PythonReflectStringTypes_AZStdStringIn);
  1020. }
  1021. else if (AzFramework::StringFunc::Equal(message, "PythonReflectStringTypes_AZStdStringOut"))
  1022. {
  1023. return static_cast<int>(LogTypes::PythonReflectStringTypes_AZStdStringOut);
  1024. }
  1025. else if (AzFramework::StringFunc::Equal(message, "PythonReflectStringTypes_AZStdVectorStringOut"))
  1026. {
  1027. return static_cast<int>(LogTypes::PythonReflectStringTypes_AZStdVectorStringOut);
  1028. }
  1029. else if (AzFramework::StringFunc::Equal(message, "PythonReflectStringTypes_AZStdVectorStringIn"))
  1030. {
  1031. return static_cast<int>(LogTypes::PythonReflectStringTypes_AZStdVectorStringIn);
  1032. }
  1033. else if (AzFramework::StringFunc::Equal(message, "PythonReflectStringTypes_EmptyStringOut"))
  1034. {
  1035. return static_cast<int>(LogTypes::PythonReflectStringTypes_EmptyStringOut);
  1036. }
  1037. else if (AzFramework::StringFunc::Equal(message, "PythonReflectStringTypes_EmptyStringIn"))
  1038. {
  1039. return static_cast<int>(LogTypes::PythonReflectStringTypes_EmptyStringIn);
  1040. }
  1041. else if (AzFramework::StringFunc::Equal(message, "PythonReflectStringTypes_AZStdVectorStringViewOut"))
  1042. {
  1043. return static_cast<int>(LogTypes::PythonReflectStringTypes_AZStdVectorStringViewOut);
  1044. }
  1045. else if (AzFramework::StringFunc::Equal(message, "PythonReflectStringTypes_AZStdVectorStringViewIn"))
  1046. {
  1047. return static_cast<int>(LogTypes::PythonReflectStringTypes_AZStdVectorStringViewIn);
  1048. }
  1049. }
  1050. return static_cast<int>(LogTypes::Skip);
  1051. };
  1052. try
  1053. {
  1054. pybind11::exec(R"(
  1055. import azlmbr.test.strings
  1056. azlmbr.test.strings.Strings_raw_pointer_in('PythonReflectStringTypes_RawStringIn')
  1057. print (azlmbr.test.strings.Strings_raw_pointer_out())
  1058. azlmbr.test.strings.Strings_string_view_in('PythonReflectStringTypes_StringViewIn')
  1059. print (azlmbr.test.strings.Strings_string_view_out())
  1060. azlmbr.test.strings.Strings_azstd_string_in('PythonReflectStringTypes_AZStdStringIn')
  1061. print (azlmbr.test.strings.Strings_azstd_string_out())
  1062. stringList = azlmbr.test.strings.Strings_output_string_list()
  1063. if (stringList[0] == 'one' and stringList[1] == 'two' and stringList[2] == 'three'):
  1064. print ('PythonReflectStringTypes_AZStdVectorStringOut')
  1065. newStringList = ['1','2','3']
  1066. if (azlmbr.test.strings.Strings_input_string_list(newStringList) == True):
  1067. print ('PythonReflectStringTypes_AZStdVectorStringIn')
  1068. stringList = azlmbr.test.strings.Strings_output_string_view_list()
  1069. if (stringList[0] == 'one' and stringList[1] == 'two' and stringList[2] == 'three'):
  1070. print ('PythonReflectStringTypes_AZStdVectorStringViewOut')
  1071. newStringList = ['a','b','c']
  1072. if (azlmbr.test.strings.Strings_input_string_view_list(newStringList) == True):
  1073. print ('PythonReflectStringTypes_AZStdVectorStringViewIn')
  1074. emptyString = azlmbr.test.strings.Strings_output_empty_string()
  1075. if (isinstance(emptyString, str) and len(emptyString) == 0):
  1076. print ('PythonReflectStringTypes_EmptyStringOut')
  1077. emptyString = ''
  1078. if (azlmbr.test.strings.Strings_input_empty_string(emptyString)):
  1079. print ('PythonReflectStringTypes_EmptyStringIn')
  1080. )");
  1081. }
  1082. catch ([[maybe_unused]] const std::exception& e)
  1083. {
  1084. AZ_Warning("UnitTest", false, "Failed on with Python exception %s", e.what());
  1085. FAIL();
  1086. }
  1087. e.Deactivate();
  1088. EXPECT_EQ(1, m_testSink.m_evaluationMap[static_cast<int>(LogTypes::PythonReflectStringTypes_RawStringIn)]);
  1089. EXPECT_EQ(1, m_testSink.m_evaluationMap[static_cast<int>(LogTypes::PythonReflectStringTypes_RawStringOut)]);
  1090. EXPECT_EQ(1, m_testSink.m_evaluationMap[static_cast<int>(LogTypes::PythonReflectStringTypes_StringViewIn)]);
  1091. EXPECT_EQ(1, m_testSink.m_evaluationMap[static_cast<int>(LogTypes::PythonReflectStringTypes_StringViewOut)]);
  1092. EXPECT_EQ(1, m_testSink.m_evaluationMap[static_cast<int>(LogTypes::PythonReflectStringTypes_AZStdStringIn)]);
  1093. EXPECT_EQ(1, m_testSink.m_evaluationMap[static_cast<int>(LogTypes::PythonReflectStringTypes_AZStdStringOut)]);
  1094. EXPECT_EQ(1, m_testSink.m_evaluationMap[static_cast<int>(LogTypes::PythonReflectStringTypes_AZStdVectorStringOut)]);
  1095. EXPECT_EQ(1, m_testSink.m_evaluationMap[static_cast<int>(LogTypes::PythonReflectStringTypes_AZStdVectorStringIn)]);
  1096. EXPECT_EQ(1, m_testSink.m_evaluationMap[static_cast<int>(LogTypes::PythonReflectStringTypes_AZStdVectorStringViewOut)]);
  1097. EXPECT_EQ(1, m_testSink.m_evaluationMap[static_cast<int>(LogTypes::PythonReflectStringTypes_AZStdVectorStringViewIn)]);
  1098. EXPECT_EQ(1, m_testSink.m_evaluationMap[static_cast<int>(LogTypes::PythonReflectStringTypes_EmptyStringOut)]);
  1099. EXPECT_EQ(1, m_testSink.m_evaluationMap[static_cast<int>(LogTypes::PythonReflectStringTypes_EmptyStringIn)]);
  1100. }
  1101. TEST_F(PythonReflectionComponentTests, MathReflectionTests)
  1102. {
  1103. enum class LogTypes
  1104. {
  1105. Skip = 0,
  1106. MathColor,
  1107. MathStaticMembers
  1108. };
  1109. m_testSink.m_evaluateMessage = [](const char* window, const char* message) -> int
  1110. {
  1111. if (AzFramework::StringFunc::Equal(window, "python"))
  1112. {
  1113. if (AzFramework::StringFunc::Equal(message, "MathColor"))
  1114. {
  1115. return static_cast<int>(LogTypes::MathColor);
  1116. }
  1117. else if (AzFramework::StringFunc::Equal(message, "MathStaticMembers"))
  1118. {
  1119. return static_cast<int>(LogTypes::MathStaticMembers);
  1120. }
  1121. }
  1122. return static_cast<int>(LogTypes::Skip);
  1123. };
  1124. AZ::Entity e;
  1125. Activate(e);
  1126. SimulateEditorBecomingInitialized();
  1127. try
  1128. {
  1129. pybind11::exec(R"(
  1130. import azlmbr.math as math
  1131. import azlmbr.object
  1132. # testing math type Color
  1133. color = azlmbr.object.create('Color')
  1134. if( color is not None ):
  1135. print ('MathColor')
  1136. color = azlmbr.object.construct('Color', 0.15, 0.25, 0.35, 0.45)
  1137. if( color is not None ):
  1138. print ('MathColor')
  1139. if( math.Math_IsClose(color.r, 0.15) == True):
  1140. print ('MathColor')
  1141. if( math.Math_IsClose(color.g, 0.25) == True):
  1142. print ('MathColor')
  1143. if( math.Math_IsClose(color.b, 0.35) == True):
  1144. print ('MathColor')
  1145. if( math.Math_IsClose(color.a, 0.45) == True):
  1146. print ('MathColor')
  1147. color.r = 0.51
  1148. color.g = 0.52
  1149. color.b = 0.53
  1150. color.a = 0.54
  1151. if( math.Math_IsClose(color.r, 0.51) == True):
  1152. print ('MathColor')
  1153. if( math.Math_IsClose(color.g, 0.52) == True):
  1154. print ('MathColor')
  1155. if( math.Math_IsClose(color.b, 0.53) == True):
  1156. print ('MathColor')
  1157. if( math.Math_IsClose(color.a, 0.54) == True):
  1158. print ('MathColor')
  1159. # testing the Vector3 math type member like functions
  1160. vec3 = azlmbr.object.create('Vector3')
  1161. vec3.x = 0.0
  1162. vec3.y = 0.0
  1163. vec3.z = 0.0
  1164. if( vec3.ToString() == '(x=0.0000000,y=0.0000000,z=0.0000000)'):
  1165. print ('MathStaticMembers')
  1166. # testing the Uuid math type member like functions
  1167. uuidString = '{E866B520-D667-48A2-82F6-6AEBE1EC9C58}'
  1168. uuid = azlmbr.math.Uuid_CreateString(uuidString)
  1169. if( uuid.ToString() == uuidString):
  1170. print ('MathStaticMembers')
  1171. )");
  1172. }
  1173. catch ([[maybe_unused]] const std::exception& e)
  1174. {
  1175. AZStd::string failReason = AZStd::string::format("Failed on DefaultModule with %s", e.what());
  1176. GTEST_FATAL_FAILURE_(failReason.c_str());
  1177. }
  1178. e.Deactivate();
  1179. EXPECT_EQ(10, m_testSink.m_evaluationMap[static_cast<int>(LogTypes::MathColor)]);
  1180. EXPECT_EQ(2, m_testSink.m_evaluationMap[static_cast<int>(LogTypes::MathStaticMembers)]);
  1181. }
  1182. TEST_F(PythonReflectionComponentTests, ComplexContainers)
  1183. {
  1184. PythonReflectionComplexContainer pythonReflectionComplexContainer;
  1185. pythonReflectionComplexContainer.Reflect(m_app.GetBehaviorContext());
  1186. pythonReflectionComplexContainer.Reflect(m_app.GetSerializeContext());
  1187. enum class LogTypes
  1188. {
  1189. Skip = 0,
  1190. GotListOfIds
  1191. };
  1192. m_testSink.m_evaluateMessage = [](const char* window, const char* message) -> int
  1193. {
  1194. if (AzFramework::StringFunc::Equal(window, "python"))
  1195. {
  1196. if (AzFramework::StringFunc::Equal(message, "GotListOfIds"))
  1197. {
  1198. return static_cast<int>(LogTypes::GotListOfIds);
  1199. }
  1200. }
  1201. return static_cast<int>(LogTypes::Skip);
  1202. };
  1203. AZ::Entity e;
  1204. Activate(e);
  1205. SimulateEditorBecomingInitialized();
  1206. try
  1207. {
  1208. pybind11::exec(R"(
  1209. import azlmbr.test
  1210. import azlmbr.object
  1211. container = azlmbr.object.create('ComplexContainer')
  1212. entityIdList = container.send_list_of_ids()
  1213. if( len(entityIdList) == 3):
  1214. print ('GotListOfIds')
  1215. if( entityIdList[0].ToString() == '[101]'):
  1216. print ('GotListOfIds')
  1217. if( entityIdList[1].ToString() == '[202]'):
  1218. print ('GotListOfIds')
  1219. if( entityIdList[2].ToString() == '[303]'):
  1220. print ('GotListOfIds')
  1221. )");
  1222. }
  1223. catch ([[maybe_unused]] const std::exception& e)
  1224. {
  1225. AZ_Warning("UnitTest", false, "Failed on DefaultModule with %s", e.what());
  1226. FAIL();
  1227. }
  1228. e.Deactivate();
  1229. EXPECT_EQ(4, m_testSink.m_evaluationMap[static_cast<int>(LogTypes::GotListOfIds)]);
  1230. }
  1231. TEST_F(PythonReflectionComponentTests, ProjectPaths)
  1232. {
  1233. enum class LogTypes
  1234. {
  1235. Skip = 0,
  1236. EngrootIs,
  1237. pathResolvedTo,
  1238. };
  1239. m_testSink.m_evaluateMessage = [](const char* window, const char* message) -> int
  1240. {
  1241. if (AzFramework::StringFunc::Equal(window, "python"))
  1242. {
  1243. AZStd::string_view m(message);
  1244. if (AzFramework::StringFunc::StartsWith(message, "engroot is "))
  1245. {
  1246. return static_cast<int>(LogTypes::EngrootIs);
  1247. }
  1248. else if (AzFramework::StringFunc::StartsWith(message, "path resolved to "))
  1249. {
  1250. return static_cast<int>(LogTypes::pathResolvedTo);
  1251. }
  1252. }
  1253. return static_cast<int>(LogTypes::Skip);
  1254. };
  1255. AZ::Entity e;
  1256. e.CreateComponent<EditorPythonBindings::PythonSystemComponent>();
  1257. e.CreateComponent<EditorPythonBindings::PythonReflectionComponent>();
  1258. e.CreateComponent<EditorPythonBindings::PythonMarshalComponent>();
  1259. e.Init();
  1260. e.Activate();
  1261. SimulateEditorBecomingInitialized();
  1262. try
  1263. {
  1264. pybind11::exec(R"(
  1265. import azlmbr.paths
  1266. if (len(azlmbr.paths.engroot) != 0):
  1267. print ('engroot is {}'.format(azlmbr.paths.engroot))
  1268. path = azlmbr.paths.resolve_path('@engroot@/engineassets/texturemsg/defaultsolids.mtl')
  1269. if (path.find('@engroot@') == -1):
  1270. print ('path resolved to {}'.format(path))
  1271. )");
  1272. }
  1273. catch ([[maybe_unused]] const std::exception& e)
  1274. {
  1275. AZ_Warning("UnitTest", false, "Failed on with Python exception: %s", e.what());
  1276. FAIL();
  1277. }
  1278. e.Deactivate();
  1279. EXPECT_EQ(m_testSink.m_evaluationMap[(int)LogTypes::EngrootIs], 1);
  1280. EXPECT_EQ(m_testSink.m_evaluationMap[(int)LogTypes::pathResolvedTo], 1);
  1281. }
  1282. }