Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.syniverse.ipmessenger.tests.robocases.common.report;
- import android.util.Log;
- import com.syniverse.ipmessenger.tests.robocases.common.utils.Str;
- import java.io.BufferedReader;
- import java.io.BufferedWriter;
- import java.io.File;
- import java.io.FileWriter;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.text.SimpleDateFormat;
- import java.util.ArrayList;
- import java.util.Calendar;
- public class ReportBuilder {
- public enum ScreenshotMode { NO_SCREENSHOTS, SCREENSHOTS_ON_FAILURE, SCREENSHOTS };
- private static ReportBuilder instance = null;
- //Singleton class
- private ReportBuilder(){ }
- public static ReportBuilder getInstance(ScreenShooter _shooter){
- if(instance==null){
- instance = new ReportBuilder();
- }
- if(_shooter!=null){
- instance.shooter = _shooter;
- }
- return instance;
- }
- volatile protected ScreenShooter shooter ;
- public static final String TAG_RAW ="ReportBuilder_RAW";
- public static final String TAG_FLOW ="ReportBuilder_FLOW";
- //Change those if needed
- private static final String screenshotsFolderName = "/Report-Screenshots/";
- private static final String reportFileName = "Report";
- //Environment.getExternalStorageDirectory() sometimes return "/storage/emulated/0/" and this emulation breaks the screenshot saving mechanism;
- private static final String externalDirRoot = "/mnt/sdcard";
- private static final int FAILED_STEPS_BUFFER_SIZE = 400;
- private static final StringBuilder failedStepsInfoListBuilder = new StringBuilder(FAILED_STEPS_BUFFER_SIZE);
- volatile private ArrayList<String> currentTestFailedSteps = new ArrayList<String>();
- private static final int logWriteMessageInvisibleThreshold = 0;
- volatile private static boolean isLogInitialized = false;
- volatile private ScreenshotMode currentTestScreenshotMode;
- volatile private String currentTestScreenshotsFileName;
- volatile private int currentTestStepNumber;
- volatile private String currentTestName="";
- volatile private boolean areStepFailuresPresent;
- volatile private boolean isCurrentStepFinalized;
- volatile private String currentStepName ="";
- synchronized public void onSetUp(){
- Log.d(TAG_FLOW, "onSetUp: ");
- currentTestStepNumber = 1;
- areStepFailuresPresent = false;
- currentTestFailedSteps.clear();
- initLog();
- }
- /**
- * Should be called at the start of a new test sequence to init the screenshot dir and init HTML headers.
- * This method is to be called only from onSetUp
- */
- synchronized private static void initLog(){
- Log.d(TAG_FLOW, "initLog:Initialization start ");
- if (!isLogInitialized) {
- Log.d(TAG_FLOW, "initLog: Log not initialized - creating it ");
- // Write the log header if this is the first test
- logRaw(Str.from(
- "<html>",
- "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />" ,
- "<body><h5>Test run started at " ,
- (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(Calendar.getInstance().getTime()),
- "</h5>\n"),false);
- isLogInitialized = true;
- clearImages();
- }
- Log.d(TAG_FLOW, "initLog: Log initialized.");
- }
- /**
- * Starts the logging for a test with screenshots taken only on failures -should be called at the beginning of each test
- * @param testName - test title
- */
- synchronized public void startTest(String testName) {
- Log.d(TAG_FLOW, "In startTest");
- startTest(testName, ScreenshotMode.SCREENSHOTS_ON_FAILURE);
- }
- /**
- * Starts the logging for a test -should be called at the beginning of each test
- * @param testName - test title
- * @param mode - if/when screenshots should be taken
- */
- synchronized public void startTest(String testName, ScreenshotMode mode) {
- Log.d(TAG_FLOW, Str.from( "In startTest with mode:", mode.name()));
- currentTestScreenshotMode = mode;
- currentTestName= testName;
- logRaw(Str.from("<h2>",testName, "</h2>\n"), true);
- currentTestScreenshotsFileName = testName.replaceAll("[^a-zA-Z0-9]", "");
- Log.d(TAG_FLOW, Str.from(" ############ Starting test:" ,testName," ############"));
- }
- /**
- * Logs the start of a test step
- * @param stepDescription
- */
- synchronized public void startStep(String stepDescription) {
- Log.d(TAG_FLOW, Str.from("****startStep: ", stepDescription));
- isCurrentStepFinalized = false;
- currentStepName = stepDescription;
- logRaw(Str.from("<!--" , Calendar.getInstance().getTime().toString() , "-->\n"), true);
- logRaw(Str.from("<p>" , (""+currentTestStepNumber++) ,". " ,stepDescription , "..."), true);
- }
- synchronized private static void logRaw(String text, boolean append) {
- Log.d(TAG_RAW, "logRaw: appending the text :\n " );
- BufferedWriter out;
- try {
- String filename = Str.from(externalDirRoot, "/",reportFileName,".html");
- Log.d(TAG_RAW,Str.from("logRaw: Opening the log file:\n (",filename,")") );
- out = new BufferedWriter(new FileWriter(filename, append));
- Log.d(TAG_RAW,"logRaw: Open success - appending...");
- out.append(text);
- out.flush();
- Log.d(TAG_RAW,"logRaw: Append success - closing file...");
- out.close();
- } catch (IOException e) {
- Log.d(TAG_RAW,"logRaw: Error closing the log file");
- e.printStackTrace();
- }
- Log.d(TAG_RAW, "logRaw: Closing logfile success!");
- }
- /**
- * Logs a message in the current test step
- * @param text
- */
- synchronized public void message(String text) {
- Log.d(TAG_FLOW, Str.from( "message: " ,text ));
- logRaw(Str.from("<ul><font size='4'>" , text , "</font></ul>\n"), true);
- }
- /**
- * Logs a message in the current test step with custom log level
- * @param text
- * @param logLevel (0 - show in report ,1 - hide message as HTML comment to keep report visually clean
- */
- synchronized public void message(String text, int logLevel) {
- Log.d(TAG_FLOW, Str.from("message with log level: " , logLevel));
- Log.d(TAG_FLOW, Str.from("message : " ,text));
- if (logLevel <= logWriteMessageInvisibleThreshold) {
- Log.d(TAG_FLOW, "message: the log level is below threshold - writing visible message" );
- message (text);
- } else {
- Log.d(TAG_FLOW, "message: the log level is past threshold - writing as html comment " );
- logRaw(Str.from("<!--" ,text , "-->\n"), true);
- }
- }
- /**
- * Logs a red test message in the current test step
- * @param text
- */
- synchronized public void messageRed(String text) {
- Log.d(TAG_FLOW, Str.from("In messageRed :" ,text));
- logRaw(Str.from("<ul><font size='2' color='red'>" , text , "</font></ul>\n"), true);
- }
- synchronized public void endStep(boolean... isPassingArgs){
- Log.d(TAG_FLOW, "endStep: boolean... isPassingArgs ");
- boolean passing = true;
- for(boolean arg : isPassingArgs){
- Log.d(TAG_FLOW, Str.from("endStep_Arg :",arg));
- passing = arg && passing;
- }
- endStep(passing);
- }
- /**
- * Logs the completion of a test step
- * @param isPassing - whether the test step passed successfully or not
- */
- synchronized public void endStep (boolean isPassing) {
- Log.d(TAG_FLOW, Str.from("endStep: isPassing: ",isPassing));
- logRaw(Str.from(
- "<font color='" ,
- (isPassing ? "green" : "red") ,
- "'>" ,
- (isPassing ? "PASSED" : "FAILED"),
- "</font>"), true);
- if ( ((currentTestScreenshotMode ==ScreenshotMode.SCREENSHOTS_ON_FAILURE)&&!isPassing)
- || (currentTestScreenshotMode ==ScreenshotMode.SCREENSHOTS) ) {
- Log.d(TAG_FLOW, "endStep: Taking screenshot");
- takeScreenshot();
- logRaw(Str.from(
- "<a href='.",
- screenshotsFolderName ,
- getCurrentScreenshotName() ,
- ".jpg'>#</a>")
- , true);
- }
- logRaw("</p>", true);
- if (!isPassing){
- Log.d(TAG_FLOW, "endStep: Step failed - adding it to the collection and rising flag");
- areStepFailuresPresent = true;
- currentTestFailedSteps.add(currentStepName);
- }
- Log.d(TAG_FLOW, "endStep: Finalized step ");
- isCurrentStepFinalized = true;
- }
- /**
- * Logs the completion of a test step as successful
- */
- synchronized public void endStep() {
- endStep(true);
- }
- /**
- * Ends the logging for a test - should be called as last line of test
- */
- synchronized public void endTest() {
- Log.d(TAG_FLOW, Str.from( " ############ Ending test: ", currentTestName , " ############"));
- logRaw("<p/>", true);
- }
- /**
- * Should be called before calling the test super.tearDown and before freeing the screenshot shooter object.
- * @return String desctibing the test failed steps , or null if no failed steps are present during the test.
- */
- synchronized public String onTearDown() {
- Log.d(TAG_FLOW, Str.from("onTearDown for test :",currentTestName));
- String testResult = null;
- //this method should not throw any exceptions because they will mess-up the test result - it should rather print them.
- try{
- if (!isCurrentStepFinalized) {
- Log.d(TAG_FLOW,"onTearDown: Step not finalized!");
- areStepFailuresPresent=true;
- currentTestFailedSteps.add(currentStepName);
- // Exception occurred during the test, take a screenshot
- if ( ((currentTestScreenshotMode ==ScreenshotMode.SCREENSHOTS_ON_FAILURE))
- || (currentTestScreenshotMode ==ScreenshotMode.SCREENSHOTS) ) {
- Log.d(TAG_FLOW, "onTearDown: Taking screenshot. ");
- takeScreenshot();
- logRaw(Str.from(
- "<font color='red'><-- Did not finish:</font><a href='.",
- screenshotsFolderName ,
- getCurrentScreenshotName() ,
- ".jpg'>#</a>")
- , true);
- }
- }
- if (areStepFailuresPresent || currentTestFailedSteps.size()>0) {
- Log.d(TAG_FLOW, "\nonTearDown: Failure steps present,collecting failed steps... ");
- failedStepsInfoListBuilder.append("\nIn test:");
- failedStepsInfoListBuilder.append(currentTestName);
- failedStepsInfoListBuilder.append(":\nThe following steps failed failed :\n");
- if(currentTestFailedSteps.size()>0){
- for(String failingStep : currentTestFailedSteps){
- failedStepsInfoListBuilder.append(failingStep);
- failedStepsInfoListBuilder.append("\n");
- }
- currentTestFailedSteps.clear();
- }
- testResult = failedStepsInfoListBuilder.toString();
- failedStepsInfoListBuilder.delete(0,FAILED_STEPS_BUFFER_SIZE);
- if(testResult!=null){
- writeLogCatToFile();//write in different file for each test
- }
- Log.d(TAG_FLOW, Str.from("onTearDown: Colected steps: " , testResult));
- return testResult;
- }else{
- Log.d(TAG_FLOW, "onTearDown: No failed steps present, returning null");
- return null;
- }
- }catch (Exception e){
- Log.d(TAG_RAW, Str.from("Exception occured :" , e.getMessage()));
- }
- currentTestName = "";
- return testResult;
- }
- synchronized protected void takeScreenshot( ){
- Log.d(TAG_FLOW, Str.from("takeScreenshot: with name ", screenshotsFolderName, getCurrentScreenshotName()));
- shooter.takeScreenshot(screenshotsFolderName, getCurrentScreenshotName());
- }
- synchronized protected String getCurrentScreenshotName(){
- return Str.from(currentTestScreenshotsFileName ,(currentTestStepNumber - 1));
- }
- /**
- * Deletes the images
- */
- synchronized private static void clearImages() {
- Log.d(TAG_FLOW, "clearImages:" );
- try {
- String folderPath = Str.from(externalDirRoot, screenshotsFolderName);
- Log.d(TAG_FLOW, Str.from("clearImages: Fetching folder :",folderPath) );
- File dir = new File(folderPath);
- if (dir != null && dir.isDirectory()) {
- Log.d(TAG_FLOW, "clearImages:Folder exists." );
- deleteDir(dir);
- dir.mkdir();
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- /**
- * Deletes a directory
- * @param dir - the directory
- * @return
- */
- synchronized private static boolean deleteDir(File dir) {
- Log.d(TAG_FLOW, "deleteDir: Deleting dir... ");
- return (emptyDir(dir) && dir.delete());
- }
- /**
- * Delete all files in a directory recursively
- * @param dir - the directory
- * @return
- */
- synchronized private static boolean emptyDir(File dir) {
- Log.d(TAG_FLOW, Str.from("emptyDir : Deleting all in dir:" , dir.toString()));
- File[] children = dir.listFiles();
- for (int i = 0; i < children.length; i++) {
- if (children[i].isDirectory()) {
- Log.d(TAG_FLOW, Str.from( "emptyDir : Found child dir:",dir.toString()) );
- emptyDir(children[i]);
- }
- Log.d(TAG_FLOW,Str.from( "emptyDir : Deleting file:",children[i].toString()) );
- boolean success = children[i].delete();
- if (!success) {
- Log.d(TAG_FLOW, Str.from("emptyDir : Could not delete file:",children[i].toString() ));
- return false;
- }
- }
- Log.d(TAG_FLOW, Str.from("emptyDir : Deleted all in dir" , dir.toString()));
- return true;
- }
- synchronized private void writeLogCatToFile() {
- Log.d(TAG_FLOW, Str.from( "writeLogCatToFile: Saving LogCat with name : ",currentTestScreenshotsFileName));
- // BufferedWriter logcatFileWriter;
- FileWriter lcFileWriter;
- try {
- Process logcatProcess = Runtime.getRuntime().exec("logcat -d");
- BufferedReader logcatReader = new BufferedReader( new InputStreamReader(logcatProcess.getInputStream()),300);
- String logcatFile = Str.from( externalDirRoot , screenshotsFolderName ,currentTestScreenshotsFileName,".log");
- //logcatFileWriter = new BufferedWriter(new FileWriter(logcatFile, false));
- lcFileWriter = new FileWriter(logcatFile,false);
- String logcatLine ;
- while ((logcatLine = logcatReader.readLine()) != null) {
- lcFileWriter.append(logcatLine);
- lcFileWriter.append('\n');
- lcFileWriter.flush();
- /*
- logcatFileWriter.append(logcatLine);
- logcatFileWriter.append('\n');
- logcatFileWriter.flush();*/
- }
- lcFileWriter.close();
- // logcatFileWriter.close();
- logcatReader.close();
- logcatProcess.waitFor();
- } catch (Exception e) {
- Log.d(TAG_RAW, Str.from("writeLogCatToFile: Error occurred" , e.getMessage()));
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement