Is it possible to run commands in Katalon? - testing

Katalon is popular in automation testing. I have already used it in our project and it works amazingly.
Now, What I want to achieve is to create a test case where it opens a terminal (using mac) and type in some commands to run it like for example:
cd /documents/pem/key.pem
connect to -my server via SSH#method
sudo su
yum install php7
yum install mysql

You are not alone, and with custom keywords you can achieve what you want. Here is an example showing a test of a command line app. You could do the same thing to call any command line script you wish. Think of a runCmd keyword, or a runCmdWithOutput to grab the output and run various asserts on it.
#Keyword
def pdfMetadata(String input) {
KeywordUtil.logInfo("input: ${input}")
def csaHome = System.getenv("CSA_HOME")
def cmd = "cmd /c ${csaHome}/bin/csa -pdfmetadata -in \"${projectPath}${input}\"";
runCmd(cmd)
}
def runCmd(String cmd) {
KeywordUtil.logInfo("cmd: ${cmd}")
def proc = cmd.execute();
def outputStream = new StringBuffer();
def errStream = new StringBuffer()
proc.waitForProcessOutput(outputStream, errStream);
println(outputStream.toString());
println(errStream.toString())
if(proc.exitValue() != 0){
KeywordUtil.markFailed("Out:" + outputStream.toString() + ", Err: " + errStream.toString())
}
}
You can then use this in a test case:
CustomKeywords.'CSA.pdfMetadata'('/src/pdf/empty.pdf')

Here is another custom keyword! It is takes the file name and path, and if you don't give it a path, it search for the file in the project root directory. It export the batch file's output in a batch_reports folder in your project folder, you need to create that in advance.
#Keyword
def runPostmanBatch(String batchName , String batchPath){
// source: https://www.mkyong.com/java/how-to-execute-shell-command-from-java/
String firstParameter = "cmd /c " + batchName;
String secondParameter = batchPath;
if (batchPath == ""){
secondParameter = RunConfiguration.getProjectDir();
}
try {
KeywordUtil.logInfo("Executing " + firstParameter + " at " + secondParameter)
Process process = Runtime.getRuntime().exec(
firstParameter , null, new File(secondParameter));
StringBuilder output = new StringBuilder();
BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
output.append(line + "\n");
}
int exitVal = process.waitFor();
Date atnow = new Date()
String now = atnow.format('yy-MM-dd HH-mm-ss')
String report_path = RunConfiguration.getProjectDir() + "/postman_reports/" + RunConfiguration.getExecutionSourceName() + "_" + now + ".txt"
BufferedWriter writer = new BufferedWriter(new FileWriter(report_path));
writer.write(output.toString());
writer.close();
KeywordUtil.logInfo("postman report at: " + report_path)
if (exitVal == 0) {
println("Success!");
println(output);
KeywordUtil.markPassed("Ran successfully")
} else {
KeywordUtil.markFailed("Something went wrong")
println(exitVal);
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

I've done some research. I did not found any resources or any people that is looking for the same thing I am. I think this is officially, No. The answer to this is, it is not possible.

It is possible to run Katalon Studio from the command line.
There's a short tutorial here.
And it will be possible to override Profile Variables via command line execution mode from v5.10 (currently in beta).
An example given on Katalon forum is:
Simply pass the parameters in command line using: -g_XXX = XXX
Below is an example of override an URL variable:
-g_URL=http://demoaut.katalon.com

Related

Where and how do I make another folder to put text files so they work when I export?

I have a folder with my text files that can read and write and work in eclipse. But, when I export to jar, it fails because the files are not found, meaning they are not exported and I don't know how to make eclipse do that. I'm sure the solution is out there, but I don't know exactly what I'm searching for. Do I make a relative directory and how? Or another source folder? What exactly do I need to do?
This shows I have a folder called conf where my files are stored but it is not there on export.
Scanner in = new Scanner(new FileReader("conf/Admins.txt"));
FileWriter out = new FileWriter("conf/CurrentUser.txt");
int id = 0;
String name = "";
String pass = "";
boolean found = false;
while(in.hasNext()) {
id = in.nextInt();
name = in.next();
pass = in.next();
if(id == userID) {
out.write(id + " " + name + " " + pass + "\n");
found = true;
break;
}
}
All I had to do was once exported, put my conf file in the same place as the exported jar file. I don't know if, theres a better way but this is a win for me.

How to retain original Last Modified/Created date of the file on FTP when we try to download them using FTPClient Class and Selenium [duplicate]

I am using org.apache.commons.net.ftp.FTPClient for retrieving files from a ftp server. It is crucial that I preserve the last modified timestamp on the file when its saved on my machine. Do anyone have a suggestion for how to solve this?
This is how I solved it:
public boolean retrieveFile(String path, String filename, long lastModified) throws IOException {
File localFile = new File(path + "/" + filename);
OutputStream outputStream = new FileOutputStream(localFile);
boolean success = client.retrieveFile(filename, outputStream);
outputStream.close();
localFile.setLastModified(lastModified);
return success;
}
I wish the Apache-team would implement this feature.
This is how you can use it:
List<FTPFile> ftpFiles = Arrays.asList(client.listFiles());
for(FTPFile file : ftpFiles) {
retrieveFile("/tmp", file.getName(), file.getTimestamp().getTime());
}
You can modify the timestamp after downloading the file.
The timestamp can be retrieved through the LIST command, or the (non standard) MDTM command.
You can see here how to do modify the time stamp: that: http://www.mkyong.com/java/how-to-change-the-file-last-modified-date-in-java/
When download list of files, like all files returned by by FTPClient.mlistDir or FTPClient.listFiles, use the timestamp returned with the listing to update timestemp of local downloaded files:
String remotePath = "/remote/path";
String localPath = "C:\\local\\path";
FTPFile[] remoteFiles = ftpClient.mlistDir(remotePath);
for (FTPFile remoteFile : remoteFiles) {
File localFile = new File(localPath + "\\" + remoteFile.getName());
OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(localFile));
if (ftpClient.retrieveFile(remotePath + "/" + remoteFile.getName(), outputStream))
{
System.out.println("File " + remoteFile.getName() + " downloaded successfully.");
}
outputStream.close();
localFile.setLastModified(remoteFile.getTimestamp().getTimeInMillis());
}
When downloading a single specific file only, use FTPClient.mdtmFile to retrieve the remote file timestamp and update timestamp of the downloaded local file accordingly:
File localFile = new File("C:\\local\\path\\file.zip");
FTPFile remoteFile = ftpClient.mdtmFile("/remote/path/file.zip");
if (remoteFile != null)
{
OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(localFile));
if (ftpClient.retrieveFile(remoteFile.getName(), outputStream))
{
System.out.println("File downloaded successfully.");
}
outputStream.close();
localFile.setLastModified(remoteFile.getTimestamp().getTimeInMillis());
}

Running PhantomJs in java

I'm trying to run phantomjs in my program, below is the command I'm running.
Process exec = Runtime.getRuntime().exec(new String[]{
"C:/Users/buddy/Desktop/phantomjs-1.9.7-windows",
"-c",
"phantomjs "
+ pipedCommand + " "
+ size + " "
+ conversion.getConversionTarget().extension() + " "
+ this.local.getId()});
and I'm getting exception when I run: (But above code runs for Linux)
I have downloaded phantomjs windows version and its in the following path: C:/Users/buddy/Desktop/phantomjs-1.9.7-windows
java.io.IOException: Cannot run program "C:/Users/buddy/Desktop/phantomjs-1.9.7-windows": CreateProcess error=5, Access is denied.
I believe you need to run it from a cmd process... not sure if it helps but how I did it was to create a shellscript file with contents similar to below
echo "- Processing : Creating screenshot image from $1"
'C:\software\phantomjs' 'C:\software\rasterize.js' http://$1 $2
and then within the java code
// Create process command
String command = "cmd /c " + imageScriptLocation + " " + cleanUrl + " " + imgLocation
// Execute the process
Runtime rt = Runtime.getRuntime();
p = rt.exec(command);
// Retrieve any errors from the script
InputStream is = p.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
logger.debug("Image Script: " + line);
}
// Wait for the process to complete and the images to be generated
p.waitFor();
if you just want to use your approach above though, the below should work...
Process exec = Runtime.getRuntime().exec(new String[]{
"cmd",
"/c",
"phantomjs "
+ pipedCommand + " "
+ size + " "
+ conversion.getConversionTarget().extension() + " "
+ this.local.getId()});
You can run PhantomJS using Selenium.
DesiredCapabilities caps = new DesiredCapabilities();
String path = "Path to PhantomJS Binary";
caps.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, path);
WebDriver driver = new PhantomJSDriver(caps);

Efficient Way to do batch import XMI in Enterprise Architect

Our team are using Enterprise Architect version 10 and SVN for the repository.
Because the EAP file size is quite big (e.g. 80 MB), we exports each packages into separate XMI and stored it into SVN. The EAP file itself is committed after some milestone. The problem is to synchronize the EAP file with work from co worker during development, we need to import lots of XMI (e.g. total can be 500 files).
I know that once the EAP file is updated, we can use Package Control -> Get All Latest. Therefore this problem occurs only during parallel development.
We have used keyboard shorcuts to do the import as follow:
Ctrl+Alt+I (Import package from XMI file)
Select the file name to import
Alt+I (Import)
Enter (Yes)
Repeat step number 2 to 4 until module finished
But still, importing hundreds of file is inefficient.
I've checked that the Control Package has Batch Import/Export. The batch import/export are working when I explicitly hard-coded the XMI Filename, but the options are not available if using version control (batch import/export options are greyed).
Is there any better ways to synchronize EAP and XMI files?
There is a scripting interface in EA. You might be able to automate the import using that. I've not used it but its probably quite good.
I'm not sure I fully understand your working environment, but I have some general points that may be of interest. It might be that if you use EA in a different way (especially my first point below), the need to batch import might go away.
Multiworker
First, multiple people can work on the same EAP file at a time. The EAP file is nothing more than an Access database file, and EA uses locking to stop multiple people editing the same package at the same time. But you can comfortably have multiple people editing different packages in one EAP file at the same time. Putting the EAP file on a file share somewhere is a good way of doing it.
Inbuilt Revision Control
Secondly, EA can interact directly with SVN (and other revision control systems). See this. In short, you can setup your EAP file so that individual packages (and everything below them) is SVN controlled. You can then check out an individual package, edit it, check it back in. Or indeed you can check out the whole branch below a package (including sub packages that are themselves SVN controlled).
Underneath the hood EA is importing and exporting XMI files and checking them in and out of SVN, whilst the EAP file is always the head revision. Just like what you're doing by hand, but automated. It makes sense given that you can all use the one single EAP file. You do have to be a bit careful rolling back - links originating from objects in older versions of one package might be pointing at objects that no longer exist (but you can look at the import log errors to see if this is the case). It takes a bit of getting used to, but it works pretty well.
There's also the built in package baselining functionality - that might be all you need anyway, and works quite well especially if you're all using the same EAP file.
Bigger Database Engine
Thirdly, you don't have to have an EAP file at all. The model's database can be in any suitable database system (MySQL, SQL Server, Oracle, etc). So that gives you all sorts of options for scaling up how its used, what its like over a WAN/Internet, etc.
In short Sparx have been quite sensible about how EA can be used in a multi-worker environment, and its worth exploiting that.
I have created the EA script using JScript for the automation
Here is the script to do the export:
!INC Local Scripts.EAConstants-JScript
/*
* Script Name : Export List of SVN Packages
* Author : SDK
* Purpose : Export a package and all of its subpackages information related to version
* controlled. The exported file then can be used to automatically import
* the XMIs
* Date : 30 July 2013
* HOW TO USE : 1. Select the package that you would like to export in the Project Browser
* 2. Change the output filepath in this script if necessary.
* By default it is "D:\\EAOutput.txt"
* 3. Send the output file to your colleague who wanted to import the XMIs
*/
var f;
function main()
{
// UPDATE THE FOLLOWING OUTPUT FILE PATH IF NECESSARY
var filename = "D:\\EAOutput.txt";
var ForReading = 1, ForWriting = 2, ForAppending = 8;
Repository.EnsureOutputVisible( "Script" );
Repository.ClearOutput( "Script" );
Session.Output("Start generating output...please wait...");
var treeSelectedType = Repository.GetTreeSelectedItemType();
switch ( treeSelectedType )
{
case otPackage:
{
var fso = new ActiveXObject("Scripting.FileSystemObject");
f = fso.OpenTextFile(filename, ForWriting, true);
var selectedObject as EA.Package;
selectedObject = Repository.GetContextObject();
reportPackage(selectedObject);
loopChildPackages(selectedObject);
f.Close();
Session.Output( "Done! Check your output at " + filename);
break;
}
default:
{
Session.Prompt( "This script does not support items of this type.", promptOK );
}
}
}
function loopChildPackages(thePackage)
{
for (var j = 0 ; j < thePackage.Packages.Count; j++)
{
var child as EA.Package;
child = thePackage.Packages.GetAt(j);
reportPackage(child);
loopChildPackages(child);
}
}
function getParentPath(childPackage)
{
if (childPackage.ParentID != 0)
{
var parentPackage as EA.Package;
parentPackage = Repository.GetPackageByID(childPackage.ParentID);
return getParentPath(parentPackage) + "/" + parentPackage.Name;
}
return "";
}
function reportPackage(thePackage)
{
f.WriteLine("GUID=" + thePackage.PackageGUID + ";"
+ "NAME=" + thePackage.Name + ";"
+ "VCCFG=" + getVCCFG(thePackage) + ";"
+ "XML=" + thePackage.XMLPath + ";"
+ "PARENT=" + getParentPath(thePackage).substring(1) + ";"
);
}
function getVCCFG(thePackage)
{
if (thePackage.IsVersionControlled)
{
var array = new Array();
array = (thePackage.Flags).split(";");
for (var z = 0 ; z < array.length; z++)
{
var pos = array[z].indexOf('=');
if (pos > 0)
{
var key = array[z].substring(0, pos);
var value = array[z].substring(pos + 1);
if (key=="VCCFG")
{
return (value);
}
}
}
}
return "";
}
main();
And the script to do the import:
!INC Local Scripts.EAConstants-JScript
/*
* Script Name : Import List Of SVN Packages
* Author : SDK
* Purpose : Imports a package with all of its sub packages generated from
* "Export List Of SVN Packages" script
* Date : 01 Aug 2013
* HOW TO USE : 1. Get the output file generated by "Export List Of SVN Packages" script
* from your colleague
* 2. Get the XMIs in the SVN local copy
* 3. Change the path to the output file in this script if necessary (var filename).
* By default it is "D:\\EAOutput.txt"
* 4. Change the path to local SVN
* 5. Run the script
*/
var f;
var svnPath;
function main()
{
// CHANGE THE FOLLOWING TWO LINES ACCORDING TO YOUR INPUT AND LOCAL SVN COPY
var filename = "D:\\EAOutput.txt";
svnPath = "D:\\svn.xxx.com\\yyy\\docs\\design\\";
var ForReading = 1, ForWriting = 2, ForAppending = 8;
Repository.EnsureOutputVisible( "Script" );
Repository.ClearOutput( "Script" );
Session.Output("[INFO] Start importing packages from " + filename + ". Please wait...");
var fso = new ActiveXObject("Scripting.FileSystemObject");
f = fso.OpenTextFile(filename, ForReading);
// Read from the file and display the results.
while (!f.AtEndOfStream)
{
var r = f.ReadLine();
parseLine(r);
Session.Output("--------------------------------------------------------------------------------");
}
f.Close();
Session.Output("[INFO] Finished");
}
function parseLine(line)
{
Session.Output("[INFO] Parsing " + line);
var array = new Array();
array = (line).split(";");
var guid;
var name;
var isVersionControlled;
var xmlPath;
var parentPath;
isVersionControlled = false;
xmlPath = "";
for (var z = 0 ; z < array.length; z++)
{
var pos = array[z].indexOf('=');
if (pos > 0)
{
var key = array[z].substring(0, pos);
var value = array[z].substring(pos + 1);
if (key=="GUID") {
guid = value;
} else if (key=="NAME") {
name = value;
} else if (key=="VCCFG") {
if (value != "") {
isVersionControlled = true;
}
} else if (key=="XML") {
if (isVersionControlled) {
xmlPath = value;
}
} else if (key=="PARENT") {
parentPath = value;
}
}
}
// Quick check for target if already exist to speed up process
var targetPackage as EA.Package;
targetPackage = Repository.GetPackageByGuid(guid);
if (targetPackage != null)
{
// target exists, do not do anything
Session.Output("[DEBUG] Target package \"" + name + "\" already exist");
return;
}
var paths = new Array();
var packages = new Array(paths.Count);
for (var i = 0; i < paths.Count; i++)
{
packages[i] = null;
}
paths = (parentPath).split("/");
if (paths.Count < 2)
{
Session.Output("[INFO] Skipped root or level1");
return;
}
packages[0] = selectRoot(paths[0]);
packages[1] = selectPackage(packages[0], paths[1]);
if (packages[1] == null)
{
Session.Output("[ERROR] Cannot find " + paths[0] + "/" + paths[1] + "in Project Browser");
return;
}
for (var j = 2; j < paths.length; j++)
{
packages[j] = selectPackage(packages[j - 1], paths[j]);
if (packages[j] == null)
{
Session.Output("[DEBUG] Creating " + packages[j].Name);
// create the parent package
var parent as EA.Package;
parent = Repository.GetPackageByGuid(packages[j-1].PackageGUID);
packages[j] = parent.Packages.AddNew(paths[j], "");
packages[j].Update();
parent.Update();
parent.Packages.Refresh();
break;
}
}
// Check if name (package to import) already exist or not
var targetPackage = selectPackage(packages[paths.length - 1], name);
if (targetPackage == null)
{
if (xmlPath == "")
{
Session.Output("[DEBUG] Creating " + name);
// The package is not SVN controlled
var newPackage as EA.Package;
newPackage = packages[paths.length - 1].Packages.AddNew(name,"");
Session.Output("New GUID = " + newPackage.PackageGUID);
newPackage.Update();
packages[paths.length - 1].Update();
packages[paths.length - 1].Packages.Refresh();
}
else
{
// The package is not SVN controlled
Session.Output("[DEBUG] Need to import: " + svnPath + xmlPath);
var project as EA.Project;
project = Repository.GetProjectInterface;
var result;
Session.Output("GUID = " + packages[paths.length - 1].PackageGUID);
Session.Output("GUID XML = " + project.GUIDtoXML(packages[paths.length - 1].PackageGUID));
Session.Output("XMI file = " + svnPath + xmlPath);
result = project.ImportPackageXMI(project.GUIDtoXML(packages[paths.length - 1].PackageGUID), svnPath + xmlPath, 1, 0);
Session.Output(result);
packages[paths.length - 1].Update();
packages[paths.length - 1].Packages.Refresh();
}
}
else
{
// target exists, do not do anything
Session.Output("[DEBUG] Target package \"" + name + "\" already exist");
}
}
function selectPackage(thePackage, childName)
{
var childPackage as EA.Package;
childPackage = null;
if (thePackage == null)
return null;
for (var i = 0; i < thePackage.Packages.Count; i++)
{
childPackage = thePackage.Packages.GetAt(i);
if (childPackage.Name == childName)
{
Session.Output("[DEBUG] Found " + childName);
return childPackage;
}
}
Session.Output("[DEBUG] Cannot find " + childName);
return null;
}
function selectRoot(rootName)
{
for (var y = 0; y < Repository.Models.Count; y++)
{
root = Repository.Models.GetAt(y);
if (root.Name == rootName)
{
return root;
}
}
return null;
}
main();

Detail Hudson test reports

Is there any way to force Hudson to give me more detailed test results - e.g. I'm comparing two strings and I want to know where they differ.
Is there any way to do this?
Thank you for help.
You should not hope Hudson give the detail information, it just shows the testing messages generated by junit.
You could show the expected string and actual string when failing asserting equals between those two strings.
For example,
protected void compareFiles(File newFile, String referenceLocation, boolean lineNumberMatters) {
BufferedReader reader = null;
BufferedReader referenceReader = null;
List<String> expectedLines = new ArrayList<String>();
try {
referenceReader = new BufferedReader(new InputStreamReader(FileLocator.openStream(Activator.getDefault().getBundle(), new Path("data/regression/" + referenceLocation), false))); //$NON-NLS-1$
expectedLines = getLinesFromReader(referenceReader);
} catch (Exception e) {
assertFalse("Exception occured during reading reference data: " + e, true); //$NON-NLS-1$
}
List<String>foundLines = new ArrayList<String>();
try {
reader = new BufferedReader(new FileReader(newFile));
foundLines = getLinesFromReader(reader);
} catch (Exception e) {
assertFalse("Exception occured during reading file: " + e, true); //$NON-NLS-1$
}
boolean throwException = expectedLines.size() != foundLines.size();
if (throwException) {
StringBuffer buffer = new StringBuffer("\n" + newFile.toString()); //$NON-NLS-1$
for (String line: foundLines)
buffer.append(line + "\n"); //$NON-NLS-1$
assertEquals("The number of lines in the reference(" + referenceLocation + ") and new output(" + newFile.getAbsolutePath()+ ") did not match!" + buffer, expectedLines.size(), foundLines.size()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
if (!lineNumberMatters) {
Collections.sort(expectedLines);
Collections.sort(foundLines);
}
/** Either the line matches character by character or it matches regex-wise, in that order */
for (int i=0;i<expectedLines.size(); i++)
assertTrue("Found errors in file (" + newFile + ")! " + foundLines.get(i) + " vs. " + expectedLines.get(i), foundLines.get(i).equals(expectedLines.get(i)) || foundLines.get(i).matches(expectedLines.get(i))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
Hudson supports JUnit directly. On your job configuration page, near the end, should be an option to "Publish JUnit test results report".
I'm not too familiar with JUnit itself, but I guess it produces (or has the ability to produce) and put results in an xml file. You just need to put the path of to the xml file (relative to the workspace) in the text box.
Once you do that, and create a build, you'll have a detailed report on your project page. You should then be able to click your way through the results for each test.