ScriptReporter.cpp 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142
  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 <Automation/ScriptReporter.h>
  9. #include <Utils/Utils.h>
  10. #include <imgui/imgui.h>
  11. #include <Atom/RHI/Factory.h>
  12. #include <AzFramework/API/ApplicationAPI.h>
  13. #include <AzFramework/StringFunc/StringFunc.h>
  14. #include <AzFramework/IO/LocalFileIO.h>
  15. #include <AzCore/IO/SystemFile.h>
  16. #include <AzCore/Utils/Utils.h>
  17. namespace AtomSampleViewer
  18. {
  19. // Must match ScriptReporter::DisplayOption Enum
  20. static const char* DiplayOptions[] =
  21. {
  22. "All Results", "Warnings & Errors", "Errors Only",
  23. };
  24. namespace ScreenshotPaths
  25. {
  26. AZStd::string GetScreenshotsFolder(bool resolvePath)
  27. {
  28. AZStd::string path = "@user@/scripts/screenshots/";
  29. if (resolvePath)
  30. {
  31. path = Utils::ResolvePath(path);
  32. }
  33. return path;
  34. }
  35. AZStd::string GetLocalBaselineFolder(bool resolvePath)
  36. {
  37. AZStd::string path = AZStd::string::format("@user@/scripts/screenshotslocalbaseline/%s", AZ::RHI::Factory::Get().GetName().GetCStr());
  38. if (resolvePath)
  39. {
  40. path = Utils::ResolvePath(path);
  41. }
  42. return path;
  43. }
  44. AZStd::string GetOfficialBaselineFolder(bool resolvePath)
  45. {
  46. AZStd::string path = "scripts/expectedscreenshots/";
  47. if (resolvePath)
  48. {
  49. path = Utils::ResolvePath(path);
  50. }
  51. return path;
  52. }
  53. AZStd::string GetLocalBaseline(const AZStd::string& forScreenshotFile)
  54. {
  55. AZStd::string localBaselineFolder = GetLocalBaselineFolder(false);
  56. AzFramework::StringFunc::Replace(localBaselineFolder, "@user@/", "");
  57. AZStd::string newPath = forScreenshotFile;
  58. if (!AzFramework::StringFunc::Replace(newPath, "scripts/screenshots", localBaselineFolder.c_str()))
  59. {
  60. newPath = "";
  61. }
  62. return newPath;
  63. }
  64. AZStd::string GetOfficialBaseline(const AZStd::string& forScreenshotFile)
  65. {
  66. AZStd::string path = forScreenshotFile;
  67. const AZStd::string userPath = Utils::ResolvePath("@user@");
  68. // make the path relative to the user folder
  69. if (!AzFramework::StringFunc::Replace(path, userPath.c_str(), ""))
  70. {
  71. return "";
  72. }
  73. // After replacing "screenshots" with "expectedscreenshots", the path should be a valid asset path, relative to asset root.
  74. if (!AzFramework::StringFunc::Replace(path, "scripts/screenshots", "scripts/expectedscreenshots"))
  75. {
  76. return "";
  77. }
  78. // Turn it back into a full path
  79. path = Utils::ResolvePath("@devassets@" + path);
  80. return path;
  81. }
  82. }
  83. AZStd::string ScriptReporter::ImageComparisonResult::GetSummaryString() const
  84. {
  85. AZStd::string resultString;
  86. if (m_resultCode == ResultCode::ThresholdExceeded || m_resultCode == ResultCode::Pass)
  87. {
  88. resultString = AZStd::string::format("Diff Score: %f", m_finalDiffScore);
  89. }
  90. else if (m_resultCode == ResultCode::WrongSize)
  91. {
  92. resultString = "Wrong size";
  93. }
  94. else if (m_resultCode == ResultCode::FileNotFound)
  95. {
  96. resultString = "File not found";
  97. }
  98. else if (m_resultCode == ResultCode::FileNotLoaded)
  99. {
  100. resultString = "File load failed";
  101. }
  102. else if (m_resultCode == ResultCode::WrongFormat)
  103. {
  104. resultString = "Format is not supported";
  105. }
  106. else if (m_resultCode == ResultCode::NullImageComparisonToleranceLevel)
  107. {
  108. resultString = "ImageComparisonToleranceLevel not provided";
  109. }
  110. else if (m_resultCode == ResultCode::None)
  111. {
  112. // "None" could be the case if the results dialog is open while the script is running
  113. resultString = "No results";
  114. }
  115. else
  116. {
  117. resultString = "Unhandled Image Comparison ResultCode";
  118. AZ_Assert(false, "Unhandled Image Comparison ResultCode");
  119. }
  120. return resultString;
  121. }
  122. void ScriptReporter::SetAvailableToleranceLevels(const AZStd::vector<ImageComparisonToleranceLevel>& toleranceLevels)
  123. {
  124. m_availableToleranceLevels = toleranceLevels;
  125. }
  126. void ScriptReporter::Reset()
  127. {
  128. m_scriptReports.clear();
  129. m_currentScriptIndexStack.clear();
  130. m_invalidationMessage.clear();
  131. }
  132. void ScriptReporter::SetInvalidationMessage(const AZStd::string& message)
  133. {
  134. m_invalidationMessage = message;
  135. // Reporting this message here instead of when running the script so it won't show up as an error in the ImGui report.
  136. AZ_Error("Automation", m_invalidationMessage.empty(), "Subsequent test results will be invalid because '%s'", m_invalidationMessage.c_str());
  137. }
  138. void ScriptReporter::PushScript(const AZStd::string& scriptAssetPath)
  139. {
  140. if (GetCurrentScriptReport())
  141. {
  142. // Only the current script should listen for Trace Errors
  143. GetCurrentScriptReport()->BusDisconnect();
  144. }
  145. m_currentScriptIndexStack.push_back(m_scriptReports.size());
  146. m_scriptReports.push_back();
  147. m_scriptReports.back().m_scriptAssetPath = scriptAssetPath;
  148. m_scriptReports.back().BusConnect();
  149. }
  150. void ScriptReporter::PopScript()
  151. {
  152. AZ_Assert(GetCurrentScriptReport(), "There is no active script");
  153. if (GetCurrentScriptReport())
  154. {
  155. GetCurrentScriptReport()->BusDisconnect();
  156. m_currentScriptIndexStack.pop_back();
  157. }
  158. if (GetCurrentScriptReport())
  159. {
  160. // Make sure the newly restored current script is listening for Trace Errors
  161. GetCurrentScriptReport()->BusConnect();
  162. }
  163. }
  164. bool ScriptReporter::HasActiveScript() const
  165. {
  166. return !m_currentScriptIndexStack.empty();
  167. }
  168. bool ScriptReporter::AddScreenshotTest(const AZStd::string& path)
  169. {
  170. AZ_Assert(GetCurrentScriptReport(), "There is no active script");
  171. ScreenshotTestInfo screenshotTestInfo;
  172. screenshotTestInfo.m_screenshotFilePath = path;
  173. GetCurrentScriptReport()->m_screenshotTests.push_back(AZStd::move(screenshotTestInfo));
  174. return true;
  175. }
  176. void ScriptReporter::TickImGui()
  177. {
  178. if (m_showReportDialog)
  179. {
  180. ShowReportDialog();
  181. }
  182. }
  183. bool ScriptReporter::HasErrorsAssertsInReport() const
  184. {
  185. for (const ScriptReport& scriptReport : m_scriptReports)
  186. {
  187. if (scriptReport.m_assertCount > 0 || scriptReport.m_generalErrorCount > 0 || scriptReport.m_screenshotErrorCount > 0)
  188. {
  189. return true;
  190. }
  191. }
  192. return false;
  193. }
  194. void ScriptReporter::ShowDiffButton(const char* buttonLabel, const AZStd::string& imagePathA, const AZStd::string& imagePathB)
  195. {
  196. if (ImGui::Button(buttonLabel))
  197. {
  198. if (!Utils::RunDiffTool(imagePathA, imagePathB))
  199. {
  200. m_messageBox.OpenPopupMessage("Can't Diff", "Image diff is not supported on this platform, or the required diff tool is not installed.");
  201. }
  202. }
  203. }
  204. const ImageComparisonToleranceLevel* ScriptReporter::FindBestToleranceLevel(float diffScore, bool filterImperceptibleDiffs) const
  205. {
  206. float thresholdChecked = 0.0f;
  207. bool ignoringMinorDiffs = false;
  208. for (const ImageComparisonToleranceLevel& level : m_availableToleranceLevels)
  209. {
  210. AZ_Assert(level.m_threshold > thresholdChecked || thresholdChecked == 0.0f, "Threshold values are not sequential");
  211. AZ_Assert(level.m_filterImperceptibleDiffs >= ignoringMinorDiffs, "filterImperceptibleDiffs values are not sequential");
  212. thresholdChecked = level.m_threshold;
  213. ignoringMinorDiffs = level.m_filterImperceptibleDiffs;
  214. if (filterImperceptibleDiffs <= level.m_filterImperceptibleDiffs && diffScore <= level.m_threshold)
  215. {
  216. return &level;
  217. }
  218. }
  219. return nullptr;
  220. }
  221. void ScriptReporter::ShowReportDialog()
  222. {
  223. if (ImGui::Begin("Script Results", &m_showReportDialog) && !m_scriptReports.empty())
  224. {
  225. const ImVec4& bgColor = ImGui::GetStyleColorVec4(ImGuiCol_WindowBg);
  226. const bool isDarkStyle = bgColor.x < 0.2 && bgColor.y < 0.2 && bgColor.z < 0.2;
  227. const ImVec4 HighlightPassed = isDarkStyle ? ImVec4{0.5, 1, 0.5, 1} : ImVec4{0, 0.75, 0, 1};
  228. const ImVec4 HighlightFailed = isDarkStyle ? ImVec4{1, 0.5, 0.5, 1} : ImVec4{0.75, 0, 0, 1};
  229. const ImVec4 HighlightWarning = isDarkStyle ? ImVec4{1, 1, 0.5, 1} : ImVec4{0.5, 0.5, 0, 1};
  230. // Local utilities for setting text color
  231. bool colorHasBeenSet = false;
  232. auto highlightTextIf = [&colorHasBeenSet](bool shouldSet, ImVec4 color)
  233. {
  234. if (colorHasBeenSet)
  235. {
  236. ImGui::PopStyleColor();
  237. colorHasBeenSet = false;
  238. }
  239. if (shouldSet)
  240. {
  241. ImGui::PushStyleColor(ImGuiCol_Text, color);
  242. colorHasBeenSet = true;
  243. }
  244. };
  245. auto highlightTextFailedOrWarning = [&](bool isFailed, bool isWarning)
  246. {
  247. if (colorHasBeenSet)
  248. {
  249. ImGui::PopStyleColor();
  250. colorHasBeenSet = false;
  251. }
  252. if (isFailed)
  253. {
  254. ImGui::PushStyleColor(ImGuiCol_Text, HighlightFailed);
  255. colorHasBeenSet = true;
  256. }
  257. else if (isWarning)
  258. {
  259. ImGui::PushStyleColor(ImGuiCol_Text, HighlightWarning);
  260. colorHasBeenSet = true;
  261. }
  262. };
  263. auto resetTextHighlight = [&colorHasBeenSet]()
  264. {
  265. if (colorHasBeenSet)
  266. {
  267. ImGui::PopStyleColor();
  268. colorHasBeenSet = false;
  269. }
  270. };
  271. auto seeConsole = [](uint32_t issueCount, const char* searchString)
  272. {
  273. if (issueCount == 0)
  274. {
  275. return AZStd::string{};
  276. }
  277. else
  278. {
  279. return AZStd::string::format("(See \"%s\" messages in console output)", searchString);
  280. }
  281. };
  282. auto seeBelow = [](uint32_t issueCount)
  283. {
  284. if (issueCount == 0)
  285. {
  286. return AZStd::string{};
  287. }
  288. else
  289. {
  290. return AZStd::string::format("(See below)");
  291. }
  292. };
  293. uint32_t totalAsserts = 0;
  294. uint32_t totalErrors = 0;
  295. uint32_t totalWarnings = 0;
  296. uint32_t totalScreenshotsCount = 0;
  297. uint32_t totalScreenshotsFailed = 0;
  298. uint32_t totalScreenshotWarnings = 0;
  299. for (ScriptReport& scriptReport : m_scriptReports)
  300. {
  301. totalAsserts += scriptReport.m_assertCount;
  302. // We don't include screenshot errors and warnings in these totals because those have their own line-items.
  303. totalErrors += scriptReport.m_generalErrorCount;
  304. totalWarnings += scriptReport.m_generalWarningCount;
  305. totalScreenshotWarnings += scriptReport.m_screenshotWarningCount;
  306. totalScreenshotsFailed += scriptReport.m_screenshotErrorCount;
  307. // This will catch any false-negatives that could occur if the screenshot failure error messages change without also updating ScriptReport::OnPreError()
  308. for (ScreenshotTestInfo& screenshotTest : scriptReport.m_screenshotTests)
  309. {
  310. if (screenshotTest.m_officialComparisonResult.m_resultCode != ImageComparisonResult::ResultCode::Pass &&
  311. screenshotTest.m_officialComparisonResult.m_resultCode != ImageComparisonResult::ResultCode::None)
  312. {
  313. AZ_Assert(scriptReport.m_screenshotErrorCount > 0, "If screenshot comparison failed in any way, m_screenshotErrorCount should be non-zero.");
  314. }
  315. }
  316. }
  317. ImGui::Separator();
  318. if (HasActiveScript())
  319. {
  320. ImGui::PushStyleColor(ImGuiCol_Text, HighlightWarning);
  321. ImGui::Text("Script is running... (_ _)zzz");
  322. ImGui::PopStyleColor();
  323. }
  324. else if (totalErrors > 0 || totalAsserts > 0 || totalScreenshotsFailed > 0)
  325. {
  326. ImGui::PushStyleColor(ImGuiCol_Text, HighlightFailed);
  327. ImGui::Text("(>_<) FAILED (>_<)");
  328. ImGui::PopStyleColor();
  329. }
  330. else
  331. {
  332. if (m_invalidationMessage.empty())
  333. {
  334. ImGui::PushStyleColor(ImGuiCol_Text, HighlightPassed);
  335. ImGui::Text("\\(^_^)/ PASSED \\(^_^)/");
  336. ImGui::PopStyleColor();
  337. }
  338. else
  339. {
  340. ImGui::Text("(-_-) INVALID ... but passed (-_-)");
  341. }
  342. }
  343. if (!m_invalidationMessage.empty())
  344. {
  345. ImGui::Separator();
  346. ImGui::PushStyleColor(ImGuiCol_Text, HighlightFailed);
  347. ImGui::Text("(%s)", m_invalidationMessage.c_str());
  348. ImGui::PopStyleColor();
  349. }
  350. ImGui::Separator();
  351. ImGui::Text("Test Script Count: %zu", m_scriptReports.size());
  352. highlightTextIf(totalAsserts > 0, HighlightFailed);
  353. ImGui::Text("Total Asserts: %u %s", totalAsserts, seeConsole(totalAsserts, "Trace::Assert").c_str());
  354. highlightTextIf(totalErrors > 0, HighlightFailed);
  355. ImGui::Text("Total Errors: %u %s", totalErrors, seeConsole(totalErrors, "Trace::Error").c_str());
  356. highlightTextIf(totalWarnings > 0, HighlightWarning);
  357. ImGui::Text("Total Warnings: %u %s", totalWarnings, seeConsole(totalWarnings, "Trace::Warning").c_str());
  358. resetTextHighlight();
  359. ImGui::Text("Total Screenshot Count: %u", totalScreenshotsCount);
  360. highlightTextIf(totalScreenshotsFailed > 0, HighlightFailed);
  361. ImGui::Text("Total Screenshot Failures: %u %s", totalScreenshotsFailed, seeBelow(totalScreenshotsFailed).c_str());
  362. highlightTextIf(totalScreenshotWarnings > 0, HighlightWarning);
  363. ImGui::Text("Total Screenshot Warnings: %u %s", totalScreenshotWarnings, seeBelow(totalScreenshotWarnings).c_str());
  364. resetTextHighlight();
  365. if (ImGui::Button("Update All Local Baseline Images"))
  366. {
  367. m_messageBox.OpenPopupConfirmation(
  368. "Update All Local Baseline Images",
  369. "This will replace all local baseline images \n"
  370. "with the images captured during this test run. \n"
  371. "Are you sure?",
  372. [this]() {
  373. UpdateAllLocalBaselineImages();
  374. });
  375. }
  376. if (ImGui::Button("Export Test Results"))
  377. {
  378. m_messageBox.OpenPopupConfirmation(
  379. "Export Test Results",
  380. "All test results will be exported \n"
  381. "Proceed?",
  382. [this]() {
  383. ExportTestResults();
  384. });
  385. }
  386. int displayOption = m_displayOption;
  387. ImGui::Combo("Display", &displayOption, DiplayOptions, AZ_ARRAY_SIZE(DiplayOptions));
  388. m_displayOption = (DisplayOption)displayOption;
  389. ImGui::Checkbox("Force Show 'Update' Buttons", &m_forceShowUpdateButtons);
  390. bool showWarnings = (m_displayOption == DisplayOption::AllResults) || (m_displayOption == DisplayOption::WarningsAndErrors);
  391. bool showAll = (m_displayOption == DisplayOption::AllResults);
  392. ImGui::Separator();
  393. const ImGuiTreeNodeFlags FlagDefaultOpen = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick | ImGuiTreeNodeFlags_DefaultOpen;
  394. const ImGuiTreeNodeFlags FlagDefaultClosed = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick;
  395. for (ScriptReport& scriptReport : m_scriptReports)
  396. {
  397. const bool scriptPassed = scriptReport.m_assertCount == 0 && scriptReport.m_generalErrorCount == 0 && scriptReport.m_screenshotErrorCount == 0;
  398. const bool scriptHasWarnings = scriptReport.m_generalWarningCount > 0 || scriptReport.m_screenshotWarningCount > 0;
  399. // Skip if tests passed without warnings and we don't want to show successes
  400. bool skipReport = (scriptPassed && !scriptHasWarnings && !showAll);
  401. // Skip if we only have warnings only and we don't want to show warnings
  402. skipReport = skipReport || (scriptPassed && scriptHasWarnings && !showWarnings);
  403. if (skipReport)
  404. {
  405. continue;
  406. }
  407. ImGuiTreeNodeFlags scriptNodeFlag = scriptPassed ? FlagDefaultClosed : FlagDefaultOpen;
  408. AZStd::string header = AZStd::string::format("%s %s",
  409. scriptPassed ? "PASSED" : "FAILED",
  410. scriptReport.m_scriptAssetPath.c_str()
  411. );
  412. highlightTextFailedOrWarning(!scriptPassed, scriptHasWarnings);
  413. if (ImGui::TreeNodeEx(&scriptReport, scriptNodeFlag, "%s", header.c_str()))
  414. {
  415. resetTextHighlight();
  416. // Number of Asserts
  417. highlightTextIf(scriptReport.m_assertCount > 0, HighlightFailed);
  418. if (showAll || scriptReport.m_assertCount > 0)
  419. {
  420. ImGui::Text("Asserts: %u %s", scriptReport.m_assertCount, seeConsole(scriptReport.m_assertCount, "Trace::Assert").c_str());
  421. }
  422. // Number of Errors
  423. highlightTextIf(scriptReport.m_generalErrorCount > 0, HighlightFailed);
  424. if (showAll || scriptReport.m_generalErrorCount > 0)
  425. {
  426. ImGui::Text("Errors: %u %s", scriptReport.m_generalErrorCount, seeConsole(scriptReport.m_generalErrorCount, "Trace::Error").c_str());
  427. }
  428. // Number of Warnings
  429. highlightTextIf(scriptReport.m_generalWarningCount > 0, HighlightWarning);
  430. if (showAll || (showWarnings && scriptReport.m_generalWarningCount > 0))
  431. {
  432. ImGui::Text("Warnings: %u %s", scriptReport.m_generalWarningCount, seeConsole(scriptReport.m_generalWarningCount, "Trace::Warning").c_str());
  433. }
  434. resetTextHighlight();
  435. // Number of screenshots
  436. if (showAll || scriptReport.m_screenshotErrorCount > 0 || (showWarnings && scriptReport.m_screenshotWarningCount > 0))
  437. {
  438. ImGui::Text("Screenshot Test Count: %zu", scriptReport.m_screenshotTests.size());
  439. }
  440. // Number of screenshot failures
  441. highlightTextIf(scriptReport.m_screenshotErrorCount > 0, HighlightFailed);
  442. if (showAll || scriptReport.m_screenshotErrorCount > 0)
  443. {
  444. ImGui::Text("Screenshot Tests Failed: %u %s", scriptReport.m_screenshotErrorCount, seeBelow(scriptReport.m_screenshotErrorCount).c_str());
  445. }
  446. // Number of screenshot warnings
  447. highlightTextIf(scriptReport.m_screenshotWarningCount > 0, HighlightWarning);
  448. if (showAll || (showWarnings && scriptReport.m_screenshotWarningCount > 0))
  449. {
  450. ImGui::Text("Screenshot Warnings: %u %s", scriptReport.m_screenshotWarningCount, seeBelow(scriptReport.m_screenshotWarningCount).c_str());
  451. }
  452. resetTextHighlight();
  453. for (ScreenshotTestInfo& screenshotResult : scriptReport.m_screenshotTests)
  454. {
  455. const bool screenshotPassed = screenshotResult.m_officialComparisonResult.m_resultCode == ImageComparisonResult::ResultCode::Pass;
  456. const bool localBaselineWarning = screenshotResult.m_localComparisonResult.m_resultCode != ImageComparisonResult::ResultCode::Pass;
  457. // Skip if tests passed without warnings and we don't want to show successes
  458. bool skipScreenshot = (screenshotPassed && !localBaselineWarning && !showAll);
  459. // Skip if we only have warnings only and we don't want to show warnings
  460. skipScreenshot = skipScreenshot || (screenshotPassed && localBaselineWarning && !showWarnings);
  461. if (skipScreenshot)
  462. {
  463. continue;
  464. }
  465. AZStd::string fileName;
  466. AzFramework::StringFunc::Path::GetFullFileName(screenshotResult.m_screenshotFilePath.c_str(), fileName);
  467. AZStd::string headerSummary;
  468. if (!screenshotPassed)
  469. {
  470. headerSummary = "(" + screenshotResult.m_officialComparisonResult.GetSummaryString() + ") ";
  471. }
  472. if (localBaselineWarning)
  473. {
  474. headerSummary += "(Local Baseline Warning)";
  475. }
  476. ImGuiTreeNodeFlags screenshotNodeFlag = FlagDefaultClosed;
  477. AZStd::string screenshotHeader = AZStd::string::format("%s %s %s", screenshotPassed ? "PASSED" : "FAILED", fileName.c_str(), headerSummary.c_str());
  478. highlightTextFailedOrWarning(!screenshotPassed, localBaselineWarning);
  479. if (ImGui::TreeNodeEx(&screenshotResult, screenshotNodeFlag, "%s", screenshotHeader.c_str()))
  480. {
  481. resetTextHighlight();
  482. ImGui::Text("Screenshot: %s", screenshotResult.m_screenshotFilePath.c_str());
  483. ImGui::Spacing();
  484. highlightTextIf(!screenshotPassed, HighlightFailed);
  485. ImGui::Text("Official Baseline: %s", screenshotResult.m_officialBaselineScreenshotFilePath.c_str());
  486. // Official Baseline Result
  487. ImGui::Indent();
  488. {
  489. ImGui::Text("%s", screenshotResult.m_officialComparisonResult.GetSummaryString().c_str());
  490. if (screenshotResult.m_officialComparisonResult.m_resultCode == ImageComparisonResult::ResultCode::ThresholdExceeded ||
  491. screenshotResult.m_officialComparisonResult.m_resultCode == ImageComparisonResult::ResultCode::Pass)
  492. {
  493. ImGui::Text("Used Tolerance: %s", screenshotResult.m_toleranceLevel.ToString().c_str());
  494. const ImageComparisonToleranceLevel* suggestedTolerance = ScriptReporter::FindBestToleranceLevel(
  495. screenshotResult.m_officialComparisonResult.m_finalDiffScore,
  496. screenshotResult.m_toleranceLevel.m_filterImperceptibleDiffs);
  497. if(suggestedTolerance)
  498. {
  499. ImGui::Text("Suggested Tolerance: %s", suggestedTolerance->ToString().c_str());
  500. }
  501. if (screenshotResult.m_toleranceLevel.m_filterImperceptibleDiffs)
  502. {
  503. // This gives an idea of what the tolerance level would be if the imperceptible diffs were not filtered out.
  504. const ImageComparisonToleranceLevel* unfilteredTolerance = ScriptReporter::FindBestToleranceLevel(
  505. screenshotResult.m_officialComparisonResult.m_standardDiffScore, false);
  506. ImGui::Text("(Unfiltered Diff Score: %f%s)",
  507. screenshotResult.m_officialComparisonResult.m_standardDiffScore,
  508. unfilteredTolerance ? AZStd::string::format(" ~ '%s'", unfilteredTolerance->m_name.c_str()).c_str() : "");
  509. }
  510. }
  511. resetTextHighlight();
  512. ImGui::PushID("Official");
  513. ShowDiffButton("View Diff", screenshotResult.m_officialBaselineScreenshotFilePath, screenshotResult.m_screenshotFilePath);
  514. ImGui::PopID();
  515. if ((!screenshotPassed || m_forceShowUpdateButtons) && ImGui::Button("Update##Official"))
  516. {
  517. if (screenshotResult.m_localComparisonResult.m_resultCode == ImageComparisonResult::ResultCode::FileNotFound)
  518. {
  519. UpdateSourceBaselineImage(screenshotResult, true);
  520. }
  521. else
  522. {
  523. m_messageBox.OpenPopupConfirmation(
  524. "Update Official Baseline Image",
  525. "This will replace the official baseline image \n"
  526. "with the image captured during this test run. \n"
  527. "Are you sure?",
  528. // It's important to bind screenshotResult by reference because UpdateOfficialBaselineImage will update it
  529. [this, &screenshotResult]() {
  530. UpdateSourceBaselineImage(screenshotResult, true);
  531. });
  532. }
  533. }
  534. }
  535. ImGui::Unindent();
  536. ImGui::Spacing();
  537. highlightTextIf(localBaselineWarning, HighlightWarning);
  538. ImGui::Text("Local Baseline: %s", screenshotResult.m_localBaselineScreenshotFilePath.c_str());
  539. // Local Baseline Result
  540. ImGui::Indent();
  541. {
  542. ImGui::Text("%s", screenshotResult.m_localComparisonResult.GetSummaryString().c_str());
  543. resetTextHighlight();
  544. ImGui::PushID("Local");
  545. ShowDiffButton("View Diff", screenshotResult.m_localBaselineScreenshotFilePath, screenshotResult.m_screenshotFilePath);
  546. ImGui::PopID();
  547. if ((localBaselineWarning || m_forceShowUpdateButtons) && ImGui::Button("Update##Local"))
  548. {
  549. if (screenshotResult.m_localComparisonResult.m_resultCode == ImageComparisonResult::ResultCode::FileNotFound)
  550. {
  551. UpdateLocalBaselineImage(screenshotResult, true);
  552. }
  553. else
  554. {
  555. m_messageBox.OpenPopupConfirmation(
  556. "Update Local Baseline Image",
  557. "This will replace the local baseline image \n"
  558. "with the image captured during this test run. \n"
  559. "Are you sure?",
  560. // It's important to bind screenshotResult by reference because UpdateLocalBaselineImage will update it
  561. [this, &screenshotResult]() {
  562. UpdateLocalBaselineImage(screenshotResult, true);
  563. });
  564. }
  565. }
  566. }
  567. ImGui::Unindent();
  568. ImGui::Spacing();
  569. resetTextHighlight();
  570. ImGui::TreePop();
  571. }
  572. }
  573. ImGui::TreePop();
  574. }
  575. resetTextHighlight();
  576. }
  577. resetTextHighlight();
  578. // Repeat the m_invalidationMessage at the bottom as well, to make sure the user doesn't miss it.
  579. if (!m_invalidationMessage.empty())
  580. {
  581. ImGui::Separator();
  582. ImGui::PushStyleColor(ImGuiCol_Text, HighlightFailed);
  583. ImGui::Text("(%s)", m_invalidationMessage.c_str());
  584. ImGui::PopStyleColor();
  585. }
  586. }
  587. m_messageBox.TickPopup();
  588. ImGui::End();
  589. }
  590. void ScriptReporter::OpenReportDialog()
  591. {
  592. m_showReportDialog = true;
  593. }
  594. ScriptReporter::ScriptReport* ScriptReporter::GetCurrentScriptReport()
  595. {
  596. if (!m_currentScriptIndexStack.empty())
  597. {
  598. return &m_scriptReports[m_currentScriptIndexStack.back()];
  599. }
  600. else
  601. {
  602. return nullptr;
  603. }
  604. }
  605. void ScriptReporter::ReportScriptError([[maybe_unused]] const AZStd::string& message)
  606. {
  607. AZ_Error("Automation", false, "Script: %s", message.c_str());
  608. }
  609. void ScriptReporter::ReportScriptWarning([[maybe_unused]] const AZStd::string& message)
  610. {
  611. AZ_Warning("Automation", false, "Script: %s", message.c_str());
  612. }
  613. void ScriptReporter::ReportScriptIssue(const AZStd::string& message, TraceLevel traceLevel)
  614. {
  615. switch (traceLevel)
  616. {
  617. case TraceLevel::Error:
  618. ReportScriptError(message);
  619. break;
  620. case TraceLevel::Warning:
  621. ReportScriptWarning(message);
  622. break;
  623. default:
  624. AZ_Assert(false, "Unhandled TraceLevel");
  625. }
  626. }
  627. void ScriptReporter::ReportScreenshotComparisonIssue(const AZStd::string& message, const AZStd::string& expectedImageFilePath, const AZStd::string& actualImageFilePath, TraceLevel traceLevel)
  628. {
  629. AZStd::string fullMessage = AZStd::string::format("%s\n Expected: '%s'\n Actual: '%s'",
  630. message.c_str(),
  631. expectedImageFilePath.c_str(),
  632. actualImageFilePath.c_str());
  633. ReportScriptIssue(fullMessage, traceLevel);
  634. }
  635. bool ScriptReporter::DiffImages(ImageComparisonResult& imageComparisonResult, const AZStd::string& expectedImageFilePath, const AZStd::string& actualImageFilePath, TraceLevel traceLevel)
  636. {
  637. using namespace AZ::Utils;
  638. AZStd::vector<uint8_t> actualImageBuffer;
  639. AZ::RHI::Size actualImageSize;
  640. AZ::RHI::Format actualImageFormat;
  641. if (!LoadPngData(imageComparisonResult, actualImageFilePath, actualImageBuffer, actualImageSize, actualImageFormat, traceLevel))
  642. {
  643. return false;
  644. }
  645. AZStd::vector<uint8_t> expectedImageBuffer;
  646. AZ::RHI::Size expectedImageSize;
  647. AZ::RHI::Format expectedImageFormat;
  648. if (!LoadPngData(imageComparisonResult, expectedImageFilePath, expectedImageBuffer, expectedImageSize, expectedImageFormat, traceLevel))
  649. {
  650. return false;
  651. }
  652. float diffScore = 0.0f;
  653. float filteredDiffScore = 0.0f;
  654. static constexpr float ImperceptibleDiffFilter = 0.01;
  655. ImageDiffResultCode rmsResult = AZ::Utils::CalcImageDiffRms(
  656. actualImageBuffer, actualImageSize, actualImageFormat,
  657. expectedImageBuffer, expectedImageSize, expectedImageFormat,
  658. &diffScore,
  659. &filteredDiffScore,
  660. ImperceptibleDiffFilter);
  661. if (rmsResult != ImageDiffResultCode::Success)
  662. {
  663. if(rmsResult == ImageDiffResultCode::SizeMismatch)
  664. {
  665. ReportScreenshotComparisonIssue(AZStd::string::format("Screenshot check failed. Sizes don't match. Expected %u x %u but was %u x %u.",
  666. expectedImageSize.m_width, expectedImageSize.m_height,
  667. actualImageSize.m_width, actualImageSize.m_height),
  668. expectedImageFilePath,
  669. actualImageFilePath,
  670. traceLevel);
  671. imageComparisonResult.m_resultCode = ImageComparisonResult::ResultCode::WrongSize;
  672. return false;
  673. }
  674. else if (rmsResult == ImageDiffResultCode::FormatMismatch || rmsResult == ImageDiffResultCode::UnsupportedFormat)
  675. {
  676. ReportScreenshotComparisonIssue(AZStd::string::format("Screenshot check failed. Could not compare screenshots due to a format issue."),
  677. expectedImageFilePath,
  678. actualImageFilePath,
  679. traceLevel);
  680. imageComparisonResult.m_resultCode = ImageComparisonResult::ResultCode::WrongFormat;
  681. return false;
  682. }
  683. }
  684. imageComparisonResult.m_standardDiffScore = diffScore;
  685. imageComparisonResult.m_filteredDiffScore = filteredDiffScore;
  686. imageComparisonResult.m_finalDiffScore = diffScore; // Set the final score to the standard score just in case the filtered one is ignored
  687. return true;
  688. }
  689. void ScriptReporter::UpdateAllLocalBaselineImages()
  690. {
  691. int failureCount = 0;
  692. int successCount = 0;
  693. for (ScriptReport& report : m_scriptReports)
  694. {
  695. for (ScreenshotTestInfo& screenshotTest : report.m_screenshotTests)
  696. {
  697. if (UpdateLocalBaselineImage(screenshotTest, false))
  698. {
  699. successCount++;
  700. }
  701. else
  702. {
  703. failureCount++;
  704. }
  705. }
  706. }
  707. ShowUpdateLocalBaselineResult(successCount, failureCount);
  708. }
  709. bool ScriptReporter::UpdateLocalBaselineImage(ScreenshotTestInfo& screenshotTest, bool showResultDialog)
  710. {
  711. const AZStd::string destinationFile = ScreenshotPaths::GetLocalBaseline(screenshotTest.m_screenshotFilePath);
  712. AZStd::string destinationFolder = destinationFile;
  713. AzFramework::StringFunc::Path::StripFullName(destinationFolder);
  714. m_fileIoErrorHandler.BusConnect();
  715. bool failed = false;
  716. if (!AZ::IO::LocalFileIO::GetInstance()->CreatePath(destinationFolder.c_str()))
  717. {
  718. failed = true;
  719. m_fileIoErrorHandler.ReportLatestIOError(AZStd::string::format("Failed to create folder '%s'.", destinationFolder.c_str()));
  720. }
  721. if (!AZ::IO::LocalFileIO::GetInstance()->Copy(screenshotTest.m_screenshotFilePath.c_str(), destinationFile.c_str()))
  722. {
  723. failed = true;
  724. m_fileIoErrorHandler.ReportLatestIOError(AZStd::string::format("Failed to copy '%s' to '%s'.", screenshotTest.m_screenshotFilePath.c_str(), destinationFile.c_str()));
  725. }
  726. m_fileIoErrorHandler.BusDisconnect();
  727. if (!failed)
  728. {
  729. // Since we just replaced the baseline image, we can update this screenshot test result as an exact match.
  730. // This will update the ImGui report dialog by the next frame.
  731. ClearImageComparisonResult(screenshotTest.m_localComparisonResult);
  732. }
  733. if (showResultDialog)
  734. {
  735. int successCount = !failed;
  736. int failureCount = failed;
  737. ShowUpdateLocalBaselineResult(successCount, failureCount);
  738. }
  739. return !failed;
  740. }
  741. bool ScriptReporter::UpdateSourceBaselineImage(ScreenshotTestInfo& screenshotTest, bool showResultDialog)
  742. {
  743. bool success = true;
  744. auto io = AZ::IO::LocalFileIO::GetInstance();
  745. // Get source folder
  746. if (m_officialBaselineSourceFolder.empty())
  747. {
  748. m_officialBaselineSourceFolder = (AZ::IO::FixedMaxPath(AZ::Utils::GetProjectPath()) / "Scripts" / "ExpectedScreenshots").String();
  749. if (!io->Exists(m_officialBaselineSourceFolder.c_str()))
  750. {
  751. AZ_Error("Automation", false, "Could not find source folder '%s'. Copying to source baseline can only be used on dev platforms.", m_officialBaselineSourceFolder.c_str());
  752. m_officialBaselineSourceFolder.clear();
  753. success = false;
  754. }
  755. }
  756. // Get official cache baseline file
  757. const AZStd::string cacheFilePath = ScreenshotPaths::GetOfficialBaseline(screenshotTest.m_screenshotFilePath);
  758. // Divide cache file path into components to we can access the file name and the parent folder
  759. AZStd::fixed_vector<AZ::IO::FixedMaxPathString, 16> reversePathComponents;
  760. auto GatherPathSegments = [&reversePathComponents](AZStd::string_view token)
  761. {
  762. reversePathComponents.emplace_back(token);
  763. };
  764. AzFramework::StringFunc::TokenizeVisitorReverse(cacheFilePath, GatherPathSegments, "/\\");
  765. // Source folder path
  766. // ".../AtomSampleViewer/Scripts/ExpectedScreenshots/" + "MyTestFolder/"
  767. AZStd::string sourceFolderPath = AZStd::string::format("%s\\%s", m_officialBaselineSourceFolder.c_str(), reversePathComponents[1].c_str());
  768. // Source file path
  769. // ".../AtomSampleViewer/Scripts/ExpectedScreenshots/MyTestFolder/" + "MyTest.png"
  770. AZStd::string sourceFilePath = AZStd::string::format("%s\\%s", sourceFolderPath.c_str(), reversePathComponents[0].c_str());
  771. m_fileIoErrorHandler.BusConnect();
  772. // Create parent folder if it doesn't exist
  773. if (success && !io->CreatePath(sourceFolderPath.c_str()))
  774. {
  775. success = false;
  776. m_fileIoErrorHandler.ReportLatestIOError(AZStd::string::format("Failed to create folder '%s'.", sourceFolderPath.c_str()));
  777. }
  778. // Replace source screenshot with new result
  779. if (success && !io->Copy(screenshotTest.m_screenshotFilePath.c_str(), sourceFilePath.c_str()))
  780. {
  781. success = false;
  782. m_fileIoErrorHandler.ReportLatestIOError(AZStd::string::format("Failed to copy '%s' to '%s'.", screenshotTest.m_screenshotFilePath.c_str(), sourceFilePath.c_str()));
  783. }
  784. m_fileIoErrorHandler.BusDisconnect();
  785. if (success)
  786. {
  787. // Since we just replaced the baseline image, we can update this screenshot test result as an exact match.
  788. // This will update the ImGui report dialog by the next frame.
  789. ClearImageComparisonResult(screenshotTest.m_officialComparisonResult);
  790. }
  791. if (showResultDialog)
  792. {
  793. AZStd::string message = "Destination: " + sourceFilePath + "\n";
  794. message += success
  795. ? AZStd::string::format("Copy successful!.\n")
  796. : AZStd::string::format("Copy failed!\n");
  797. m_messageBox.OpenPopupMessage("Update Baseline Image(s) Result", message);
  798. }
  799. return success;
  800. }
  801. void ScriptReporter::ClearImageComparisonResult(ImageComparisonResult& comparisonResult)
  802. {
  803. comparisonResult.m_resultCode = ImageComparisonResult::ResultCode::Pass;
  804. comparisonResult.m_standardDiffScore = 0.0f;
  805. comparisonResult.m_filteredDiffScore = 0.0f;
  806. comparisonResult.m_finalDiffScore = 0.0f;
  807. }
  808. void ScriptReporter::ShowUpdateLocalBaselineResult(int successCount, int failureCount)
  809. {
  810. AZStd::string message;
  811. if (failureCount == 0 && successCount == 0)
  812. {
  813. message = "No screenshots found.";
  814. }
  815. else
  816. {
  817. message = "Destination: " + ScreenshotPaths::GetLocalBaselineFolder(true) + "\n";
  818. if (successCount > 0)
  819. {
  820. message += AZStd::string::format("Successfully copied %d files.\n", successCount);
  821. }
  822. if (failureCount > 0)
  823. {
  824. message += AZStd::string::format("Failed to copy %d files.\n", failureCount);
  825. }
  826. }
  827. m_messageBox.OpenPopupMessage("Update Baseline Image(s) Result", message);
  828. }
  829. void ScriptReporter::CheckLatestScreenshot(const ImageComparisonToleranceLevel* toleranceLevel)
  830. {
  831. AZ_Assert(GetCurrentScriptReport(), "There is no active script");
  832. if (GetCurrentScriptReport() == nullptr || GetCurrentScriptReport()->m_screenshotTests.empty())
  833. {
  834. ReportScriptError("CheckLatestScreenshot() did not find any screenshots to check.");
  835. return;
  836. }
  837. ScreenshotTestInfo& screenshotTestInfo = GetCurrentScriptReport()->m_screenshotTests.back();
  838. if (toleranceLevel == nullptr)
  839. {
  840. screenshotTestInfo.m_officialComparisonResult.m_resultCode = ImageComparisonResult::ResultCode::NullImageComparisonToleranceLevel;
  841. ReportScriptError("Screenshot check failed. No ImageComparisonToleranceLevel provided.");
  842. return;
  843. }
  844. screenshotTestInfo.m_toleranceLevel = *toleranceLevel;
  845. screenshotTestInfo.m_officialBaselineScreenshotFilePath = ScreenshotPaths::GetOfficialBaseline(screenshotTestInfo.m_screenshotFilePath);
  846. if (screenshotTestInfo.m_officialBaselineScreenshotFilePath.empty())
  847. {
  848. ReportScriptError(AZStd::string::format("Screenshot check failed. Could not determine expected screenshot path for '%s'", screenshotTestInfo.m_screenshotFilePath.c_str()));
  849. screenshotTestInfo.m_officialComparisonResult.m_resultCode = ImageComparisonResult::ResultCode::FileNotFound;
  850. }
  851. else
  852. {
  853. bool imagesWereCompared = DiffImages(
  854. screenshotTestInfo.m_officialComparisonResult,
  855. screenshotTestInfo.m_officialBaselineScreenshotFilePath,
  856. screenshotTestInfo.m_screenshotFilePath,
  857. TraceLevel::Error);
  858. if (imagesWereCompared)
  859. {
  860. screenshotTestInfo.m_officialComparisonResult.m_finalDiffScore = toleranceLevel->m_filterImperceptibleDiffs ?
  861. screenshotTestInfo.m_officialComparisonResult.m_filteredDiffScore :
  862. screenshotTestInfo.m_officialComparisonResult.m_standardDiffScore;
  863. if (screenshotTestInfo.m_officialComparisonResult.m_finalDiffScore <= toleranceLevel->m_threshold)
  864. {
  865. screenshotTestInfo.m_officialComparisonResult.m_resultCode = ImageComparisonResult::ResultCode::Pass;
  866. }
  867. else
  868. {
  869. // Be aware there is an automation test script that looks for the "Screenshot check failed. Diff score" string text to report failures.
  870. // If you change this message, be sure to update the associated tests as well located here: "C:/path/to/Lumberyard/AtomSampleViewer/Standalone/PythonTests"
  871. ReportScreenshotComparisonIssue(
  872. AZStd::string::format("Screenshot check failed. Diff score %f exceeds threshold of %f ('%s').",
  873. screenshotTestInfo.m_officialComparisonResult.m_finalDiffScore, toleranceLevel->m_threshold, toleranceLevel->m_name.c_str()),
  874. screenshotTestInfo.m_officialBaselineScreenshotFilePath,
  875. screenshotTestInfo.m_screenshotFilePath,
  876. TraceLevel::Error);
  877. screenshotTestInfo.m_officialComparisonResult.m_resultCode = ImageComparisonResult::ResultCode::ThresholdExceeded;
  878. }
  879. }
  880. }
  881. screenshotTestInfo.m_localBaselineScreenshotFilePath = ScreenshotPaths::GetLocalBaseline(screenshotTestInfo.m_screenshotFilePath);
  882. if (screenshotTestInfo.m_localBaselineScreenshotFilePath.empty())
  883. {
  884. ReportScriptWarning(AZStd::string::format("Screenshot check failed. Could not determine local baseline screenshot path for '%s'", screenshotTestInfo.m_screenshotFilePath.c_str()));
  885. screenshotTestInfo.m_localComparisonResult.m_resultCode = ImageComparisonResult::ResultCode::FileNotFound;
  886. }
  887. else
  888. {
  889. // Local screenshots should be expected match 100% every time, otherwise warnings are reported. This will help developers track and investigate changes,
  890. // for example if they make local changes that impact some unrelated AtomSampleViewer sample in an unexpected way, they will see a warning about this.
  891. bool imagesWereCompared = DiffImages(
  892. screenshotTestInfo.m_localComparisonResult,
  893. screenshotTestInfo.m_localBaselineScreenshotFilePath,
  894. screenshotTestInfo.m_screenshotFilePath,
  895. TraceLevel::Warning);
  896. if (imagesWereCompared)
  897. {
  898. if(screenshotTestInfo.m_localComparisonResult.m_standardDiffScore == 0.0f)
  899. {
  900. screenshotTestInfo.m_localComparisonResult.m_resultCode = ImageComparisonResult::ResultCode::Pass;
  901. }
  902. else
  903. {
  904. ReportScreenshotComparisonIssue(
  905. AZStd::string::format("Screenshot check failed. Screenshot does not match the local baseline; something has changed. Diff score is %f.", screenshotTestInfo.m_localComparisonResult.m_standardDiffScore),
  906. screenshotTestInfo.m_localBaselineScreenshotFilePath,
  907. screenshotTestInfo.m_screenshotFilePath,
  908. TraceLevel::Warning);
  909. screenshotTestInfo.m_localComparisonResult.m_resultCode = ImageComparisonResult::ResultCode::ThresholdExceeded;
  910. }
  911. }
  912. }
  913. }
  914. void ScriptReporter::ExportTestResults()
  915. {
  916. for (const ScriptReport& scriptReport : m_scriptReports)
  917. {
  918. const AZStd::string assertLogLine = AZStd::string::format("Asserts: %u \n", scriptReport.m_assertCount);
  919. const AZStd::string errorsLogLine = AZStd::string::format("Errors: %u \n", scriptReport.m_generalErrorCount);
  920. const AZStd::string warningsLogLine = AZStd::string::format("Warnings: %u \n", scriptReport.m_generalWarningCount);
  921. const AZStd::string screenshotErrorsLogLine = AZStd::string::format("Screenshot errors: %u \n", scriptReport.m_screenshotErrorCount);
  922. const AZStd::string screenshotWarningsLogLine = AZStd::string::format("Screenshot warnings: %u \n", scriptReport.m_screenshotWarningCount);
  923. const AZStd::string failedScreenshotsLogLine = "\nScreenshot test info below.\n";
  924. const auto projectPath = AZ::Utils::GetProjectPath();
  925. AZStd::chrono::system_clock::time_point now = AZStd::chrono::system_clock::now();
  926. float timeFloat = AZStd::chrono::duration<float>(now.time_since_epoch()).count();
  927. AZStd::string timeString = AZStd::string::format("%.4f", timeFloat);
  928. AZStd::string exportFileName = AZStd::string::format("exportedTestResults_%s.txt", timeString.c_str());
  929. AZStd::string exportTestResultsFolder;
  930. AzFramework::StringFunc::Path::Join(projectPath.c_str(), "TestResults/", exportTestResultsFolder);
  931. auto io = AZ::IO::LocalFileIO::GetInstance();
  932. io->CreatePath(exportTestResultsFolder.c_str());
  933. AZStd::string exportFile;
  934. AzFramework::StringFunc::Path::Join(exportTestResultsFolder.c_str(), exportFileName.c_str(), exportFile);
  935. AZ::IO::HandleType logHandle;
  936. if (io->Open(exportFile.c_str(), AZ::IO::OpenMode::ModeWrite, logHandle))
  937. {
  938. io->Write(logHandle, assertLogLine.c_str(), assertLogLine.size());
  939. io->Write(logHandle, errorsLogLine.c_str(), errorsLogLine.size());
  940. io->Write(logHandle, warningsLogLine.c_str(), warningsLogLine.size());
  941. io->Write(logHandle, screenshotErrorsLogLine.c_str(), screenshotErrorsLogLine.size());
  942. io->Write(logHandle, screenshotWarningsLogLine.c_str(), screenshotWarningsLogLine.size());
  943. io->Write(logHandle, failedScreenshotsLogLine.c_str(), failedScreenshotsLogLine.size());
  944. for (const ScreenshotTestInfo& screenshotTest : scriptReport.m_screenshotTests)
  945. {
  946. const AZStd::string toleranceLevelLogLine = AZStd::string::format("Tolerance level: %s \n", screenshotTest.m_toleranceLevel.ToString().c_str());
  947. const AZStd::string officialComparisonLogLine = AZStd::string::format("Image comparison result: %s \n", screenshotTest.m_officialComparisonResult.GetSummaryString().c_str());
  948. io->Write(logHandle, toleranceLevelLogLine.c_str(), toleranceLevelLogLine.size());
  949. io->Write(logHandle, officialComparisonLogLine.c_str(), officialComparisonLogLine.size());
  950. }
  951. io->Close(logHandle);
  952. }
  953. m_messageBox.OpenPopupMessage("Exported test results", "Results exported to " + exportFile);
  954. }
  955. }
  956. } // namespace AtomSampleViewer