Maven plugin - modifying configuration of another plugin - maven

I'm developing custom maven plugin.
My plugin requires a specific configuration for the surefire plugin. As result, as part of my MOJO I'm searching for 'surefire' and if it is present I'm trying to modify its configuration.
My problem is that the configuration is not used.
Here's most of my code:
package io.kuku.agents.plugin;
import org.apache.maven.model.Dependency;
import org.apache.maven.model.Model;
import org.apache.maven.model.Plugin;
import org.apache.maven.model.PluginExecution;
import org.apache.maven.model.io.xpp3.MavenXpp3Writer;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.codehaus.plexus.util.xml.Xpp3Dom;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
/**
* Initialize the integration with the Testing Framework.
*
* #phase test
* #goal initialize-test-listener
* #since 1.0.0
*/
public class SetupMojo extends AbstractKukusMojo {
boolean hasJunit = false;
boolean hasTestNG = false;
public void execute() throws MojoExecutionException, MojoFailureException {
analyzeDependencies();
Plugin surefirePlugin = lookupPlugin("org.apache.maven.plugins:maven-surefire-plugin");
Object config = updateConfiguration(hasJunit, hasTestNG, surefirePlugin.getConfiguration());
surefirePlugin.setConfiguration(config);
List<PluginExecution> executions = surefirePlugin.getExecutions();
for (PluginExecution execution : executions) {
if (execution.getId().equals("default-test")) {
System.out.println("Setting DEFAULT-TEST");
config = updateConfiguration(hasJunit, hasTestNG, execution.getConfiguration());
execution.setConfiguration(config);
break;
}
}
}
private void analyzeDependencies() {
List dependencies = this.project.getDependencies();
for (int i = 0; i < dependencies.size(); i++) {
Dependency dependency = (Dependency) dependencies.get(i);
if (dependency.getArtifactId().equalsIgnoreCase("junit")) {
hasJunit = true;
if (hasJunit && hasTestNG)
break;
else
continue;
}
if (dependency.getArtifactId().equalsIgnoreCase("testng")) {
hasTestNG = true;
if (hasJunit && hasTestNG)
break;
else
continue;
}
}
}
private Object updateConfiguration(boolean hasJunit, boolean hasTestNG, Object configuration) throws MojoExecutionException {
if (configuration == null)
configuration = new Xpp3Dom("configuration");
if (configuration instanceof Xpp3Dom) {
Xpp3Dom xml = (Xpp3Dom) configuration;
Xpp3Dom properties = xml.getChild("properties");
if (properties == null)
{
properties = new Xpp3Dom("properties");
xml.addChild(properties);
}
Xpp3Dom[] property = properties.getChildren("property");
//My logic goes here
...
...
}
return configuration;
}
}
I'll appreciate your help.
N.
EDIT - This is my parent pom:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>sllistenertest</groupId>
<artifactId>parent-artifact</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>pom</packaging>
<name>Sl Listener Test (Parent)</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>io.kuku.on-premise.agents.plugin</groupId>
<artifactId>kuku-maven-plugin</artifactId>
<version>1.0.0</version>
<configuration>
<customerid>nadav2</customerid>
<server>https://fake.kuku.co/api</server>
<appName>fake-app-name</appName>
<moduleName>fake-module-name</moduleName>
<workspacepath>${project.basedir}</workspacepath>
<build>52</build>
<branch>fake-branch</branch>
<packagesincluded>*fklistenertest*</packagesincluded>
<packagesexcluded>com.fake.excluded.*</packagesexcluded>
<filesincluded>*.class</filesincluded>
<logLevel>INFO</logLevel>
<logFolder>c:\fake-log-folder</logFolder>
<logToFile>true</logToFile>
<logEnabled>true</logEnabled>
</configuration>
<executions>
<execution>
<id>a1</id>
<goals>
<goal>build-scanner</goal>
</goals>
</execution>
<execution>
<id>a2</id>
<goals>
<goal>test-listener</goal>
</goals>
</execution>
<execution>
<id>a3</id>
<goals>
<goal>initialize-test-listener</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19</version>
<!--<configuration>
<properties>
<property>
<name>listener</name>
<value>io.kuku.onpremise.agents.java.agent.integrations.testng.TestListener</value>
</property>
</properties>
<additionalClasspathElements>
<additionalClasspathElement>C:\Temp\kuku-java-1.3.160\artifacts\kuku-api-1.3.160.jar</additionalClasspathElement>
</additionalClasspathElements>
</configuration>-->
<executions>
<execution>
<id>default-test</id>
<phase>none</phase>
</execution>
<execution>
<id>run-after-antrun</id>
<phase>test</phase>
<goals>
<goal>test</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19</version>
<executions>
<execution>
<id>default-test</id>
<phase>none</phase>
</execution>
<execution>
<id>run-after-antrun</id>
<phase>test</phase>
<goals>
<goal>test</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<modules>
<module>Only Junit</module>
<module>Only TestNG</module>
<module>Both</module>
</modules>
</project>
This is the pom for one of the children:
<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>sllistenertest</groupId>
<artifactId>parent-artifact</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<groupId>sllistenertest</groupId>
<artifactId>onlyjunit</artifactId>
<version>1.0-SNAPSHOT</version>
<name>Only JUnit</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>io.kuku.on-premise.agents.plugin</groupId>
<artifactId>kuku-maven-plugin</artifactId>
<version>1.0.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19</version>
</plugin>
</plugins>
</build>
</project>

You should take a look here:
for JUnit
https://maven.apache.org/surefire/maven-surefire-plugin/examples/junit.html#Using_Custom_Listeners_and_Reporters
For TestNG:
https://maven.apache.org/surefire/maven-surefire-plugin/examples/testng.html#Using_Custom_Listeners_and_Reporters
So i don't see the requirement to implement a plugin...

Related

How to add the CryptoJS into maven that used for Jmeter

I used CryptoJS libraries (Downloaded and placed under lib folder in Jmeter) in Jmeter JSR223 Sampler using load directive.
load('crypto-js-3.1.9/crypto-js.js');
function AESEncryption(text, passphase, bytessize) {
var key = CryptoJS.enc.Utf8.parse('ABCDEFGHIJKL1234567891234');
var iv = CryptoJS.enc.Utf8.parse('1234567890123456');
var blocksize = bytessize / 2;
var encrypted = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(text), passphase, key,
{
keySize: bytessize,
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
var dta = String(encrypted);
return dta;}
function AESDecryption(text, key, bytessize) {
try {
//alert(text + ":" + key + ":" + bytessize);
var e = CryptoJS.AES.decrypt(text, key, bytessize);
//alert("Ec:" + e);
return CryptoJS.AES.decrypt(text, key, bytessize).toString(CryptoJS.enc.Utf8);
}
catch (Error) {
return "";}}
I just want to integrate this JMX file into MAVEN com.lazerycode.jmeter.Plugin. I just copied the JMX file into src/test/jmeter folder but when I tried to run the script from CLI using mvn install its failing to load the Crypto module (Actullay I just copied the JMX file and I'm not sure where I should place this CryptoJS into maven folder).
Let me know where should I keep this CryptoJS that will work in maven environment.
POM.XML
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.paypal</groupId>
<artifactId>AMAZON_P2P</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>AMAZON_P2P</name>
<url>http://maven.apache.org</url>
<properties>
<maven.compiler.source>1.6</maven.compiler.source>
<maven.compiler.target>1.6</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- ttps://mvnrepository.com/artifact/com.jayway.jsonpath/json-path -->
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M5</version>
</plugin>
<plugin>
<groupId>com.lazerycode.jmeter</groupId>
<artifactId>jmeter-maven-plugin</artifactId>
<version>2.4.0</version>
<configuration>
<testResultsTimestamp>false</testResultsTimestamp>
<propertiesUser>
<threadCount>${performancetest.threadCount}</threadCount>
<testIterations>${performancetest.testIterations}</testIterations>
</propertiesUser>
<propertiesJMeter>
<jmeter.save.saveservice.thread_counts>true</jmeter.save.saveservice.thread_counts>
<jmeter.save.saveservice.sample_count>true</jmeter.save.saveservice.sample_count>
</propertiesJMeter>
</configuration>
<executions>
<execution>
<id>jmeter-tests</id>
<phase>verify</phase>
<goals>
<goal>jmeter</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
The below lines does the magic:
<jmeterExtensions>
<artifact>org.webjars.bower:crypto-js:3.1.9</artifact>
</jmeterExtensions>

Deploying running word count on Spark

I have a problem deploying the running word count example for Spark Streaming. I am trying to deploy the same file that is provided with Spark examples, but I want to build and deploy this specific example as a stand alone application.
My file looks like this:
package test;
import scala.Tuple2;
import com.google.common.collect.Lists;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.function.FlatMapFunction;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.api.java.function.PairFunction;
import org.apache.spark.api.java.StorageLevels;
import org.apache.spark.streaming.Durations;
import org.apache.spark.streaming.api.java.JavaDStream;
import org.apache.spark.streaming.api.java.JavaPairDStream;
import org.apache.spark.streaming.api.java.JavaReceiverInputDStream;
import org.apache.spark.streaming.api.java.JavaStreamingContext;
import java.util.regex.Pattern;
public final class JavaNetworkWordCount {
private static final Pattern SPACE = Pattern.compile(" ");
public static void main(String[] args) {
if (args.length < 2) {
System.err.println("Usage: JavaNetworkWordCount <hostname> <port>");
System.exit(1);
}
// Create the context with a 1 second batch size
SparkConf sparkConf = new SparkConf()
.setAppName("JavaNetworkWordCount");
JavaStreamingContext ssc = new JavaStreamingContext(sparkConf,
Durations.seconds(1));
// Create a JavaReceiverInputDStream on target ip:port and count the
// words in input stream of \n delimited text (eg. generated by 'nc')
// Note that no duplication in storage level only for running locally.
// Replication necessary in distributed scenario for fault tolerance.
JavaReceiverInputDStream<String> lines = ssc.socketTextStream(args[0],
Integer.parseInt(args[1]), StorageLevels.MEMORY_AND_DISK_SER);
JavaDStream<String> words = lines
.flatMap(new FlatMapFunction<String, String>() {
public Iterable<String> call(String x) {
return Lists.newArrayList(SPACE.split(x));
}
});
JavaPairDStream<String, Integer> wordCounts = words.mapToPair(
new PairFunction<String, String, Integer>() {
public Tuple2<String, Integer> call(String s) {
return new Tuple2<String, Integer>(s, 1);
}
}).reduceByKey(new Function2<Integer, Integer, Integer>() {
public Integer call(Integer i1, Integer i2) {
return i1 + i2;
}
});
wordCounts.print();
ssc.start();
ssc.awaitTermination();
}
}
And my POM looks like this:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>io.tester</groupId>
<artifactId>streamer</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>streamer</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<scala.binary.version>2.11</scala.binary.version>
<spark.version>1.4.1</spark.version>
<java.version>1.7</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-core_${scala.binary.version}</artifactId>
<version>${spark.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-streaming_${scala.binary.version}</artifactId>
<version>${spark.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<archive>
<manifest>
<mainClass>test.JavaNetworkWordCount</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
The error that I get is:
java.lang.NoClassDefFoundError: com/google/common/collect/Lists
I look through my jar that I built with maven. It has a with-dependencies appended to it, but it doesn't seem to actually have any dependencies in it. I run it via mvn assembly:single. What am I doing wrong?
As the maven-assembly-plugin indicates
If your project wants to package your artifact in an uber-jar, the assembly plugin provides only basic support. For more control, use the Maven Shade Plugin
you can try to use the maven-shade-plugin. Try to replace the maven-assembly-plugin plugin tag with:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.3</version>
<executions>
<!-- Run shade goal on package phase -->
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<!-- add Main-Class to manifest file -->
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>test.JavaNetworkWordCount</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
This should hopefully create a fat jar containing all your dependencies.
I got it figured out. I had two problems. One, I didn't notice that I had the provided clause (stupid cut and paste error). The second problem I had was that one of the dependencies pulled in was signed and I needed to explicitly exclude the signature files. My end product that actually works looks like this in case someone else is having this problem:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>io.tester</groupId>
<artifactId>streamer</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>streamer</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<scala.binary.version>2.11</scala.binary.version>
<spark.version>1.4.1</spark.version>
<java.version>1.7</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-core_${scala.binary.version}</artifactId>
<version>${spark.version}</version>
</dependency>
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-streaming_${scala.binary.version}</artifactId>
<version>${spark.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.3</version>
<executions>
<!-- Run shade goal on package phase -->
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
</filters>
<transformers>
<!-- add Main-Class to manifest file -->
<transformer
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>io.tester.streamer.JavaNetworkWordCount</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>

maven plugin descriptor not getting generated

I'm creating a maven plugin, MVN clean install build succeeds but plugin.xml is not getting generated.
#Mojo( name = "cover", defaultPhase = LifecyclePhase.POST_INTEGRATION_TEST)
public class RunCoverage extends AbstractMojo
{
#Parameter( property = "cover.wadl", defaultValue = "test")
private String wadl;
#Parameter( property = "cover.endpoints",defaultValue = "test")
private String endpoints;
#Override
public void execute() throws MojoExecutionException
{
<somecode>
}
}
And the pom.xml is
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>end-point-test-coverage</artifactId>
<version>1</version>
<dependencies>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-plugin-api</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>org.apache.maven.plugin-tools</groupId>
<artifactId>maven-plugin-annotations</artifactId>
<version>3.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-plugin-plugin</artifactId>
<version>3.2</version>
<executions>
<execution>
<id>default-descriptor</id>
<goals>
<goal>descriptor</goal>
</goals>
<phase>process-classes</phase>
</execution>
<execution>
<id>help-descriptor</id>
<goals>
<goal>helpmojo</goal>
</goals>
<phase>process-classes</phase>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.0.2</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
Maven clean install doesn't generate plugin.xml
When used in a dependent project, I'm getting the following error
Failed to parse plugin descriptor for it.gruppopam.common:end-point-test-coverage:1 (/home/d/.m2/repository/it/common/end-point-test-coverage/1/end-point-test-coverage-1.jar): No plugin descriptor found at META-INF/maven/plugin.xml -> [Help 1]
[ERROR]
First i would try to set the packaging type to maven-plugin instead of the default which is jar. Furthermore i would suggest to use more up-to-date versions of plugins (maven-compiler-plugin: 3.1) and use a more up-to-date version of maven-plugin-api (3.0? but not 2.0).
you have to remember to change it in your pom.xml to:
<packaging>maven-plugin</packaging>
it is by default:
<packaging>jar</packaging>

How to pass java code a parameter from maven for testing

I need to pass on following values …
exeEvironment (Test environment) ,
testGroup (Group in testNG)
from Command-Line -> POM -> TestNG -> Test cases.
Based on these two posts ....
pass a java parameter from maven
How to pass parameters to guicified TestNG test from Surefire Maven plugin?
I did the following configuration ..
In surefire plugin, I tried following two options, none seem to work.
=====
(1)
<execution>
<id>default-test</id>
<goals>
<goal>test</goal>
</goals>
<configuration>
<properties>
<exeEnvironment>${exeEnvironment}</exeEnvironment>
<testGroup>${testGroup}</testGroup>
</properties>
<suiteXmlFiles>
<suiteXmlFile>testng.xml</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</execution>
(2)
<execution>
<id>default-test</id>
<goals>
<goal>test</goal>
</goals>
<configuration>
<systemPropertyVariables> <exeEnvironment>${exeEnvironment}</exeEnvironment>
<testGroup>${testGroup}</testGroup> </systemPropertyVariables>
<suiteXmlFiles>
<suiteXmlFile>testng.xml</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</execution>
In testNG.xml , can I use the the variable testGroup like …
<test name="Web Build Acceptance">
<groups>
<run>
<include name="${testGroup} />
</run>
</groups>
<classes>
<class name="com.abc.pqr" />
</classes>
</test>
This doesn't seem to work as well, do I need to define a parameter.
In the test cases , I tried to get he variables in following two ways ….
(1)
testEnv = testContext.getSuite().getParameter("exeEnvironment");
testGroup = testContext.getSuite().getParameter("testGroup");
(2)
testEnv = System.getProperty("exeEnvironment");
testGroup = System.getProperty("testGroup");
This is the exact thing I was looking for my automation test and I got it working.
Command Line argument
mvn clean test -Denv.USER=UAT -Dgroups=Sniff
My Pom Xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>TestNg</groupId>
<artifactId>TestNg</artifactId>
<version>1.0</version>
<dependencies>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.8</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.12.4</version>
<configuration>
<systemPropertyVariables>
<environment>${env.USER}</environment>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</project>
TestNG test
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
public class TestAuthentication {
#Test (groups = { "Sniff", "Regression" })
public void validAuthenticationTest(){
System.out.println(" Sniff + Regression" + System.getProperty("environment"));
}
#Test (groups = { "Regression" },parameters = {"environment"})
public void failedAuthenticationTest(String environment){
System.out.println("Regression-"+environment);
}
#Parameters("environment")
#Test (groups = { "Sniff"})
public void newUserAuthenticationTest(String environment){
System.out.println("Sniff-"+environment);
}
}
The above works well. Additionally, if you need to use testng.xml, you can specify the suiteXmlFile like ...
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.12.4</version>
<configuration>
<systemPropertyVariables>
<environment>${env.USER}</environment>
</systemPropertyVariables>
<suiteXmlFiles>
<suiteXmlFile>testng.xml</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</plugin>
Also, I prefer using #Parameters instead of parameters in #Test() as the later is deprecated.
You need not define anything for groups in testng xml or the pom, the support comes inbuilt. You can simply specify the groups on the cmd line
http://maven.apache.org/plugins/maven-surefire-plugin/test-mojo.html#groups
Hope it helps..
Edit 2:
Ok..so here's another option...Implement IMethodInterceptor
Define your custom property.
Use -Dcustomproperty=groupthatneedstoberun in your command line call.
In the intercept call, scan through all methods ..something to the effect..
System.getProperty("customproperty");
for(IMethodInstance ins : methods) {
if(ins.getMethod().getGroups()) contains group)
Add to returnedVal;
}
return returnedVal;
Add this to the listeners list in your xml.
Perfect.
The simplest way to pass the variable from POM.xml to ABC.java
POM.xml
<properties>
<hostName>myhostname.com</hostName>
</properties>
And in the ABC.java we can call it from the system properties like this
System.getProperty("hostName")
Passing parameter like browser and other can be done as below :
<properties>
<BrowserName></BrowserName>
<TestRunID></TestRunID>
</properties>
<!-- Below plug-in is used to execute tests -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.18.1</version>
<configuration>
<suiteXmlFiles>
<suiteXmlFile>src/test/resources/${testXml}</suiteXmlFile>
</suiteXmlFiles>
<systemPropertyVariables>
<browserName>${BrowserName}</browserName>
<testRunID>${TestRunID}</testRunID>
</systemPropertyVariables>
</configuration>
<executions>
<execution>
<id>surefire-it</id>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<skip>false</skip>
<testFailureIgnore>true</testFailureIgnore>
</configuration>
</execution>
</executions>
</plugin>
and to handle this in java code use this :
public static final String Browser_Jenkin=System.getProperty("BrowserName");
public static final String TestRunID=System.getProperty("TestRunID");
public static String browser_Setter()
{
String value=null;
try {
if(!Browser_Jenkin.isEmpty())
{
value = Browser_Jenkin;
}
} catch (Exception e) {
value =propObj.getProperty("BROWSER");
}
return value;
}
public static String testRunID_Setter()
{
String value=null;
try {
if(!TestRunID.isEmpty())
{
value = TestRunID;
}
} catch (Exception e) {
value =propObj.getProperty("TEST_RUN_ID");
}
return value;
}
building on the accepted answer
if maven surefire and the <systemPropertyVariables> are declared in a maven profile, they are not available and will return null unless the profile is also invoked.
Command Line argument
mvn clean test -PmyTestProfile -Denv.USER=UAT -Dgroups=Sniff
pom.xml
<profiles>
<profile>
<id>myTestProfile</id>
<activation>
<activeByDefault>false</activeByDefault>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${surefire.version}</version>
<configuration>
<systemPropertyVariables>
<environment>${env.USER}</environment>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
You don't need to use environment variables or edit pom.xml to use them.
The goals and options for Invoke Maven 3 under Build section takes the parameter. Try this (assuming you parameterized the build):
Invoke Maven 3
Goals and options = test -Denv=$PARAM_ENV -Dgroup=$PARAM_GROUP

Maven JBehave : encoding stories UTF8

We managed to create and run tests with internationalized stories using JBehave within eclipse.
Everything went fine.
But when we tried to run them using the maven plug-in, we cannot get rud of the encoding problem (for example, instead of reading "scénario" from the story, it gets "Scénario" : clearly an UTF8 encoding problem).
Does someone have found a way to get JBehave to read the stories in UTF8 using the maven plug-in ?
What we already tried :
adding -Dfile.encoding=UTF-8 option
changing keyword file using UTF8
changing the whole project encoding in ISO => which works but isn't suitable for production part that need to display messages in UTF8
our Pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
...
<properties>
<jbehave.version>3.6.5</jbehave.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<resource.encoding>UTF-8</resource.encoding>
</properties>
<build>
<testOutputDirectory>target/classes</testOutputDirectory>
<testResources>
<testResource>
<directory>src/test/resources</directory>
</testResource>
<testResource>
<directory>src/test/story</directory>
</testResource>
</testResources>
<plugins>
...
<plugin>
<artifactId>maven-eclipse-plugin</artifactId>
<version>2.8</version>
<configuration>
<downloadSources>true</downloadSources>
<downloadJavadocs>true</downloadJavadocs>
<additionalBuildcommands>
<buildcommand>com.google.gdt.eclipse.core.webAppProjectValidator</buildcommand>
</additionalBuildcommands>
<additionalProjectnatures>
<projectnature>com.google.gwt.eclipse.core.gwtNature</projectnature>
</additionalProjectnatures>
<classpathContainers>
<classpathContainer>org.eclipse.jdt.launching.JRE_CONTAINER</classpathContainer>
</classpathContainers>
<additionalConfig>
<file>
<name>.settings/org.eclipse.core.resources.prefs</name>
<content>
<![CDATA[eclipse.preferences.version=1
encoding/<project>=UTF-8]]>
</content>
</file>
</additionalConfig>
</configuration>
</plugin>
<plugin>
<groupId>org.jbehave</groupId>
<artifactId>jbehave-maven-plugin</artifactId>
<version>${jbehave.version}</version>
<executions>
<execution>
<id>run-stories-as-embeddables</id>
<phase>test</phase>
<configuration>
<scope>test</scope>
<includes>
<include>**/*Story.java</include>
</includes>
<ignoreFailureInStories>true</ignoreFailureInStories>
<ignoreFailureInView>false</ignoreFailureInView>
</configuration>
<goals>
<goal>run-stories-as-embeddables</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>unpack-jbehave-site-resources</id>
<phase>generate-resources</phase>
<goals>
<goal>unpack</goal>
</goals>
<configuration>
<overwriteReleases>false</overwriteReleases>
<overwriteSnapshots>true</overwriteSnapshots>
<artifactItems>
<artifactItem>
<groupId>org.jbehave.site</groupId>
<artifactId>jbehave-site-resources</artifactId>
<version>3.1.1</version>
<type>zip</type>
<outputDirectory>
${project.build.directory}/jbehave/view
</outputDirectory>
</artifactItem>
</artifactItems>
</configuration>
</execution>
<execution>
<id>unpack-jbehave-reports-resources</id>
<phase>generate-resources</phase>
<goals>
<goal>unpack</goal>
</goals>
<configuration>
<overwriteReleases>false</overwriteReleases>
<overwriteSnapshots>true</overwriteSnapshots>
<artifactItems>
<artifactItem>
<groupId>org.jbehave</groupId>
<artifactId>jbehave-core</artifactId>
<version>${jbehave.version}</version>
<outputDirectory>
${project.build.directory}/jbehave/view
</outputDirectory>
<includes>
**\/*.css,**\/*.ftl,**\/*.js
</includes>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
...
<!-- JBehave Dependencies -->
<dependency>
<groupId>org.jbehave</groupId>
<artifactId>jbehave-core</artifactId>
<version>${jbehave.version}</version>
</dependency>
<!-- Test Frameworks Dependencies -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.8.4</version>
<scope>test</scope>
</dependency>
</dependencies>
I have had some success subclassing the org.jbehave.core.io.LoadFromClasspath class, which I use in my configuration as the story loader, i.e.
MostUsefulConfiguration().useStoryLoader(new LoadFromClasspathUtf8());
here's my subclass with the proper method override:
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.io.IOUtils;
import org.jbehave.core.io.InvalidStoryResource;
import org.jbehave.core.io.LoadFromClasspath;
public class LoadFromClasspathUtf8 extends LoadFromClasspath {
public LoadFromClasspathUtf8(Class<?> loadFromClass) {
super(loadFromClass);
}
public LoadFromClasspathUtf8(ClassLoader classLoader) {
super(classLoader);
}
#Override
public String loadResourceAsText(String resourcePath) {
InputStream stream = resourceAsStream(resourcePath);
try {
return IOUtils.toString(stream, "UTF-8");
} catch (IOException e) {
throw new InvalidStoryResource(resourcePath, stream, e);
}
}
}
I say "I had some success" because when I look at the logs of my jbehave execution, accented french characters like è,à,é etc. are replaced by ?, but then, jbehave still matches this correctly to the steps using the regular RegexStoryParser. I didn't take time to investigate why this is, but I'm satisfied that my stories work correctly now.
I also added the file.encoding system property to my plugin configuration to make it clear that I intend to use UTF-8 encoding.
Same problem here as well. Even after adding the "-Dfile.encoding=UTF-8" parameter to MAVEN_OPTS the problem persisted. Turn out that I had this line inside my ~/.mavenrc file:
export MAVEN_OPTS="-Xmx1024m"
What was happening is the MAVEN_OPTS variable got reset before executing the JVM.
After change the ~/.mavenrc file to:
export MAVEN_OPTS="$MAVEN_OPTS -Xmx1024m"
The problem was solved. The file encoding is set correct when running:
export MAVEN_OPTS="$MAVEN_OPTS -Dfile.encoding=UTF-8"
mvn clean integration-test
Since you have your stories in the "test" context rather than "main" (in another module) - I think that there is probably something going on when stories are copied to target/test-classes.
I had exactly the same problem. By default, JBehave doesn't honor platform encoding. In order to fix this, you can use this custom StoryLoader which honors file.encoding system property:
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import org.apache.commons.io.IOUtils;
import org.jbehave.core.io.InvalidStoryResource;
import org.jbehave.core.io.LoadFromClasspath;
/**
* #author cedric.vidal
*
*/
public class FixedStoryLoader extends LoadFromClasspath {
public String loadResourceAsText(String resourcePath) {
InputStream stream = resourceAsStream(resourcePath);
try {
return IOUtils.toString(stream, platformCharset().name());
} catch (IOException e) {
throw new InvalidStoryResource(resourcePath, stream, e);
}
}
public static Charset platformCharset() {
String csn = System.getProperty("file.encoding");
Charset cs = Charset.forName(csn);
if (cs == null) {
cs = Charset.forName("UTF-8");
}
return cs;
}
}
Register it in JBehave configuration with:
new MostUsefulConfiguration().useStoryLoader(new FixedStoryLoader());
Configure your POM to use UTF-8 in all respectfull plugins (will be used by m2eclipse too):
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
And tell the JBehave Maven Plugin to use it also (look for the systemProperties block):
<plugin>
<groupId>org.jbehave</groupId>
<artifactId>jbehave-maven-plugin</artifactId>
<version>${jbehave.core.version}</version>
<executions>
<execution>
<id>unpack-view-resources</id>
<phase>process-resources</phase>
<goals>
<goal>unpack-view-resources</goal>
</goals>
</execution>
<execution>
<id>embeddable-stories</id>
<phase>integration-test</phase>
<configuration>
<includes>
<include>${embeddables}</include>
</includes>
<excludes/>
<systemProperties>
<property>
<name>file.encoding</name>
<value>${project.build.sourceEncoding}</value>
</property>
</systemProperties>
<ignoreFailureInStories>true</ignoreFailureInStories>
<ignoreFailureInView>false</ignoreFailureInView>
<threads>1</threads>
<metaFilters>
<metaFilter/>
</metaFilters>
</configuration>
<goals>
<goal>run-stories-as-embeddables</goal>
</goals>
</execution>
</executions>
</plugin>

Resources