How to use allure annotations in code directly? - java

I am writing selenium based browser tests , I would like to implement #Step annotation inside page object models which are in src/java folder.
When doing that I am not able to use / import #Step annotation ( i have gradle ktls plugin installed )
This is code which is part of page object model under src/java
#Step("Find flow based on file name : {fileName}")
public DataTable findByFileName(String fileName) {
selectedElement= dataTableElementList.stream()
.filter(dataTableElement -> fileName.equals(dataTableElement.getFile_name()))
.findFirst()
.orElse(null);
return this;
}
Overall idea is to annotate all steps which are taken in page object model methods and then use it to create step-by-step annotated report.
My kotlin build
buildscript {
repositories {
mavenLocal()
jcenter()
}
}
tasks.existing(Wrapper::class) {
gradleVersion = "4.10.2"
distributionType = Wrapper.DistributionType.ALL
}
description = "LM"
group = "ru.lm"
version = version
plugins {
java
id("io.qameta.allure") version "2.6.0"
id("io.freefair.lombok") version "5.3.0"
}
java {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
val allureVersion = "2.9.0"
allure {
version = allureVersion
useTestNG {
version = allureVersion
}
downloadLink = "https://repo.maven.apache.org/maven2/io/qameta/allure/allure-commandline/$allureVersion/allure-commandline-$allureVersion.zip"
}
dependencies {
implementation("org.testng:testng:6.14.3")
implementation("com.fasterxml.jackson.core:jackson-annotations:2.12.3")
implementation("com.codeborne:selenide:6.2.1")
implementation("net.andreinc:mockneat:0.4.8")
implementation("com.konghq:unirest-java:4.0.0-RC2")
implementation("io.rest-assured:rest-assured:4.5.0")
implementation("org.hamcrest:hamcrest-all:1.3")
implementation("org.apache.logging.log4j:log4j-api:2.16.0")
implementation("org.apache.logging.log4j:log4j-core:2.16.0")
testImplementation("org.slf4j:slf4j-simple:2.0.0-alpha6")
}
tasks.named<Test>("test") {
useTestNG(closureOf<TestNGOptions> {
suites("src/test/resources/workflow.xml")
})
}
tasks.withType(JavaCompile::class) {
options.encoding = "UTF-8"
}
repositories {
mavenLocal()
jcenter()
}

Related

ClassNotFoundException When running jar file but runs fine in Intellij

I created a small mqtt application using eclipse paho mqtt library in kotlin with Gradle in Intellij IDE. it runs fine when running it through Intellij but when I build it and run the jar file that gets created I get a NoClassDefFoundError error.
From other questions I have seen about this it looks like it has something to do with the class path but I am not sure what needs to be done if that is indeed the issue because I am using gradle and not jar files for libraries.
I was following this tutorial
Here is my gradle file
plugins {
id 'org.jetbrains.kotlin.jvm' version '1.4.31'
id 'application'
}
group = 'me.package'
version = '1.0-SNAPSHOT'
repositories {
mavenCentral()
maven {
url "https://repo.eclipse.org/content/repositories/paho-snapshots/"
}
}
dependencies {
implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.2.5'
testImplementation 'org.jetbrains.kotlin:kotlin-test-junit'
}
test {
useJUnit()
}
compileKotlin {
kotlinOptions.jvmTarget = '1.8'
}
compileTestKotlin {
kotlinOptions.jvmTarget = '1.8'
}
application {
mainClassName = 'com.publisher.MainKt'
}
tasks.jar {
manifest {
attributes 'Main-Class': 'com.publisher.MainKt'
}
from {
configurations.compile.collect {
it.isDirectory() ? it : zipTree(it)
}
}
}
And my MainKt file
package com.publisher
import org.eclipse.paho.client.mqttv3.*
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence
import java.io.File
fun main(args: Array<String>) {
val client = MqttClient("tcp://192.168.0.55:1883","publisher", MemoryPersistence())
val connOpts = MqttConnectOptions()
connOpts.isCleanSession = false
connOpts.isAutomaticReconnect = true
client.setCallback(object: MqttCallback {
override fun connectionLost(cause: Throwable?) {
println("Connection lost")
println(cause!!.message)
}
override fun messageArrived(topic: String?, message: MqttMessage?) {
println("Message Received for topic: $topic")
println("Message: ${message!!.payload}")
}
override fun deliveryComplete(token: IMqttDeliveryToken?) {
println("Message delivered")
}
})
try{
client.connect(connOpts)
println("Connected")
client.subscribe("config/+", 1) { topic, message ->
println("Getting configuration for $message")
val path = System.getProperty("user.dir")
val file = File("$path/${message}.json")
if(file.exists()){
client.publish("/devices/ + $message + /config", MqttMessage(file.readBytes()))
}
}
}catch (e: MqttException){
println("Error: ${e.localizedMessage}")
e.printStackTrace()
}
}
The way you start your application does not include the dependencies, meaning your MQTT driver and the Kotlin dependencies are not included.
Do the following:
gradle distZip
# alternatively
gradle distTar
This will create a zip/tar file containing all the dependencies and a start script. Use that to start your application.
You could consider the Shadow plugin, as it is straightforward to use. Your build.gradle would look something like this:
plugins {
id 'org.jetbrains.kotlin.jvm' version '1.4.31'
// Shadow plugin
id 'com.github.johnrengelman.shadow' version '6.1.0'
id 'java'
}
group = 'me.package'
version = '1.0-SNAPSHOT'
repositories {
mavenCentral()
maven {
url "https://repo.eclipse.org/content/repositories/paho-snapshots/"
}
}
dependencies {
implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.2.5'
testImplementation 'org.jetbrains.kotlin:kotlin-test-junit'
}
test {
useJUnit()
}
compileKotlin {
kotlinOptions.jvmTarget = '1.8'
}
compileTestKotlin {
kotlinOptions.jvmTarget = '1.8'
}
application {
mainClassName = 'com.publisher.MainKt'
}
tasks.jar {
manifest {
attributes 'Main-Class': 'com.publisher.MainKt'
}
}
So your fat JAR is generated in the /build/libs directory with all the dependencies included.

Kotlin Gradle build with Spring Boot not publishing jars to Artifactory - only build info

I'm trying to publish a Spring Boot jar to Artifactory and cannot get it to work. Here's my build.gradle.kts:
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
group = "com.blah"
version = "0.0.2"
java.sourceCompatibility = JavaVersion.VERSION_1_8
plugins {
id("maven-publish")
id("org.springframework.boot") version "2.3.1.RELEASE"
id("io.spring.dependency-management") version "1.0.9.RELEASE"
id("com.google.cloud.tools.jib") version "2.5.0"
kotlin("jvm") version "1.3.72"
kotlin("plugin.spring") version "1.3.72"
id("com.jfrog.artifactory") version "4.13.0"
}
tasks.getByName<Jar>("jar") {
enabled = true
}
tasks.getByName<Jar>("bootJar") {
classifier = "application"
}
repositories {
mavenCentral()
maven {
setUrl("https://artifactory:443/artifactory/txo-maven-virtual")
credentials {
username = System.getenv("ARTIFACTORY_USR")
password = System.getenv("ARTIFACTORY_PSW")
}
}
}
dependencies {
implementation("org.springframework.boot:spring-boot-starter")
implementation("org.springframework.boot:spring-boot-starter-web")
implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
implementation("org.jetbrains.kotlin:kotlin-reflect")
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
testImplementation("org.springframework.boot:spring-boot-starter-test") {
exclude(group = "org.junit.vintage", module = "junit-vintage-engine")
}
}
//publishing {
// (publications) {
// "mavenJava" (MavenPublication::class) {
// from(components["java"])
// }
// }
//}
artifactory {
setContextUrl("https://artifactory/artifactory")
publish(delegateClosureOf<org.jfrog.gradle.plugin.artifactory.dsl.PublisherConfig> {
repository(delegateClosureOf<org.jfrog.gradle.plugin.artifactory.dsl.DoubleDelegateWrapper> {
setProperty("repoKey", "txo-")
setProperty("username", System.getenv("ARTIFACTORY_USR"))
setProperty("password", System.getenv("ARTIFACTORY_PSW"))
setProperty("maven", true)
})
defaults(delegateClosureOf<groovy.lang.GroovyObject> {
invokeMethod("publications", "mavenJava")
})
})
}
tasks.withType<Test> {
useJUnitPlatform()
}
tasks.withType<KotlinCompile> {
kotlinOptions {
freeCompilerArgs = listOf("-Xjsr305=strict")
jvmTarget = "1.8"
}
}
This builds and pushes the build info to artifactory/api/build but does not push any jars.
If I uncomment the commented-out stuff, I get:
What went wrong: Publication with name 'mavenJava' not found.
How can I get this thing to publish my jar files?
Try this:
publishing {
publications {
register("mavenJava", MavenPublication::class) {
from(components["java"])
}
}
}

unnamed module #0x7cd3a5 error while running tests for java application(with module system enabled) using gradle

I am trying to run the test for java applications (with module system enabled) using Gradle and getting the following error.
java.lang.IllegalAccessError: class org.junit.platform.launcher.core.LauncherFactory (in unnamed module #0x7cd3a5) cannot access class org.junit.platform.commons.util.Preconditions (in module org.junit.platform.commons) because module org.junit.platform.commons does not export org.junit.platform.commons.util to unnamed module #0x7cd3a5
Error says module org.junit.platform.commons does not export org.junit.platform.commons.util
This is how my build file looks like:
import org.springframework.boot.gradle.plugin.SpringBootPlugin
plugins {
id 'java'
id 'org.springframework.boot' version '2.3.1.RELEASE'
id 'io.spring.dependency-management' version '1.0.9.RELEASE'
id "org.beryx.jlink" version "2.21.0"
id "org.javamodularity.moduleplugin" version "1.6.0"
}
repositories {
gradlePluginPortal()
jcenter()
}
sourceCompatibility = JavaVersion.VERSION_14
targetCompatibility = JavaVersion.VERSION_14
tasks.withType(JavaCompile) {
options.encoding = 'UTF-8'
}
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
jar {
enabled = true;
}
application{
mainModule='com.sudhir.registration'
}
test {
useJUnitPlatform()
}
configurations {
springFactoriesHolder { transitive = false }
}
dependencyManagement {
imports {
mavenBom SpringBootPlugin.BOM_COORDINATES
}
}
dependencies {
springFactoriesHolder 'org.springframework.boot:spring-boot-actuator-autoconfigure'
springFactoriesHolder 'org.springframework.boot:spring-boot-autoconfigure'
springFactoriesHolder 'org.springframework.boot:spring-boot'
implementation 'org.springframework.boot:spring-boot-starter-web'
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
exclude group: 'com.vaadin.external.google', module: 'android-json'
}
}
mainClassName = "com.sudhir.registration.ApiApplication"
prepareMergedJarsDir.doLast {
// extract and merge META-INF/spring.factories from springFactoriesHolder
def factories = configurations.springFactoriesHolder.files.collect {
def props = new Properties()
props.load(zipTree(it).matching { include 'META-INF/spring.factories' }.singleFile.newInputStream())
props
}
def mergedProps = new Properties()
factories.each { props ->
props.each { key, value ->
def oldVal = mergedProps[key]
mergedProps[key] = oldVal ? "$oldVal,$value" : value
}
}
def content = mergedProps.collect { key, value ->
def v = (value as String).replace(',', ',\\\n')
"$key=$v"
}.join('\n\n')
mkdir("$jlinkBasePath/META-INF")
new File("$jlinkBasePath/META-INF/spring.factories").text = content
// insert META-INF/spring.factories into the main jar
ant.zip(update: "true", destfile: jar.archivePath, keepcompression: true) {
fileset(dir: "$jlinkBasePath", includes: 'META-INF/**')
}
}
jlink {
imageZip = file("$buildDir/image-zip/registration-service-image.zip")
options = ['--strip-java-debug-attributes', '--compress', '2', '--no-header-files', '--no-man-pages']
forceMerge 'jaxb-api', 'byte-buddy', 'classgraph'
mergedModule {
uses 'ch.qos.logback.classic.spi.Configurator'
excludeRequires 'com.fasterxml.jackson.module.paramnames'
excludeProvides implementation: 'com.sun.xml.bind.v2.ContextFactory'
excludeProvides servicePattern: 'javax.enterprise.inject.*'
excludeProvides service: 'org.apache.logging.log4j.spi.Provider'
excludeProvides servicePattern: 'reactor.blockhound.integration.*'
}
launcher {
name = 'run'
jvmArgs = [
'--add-reads', 'registration.service.merged.module=com.sudhir.registration',
'-cp', 'config/',
]
}
}
tasks.jlink.doLast {
copy {
from "src/main/resources"
into "$imageDir.asFile/bin/config"
}
copy {
from "$buildDir/classes/java/main/com/sudhir/registration"
into "$imageDir.asFile/bin/config/com/sudhir/registration/for-spring-classpath-scanner"
}
}
However, I am able to run specific tests in IntelliJ. I think it's because Intellij is using classpath instead of module path.
I am using gradle-module-system plugin to build, test and run. sample code can be found here.
Can someone please assist me how to deal with this issue. I am very new to using java module system.
Not quite sure on the reason of this problem. These threads may help to understand it: this, this, this or this
But this is what helped me in a similar case:
test {
moduleOptions {
runOnClasspath = true
}
useJUnitPlatform()
}
(Adding moduleOptions setting to the test task)

Error when running jUnit tests from Intellij command line with Gradle and Serenity Bdd

I keep having very often the below error when running jUnit tests from Intellij command line with the following command: gradlew clean test aggregate -Dtags="domain:SmokeTests"
The page object class de.telekom.commtech.bart.pages.common.TelekomLandingPageObject looks dodgy: Failed to instantiate page (net.thucydides.core.webdriver.UnsupportedDriverException: Could not instantiate class org.openqa.selenium.firefox.FirefoxDriver) de.telekom.commtech.bart.steps.AbstractScenarioSteps.getTelekomLandingPageObject(AbstractScenarioSteps.java :52) de.telekom.commtech.bart.steps.inbox.AuthNavigationSteps.landingPageShouldAppear(AuthNavigationSteps.java :245) de.telekom.commtech.bart.testcases.BaseTest.login(BaseTest.java :447) de.telekom.commtech.bart.testcases.adressbook.lefthandnavigation.AdressBookContactsGroupTestCase.setup(AdressBookContactsGroupTestCase.java :46)
I use latest version of Serenity Bdd (1.1.42) and Firefox 47.0.2
If I run individual tests with Run Configuration, I don't get that error.
I tried downgrading the Firefox version to 45.0, but it acts the same.
What else can I try?
EDIT: The build.gradle file looks like this:
repositories {
mavenLocal()
maven {
name "bart"
credentials {
username nexusUser
password nexusPassword
}
url nexusBartRepoUrl
}
maven {
name "Testchameleon"
url "https://admin.testChameleon.com/artifactory/libs-release-local"
}
jcenter()
}
buildscript {
repositories {
mavenLocal()
jcenter()
}
dependencies {
classpath("net.serenity-bdd:serenity-gradle-plugin:1.1.42")
classpath 'org.asciidoctor:asciidoctor-gradle-plugin:1.5.2'
classpath 'org.asciidoctor:asciidoctorj-pdf:1.5.0-alpha.8'
}
}
group = 'de.telekom.bart'
description = 'Bart Test Framework'
apply plugin: 'org.asciidoctor.convert'
apply plugin: 'java'
apply plugin: 'net.serenity-bdd.aggregator'
tasks.withType(JavaCompile) {
sourceCompatibility = "1.8"
targetCompatibility = "1.8"
options.deprecation = true
options.encoding = 'UTF-8'
options.compilerArgs << "-Xlint:unchecked"
}
dependencies {
compile('de.telekom.bart:bart-account-manager:2.0.12')
compile('net.serenity-bdd:serenity-core:1.1.42')
compile('org.slf4j:slf4j-api:1.7.7')
compile('org.slf4j:log4j-over-slf4j:1.7.7')
compile('org.slf4j:jul-to-slf4j:1.7.7')
compile('org.slf4j:jcl-over-slf4j:1.7.7')
compile('ch.qos.logback:logback-classic:1.1.3')
compile('de.testbirds.tech:testcase-api:0.3.20')
compile('org.mnode.ical4j:ical4j:1.0.7')
compile('org.apache.commons:commons-lang3:3.1')
testCompile('net.serenity-bdd:serenity-junit:1.1.42')
testCompile('org.reflections:reflections:0.9.8')
testCompile('junit:junit:4.12')
testCompile('org.assertj:assertj-core:1.7.0')
}
gradle.startParameter.continueOnFailure = true
test {
maxParallelForks = Runtime.runtime.availableProcessors()
if (System.properties['https.proxyHost']) {
systemProperty 'https.proxyHost', System.properties['https.proxyHost']
systemProperty 'https.proxyPort', System.properties['https.proxyPort']
systemProperty 'https.nonProxyHosts', System.properties['https.nonProxyHosts']
}
if (System.properties['http.proxyHost']) {
systemProperty 'http.proxyHost', System.properties['http.proxyHost']
systemProperty 'http.proxyPort', System.properties['http.proxyPort']
systemProperty 'http.nonProxyHosts', System.properties['http.nonProxyHosts']
}
if (System.properties['tags']) {
systemProperty 'tags', System.properties['tags']
}
System.properties.each { key, value ->
if (key.startsWith('serenity') || key.startsWith('webdriver') || key.startsWith('bart') ||(key.startsWith('test'))) {
systemProperty key, value
}
}
testLogging {
showStandardStreams = true
}
/* Pass all system properties: */
systemProperties System.getProperties()
beforeTest { descriptor ->
logger.lifecycle("Running test: ${descriptor}")
}
}
asciidoctor {
//backends = ['html5', 'pdf']
backends = ['html5']
sources {
include 'index.adoc'
}
}
task copyDocs(type: Copy, dependsOn: 'asciidoctor') {
from asciidoctor.outputDir.canonicalPath
into '/data/www/htdocs/bart-docs'
}
task wrapper(type: Wrapper) {
gradleVersion = '3.1'
}

Permanently add a plugin to Gradle

I use a third-party Gradle plugin in a lot of projects and would like to add this plugin permanently to my gradle installation. Currently I need to add the plugin to each build.gradle like so:
buildscript {
repositories {
jcenter()
}
dependencies {
classpath "com.github.dcendents:android-maven-plugin:1.2"
}
}
Is there a way to add this plugin to my Gradle installation so that I don't need to include it in every build file?
I do realise it might not be the best practice and can result in unreproducible builds.
This is a hack and not a solution
Here is now an updated version which is also able to apply plugins and add maven repositories. Testet with gradle 2.10.
Add this Plugin to your .gradle/init.gradle:
apply plugin:AddDepPlugin
class AddDepPlugin implements Plugin<Gradle> {
def addDeps = [
"org.ensime.gradle": "gradle.plugin.net.coacoas.gradle:ensime-gradle:0.2.2",
"com.github.dcendents.android-maven": "com.github.dcendents:android-maven-plugin:1.2"]
def addRepos = ["https://plugins.gradle.org/m2/"]
void apply(Gradle gradle) {
def add = 0
gradle.allprojects { project ->
plugins.whenPluginAdded { t ->
if (++add == 1) {
project.getBuildScriptSource()
def bs = project.getBuildscript()
bs.getDependencies()
def repo = bs.getRepositories()
def ccf = bs.class.getDeclaredField("classpathConfiguration")
ccf.setAccessible(true)
def cc = ccf.get(bs)
addDeps.each { k,v-> cc.dependencies.add(project.dependencies.create(v))}
addRepos.each { k-> repo.maven { -> setUrl(k) } }
}
if (add == 8)
addDeps.each { k,v ->
if (!k.startsWith("x")) project.apply([plugin: k])
}
}
}
}
}
On http://ensime.github.io//build_tools/gradle/ I found this alternative solution (this is for the ENSIME plugin):
apply plugin: AddEnsimePlugin
class AddEnsimePlugin implements Plugin<Gradle> {
def supportedPlugins = [
'org.gradle.api.plugins.JavaPlugin',
'org.gradle.api.plugins.ScalaPlugin',
'jp.leafytree.gradle.AndroidScalaPlugin'
]
void apply(Gradle gradle) {
def added = false
gradle.allprojects { project ->
project.with {
if (parent == null) {
buildscript {
repositories {
jcenter()
maven {
name 'JFrog OSS Snapshot Repository'
url 'http://oss.jfrog.org/oss-snapshot-local'
}
}
dependencies {
classpath 'net.coacoas.gradle:ensime-gradle:0.2.6'
}
}
}
plugins.whenPluginAdded { plugin ->
if (!added && supportedPlugins.contains(plugin.class.name)) {
rootProject.apply plugin: 'org.ensime.gradle'
added = true
}
}
}
}
}
}
It works for me with Gradle 2.12. The other answer also works for me.

Categories

Resources