Why does my script has all red lines when I enter status code in Assertion - rest-assured

I am new in API testing and writing my first java script. Every thing works fine till I tried to do assertion and put status Code 200. Then whole script got red lines.
import io.restassured.RestAssured;
import static io.restassured.RestAssured.given;
public class Bases {
public static void main(String[] args) {
RestAssured.baseURI= "https://maps.googleapis.com";
given().
param("input","%2B61293744000").
param("inputtype" , "phonenumber").
param("fields","place_id").
param("key","AIzaSyAPKUY3YgFBlyyQxjh9q9RQ5cDFdDjqlz4").
when().
get("/maps/api/place/findplacefromtext/json").
then().assertThat().statusCode(200);

I just downloaded jars ver 3.2 and it works now. So I believe we can not use update
ver 4.1.2.jars.

Related

Cannot import package in unit tests for a Jenkins Shared Library

I'm attempting to create unit tests for a JenkinsShared library using Gradle in order to run the test tasks.
I've followed this tutorial which upon conclusion one has a working test suite for a shared library for functions within the vars folder (with the unit tests in src/test/groovy/*Test.groovy).
However, in our internal shared jenkins library we followed a more object oriented style and isolated functionality into a package of classes in the format: src/org/company/*.groovy.
The problem arises when attempting to import said package into a unit test class. In the tutorial, the functions are imported using the loadScript method this method fails when loading a class which is dependent on another file.
Take the class:
package tests
import org.junit.*
import com.lesfurets.jenkins.unit.*
import static groovy.test.GroovyAssert.*
import org.company.UtilFactory
class UtilFactoryTest extends BasePipelineTest {
#Test
void testCall() {
def util = UtilFactory.getUtil("hello")
assertEquals true, true
}
}
src/org/company/UtilFactory.groovy
package org.company
class UtilFactory implements Serializable {
static Util instance
static Util getUtil(script=null) {
if (!(UtilFactory.instance)) {
if (!script) {
// Throws an exception if on the first call to getUtil the
// script parameter is null.
throw new ScriptUndefinedException("script parameter null on initial call to getUtil")
}
UtilFactory.instance = new Util(script)
}
return UtilFactory.instance
}
}
class ScriptUndefinedException extends Exception {
// Parameterless Constructor
public ScriptUndefinedException() {}
// Constructor that accepts a message
public ScriptUndefinedException(String message)
{
super(message);
}
}
Which gives me the exception:
jenkins-utilities/src/test/groovy/UtilFactoryTest.groovy: 7:
unable to resolve class org.company.UtilFactory
# line 7, column 1.
import org.company.UtilFactory
This may be more of a Gradle issue than a JenkinsShared Library. I've just spent a good portion of my day trying to figure out exactly what I'm doing wrong to no avail.
I would really appreciate any help to guide me in the right direction.
This library may be helpful getting your shared libraries to work in the unit test https://github.com/stchar/pipeline-sharedlib-testharness

How to make UI receive scroll events

In my vaadin application I need to implement a fixed header, that changes size depending on the scroll position of the UI.
While there are geters for scroll position in Vaadin 8, there seems to be no functionallity implemented to listen for scroll events. So I tried to implement a JavaScript connector, that just informs the server-side UI, that the user has scrolled, so the server-side UI can then notify the Header as a scrollListener.
So far thats what I planned, but I just can't find out, how to implement my connector in a way that it.
is active after the site got requested by a Client.
is able to call my server-side UI.onScrollEvent() method.
Does anyone know, how the described behavior could be implemented?
Thank you for your help in advance.
After I ran into a few issues with implementaton of a custom widget to achieve, I went for a different approach, using extensions in a vaadin-sense. Here is the truncated code for what I did.
(Vaadin requires the client-side connector code shown later in this post to be in a Widget package. I'm not entirely sure if the server-side component has to be in one too, but for conformity reasons with the usual widget-skeleton I put it into one)
So in the package for the widget:
package my.company.project.scrollUI;
import com.vaadin.server.AbstractExtension;
import com.vaadin.ui.UI;
import my.company.project.scrollUI.client.scrollUI.ScrollUIServerRpc;
public class ScrollUI extends AbstractExtension {
private ScrollUIServerRpc rpc = new ScrollUIServerRpc() {
#Override
public void onScroll() {
//do whatever you need for your implementation
...
}
};
public ScrollUI() {
registerRpc(rpc);
}
public void extend(UI ui) {
super.extend(ui);
}
}
as usual the .gwt.xml file in the package folder, nothing special here:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE module PUBLIC "-//Google Inc.//DTD Google Web Toolkit 2.5.1//EN" "http://google-web-toolkit.googlecode.com/svn/tags/2.5.1/distro-source/core/src/gwt-module.dtd">
<module>
<inherits name="com.vaadin.DefaultWidgetSet" />
</module>
In the package for the client-side code to be compiled to JavaScript:
package my.company.project.scrollUI.client.scrollUI;
import com.vaadin.shared.communication.ServerRpc;
public Interface ScrollUIServerRpc extends ServerRpc {
public void onScroll();
}
And finally the connector for the extension:
package my.company.project.scrollUI.client.scrollUI;
import com.google.gwt.event.dom.client.ScrollEvent;
import com.google.gwt.event.dom.client.ScrollHandler;
import com.google.gwt.user.client.ui.Widget;
import com.vaadin.client.ComponentConnector;
import com.vaadin.client.ServerConnector;
import com.vaadin.client.communication.RpcProxy;
import com.vaadin.client.extensions.AbstractExtensionConnector;
import com.vaadin.shared.ui.Connect;
#Connect(ScrollUI.class)
public class ScrollUIConnector extends AbstractExtensionConnector {
ScrollUIServerRpc rpc = RpcProxy.create(ScrollUIServerRpc.class, this);
#Override
protected void extend(ServerConnector target) {
final Widget ui = ((ComponentConnector) target).getWidget();
ui.addDomHandler(new ScrollHandler() {
#Override
public void onScroll(ScrollEvent event) {
rpc.onScroll();
}
}, ScrollEvent.getType());
}
}
Now don't forget to compile the Widgetset and everything is good to go to be used for your actual UI like all other vaadin extensions:
public class MyUI extends com.vaadin.ui.UI {
#Override
protected void init(VaadinRequest vaadinRequest) {
ScrollUI scrollUI = new ScrollUI();
scrollUI.extend(this);
//everything else that needs to be done
...
}
//everything else that Needs to be done
...
}
I hope this was helpfull for anyone with a similar issue.
I have done this once few years ago by extending the layout component that wrapped the part of UI where I needed this. In GWT there is gwtproject.org/javadoc/latest/com/google/gwt/event/dom/client/… which can be used in DOM handler. So yes, GWT provides suitable client side event. I then used RPC call to server side, where I triggered the corresponding server side event, which I could listen in other parts of the app. The code is not public, but there is LazyLayout add-on that has similar type of implementation, which you could check as reference for your implementation.
https://github.com/alump/LazyLayouts/blob/master/lazylayouts-addon/src/main/java/org/vaadin/alump/lazylayouts/client/LazyVerticalLayoutConnector.java

How to create "Mandatory" spock extension

I am using Spock in combination with Geb for web browser testing.
I have created the "stepThrough" extension by following the instructions found here:
Spock Stepwise - Keep running testsuite after single failure
That works all fine and well, but I would like to make a new annotation. That sets a a geb feature method to "Mandatory" meaning that if this feature method fails I would like to stop execution of the rest of the test.
I like the stepThrough annotation because if one test case fails I can continue with the rest of my testing, but if something like login fails, then I would want to stop the testing because obviously nothing else would work if Login fails.
This is what I have so Far but it does not seem to be working. Where have I gone wrong?
Here is the Annotation class
import org.spockframework.runtime.extension.ExtensionAnnotation
import java.lang.annotation.ElementType
import java.lang.annotation.Retention
import java.lang.annotation.RetentionPolicy
import java.lang.annotation.Target
#Target(ElementType.METHOD)
#Retention(RetentionPolicy.RUNTIME)
#ExtensionAnnotation(ManditoryExtension.class)
#interface Manditory {}
Here is the extension:
class ManditoryExtension extends AbstractAnnotationDrivenExtension<Manditory>{
void visitFeatureAnnotation(Manditory annotation, FeatureInfo feature) {
skipFeaturesAfterFirstFailingFeature(feature)
}
private void skipFeaturesAfterFirstFailingFeature(final FeatureInfo feature){
feature.getParent().getBottomSpec().addListener(new AbstractRunListener() {
void error(ErrorInfo error) {
if (!error.getMethod().equals(feature)) return
for (FeatureInfo feat : feature.getSpec().getFeatures())
feat.setSkipped(true)
}
})
}
}

JMockit Mocking java.net.URL causes test not run

I'm using the newest versions of junit and jmockit and Oracle JDK 7 in Eclipse. When I try to mock java.net.URL my test won't run.
I have in my code something like:
URL url = new URL("String representing the url.");
So I figured in my test I could mock this like so:
#Mocked private URL _url;
Since this works for pretty much everything else, I know URL is final but I thought that was okay with JMockit.
When I run a test class with the above mock in eclipse the result is a grey line(as opposed to green or red.) So I'm assuming some kind of initialization problem. The rest of the test or code doesn't seem to matter, no matter what I put that #Mocked line in, this happens.
A workaround would be great, an explanation of what is actually causing this would be even better. Any help is definitely appreciated! Thanks!
Quick example. This actually gives an exception, but I think it is basically doing the same thing I have seen:
package demo;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class Connecting {
public boolean connectionattempt() throws IOException {
URL url = new URL("http://nowhere/");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
if (connection != null) {
return true;
}
else {
return false;
}
}
}
And this test:
package demo;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import org.junit.Test;
import mockit.Expectations;
import mockit.Mocked;
import mockit.Tested;
public class TestConnecting {
#Mocked URL _url;
#Mocked HttpURLConnection _connection;
#Tested Connecting _sut;
#Test
public void testConnect() throws IOException {
new Expectations() { {
_url.openConnection(); result = _connection;
} };
assertEquals(true, _sut.connectionattempt());
}
}
and the stack trace:
java.lang.NoClassDefFoundError: org/eclipse/jdt/internal/junit/runner/TestReferenceFailure
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestListener.testFailure(JUnit4TestListener.java:91)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestListener.testFailure(JUnit4TestListener.java:69)
at org.junit.runner.notification.RunNotifier$4.notifyListener(RunNotifier.java:139)
at org.junit.runner.notification.RunNotifier$SafeNotifier.run(RunNotifier.java:61)
at org.junit.runner.notification.RunNotifier.fireTestFailures(RunNotifier.java:134)
at org.junit.runner.notification.RunNotifier.fireTestFailure(RunNotifier.java:128)
at org.junit.internal.runners.model.EachTestNotifier.addFailure(EachTestNotifier.java:23)
at org.junit.runners.ParentRunner.run(ParentRunner.java:315)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
I executed the test on Eclipse Kepler SR2, IntelliJ IDEA 13.1, and Netbeans 8.0.1, using JMockit 1.13, JUnit 4.11, and Oracle JDK 1.7.0_67.
The test passes in every case, it's all green! So, I don't know what could possibly be the problem in your environment. Are you sure the "newest version" of JMockit (1.13 at this time) was the one actually used?

Using new Groovy Grape capability results in "unable to resolve class" error

I've tried to use the new Groovy Grape capability in Groovy 1.6-beta-2 but I get an error message;
unable to resolve class com.jidesoft.swing.JideSplitButton
from the Groovy Console (/opt/groovy/groovy-1.6-beta-2/bin/groovyConsole) when running the stock example;
import com.jidesoft.swing.JideSplitButton
#Grab(group='com.jidesoft', module='jide-oss', version='[2.2.1,)')
public class TestClassAnnotation {
public static String testMethod () {
return JideSplitButton.class.name
}
}
I even tried running the grape command line tool to ensure the library is imported. Like this;
$ /opt/groovy/groovy-1.6-beta-2/bin/grape install com.jidesoft jide-oss
which does install the library just fine. How do I get the code to run/compile correctly from the groovyConsole?
There is still some kinks in working out the startup/kill switch routine. For Beta-2 do this in it's own script first:
groovy.grape.Grape.initGrape()
Another issue you will run into deals with the joys of using an unbounded upper range. Jide-oss from 2.3.0 onward has been compiling their code to Java 6 bytecodes, so you will need to either run the console in Java 6 (which is what you would want to do for Swing anyway) or set an upper limit on the ranges, like so
import com.jidesoft.swing.JideSplitButton
#Grab(group='com.jidesoft', module='jide-oss', version='[2.2.1,2.3.0)')
public class TestClassAnnotation {
public static String testMethod () {
return JideSplitButton.class.name
}
}
new TestClassAnnotation().testMethod()
I finally got it working for Groovy Shell (1.6.5, JVM: 1.6.0_13). This should be documented better.
First at the command line...
grape install org.codehaus.groovy.modules.http-builder http-builder 0.5.0-RC2
Then in groovysh...
groovy:000> import groovy.grape.Grape
groovy:000> Grape.grab(group:'org.codehaus.groovy.modules.http-builder', module:'http-builder', version:'0.5.0-RC2')
groovy:000> def http= new groovyx.net.http.HTTPBuilder('http://rovio')
===> groovyx.net.http.HTTPBuilder#91520
The #grab is better used in a file than the shell.
Ok. Seems like this a short working demo (running from the groovyConsole)
groovy.grape.Grape.initGrape()
#Grab(group='com.jidesoft', module='jide-oss', version='[2.2.1,2.3.0)')
public class UsedToExposeAnnotationToComplier {}
com.jidesoft.swing.JideSplitButton.class.name
When run it produces
Result: "com.jidesoft.swing.JideSplitButton"
Very cool!!
The import statement must appear after the grabs.
Ps. At least one import statement must exists after the grabs
#Grab(group='com.jidesoft', module='jide-oss', version='[2.2.1,)')
import com.jidesoft.swing.JideSplitButton
public class TestClassAnnotation {
public static String testMethod () {
return JideSplitButton.class.name
}
}
Different example using latest RC-2 (note: Grab annotates createEmptyInts):
// create and use a primitive array
import org.apache.commons.collections.primitives.ArrayIntList
#Grab(group='commons-primitives', module='commons-primitives', version='1.0')
def createEmptyInts() { new ArrayIntList() }
def ints = createEmptyInts()
ints.add(0, 42)
assert ints.size() == 1
assert ints.get(0) == 42
Another example (note: Grab annotates getHtml):
// find the PDF links in the Java 1.5.0 documentation
#Grab(group='org.ccil.cowan.tagsoup', module='tagsoup', version='0.9.7')
def getHtml() {
def parser = new XmlParser(new org.ccil.cowan.tagsoup.Parser())
parser.parse("http://java.sun.com/j2se/1.5.0/download-pdf.html")
}
html.body.'**'.a.#href.grep(~/.*\.pdf/).each{ println it }
Another example (note: Grab annotates getFruit):
// Google Collections example
import com.google.common.collect.HashBiMap
#Grab(group='com.google.code.google-collections', module='google-collect', version='snapshot-20080530')
def getFruit() { [grape:'purple', lemon:'yellow', orange:'orange'] as HashBiMap }
assert fruit.inverse().yellow == 'lemon'

Resources