Java Code Examples for com.intuit.karate.FileUtils

The following examples show how to use com.intuit.karate.FileUtils. These examples are extracted from open source projects. 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 Project: karate   Source File: Consumer.java    License: MIT License 7 votes vote down vote up
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 Project: karate   Source File: DockerTarget.java    License: MIT License 6 votes vote down vote up
@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 3
Source Project: karate   Source File: Demo01JavaRunner.java    License: 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 4
Source Project: karate   Source File: ConvertUtilsTest.java    License: MIT License 6 votes vote down vote up
@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 5
Source Project: karate   Source File: FeatureNode.java    License: MIT License 6 votes vote down vote up
@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 6
Source Project: karate   Source File: Karate.java    License: MIT License 6 votes vote down vote up
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 7
Source Project: karate   Source File: JarLoadingTest.java    License: MIT License 6 votes vote down vote up
@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 8
Source Project: karate   Source File: ChromeWebDriver.java    License: MIT License 6 votes vote down vote up
@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 9
Source Project: karate   Source File: ResponseLoggingInterceptor.java    License: MIT License 6 votes vote down vote up
@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 10
Source Project: karate   Source File: GatlingJobServer.java    License: MIT License 6 votes vote down vote up
@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 11
Source Project: karate   Source File: Robot.java    License: MIT License 6 votes vote down vote up
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 12
Source Project: karate   Source File: DapDecoder.java    License: MIT License 6 votes vote down vote up
@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 13
Source Project: karate   Source File: Main.java    License: MIT License 6 votes vote down vote up
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 14
Source Project: karate   Source File: SafariWebDriver.java    License: MIT License 6 votes vote down vote up
@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 15
Source Project: karate   Source File: CatsMockRunner.java    License: MIT License 5 votes vote down vote up
@BeforeClass
public static void beforeClass() {
    File file = FileUtils.getFileRelativeTo(CatsMockRunner.class, "cats-mock.feature");
    FeatureServer server = FeatureServer.start(file, 0, false, null);
    System.setProperty("karate.env", "mock");
    System.setProperty("mock.cats.url", "http://localhost:" + server.getPort() + "/cats");
}
 
Example 16
Source Project: karate   Source File: DemoMockProxySslRunner.java    License: MIT License 5 votes vote down vote up
@BeforeClass
public static void beforeClass() throws Exception {
    demoServerPort = TestBase.startServer();
    Map map = new Match().def("demoServerPort", null).allAsMap(); // don't rewrite url
    File file = FileUtils.getFileRelativeTo(DemoMockProxySslRunner.class, "demo-mock-proceed.feature");
    server = FeatureServer.start(file, 0, false, map);
}
 
Example 17
Source Project: karate   Source File: DemoMockProxyRunner.java    License: MIT License 5 votes vote down vote up
@BeforeClass
public static void beforeClass() throws Exception {
    demoServerPort = TestBase.startServer();
    Map map = new Match().def("demoServerPort", null).allAsMap(); // don't rewrite url
    File file = FileUtils.getFileRelativeTo(DemoMockProxyRunner.class, "demo-mock-proceed.feature");
    server = FeatureServer.start(file, 0, false, map);
}
 
Example 18
Source Project: karate   Source File: PaymentServiceContractUsingMockSslTest.java    License: MIT License 5 votes vote down vote up
@BeforeClass
public static void beforeClass() {
    String queueName = "DEMO.CONTRACT.MOCK.SSL";
    System.setProperty("karate.env", "contract");
    File file = FileUtils.getFileRelativeTo(PaymentServiceContractUsingMockSslTest.class, "payment-service-mock.feature");
    server = FeatureServer.start(file, 0, true, Collections.singletonMap("queueName", queueName));
    String paymentServiceUrl = "https://localhost:" + server.getPort();
    System.setProperty("payment.service.url", paymentServiceUrl);
    System.setProperty("shipping.queue.name", queueName);
}
 
Example 19
Source Project: karate   Source File: ConsumerUsingProxyRewriteSslTest.java    License: MIT License 5 votes vote down vote up
@BeforeClass
public static void beforeClass() {
    // actual service      
    String queueName = "DEMO.PROXY.REWRITE.SSL";       
    context = PaymentService.start(queueName, true);
    String paymentServiceUrl = "https://localhost:" + PaymentService.getPort(context);
    // proxy
    File file = FileUtils.getFileRelativeTo(ConsumerUsingProxyRewriteSslTest.class, "payment-service-proxy.feature");                        
    Map config = Collections.singletonMap("paymentServiceUrl", paymentServiceUrl);
    // requests will be forwarded / url re-written to paymentServiceUrl
    server = FeatureServer.start(file, 0, false, config);
    // consumer
    String proxyUrl = "http://localhost:" + server.getPort();        
    consumer = new Consumer(proxyUrl, queueName);        
}
 
Example 20
Source Project: karate   Source File: PaymentServiceMockSslMain.java    License: MIT License 5 votes vote down vote up
public static void main(String[] args) {
    File mockFeatureFile = FileUtils.getFileRelativeTo(PaymentServiceMockSslMain.class, "payment-service-mock.feature");
    File certFile = new File("src/test/java/mock-cert.pem");
    File privateKeyFile = new File("src/test/java/mock-key.pem");
    FeatureServer server = FeatureServer.start(mockFeatureFile, 8443, true, certFile, privateKeyFile, Collections.singletonMap("queueName", "DEMO.MOCK.8443"));
    server.waitSync();
}
 
Example 21
Source Project: karate   Source File: Main.java    License: MIT License 5 votes vote down vote up
public static StringUtils.Pair parseCommandLine(String commandLine, String cwd) {
    Matcher matcher = COMMAND_NAME.matcher(commandLine);
    String name;
    if (matcher.find()) {
        name = matcher.group(1);
        commandLine = matcher.replaceFirst("");
    } else {
        name = null;
    }
    List<String> args = Arrays.asList(commandLine.split("\\s+"));
    Iterator<String> iterator = args.iterator();
    String path = null;
    while (iterator.hasNext()) {
        String arg = iterator.next();
        if (arg.equals("--plugin") || arg.equals("--glue")) {
            iterator.next();
        }
        if (arg.startsWith("--") || arg.startsWith("com.") || arg.startsWith("cucumber.") || arg.startsWith("org.")) {
            // do nothing
        } else {
            path = arg;
        }
    }
    if (path == null) {
        return null;
    }
    if (cwd == null) {
        cwd = new File("").getAbsoluteFile().getPath();
    }
    cwd = cwd.replace('\\', '/'); // fix for windows
    path = path.substring(cwd.length() + 1);
    if (path.startsWith(FileUtils.SRC_TEST_JAVA)) {
        path = FileUtils.CLASSPATH_COLON + path.substring(FileUtils.SRC_TEST_JAVA.length() + 1);
    } else if (path.startsWith(FileUtils.SRC_TEST_RESOURCES)) {
        path = FileUtils.CLASSPATH_COLON + path.substring(FileUtils.SRC_TEST_RESOURCES.length() + 1);
    }
    return StringUtils.pair(path, name);
}
 
Example 22
Source Project: karate   Source File: Test01Runner.java    License: MIT License 5 votes vote down vote up
@BeforeClass
public static void beforeClass() {
    File file = FileUtils.getFileRelativeTo(Test01Runner.class, "_mock.feature");
    FeatureServer server = FeatureServer.start(file, 0, false, null);
    System.setProperty("karate.env", "mock");
    System.setProperty("web.url.base", "http://localhost:" + server.getPort());
}
 
Example 23
Source Project: karate   Source File: Test01ParallelRunner.java    License: MIT License 5 votes vote down vote up
@BeforeClass
public static void beforeClass() {
    File file = FileUtils.getFileRelativeTo(Test01Runner.class, "_mock.feature");
    FeatureServer server = FeatureServer.start(file, 0, false, null);
    System.setProperty("karate.env", "mock");
    System.setProperty("web.url.base", "http://localhost:" + server.getPort());
}
 
Example 24
Source Project: karate   Source File: Test04Runner.java    License: MIT License 5 votes vote down vote up
@BeforeClass
public static void beforeClass() {
    File file = FileUtils.getFileRelativeTo(Test04Runner.class, "_mock.feature");
    FeatureServer server = FeatureServer.start(file, 0, false, null);
    System.setProperty("karate.env", "mock");
    System.setProperty("web.url.base", "http://localhost:" + server.getPort());
}
 
Example 25
Source Project: karate   Source File: PaymentContractAgainstMockTest.java    License: MIT License 5 votes vote down vote up
@BeforeClass
public static void beforeClass() {       
    File file = FileUtils.getFileRelativeTo(PaymentContractAgainstMockTest.class, "payment-mock.feature");
    server = FeatureServer.start(file, 0, false, null);
    String paymentServiceUrl = "http://localhost:" + server.getPort();
    System.setProperty("payment.service.url", paymentServiceUrl);
}
 
Example 26
Source Project: karate   Source File: PostmanConverterTest.java    License: MIT License 5 votes vote down vote up
@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 27
Source Project: karate   Source File: AllKarateFeaturesTest.java    License: MIT License 5 votes vote down vote up
@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 28
Source Project: karate   Source File: NoHeadersRunner.java    License: MIT License 5 votes vote down vote up
@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 29
Source Project: karate   Source File: CookiesRunner.java    License: MIT License 5 votes vote down vote up
@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 30
Source Project: karate   Source File: FormRunner.java    License: MIT License 5 votes vote down vote up
@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 + "");
}