Advertisement
Guest User

Untitled

a guest
Jan 24th, 2017
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 16.02 KB | None | 0 0
  1. package com.syniverse.ipmessenger.tests.robocases.common.report;
  2.  
  3. import android.util.Log;
  4.  
  5. import com.syniverse.ipmessenger.tests.robocases.common.utils.Str;
  6.  
  7. import java.io.BufferedReader;
  8. import java.io.BufferedWriter;
  9. import java.io.File;
  10. import java.io.FileWriter;
  11. import java.io.IOException;
  12. import java.io.InputStreamReader;
  13. import java.text.SimpleDateFormat;
  14. import java.util.ArrayList;
  15. import java.util.Calendar;
  16.  
  17.  
  18. public class ReportBuilder {
  19. public enum ScreenshotMode { NO_SCREENSHOTS, SCREENSHOTS_ON_FAILURE, SCREENSHOTS };
  20.  
  21. private static ReportBuilder instance = null;
  22.  
  23. //Singleton class
  24. private ReportBuilder(){ }
  25.  
  26. public static ReportBuilder getInstance(ScreenShooter _shooter){
  27.  
  28. if(instance==null){
  29. instance = new ReportBuilder();
  30. }
  31.  
  32. if(_shooter!=null){
  33. instance.shooter = _shooter;
  34. }
  35. return instance;
  36. }
  37.  
  38. volatile protected ScreenShooter shooter ;
  39. public static final String TAG_RAW ="ReportBuilder_RAW";
  40. public static final String TAG_FLOW ="ReportBuilder_FLOW";
  41. //Change those if needed
  42. private static final String screenshotsFolderName = "/Report-Screenshots/";
  43. private static final String reportFileName = "Report";
  44. //Environment.getExternalStorageDirectory() sometimes return "/storage/emulated/0/" and this emulation breaks the screenshot saving mechanism;
  45. private static final String externalDirRoot = "/mnt/sdcard";
  46. private static final int FAILED_STEPS_BUFFER_SIZE = 400;
  47. private static final StringBuilder failedStepsInfoListBuilder = new StringBuilder(FAILED_STEPS_BUFFER_SIZE);
  48.  
  49. volatile private ArrayList<String> currentTestFailedSteps = new ArrayList<String>();
  50.  
  51. private static final int logWriteMessageInvisibleThreshold = 0;
  52. volatile private static boolean isLogInitialized = false;
  53.  
  54. volatile private ScreenshotMode currentTestScreenshotMode;
  55. volatile private String currentTestScreenshotsFileName;
  56. volatile private int currentTestStepNumber;
  57. volatile private String currentTestName="";
  58.  
  59. volatile private boolean areStepFailuresPresent;
  60. volatile private boolean isCurrentStepFinalized;
  61. volatile private String currentStepName ="";
  62.  
  63.  
  64.  
  65. synchronized public void onSetUp(){
  66. Log.d(TAG_FLOW, "onSetUp: ");
  67. currentTestStepNumber = 1;
  68. areStepFailuresPresent = false;
  69. currentTestFailedSteps.clear();
  70. initLog();
  71. }
  72.  
  73. /**
  74. * Should be called at the start of a new test sequence to init the screenshot dir and init HTML headers.
  75. * This method is to be called only from onSetUp
  76. */
  77. synchronized private static void initLog(){
  78. Log.d(TAG_FLOW, "initLog:Initialization start ");
  79. if (!isLogInitialized) {
  80. Log.d(TAG_FLOW, "initLog: Log not initialized - creating it ");
  81. // Write the log header if this is the first test
  82. logRaw(Str.from(
  83. "<html>",
  84. "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />" ,
  85. "<body><h5>Test run started at " ,
  86. (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(Calendar.getInstance().getTime()),
  87. "</h5>\n"),false);
  88.  
  89.  
  90. isLogInitialized = true;
  91. clearImages();
  92. }
  93. Log.d(TAG_FLOW, "initLog: Log initialized.");
  94. }
  95.  
  96.  
  97. /**
  98. * Starts the logging for a test with screenshots taken only on failures -should be called at the beginning of each test
  99. * @param testName - test title
  100. */
  101. synchronized public void startTest(String testName) {
  102. Log.d(TAG_FLOW, "In startTest");
  103. startTest(testName, ScreenshotMode.SCREENSHOTS_ON_FAILURE);
  104. }
  105.  
  106. /**
  107. * Starts the logging for a test -should be called at the beginning of each test
  108. * @param testName - test title
  109. * @param mode - if/when screenshots should be taken
  110. */
  111. synchronized public void startTest(String testName, ScreenshotMode mode) {
  112. Log.d(TAG_FLOW, Str.from( "In startTest with mode:", mode.name()));
  113. currentTestScreenshotMode = mode;
  114. currentTestName= testName;
  115. logRaw(Str.from("<h2>",testName, "</h2>\n"), true);
  116. currentTestScreenshotsFileName = testName.replaceAll("[^a-zA-Z0-9]", "");
  117.  
  118. Log.d(TAG_FLOW, Str.from(" ############ Starting test:" ,testName," ############"));
  119. }
  120.  
  121. /**
  122. * Logs the start of a test step
  123. * @param stepDescription
  124. */
  125.  
  126.  
  127. synchronized public void startStep(String stepDescription) {
  128. Log.d(TAG_FLOW, Str.from("****startStep: ", stepDescription));
  129. isCurrentStepFinalized = false;
  130. currentStepName = stepDescription;
  131. logRaw(Str.from("<!--" , Calendar.getInstance().getTime().toString() , "-->\n"), true);
  132. logRaw(Str.from("<p>" , (""+currentTestStepNumber++) ,". " ,stepDescription , "..."), true);
  133.  
  134. }
  135.  
  136. synchronized private static void logRaw(String text, boolean append) {
  137. Log.d(TAG_RAW, "logRaw: appending the text :\n " );
  138. BufferedWriter out;
  139. try {
  140. String filename = Str.from(externalDirRoot, "/",reportFileName,".html");
  141.  
  142. Log.d(TAG_RAW,Str.from("logRaw: Opening the log file:\n (",filename,")") );
  143.  
  144. out = new BufferedWriter(new FileWriter(filename, append));
  145. Log.d(TAG_RAW,"logRaw: Open success - appending...");
  146. out.append(text);
  147. out.flush();
  148. Log.d(TAG_RAW,"logRaw: Append success - closing file...");
  149. out.close();
  150. } catch (IOException e) {
  151. Log.d(TAG_RAW,"logRaw: Error closing the log file");
  152. e.printStackTrace();
  153. }
  154. Log.d(TAG_RAW, "logRaw: Closing logfile success!");
  155. }
  156.  
  157. /**
  158. * Logs a message in the current test step
  159. * @param text
  160. */
  161. synchronized public void message(String text) {
  162. Log.d(TAG_FLOW, Str.from( "message: " ,text ));
  163. logRaw(Str.from("<ul><font size='4'>" , text , "</font></ul>\n"), true);
  164. }
  165.  
  166. /**
  167. * Logs a message in the current test step with custom log level
  168. * @param text
  169. * @param logLevel (0 - show in report ,1 - hide message as HTML comment to keep report visually clean
  170. */
  171. synchronized public void message(String text, int logLevel) {
  172. Log.d(TAG_FLOW, Str.from("message with log level: " , logLevel));
  173. Log.d(TAG_FLOW, Str.from("message : " ,text));
  174. if (logLevel <= logWriteMessageInvisibleThreshold) {
  175. Log.d(TAG_FLOW, "message: the log level is below threshold - writing visible message" );
  176. message (text);
  177. } else {
  178. Log.d(TAG_FLOW, "message: the log level is past threshold - writing as html comment " );
  179. logRaw(Str.from("<!--" ,text , "-->\n"), true);
  180. }
  181.  
  182. }
  183.  
  184. /**
  185. * Logs a red test message in the current test step
  186. * @param text
  187. */
  188. synchronized public void messageRed(String text) {
  189. Log.d(TAG_FLOW, Str.from("In messageRed :" ,text));
  190. logRaw(Str.from("<ul><font size='2' color='red'>" , text , "</font></ul>\n"), true);
  191. }
  192.  
  193.  
  194. synchronized public void endStep(boolean... isPassingArgs){
  195. Log.d(TAG_FLOW, "endStep: boolean... isPassingArgs ");
  196. boolean passing = true;
  197. for(boolean arg : isPassingArgs){
  198. Log.d(TAG_FLOW, Str.from("endStep_Arg :",arg));
  199. passing = arg && passing;
  200. }
  201.  
  202. endStep(passing);
  203.  
  204. }
  205.  
  206. /**
  207. * Logs the completion of a test step
  208. * @param isPassing - whether the test step passed successfully or not
  209. */
  210. synchronized public void endStep (boolean isPassing) {
  211. Log.d(TAG_FLOW, Str.from("endStep: isPassing: ",isPassing));
  212.  
  213. logRaw(Str.from(
  214. "<font color='" ,
  215. (isPassing ? "green" : "red") ,
  216. "'>" ,
  217. (isPassing ? "PASSED" : "FAILED"),
  218. "</font>"), true);
  219.  
  220. if ( ((currentTestScreenshotMode ==ScreenshotMode.SCREENSHOTS_ON_FAILURE)&&!isPassing)
  221. || (currentTestScreenshotMode ==ScreenshotMode.SCREENSHOTS) ) {
  222. Log.d(TAG_FLOW, "endStep: Taking screenshot");
  223. takeScreenshot();
  224. logRaw(Str.from(
  225. "<a href='.",
  226. screenshotsFolderName ,
  227. getCurrentScreenshotName() ,
  228. ".jpg'>#</a>")
  229. , true);
  230. }
  231. logRaw("</p>", true);
  232. if (!isPassing){
  233. Log.d(TAG_FLOW, "endStep: Step failed - adding it to the collection and rising flag");
  234. areStepFailuresPresent = true;
  235. currentTestFailedSteps.add(currentStepName);
  236. }
  237. Log.d(TAG_FLOW, "endStep: Finalized step ");
  238. isCurrentStepFinalized = true;
  239. }
  240.  
  241. /**
  242. * Logs the completion of a test step as successful
  243. */
  244. synchronized public void endStep() {
  245. endStep(true);
  246. }
  247.  
  248. /**
  249. * Ends the logging for a test - should be called as last line of test
  250. */
  251. synchronized public void endTest() {
  252. Log.d(TAG_FLOW, Str.from( " ############ Ending test: ", currentTestName , " ############"));
  253. logRaw("<p/>", true);
  254. }
  255.  
  256. /**
  257. * Should be called before calling the test super.tearDown and before freeing the screenshot shooter object.
  258. * @return String desctibing the test failed steps , or null if no failed steps are present during the test.
  259. */
  260. synchronized public String onTearDown() {
  261. Log.d(TAG_FLOW, Str.from("onTearDown for test :",currentTestName));
  262. String testResult = null;
  263. //this method should not throw any exceptions because they will mess-up the test result - it should rather print them.
  264. try{
  265. if (!isCurrentStepFinalized) {
  266. Log.d(TAG_FLOW,"onTearDown: Step not finalized!");
  267. areStepFailuresPresent=true;
  268. currentTestFailedSteps.add(currentStepName);
  269. // Exception occurred during the test, take a screenshot
  270. if ( ((currentTestScreenshotMode ==ScreenshotMode.SCREENSHOTS_ON_FAILURE))
  271. || (currentTestScreenshotMode ==ScreenshotMode.SCREENSHOTS) ) {
  272. Log.d(TAG_FLOW, "onTearDown: Taking screenshot. ");
  273. takeScreenshot();
  274. logRaw(Str.from(
  275. "<font color='red'><-- Did not finish:</font><a href='.",
  276. screenshotsFolderName ,
  277. getCurrentScreenshotName() ,
  278. ".jpg'>#</a>")
  279. , true);
  280. }
  281. }
  282.  
  283. if (areStepFailuresPresent || currentTestFailedSteps.size()>0) {
  284. Log.d(TAG_FLOW, "\nonTearDown: Failure steps present,collecting failed steps... ");
  285.  
  286. failedStepsInfoListBuilder.append("\nIn test:");
  287. failedStepsInfoListBuilder.append(currentTestName);
  288. failedStepsInfoListBuilder.append(":\nThe following steps failed failed :\n");
  289.  
  290. if(currentTestFailedSteps.size()>0){
  291. for(String failingStep : currentTestFailedSteps){
  292. failedStepsInfoListBuilder.append(failingStep);
  293. failedStepsInfoListBuilder.append("\n");
  294. }
  295. currentTestFailedSteps.clear();
  296. }
  297.  
  298. testResult = failedStepsInfoListBuilder.toString();
  299. failedStepsInfoListBuilder.delete(0,FAILED_STEPS_BUFFER_SIZE);
  300.  
  301. if(testResult!=null){
  302. writeLogCatToFile();//write in different file for each test
  303. }
  304.  
  305.  
  306. Log.d(TAG_FLOW, Str.from("onTearDown: Colected steps: " , testResult));
  307. return testResult;
  308. }else{
  309. Log.d(TAG_FLOW, "onTearDown: No failed steps present, returning null");
  310. return null;
  311. }
  312. }catch (Exception e){
  313. Log.d(TAG_RAW, Str.from("Exception occured :" , e.getMessage()));
  314. }
  315. currentTestName = "";
  316.  
  317. return testResult;
  318. }
  319.  
  320. synchronized protected void takeScreenshot( ){
  321. Log.d(TAG_FLOW, Str.from("takeScreenshot: with name ", screenshotsFolderName, getCurrentScreenshotName()));
  322. shooter.takeScreenshot(screenshotsFolderName, getCurrentScreenshotName());
  323. }
  324.  
  325. synchronized protected String getCurrentScreenshotName(){
  326. return Str.from(currentTestScreenshotsFileName ,(currentTestStepNumber - 1));
  327. }
  328. /**
  329. * Deletes the images
  330. */
  331. synchronized private static void clearImages() {
  332. Log.d(TAG_FLOW, "clearImages:" );
  333. try {
  334. String folderPath = Str.from(externalDirRoot, screenshotsFolderName);
  335. Log.d(TAG_FLOW, Str.from("clearImages: Fetching folder :",folderPath) );
  336. File dir = new File(folderPath);
  337. if (dir != null && dir.isDirectory()) {
  338. Log.d(TAG_FLOW, "clearImages:Folder exists." );
  339. deleteDir(dir);
  340. dir.mkdir();
  341. }
  342. } catch (Exception e) {
  343. e.printStackTrace();
  344. }
  345. }
  346.  
  347. /**
  348. * Deletes a directory
  349. * @param dir - the directory
  350. * @return
  351. */
  352. synchronized private static boolean deleteDir(File dir) {
  353. Log.d(TAG_FLOW, "deleteDir: Deleting dir... ");
  354. return (emptyDir(dir) && dir.delete());
  355. }
  356.  
  357. /**
  358. * Delete all files in a directory recursively
  359. * @param dir - the directory
  360. * @return
  361. */
  362. synchronized private static boolean emptyDir(File dir) {
  363. Log.d(TAG_FLOW, Str.from("emptyDir : Deleting all in dir:" , dir.toString()));
  364. File[] children = dir.listFiles();
  365. for (int i = 0; i < children.length; i++) {
  366. if (children[i].isDirectory()) {
  367. Log.d(TAG_FLOW, Str.from( "emptyDir : Found child dir:",dir.toString()) );
  368. emptyDir(children[i]);
  369. }
  370. Log.d(TAG_FLOW,Str.from( "emptyDir : Deleting file:",children[i].toString()) );
  371. boolean success = children[i].delete();
  372. if (!success) {
  373. Log.d(TAG_FLOW, Str.from("emptyDir : Could not delete file:",children[i].toString() ));
  374. return false;
  375. }
  376. }
  377. Log.d(TAG_FLOW, Str.from("emptyDir : Deleted all in dir" , dir.toString()));
  378. return true;
  379. }
  380.  
  381. synchronized private void writeLogCatToFile() {
  382.  
  383. Log.d(TAG_FLOW, Str.from( "writeLogCatToFile: Saving LogCat with name : ",currentTestScreenshotsFileName));
  384. // BufferedWriter logcatFileWriter;
  385. FileWriter lcFileWriter;
  386. try {
  387. Process logcatProcess = Runtime.getRuntime().exec("logcat -d");
  388. BufferedReader logcatReader = new BufferedReader( new InputStreamReader(logcatProcess.getInputStream()),300);
  389.  
  390. String logcatFile = Str.from( externalDirRoot , screenshotsFolderName ,currentTestScreenshotsFileName,".log");
  391.  
  392. //logcatFileWriter = new BufferedWriter(new FileWriter(logcatFile, false));
  393. lcFileWriter = new FileWriter(logcatFile,false);
  394.  
  395. String logcatLine ;
  396. while ((logcatLine = logcatReader.readLine()) != null) {
  397.  
  398. lcFileWriter.append(logcatLine);
  399. lcFileWriter.append('\n');
  400. lcFileWriter.flush();
  401. /*
  402. logcatFileWriter.append(logcatLine);
  403. logcatFileWriter.append('\n');
  404. logcatFileWriter.flush();*/
  405. }
  406.  
  407. lcFileWriter.close();
  408. // logcatFileWriter.close();
  409. logcatReader.close();
  410. logcatProcess.waitFor();
  411.  
  412. } catch (Exception e) {
  413. Log.d(TAG_RAW, Str.from("writeLogCatToFile: Error occurred" , e.getMessage()));
  414. }
  415.  
  416. }
  417.  
  418. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement