How to use readStream method of com.qaprosoft.carina.core.foundation.report.ReportContext class

Best Carina code snippet using com.qaprosoft.carina.core.foundation.report.ReportContext.readStream

Source:ReportContext.java Github

copy

Full Screen

...245 String basicAuthPayload = "Basic " + Base64.getEncoder().encodeToString(usernameColonPassword.getBytes());246 con.addRequestProperty("Authorization", basicAuthPayload);247 }248 int responseCode = con.getResponseCode();249 String responseBody = readStream(con.getInputStream());250 if (responseCode == HttpURLConnection.HTTP_NOT_FOUND &&251 responseBody.contains("\"error\":\"invalid session id\",\"message\":\"unknown session")) {252 throw new RuntimeException("Invalid session id. Something wrong with driver");253 }254 if (responseCode == HttpURLConnection.HTTP_OK) {255 String hrefAttributePattern = "href=([\"'])((?:(?!\\1)[^\\\\]|(?:\\\\\\\\)*\\\\[^\\\\])*)\\1";256 Pattern pattern = Pattern.compile(hrefAttributePattern);257 Matcher matcher = pattern.matcher(responseBody);258 while (matcher.find()) {259 if (!artifactNames.contains(matcher.group(2))) {260 artifactNames.add(matcher.group(2));261 }262 }263 }264 } catch (IOException e) {265 LOGGER.debug("Something went wrong when try to get artifacts from remote", e);266 } 267 return artifactNames;268 }269 270 /**271 * Get artifacts from auto download folder of local or remove driver session by pattern272 * 273 * @param driver WebDriver274 * @param pattern String - regex for artifacts 275 * @return list of artifact files276 */277 public static List<File> getArtifacts(WebDriver driver, String pattern) {278 List<String> filteredFilesNames = listArtifacts(driver)279 .stream()280 // ignore directories281 .filter(fileName -> !fileName.endsWith("/"))282 .filter(fileName -> fileName.matches(pattern))283 .collect(Collectors.toList());284 List<File> artifacts = new ArrayList<>();285 for (String fileName : filteredFilesNames) {286 artifacts287 .add(getArtifact(driver, fileName));288 }289 return artifacts;290 } 291 /**292 * Get artifact from auto download folder of local or remove driver session by name293 * 294 * @param driver WebDriver295 * @param name String - filename with extension296 * @return artifact File297 */298 public static File getArtifact(WebDriver driver, String name) {299 File file = new File(getArtifactsFolder() + File.separator + name);300 if (file.exists()) {301 return file;302 }303 304 String path = file.getAbsolutePath();305 LOGGER.debug("artifact file to download: " + path);306 String url = getUrl(driver, name);307 String username = getField(url, 1);308 String password = getField(url, 2);309 310 if (!username.isEmpty() && !password.isEmpty()) {311 Authenticator.setDefault(new CustomAuthenticator(username, password));312 } 313 if (checkArtifactUsingHttp(url, username, password)) {314 try {315 FileUtils.copyURLToFile(new URL(url), file);316 LOGGER.debug("Successfully downloaded artifact: {}", name);317 } catch (IOException e) {318 LOGGER.error("Artifact: " + url + " wasn't downloaded to " + path, e);319 }320 } else {321 Assert.fail("Unable to find artifact: " + name);322 }323 // publish as test artifact to Zebrunner Reporting324 Artifact.attachToTest(name, file); 325 return file;326 }327 /**328 * check if artifact exists using http329 * 330 * @param url String331 * @param username String332 * @param password String333 * @return boolean334 */335 private static boolean checkArtifactUsingHttp(String url, String username, String password) {336 try {337 HttpURLConnection.setFollowRedirects(false);338 // note : you may also need339 // HttpURLConnection.setInstanceFollowRedirects(false)340 HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();341 con.setRequestMethod("HEAD");342 if (!username.isEmpty() && !password.isEmpty()) {343 String usernameColonPassword = username + ":" + password;344 String basicAuthPayload = "Basic " + Base64.getEncoder().encodeToString(usernameColonPassword.getBytes());345 con.addRequestProperty("Authorization", basicAuthPayload);346 }347 return (con.getResponseCode() == HttpURLConnection.HTTP_OK);348 } catch (Exception e) {349 LOGGER.debug("Artifact doesn't exist: " + url, e);350 return false;351 }352 }353 /**354 * get username or password from url355 * 356 * @param url String357 * @param position int358 * @return String359 */360 private static String getField(String url, int position) {361 Pattern pattern = Pattern.compile(".*:\\/\\/(.*):(.*)@");362 Matcher matcher = pattern.matcher(url);363 return matcher.find() ? matcher.group(position) : "";364 }365 366 /**367 * Generate file in artifacts location and register in Zebrunner Reporting368 * 369 * @param name String370 * @param source InputStream371 */ 372 public static void saveArtifact(String name, InputStream source) throws IOException {373 File artifact = new File(String.format("%s/%s", getArtifactsFolder(), name));374 artifact.createNewFile();375 FileUtils.writeByteArrayToFile(artifact, IOUtils.toByteArray(source));376 377 Artifact.attachToTest(name, IOUtils.toByteArray(source));378 }379 /**380 * Copy file into artifacts location and register in Zebrunner Reporting381 * @param source File382 */ 383 public static void saveArtifact(File source) throws IOException {384 File artifact = new File(String.format("%s/%s", getArtifactsFolder(), source.getName()));385 artifact.createNewFile();386 FileUtils.copyFile(source, artifact);387 388 Artifact.attachToTest(source.getName(), artifact);389 } 390 /**391 * generate url for artifact by name392 * 393 * @param driver WebDriver394 * @param name String395 * @return String396 */397 private static String getUrl(WebDriver driver, String name) {398 String seleniumHost = Configuration.getSeleniumUrl().replace("wd/hub", "download/");399 WebDriver drv = (driver instanceof EventFiringWebDriver) ? ((EventFiringWebDriver) driver).getWrappedDriver() : driver;400 String sessionId = ((RemoteWebDriver) drv).getSessionId().toString();401 String url = seleniumHost + sessionId + "/" + name;402 LOGGER.debug("url: " + url);403 return url;404 }405 private static void stopThreadLogAppender() {406 try {407 LoggerContext loggerContext = (LoggerContext) LogManager.getContext(true);408 ThreadLogAppender appender = loggerContext.getConfiguration().getAppender("ThreadLogAppender");;409 if (appender != null) {410 appender.stop();411 }412 } catch (Exception e) {413 LOGGER.error("Exception while closing thread log appender.", e);414 }415 }416 private static File renameTestDir(String test) {417 File testDir = testDirectory.get();418 initIsCustomTestDir();419 if (testDir != null && !isCustomTestDirName.get()) {420 File newTestDir = new File(String.format("%s/%s", getBaseDir(), test.replaceAll("[^a-zA-Z0-9.-]", "_")));421 if (!newTestDir.exists()) {422 boolean isRenamed = false;423 int retry = 5;424 while (!isRenamed && retry > 0) {425 // close ThreadLogAppender resources before renaming426 stopThreadLogAppender();427 isRenamed = testDir.renameTo(newTestDir);428 if (!isRenamed) {429 CommonUtils.pause(1);430 System.err.println("renaming failed to '" + newTestDir + "'");431 }432 retry--;433 }434 435 if (isRenamed) {436 testDirectory.set(newTestDir);437 System.out.println("Test directory renamed to '" + newTestDir + "'");438 }439 }440 } else {441 LOGGER.error("Unexpected case with absence of test.log for '" + test + "'");442 }443 return testDir;444 }445 private static void initIsCustomTestDir() {446 if (isCustomTestDirName.get() == null) {447 isCustomTestDirName.set(Boolean.FALSE);448 }449 ;450 }451 /**452 * Removes emailable html report and oldest screenshots directories according to history size defined in config.453 */454 private static void removeOldReports() {455 File baseDir = new File(String.format("%s/%s", System.getProperty("user.dir"),456 Configuration.get(Parameter.PROJECT_REPORT_DIRECTORY)));457 if (baseDir.exists()) {458 // remove old emailable report459 File reportFile = new File(String.format("%s/%s/%s", System.getProperty("user.dir"),460 Configuration.get(Parameter.PROJECT_REPORT_DIRECTORY), SpecialKeywords.HTML_REPORT));461 if (reportFile.exists()) {462 reportFile.delete();463 }464 List<File> files = FileManager.getFilesInDir(baseDir);465 List<File> screenshotFolders = new ArrayList<File>();466 for (File file : files) {467 if (file.isDirectory() && !file.getName().startsWith(".")) {468 screenshotFolders.add(file);469 }470 }471 int maxHistory = Configuration.getInt(Parameter.MAX_SCREENSHOOT_HISTORY);472 if (maxHistory > 0 && screenshotFolders.size() + 1 > maxHistory) {473 Comparator<File> comp = new Comparator<File>() {474 @Override475 public int compare(File file1, File file2) {476 return file2.getName().compareTo(file1.getName());477 }478 };479 Collections.sort(screenshotFolders, comp);480 for (int i = maxHistory - 1; i < screenshotFolders.size(); i++) {481 if (screenshotFolders.get(i).getName().equals("gallery-lib")) {482 continue;483 }484 try {485 FileUtils.deleteDirectory(screenshotFolders.get(i));486 } catch (IOException e) {487 System.out.println((e + "\n" + e.getMessage()));488 }489 }490 }491 }492 }493 public static void generateHtmlReport(String content) {494 String emailableReport = SpecialKeywords.HTML_REPORT;495 File reportFile = new File(String.format("%s/%s/%s", System.getProperty("user.dir"),496 Configuration.get(Parameter.PROJECT_REPORT_DIRECTORY), emailableReport));497 File reportFileToBaseDir = new File(String.format("%s/%s", getBaseDir(), emailableReport));498 try (FileWriter reportFileWriter = new FileWriter(reportFile.getAbsoluteFile());499 BufferedWriter reportBufferedWriter = new BufferedWriter(reportFileWriter);500 FileWriter baseDirFileWriter = new FileWriter(reportFileToBaseDir.getAbsolutePath());501 BufferedWriter baseDirBufferedWriter = new BufferedWriter(baseDirFileWriter)) {502 createNewFileIfNotExists(reportFile);503 reportBufferedWriter.write(content);504 createNewFileIfNotExists(reportFileToBaseDir);505 baseDirBufferedWriter.write(content);506 } catch (IOException e) {507 LOGGER.error("generateHtmlReport failure", e);508 }509 }510 private static void createNewFileIfNotExists(File file) throws IOException {511 if (!file.exists()) {512 boolean isCreated = file.createNewFile();513 if (!isCreated) {514 throw new RuntimeException("File not created: " + file.getAbsolutePath());515 }516 }517 }518 /**519 * Returns URL for test artifacts folder.520 * 521 * @return - URL for test screenshot folder.522 */523 public static String getTestArtifactsLink() {524 String link = "";525 if (!Configuration.get(Parameter.REPORT_URL).isEmpty()) {526 link = String.format("%s/%d/artifacts", Configuration.get(Parameter.REPORT_URL), rootID);527 } else {528 link = String.format("file://%s/artifacts", getBaseDirAbsolutePath());529 }530 return link;531 }532 /**533 * Returns URL for test screenshot folder.534 * 535 * @return - URL for test screenshot folder.536 */537 public static String getTestScreenshotsLink() {538 String link = "";539 try {540 if (FileUtils.listFiles(ReportContext.getTestDir(), new String[] { "png" }, false).isEmpty()) {541 // no png screenshot files at all542 return link;543 }544 } catch (Exception e) {545 LOGGER.error("Exception during report directory scanning", e);546 }547 548 String test = testDirectory.get().getName().replaceAll("[^a-zA-Z0-9.-]", "_");549 550 if (!Configuration.get(Parameter.REPORT_URL).isEmpty()) {551 link = String.format("%s/%d/%s/report.html", Configuration.get(Parameter.REPORT_URL), rootID, test);552 } else {553 link = String.format("file://%s/%s/report.html", getBaseDirAbsolutePath(), test);554 }555 return link;556 }557 /**558 * Returns URL for test log.559 * @return - URL to test log folder.560 */561 public static String getTestLogLink() {562 String link = "";563 File testLogFile = new File(ReportContext.getTestDir() + "/" + "test.log");564 if (!testLogFile.exists()) {565 // no test.log file at all566 return link;567 }568 String test = testDirectory.get().getName().replaceAll("[^a-zA-Z0-9.-]", "_");569 if (!Configuration.get(Parameter.REPORT_URL).isEmpty()) {570 link = String.format("%s/%d/%s/test.log", Configuration.get(Parameter.REPORT_URL), rootID, test);571 } else {572 link = String.format("file://%s/%s/test.log", getBaseDirAbsolutePath(), test);573 }574 return link;575 }576 /**577 * Returns URL for cucumber report.578 * 579 * @return - URL to test log folder.580 */581 public static String getCucumberReportLink() {582 String folder = SpecialKeywords.CUCUMBER_REPORT_FOLDER;583 String subFolder = SpecialKeywords.CUCUMBER_REPORT_SUBFOLDER;584 String fileName = SpecialKeywords.CUCUMBER_REPORT_FILE_NAME;585 String link = "";586 if (!Configuration.get(Parameter.REPORT_URL).isEmpty()) {587 // remove report url and make link relative588 // link = String.format("./%d/report.html", rootID);589 String report_url = Configuration.get(Parameter.REPORT_URL);590 if (report_url.contains("n/a")) {591 LOGGER.error("Contains n/a. Replace it.");592 report_url = report_url.replace("n/a", "");593 }594 link = String.format("%s/%d/%s/%s/%s", report_url, rootID, folder, subFolder, fileName);595 } else {596 link = String.format("file://%s/%s/%s/%s", getBaseDirAbsolutePath(), folder, subFolder, fileName);597 }598 return link;599 }600 /**601 * Saves screenshot.602 * 603 * @param screenshot - {@link BufferedImage} file to save604 * 605 * @return - screenshot name.606 */607 public static String saveScreenshot(BufferedImage screenshot) {608 long now = System.currentTimeMillis();609 executor.execute(new ImageSaverTask(screenshot, String.format("%s/%d.png", getTestDir().getAbsolutePath(), now),610 Configuration.getInt(Parameter.BIG_SCREEN_WIDTH), Configuration.getInt(Parameter.BIG_SCREEN_HEIGHT)));611 return String.format("%d.png", now);612 }613 /**614 * Asynchronous image saver task.615 */616 private static class ImageSaverTask implements Runnable {617 private BufferedImage image;618 private String path;619 private Integer width;620 private Integer height;621 public ImageSaverTask(BufferedImage image, String path, Integer width, Integer height) {622 this.image = image;623 this.path = path;624 this.width = width;625 this.height = height;626 }627 @Override628 public void run() {629 try {630 if (width > 0 && height > 0) {631 BufferedImage resizedImage = Scalr.resize(image, Scalr.Method.BALANCED, Scalr.Mode.FIT_TO_WIDTH, width, height,632 Scalr.OP_ANTIALIAS);633 if (resizedImage.getHeight() > height) {634 resizedImage = Scalr.crop(resizedImage, resizedImage.getWidth(), height);635 }636 ImageIO.write(resizedImage, "PNG", new File(path));637 } else {638 ImageIO.write(image, "PNG", new File(path));639 }640 } catch (Exception e) {641 LOGGER.error("Unable to save screenshot: " + e.getMessage());642 }643 }644 }645 private static void copyGalleryLib() {646 File reportsRootDir = new File(System.getProperty("user.dir") + "/" + Configuration.get(Parameter.PROJECT_REPORT_DIRECTORY));647 if (!new File(reportsRootDir.getAbsolutePath() + "/gallery-lib").exists()) {648 try {649 InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream(GALLERY_ZIP);650 if (is == null) {651 System.out.println("Unable to find in classpath: " + GALLERY_ZIP);652 return;653 }654 ZipManager.copyInputStream(is, new BufferedOutputStream(new FileOutputStream(reportsRootDir.getAbsolutePath() + "/"655 + GALLERY_ZIP)));656 ZipManager.unzip(reportsRootDir.getAbsolutePath() + "/" + GALLERY_ZIP, reportsRootDir.getAbsolutePath());657 File zip = new File(reportsRootDir.getAbsolutePath() + "/" + GALLERY_ZIP);658 zip.delete();659 } catch (Exception e) {660 System.out.println("Unable to copyGalleryLib! " + e);661 }662 }663 }664 public static void generateTestReport() {665 File testDir = testDirectory.get();666 try {667 List<File> images = FileManager.getFilesInDir(testDir);668 List<String> imgNames = new ArrayList<String>();669 for (File image : images) {670 imgNames.add(image.getName());671 }672 imgNames.remove("test.log");673 imgNames.remove("sql.log");674 if (imgNames.size() == 0)675 return;676 Collections.sort(imgNames);677 StringBuilder report = new StringBuilder();678 for (int i = 0; i < imgNames.size(); i++) {679 // convert toString680 String image = R.REPORT.get("image");681 image = image.replace("${image}", imgNames.get(i));682 String title = getScreenshotComment(imgNames.get(i));683 if (title == null) {684 title = "";685 }686 image = image.replace("${title}", StringUtils.substring(title, 0, MAX_IMAGE_TITLE));687 report.append(image);688 }689 // String wholeReport = R.REPORT.get("container").replace("${images}", report.toString());690 String wholeReport = R.REPORT.get("container").replace("${images}", report.toString());691 wholeReport = wholeReport.replace("${title}", TITLE);692 String folder = testDir.getAbsolutePath();693 FileManager.createFileWithContent(folder + REPORT_NAME, wholeReport);694 } catch (Exception e) {695 LOGGER.error("generateTestReport failure", e);696 }697 }698 /**699 * Stores comment for screenshot.700 *701 * @param screenId screenId id702 * @param msg message703 * 704 */705 public static void addScreenshotComment(String screenId, String msg) {706 if (!StringUtils.isEmpty(screenId)) {707 screenSteps.put(screenId, msg);708 }709 }710 /**711 * Return comment for screenshot.712 * 713 * @param screenId Screen Id714 * 715 * @return screenshot comment716 */717 public static String getScreenshotComment(String screenId) {718 String comment = "";719 if (screenSteps.containsKey(screenId))720 comment = screenSteps.get(screenId);721 return comment;722 }723 private static String getBaseDirAbsolutePath() {724 if (baseDirectory != null) {725 return baseDirectory.getAbsolutePath();726 }727 return null;728 }729 730 // Converting InputStream to String731 private static String readStream(InputStream in) {732 BufferedReader reader = null;733 StringBuffer response = new StringBuffer();734 try {735 reader = new BufferedReader(new InputStreamReader(in));736 String line = "";737 while ((line = reader.readLine()) != null) {738 response.append(line);739 }740 } catch (IOException e) {741 // do noting742 } finally {743 if (reader != null) {744 try {745 reader.close();...

Full Screen

Full Screen

readStream

Using AI Code Generation

copy

Full Screen

1import com.qaprosoft.carina.core.foundation.report.ReportContext;2import com.qaprosoft.carina.core.foundation.utils.common.CommonUtils;3import com.qaprosoft.carina.core.foundation.utils.factory.DeviceType;4import com.qaprosoft.carina.core.foundation.utils.factory.DeviceType.DeviceTypeEnum;5import java.io.File;6import java.io.IOException;7import java.nio.file.Files;8import java.nio.file.Path;9import java.nio.file.Paths;10import java.util.stream.Stream;11public class ReportContextExample {12 public static void main(String[] args) throws IOException {13 DeviceType deviceType = new DeviceType(DeviceTypeEnum.MOBILE);14 ReportContext.setDeviceType(deviceType);15 ReportContext.setTestName("TestName");16 ReportContext.setTestDescription("TestDescription");17 ReportContext.setTestAuthor("TestAuthor");18 ReportContext.setTestGroup("TestGroup");19 ReportContext.setTestFeature("TestFeature");20 ReportContext.setTestStory("TestStory");21 ReportContext.setTestType("TestType");22 ReportContext.setTestSeverity("TestSeverity");23 ReportContext.setTestVersion("TestVersion");24 ReportContext.setTestLink("TestLink");25 ReportContext.setTestAttribute("testAttribute", "testAttributeValue");26 ReportContext.setTestAttribute("testAttribute", "testAttributeValue", "testAttributeDescription");27 ReportContext.setTestAttribute("testAttribute", "testAttributeValue", "testAttributeDescription", "testAttributeCategory");28 ReportContext.setTestAttribute("testAttribute", "testAttributeValue", "testAttributeDescription", "testAttributeCategory", "testAttributeStatus");29 ReportContext.setTestAttribute("testAttribute", "testAttributeValue", "testAttributeDescription", "testAttributeCategory", "testAttributeStatus", "testAttributePriority");30 ReportContext.setTestAttribute("testAttribute", "testAttributeValue", "testAttributeDescription", "testAttributeCategory", "testAttributeStatus", "testAttributePriority", "testAttributeScreenShot");31 ReportContext.setTestAttribute("testAttribute", "testAttributeValue", "testAttributeDescription", "testAttributeCategory", "testAttributeStatus", "testAttributePriority", "testAttributeScreenShot", "testAttributeLink");32 ReportContext.setTestAttribute("testAttribute", "testAttributeValue", "testAttributeDescription", "testAttributeCategory", "testAttributeStatus", "testAttributePriority", "testAttributeScreenShot", "testAttributeLink", "testAttributeLinkName");33 ReportContext.setTestAttribute("testAttribute

Full Screen

Full Screen

readStream

Using AI Code Generation

copy

Full Screen

1import com.qaprosoft.carina.core.foundation.report.ReportContext2import com.qaprosoft.carina.core.foundation.report.ReportContext.ReportType3def reportContext = new ReportContext()4def report = reportContext.readStream(ReportType.HTML)5reportContext.getTestName()6reportContext.getTestStatus()7reportContext.getTestStart()8reportContext.getTestEnd()9reportContext.getTestDuration()10reportContext.getTestMessage()11reportContext.getTestAttachments()12reportContext.getTestParameters()13reportContext.getTestSteps()14reportContext.getTestSteps().each {15 it.getStepName()16 it.getStepStatus()17 it.getStepStart()18 it.getStepEnd()19 it.getStepDuration()20 it.getStepMessage()21 it.getStepAttachments()22 it.getStepParameters()23}24reportContext.getReportAsString()25reportContext.getReportAsJson()26reportContext.getReportAsJsonString()27reportContext.getReportAsJson(true)28reportContext.getReportAsJsonString(true)29reportContext.getReportAsJson(false)30reportContext.getReportAsJsonString(false)31reportContext.getReportAsJson(true, 4)32reportContext.getReportAsJsonString(true, 4)33reportContext.getReportAsJson(false, 4)34reportContext.getReportAsJsonString(false, 4)35reportContext.getReportAsXml()36reportContext.getReportAsXmlString()

Full Screen

Full Screen

readStream

Using AI Code Generation

copy

Full Screen

1import org.testng.annotations.DataProvider;2import org.testng.annotations.Test;3import com.qaprosoft.carina.core.foundation.report.ReportContext;4public class ExcelDataProvider {5 public Object[][] readData() {6 return ReportContext.readStream("src/test/resources/test_data.xlsx");7 }8 @Test(dataProvider = "readData")9 public void testMethod(String username, String password) {10 System.out.println("Username: " + username + " Password: " + password);11 }12}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful