Build Gradle getProperties before running already made task - gradle

I’m trying to use a Java, Serenity-BDD project with gradle version 4.8+, but the application is not pulling the CLI arguments of -Denvironment and -Dservicebranches. I have these properties as blank values in my local.properties file, and they’re not getting assigned when my app runs.
./gradlew --build-cache build -Dwebdriver.remote.url=${SELENIUM_REMOTE_URL} -Denvironment=${ENVIRONMENT} -Dservicebranches=${SERVICE_BRANCHES} -Dtags=${TAGS}
I have a local.properties file with properties that are being successfully dependency injected into the project (through Serenity-Spring). I'm hoping that these CLI arguments will override these values:
servicebranches=
environment=local
But right now, anything specified in the CLI arguments are not being passed into the project. Either through DI, or through explicitly grabbing the environment variables in the build.gradle, which what I've tried hasn't been working.
Here's a few things which I have tried in the build.gradle:
//task integrationTests() {
// doFirst
// {
// def environment = System.getProperty('environment')
// def servicebranches = System.getProperty('servicebranches')
// }
// tasks.build.execute()
//}
//integrationTests.dependsOn(build)
//build.doFirst{
// systemProperties System.properties
// def environment = System.properties['environment']
// environment = environment //This actually flags with 'Silly assignment'
//}
build.doFirst{
def environment = System.getProperty('environment')
def servicebranches = System.getProperty('servicebranches')
}
The latest one seems to still be missing a step, because the program is still working, but the args are still not getting through. I've even tried -Denvironment=potato, and no errors have come up because I do not have a property or properties file named that.
I've also tried using the -P tag instead of -D tag, but that doesn't seem to be working either.
All I’m trying to do is use build.gradle to use System.getProperty(‘environment’) and System.getProperty(‘servicebranches’) before I use the already created ‘build’ task that comes with Serenity. How would I do this? Do I build a whole new task, where I use these getProperties, and then call the build task? Do I have to specify the assignment of these same named variables in the local.properties file?

-D is for system properties in Gradle. Try with -P instead (https://docs.gradle.org/current/userguide/build_environment.html#sec:project_properties)

I know this is a very old question but here's what I did to solve my problem, I got the idea from here: https://github.com/serenity-bdd/serenity-documentation/pull/120/files
Serenity was not pulling the environment from gradle to use EnvironmentSpecificProperties, it kept saying "undefined property for environment 'null" when I removed the default environment. I had to add this to my Gradle file:
test {
systemProperty 'environment', System.properties['environment']
}

Related

Get gradle play plugin to use alternative application.conf

I am trying to get my play application to use a different application.conf. I have both application.conf and dev_application.conf in the conf directory. I've tried setting jvmargs off of fork options, but it doesn't seem to work, or even throw an error. My build.gradle can be seen here:
https://pastebin.com/C8FkM4Kb
But the important part is
binaries.all {
tasks.withType(PlayRun) {
forkOptions.jvmArgs = ["-Dconfig.resource=dev_application.conf"]
}
}
Then I try to run gradle runPlayBinary, and I always get the regular application.conf instead of the dev_application.conf
Why isn't this working?
move tasks.withType(PlayRun) to global scope seems work.

Java: How to add Environment Variables to a JUnit Tests in Gradle

I've managed to get the test task to run my unit tests, but they fail because env properties I am using are not set, eg: String base=System.getenv("TESTNG_BASE_PATH");
So, I've done something like:
tasks.withType(Test) {
systemProperty 'TESTNG_BASE_PATH','long\\path\\to\env\var\value'
}
But I still get the same exception from my code that the file is not found, so its obviously not the right way of doing this.
So how to do this, please?
If you are getting via System.getenv(...) you'll need to set an environment variable. I've also included a command line flag for switching on/off standard streams
tasks.withType(Test) {
environment 'TESTNG_BASE_PATH','long\\path\\to\env\var\value'
testLogging.showStandardStreams = Boolean.parseBoolean(findProperty('showStandardStreams'))
}
To run you could do
./gradlew check -PshowStandardStreams=true

createStartScripts change script name

In an attempt to follow the doc, I added a task like this to my build.gradle file:
task createStartScripts(type: CreateStartScripts) {
applicationName = 'dc-coverage-calculator'
}
I then executed
./gradlew clean installDist
at which point I expected to find a file at build/install/dc-coverage-calculator/bin/dc-coverage-calculator, but no files with dc-coverage-calculator were created anywhere the build folder. Instead, gradle continued to use the default application name, based on the mainClassName.
I also tried removing the hyphens from the app name.
Unfortunately it doesn't work this way. You've added a new task whereas yo need to modify the existing one, which will be done this way:
startScripts {
applicationName = 'dc-coverage-calculator'
}
Grab a demo here.

How to use variable outside the task in gradle script

I am stuck in a situation where need to read a file (for some values, let's say version number) from inside a war file and use it somewhere else in the same script (I am exploding the war file for this purpose using a Copy task). To explain the need, I will write down with the example below:
Defined the variable:
def projVersion = "NULL"
Exploding the war:
task explodedWar(type: Copy) {
from zipTree("$buildPath/projectName.war")
into file("$buildPath/projectName")
}
Reading the file from exploded folder and getting a value:
task warVersion(dependsOn : ['explodedWar']) <<{
Properties versionFile = new Properties()
versionFile.load(new FileInputStream("$buildPath/projectName/META-INF/MANIFEST.MF"))
ext.projVersion = versionFile.getProperty("Version")
}
When Using the variables new value outside the task (This part is throwing Error):
println "Variables new value: " + warVersion.projVersion
When Using the variables new value inside some other task (This part is Successful):
task VersionPrint(dependsOn : ['warVersion']) <<{
println "Project Version under print task" + warVersion.projVersion
}
Basically, I am able to use the new value of the variable inside any other task in the same script, but when I am trying to use the variables new value outside the task areas (sorry but it's a need), it is throwing error:
Error (When using variable outside the task) ***
* What went wrong:
A problem occurred evaluating root project 'Scripts'.
> Could not find property 'projVersion' on task ':warVersion'
Let me know, Am I trying to achieve something which is achievable? or is it going to be rule breaking way for gradle?
If it is possible what I am searching for, please let me know the solution, how to achieve.
You're not thinking about the build lifecycle correctly.
When you define the warVersion task, which depends on explodedWar, you're telling Gradle that you want to set the property projVersion during the execution of the warVersion task.
This means that you can't attempt to read the property until after the warVersion task is run. Otherwise, it will not be defined. If you attempt to "use the value outside of a task", you're no longer waiting for the warVersion task to run. Code that is outside of the scope of a task will be executed during the configuration phase, not the execution phase.
when I am trying to use the variables new value outside the task areas (sorry but it's a need), it is throwing error:
You need to refactor how you define the projVersion variable.
You could refactor your code so you don't need to use the value outside of tasks.
You could use the new PropertyState API for lazy-evaluated properties.
You could change your logic to execute during the configuration phase.
The last is not ideal as it bypasses task conveniences, such as up-to-date checking. However, you can try it out by changing your copy task to call Project#copy, then read the properties file and declare your properties value, all outside of the scope of tasks:
copy {
from zipTree("$buildPath/projectName.war")
into file("$buildPath/projectName")
}
Properties versionFile = new Properties()
versionFile.load(new FileInputStream("$buildPath/projectName/META-INF/MANIFEST.MF"))
ext.projVersion = versionFile.getProperty("Version")
This code will be executing during the configuration phase. Now, anywhere after this point you should be able to reference ext.projVersion.

How can I reference a Travis secure variable in my build.gradle?

One of my project dependencies sits on a private Bintray repo, which requires a username and password to access. Locally, I have these set in my gradle.properties:
bintrayUsername=<myUserName>
bintrayPassword=<myPass>
This works (locally), where hasProperty(X) resolves true and it uses this property:
allprojects {
repositories {
jcenter()
def mahBintrayUsername = hasProperty(bintrayUsername) ? bintrayUsername : System.getenv('bintrayUsername')
def mahBintrayPassword = hasProperty(bintrayPassword) ? bintrayPassword : System.getenv('bintrayPassword')
maven {
credentials {
username mahBintrayUsername
password mahBintrayPassword
}
url 'http://dl.bintray.com/my-repo-org/maven-private'
}
}
}
On Travis, I use secure variables so I don't have to expose these values in my public repo, but with the aim of being able to build directly from my public repo. When the build starts, you can see that the variables are exported:
Setting environment variables from .travis.yml
$ export bintrayUsername=[secure]
$ export bintrayPassword=[secure]
$ export TERM=dumb
...
FAILURE: Build failed with an exception.
* Where:
Build file '/home/travis/build/ataulm/wutson/build.gradle' line: 15
* What went wrong:
A problem occurred evaluating root project 'wutson'.
> Could not find property 'bintrayUsername' on repository container.
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
BUILD FAILED
I'm unsure how to reference the exported environment variables in my build.gradle such that they would be found.
I've checked this answer which doesn't seem to work (as above), as well as this comment which results in the same build failure.
The series of commits I've tried can be seen here, with the latest: https://github.com/ataulm/wutson/commit/9331b8d91b4acf11fd3e286ff8ba1a24ed527177
The error is a result of your ternary statement attempting to evaluate bintrayUsername as part of the condition.
The hasProperty() method takes a String argument so you should use hasProperty('bintrayUsername'), instead of hasProperty(bintrayUsername). Doing the latter will attempt to evaluate a property that may not exist, leading to the MissingPropertyException.
Simply remember that trying to evaluate any symbol that doesn't exist will typically result in a MissingPropertyException.
Below an example to define a project property -not a local variable- if it is not defined, by getting the value from the Environment, i.e. where Travis puts your secure variable.
project.ext {
if (! project.hasProperty('some_prop')) {
some_prop = System.getenv('some_prop')
}
}
If you never set it as a property (not using gradle.properties files) and you always want to set it from the environment, just remove the IF part. :)
Note: I wanted a project property so I can use it also to set values in my spring-boot YAML file... both locally and in CI.

Resources