com.intuit.karate.FileUtils Java Examples
The following examples show how to use
com.intuit.karate.FileUtils.
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: Consumer.java From karate with MIT License | 7 votes |
public Payment create(Payment payment) { try { HttpURLConnection con = getConnection("/payments"); con.setRequestMethod("POST"); con.setDoOutput(true); con.setRequestProperty("Content-Type", "application/json"); String json = JsonUtils.toJson(payment); IOUtils.write(json, con.getOutputStream(), "utf-8"); int status = con.getResponseCode(); if (status != 200) { throw new RuntimeException("status code was " + status); } String content = FileUtils.toString(con.getInputStream()); return JsonUtils.fromJson(content, Payment.class); } catch (Exception e) { throw new RuntimeException(e); } }
Example #2
Source File: ConvertUtilsTest.java From karate with MIT License | 6 votes |
@Test public void testReadingItemListWithSubItems() { String collectionFileName = "postman-multiple-items-and-sub-items.postman_collection"; InputStream is = getClass().getResourceAsStream(collectionFileName); String json = FileUtils.toString(is); List<PostmanItem> items = PostmanUtils.readPostmanJson(json); logger.debug("list: {}", items); String featureJson = PostmanUtils.toKarateFeature(collectionFileName, items).trim(); assertTrue(featureJson.startsWith("Feature: " + collectionFileName)); // assert feature name assertTrue(featureJson.contains("Scenario: rootItem-1")); // assert scenario names assertTrue(featureJson.contains("Scenario: rootItem-2")); assertTrue(featureJson.contains("Scenario: rootItem-3")); assertTrue(featureJson.contains("# subitem-1-1")); // assert comment for each sub request assertTrue(featureJson.contains("# subitem-1-2")); assertTrue(featureJson.contains("# subitem-2-1")); }
Example #3
Source File: JarLoadingTest.java From karate with MIT License | 6 votes |
@Test public void testRunningFromJarFile() throws Exception { ClassLoader cl = getJarClassLoader1(); Class main = cl.loadClass("demo.jar1.Main"); Method meth = main.getMethod("hello"); Object result = meth.invoke(null); assertEquals("hello world", result); List<Resource> list = FileUtils.scanForFeatureFiles(Collections.singletonList("classpath:demo"), cl); assertEquals(4, list.size()); logger.debug("resources: {}", list); list = FileUtils.scanForFeatureFiles(Collections.singletonList("classpath:demo/jar1/caller.feature"), cl); assertEquals(1, list.size()); Resource resource = list.get(0); assertTrue(FileUtils.isJarPath(resource.getPath().toUri())); Path path = FileUtils.fromRelativeClassPath("classpath:demo/jar1/caller.feature", cl); String relativePath = FileUtils.toRelativeClassPath(path, cl); assertEquals("classpath:demo/jar1/caller.feature", relativePath); Feature feature = FeatureParser.parse(resource); Thread.currentThread().setContextClassLoader(cl); Map<String, Object> map = Runner.runFeature(feature, null, false); assertEquals(true, map.get("success")); }
Example #4
Source File: ChromeWebDriver.java From karate with MIT License | 6 votes |
@Override public void activate() { if (!options.headless) { try { switch (FileUtils.getOsType()) { case MACOSX: Runtime.getRuntime().exec(new String[]{"osascript", "-e", "tell app \"Chrome\" to activate"}); break; default: } } catch (Exception e) { logger.warn("native window switch failed: {}", e.getMessage()); } } }
Example #5
Source File: DockerTarget.java From karate with MIT License | 6 votes |
@Override public Map<String, Object> stop(Logger logger) { Command.execLine(null, "docker stop " + containerId); if (!karateChrome) { // no video Command.execLine(null, "docker rm " + containerId); return Collections.EMPTY_MAP; } String shortName = containerId.contains("_") ? containerId : StringUtils.truncate(containerId, 12, false); String dirName = "karate-chrome_" + shortName; String resultsDir = Command.getBuildDir() + File.separator + dirName; Command.execLine(null, "docker cp " + containerId + ":/tmp " + resultsDir); Command.execLine(null, "docker rm " + containerId); String video = resultsDir + File.separator + "karate.mp4"; File file = new File(video); if (!file.exists()) { logger.warn("video file missing: {}", file); return Collections.EMPTY_MAP; } File copy = new File(Command.getBuildDir() + File.separator + "cucumber-html-reports" + File.separator + dirName + ".mp4"); FileUtils.copy(file, copy); return Collections.singletonMap("video", copy.getName()); }
Example #6
Source File: ResponseLoggingInterceptor.java From karate with MIT License | 6 votes |
@Override public void process(HttpResponse response, HttpContext httpContext) throws HttpException, IOException { HttpRequest actual = context.getPrevRequest(); actual.stopTimer(); int id = requestInterceptor.getCounter().get(); StringBuilder sb = new StringBuilder(); sb.append("response time in milliseconds: ").append(actual.getResponseTimeFormatted()).append('\n'); sb.append(id).append(" < ").append(response.getStatusLine().getStatusCode()).append('\n'); HttpLogModifier responseModifier = logModifier == null ? null : logModifier.enableForUri(actual.getUri()) ? logModifier : null; LoggingUtils.logHeaders(responseModifier, sb, id, '<', response); HttpEntity entity = response.getEntity(); if (LoggingUtils.isPrintable(entity)) { LoggingEntityWrapper wrapper = new LoggingEntityWrapper(entity); String buffer = FileUtils.toString(wrapper.getContent()); if (context.getConfig().isLogPrettyResponse()) { buffer = FileUtils.toPrettyString(buffer); } if (responseModifier != null) { buffer = responseModifier.response(actual.getUri(), buffer); } sb.append(buffer).append('\n'); response.setEntity(wrapper); } context.logger.debug(sb.toString()); }
Example #7
Source File: GatlingJobServer.java From karate with MIT License | 6 votes |
@Override public synchronized void handleUpload(File upload, String executorId, String chunkId) { String karateLog = upload.getPath() + File.separator + "karate.log"; File karateLogFile = new File(karateLog); if (karateLogFile.exists()) { karateLogFile.renameTo(new File(karateLog + ".txt")); } String gatlingReportDir = "target" + File.separator + "reports" + File.separator; File[] dirs = upload.listFiles(); for (File dir : dirs) { if (dir.isDirectory()) { File file = getFirstFileWithExtension(dir, "log"); if (file != null) { FileUtils.copy(file, new File(gatlingReportDir + "simulation_" + chunkId + ".log")); } } } completed.add(executorId); }
Example #8
Source File: DapDecoder.java From karate with MIT License | 6 votes |
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { if (remaining > 0 && in.readableBytes() >= remaining) { out.add(encode(in, remaining)); remaining = 0; } int pos; while ((pos = findCrLfCrLf(in)) != -1) { int delimiterPos = pos; while (in.getByte(--pos) != ':') { // skip backwards } in.readerIndex(++pos); CharSequence lengthString = in.readCharSequence(delimiterPos - pos, FileUtils.UTF8); int length = Integer.valueOf(lengthString.toString().trim()); in.readerIndex(delimiterPos + 4); if (in.readableBytes() >= length) { out.add(encode(in, length)); remaining = 0; } else { remaining = length; } } }
Example #9
Source File: Main.java From karate with MIT License | 6 votes |
public static void main(String[] args) { String command; if (args.length > 0) { command = StringUtils.join(args, ' '); } else { command = System.getProperty("sun.java.command"); } System.out.println("command: " + command); boolean isIntellij = command.contains("org.jetbrains"); RunnerOptions ro = RunnerOptions.parseCommandLine(command); String targetDir = FileUtils.getBuildDir() + File.separator + "surefire-reports"; int debugPort = ro.getDebugPort(); if (debugPort != -1) { DapServer server = new DapServer(debugPort); server.waitSync(); return; } CliExecutionHook hook = new CliExecutionHook(true, targetDir, isIntellij); Runner.path(ro.getFeatures()) .tags(ro.getTags()).scenarioName(ro.getName()) .hook(hook).parallel(ro.getThreads()); }
Example #10
Source File: Demo01JavaRunner.java From karate with MIT License | 6 votes |
@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 #11
Source File: SafariWebDriver.java From karate with MIT License | 6 votes |
@Override public void activate() { if (!options.headless) { try { switch (FileUtils.getOsType()) { case MACOSX: Runtime.getRuntime().exec(new String[]{"osascript", "-e", "tell app \"Safari\" to activate"}); break; default: } } catch (Exception e) { logger.warn("native window switch failed: {}", e.getMessage()); } } }
Example #12
Source File: Karate.java From karate with MIT License | 6 votes |
public Karate(Class<?> clazz) throws InitializationError, IOException { super(clazz); List<FrameworkMethod> testMethods = getTestClass().getAnnotatedMethods(Test.class); if (!testMethods.isEmpty()) { logger.warn("WARNING: there are methods annotated with '@Test', they will NOT be run when using '@RunWith(Karate.class)'"); } RunnerOptions options = RunnerOptions.fromAnnotationAndSystemProperties(clazz); List<Resource> resources = FileUtils.scanForFeatureFiles(options.getFeatures(), clazz.getClassLoader()); children = new ArrayList(resources.size()); featureMap = new HashMap(resources.size()); for (Resource resource : resources) { Feature feature = FeatureParser.parse(resource); feature.setCallName(options.getName()); feature.setCallLine(resource.getLine()); children.add(feature); } tagSelector = Tags.fromKarateOptionsTags(options.getTags()); }
Example #13
Source File: FeatureNode.java From karate with MIT License | 6 votes |
@Override public DynamicTest next() { ScenarioExecutionUnit unit = iterator.next(); return DynamicTest.dynamicTest(unit.scenario.getNameForReport(), () -> { featureUnit.run(unit); boolean failed = unit.result.isFailed(); if (unit.isLast() || failed) { featureUnit.stop(); exec.result.printStats(null); Engine.saveResultHtml(FileUtils.getBuildDir() + File.separator + "surefire-reports", exec.result, null); } if (failed) { Assertions.fail(unit.result.getError().getMessage()); } }); }
Example #14
Source File: Robot.java From karate with MIT License | 6 votes |
public boolean switchTo(String title) { if (title.startsWith("^")) { return switchTo(t -> t.contains(title.substring(1))); } FileUtils.OsType type = FileUtils.getOsType(); switch (type) { case LINUX: return RobotUtils.switchToLinuxOs(title); case MACOSX: return RobotUtils.switchToMacOs(title); case WINDOWS: return RobotUtils.switchToWinOs(title); default: logger.warn("unsupported os: {}", type); return false; } }
Example #15
Source File: MockServerTest.java From karate with MIT License | 5 votes |
private static void generateReport(String karateOutputPath) { Collection<File> jsonFiles = org.apache.commons.io.FileUtils.listFiles(new File(karateOutputPath), new String[]{"json"}, true); List<String> jsonPaths = new ArrayList(jsonFiles.size()); for (File file : jsonFiles) { jsonPaths.add(file.getAbsolutePath()); } Configuration config = new Configuration(new File("target"), "mock"); ReportBuilder reportBuilder = new ReportBuilder(jsonPaths, config); reportBuilder.generateReports(); }
Example #16
Source File: FormRunner.java From karate with MIT License | 5 votes |
@BeforeClass public static void beforeClass() { File file = FileUtils.getFileRelativeTo(MockServerTest.class, "_mock.feature"); server = FeatureServer.start(file, 0, false, null); int port = server.getPort(); System.setProperty("karate.server.port", port + ""); }
Example #17
Source File: DownloadRunner.java From karate with MIT License | 5 votes |
@BeforeClass public static void beforeClass() { File file = FileUtils.getFileRelativeTo(MockServerTest.class, "_mock.feature"); server = FeatureServer.start(file, 0, false, null); int port = server.getPort(); System.setProperty("karate.server.port", port + ""); }
Example #18
Source File: MalformedRunner.java From karate with MIT License | 5 votes |
@BeforeClass public static void beforeClass() { File file = FileUtils.getFileRelativeTo(MockServerTest.class, "_mock.feature"); server = FeatureServer.start(file, 0, false, null); int port = server.getPort(); System.setProperty("karate.server.port", port + ""); }
Example #19
Source File: FileLogAppender.java From karate with MIT License | 5 votes |
@Override public String collect() { try { int pos = (int) channel.position(); ByteBuffer buf = ByteBuffer.allocate(pos - prevPos); channel.read(buf, prevPos); prevPos = pos; ((Buffer) buf).flip(); // java 8 to 9 fix return FileUtils.toString(buf.array()); } catch (Exception e) { throw new RuntimeException(e); } }
Example #20
Source File: HeadersRunner.java From karate with MIT License | 5 votes |
@BeforeClass public static void beforeClass() { File file = FileUtils.getFileRelativeTo(MockServerTest.class, "_mock.feature"); server = FeatureServer.start(file, 0, false, null); int port = server.getPort(); System.setProperty("karate.server.port", port + ""); }
Example #21
Source File: FileLogAppender.java From karate with MIT License | 5 votes |
@Override public void append(String text) { if (closed) { return; } try { channel.write(ByteBuffer.wrap(text.getBytes(FileUtils.UTF8))); } catch (Exception e) { throw new RuntimeException(e); } }
Example #22
Source File: Chrome.java From karate with MIT License | 5 votes |
public static Chrome start(ScenarioContext context, Map<String, Object> map, LogAppender appender) { DriverOptions options = new DriverOptions(context, map, appender, 9222, FileUtils.isOsWindows() ? DEFAULT_PATH_WIN : FileUtils.isOsMacOsX() ? DEFAULT_PATH_MAC : DEFAULT_PATH_LINUX); options.arg("--remote-debugging-port=" + options.port); options.arg("--no-first-run"); options.arg("--user-data-dir=" + options.workingDirPath); options.arg("--disable-popup-blocking"); if (options.headless) { options.arg("--headless"); } Command command = options.startProcess(); Http http = options.getHttp(); Command.waitForHttp(http.urlBase); Http.Response res = http.path("json").get(); if (res.body().asList().isEmpty()) { if (command != null) { command.close(true); } throw new RuntimeException("chrome server returned empty list from " + http.urlBase); } String webSocketUrl = res.jsonPath("get[0] $[?(@.type=='page')].webSocketDebuggerUrl").asString(); Chrome chrome = new Chrome(options, command, webSocketUrl); chrome.activate(); chrome.enablePageEvents(); chrome.enableRuntimeEvents(); chrome.enableTargetEvents(); if (!options.headless) { chrome.initWindowIdAndState(); } return chrome; }
Example #23
Source File: JarLoadingTest.java From karate with MIT License | 5 votes |
@Test public void testFileUtilsForJarFile() throws Exception { File file = new File("src/test/java/common.feature"); assertTrue(!FileUtils.isJarPath(file.toPath().toUri())); ClassLoader cl = getJarClassLoader1(); Class main = cl.loadClass("demo.jar1.Main"); Path path = FileUtils.getPathContaining(main); assertTrue(FileUtils.isJarPath(path.toUri())); String relativePath = FileUtils.toRelativeClassPath(path, cl); assertEquals("classpath:", relativePath); // TODO doesn't matter but fix in future if possible path = FileUtils.fromRelativeClassPath("classpath:demo/jar1", cl); assertEquals(path.toString(), "/demo/jar1"); }
Example #24
Source File: CookiesRunner.java From karate with MIT License | 5 votes |
@BeforeClass public static void beforeClass() { File file = FileUtils.getFileRelativeTo(MockServerTest.class, "_mock.feature"); server = FeatureServer.start(file, 0, false, null); int port = server.getPort(); System.setProperty("karate.server.port", port + ""); }
Example #25
Source File: NoHeadersRunner.java From karate with MIT License | 5 votes |
@BeforeClass public static void beforeClass() { File file = FileUtils.getFileRelativeTo(MockServerTest.class, "_mock.feature"); server = FeatureServer.start(file, 0, false, null); int port = server.getPort(); System.setProperty("karate.server.port", port + ""); }
Example #26
Source File: AllKarateFeaturesTest.java From karate with MIT License | 5 votes |
@Test public void testParsingAllFeaturesInKarate() { List<Resource> files = FileUtils.scanForFeatureFiles(false, "..", null); logger.debug("found files count: {}", files.size()); assertTrue(files.size() > 200); for (Resource file : files) { logger.trace("parsing: {}", file.getRelativePath()); FeatureParser.parse(file); } }
Example #27
Source File: Engine.java From karate with MIT License | 5 votes |
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 #28
Source File: ScenarioResultTest.java From karate with MIT License | 5 votes |
@Test public void testJsonToScenarioResult() { String json = FileUtils.toString(getClass().getResourceAsStream("simple1.json")); List<Map<String, Object>> list = JsonUtils.toJsonDoc(json).read("$[0].elements"); Feature feature = FeatureParser.parse("classpath:com/intuit/karate/core/simple1.feature"); Scenario scenario = feature.getSections().get(0).getScenario(); ScenarioResult sr = new ScenarioResult(scenario, list, true); Match.init(list.get(0)).equalsObject(sr.backgroundToMap()); Match.init(list.get(1)).equalsObject(sr.toMap()); }
Example #29
Source File: PostmanConverterTest.java From karate with MIT License | 5 votes |
@Test public void testSuccess() throws IOException { if (FileUtils.isOsWindows()) { // TODO return; } // create the temp file and dirctory File tempSource = File.createTempFile("karate-postman-input", ".postman_collection.json"); tempSource.deleteOnExit(); Path tempOutput = Files.createTempDirectory("karate-postman-output"); tempOutput.toFile().deleteOnExit(); // populate the temp source file with the Postman export data InputStream is = getClass().getResourceAsStream("postman-echo-single.postman_collection"); String postman = FileUtils.toString(is); Files.write(Paths.get(tempSource.toURI()), postman.getBytes()); // perform the conversion boolean successful = new PostmanConverter().convert(tempSource.toString(), tempOutput.toString()); Assert.assertTrue(successful); // load the expected output from the resources is = getClass().getResourceAsStream("expected-converted.txt"); String expectedConverted = FileUtils.toString(is); // load the actual output form the disk Path actualOutputPath = Paths.get(tempOutput.toString(), tempSource.getName().replace(".postman_collection.json", "") + ".feature"); String converted = new String(Files.readAllBytes(actualOutputPath), StandardCharsets.UTF_8); // the first line is dynamic, as it contains the temp dir characters Assert.assertTrue(converted.startsWith("Feature: karate-postman-input")); // trim the file so it doesn't contain the line starting with 'Feature': String convertedTrimmed = Arrays.stream(converted.split(System.lineSeparator())) .filter(line -> !line.startsWith("Feature:")) .collect(Collectors.joining(System.lineSeparator())); // assert that the trimmed actual output equals the trimmed expected output Assert.assertEquals(convertedTrimmed.trim(), expectedConverted.trim()); }
Example #30
Source File: RequestLoggingInterceptor.java From karate with MIT License | 5 votes |
@Override public void process(org.apache.http.HttpRequest request, HttpContext httpContext) throws HttpException, IOException { HttpRequest actual = new HttpRequest(); int id = counter.incrementAndGet(); String uri = (String) httpContext.getAttribute(ApacheHttpClient.URI_CONTEXT_KEY); String method = request.getRequestLine().getMethod(); actual.setUri(uri); actual.setMethod(method); StringBuilder sb = new StringBuilder(); sb.append("request:\n").append(id).append(" > ").append(method).append(' ').append(uri).append('\n'); HttpLogModifier requestModifier = logModifier == null ? null : logModifier.enableForUri(uri) ? logModifier : null; LoggingUtils.logHeaders(requestModifier, sb, id, '>', request, actual); if (request instanceof HttpEntityEnclosingRequest) { HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request; HttpEntity entity = entityRequest.getEntity(); if (LoggingUtils.isPrintable(entity)) { LoggingEntityWrapper wrapper = new LoggingEntityWrapper(entity); // todo optimize, preserve if stream String buffer = FileUtils.toString(wrapper.getContent()); if (context.getConfig().isLogPrettyRequest()) { buffer = FileUtils.toPrettyString(buffer); } if (requestModifier != null) { buffer = requestModifier.request(uri, buffer); } sb.append(buffer).append('\n'); actual.setBody(wrapper.getBytes()); entityRequest.setEntity(wrapper); } } context.setPrevRequest(actual); context.logger.debug(sb.toString()); actual.startTimer(); }