Search code examples
javascriptfiledirectorykaratefilesystemobject

Need to check folders, files and file details for given directory using JavaScript in standalone karate.jar


I need to check folders, files and file details (file size) for given directory using JavaScript in standalone karate.jar and this validation is part of test automation script.

I understand this can be achieved by writing custom java packages in maven and use them in JavaScript of karate script.

How to implement this in standalone karate.jar. Pass directory path and directory name as two arguments to JavaScript functions which validate given directory name exists in provided directory path. Its kind of handling file system objects.

I understand the karate supports only read the files and not the read folder names and file names/ file details in directory. Read files in karate script : https://intuit.github.io/karate/#reading-files The allowed file extensions are : .json, .xml, .yaml, .csv, .txt, .feature

Please guide me how to implement this using Javascript in karate?

Thanks Chandra.


Solution

  • Yes this is harder with the standalone JAR. Here are some suggestions:

    • write a small JAR file (one-time) that you can include in your stand-alone project: https://stackoverflow.com/a/56458094/143475
    • use OS commands via karate.exec(), e.g. on windows * def homePath = karate.exec('cmd /c echo %HOMEPATH%')
    • with some work, you can create pure JS scripts that use the JVM libraries, but you need a good understanding of what exists in Java and these are very hard to debug so I don't recommend this approach. I am giving an example below:
    
    * def findFile = 
    """
    function(file, condition) {
      var root = new java.io.File(file);
      function recurse(file) {
        var list = file.listFiles();
        for (var i = 0; i < list.length; i++) {
          var f = list[i];
          if (f.directory) {
            // karate.log('recurse:', f);
            return recurse(f);
          } else {
            var path = f.path;
            // karate.log('scan:', path);
            if (condition(path)) {
              karate.log('*** found:', path);
              return f;
            }
          }
        }
      }  
      return recurse(root);
    }
    """
    * def filter = function(x){ return x.contains('/test-') && x.endsWith('.log') }
    * def found = findFile('.', filter)
    * print 'found:', found