Java Code Examples for com.intuit.karate.FileUtils#writeToFile()

The following examples show how to use com.intuit.karate.FileUtils#writeToFile() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Demo01JavaRunner.java    From karate with MIT License 6 votes vote down vote up
@Test
public void testChrome() throws Exception {
    
    Chrome driver = Chrome.start();        
    driver.setUrl("https://github.com/login");
    driver.input("#login_field", "dummy");
    driver.input("#password", "world");
    driver.submit().click("input[name=commit]");
    String html = driver.html("#js-flash-container");
    assertTrue(html.contains("Incorrect username or password."));
    driver.setUrl("https://google.com");
    driver.input("input[name=q]", "karate dsl");
    driver.submit().click("input[name=btnI]");
    assertEquals("https://github.com/intuit/karate", driver.getUrl());
    byte[] bytes = driver.screenshot();
    // byte[] bytes = driver.screenshotFull();
    FileUtils.writeToFile(new File("target/screenshot.png"), bytes);        
    driver.quit();
}
 
Example 2
Source File: LargePayloadRunner.java    From karate with MIT License 6 votes vote down vote up
@BeforeClass
public static void createLargeXml() {
    Document doc = XmlUtils.toXmlDoc("<ProcessRequest xmlns=\"http://someservice.com/someProcess\"/>");
    Element root = doc.getDocumentElement();        
    Element test = doc.createElement("statusCode");
    test.setTextContent("changeme");
    root.appendChild(test);
    Element foo = doc.createElement("foo");
    root.appendChild(foo);
    for (int i = 0; i < 1000000; i++) {
        Element bar = doc.createElement("bar");
        bar.setTextContent("baz" + i);
        foo.appendChild(bar);
    }
    String xml = XmlUtils.toString(doc);
    byte[] bytes = FileUtils.toBytes(xml);
    int size = bytes.length;
    logger.debug("xml byte count: " + size);
    FileUtils.writeToFile(new File("target/large.xml"), xml);
}
 
Example 3
Source File: ChromePdfRunner.java    From karate with MIT License 5 votes vote down vote up
public static void main(String[] args) {
    Chrome chrome = Chrome.startHeadless();
    chrome.setUrl("https://github.com/login");
    byte[] bytes = chrome.pdf(Collections.EMPTY_MAP);
    FileUtils.writeToFile(new File("target/github.pdf"), bytes);
    bytes = chrome.screenshot();
    FileUtils.writeToFile(new File("target/github.png"), bytes);
    chrome.quit();
}
 
Example 4
Source File: ChromeFullPageRunner.java    From karate with MIT License 5 votes vote down vote up
@Test
public void testChrome() throws Exception {
    Chrome chrome = Chrome.startHeadless();
    chrome.setUrl("https://github.com/intuit/karate/graphs/contributors");
    byte[] bytes = chrome.pdf(Collections.EMPTY_MAP);
    FileUtils.writeToFile(new File("target/fullscreen.pdf"), bytes);
    bytes = chrome.screenshot(true);
    FileUtils.writeToFile(new File("target/fullscreen.png"), bytes);
    chrome.quit();
}
 
Example 5
Source File: DapServer.java    From karate with MIT License 5 votes vote down vote up
public DapServer(int requestedPort) {
    bossGroup = new NioEventLoopGroup(1);
    workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                // .handler(new LoggingHandler(getClass().getName(), LogLevel.TRACE))
                .childHandler(new ChannelInitializer() {
                    @Override
                    protected void initChannel(Channel c) {
                        ChannelPipeline p = c.pipeline();
                        p.addLast(new DapDecoder());
                        p.addLast(new DapEncoder());
                        p.addLast(new DapServerHandler(DapServer.this));
                    }
                });
        channel = b.bind(requestedPort).sync().channel();
        InetSocketAddress isa = (InetSocketAddress) channel.localAddress();
        host = "127.0.0.1"; //isa.getHostString();
        port = isa.getPort();
        logger.info("debug server started on port: {}", port);
        String buildDir = FileUtils.getBuildDir();
        FileUtils.writeToFile(new File(buildDir + File.separator + "karate-debug-port.txt"), port + "");
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 6
Source File: JobExecutor.java    From karate with MIT License 5 votes vote down vote up
private JobExecutor(String serverUrl) {
    this.serverUrl = serverUrl;
    String targetDir = FileUtils.getBuildDir();
    appender = new FileLogAppender(new File(targetDir + File.separator + "karate-executor.log"));
    logger = new Logger();
    logger.setAppender(appender);
    if (!Command.waitForHttp(serverUrl)) {
        logger.error("unable to connect to server, aborting");
        System.exit(1);
    }
    http = Http.forUrl(appender, serverUrl);
    http.config("lowerCaseResponseHeaders", "true");
    // download ============================================================
    JobMessage download = invokeServer(new JobMessage("download"));
    logger.info("download response: {}", download);
    jobId = download.getJobId();
    executorId = download.getExecutorId();
    workingDir = FileUtils.getBuildDir() + File.separator + jobId + "_" + executorId;
    byte[] bytes = download.getBytes();
    File file = new File(workingDir + ".zip");
    FileUtils.writeToFile(file, bytes);
    JobUtils.unzip(file, new File(workingDir));
    logger.info("download done: {}", workingDir);
    // init ================================================================
    JobMessage init = invokeServer(new JobMessage("init").put("log", appender.collect()));
    logger.info("init response: {}", init);
    uploadDir = workingDir + File.separator + init.get(JobContext.UPLOAD_DIR, String.class);
    List<JobCommand> startupCommands = init.getCommands("startupCommands");
    environment = init.get("environment", Map.class);
    executeCommands(startupCommands, environment);
    shutdownCommands = init.getCommands("shutdownCommands");
    logger.info("init done");        
}
 
Example 7
Source File: JobExecutor.java    From karate with MIT License 5 votes vote down vote up
private void loopNext() {
    do {
        File uploadDirFile = new File(uploadDir);
        uploadDirFile.mkdirs();
        JobMessage req = new JobMessage("next")
                .put(JobContext.UPLOAD_DIR, uploadDirFile.getAbsolutePath());
        req.setChunkId(chunkId);
        JobMessage res = invokeServer(req);
        if (res.is("stop")) {
            logger.info("stop received, shutting down");
            break;
        }
        chunkId = res.getChunkId();
        executeCommands(res.getCommands("preCommands"), environment);
        executeCommands(res.getCommands("mainCommands"), environment);
        stopBackgroundCommands();
        executeCommands(res.getCommands("postCommands"), environment);
        String log = appender.collect();
        File logFile = new File(uploadDir + File.separator + "karate.log");
        FileUtils.writeToFile(logFile, log);
        String zipBase = uploadDir + "_" + chunkId;
        File toZip = new File(zipBase);
        uploadDirFile.renameTo(toZip);
        File toUpload = new File(zipBase + ".zip");
        JobUtils.zip(toZip, toUpload);
        byte[] upload = toBytes(toUpload);
        req = new JobMessage("upload");
        req.setChunkId(chunkId);
        req.setBytes(upload);
        invokeServer(req);
    } while (true);
}
 
Example 8
Source File: JobServer.java    From karate with MIT License 5 votes vote down vote up
protected void handleUpload(byte[] bytes, String executorId, String chunkId) {
    String chunkBasePath = basePath + File.separator + executorId + File.separator + chunkId;
    File zipFile = new File(chunkBasePath + ".zip");
    FileUtils.writeToFile(zipFile, bytes);
    File upload = new File(chunkBasePath);
    JobUtils.unzip(zipFile, upload);
    handleUpload(upload, executorId, chunkId);
}
 
Example 9
Source File: Engine.java    From karate with MIT License 5 votes vote down vote up
public static File saveResultJson(String targetDir, FeatureResult result, String fileName) {
    List<Map> single = Collections.singletonList(result.toMap());
    String json = JsonUtils.toJson(single);
    if (fileName == null) {
        fileName = result.getPackageQualifiedName() + ".json";
    }
    File file = new File(targetDir + File.separator + fileName);
    FileUtils.writeToFile(file, json);
    return file;
}
 
Example 10
Source File: Engine.java    From karate with MIT License 5 votes vote down vote up
public static File saveResultHtml(String targetDir, FeatureResult result, String fileName) {
    DecimalFormat formatter = (DecimalFormat) NumberFormat.getNumberInstance(Locale.US);
    formatter.applyPattern("0.######");
    String html = getClasspathResource("report-template.html");
    String img = getClasspathResource("karate-logo.svg");
    Node svg = XmlUtils.toXmlDoc(img);
    String js = getClasspathResource("report-template-js.txt");
    Document doc = XmlUtils.toXmlDoc(html);
    XmlUtils.setByPath(doc, "/html/body/img", svg);
    String baseName = result.getPackageQualifiedName();
    set(doc, "/html/head/title", baseName);
    set(doc, "/html/head/script", js);
    for (ScenarioResult sr : result.getScenarioResults()) {
        Node scenarioDiv = div(doc, "scenario");
        append(doc, "/html/body/div", scenarioDiv);
        Node scenarioHeadingDiv = div(doc, "scenario-heading",
                node(doc, "span", "scenario-keyword", sr.getScenario().getKeyword() + ": " + sr.getScenario().getDisplayMeta()),
                node(doc, "span", "scenario-name", sr.getScenario().getName()));
        scenarioDiv.appendChild(scenarioHeadingDiv);
        for (StepResult stepResult : sr.getStepResults()) {
            stepHtml(doc, formatter, stepResult, scenarioDiv);
        }
    }
    if (fileName == null) {
        fileName = baseName + ".html";
    }
    File file = new File(targetDir + File.separator + fileName);
    String xml = "<!DOCTYPE html>\n" + XmlUtils.toString(doc, false);
    try {
        FileUtils.writeToFile(file, xml);
        System.out.println("\nHTML report: (paste into browser to view) | Karate version: "
                + FileUtils.getKarateVersion() + "\n"
                + file.toURI()
                + "\n---------------------------------------------------------\n");
    } catch (Exception e) {
        System.out.println("html report output failed: " + e.getMessage());
    }
    return file;
}
 
Example 11
Source File: Engine.java    From karate with MIT License 5 votes vote down vote up
public static File saveStatsJson(String targetDir, Results results, String fileName) {
    String json = JsonUtils.toJson(results.toMap());
    if (fileName == null) {
        fileName = "results-json.txt";
    }
    File file = new File(targetDir + File.separator + fileName);
    FileUtils.writeToFile(file, json);
    return file;
}
 
Example 12
Source File: ScriptBridge.java    From karate with MIT License 5 votes vote down vote up
public File write(Object o, String path) {
    ScriptValue sv = new ScriptValue(o);
    path = FileUtils.getBuildDir() + File.separator + path;
    File file = new File(path);
    FileUtils.writeToFile(file, sv.getAsByteArray());
    return file;
}
 
Example 13
Source File: Engine.java    From karate with MIT License 4 votes vote down vote up
public static File saveResultXml(String targetDir, FeatureResult result, String fileName) {
    DecimalFormat formatter = (DecimalFormat) NumberFormat.getNumberInstance(Locale.US);
    formatter.applyPattern("0.######");
    Document doc = XmlUtils.newDocument();
    Element root = doc.createElement("testsuite");
    doc.appendChild(root);
    root.setAttribute("name", result.getDisplayUri()); // will be uri
    root.setAttribute("skipped", "0");
    String baseName = result.getPackageQualifiedName();
    int testCount = 0;
    int failureCount = 0;
    long totalDuration = 0;
    Throwable error;
    Iterator<ScenarioResult> iterator = result.getScenarioResults().iterator();
    StringBuilder sb = new StringBuilder();
    while (iterator.hasNext()) {
        ScenarioResult sr = iterator.next();
        totalDuration += sr.getDurationNanos();
        if (sr.isFailed()) {
            failureCount++;
        }
        Element testCase = doc.createElement("testcase");
        root.appendChild(testCase);
        testCase.setAttribute("classname", baseName);
        testCount++;
        long duration = sr.getDurationNanos();
        error = appendSteps(sr.getStepResults(), sb);
        String name = sr.getScenario().getName();
        if (StringUtils.isBlank(name)) {
            name = testCount + "";
        }
        testCase.setAttribute("name", name);
        testCase.setAttribute("time", formatNanos(duration, formatter));
        Element stepsHolder;
        if (error != null) {
            stepsHolder = doc.createElement("failure");
            stepsHolder.setAttribute("message", error.getMessage());
        } else {
            stepsHolder = doc.createElement("system-out");
        }
        testCase.appendChild(stepsHolder);
        stepsHolder.setTextContent(sb.toString());
    }
    root.setAttribute("tests", testCount + "");
    root.setAttribute("failures", failureCount + "");
    root.setAttribute("time", formatNanos(totalDuration, formatter));
    String xml = XmlUtils.toString(doc, true);
    if (fileName == null) {
        fileName = baseName + ".xml";
    }
    File file = new File(targetDir + File.separator + fileName);
    FileUtils.writeToFile(file, xml);
    return file;
}
 
Example 14
Source File: Engine.java    From karate with MIT License 4 votes vote down vote up
public static File saveTimelineHtml(String targetDir, Results results, String fileName) {
    Map<String, Integer> groupsMap = new LinkedHashMap();
    List<ScenarioResult> scenarioResults = results.getScenarioResults();
    List<Map> items = new ArrayList(scenarioResults.size());
    int id = 1;
    DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss.SSS");
    for (ScenarioResult sr : scenarioResults) {
        String threadName = sr.getThreadName();
        Integer groupId = groupsMap.get(threadName);
        if (groupId == null) {
            groupId = groupsMap.size() + 1;
            groupsMap.put(threadName, groupId);
        }
        Map<String, Object> item = new LinkedHashMap(7);
        items.add(item);
        item.put("id", id++);
        item.put("group", groupId);
        Scenario s = sr.getScenario();
        String featureName = s.getFeature().getResource().getFileNameWithoutExtension();
        String content = featureName + s.getDisplayMeta();
        item.put("content", content);
        item.put("start", sr.getStartTime());
        item.put("end", sr.getEndTime());
        String startTime = dateFormat.format(new Date(sr.getStartTime()));
        String endTime = dateFormat.format(new Date(sr.getEndTime()));
        content = content + " " + startTime + "-" + endTime;
        String scenarioTitle = StringUtils.trimToEmpty(s.getName());
        if (!scenarioTitle.isEmpty()) {
            content = content + " " + scenarioTitle;
        }
        item.put("title", content);
    }
    List<Map> groups = new ArrayList(groupsMap.size());
    groupsMap.forEach((k, v) -> {
        Map<String, Object> group = new LinkedHashMap(2);
        groups.add(group);
        group.put("id", v);
        group.put("content", k);
    });
    StringBuilder sb = new StringBuilder();
    sb.append("\nvar groups = new vis.DataSet(").append(JsonUtils.toJson(groups)).append(");").append('\n');
    sb.append("var items = new vis.DataSet(").append(JsonUtils.toJson(items)).append(");").append('\n');
    sb.append("var container = document.getElementById('visualization');\n"
            + "var timeline = new vis.Timeline(container);\n"
            + "timeline.setOptions({ groupOrder: 'content' });\n"
            + "timeline.setGroups(groups);\n"
            + "timeline.setItems(items);\n");
    if (fileName == null) {
        fileName = File.separator + "timeline.html";
    }
    File htmlFile = new File(targetDir + fileName);
    String html = getClasspathResource("timeline-template.html");
    html = html.replaceFirst("//timeline//", sb.toString());
    FileUtils.writeToFile(htmlFile, html);
    return htmlFile;
}