katalon compare api response with database - katalon-studio

I am not sure how to link test cases, add more verification.
I am thinking how to link both above, store the API response and after this completed successfully: ID, productid, productinfo.
Then query the database details, store it if possible (I have checkpoint created, not sure if this is the right approach), then verify values from API response same as the database column value.
I have object repository for sets of API message (GET/POST)
POST API to insert new product
Then 2 keywords to test the response of API matched the database records
connect to API and POST to insert the new product
connect to database and Get the table details
I have an individual test case to test the API POST message getting response 200 and run successfully. And another test case to connect to the database and query the table details.
===========
1. add product keyword groovy script
package Product
import static com.kms.katalon.core.testobject.ObjectRepository.findTestObject
import com.kms.katalon.core.annotation.Keyword
import com.kms.katalon.core.webservice.keyword.WSBuiltInKeywords as WS
import groovy.json.JsonBuilder
import groovy.json.JsonOutput
import groovy.json.JsonSlurper
public class API {
#Keyword
AddProduct() {
def result = WS.sendRequestAndVerify(findTestObject('AddProduct'))
return result
}
}
======================================
2. database groovy script
package database
import java.sql.*
import com.kms.katalon.core.annotation.Keyword
public class postgresHandler {
Connection c = null
Statement stmt = null
#Keyword
public void connectToPostgres(){
try {
Class.forName("org.postgresql.Driver")
String url = "jdbc:postgresql://localhost:5433/postgres?currentSchema=SCHEMA";
Properties props = new Properties();
props.setProperty("user","postgres");
props.setProperty("password","postgres");
c = DriverManager.getConnection(url, props);
} catch (Exception e) {
e.printStackTrace()
System.err.println(e.getClass().getName()+": "+e.getMessage())
System.exit(0)
}
System.out.println("Opened database successfully")
}
#Keyword
public void getProduct(){
try {
Class.forName("org.postgresql.Driver")
String url = "jdbc:postgresql://localhost:5433/postgres?currentSchema=SCHEMA";
Properties props = new Properties();
props.setProperty("user","postgres");
props.setProperty("password","postgres");
c = DriverManager.getConnection(url, props);
c.setAutoCommit(false)
System.out.println("Opened database successfully")
stmt = c.createStatement()
ResultSet rs = stmt.executeQuery( "select * from products.products;" )
while ( rs.next() ) {
String id = rs.getString("id")
String productid = rs.getString("productid")
String productInfo = rs.getString("productInfo")
System.out.println( "ID = " + id )
System.out.println( "productID = " + productid )
System.out.println( "productInfo = " + productInfo )
System.out.println()
}
rs.close()
stmt.close()
c.close()
} catch ( Exception e ) {
System.err.println( e.getClass().getName()+": "+ e.getMessage() )
System.exit(0)
}
System.out.println("Operation done successfully")
}
}
=============================================================
3. Test case to call add product keyword groovy script
import static com.kms.katalon.core.testobject.ObjectRepository.findTestObject
import com.kms.katalon.core.webservice.keyword.WSBuiltInKeywords as WS
result = CustomKeywords.'swisslog.KafkaRest.AddProduct'()
print(result)
WS.sendRequest(findTestObject('AddProduct'))
=====================================================
Test case to call database groovy script
import com.kms.katalon.core.configuration.RunConfiguration
CustomKeywords.'dsdatabase.postgresHandler.connectToPostgres'()
CustomKeywords.'dsdatabase.postgresHandler.getProduct'()

Related

Adding file to GitHub using java client - org.eclipse.egit.github.core

I am trying to add a file to a repository using the below code but I am getting below error. I just want to add a file for now.
org.eclipse.egit.github.core.client.RequestException: Invalid request.
For 'properties/email', nil is not a string. For 'properties/name',
nil is not a string. For 'properties/email', nil is not a string. For
'properties/name', nil is not a string. (422) at
org.eclipse.egit.github.core.client.GitHubClient.createException(GitHubClient.java:552)
at
org.eclipse.egit.github.core.client.GitHubClient.sendJson(GitHubClient.java:643)
at
org.eclipse.egit.github.core.client.GitHubClient.post(GitHubClient.java:757)
at
org.eclipse.egit.github.core.service.DataService.createCommit(DataService.java:397)
I sense that it is expecting some properties but how to supply this is not clear. What is that i am missing?
Referring to https://gist.github.com/Detelca/2337731
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import org.eclipse.egit.github.core.Blob;
import org.eclipse.egit.github.core.Commit;
import org.eclipse.egit.github.core.CommitUser;
import org.eclipse.egit.github.core.Reference;
import org.eclipse.egit.github.core.Repository;
import org.eclipse.egit.github.core.RepositoryCommit;
import org.eclipse.egit.github.core.Tree;
import org.eclipse.egit.github.core.TreeEntry;
import org.eclipse.egit.github.core.TypedResource;
import org.eclipse.egit.github.core.User;
import org.eclipse.egit.github.core.client.GitHubClient;
import org.eclipse.egit.github.core.service.CommitService;
import org.eclipse.egit.github.core.service.DataService;
import org.eclipse.egit.github.core.service.RepositoryService;
import org.eclipse.egit.github.core.service.UserService;
public class GHWriter {
public static void main(String[] args) {
try {
new GHWriter().writeFile("test_two.txt", "test content");
} catch (IOException e) {
e.printStackTrace();
}
}
//https://gist.github.com/Detelca/2337731
public boolean writeFile(String fileName, String fileContent) throws IOException{
// initialize github client
GitHubClient client = new GitHubClient();
//TextView password = (TextView)findViewById(R.id.textViewPassword);
client.setCredentials("username", "password");
// create needed services
RepositoryService repositoryService = new RepositoryService();
CommitService commitService = new CommitService(client);
DataService dataService = new DataService(client);
// get some sha's from current state in git
Repository repository = repositoryService.getRepository("username", "repositoryName");
String baseCommitSha = repositoryService.getBranches(repository).get(0).getCommit().getSha();
RepositoryCommit baseCommit = commitService.getCommit(repository, baseCommitSha);
String treeSha = baseCommit.getSha();
// create new blob with data
Blob blob = new Blob();
blob.setContent("[\"" + System.currentTimeMillis() + "\"]").setEncoding(Blob.ENCODING_UTF8);
String blob_sha = dataService.createBlob(repository, blob);
Tree baseTree = dataService.getTree(repository, treeSha);
// create new tree entry
TreeEntry treeEntry = new TreeEntry();
treeEntry.setPath("testfile.txt");
treeEntry.setMode(TreeEntry.MODE_BLOB);
treeEntry.setType(TreeEntry.TYPE_BLOB);
treeEntry.setSha(blob_sha);
treeEntry.setSize(blob.getContent().length());
Collection<TreeEntry> entries = new ArrayList<TreeEntry>();
entries.add(treeEntry);
Tree newTree = dataService.createTree(repository, entries, baseTree.getSha());
// create commit
Commit commit = new Commit();
commit.setMessage("first commit at " + new Date(System.currentTimeMillis()).toLocaleString());
commit.setTree(newTree);
UserService userService = new UserService( client );
User user = userService.getUser();
CommitUser author = new CommitUser();
author.setName( user.getName() );
Calendar now = Calendar.getInstance();
author.setDate(now.getTime());
commit.setAuthor(author);
commit.setCommitter(author);
List<Commit> listOfCommits = new ArrayList<Commit>();
listOfCommits.add(new Commit().setSha(baseCommitSha));
// listOfCommits.containsAll(base_commit.getParents());
commit.setParents(listOfCommits);
// commit.setSha(base_commit.getSha());
Commit newCommit = dataService.createCommit(repository, commit);
// create resource
TypedResource commitResource = new TypedResource();
commitResource.setSha(newCommit.getSha());
commitResource.setType(TypedResource.TYPE_COMMIT);
commitResource.setUrl(newCommit.getUrl());
// get master reference and update it
Reference reference = dataService.getReference(repository, "heads/master");
reference.setObject(commitResource);
dataService.editReference(repository, reference, true);
System.out.println("Committed URL: "+ newCommit.getUrl());
return false;
}
}
Thanks
After some debugging, found that email and name values are coming as null which is the source of the issue.
Adding below two lines will solve the issue:
author.setName( userName );
author.setEmail(email);

SQL query class has no persistent fields in the SELECT

static void go() {
PersistenceManager pm = null;
Transaction tx = null;
try {
pm = new JDOFactory().getFactory().getPersistenceManager();
tx = pm.currentTransaction();
Query q = pm.newQuery("javax.jdo.query.SQL", "select * from \"OAUTHTEMP\" where \"O_AUTH_TOKEN\"=:oAuthToken and \"O_AUTH_VERIFIED\"=:oAuthVerified");
Map params = new HashMap();
params.put("oAuthToken", "08f727ab-7132-426c-8fc2-9ce2b30ebf9d");
params.put("oAuthVerifier", "C3ExGzv+cAQkOqwL4oY94fZhDyVLyo/0H31w8F3q+YYLSBDxl2YARcglqPuKcsfT");
List<OAuthTemp> result = (List<OAuthTemp>) q.executeWithMap(params);
} catch (Exception e) {
e.printStackTrace();
}
}
This is my function to fetch all data on the basis of token and verifier but I am getting the exception below:
SQL query class has no persistent fields in the SELECT : select * from "OAUTHTEMP" where "O_AUTH_TOKEN"=:oAuthToken and "O_AUTH_VERIFIED"=:oAuthVerified
org.datanucleus.exceptions.NucleusUserException: SQL query class has no persistent fields in the SELECT : select * from "OAUTHTEMP" where "O_AUTH_TOKEN"=:oAuthToken and "O_AUTH_VERIFIED"=:oAuthVerified
at org.datanucleus.store.rdbms.query.SQLQuery.prepareForExecution(SQLQuery.java:994)
at org.datanucleus.store.rdbms.query.SQLQuery.executeWithMap(SQLQuery.java:818)
at org.datanucleus.api.jdo.JDOQuery.executeInternal(JDOQuery.java:369)
at org.datanucleus.api.jdo.JDOQuery.executeWithMap(JDOQuery.java:276)
at com.xenonstack.demo.test.Test.go(Test.java:61)
at com.xenonstack.demo.test.Test.main(Test.java:40)
My OAuthTemp class is this
OauthTemp class.
You seem to have a query with a parameter called oAuthVerified yet are providing a value for oAuthVerifier. Perhaps if you fix that it would work?

Intersystems Cache using XEP

I am trying to extract data from the Samples namespace that comes with Intersystems Cache install. Specifically, I am trying to retrieve Sample.Company global data using XEP. Inorder to achieve this, I created Sample.Company class like this -
package Sample;
public class Company {
public Long id;
public String mission;
public String name;
public Long revenue;
public String taxId;
public Company(Long id, String mission, String name, Long revenue,
String taxId) {
this.id = id;
this.mission = mission;
this.name = name;
this.revenue = revenue;
this.taxId = taxId;
}
public Company() {
}
}
XEP related code looks like this -
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Service;
import Sample.Company;
import com.intersys.xep.Event;
import com.intersys.xep.EventPersister;
import com.intersys.xep.EventQuery;
import com.intersys.xep.EventQueryIterator;
import com.intersys.xep.PersisterFactory;
import com.intersys.xep.XEPException;
#Service
public class CompanyService {
public List<Company> fetch() {
EventPersister myPersister = PersisterFactory.createPersister();
myPersister.connect("SAMPLES", "user", "pwd");
try { // delete any existing SingleStringSample events, then import
// new ones
Event.isEvent("Sample.Company");
myPersister.deleteExtent("Sample.Company");
String[] generatedClasses = myPersister.importSchema("Sample.Company");
for (int i = 0; i < generatedClasses.length; i++) {
System.out.println("Event class " + generatedClasses[i]
+ " successfully imported.");
}
} catch (XEPException e) {
System.out.println("import failed:\n" + e);
throw new RuntimeException(e);
}
EventQuery<Company> myQuery = null;
List<Company> list = new ArrayList<Company>();
try {
Event newEvent = myPersister.getEvent("Sample.Company");
String sql = "Select * from Sample.Company";
myQuery = newEvent.createQuery(sql);
newEvent.close();
myQuery.execute();
EventQueryIterator<Company> iterator = myQuery.getIterator();
while (iterator.hasNext()) {
Company c = iterator.next();
System.out.println(c);
list.add(c);
}
myQuery.close();
myPersister.close();
return list;
} catch (XEPException e) {
System.out.println("createQuery failed:\n" + e);
throw new RuntimeException(e);
}
}
}
When I try executing the fetch() method of the above class, I am seeing the following exception -
com.intersys.xep.XEPException: Cannot import - extent for Sample.Company not empty.
at com.intersys.xep.internal.Generator.generate(Generator.java:52)
at com.intersys.xep.EventPersister.importSchema(EventPersister.java:954)
at com.intersys.xep.EventPersister.importSchema(EventPersister.java:363)
I got the simple string example working. Does it mean, we can not read the existing data using XEP? If we can read, Could some please help me in resolving the above issue? Thanks in advance.
You are trying to create a new class named Sample.Company in your instance:
String[] generatedClasses = myPersister.importSchema("Sample.Company");
But you still have data and an existing class there.

How do I write an email body to a text file using the Java Gmail API

i'm trying to access my Gmail account using Java Gmail API then access the body of the first Email and then save it into text file using this path in my computer D:\Email , so any suggestion ? i have tried so many examples such as using saveFile but none of them worked for me !
NOTE: i want only to save the body of the Email
package ReadingEmail;
import java.util.*;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Store;
//===================================================================================
public class ReadingEmail {
public static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
Properties props = new Properties();
props.setProperty("mail.store.protocol", "imaps");
try {
Session session = Session.getInstance(props, null);
Store store = session.getStore();
System.out.println("enter your email");
String email= input.nextLine();
System.out.println("enter your password");
String pass= input.nextLine();
store.connect("imap.gmail.com", email, pass); //connect to email
Folder inbox = store.getFolder("INBOX");// go to index
inbox.open(Folder.READ_ONLY); // open index
//==============================================================================================
int messageCount = inbox.getMessageCount();// line 20,21 show the number of emails
System.out.println("Total Messages" + messageCount);
int Message1 = messageCount;
int Message2 = Message1 -1 ;
Message msg1= inbox.getMessage(messageCount);
Message msg2= inbox.getMessage(Message2);
Address[] in1 = msg1.getFrom();
for (Address address1 : in1) {}
//================================================================================
Message msg = inbox.getMessage(inbox.getMessageCount());
Address[] in = msg.getFrom();
for (Address address : in) {
}
Multipart mp = (Multipart) msg.getContent();
BodyPart bp = mp.getBodyPart(0);
System.out.println("CONTENT:" + bp.getContent());
}
catch (Exception ex) // wrong password
{ System.out.println("the email or password is wrong "); }
}
}
Are you getting any error? Right now I am unable to see any code to save to a file.
Also when you use System.out.println("CONTENT:" + bp.getContent()); are you able to print the text to console or not?

Executing multiple commands using j2ssh

I would like to know how to execute multiple commands using j2ssh. The code I got from the net is as follows:
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import com.sshtools.j2ssh.io.IOStreamConnector;
import com.sshtools.j2ssh.io.IOStreamConnectorState;
import com.sshtools.j2ssh.connection.*;
import com.sshtools.j2ssh.SshClient;
import com.sshtools.j2ssh.authentication.PasswordAuthenticationClient;
import com.sshtools.j2ssh.authentication.AuthenticationProtocolState;
import com.sshtools.j2ssh.session.SessionChannelClient;
import com.sshtools.j2ssh.configuration.SshConnectionProperties;
import com.sshtools.j2ssh.transport.ConsoleHostKeyVerification;
public class MySSHClient {
SshClient ssh = null;
SshConnectionProperties properties = null;
SessionChannelClient session = null;
public MySSHClient(String hostName, String userName, String passwd )
{
try
{
// Make a client connection
ssh = new SshClient();
properties = new SshConnectionProperties();
properties.setHost(hostName);
// Connect to the host
ssh.connect(properties, new ConsoleHostKeyVerification());
// Create a password authentication instance
PasswordAuthenticationClient pwd = new PasswordAuthenticationClient();
pwd.setUsername(userName);
pwd.setPassword(passwd);
// Try the authentication
int result = ssh.authenticate(pwd);
// Evaluate the result
if (result==AuthenticationProtocolState.COMPLETE) {
System.out.println("Connection Authenticated");
}
}
catch(Exception e)
{
System.out.println("Exception : " + e.getMessage());
}
}//end of method.
public String execCmd(String cmd)
{
String theOutput = "";
try
{
// The connection is authenticated we can now do some real work!
session = ssh.openSessionChannel();
if ( session.executeCommand(cmd) )
{
IOStreamConnector output = new IOStreamConnector();
java.io.ByteArrayOutputStream bos = new
java.io.ByteArrayOutputStream();
output.connect(session.getInputStream(), bos );
session.getState().waitForState(ChannelState.CHANNEL_CLOSED);
theOutput = bos.toString();
}
//else
//throw Exception("Failed to execute command : " + cmd);
//System.out.println("Failed to execute command : " + cmd);
}
catch(Exception e)
{
System.out.println("Exception : " + e.getMessage());
}
return theOutput;
}
}
I tried to go to a directory then list the files using the ls command but it didn't work
MySSHClient sshc = new MySSHClient(<hostName>, <userName>, <passwd>);
System.out.println( sshc.execCmd("cd test") );
System.out.println( sshc.execCmd("ls") );
Any help please?
Try separating commands by a semicolon. For example: System.out.println( sshc.execCmd("cd test; ls") );
Add the and operator (&&) between the commands:
System.out.println( sshc.execCmd("cd test && ls") );
&& is better than ; because if the cd fails the ls is not executed.
Instead of using executeCommand, try to write your commands in output stream - session.getOutputStream() with '\n' addition on the end.
Then read input stream.
For example:
session.getOutputStream().write((command + "\n").getBytes());