2
0

ScriptReporter.cpp 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148
  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("@projectroot@/" + 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. ImGui::Text("Exported test results: %s", m_exportedTestResultsPath.c_str());
  365. resetTextHighlight();
  366. if (ImGui::Button("Update All Local Baseline Images"))
  367. {
  368. m_messageBox.OpenPopupConfirmation(
  369. "Update All Local Baseline Images",
  370. "This will replace all local baseline images \n"
  371. "with the images captured during this test run. \n"
  372. "Are you sure?",
  373. [this]() {
  374. UpdateAllLocalBaselineImages();
  375. });
  376. }
  377. if (ImGui::Button("Export Test Results"))
  378. {
  379. m_messageBox.OpenPopupConfirmation(
  380. "Export Test Results",
  381. "All test results will be exported \n"
  382. "Proceed?",
  383. [this]() {
  384. ExportTestResults();
  385. });
  386. }
  387. int displayOption = m_displayOption;
  388. ImGui::Combo("Display", &displayOption, DiplayOptions, AZ_ARRAY_SIZE(DiplayOptions));
  389. m_displayOption = (DisplayOption)displayOption;
  390. ImGui::Checkbox("Force Show 'Update' Buttons", &m_forceShowUpdateButtons);
  391. bool showWarnings = (m_displayOption == DisplayOption::AllResults) || (m_displayOption == DisplayOption::WarningsAndErrors);
  392. bool showAll = (m_displayOption == DisplayOption::AllResults);
  393. ImGui::Separator();
  394. const ImGuiTreeNodeFlags FlagDefaultOpen = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick | ImGuiTreeNodeFlags_DefaultOpen;
  395. const ImGuiTreeNodeFlags FlagDefaultClosed = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick;
  396. for (ScriptReport& scriptReport : m_scriptReports)
  397. {
  398. const bool scriptPassed = scriptReport.m_assertCount == 0 && scriptReport.m_generalErrorCount == 0 && scriptReport.m_screenshotErrorCount == 0;
  399. const bool scriptHasWarnings = scriptReport.m_generalWarningCount > 0 || scriptReport.m_screenshotWarningCount > 0;
  400. // Skip if tests passed without warnings and we don't want to show successes
  401. bool skipReport = (scriptPassed && !scriptHasWarnings && !showAll);
  402. // Skip if we only have warnings only and we don't want to show warnings
  403. skipReport = skipReport || (scriptPassed && scriptHasWarnings && !showWarnings);
  404. if (skipReport)
  405. {
  406. continue;
  407. }
  408. ImGuiTreeNodeFlags scriptNodeFlag = scriptPassed ? FlagDefaultClosed : FlagDefaultOpen;
  409. AZStd::string header = AZStd::string::format("%s %s",
  410. scriptPassed ? "PASSED" : "FAILED",
  411. scriptReport.m_scriptAssetPath.c_str()
  412. );
  413. highlightTextFailedOrWarning(!scriptPassed, scriptHasWarnings);
  414. if (ImGui::TreeNodeEx(&scriptReport, scriptNodeFlag, "%s", header.c_str()))
  415. {
  416. resetTextHighlight();
  417. // Number of Asserts
  418. highlightTextIf(scriptReport.m_assertCount > 0, HighlightFailed);
  419. if (showAll || scriptReport.m_assertCount > 0)
  420. {
  421. ImGui::Text("Asserts: %u %s", scriptReport.m_assertCount, seeConsole(scriptReport.m_assertCount, "Trace::Assert").c_str());
  422. }
  423. // Number of Errors
  424. highlightTextIf(scriptReport.m_generalErrorCount > 0, HighlightFailed);
  425. if (showAll || scriptReport.m_generalErrorCount > 0)
  426. {
  427. ImGui::Text("Errors: %u %s", scriptReport.m_generalErrorCount, seeConsole(scriptReport.m_generalErrorCount, "Trace::Error").c_str());
  428. }
  429. // Number of Warnings
  430. highlightTextIf(scriptReport.m_generalWarningCount > 0, HighlightWarning);
  431. if (showAll || (showWarnings && scriptReport.m_generalWarningCount > 0))
  432. {
  433. ImGui::Text("Warnings: %u %s", scriptReport.m_generalWarningCount, seeConsole(scriptReport.m_generalWarningCount, "Trace::Warning").c_str());
  434. }
  435. resetTextHighlight();
  436. // Number of screenshots
  437. if (showAll || scriptReport.m_screenshotErrorCount > 0 || (showWarnings && scriptReport.m_screenshotWarningCount > 0))
  438. {
  439. ImGui::Text("Screenshot Test Count: %zu", scriptReport.m_screenshotTests.size());
  440. }
  441. // Number of screenshot failures
  442. highlightTextIf(scriptReport.m_screenshotErrorCount > 0, HighlightFailed);
  443. if (showAll || scriptReport.m_screenshotErrorCount > 0)
  444. {
  445. ImGui::Text("Screenshot Tests Failed: %u %s", scriptReport.m_screenshotErrorCount, seeBelow(scriptReport.m_screenshotErrorCount).c_str());
  446. }
  447. // Number of screenshot warnings
  448. highlightTextIf(scriptReport.m_screenshotWarningCount > 0, HighlightWarning);
  449. if (showAll || (showWarnings && scriptReport.m_screenshotWarningCount > 0))
  450. {
  451. ImGui::Text("Screenshot Warnings: %u %s", scriptReport.m_screenshotWarningCount, seeBelow(scriptReport.m_screenshotWarningCount).c_str());
  452. }
  453. resetTextHighlight();
  454. for (ScreenshotTestInfo& screenshotResult : scriptReport.m_screenshotTests)
  455. {
  456. const bool screenshotPassed = screenshotResult.m_officialComparisonResult.m_resultCode == ImageComparisonResult::ResultCode::Pass;
  457. const bool localBaselineWarning = screenshotResult.m_localComparisonResult.m_resultCode != ImageComparisonResult::ResultCode::Pass;
  458. // Skip if tests passed without warnings and we don't want to show successes
  459. bool skipScreenshot = (screenshotPassed && !localBaselineWarning && !showAll);
  460. // Skip if we only have warnings only and we don't want to show warnings
  461. skipScreenshot = skipScreenshot || (screenshotPassed && localBaselineWarning && !showWarnings);
  462. if (skipScreenshot)
  463. {
  464. continue;
  465. }
  466. AZStd::string fileName;
  467. AzFramework::StringFunc::Path::GetFullFileName(screenshotResult.m_screenshotFilePath.c_str(), fileName);
  468. AZStd::string headerSummary;
  469. if (!screenshotPassed)
  470. {
  471. headerSummary = "(" + screenshotResult.m_officialComparisonResult.GetSummaryString() + ") ";
  472. }
  473. if (localBaselineWarning)
  474. {
  475. headerSummary += "(Local Baseline Warning)";
  476. }
  477. ImGuiTreeNodeFlags screenshotNodeFlag = FlagDefaultClosed;
  478. AZStd::string screenshotHeader = AZStd::string::format("%s %s %s", screenshotPassed ? "PASSED" : "FAILED", fileName.c_str(), headerSummary.c_str());
  479. highlightTextFailedOrWarning(!screenshotPassed, localBaselineWarning);
  480. if (ImGui::TreeNodeEx(&screenshotResult, screenshotNodeFlag, "%s", screenshotHeader.c_str()))
  481. {
  482. resetTextHighlight();
  483. ImGui::Text("Screenshot: %s", screenshotResult.m_screenshotFilePath.c_str());
  484. ImGui::Spacing();
  485. highlightTextIf(!screenshotPassed, HighlightFailed);
  486. ImGui::Text("Official Baseline: %s", screenshotResult.m_officialBaselineScreenshotFilePath.c_str());
  487. // Official Baseline Result
  488. ImGui::Indent();
  489. {
  490. ImGui::Text("%s", screenshotResult.m_officialComparisonResult.GetSummaryString().c_str());
  491. if (screenshotResult.m_officialComparisonResult.m_resultCode == ImageComparisonResult::ResultCode::ThresholdExceeded ||
  492. screenshotResult.m_officialComparisonResult.m_resultCode == ImageComparisonResult::ResultCode::Pass)
  493. {
  494. ImGui::Text("Used Tolerance: %s", screenshotResult.m_toleranceLevel.ToString().c_str());
  495. const ImageComparisonToleranceLevel* suggestedTolerance = ScriptReporter::FindBestToleranceLevel(
  496. screenshotResult.m_officialComparisonResult.m_finalDiffScore,
  497. screenshotResult.m_toleranceLevel.m_filterImperceptibleDiffs);
  498. if(suggestedTolerance)
  499. {
  500. ImGui::Text("Suggested Tolerance: %s", suggestedTolerance->ToString().c_str());
  501. }
  502. if (screenshotResult.m_toleranceLevel.m_filterImperceptibleDiffs)
  503. {
  504. // This gives an idea of what the tolerance level would be if the imperceptible diffs were not filtered out.
  505. const ImageComparisonToleranceLevel* unfilteredTolerance = ScriptReporter::FindBestToleranceLevel(
  506. screenshotResult.m_officialComparisonResult.m_standardDiffScore, false);
  507. ImGui::Text("(Unfiltered Diff Score: %f%s)",
  508. screenshotResult.m_officialComparisonResult.m_standardDiffScore,
  509. unfilteredTolerance ? AZStd::string::format(" ~ '%s'", unfilteredTolerance->m_name.c_str()).c_str() : "");
  510. }
  511. }
  512. resetTextHighlight();
  513. ImGui::PushID("Official");
  514. ShowDiffButton("View Diff", screenshotResult.m_officialBaselineScreenshotFilePath, screenshotResult.m_screenshotFilePath);
  515. ImGui::PopID();
  516. if ((!screenshotPassed || m_forceShowUpdateButtons) && ImGui::Button("Update##Official"))
  517. {
  518. if (screenshotResult.m_localComparisonResult.m_resultCode == ImageComparisonResult::ResultCode::FileNotFound)
  519. {
  520. UpdateSourceBaselineImage(screenshotResult, true);
  521. }
  522. else
  523. {
  524. m_messageBox.OpenPopupConfirmation(
  525. "Update Official Baseline Image",
  526. "This will replace the official baseline image \n"
  527. "with the image captured during this test run. \n"
  528. "Are you sure?",
  529. // It's important to bind screenshotResult by reference because UpdateOfficialBaselineImage will update it
  530. [this, &screenshotResult]() {
  531. UpdateSourceBaselineImage(screenshotResult, true);
  532. });
  533. }
  534. }
  535. }
  536. ImGui::Unindent();
  537. ImGui::Spacing();
  538. highlightTextIf(localBaselineWarning, HighlightWarning);
  539. ImGui::Text("Local Baseline: %s", screenshotResult.m_localBaselineScreenshotFilePath.c_str());
  540. // Local Baseline Result
  541. ImGui::Indent();
  542. {
  543. ImGui::Text("%s", screenshotResult.m_localComparisonResult.GetSummaryString().c_str());
  544. resetTextHighlight();
  545. ImGui::PushID("Local");
  546. ShowDiffButton("View Diff", screenshotResult.m_localBaselineScreenshotFilePath, screenshotResult.m_screenshotFilePath);
  547. ImGui::PopID();
  548. if ((localBaselineWarning || m_forceShowUpdateButtons) && ImGui::Button("Update##Local"))
  549. {
  550. if (screenshotResult.m_localComparisonResult.m_resultCode == ImageComparisonResult::ResultCode::FileNotFound)
  551. {
  552. UpdateLocalBaselineImage(screenshotResult, true);
  553. }
  554. else
  555. {
  556. m_messageBox.OpenPopupConfirmation(
  557. "Update Local Baseline Image",
  558. "This will replace the local baseline image \n"
  559. "with the image captured during this test run. \n"
  560. "Are you sure?",
  561. // It's important to bind screenshotResult by reference because UpdateLocalBaselineImage will update it
  562. [this, &screenshotResult]() {
  563. UpdateLocalBaselineImage(screenshotResult, true);
  564. });
  565. }
  566. }
  567. }
  568. ImGui::Unindent();
  569. ImGui::Spacing();
  570. resetTextHighlight();
  571. ImGui::TreePop();
  572. }
  573. }
  574. ImGui::TreePop();
  575. }
  576. resetTextHighlight();
  577. }
  578. resetTextHighlight();
  579. // Repeat the m_invalidationMessage at the bottom as well, to make sure the user doesn't miss it.
  580. if (!m_invalidationMessage.empty())
  581. {
  582. ImGui::Separator();
  583. ImGui::PushStyleColor(ImGuiCol_Text, HighlightFailed);
  584. ImGui::Text("(%s)", m_invalidationMessage.c_str());
  585. ImGui::PopStyleColor();
  586. }
  587. }
  588. m_messageBox.TickPopup();
  589. ImGui::End();
  590. }
  591. void ScriptReporter::OpenReportDialog()
  592. {
  593. m_showReportDialog = true;
  594. }
  595. ScriptReporter::ScriptReport* ScriptReporter::GetCurrentScriptReport()
  596. {
  597. if (!m_currentScriptIndexStack.empty())
  598. {
  599. return &m_scriptReports[m_currentScriptIndexStack.back()];
  600. }
  601. else
  602. {
  603. return nullptr;
  604. }
  605. }
  606. void ScriptReporter::ReportScriptError([[maybe_unused]] const AZStd::string& message)
  607. {
  608. AZ_Error("Automation", false, "Script: %s", message.c_str());
  609. }
  610. void ScriptReporter::ReportScriptWarning([[maybe_unused]] const AZStd::string& message)
  611. {
  612. AZ_Warning("Automation", false, "Script: %s", message.c_str());
  613. }
  614. void ScriptReporter::ReportScriptIssue(const AZStd::string& message, TraceLevel traceLevel)
  615. {
  616. switch (traceLevel)
  617. {
  618. case TraceLevel::Error:
  619. ReportScriptError(message);
  620. break;
  621. case TraceLevel::Warning:
  622. ReportScriptWarning(message);
  623. break;
  624. default:
  625. AZ_Assert(false, "Unhandled TraceLevel");
  626. }
  627. }
  628. void ScriptReporter::ReportScreenshotComparisonIssue(const AZStd::string& message, const AZStd::string& expectedImageFilePath, const AZStd::string& actualImageFilePath, TraceLevel traceLevel)
  629. {
  630. AZStd::string fullMessage = AZStd::string::format("%s\n Expected: '%s'\n Actual: '%s'",
  631. message.c_str(),
  632. expectedImageFilePath.c_str(),
  633. actualImageFilePath.c_str());
  634. ReportScriptIssue(fullMessage, traceLevel);
  635. }
  636. bool ScriptReporter::DiffImages(ImageComparisonResult& imageComparisonResult, const AZStd::string& expectedImageFilePath, const AZStd::string& actualImageFilePath, TraceLevel traceLevel)
  637. {
  638. using namespace AZ::Utils;
  639. AZStd::vector<uint8_t> actualImageBuffer;
  640. AZ::RHI::Size actualImageSize;
  641. AZ::RHI::Format actualImageFormat;
  642. if (!LoadPngData(imageComparisonResult, actualImageFilePath, actualImageBuffer, actualImageSize, actualImageFormat, traceLevel))
  643. {
  644. return false;
  645. }
  646. AZStd::vector<uint8_t> expectedImageBuffer;
  647. AZ::RHI::Size expectedImageSize;
  648. AZ::RHI::Format expectedImageFormat;
  649. if (!LoadPngData(imageComparisonResult, expectedImageFilePath, expectedImageBuffer, expectedImageSize, expectedImageFormat, traceLevel))
  650. {
  651. return false;
  652. }
  653. float diffScore = 0.0f;
  654. float filteredDiffScore = 0.0f;
  655. static constexpr float ImperceptibleDiffFilter = 0.01;
  656. ImageDiffResultCode rmsResult = AZ::Utils::CalcImageDiffRms(
  657. actualImageBuffer, actualImageSize, actualImageFormat,
  658. expectedImageBuffer, expectedImageSize, expectedImageFormat,
  659. &diffScore,
  660. &filteredDiffScore,
  661. ImperceptibleDiffFilter);
  662. if (rmsResult != ImageDiffResultCode::Success)
  663. {
  664. if(rmsResult == ImageDiffResultCode::SizeMismatch)
  665. {
  666. ReportScreenshotComparisonIssue(AZStd::string::format("Screenshot check failed. Sizes don't match. Expected %u x %u but was %u x %u.",
  667. expectedImageSize.m_width, expectedImageSize.m_height,
  668. actualImageSize.m_width, actualImageSize.m_height),
  669. expectedImageFilePath,
  670. actualImageFilePath,
  671. traceLevel);
  672. imageComparisonResult.m_resultCode = ImageComparisonResult::ResultCode::WrongSize;
  673. return false;
  674. }
  675. else if (rmsResult == ImageDiffResultCode::FormatMismatch || rmsResult == ImageDiffResultCode::UnsupportedFormat)
  676. {
  677. ReportScreenshotComparisonIssue(AZStd::string::format("Screenshot check failed. Could not compare screenshots due to a format issue."),
  678. expectedImageFilePath,
  679. actualImageFilePath,
  680. traceLevel);
  681. imageComparisonResult.m_resultCode = ImageComparisonResult::ResultCode::WrongFormat;
  682. return false;
  683. }
  684. }
  685. imageComparisonResult.m_standardDiffScore = diffScore;
  686. imageComparisonResult.m_filteredDiffScore = filteredDiffScore;
  687. imageComparisonResult.m_finalDiffScore = diffScore; // Set the final score to the standard score just in case the filtered one is ignored
  688. return true;
  689. }
  690. void ScriptReporter::UpdateAllLocalBaselineImages()
  691. {
  692. int failureCount = 0;
  693. int successCount = 0;
  694. for (ScriptReport& report : m_scriptReports)
  695. {
  696. for (ScreenshotTestInfo& screenshotTest : report.m_screenshotTests)
  697. {
  698. if (UpdateLocalBaselineImage(screenshotTest, false))
  699. {
  700. successCount++;
  701. }
  702. else
  703. {
  704. failureCount++;
  705. }
  706. }
  707. }
  708. ShowUpdateLocalBaselineResult(successCount, failureCount);
  709. }
  710. bool ScriptReporter::UpdateLocalBaselineImage(ScreenshotTestInfo& screenshotTest, bool showResultDialog)
  711. {
  712. const AZStd::string destinationFile = ScreenshotPaths::GetLocalBaseline(screenshotTest.m_screenshotFilePath);
  713. AZStd::string destinationFolder = destinationFile;
  714. AzFramework::StringFunc::Path::StripFullName(destinationFolder);
  715. bool failed = false;
  716. if (!AZ::IO::LocalFileIO::GetInstance()->CreatePath(destinationFolder.c_str()))
  717. {
  718. failed = true;
  719. AZ_Error("ScriptReporter", false, "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. AZ_Error("ScriptReporter", false, "Failed to copy '%s' to '%s'.", screenshotTest.m_screenshotFilePath.c_str(), destinationFile.c_str());
  725. }
  726. if (!failed)
  727. {
  728. // Since we just replaced the baseline image, we can update this screenshot test result as an exact match.
  729. // This will update the ImGui report dialog by the next frame.
  730. ClearImageComparisonResult(screenshotTest.m_localComparisonResult);
  731. }
  732. if (showResultDialog)
  733. {
  734. int successCount = !failed;
  735. int failureCount = failed;
  736. ShowUpdateLocalBaselineResult(successCount, failureCount);
  737. }
  738. return !failed;
  739. }
  740. bool ScriptReporter::UpdateSourceBaselineImage(ScreenshotTestInfo& screenshotTest, bool showResultDialog)
  741. {
  742. bool success = true;
  743. auto io = AZ::IO::LocalFileIO::GetInstance();
  744. // Get source folder
  745. if (m_officialBaselineSourceFolder.empty())
  746. {
  747. m_officialBaselineSourceFolder = (AZ::IO::FixedMaxPath(AZ::Utils::GetProjectPath()) / "Scripts" / "ExpectedScreenshots").String();
  748. if (!io->Exists(m_officialBaselineSourceFolder.c_str()))
  749. {
  750. 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());
  751. m_officialBaselineSourceFolder.clear();
  752. success = false;
  753. }
  754. }
  755. // Get official cache baseline file
  756. const AZStd::string cacheFilePath = ScreenshotPaths::GetOfficialBaseline(screenshotTest.m_screenshotFilePath);
  757. // Divide cache file path into components to we can access the file name and the parent folder
  758. AZStd::fixed_vector<AZ::IO::FixedMaxPathString, 16> reversePathComponents;
  759. auto GatherPathSegments = [&reversePathComponents](AZStd::string_view token)
  760. {
  761. reversePathComponents.emplace_back(token);
  762. };
  763. AzFramework::StringFunc::TokenizeVisitorReverse(cacheFilePath, GatherPathSegments, "/\\");
  764. // Source folder path
  765. // ".../AtomSampleViewer/Scripts/ExpectedScreenshots/" + "MyTestFolder/"
  766. AZStd::string sourceFolderPath = AZStd::string::format("%s\\%s", m_officialBaselineSourceFolder.c_str(), reversePathComponents[1].c_str());
  767. // Source file path
  768. // ".../AtomSampleViewer/Scripts/ExpectedScreenshots/MyTestFolder/" + "MyTest.png"
  769. AZStd::string sourceFilePath = AZStd::string::format("%s\\%s", sourceFolderPath.c_str(), reversePathComponents[0].c_str());
  770. // Create parent folder if it doesn't exist
  771. if (success && !io->CreatePath(sourceFolderPath.c_str()))
  772. {
  773. success = false;
  774. AZ_Error("ScriptReporter", false, "Failed to create folder '%s'.", sourceFolderPath.c_str());
  775. }
  776. // Replace source screenshot with new result
  777. if (success && !io->Copy(screenshotTest.m_screenshotFilePath.c_str(), sourceFilePath.c_str()))
  778. {
  779. success = false;
  780. AZ_Error("ScriptReporter", false, "Failed to copy '%s' to '%s'.", screenshotTest.m_screenshotFilePath.c_str(), sourceFilePath.c_str());
  781. }
  782. if (success)
  783. {
  784. // Since we just replaced the baseline image, we can update this screenshot test result as an exact match.
  785. // This will update the ImGui report dialog by the next frame.
  786. ClearImageComparisonResult(screenshotTest.m_officialComparisonResult);
  787. }
  788. if (showResultDialog)
  789. {
  790. AZStd::string message = "Destination: " + sourceFilePath + "\n";
  791. message += success
  792. ? AZStd::string::format("Copy successful!.\n")
  793. : AZStd::string::format("Copy failed!\n");
  794. m_messageBox.OpenPopupMessage("Update Baseline Image(s) Result", message);
  795. }
  796. return success;
  797. }
  798. void ScriptReporter::ClearImageComparisonResult(ImageComparisonResult& comparisonResult)
  799. {
  800. comparisonResult.m_resultCode = ImageComparisonResult::ResultCode::Pass;
  801. comparisonResult.m_standardDiffScore = 0.0f;
  802. comparisonResult.m_filteredDiffScore = 0.0f;
  803. comparisonResult.m_finalDiffScore = 0.0f;
  804. }
  805. void ScriptReporter::ShowUpdateLocalBaselineResult(int successCount, int failureCount)
  806. {
  807. AZStd::string message;
  808. if (failureCount == 0 && successCount == 0)
  809. {
  810. message = "No screenshots found.";
  811. }
  812. else
  813. {
  814. message = "Destination: " + ScreenshotPaths::GetLocalBaselineFolder(true) + "\n";
  815. if (successCount > 0)
  816. {
  817. message += AZStd::string::format("Successfully copied %d files.\n", successCount);
  818. }
  819. if (failureCount > 0)
  820. {
  821. message += AZStd::string::format("Failed to copy %d files.\n", failureCount);
  822. }
  823. }
  824. m_messageBox.OpenPopupMessage("Update Baseline Image(s) Result", message);
  825. }
  826. void ScriptReporter::CheckLatestScreenshot(const ImageComparisonToleranceLevel* toleranceLevel)
  827. {
  828. AZ_Assert(GetCurrentScriptReport(), "There is no active script");
  829. if (GetCurrentScriptReport() == nullptr || GetCurrentScriptReport()->m_screenshotTests.empty())
  830. {
  831. ReportScriptError("CheckLatestScreenshot() did not find any screenshots to check.");
  832. return;
  833. }
  834. ScreenshotTestInfo& screenshotTestInfo = GetCurrentScriptReport()->m_screenshotTests.back();
  835. if (toleranceLevel == nullptr)
  836. {
  837. screenshotTestInfo.m_officialComparisonResult.m_resultCode = ImageComparisonResult::ResultCode::NullImageComparisonToleranceLevel;
  838. ReportScriptError("Screenshot check failed. No ImageComparisonToleranceLevel provided.");
  839. return;
  840. }
  841. screenshotTestInfo.m_toleranceLevel = *toleranceLevel;
  842. screenshotTestInfo.m_officialBaselineScreenshotFilePath = ScreenshotPaths::GetOfficialBaseline(screenshotTestInfo.m_screenshotFilePath);
  843. if (screenshotTestInfo.m_officialBaselineScreenshotFilePath.empty())
  844. {
  845. ReportScriptError(AZStd::string::format("Screenshot check failed. Could not determine expected screenshot path for '%s'", screenshotTestInfo.m_screenshotFilePath.c_str()));
  846. screenshotTestInfo.m_officialComparisonResult.m_resultCode = ImageComparisonResult::ResultCode::FileNotFound;
  847. }
  848. else
  849. {
  850. bool imagesWereCompared = DiffImages(
  851. screenshotTestInfo.m_officialComparisonResult,
  852. screenshotTestInfo.m_officialBaselineScreenshotFilePath,
  853. screenshotTestInfo.m_screenshotFilePath,
  854. TraceLevel::Error);
  855. if (imagesWereCompared)
  856. {
  857. screenshotTestInfo.m_officialComparisonResult.m_finalDiffScore = toleranceLevel->m_filterImperceptibleDiffs ?
  858. screenshotTestInfo.m_officialComparisonResult.m_filteredDiffScore :
  859. screenshotTestInfo.m_officialComparisonResult.m_standardDiffScore;
  860. if (screenshotTestInfo.m_officialComparisonResult.m_finalDiffScore <= toleranceLevel->m_threshold)
  861. {
  862. screenshotTestInfo.m_officialComparisonResult.m_resultCode = ImageComparisonResult::ResultCode::Pass;
  863. }
  864. else
  865. {
  866. // Be aware there is an automation test script that looks for the "Screenshot check failed. Diff score" string text to report failures.
  867. // If you change this message, be sure to update the associated tests as well located here: "C:/path/to/Lumberyard/AtomSampleViewer/Standalone/PythonTests"
  868. ReportScreenshotComparisonIssue(
  869. AZStd::string::format("Screenshot check failed. Diff score %f exceeds threshold of %f ('%s').",
  870. screenshotTestInfo.m_officialComparisonResult.m_finalDiffScore, toleranceLevel->m_threshold, toleranceLevel->m_name.c_str()),
  871. screenshotTestInfo.m_officialBaselineScreenshotFilePath,
  872. screenshotTestInfo.m_screenshotFilePath,
  873. TraceLevel::Error);
  874. screenshotTestInfo.m_officialComparisonResult.m_resultCode = ImageComparisonResult::ResultCode::ThresholdExceeded;
  875. }
  876. }
  877. }
  878. screenshotTestInfo.m_localBaselineScreenshotFilePath = ScreenshotPaths::GetLocalBaseline(screenshotTestInfo.m_screenshotFilePath);
  879. if (screenshotTestInfo.m_localBaselineScreenshotFilePath.empty())
  880. {
  881. ReportScriptWarning(AZStd::string::format("Screenshot check failed. Could not determine local baseline screenshot path for '%s'", screenshotTestInfo.m_screenshotFilePath.c_str()));
  882. screenshotTestInfo.m_localComparisonResult.m_resultCode = ImageComparisonResult::ResultCode::FileNotFound;
  883. }
  884. else
  885. {
  886. // Local screenshots should be expected match 100% every time, otherwise warnings are reported. This will help developers track and investigate changes,
  887. // for example if they make local changes that impact some unrelated AtomSampleViewer sample in an unexpected way, they will see a warning about this.
  888. bool imagesWereCompared = DiffImages(
  889. screenshotTestInfo.m_localComparisonResult,
  890. screenshotTestInfo.m_localBaselineScreenshotFilePath,
  891. screenshotTestInfo.m_screenshotFilePath,
  892. TraceLevel::Warning);
  893. if (imagesWereCompared)
  894. {
  895. if(screenshotTestInfo.m_localComparisonResult.m_standardDiffScore == 0.0f)
  896. {
  897. screenshotTestInfo.m_localComparisonResult.m_resultCode = ImageComparisonResult::ResultCode::Pass;
  898. }
  899. else
  900. {
  901. ReportScreenshotComparisonIssue(
  902. 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),
  903. screenshotTestInfo.m_localBaselineScreenshotFilePath,
  904. screenshotTestInfo.m_screenshotFilePath,
  905. TraceLevel::Warning);
  906. screenshotTestInfo.m_localComparisonResult.m_resultCode = ImageComparisonResult::ResultCode::ThresholdExceeded;
  907. }
  908. }
  909. }
  910. }
  911. void ScriptReporter::ExportTestResults()
  912. {
  913. m_exportedTestResultsPath = GenerateAndCreateExportedTestResultsPath();
  914. for (const ScriptReport& scriptReport : m_scriptReports)
  915. {
  916. const AZStd::string assertLogLine = AZStd::string::format("Asserts: %u \n", scriptReport.m_assertCount);
  917. const AZStd::string errorsLogLine = AZStd::string::format("Errors: %u \n", scriptReport.m_generalErrorCount);
  918. const AZStd::string warningsLogLine = AZStd::string::format("Warnings: %u \n", scriptReport.m_generalWarningCount);
  919. const AZStd::string screenshotErrorsLogLine = AZStd::string::format("Screenshot errors: %u \n", scriptReport.m_screenshotErrorCount);
  920. const AZStd::string screenshotWarningsLogLine = AZStd::string::format("Screenshot warnings: %u \n", scriptReport.m_screenshotWarningCount);
  921. const AZStd::string failedScreenshotsLogLine = "\nScreenshot test info below.\n";
  922. AZ::IO::HandleType logHandle;
  923. auto io = AZ::IO::LocalFileIO::GetInstance();
  924. if (io->Open(m_exportedTestResultsPath.c_str(), AZ::IO::OpenMode::ModeWrite, logHandle))
  925. {
  926. io->Write(logHandle, assertLogLine.c_str(), assertLogLine.size());
  927. io->Write(logHandle, errorsLogLine.c_str(), errorsLogLine.size());
  928. io->Write(logHandle, warningsLogLine.c_str(), warningsLogLine.size());
  929. io->Write(logHandle, screenshotErrorsLogLine.c_str(), screenshotErrorsLogLine.size());
  930. io->Write(logHandle, screenshotWarningsLogLine.c_str(), screenshotWarningsLogLine.size());
  931. io->Write(logHandle, failedScreenshotsLogLine.c_str(), failedScreenshotsLogLine.size());
  932. for (const ScreenshotTestInfo& screenshotTest : scriptReport.m_screenshotTests)
  933. {
  934. const AZStd::string screenshotPath = AZStd::string::format("Test screenshot path: %s \n", screenshotTest.m_screenshotFilePath.c_str());
  935. const AZStd::string officialBaselineScreenshotPath = AZStd::string::format("Official baseline screenshot path: %s \n", screenshotTest.m_officialBaselineScreenshotFilePath.c_str());
  936. const AZStd::string toleranceLevelLogLine = AZStd::string::format("Tolerance level: %s \n", screenshotTest.m_toleranceLevel.ToString().c_str());
  937. const AZStd::string officialComparisonLogLine = AZStd::string::format("Image comparison result: %s \n", screenshotTest.m_officialComparisonResult.GetSummaryString().c_str());
  938. io->Write(logHandle, toleranceLevelLogLine.c_str(), toleranceLevelLogLine.size());
  939. io->Write(logHandle, officialComparisonLogLine.c_str(), officialComparisonLogLine.size());
  940. }
  941. io->Close(logHandle);
  942. }
  943. m_messageBox.OpenPopupMessage("Exported test results", AZStd::string::format("Results exported to %s", m_exportedTestResultsPath.c_str()));
  944. AZ_Printf("Test results exported to %s \n", m_exportedTestResultsPath.c_str());
  945. }
  946. }
  947. AZStd::string ScriptReporter::GenerateAndCreateExportedTestResultsPath() const
  948. {
  949. // Setup our variables for the exported test results path and .txt file.
  950. const auto projectPath = AZ::Utils::GetProjectPath();
  951. const AZStd::chrono::system_clock::time_point now = AZStd::chrono::system_clock::now();
  952. const float timeFloat = AZStd::chrono::duration<float>(now.time_since_epoch()).count();
  953. const AZStd::string timeString = AZStd::string::format("%.4f", timeFloat);
  954. const AZStd::string exportFileName = AZStd::string::format("exportedTestResults_%s.txt", timeString.c_str());
  955. AZStd::string exportTestResultsFolder;
  956. AzFramework::StringFunc::Path::Join(projectPath.c_str(), "TestResults/", exportTestResultsFolder);
  957. // Create the exported test results path & return .txt file path.
  958. auto io = AZ::IO::LocalFileIO::GetInstance();
  959. io->CreatePath(exportTestResultsFolder.c_str());
  960. AZStd::string exportFile;
  961. AzFramework::StringFunc::Path::Join(exportTestResultsFolder.c_str(), exportFileName.c_str(), exportFile);
  962. return exportFile;
  963. }
  964. } // namespace AtomSampleViewer