Say we are running mvn test.
I am wondering if there is a way to configure Maven to run some files before executing tests. In my case, I want to configure a library, but don't want to have to configure this library for every entrypoint in my app/tests. I am just looking to configure the lib for every mvn lifecycle hook which invokes a runtime.
Something like this:
#MavenRuntimeLifecycle
public class Whatever {
public void runtimeBegin(){
// right when the java process starts up
Mylib.configure("foo");
}
public void runtimeEnd(){
// right before the process shuts down
}
}
I assume this would be a Maven specific thing - not that it has to be in the same Java process as my server or tests etc.
Note that using Node.js, I would simply do it like so:
export class MyLib {
isConfigLoaded = false;
static loadConfig(){
// ...
}
static void run(){
if(!this.isConfigLoaded){
MyLib.loadConfig(require('../some/path/to/.mylib.config.js'));
this.isConfigLoaded = true;
}
this.doTheThing();
}
}
I could do the same thing with Java or Maven project, and just store a .java file in the resources directory. It's more manual, but it could be done.
Related
I'm creating a Gradle plugin with its corresponding objects for use in the Groovy DSL. I'm confused between the difference and extension and a task and how configuration should be passed between the two along with where the input and out annotations should be put. Here's my task
abstract public class UrlVerify extends DefaultTask {
#Input
abstract public Property<String> getUrl();
#TaskAction
public void verify() {
System.out.println(getUrl().get().toString());
}
}
Here's the extension
abstract public class UrlVerifierExtension {
abstract public Property<String> getUrl();
abstract public Property<Configuration> getConfiguration();
abstract public Property<Boolean> getIgnoreFailures();
public Set<ConflictCategory> getIncludeCategories() {
return includeCategories;
}
}
This plugin simply accepts a URL and validates it.
verification {
url = 'https://www.moooooereee.com/'
configuration = configurations.runtimeClasspath
ignoreFailures = false
}
I have the following plugin. I manually needed to pass the URL from the extension to the task and wondered if this is the correct way?
public class UrlVerifierPlugin implements Plugin<Project> {
#Override
public void apply(Project project) {
project.getPluginManager().apply(JavaLibraryPlugin.class);
UrlVerifierExtension extension = project.getExtensions().create("verification", UrlVerifierExtension.class);
UrlVerify verifyUrlTask = project.getTasks().create("verifyUrl", UrlVerify.class);
verifyUrlTask.getUrl().set(extension.getUrl());
}
}
Along with this, it is also unclear whether the #Input annotation belongs to the properties of the extension or the task?
You seem to have followed the examples from the Gradle documentation very precisely. This is the correct way to configure your custom tasks. The exact purpose of extensions is to have user-provided settings which are then consumed by your plugin to configure it and tasks.
Extensions are for the user to provide settings.
Tasks are for executing an action while Gradle is running.
The #Input annotation is used by Gradle to determine if the tasks needs to run. If the tasks has not run before, or if the input value has changed since the previous execution, then the tasks will run again.
Outputs declare some result produced by running the task. An example is a task that compiles Java files. The outputs would the the class files produced from the compilation process. If output files are modified or deleted by something other than the task that created them, then the task that created them is out-of-date, and Gradle will run it again.
Also, a task can declare the outputs of another task as its input. If task A creates some output files, and task B uses the outputs of task A as an input, then task B will be run when task A updates or creates its files.
In your case with the #Input annotation, my guess is that you do not want that in this case, because it tells Gradle that your tasks only needs to run once, then after that, only if the user updates the setting.
I've set up a test file in src/main/java with my cucumber annotations containing class A, as well as a test file extending class A in src/test/java with the following annotation on class B:
#ContextConfiguration(locations = {"classpath:META-INF/application-config.xml", "classpath:META-INF/overrule.xml" })
This is working fine when I do a maven clean install.
What I would like to achieve though is being able to run a feature file through the cucumber setup of class A and see its output. So far I've managed to find a method which should allow me to run the cucumber test, but I can't seem to figure out what its arguments should be. Could anyone provide me with an example of how to implement the function cucumber.api.cli.Main.run()?
#Override
public void buttonClick(final ClickEvent event) {
try {
final String[] arguments = {"foo", "bar" };
cucumber.api.cli.Main.run(arguments, ClassLoader.getSystemClassLoader());
} catch (final Throwable e) {
e.printStackTrace();
}
}
I would invoke the command line version using cucumber.api.cli.Main.main(args);
where args is a String array with the parameters set. I would not use the run command you refer to.
The documentation describes all available options.
Another source may be the getting started project supplied by the Cucumber team: https://github.com/cucumber/cucumber-java-skeleton
It may be of specific interest to look into the Ant build script https://github.com/cucumber/cucumber-java-skeleton/blob/master/build.xml to see what arguments they supply to Cucumber.
I created a jar file that launches an application to allow the user to select which test they want to run. Each test has its own class and main method. The UI application passes parameters to the main method for the class that represents the test.
I was able to create the executable JAR file for the UI application but nothing happens when I select the test I want to run. I think it is that JAR file can only handle one main method.
Below is part of the code for the application that allows the user to select which test to run.
public class UI extends JFrame {
String[] args={Environment, Browser, TestingCoverage, DBLog, "UI"};
if (chckbxEQ_CA_Home.isSelected())
{
EQ_CA_Home.main(args);
}
if (chckbxEQ_CA_Condo.isSelected())
{
EQ_CA_Condo.main(args);
}
if (chckbxEQ_CA_Renter.isSelected())
{
EQ_CA_Renter.main(args);
}
}
You can do that using Junit library.
JUnitCore junit = new JUnitCore();
Result res = junit.run(yourTestClass);
Don't invoke the main() method to avoid any possible interruptions, just let the JUnitcore find the appropriate test methods.
And also don't forget to include Junit.jar in classpath (or) include it as part of your jar file (as a fat jar).
I am trying to get gwt-test-utils to work. I set up the project in the following way:
src/main/java : all the java source code
src/test/java : the test source code
src/test/resources : resource files for the tests
I am building my project with gradle and eclipse. Gradle uses these directories correctly by default and I added all three of them as source directories to Eclipse.
I have successfully built and run the project and was able to execute some plain old JUnit tests as well as a GWTTestCase, so I think I set up the project and its dependencies correctly.
Now I wanted to use gwt-test-utils for some more advanced integration tests. To do so I did the following:
Add the gwt-test-utils and gwt-test-utils-csv to my dependencies
gwtTestUtilsVersion = '0.45'
testCompile group:'com.googlecode.gwt-test-utils', name:'gwt-test-utils', version:gwtTestUtilsVersion
testCompile group:'com.googlecode.gwt-test-utils', name:'gwt-test-utils-csv', version:gwtTestUtilsVersion
Add a gwt-test-utils.properties file to the directory src/test/resources/META-INF with the following content:
path/to/my/module = gwt-module
Added a class that extends GwtCsvTest to a package in the src/test/java directory. It is modeled after the second example in HowToWriteCsvScenario from the gwt-test-utils project wiki, replacing occurrence of their example classes with mine. It looks like this
#CsvDirectory(value = "gwtTests")
public class LoginLogoutTest extends GwtCsvTest
{
#Mock
private MainServiceAsync mainService;
private AppController appController = new AppController();
#CsvMethod
public void initApp()
{
appController.onModuleLoad();
}
#Before
public void setup()
{
GwtFinder.registerNodeFinder("myApp", new NodeObjectFinder()
{
#Override
public Object find(Node node)
{
return csvRunner.getNodeValue(appController, node);
}
});
GwtFinder.registerNodeFinder("loginView", new NodeObjectFinder()
{
#Override
public Object find(Node node)
{
return csvRunner.getNodeValue(appController.getRootPresenter().getCurrentlyActiveSubPresenters().iterator().next().getView(), node);
}
});
addGwtCreateHandler(createRemoteServiceCreateHandler());
}
}
added a csv-file for configuring the test to src/test/resources/gwtTests with the following content
start
initApp
assertExist;/loginView/emailTextBox
I tried executing it via the Eclipse's Run As > JUnit Test and indirectly via gradle build (which executes all the test cases, not just this one). Both lead to the same error:
ERROR GwtTreeLogger Unable to find type 'myPackage.client.AppController'
ERROR GwtTreeLogger Hint: Check that the type name 'myPackage.client.AppController' is really what you meant
ERROR GwtTreeLogger Hint: Check that your classpath includes all required source roots
The AppController class is the entry-point configured in the module I configured in gwt-test-utils.properties, which makes me think that configuration works correctly and the rest of the setup (dependencies and all) work as well.
In an earlier version I used the same file as a subclass of GWTTestCase and created an AppController instance in the same way. That worked, so I'm pretty sure the class path is setup correctly to include it as well. I also tried changing it back to the previous version just now and it still works.
I have no clue why the class is not found. Is there anything gwt-test-utils does differently which means I need to specifically set the class path for it? Otherwise it should just work, since both gradle and eclipse know about all the relevant source folders and dependencies.
I'm reading up on Gradle and am very interested in it, specifically because (it appears) that it allows the introduction of inheritance into the build process. For instance, if I have a Java web app that might be packaged and deployed to Google App Engine instances as well as Amazon EC2 instances, I need a sophisticated build that can take the same Java, XML, PROPERTIES, CSS and image files and package/deploy them into 2 drastically-differently packaged WAR files.
GAE apps are very specific as to how they are packaged; EC2 (pretty much) just require that you conform to servlet specs. GAE apps get "deployed" by running an update command from the appcfg.sh script that comes with your SDK; EC2 has their own way to deploy apps. The point is, they are very different packaging/deployment processes for both PaaS providers:
public abstract class PackageTask {
// ...
}
// Package my Eclipse project for deployment to GAE.
public class AppEnginePackageTask extends PackageTask {
// ...
}
// Package my Eclipse project for deployment to EC2 instances.
public class AmazonPackageTask extends PackageTask {
// ...
}
public abstract class DeployTask {
// ...
}
// Deployment to GAE.
public class AppEngineDeployTask extends DeployTask {
// ...
}
// Deployment to EC2.
public class AmazonDeployTask extends DeployTask {
// ...
}
Then, I might have a myapp.gradle buildfile that templates the build order of tasks:
clean()
compile()
package()
deploy()
...and somehow, I can configure/inject AppEnginePackageTask/AppEngineDeployTask in place of package()/deploy() for a GAE-based build, or I can configure/inject AmazonPackageTask/AmazoneDeployTask into those templated tasks. Again, I'm not sure how to do this (or even if Gradle can do this), but it's what I'm after.
My understanding was that Gradle can do this. Ant can also be forced to have highly-modular, elegant builds that work this way, but being XML-based, it takes some finessing, whereas an OOP-based language like Groovy makes this cleaner and simpler.
However, all the examples I see of Gradle tasks take the following form:
task package(dependsOn: 'compile') {
// ...
}
task deploy(dependsOn: 'package') {
// ...
}
So I ask: these look/feel like non-OOP task definitions. Is my understanding of Gradle (and its OOP nature) fundamentally incorrect? What am I missing here? How can I accomplish these notions of "configurable/injectable build templates" and inheritance-based tasks? Thanks in advance!
Edit I re-tagged this question with "groovy" because Gradle buildscripts are written in a Groovy DSL, and someone who happens to be a Groovy-guru (say that 5 times fast) might also be able to chime in even if they know little about Gradle.
As described here, there are simple tasks and enhanced tasks. The latter are much more flexible and powerful.
The following example isn't exactly what you describe, re:injection, but it illustrates OOP.
Here is the sample build.gradle file. It avoids "package" as that is a keyword in Java/Groovy. The 'build' target depends on 'compile' and some flavour of 'doPack', depending on a property called 'pkgTarget'.
task compile << {
println "compiling..."
}
task build() << {
}
build.dependsOn {
compile
}
build.dependsOn {
if (pkgTarget == "Amazon") {
task doPack(type: AmazonPackageTask)
} else if (pkgTarget == "Google") {
task doPack(type: GooglePackageTask)
} else {
task doPack(type: MyPackageTask)
}
}
where the tasks are defined later in the same file. (Per doc, this code can go into a "build src" directory):
// -----
class MyPackageTask extends DefaultTask {
def init() { println 'common stuff' }
#TaskAction
def doPackage() {
println 'hello from MyPackageTask'
}
}
class AmazonPackageTask extends MyPackageTask {
#TaskAction
def doPackage() {
init()
println 'hello from AmazonPackageTask'
}
}
class GooglePackageTask extends MyPackageTask {
#TaskAction
def doPackage() {
init()
println 'hello from GooglePackageTask'
}
}
and here is the gradle.properties file:
pkgTarget=Amazon