Choose arquillian container during gradle build - junit

I am running arquillian tests with junit and gradle. How do I choose which container gets started?
At the moment I am defining the container qualifier in a file with name arquillian.launch.
My arquillian.xml looks as follows:
<?xml version="1.0" encoding="UTF-8" ?>
<arquillian ...>
<container qualifier="glassfish3-embedded" default="true">
<configuration>
...
</configuration>
</container>
<container qualifier="wls">
<configuration>
...
</configuration>
</container>
</arquillian>
My build.gradle looks as follows:
[...]
configurations {
glassfishEmbeddedTestRuntime { extendsFrom testRuntime }
weblogic10RemoteTestRuntime { extendsFrom testRuntime }
}
dependencies {
glassfishEmbeddedTestRuntime group: 'org.jboss.arquillian.container', name: 'arquillian-glassfish-embedded-3.1', version: '1.0.0.CR4'
glassfishEmbeddedTestRuntime group: 'org.glassfish.main.extras', name: 'glassfish-embedded-all', version: libraryVersions.glassfish
weblogic10RemoteTestRuntime group: 'org.jboss.arquillian.container', name: 'arquillian-wls-remote-10.3', version: '1.0.0.Alpha2'
}
task glassfishEmbeddedTest(type: Test)
task weblogic10RemoteTest(type: Test)
tasks.withType(Test).matching({ t-> t.name.endsWith('Test') } as Spec).each { t ->
t.classpath = project.configurations.getByName(t.name + 'Runtime') + project.sourceSets.main.output + project.sourceSets.test.output
}
How can I expand the definition for weblogic10RemoteTest, so that I can choose the container, and I don't have to edit the arquillian.launch file or the arquillian.xml file by changing the xml before executing the tests?
I thought about doing it like here: https://github.com/seam/solder/blob/develop/testsuite/pom.xml#L123
But I don't know the equivalent of this statement in gradle.

The POM you linked to sets system properties for the JVM running the tests. You can do the same in Gradle by configuring your Test task(s):
test { // or: tasks.withType(Test) {
systemProperty "one", "foo"
systemProperty "two", "bar"
}
(Note that Gradle always runs tests in a separate JVM.)
For further information, see Test in the Gradle Build Language Reference.

Related

How to get or parse coverage persentage of Jacoco report in GitHub Actions

I have Spring Boot app it uses gradle for build and package. I have configured Jacoco plugin and generating report in my local as HTML. I want to include it in my GitHub build workflow so whenever build runs I want to upload/store that Jacoco generated html report in the branch in which build is running. Is it possible using GitHub Actions?
Also once Jacoco build report is created want to extract final code coverage percentage of that build (this percentage is only for my defined coverage rule) and create a badge in the repository in which build is running.
EDIT
test {
finalizedBy jacocoTestReport // report is always generated after tests run
}
jacocoTestReport {
dependsOn test // tests are required to run before generating the report
}
jacoco {
toolVersion = "0.8.6"
//reportsDirectory = file("$buildDir/report/")
}
jacocoTestReport {
dependsOn test
sourceSets sourceSets.main
executionData fileTree(project.rootDir.absolutePath).include("**/build/jacoco/*.exec")
reports {
xml.enabled false
csv.enabled true
html.destination file("${buildDir}/reports/jacoco/Html")
csv.destination file("${buildDir}/reports/jacoco/jacoco.csv")
}
}
//Test coverage Rule to make sure code coverage is 100 %
jacocoTestCoverageVerification {
violationRules {
rule {
element = 'CLASS'
limit {
counter = 'LINE'
value = 'COVEREDRATIO'
minimum = 1.0
}
excludes = [
'com.cicd.herokuautodeploy.model.*',
'com.cicd.herokuautodeploy.HerokuautodeployApplication',
'com.cicd.herokuautodeploy.it.*'
]
}
}
}
WorkFlow File
# This workflow will build a Java project with Gradle whenever Pull and Merge request to main branch
# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-gradle
name: Build WorkFlow - Building and Validating Test Coverage
on:
pull_request:
branches: [ main,dev ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout#v2
- name: Set up JDK 1.11
uses: actions/setup-java#v1
with:
java-version: 1.11
- name: Grant execute permission for gradlew
run: chmod +x gradlew
- name: Build with Gradle
run: ./gradlew build
- name: Generate JaCoCo Badge
id: jacoco
uses: cicirello/jacoco-badge-generator#v2.0.1
- name: Log coverage percentage
run: |
echo "coverage = ${{ steps.jacoco.outputs.coverage }}"
echo "branch coverage = ${{ steps.jacoco.outputs.branches }}"
- name: Commit the badge (if it changed)
run: |
if [[ `git status --porcelain` ]]; then
git config --global user.name 'UserName'
git config --global user.email 'useremail#gmail.com'
git add -A
git commit -m "Autogenerated JaCoCo coverage badge"
git push
fi
- name: Upload JaCoCo coverage report
uses: actions/upload-artifact#v2
with:
name: jacoco-report
path: reports/jacoco/
Error
File "/JacocoBadgeGenerator.py", line 88, in computeCoverage
with open(filename, newline='') as csvfile :
FileNotFoundError: [Errno 2] No such file or directory: 'target/site/jacoco/jacoco.csv'
Disclosure: I am the author of the cicirello/jacoco-badge-generator GitHub Action that this question concerns.
Although the default behavior assumes Maven's location of the jacoco.csv, there is an action input that can be used to indicate the location of the jacoco report. So in your case, with gradle, you can change the cicirello/jacoco-badge-generator step of your workflow to the following (if you use gradle's default location and filename for the report):
- name: Generate JaCoCo Badge
uses: cicirello/jacoco-badge-generator#v2
with:
jacoco-csv-file: build/reports/jacoco/test/jacocoTestReport.csv
It looks like your gradle configuration changed the report location though, so you will need the following in order to coincide with your report location and filename:
- name: Generate JaCoCo Badge
id: jacoco
uses: cicirello/jacoco-badge-generator#v2
with:
jacoco-csv-file: build/reports/jacoco/jacoco.csv
The id: jacoco is just because one of your later steps in your workflow is referring to the action outputs through that id.
If you can configure jacoco to generate a jacoco.csv file, then the GitHub Action jacoco-badge-generator can generate the requested badge.
See for instance "Use Jacoco And GitHub Actions to Improve Code Coverage" from Rodrigo Graciano for an example of pom.xml project configuration to generate the report during build.
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>${jacoco.plugin.version}</version>
<executions>
<execution>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>report</id>
<phase>prepare-package</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
</executions>
</plugin>
For a gradle example:
jacocoTestReport {
dependsOn test
sourceSets sourceSets.main
executionData fileTree(project.rootDir.absolutePath).include("**/build/jacoco/*.exec")
reports {
xml.enabled false
csv.enabled true
html.destination file("${buildDir}/reports/jacoco/Html")
csv.destination file("${buildDir}/reports/jacoco/jacoco.csv")
}
}

Springboot version upgrade - my sql error while deploying in aws elastic beanstalk

We are trying to upgrade our project through build.gradle dependencies :
build.gradle file:
buildscript {
ext {
springBootVersion = '2.3.3.RELEASE'
}
repositories {
mavenCentral()
maven {
url "https://plugins.gradle.org/m2/"
}
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
classpath('se.transmode.gradle:gradle-docker:1.2')
}
}
group = 'testing'
version = '0.0.1-SNAPSHOT'
apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
apply plugin: "jacoco"
apply from: 'docker.gradle'
sourceCompatibility = 1.8
bootJar {
launchScript()
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-actuator'
compile ('org.springframework.boot:spring-boot-starter-data-jpa')
compile ('org.springframework.boot:spring-boot-starter-web')
implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation 'org.flywaydb:flyway-core'
runtime 'mysql:mysql-connector-java:5.1.47'
implementation 'com.zaxxer:HikariCP'
annotationProcessor('org.hibernate:hibernate-jpamodelgen')
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.mobile:spring-mobile-device:1.1.5.RELEASE'
implementation 'io.jsonwebtoken:jjwt-api:0.10.5'
runtimeOnly 'io.jsonwebtoken:jjwt-impl:0.10.5'
runtimeOnly 'io.jsonwebtoken:jjwt-jackson:0.10.5'
implementation 'com.amazonaws:aws-java-sdk-s3:1.11.136'
implementation 'org.springframework.boot:spring-boot-starter-mail'
implementation 'org.springframework.boot:spring-boot-starter-freemarker'
implementation 'org.springframework.boot:spring-boot-starter-tomcat'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
testCompile('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
testImplementation('org.springframework.security:spring-security-test')
compile 'com.h2database:h2'
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
implementation 'org.apache.commons:commons-lang3'
implementation 'com.univocity:univocity-parsers:2.7.6'
implementation 'org.quartz-scheduler:quartz:2.2.1'
implementation 'org.apache.poi:poi:3.17'
implementation 'org.apache.poi:poi-ooxml:3.17'
}
test.reports.junitXml.setDestination(file("${buildDir}/test-results"))
jacocoTestReport {
reports {
html.destination file("${buildDir}/jacocoHtml")
}
}
sourceSets {
main {
java {
srcDirs += "src/jpaModelgen/java"
}
}
}
compileJava {
options.compilerArgs += ['-AaddGenerationDate=true'] // Specific to Hibernate JPA meta model generation processor.
options.annotationProcessorGeneratedSourcesDirectory = file("src/jpaModelgen/java")
}
application.properties file:
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.database=mysql
spring.data.jpa.repositories.enabled=true
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.datasource.url= jdbc:mysql://MyDB:3306/myschema
spring.datasource.username= testing
spring.datasource.password= root
spring-boot from version 1.5.7 to 2.3.3
Gradle from versionGradle-4.8-all to Gradle-6.4.1-all
while we run aplication in localy we get folowing output in log,
o.f.c.internal.database.DatabaseFactory : Database: jdbc:mysql://MyDB:3306/myschema (MySQL 5.7)
when we deploy this same code to AWS Elastic Beanstalk,
We are getting the following error:
Error creating bean with name 'flywayInitializer' defined in class path resource [org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration$FlywayConfiguration.class]: Invocation of init method failed; nested exception is org.flywaydb.core.internal.command.DbMigrate$FlywayMigrateException:
Migration V3__Sequence_Table.sql failed
---------------------------------------
SQL State : 42001
Error Code : 42001
Message : Syntax error in SQL statement "DELIMITER[*]
JDBC connection URL has been changed as below now,
o.f.c.internal.database.DatabaseFactory : Database: jdbc:h2:mem:testdb (H2 1.4)
Is this the cause of the above flyway migration error or Docker version error?
problem:
Run command for jar file is a problem for this project `
Dspring.config.location=run.properties this commad execute only run.properties
solution:
Instead of the above run command, I have tried this run command for the jar file
Dspring.config.additional-location=run.properties
this was working well

How do I configure jooq with Gradle and Mysql for a single database

I'm trying to use jooq to load configurations automatically from gradle but had a hard time following the guide.
I finally have it loading data, but so far I can only get all databases to work (by having the database() chunk be blank).
My code below has my attempt to load only one database.
buildscript {
repositories {
mavenCentral()
maven {
name 'JFrog OSS snapshot repo'
url 'https://oss.jfrog.org/oss-snapshot-local/'
}
jcenter()
}
dependencies {
classpath 'org.jooq:jooq-codegen:3.9.1'
classpath group: 'mysql', name: 'mysql-connector-java', version: '6.0.6'
}
}
apply plugin: 'application'
apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'antlr'
repositories {
mavenLocal()
mavenCentral()
jcenter()
}
dependencies {
//compile group: 'com.github.javaparser', name: 'javaparser-core', version: '3.0.0-alpha.2'
compile group: 'com.github.javaparser', name: 'java-symbol-solver-core', version: '0.5.2'
compile 'org.jooq:jooq:3.9.1'
runtime group: 'mysql', name: 'mysql-connector-java', version: '6.0.6'
testCompile "junit:junit:latest.release"
}
idea {
module {
excludeDirs += file('src/main/resources')
}
}
// Use your favourite XML builder to construct the code generation configuration file
// ----------------------------------------------------------------------------------
def writer = new StringWriter()
def xml = new groovy.xml.MarkupBuilder(writer)
.configuration('xmlns': 'http://www.jooq.org/xsd/jooq-codegen-3.9.0.xsd') {
jdbc() {
driver('com.mysql.cj.jdbc.Driver')
url('jdbc:mysql://127.0.0.1/graphUpgrade?serverTimezone=UTC')
user('parseUser')
password('password')
}
generator() {
database() {
name('org.jooq.util.mysql.MySQLDatabase')
inputSchema('graphUpgrade')
includes('.*')
}
// Watch out for this caveat when using MarkupBuilder with "reserved names"
// - https://github.com/jOOQ/jOOQ/issues/4797
// - http://stackoverflow.com/a/11389034/521799
// - https://groups.google.com/forum/#!topic/jooq-user/wi4S9rRxk4A
generate([:]) {
pojos true
daos true
}
target() {
packageName('us.klingman.codeParser.db')
directory('src/main/java')
}
}
}
print writer.toString()
// Run the code generator
// ----------------------
org.jooq.util.GenerationTool.generate(
javax.xml.bind.JAXB.unmarshal(new StringReader(writer.toString()), org.jooq.util.jaxb.Configuration.class)
)
Running this code produces the following error:
Error while fetching tables
java.lang.NullPointerException
at org.jooq.util.AbstractElementContainerDefinition.<init>(AbstractElementContainerDefinition.java:79)
at org.jooq.util.AbstractElementContainerDefinition.<init>(AbstractElementContainerDefinition.java:75)
at org.jooq.util.AbstractTableDefinition.<init>(AbstractTableDefinition.java:68)
at org.jooq.util.mysql.MySQLTableDefinition.<init>(MySQLTableDefinition.java:70)
at org.jooq.util.mysql.MySQLDatabase.getTables0(MySQLDatabase.java:256)
at org.jooq.util.AbstractDatabase.getTables(AbstractDatabase.java:1137)
at org.jooq.util.AbstractDatabase.getTable(AbstractDatabase.java:1163)
at org.jooq.util.AbstractDatabase.getTable(AbstractDatabase.java:1158)
at org.jooq.util.mysql.MySQLDatabase.getEnums0(MySQLDatabase.java:295)
at org.jooq.util.AbstractDatabase.getEnums(AbstractDatabase.java:1182)
at org.jooq.util.JavaGenerator.generateSchemaIfEmpty(JavaGenerator.java:334)
at org.jooq.util.JavaGenerator.generateCatalogIfEmpty(JavaGenerator.java:323)
at org.jooq.util.JavaGenerator.generate(JavaGenerator.java:297)
at org.jooq.util.GenerationTool.run(GenerationTool.java:610)
at org.jooq.util.GenerationTool.generate(GenerationTool.java:199)
at org.jooq.util.GenerationTool$generate.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:108)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
at build_87hklhc6v691dvh83y5ogqnvl.run(/Users/lorenklingman/Sites/code-search-parser/build.gradle:79)
at org.gradle.groovy.scripts.internal.DefaultScriptRunnerFactory$ScriptRunnerImpl.run(DefaultScriptRunnerFactory.java:74)
Finally, for completeness, here are the files generated for all databases.
I believe you've run into this problem here: #5213
Be sure to always use the exact upper/lower case writing of your database name also in the jOOQ configuration. Also, there are some caveats with case sensitivity in MySQL and MariaDB, depending on the operating system. These caveats can affect other tools than jOOQ. The relevant info is also in #5213.

I'm getting java.lang.UnsatisfiedLinkError when I run my jUnit test on command line by gradle, but it runs fine when run on AndroidStudio

So I finally managed to get my android studio to run JUnit test that's integrated with robolectric so I can do http calls and other things without running it on device or emulator. Followed the structure from here which worked wonders: https://github.com/robolectric/deckard-gradle
Now, I managed to run it fine on AndroidStudio, however I want to setup a cron so it can be run automatically, and when executing the test by command line via gradle I am getting "java.lang.UnsatisfiedLinkError: no pjsua in java.library.path". Note that our code uses a pjsip lib code that we compile separately, and we put the .so file in the jniLibs folder. I have another jUnit test that's really simple, and that one works fine whether through gradle command line or AndroidStudio.
The gradle command I followed from http://tools.android.com/tech-docs/unit-testing-support which are either:
1) ./gradlew test --continue
or
2) ./gradlew test -Dtest.single=Test.java
This is what our gradle file looks like for the app layer:
apply plugin: 'com.android.application'
android {
compileSdkVersion 21
buildToolsVersion "21.1.2"
defaultConfig {
applicationId "com.foo.test"
minSdkVersion 14
targetSdkVersion 21
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
ndk {
moduleName "libpjsua"
}
}
sourceSets {
main {
jni.srcDirs = []
}
}
signingConfigs {
// hidden
}
buildTypes {
release {
signingConfig signingConfigs.release
}
debug {
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: '*.jar')
compile 'com.android.support:appcompat-v7:21.0.3'
compile files('libs/android-logging-log4j-1.0.3.jar')
compile files('libs/libphonenumber-6.2.jar')
compile files('libs/log4j-1.2.17.jar')
compile files('libs/nineoldandroids-2.4.0.jar')
compile files('libs/ostermillerutils_1_07_00.jar')
// dependencies to do automation testing
testCompile 'junit:junit:4.12'
testCompile 'org.hamcrest:hamcrest-core:1.1'
testCompile 'org.hamcrest:hamcrest-library:1.1'
testCompile 'org.hamcrest:hamcrest-integration:1.1'
testCompile('org.robolectric:robolectric:2.4') {
exclude module: 'classworlds'
exclude module: 'commons-logging'
exclude module: 'httpclient'
exclude module: 'maven-artifact'
exclude module: 'maven-artifact-manager'
exclude module: 'maven-error-diagnostics'
exclude module: 'maven-model'
exclude module: 'maven-project'
exclude module: 'maven-settings'
exclude module: 'plexus-container-default'
exclude module: 'plexus-interpolation'
exclude module: 'plexus-utils'
exclude module: 'wagon-file'
exclude module: 'wagon-http-lightweight'
exclude module: 'wagon-provider-api'
}
}
Does anyone have any idea? Many thanks in advance, been at this for a couple of days now.

Specifying Gradle dependencies for *.jar files

This must be straight forward but I fail to see where group: name: and version: come from for a particular jar file. For example from Gradle's documentation.
dependencies {
compile group: 'org.hibernate', name: 'hibernate-core', version: '3.6.7.Final'
testCompile group: 'junit', name: 'junit', version: '4.+'
testRuntime "org.hamcrest:SelfDescribing:1.+"
}
I'm trying to make use of a hamcrest jar for my junit testing. I need hamcrest for runtime testing but I don't know how to correctly specify this. Below is my build.gradle file. This test project will build successfully but will not run the unit tests due to unresolved dependencies.
apply plugin: 'java'
apply plugin: 'eclipse-wtp'
version = '1.0'
compileJava.destinationDir = file("$buildDir/classes/test")
sourceSets {
main {
java {
srcDir 'src'
}
}
}
repositories {
flatDir dirs: "C:/eclipse/plugins/org.junit_4.11.0.v201303080030"
flatDir dirs: "C:/eclipse/plugins"
}
dependencies {
compile "junit:junit:4"
testCompile "junit:junit:4"
testRuntime "org.hamcrest:SelfDescribing:1.+"
}
test {
testLogging.showStandardStreams = true
testLogging {
events 'started', 'passed', 'skipped', 'failed', 'standardOut', 'standardError'
exceptionFormat 'short'
}
}
jar {
manifest.attributes provider: 'gradle'
}
To add a dependency on a jar file, add a statement like this to your dependencies block:
compile files('path/to/archive.jar')
A popular approach is this, which will automatically pick up all jar files in a libs directory:
compile fileTree(dir: 'path/to/libs', include: '*.jar')
When using a flatDir repository, you'll have to make sure that:
Artifact files are contained directly in the specified directory (not in a subdirectory).
Artifact filenames match the pattern module-version.extension (e.g. junit-4.jar) or module.extension (e.g. junit.jar).
Alternatively, you could use file dependencies as described in Scott's answer.
PS: I'm not sure if version ranges work with flatDir repositories.