Reflection error unit testing Java with Cucumber - junit

I am running one simple cucumber test.
While running I am getting the following error.
java.lang.reflect.InvocationTargetException
My Runner class is -
package com.my.automation;
import cucumber.junit.Cucumber;
import org.junit.runner.RunWith;
#RunWith(Cucumber.class)
#Cucumber.Options(format = {"html:target/cucumber-html","json:target/cucumber.json",
"junit:target/cucumber-junit/cukey-junit_results.xml"},
features = {"src/test/resources/com/my/automation/cuketest/CukeTest.feature"} )
public class RunTest {
}

Related

generate html and json reports for selenium python automation test using pytest

I have a selenium python automation test, it works fine, now I want to generate Html and JSON reports and have screenshots in the report using pytest. I am new to automation and python so I am not much aware of how its done.
following is my code
test_screenshot.py
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import pytest_html
from selenium.common.exceptions import InvalidSessionIdException
def test_Openurl(setup):
driver = setup["driver"]
url = setup["url"]
try:
driver.get(url)
except Exception as e:
print(e.message)
assert driver.current_url == URL
driver.save_screenshot("ss.png")
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
driver.save_screenshot("ss1.png")
driver.close()
conftest.py
import pytest
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service
def pytest_addoption(parser):
parser.addoption("--url", action="store", default="https://google.com/")
#pytest.fixture()
def setup(pytestconfig):
s = Service("C:/Users/Yash/Downloads/chromedriver_win32/chromedriver.exe")
driver = webdriver.Chrome(service=s)
driver.maximize_window()
yield {"driver":driver, "url": pytestconfig.getoption("url")}
I ran this using
pytest test_screenshot.py --url "https://www.netflix.com/in/"
Test case is passed. How do I generate HTML and JSON report?
I tried this
pytest -v -s --json-report --json-report-indent=4 --json-report-file=report/report.json --html=report/report.html test_screenshot.py
but got this error
ERROR: usage: pytest [options] [file_or_dir] [file_or_dir] [...]
pytest: error: unrecognized arguments: --json-report --json-report-indent=4 --json-report-file=report/report.json
inifile: None
You need to install these two libraries : https://pypi.org/project/pytest-json-report/ & https://pypi.org/project/pytest-html/

Using Spring Boot Data to read MySQL data

I'm trying to create a framework to read data from MySQL using Spring Data. The end goal is to be able to write automated tests that could read data from two different MySQL dbs and compare the data (for example, to make sure data is replicating correctly). I'm currently having loads of trouble in actually getting the Spring code to work (I've never used Spring before, I've tried modifying some various tutorial code I've found on the web, but so far haven't gotten it working.)
Here's what I've got.
MySQL
table: credentials
columns: id (int), password_hash (string)
Has 4 entries in it.
Project layout:
src/main
groovy
domain
Credentials
repository
CredentialsRepository
resources
application.properties
src/test/groovy/
CredentialsTest
build.gradle
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.4.3.RELEASE")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'
jar {
baseName = 'gs-accessing-data-jpa'
version = '0.1.0'
}
repositories {
mavenCentral()
maven { url "https://repository.jboss.org/nexus/content/repositories/releases" }
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
dependencies {
compile 'org.codehaus.groovy:groovy-all:2.4.7'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa', version: '1.4.3.RELEASE'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-test', version: '1.4.3.RELEASE'
testCompile 'junit:junit:4.11'
}
application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/my_db
spring.datasource.username=my_user
spring.datasource.password=my_password
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.show_sql=true
spring.jpa.properties.hibernate.use_sql_comments=true
spring.jpa.properties.hibernate.format_sql=true
Credentials.groovy
package domain
import org.springframework.data.annotation.Id
import javax.persistence.Column
import javax.persistence.Entity
import javax.persistence.GeneratedValue
import javax.persistence.GenerationType
import javax.persistence.Table
#Entity
#Table(name = 'credentials')
class Credentials {
#Id #GeneratedValue(strategy = GenerationType.AUTO) #Column(name='id')
int id
#Column(name='password_hash')
String passwordHash
protected Credentials() {}
#Override
String toString() {
"Credential: [id=${id}, passwordHash=${passwordHash}]"
}
}
CredentialsRepository.groovy
package repository
import domain.Credentials
import org.springframework.data.repository.CrudRepository
interface CredentialsRepository extends CrudRepository<Credentials, Integer> {
}
CredentialsTest.groovy
import domain.Credentials
import repository.CredentialsRepository
import org.junit.Test
import org.junit.runner.RunWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner
import static org.junit.Assert.assertEquals
#RunWith(SpringJUnit4ClassRunner.class) //#EnableJpaRepositories(['domain.Credentials'])
#SpringBootTest(classes = MysqlJpaDemoApplication.class)
class CredentialsTest {
#Autowired
CredentialsRepository credentialsRepository
#Test
void testLoadCredentials() {
List<Credentials> credentialsList = credentialsRepository.findAll() as ArrayList<Credentials>
assertEquals(20, credentialsList.size())
}
}
Running the testLoadCredentials test gives the following stacktrace:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'CredentialsTest': Unsatisfied dependency expressed through field 'credentialsRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'repository.CredentialsRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1225)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:386)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:118)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
at org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener.prepareTestInstance(SpringBootDependencyInjectionTestExecutionListener.java:44)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:237)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'repository.CredentialsRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1474)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1102)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1064)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585)
... 33 more
2016-12-28 14:14:32.638 INFO 39748 --- [ Thread-1] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext#742ff096: startup date [Wed Dec 28 14:14:32 PST 2016]; root of context hierarchy
Process finished with exit code 255
Seems that the application class MysqlJpaDemoApplication that you're using to configure your tests is in the default (top-level) package. As Spring runs some checks when using #ComponentScan, it will prevent your application to scan the whole classpath.
You should move MysqlJpaDemoApplication to a new package, ie,com.example. Your source folder would look like this:
src/main
/groovy/com/example
|-- /domain
| |-- Credentials.groovy
|-- /repository
| |-- CredentialsRepository.groovy
|-- MysqlJpaDemoApplicatin.groovy
Looks like this is what got it to work:
com.example/
domain/
Credentials
repository/
CredentialsRepository
SpringConfig
Credentials.groovy
#Entity
#Table(name = 'credentials')
class Credentials {
#Id #GeneratedValue(strategy = GenerationType.AUTO)
int id
#Column(name='password_hash')
String passwordHash
protected Credentials() {}
#Override
String toString() {
"Credential: [id=${id}, passwordHash=${passwordHash}]"
}
}
CredentialsRepository
interface CredentialsRepository extends CrudRepository<Credentials, Integer> {}
SpringConfig.groovy
#Configuration
#EnableAutoConfiguration
#ComponentScan('com.example')
class SpringConfig {}
CredentialsTest.groovy
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes=SpringConfig.class)
#SpringBootTest(classes = SpringConfig.class)
class CredentialsTest {
#Autowired
CredentialsRepository credentialsRepository
#Test
void testLoadCredentials() {
List<Credentials> credentialsList = credentialsRepository.findAll() as ArrayList<Credentials>
assertEquals(4, credentialsList.size())
}
}

Error, when i try validate Json from response with schema in soapUI

i use sopaUI 5.0.0 with libraries:
btf 1.2
jackson-annotations-2.0.1
jackson-core-2.8.1
jackson-coreutils-1.8
json-schema-core-1.2.5
json-schema-validator-2.2.6
I try do this code:
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.ObjectMapper
import com.github.fge.jsonschema.core.report.ProcessingReport
import com.github.fge.jsonschema.main.JsonSchema
import com.github.fge.jsonschema.main.JsonSchemaFactory
def response = testRunner.testCase.getTestStepByName("getClientByID").getPropertyValue("response")
ObjectMapper mapper = new ObjectMapper()
JsonNode invoiceJSON = mapper.readTree(response)
JsonNode invoiceSchemaJSON = mapper.readTree(new File("C:\\test\\resources\\schems\\client-card-rs.json"))
log.info( invoiceSchemaJSON)
JsonSchemaFactory factory = JsonSchemaFactory.byDefault()
JsonSchema invoiceSchema = factory.getJsonSchema(invoiceSchemaJSON)
if (invoiceSchema.validInstance(invoiceJSON)) log.info("Response Validated!")
else {
testRunner.fail(invoiceSchema.validate(invoiceJSON).toString())
}
But script crash with error at line:
JsonSchemaFactory factory = JsonSchemaFactory.byDefault()
First,issued error:
"write_bigdecimal_as_plain"
Later
java.lang.NoClassDefFoundError: Could not initialize class com.github.fge.jsonschema.SchemaVersion
SoapUI error log:
2016-09-11 15:39:49,202 ERROR [errorlog] java.lang.NoClassDefFoundError: Could not initialize class com.github.fge.jsonschema.SchemaVersion
java.lang.NoClassDefFoundError: Could not initialize class com.github.fge.jsonschema.SchemaVersion
at com.github.fge.jsonschema.core.load.configuration.LoadingConfigurationBuilder.<init>(LoadingConfigurationBuilder.java:117)
at com.github.fge.jsonschema.core.load.configuration.LoadingConfiguration.byDefault(LoadingConfiguration.java:151)
at com.github.fge.jsonschema.main.JsonSchemaFactoryBuilder.<init>(JsonSchemaFactoryBuilder.java:67)
at com.github.fge.jsonschema.main.JsonSchemaFactory.newBuilder(JsonSchemaFactory.java:123)
at com.github.fge.jsonschema.main.JsonSchemaFactory.byDefault(JsonSchemaFactory.java:113)
at com.github.fge.jsonschema.main.JsonSchemaFactory$byDefault.call(Unknown Source)
at Script6.run(Script6.groovy:20)
at com.eviware.soapui.support.scripting.groovy.SoapUIGroovyScriptEngine.run(SoapUIGroovyScriptEngine.java:100)
at com.eviware.soapui.impl.wsdl.teststeps.WsdlGroovyScriptTestStep.run(WsdlGroovyScriptTestStep.java:154)
at com.eviware.soapui.impl.wsdl.panels.teststeps.GroovyScriptStepDesktopPanel$RunAction$1.run(GroovyScriptStepDesktopPanel.java:277)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Help pls.
The only solution that worked for me was using the json-schema-validator-2.2.8-lib.jar from com.github.java-json-tools (https://mvnrepository.com/artifact/com.github.java-json-tools/json-schema-validator/2.2.8) instead of com.github.fge (which supported the project till its 2.2.6 version). It is important to use the package of libs provided instead of collecting all the relevant dependencies manually. Somehow it doesn't want to work correctly.
I am using SoapUI 5.2.1 on Docker container built on top of an OpenJDK 8 image.

json4s NoSuchMethodError on running

I'm using json4s to parse json string, the code is running good locally, but when I put it into the production server, it throws NoSuchMethodError. My code as follows please:
import scala.util.parsing.json.JSON
import scala.util.matching.Regex
import org.json4s._
import org.json4s.JsonDSL._
import org.json4s.native.JsonMethods._
import org.json4s.JsonInput
def getIndexMap(vtStr: String): Map[String, Any] = {
implicit val formats = DefaultFormats
import org.json4s.native.JsonMethods
import JsonMethods._
var json = JsonMethods.parse(StringInput(vtStr), false, true) // the exception thrown here
}
The stacktrace please:
WARN scheduler.TaskSetManager: Lost task 0.0 in stage 3.0 (TID 79, avh007.av.pan.local): java.lang.NoSuchMethodError: scala.runtime.ObjectRef.create(Ljava/lang/Object;)Lscala/runtime/ObjectRef;
at org.json4s.native.JsonParser$$anonfun$1.apply(JsonParser.scala:145)
at org.json4s.native.JsonParser$$anonfun$1.apply(JsonParser.scala:143)
at org.json4s.native.JsonParser$.parse(JsonParser.scala:131)
at org.json4s.native.JsonParser$.parse(JsonParser.scala:71)
at org.json4s.native.JsonParser$.parse(JsonParser.scala:66)
at org.json4s.native.JsonMethods$class.parse(JsonMethods.scala:11)
at org.json4s.native.JsonMethods$.parse(JsonMethods.scala:63)
at com.panw.spark.PanavParser$.getIndexMap(PanavParser.scala:84)
at com.panw.spark.PanavStreamScala2$$anonfun$main$2$$anonfun$apply$1$$anonfun$apply$2.apply(PanavStreamScala2.scala:184)
at com.panw.spark.PanavStreamScala2$$anonfun$main$2$$anonfun$apply$1$$anonfun$apply$2.apply(PanavStreamScala2.scala:163)
at scala.collection.Iterator$class.foreach(Iterator.scala:727)
at scala.collection.AbstractIterator.foreach(Iterator.scala:1157)
at com.panw.spark.PanavStreamScala2$$anonfun$main$2$$anonfun$apply$1.apply(PanavStreamScala2.scala:163)
at com.panw.spark.PanavStreamScala2$$anonfun$main$2$$anonfun$apply$1.apply(PanavStreamScala2.scala:140)
at org.apache.spark.rdd.RDD$$anonfun$foreachPartition$1.apply(RDD.scala:806)
at org.apache.spark.rdd.RDD$$anonfun$foreachPartition$1.apply(RDD.scala:806)
at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:1498)
at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:1498)
at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:61)
at org.apache.spark.scheduler.Task.run(Task.scala:64)
at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:203)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)

Gradle loads mysql-connector jar but no dbunit jar as external dependencies, why?

Please give me some lights about what I'm doing wrong here. First of all I'm newbie with Gradle and Groovy and for learning purposes I'm playing with them and DBUnit.
I tried the code listed below, my goal is to generate a dataset getting the data from a mysql db.
import groovy.sql.Sql
import org.dbunit.database.DatabaseConnection;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.xml.FlatXmlDataSet;
repositories {
mavenCentral()
}
configurations {
dbunit
}
dependencies {
dbunit 'dbunit:dbunit:2.2',
'junit:junit:4.11',
'mysql:mysql-connector-java:5.1.25'
}
URLClassLoader loader = GroovyObject.class.classLoader
configurations.dbunit.each { File file -> loader.addURL(file.toURL()) }
task listJars << {
configurations.dbunit.each { File file -> println file.name }
}
task listTables << {
getConnection("mydb").eachRow('show tables') { row -> println row[0] }
}
task generateDataSet << {
def IDatabaseConnection conn = new DatabaseConnection(getConnection("mydb").connection)
def IDataSet fullDataSet = conn.createDataSet()
FlatXmlDataSet.write(fullDataSet, new FileOutputStream("full.xml"))
}
static Sql getConnection(db) {
def props = [user: 'dbuser', password: 'userpass', allowMultiQueries: 'true'] as Properties
def url = (db) ? 'jdbc:mysql://host:3306/'.plus(db) : 'jdbc:mysql://host:3306/'
def driver = 'com.mysql.jdbc.Driver'
Sql.newInstance(url, props, driver)
}
What is weird to me is that all MySQL methods work well, I can get the list of tables and for instance the connection was done well so the mysql-connector-java.jar is being loaded (I think), but when I add the DBUnit stuff (import libs and the generateDataSet method) it seems the dbunit jar is not available for the script, I got the following errors:
FAILURE: Build failed with an exception.
* Where:
Build file '/home/me/tmp/dbunit/build.gradle' line: 5
* What went wrong:
Could not compile build file '/home/me/tmp/dbunit/build.gradle'.
> startup failed:
build file '/home/me/tmp/dbunit/build.gradle': 5: unable to resolve class org.dbunit.dataset.xml.FlatXmlDataSet
# line 5, column 1.
import org.dbunit.dataset.xml.FlatXmlDataSet;
^
build file '/home/me/tmp/dbunit/build.gradle': 2: unable to resolve class org.dbunit.database.DatabaseConnection
# line 2, column 1.
import org.dbunit.database.DatabaseConnection;
^
build file '/home/me/tmp/dbunit/build.gradle': 3: unable to resolve class org.dbunit.database.IDatabaseConnection
# line 3, column 1.
import org.dbunit.database.IDatabaseConnection;
^
build file '/home/me/tmp/dbunit/build.gradle': 4: unable to resolve class org.dbunit.dataset.IDataSet
# line 4, column 1.
import org.dbunit.dataset.IDataSet;
^
4 errors
But if I call the listJars task, I got this:
:listJars
junit-4.11.jar
mysql-connector-java-5.1.25.jar
hamcrest-core-1.3.jar
xercesImpl-2.6.2.jar
xmlParserAPIs-2.6.2.jar
junit-addons-1.4.jar
poi-2.5.1-final-20040804.jar
commons-collections-3.1.jar
commons-lang-2.1.jar
commons-logging-1.0.4.jar
dbunit-2.2.jar
BUILD SUCCESSFUL
Which in my understanding means all those jars were loaded and are available for the script, am I right? or am I doing something wrong with the class loader stuff?
Thanks very much.
The GroovyObject.class.classLoader.addURL hack is not the right way to add a dependency to the build script class path. It's just sometimes necessary to get JDBC drivers to work with Groovy (long story). Here is how you add a dependency to the build script class path:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath "some:library:1.0"
}
}
// library can be used in the rest of the build script
You can learn more about this in the Gradle User Guide.