Search code examples
karatewritetofilefileutils

how to use FileUtils in Karate?


need to convert generate PDF from encoded string and save it as pdf for comparison.

Sample feature file:

Feature: Compute All  

Scenario: trial and error
* call read('common.feature')
* def xyz = getMDash( 'my password')
* print xyz
* call read('classpath:/test/java/com/intuit/karate/FileUtils.java')



* def doWork =
"""
function('temp.txt','hello world') {
  var JavaDemo = Java.type('com.intuit.karate.FileUtils');
  var jd = new JavaDemo();
  jd.writeToFile('temp.txt','hello world');  
}
"""

* def result = call writeToFile 'temp.txt','hello world'


* def FileUtils = Java.type('com.intuit.karate.FileUtils')
* def result = FileUtils.writeToFile('temp.txt','hello world')

using examples as given.

error in log:

Tests run: 9, Failures: 0, Errors: 2, Skipped: 3, Time elapsed: 1.314 sec <<< FAILURE!
* def doWork =(Scenario: trial and error)  Time elapsed: 0 sec  <<< ERROR!
java.lang.RuntimeException: javascript evaluation failed: function('temp.txt','hello world') {
  var JavaDemo = Java.type('com.intuit.karate.FileUtils');
  var jd = new JavaDemo();
  jd.writeToFile('temp.txt','hello world');
}
at com.intuit.karate.ScriptBindings.eval(ScriptBindings.java:115)
at com.intuit.karate.ScriptBindings.updateBindingsAndEval(ScriptBindings.java:103)
at com.intuit.karate.ScriptBindings.evalInNashorn(ScriptBindings.java:88)
at com.intuit.karate.Script.evalJsExpression(Script.java:362)
at com.intuit.karate.Script.evalKarateExpression(Script.java:284)
at com.intuit.karate.Script.evalKarateExpression(Script.java:170)
at com.intuit.karate.Script.assign(Script.java:598)
at com.intuit.karate.Script.assign(Script.java:524)
at com.intuit.karate.StepDefs.def(StepDefs.java:305)
at com.intuit.karate.StepDefs.defDocString(StepDefs.java:300)
at ?.* def doWork =(testSuite/users/dummy.feature:11)
**Caused by: javax.script.ScriptException**: <eval>:1:10 Expected ident but found temp.txt
function('temp.txt','hello world')

need help on using fileUtils in karate.


Solution

  • Karate does not have any support for writing files because it is bad practice. I have no idea what you are trying to do above. Normally you do your comparison by keeping responses in memory, refer to the file upload example: https://github.com/intuit/karate/blob/master/karate-demo/src/test/java/demo/upload/upload.feature

    The same example also has an example of using a custom Java class. If you really really need to write something to a file, write your own utility using the above code and using com.intuit.karate.demo.util.FileChecker as a reference.