PythonReflectionComponentTests.cpp 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484
  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. }