I have a web app which I would like to test using Selenium, with this app communicating with the backend using a REST API.
It is my understanding that Selenium is mainly used to test the flows through an application and the appearance/presence of widgets for each of these states. This would suggest to me that it makes a lot of sense when writing Selenium tests to simulate the backend. Python is my language of choice but I am also familiar with node.js, javascript and JAVA. What approach would you recommend with regard to simulating the REST API. I was thinking of writing a server using Python. I can create this server within my test environment and configure how it responds to requests from the front-end on a test by test basis. Are there any tools, libraries you might recommend me?
I should also add that I am using raml to define my api.
So with my simulation of the backend, the tests would look something like this:
def test_no_table_for_one_user():
# configure reply for api request
rest_sim.get_users_response = (200, [{name: "Foo Bar", address: "West side"}])
navigate_to_users_page()
# test that this users details are presented without the use of a table
...
def test_table_for_multiple_users():
# configure reply for api request
rest_sim.get_users_response = (200, [{name: "Foo Bar", address: "West side"}, {name: "Foo Baz", address: "East side"}])
navigate_to_users_page()
# test that the two users are presented in the form of a table
...
For mocking simple REST API you can try node.js-based json-server.
It's easy to setup, you just need to create JSON file with some data to simulate db, json-server will create all common REST API routes for you.
There are many libraries and tools available to help you with this. What you are talking about is creating a test harness, or emulator/simulator. In most situations, it is generally recommended that the person who builds and develops the backend, provide you with the harness since they are owners of the API and control different versions and change. Reciprocally, you can provide them with your client so they can understand how you use the API.
If they cannot do this, then you will need to create a harness yourself. The best tool to help you do this for HTTP API's is WireMock
http://wiremock.org/
In your example you will probably want to run this as Stand Alone:
http://wiremock.org/docs/running-standalone/
And then using JSON file configuration to define the behaviour.
My preference is to also wrap and deploy you WireMock test harness as a Docker image and publish to a Docker repository so that other people can use it. In this case its simply a case of creating a Dockerfile with the following and running a docker container:
Dockerfile
FROM java:8
WORKDIR /opt
RUN apt-get install wget
RUN wget http://repo1.maven.org/maven2/com/github/tomakehurst/wiremock-standalone/2.5.0/wiremock-standalone-2.5.0.jar
RUN mkdir mappings
VOLUME /opt/mappings
EXPOSE 8080
CMD java -jar wiremock-standalone-2.5.0.jar
command line
docker build -t wiremock/apiname:[version] .
docker run -d -p [exposedport]:8080 -v /directory/with/json:/opt/mappings --name apiname wiremock/apiname:[version]
I would choose Python without any problems.
Please have a look at the requests module:
http://docs.python-requests.org/en/master/
It is really easy to install and to make requests by using REST messages.
No matter what you have to do, I will continue with Python.
How to use REST API from requests after installation (with pip for instance):
import requests
class RESTIF():
'''
Class to handle a connection towards your server
'''
def __init__(self):
'''Initialization of a single Session and header dictionary to be used for REST requests.'''
self.nSession = requests.Session()
# Default header values to get initial connection:
self.header = {"Content-Type":"application/json",
"KeepAlive":"true",
"Authorization":"Basic ",
"Cookie": None}
def action(self, URL, JSONdata):
myCreate = self.nSession.post(URL, headers=self.header, data=JSONdata)
The header is quite useful in case of Cookie exchange. Requests will take care of that.
You can handle login to a rest api or send PUT/POST/DELETE/GET messages easily!
Everything is possible and no need to switch to Java or other languages.
Please let me know if you have additional queries or that solved your question. Have a great one!
Related
I'm trying to find some API (for example java, but could be some other) how to get published docker image names / tags from google cloud platform registry. I found how to do this using gcloud console commands:
gcloud container images list-tags gcr.io/[GCP_REPOSITORY_NAME]
And it basically gave what I want, but it is console and I need this data get programmatically on back-end side. Any ideas guys? Thanks in advance.
Currently there is no REST API for the Google Container Registry product but you can use the Registry name as an URL and run an HTTP request within your Java code against it:
curl -u "oauth2accesstoken:yourAccessToken" https://gcr.io/v2/yourProject/yourImage/tags/list
You can get the accessToken with the command gcloud auth print-access-token. The recommend approach is that it belongs to a serviceAccount.
Although I am not sure if the Docker Registry HTTP API V2 is fully compatible with Google Container Registry, this specific method has worked for me.
I have developed one web service for order management. This web service takes many complex objects as input parameters. I used curl to test and it works fine. Now I am writing a client but having issue when for ArrayList (e.g. the items are coming as ArrayList) objects. It's sending as String. It's seems the limitation the client framework I am using. I have tried one or two open frameworks but they are not working as expected. It will be great if you can suggest some framework with some examples.
Below is the sample curl request, I have removed some extra parameters to keep it simple.
curl -L -v -b agent_cookies.txt -H "Content-Type: application/json" -d
"{"items":{"atg-rest-class-type":"java.util.ArrayList","atg-rest-values":
[{"atg-rest-class-type":"com.bean.CommerceItemInfo","tinSkuNumber":"41589367","itemNumber":
280594,"color": 9,"size":
94,"salePrice":50.00,"taxAmount":3.5,"stateTax":0.48,"countyTax":0.08,"currencyCode":"USD"},{"atg-rest-class-type":"com..bean.CommerceItemInfo",
"tinSkuNumber":"41589375","itemNumber": 280594,"color": 9,"size":
96,"salePrice":100.00,"taxAmount":7,"stateTax":0.96,"countyTax":0.16,"currencyCode":"USD"}]},orderInfo:{...},"clientAddress":{"atg-rest-class-type":"java.util.ArrayList","atg-rest-values":
[{"atg-rest-class-type":"com.bean.ClientAddress",\"firstName\":\"John\",\"lastName\":\"Dao\",\"state\":\"FL\",\"country\":\"US\",\"postalCode\":\"33606\",\"address1\":\"100
S Edison Avenue\",\"address2\":\"Suite
D\",\"city\":\"Tampa\",\"addressType\":\"BOTH\"}]},{......}}"
http://localhost:8080/rest/model/com/web/actor/CartActor/testOrder
Thank you
After some research I found the limitation of ATG client and no way we can send List.I changed the arguments to accept individual beans only.
I've inherited a project that contains many jaxws services. I want to add another one and am trying to duplicate a similar working example. I can test that one like this
./soapget.sh soap_serial.xml r.xml
where soapget.sh is
#!/bin/bash
wget "http://localhost:5032/VCWH_QueryService/soap/SettopChannelMapResourceService" --post-file=$1 --header="Content-Type: text/xml" -O $2
This produces a good response, captured in r.xml.
Like the working service, my new service uses three classes. The code compiles ok, assembles into a .war file, and deploys. Now when I try the same thing for the new service I wrote
./bsg.sh soap_rate.xml r2.xml
where bsg.sh is
#!/bin/bash
wget "http://localhost:5032/VCWH_QueryService/soap/BsgHandleResourceService" --post-file=$1 --header="Content-Type: text/xml" -O $2
I get the useless error
2015-11-23 20:26:52 ERROR 500: Internal Server Error
The log files for the project do not contain any more info either.
There are just too many black boxes interacting that I can't figure out what's going on... Maven-Enunciate-Plugin, jax-ws, Java, etc.
For example, how does calling BSGHandleResourceService find its way to the actual code, one of which is called BSGHandleResource.java? Normally I would make those hooks in the web.xml file but that has been taken over by the black boxes.
Are there any jax-ws/maven experts out there that can shed some light?
I was able to find and fix the problem by sending a soap request to the service using SoapUI. That returned useful error messages whereas the other method did not.
I'm porting a PowerShell script to Java. One of the PowerShell commands is Invoke-WebRequest that looks like:
$r = Invoke-WebRequest $formUrl -SessionVariable session1
I was wondering if anyone knew a quick way of doing this in Java?
Thanks in advance.
Invoke-WebRequest issues a HTTP request to the URL at $formUrl and stores the results in the $r variable. The -SessionVariable argument also stores state information, such as cookies and credentials in an object that can be shared with further requests. See http://technet.microsoft.com/en-us/library/hh849901.aspx for a complete documentation on Invoke-WebRequest.
In Java, you can use java.net.HttpURLConnection / java.net.URL to issue a HTTP request and fetch the response. From what I gather, these are pretty-low level classes and you will have to do quite a bit of bookkeeping to provide the functionality of a PowerShell session variable. For instance, cookie management is provided by java.net.CookieManager, but credentials are handled a different way.
You may also want to look into Apache HttpComponents (formerly called Apache HttpClient) or other HTTP libraries for Java that take care of state management.
I need to query a nrpe nagios server from a Java application remotely just as check_nrpe would do:
check_nrpe -H 192.***.***.*** -p 56** -c "check_load"
When I say "from a Java application" I mean I want the results to be received and processed at my Java application. The first idea I had was to call the "check_nrpe" command from my application and retrieve its output and return value but I would like more a standalone solution where no external programs are called.
I don't need to wait for state changes, just eventually check the monitor state. Since I have been unable to locate any Java library (should I try JNRPE?), I would like to implement the protocol check_nrpe and nrpe daemon use to communicate.
Have any of you tried this before? In that case, do you have a description of this protocol?
If your answers are negative I will try to analize the protocol using whireshark but any clue will be much appreciated.
An explanation of NRPE protocol from Andreas Marschke blog, The NRPE Protocol explained (on gitHub too)
Anyway, JNRPE have a full working implementation of the protocol, you can download jcheck_nrpe-2.0.3-RC5 source code and take a look at jcheck_nrpe-2.0.3-RC5\src\main\java\it\jnrpe\client\JNRPEClient.java class for a sample client who's using jnrpe-lib-1.0.1-RC5.
jnrpe-lib have two concrete classes which implements the protocol request and response
JNRPERequest.java
JNRPEResponse.java
The full protocol implementation classes can be found at jnrpe-lib-1.0.1-RC5\src\main\java\it\jnrpe\net\ folder