ScriptReporter.cpp 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156
  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. m_fileIoErrorHandler.BusConnect();
  716. bool failed = false;
  717. if (!AZ::IO::LocalFileIO::GetInstance()->CreatePath(destinationFolder.c_str()))
  718. {
  719. failed = true;
  720. m_fileIoErrorHandler.ReportLatestIOError(AZStd::string::format("Failed to create folder '%s'.", destinationFolder.c_str()));
  721. }
  722. if (!AZ::IO::LocalFileIO::GetInstance()->Copy(screenshotTest.m_screenshotFilePath.c_str(), destinationFile.c_str()))
  723. {
  724. failed = true;
  725. m_fileIoErrorHandler.ReportLatestIOError(AZStd::string::format("Failed to copy '%s' to '%s'.", screenshotTest.m_screenshotFilePath.c_str(), destinationFile.c_str()));
  726. }
  727. m_fileIoErrorHandler.BusDisconnect();
  728. if (!failed)
  729. {
  730. // Since we just replaced the baseline image, we can update this screenshot test result as an exact match.
  731. // This will update the ImGui report dialog by the next frame.
  732. ClearImageComparisonResult(screenshotTest.m_localComparisonResult);
  733. }
  734. if (showResultDialog)
  735. {
  736. int successCount = !failed;
  737. int failureCount = failed;
  738. ShowUpdateLocalBaselineResult(successCount, failureCount);
  739. }
  740. return !failed;
  741. }
  742. bool ScriptReporter::UpdateSourceBaselineImage(ScreenshotTestInfo& screenshotTest, bool showResultDialog)
  743. {
  744. bool success = true;
  745. auto io = AZ::IO::LocalFileIO::GetInstance();
  746. // Get source folder
  747. if (m_officialBaselineSourceFolder.empty())
  748. {
  749. m_officialBaselineSourceFolder = (AZ::IO::FixedMaxPath(AZ::Utils::GetProjectPath()) / "Scripts" / "ExpectedScreenshots").String();
  750. if (!io->Exists(m_officialBaselineSourceFolder.c_str()))
  751. {
  752. 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());
  753. m_officialBaselineSourceFolder.clear();
  754. success = false;
  755. }
  756. }
  757. // Get official cache baseline file
  758. const AZStd::string cacheFilePath = ScreenshotPaths::GetOfficialBaseline(screenshotTest.m_screenshotFilePath);
  759. // Divide cache file path into components to we can access the file name and the parent folder
  760. AZStd::fixed_vector<AZ::IO::FixedMaxPathString, 16> reversePathComponents;
  761. auto GatherPathSegments = [&reversePathComponents](AZStd::string_view token)
  762. {
  763. reversePathComponents.emplace_back(token);
  764. };
  765. AzFramework::StringFunc::TokenizeVisitorReverse(cacheFilePath, GatherPathSegments, "/\\");
  766. // Source folder path
  767. // ".../AtomSampleViewer/Scripts/ExpectedScreenshots/" + "MyTestFolder/"
  768. AZStd::string sourceFolderPath = AZStd::string::format("%s\\%s", m_officialBaselineSourceFolder.c_str(), reversePathComponents[1].c_str());
  769. // Source file path
  770. // ".../AtomSampleViewer/Scripts/ExpectedScreenshots/MyTestFolder/" + "MyTest.png"
  771. AZStd::string sourceFilePath = AZStd::string::format("%s\\%s", sourceFolderPath.c_str(), reversePathComponents[0].c_str());
  772. m_fileIoErrorHandler.BusConnect();
  773. // Create parent folder if it doesn't exist
  774. if (success && !io->CreatePath(sourceFolderPath.c_str()))
  775. {
  776. success = false;
  777. m_fileIoErrorHandler.ReportLatestIOError(AZStd::string::format("Failed to create folder '%s'.", sourceFolderPath.c_str()));
  778. }
  779. // Replace source screenshot with new result
  780. if (success && !io->Copy(screenshotTest.m_screenshotFilePath.c_str(), sourceFilePath.c_str()))
  781. {
  782. success = false;
  783. m_fileIoErrorHandler.ReportLatestIOError(AZStd::string::format("Failed to copy '%s' to '%s'.", screenshotTest.m_screenshotFilePath.c_str(), sourceFilePath.c_str()));
  784. }
  785. m_fileIoErrorHandler.BusDisconnect();
  786. if (success)
  787. {
  788. // Since we just replaced the baseline image, we can update this screenshot test result as an exact match.
  789. // This will update the ImGui report dialog by the next frame.
  790. ClearImageComparisonResult(screenshotTest.m_officialComparisonResult);
  791. }
  792. if (showResultDialog)
  793. {
  794. AZStd::string message = "Destination: " + sourceFilePath + "\n";
  795. message += success
  796. ? AZStd::string::format("Copy successful!.\n")
  797. : AZStd::string::format("Copy failed!\n");
  798. m_messageBox.OpenPopupMessage("Update Baseline Image(s) Result", message);
  799. }
  800. return success;
  801. }
  802. void ScriptReporter::ClearImageComparisonResult(ImageComparisonResult& comparisonResult)
  803. {
  804. comparisonResult.m_resultCode = ImageComparisonResult::ResultCode::Pass;
  805. comparisonResult.m_standardDiffScore = 0.0f;
  806. comparisonResult.m_filteredDiffScore = 0.0f;
  807. comparisonResult.m_finalDiffScore = 0.0f;
  808. }
  809. void ScriptReporter::ShowUpdateLocalBaselineResult(int successCount, int failureCount)
  810. {
  811. AZStd::string message;
  812. if (failureCount == 0 && successCount == 0)
  813. {
  814. message = "No screenshots found.";
  815. }
  816. else
  817. {
  818. message = "Destination: " + ScreenshotPaths::GetLocalBaselineFolder(true) + "\n";
  819. if (successCount > 0)
  820. {
  821. message += AZStd::string::format("Successfully copied %d files.\n", successCount);
  822. }
  823. if (failureCount > 0)
  824. {
  825. message += AZStd::string::format("Failed to copy %d files.\n", failureCount);
  826. }
  827. }
  828. m_messageBox.OpenPopupMessage("Update Baseline Image(s) Result", message);
  829. }
  830. void ScriptReporter::CheckLatestScreenshot(const ImageComparisonToleranceLevel* toleranceLevel)
  831. {
  832. AZ_Assert(GetCurrentScriptReport(), "There is no active script");
  833. if (GetCurrentScriptReport() == nullptr || GetCurrentScriptReport()->m_screenshotTests.empty())
  834. {
  835. ReportScriptError("CheckLatestScreenshot() did not find any screenshots to check.");
  836. return;
  837. }
  838. ScreenshotTestInfo& screenshotTestInfo = GetCurrentScriptReport()->m_screenshotTests.back();
  839. if (toleranceLevel == nullptr)
  840. {
  841. screenshotTestInfo.m_officialComparisonResult.m_resultCode = ImageComparisonResult::ResultCode::NullImageComparisonToleranceLevel;
  842. ReportScriptError("Screenshot check failed. No ImageComparisonToleranceLevel provided.");
  843. return;
  844. }
  845. screenshotTestInfo.m_toleranceLevel = *toleranceLevel;
  846. screenshotTestInfo.m_officialBaselineScreenshotFilePath = ScreenshotPaths::GetOfficialBaseline(screenshotTestInfo.m_screenshotFilePath);
  847. if (screenshotTestInfo.m_officialBaselineScreenshotFilePath.empty())
  848. {
  849. ReportScriptError(AZStd::string::format("Screenshot check failed. Could not determine expected screenshot path for '%s'", screenshotTestInfo.m_screenshotFilePath.c_str()));
  850. screenshotTestInfo.m_officialComparisonResult.m_resultCode = ImageComparisonResult::ResultCode::FileNotFound;
  851. }
  852. else
  853. {
  854. bool imagesWereCompared = DiffImages(
  855. screenshotTestInfo.m_officialComparisonResult,
  856. screenshotTestInfo.m_officialBaselineScreenshotFilePath,
  857. screenshotTestInfo.m_screenshotFilePath,
  858. TraceLevel::Error);
  859. if (imagesWereCompared)
  860. {
  861. screenshotTestInfo.m_officialComparisonResult.m_finalDiffScore = toleranceLevel->m_filterImperceptibleDiffs ?
  862. screenshotTestInfo.m_officialComparisonResult.m_filteredDiffScore :
  863. screenshotTestInfo.m_officialComparisonResult.m_standardDiffScore;
  864. if (screenshotTestInfo.m_officialComparisonResult.m_finalDiffScore <= toleranceLevel->m_threshold)
  865. {
  866. screenshotTestInfo.m_officialComparisonResult.m_resultCode = ImageComparisonResult::ResultCode::Pass;
  867. }
  868. else
  869. {
  870. // Be aware there is an automation test script that looks for the "Screenshot check failed. Diff score" string text to report failures.
  871. // If you change this message, be sure to update the associated tests as well located here: "C:/path/to/Lumberyard/AtomSampleViewer/Standalone/PythonTests"
  872. ReportScreenshotComparisonIssue(
  873. AZStd::string::format("Screenshot check failed. Diff score %f exceeds threshold of %f ('%s').",
  874. screenshotTestInfo.m_officialComparisonResult.m_finalDiffScore, toleranceLevel->m_threshold, toleranceLevel->m_name.c_str()),
  875. screenshotTestInfo.m_officialBaselineScreenshotFilePath,
  876. screenshotTestInfo.m_screenshotFilePath,
  877. TraceLevel::Error);
  878. screenshotTestInfo.m_officialComparisonResult.m_resultCode = ImageComparisonResult::ResultCode::ThresholdExceeded;
  879. }
  880. }
  881. }
  882. screenshotTestInfo.m_localBaselineScreenshotFilePath = ScreenshotPaths::GetLocalBaseline(screenshotTestInfo.m_screenshotFilePath);
  883. if (screenshotTestInfo.m_localBaselineScreenshotFilePath.empty())
  884. {
  885. ReportScriptWarning(AZStd::string::format("Screenshot check failed. Could not determine local baseline screenshot path for '%s'", screenshotTestInfo.m_screenshotFilePath.c_str()));
  886. screenshotTestInfo.m_localComparisonResult.m_resultCode = ImageComparisonResult::ResultCode::FileNotFound;
  887. }
  888. else
  889. {
  890. // Local screenshots should be expected match 100% every time, otherwise warnings are reported. This will help developers track and investigate changes,
  891. // for example if they make local changes that impact some unrelated AtomSampleViewer sample in an unexpected way, they will see a warning about this.
  892. bool imagesWereCompared = DiffImages(
  893. screenshotTestInfo.m_localComparisonResult,
  894. screenshotTestInfo.m_localBaselineScreenshotFilePath,
  895. screenshotTestInfo.m_screenshotFilePath,
  896. TraceLevel::Warning);
  897. if (imagesWereCompared)
  898. {
  899. if(screenshotTestInfo.m_localComparisonResult.m_standardDiffScore == 0.0f)
  900. {
  901. screenshotTestInfo.m_localComparisonResult.m_resultCode = ImageComparisonResult::ResultCode::Pass;
  902. }
  903. else
  904. {
  905. ReportScreenshotComparisonIssue(
  906. 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),
  907. screenshotTestInfo.m_localBaselineScreenshotFilePath,
  908. screenshotTestInfo.m_screenshotFilePath,
  909. TraceLevel::Warning);
  910. screenshotTestInfo.m_localComparisonResult.m_resultCode = ImageComparisonResult::ResultCode::ThresholdExceeded;
  911. }
  912. }
  913. }
  914. }
  915. void ScriptReporter::ExportTestResults()
  916. {
  917. m_exportedTestResultsPath = GenerateAndCreateExportedTestResultsPath();
  918. for (const ScriptReport& scriptReport : m_scriptReports)
  919. {
  920. const AZStd::string assertLogLine = AZStd::string::format("Asserts: %u \n", scriptReport.m_assertCount);
  921. const AZStd::string errorsLogLine = AZStd::string::format("Errors: %u \n", scriptReport.m_generalErrorCount);
  922. const AZStd::string warningsLogLine = AZStd::string::format("Warnings: %u \n", scriptReport.m_generalWarningCount);
  923. const AZStd::string screenshotErrorsLogLine = AZStd::string::format("Screenshot errors: %u \n", scriptReport.m_screenshotErrorCount);
  924. const AZStd::string screenshotWarningsLogLine = AZStd::string::format("Screenshot warnings: %u \n", scriptReport.m_screenshotWarningCount);
  925. const AZStd::string failedScreenshotsLogLine = "\nScreenshot test info below.\n";
  926. AZ::IO::HandleType logHandle;
  927. auto io = AZ::IO::LocalFileIO::GetInstance();
  928. if (io->Open(m_exportedTestResultsPath.c_str(), AZ::IO::OpenMode::ModeWrite, logHandle))
  929. {
  930. io->Write(logHandle, assertLogLine.c_str(), assertLogLine.size());
  931. io->Write(logHandle, errorsLogLine.c_str(), errorsLogLine.size());
  932. io->Write(logHandle, warningsLogLine.c_str(), warningsLogLine.size());
  933. io->Write(logHandle, screenshotErrorsLogLine.c_str(), screenshotErrorsLogLine.size());
  934. io->Write(logHandle, screenshotWarningsLogLine.c_str(), screenshotWarningsLogLine.size());
  935. io->Write(logHandle, failedScreenshotsLogLine.c_str(), failedScreenshotsLogLine.size());
  936. for (const ScreenshotTestInfo& screenshotTest : scriptReport.m_screenshotTests)
  937. {
  938. const AZStd::string screenshotPath = AZStd::string::format("Test screenshot path: %s \n", screenshotTest.m_screenshotFilePath.c_str());
  939. const AZStd::string officialBaselineScreenshotPath = AZStd::string::format("Official baseline screenshot path: %s \n", screenshotTest.m_officialBaselineScreenshotFilePath.c_str());
  940. const AZStd::string toleranceLevelLogLine = AZStd::string::format("Tolerance level: %s \n", screenshotTest.m_toleranceLevel.ToString().c_str());
  941. const AZStd::string officialComparisonLogLine = AZStd::string::format("Image comparison result: %s \n", screenshotTest.m_officialComparisonResult.GetSummaryString().c_str());
  942. io->Write(logHandle, toleranceLevelLogLine.c_str(), toleranceLevelLogLine.size());
  943. io->Write(logHandle, officialComparisonLogLine.c_str(), officialComparisonLogLine.size());
  944. }
  945. io->Close(logHandle);
  946. }
  947. m_messageBox.OpenPopupMessage("Exported test results", AZStd::string::format("Results exported to %s", m_exportedTestResultsPath.c_str()));
  948. AZ_Printf("Test results exported to %s \n", m_exportedTestResultsPath.c_str());
  949. }
  950. }
  951. AZStd::string ScriptReporter::GenerateAndCreateExportedTestResultsPath() const
  952. {
  953. // Setup our variables for the exported test results path and .txt file.
  954. const auto projectPath = AZ::Utils::GetProjectPath();
  955. const AZStd::chrono::system_clock::time_point now = AZStd::chrono::system_clock::now();
  956. const float timeFloat = AZStd::chrono::duration<float>(now.time_since_epoch()).count();
  957. const AZStd::string timeString = AZStd::string::format("%.4f", timeFloat);
  958. const AZStd::string exportFileName = AZStd::string::format("exportedTestResults_%s.txt", timeString.c_str());
  959. AZStd::string exportTestResultsFolder;
  960. AzFramework::StringFunc::Path::Join(projectPath.c_str(), "TestResults/", exportTestResultsFolder);
  961. // Create the exported test results path & return .txt file path.
  962. auto io = AZ::IO::LocalFileIO::GetInstance();
  963. io->CreatePath(exportTestResultsFolder.c_str());
  964. AZStd::string exportFile;
  965. AzFramework::StringFunc::Path::Join(exportTestResultsFolder.c_str(), exportFileName.c_str(), exportFile);
  966. return exportFile;
  967. }
  968. } // namespace AtomSampleViewer