How to programmatically parse/retrieve user's parameters in Intellij project from Gradle build file - intellij-idea

I need to retrieve some user specific parameters from Gradle build file in an Intellij project (build.gradle.kts)
Here a "build.gradle.kts" file content example I need to parse:
cutomParameters {
param1.set("any value")
sub_parameters1 {
sub_parameter1_1.set("foo")
}
subParameters2 {
subParameter21("foo")
subParameter22 {
subParameter221.set("foo")
}
}
}
I tried some code like this:
val connection: ProjectConnection =
GradleConnector.newConnector().forProjectDirectory(File(projectPath)).connect()
val model = connection.model(GradleBuild::class.java)
I can get the gradle build file using model.get().buildFile but how to retrieve the custom parameters described in the previous example?

Related

How to add SolanaKT to my project kotlin?

I have an existing kotlin project. Now I'm trying to add the SolanaKT library to it.
I have added the JitPack repository maven { url 'https://jitpack.io' } and dependency implementation 'com.github.metaplex-foundation:SolanaKT:2.0.1'.
Then I did a gradle sync.
I try using:
val endPoint = RPCEndpoint.devnetSolana
val network = HttpNetworkingRouter(endPoint)
val solana = Solana(network)
But i get error Unresolved reference: RPCEndpoint.
What am I doing wrong? Is there anything else I should do (maybe copy some files to the project) ?

Why do I need to reference a custom gradle config with square brackets?

I created a gradle build config just to download some dependencies. The documentation has been sparse, so I've piece together this working snippet based on random snippets and guesses.
configurations {
create("downloadDeps")
}
dependencies {
// JSON
configurations["downloadDeps"]("com.fasterxml.jackson.core:jackson-databind:2.13.3")
configurations["downloadDeps"]("com.fasterxml.jackson.module:jackson-module-kotlin:2.13.3")
}
repositories {
// internal repository
maven {
url = uri("...")
credentials {
username = System.getenv("ARTIFACTORY_USER") ?: System.getProperty("ARTIFACTORY_USER") as String
password = System.getenv("ARTIFACTORY_TOKEN") ?: System.getProperty("ARTIFACTORY_TOKEN") as String
}
}
}
tasks.register<Copy> ("downloadDeps") {
from(configurations["downloadDeps"])
into("lib/")
}
If I reference the "downloadDeps" dependency like configuration.downloadDeps or downloadDeps("com.fasterxml.jackson.core:jackson-databind:2.13.3"). I get an error about an unresolved reference to "downloadDeps".
Why does implementation("...") or configuration.implementation.get() work?
The documentation #Slaw provided helped me understand why I can do something like this:
implementation("group:artifact:1.0.0")
but not
myCustomConfig("group:artifact:1.0.0")
implementation being declared that way is supported because it comes from a plugin (the Kotlin/Java plugins)
The simplest way to associate a dependency with myCustomConfig would be to do this (see these docs):
"myCustomConfig"("group:artifact:1.0.0")

Room Migration test failing : schema not found

I'm try to implement android test for my room database, to test migrations. For this, I generated the schema needed, and I follow the step from the Android documentation.
When I run my migration test, it shows that the schema cannot be loaded, despite I added the assets line in the Gradle build. I added multiple other build types, it was not helping. I'm making something wrong, but I can't find where.
Room Version : 2.3.0
The error :
Cannot find the schema file in the assets folder. Make sure to include the exported json schemas in your test assert inputs. See https://developer.android.com/training/data-storage/room/migrating-db-versions#export-schema for details. Missing file: Asset file database.Sauvegarde/1.json not found
java.io.FileNotFoundException: Cannot find the schema file in the assets folder. Make sure to include the exported json schemas in your test assert inputs. See https://developer.android.com/training/data-storage/room/migrating-db-versions#export-schema for details. Missing file: Asset file database.Sauvegarde/1.json not found
at androidx.room.testing.MigrationTestHelper.loadSchema(MigrationTestHelper.java:326)
at androidx.room.testing.MigrationTestHelper.createDatabase(MigrationTestHelper.java:152)
at globalTests.migrations.MigrationTest.migrate1To2(MigrationTest.java:31)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.rules.TestWatcher$1.evaluate(TestWatcher.java:61)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.robolectric.RobolectricTestRunner$HelperTestRunner$1.evaluate(RobolectricTestRunner.java:575)
at org.robolectric.internal.SandboxTestRunner$2.lambda$evaluate$0(SandboxTestRunner.java:263)
at org.robolectric.internal.bytecode.Sandbox.lambda$runOnMainThread$0(Sandbox.java:89)
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:834)
In test structure:
MigrationTest :
package globalTests.migrations;
import ...;
#RunWith(AndroidJUnit4.class)
public class MigrationTest {
private static final String TEST_DB = "migration-test";
#Rule
public MigrationTestHelper helper;
public MigrationTest() {
helper = new MigrationTestHelper(InstrumentationRegistry.getInstrumentation(),
Sauvegarde.class.getCanonicalName(),
new FrameworkSQLiteOpenHelperFactory());
}
#Test
public void migrate1To2() throws IOException {
SupportSQLiteDatabase db = helper.createDatabase(TEST_DB, 1);
// Prepare for the next version.
db.close();
// Re-open the database with version 2 and provide
// MIGRATION_1_2 as the migration process.
db = helper.runMigrationsAndValidate(TEST_DB, 2, true, Migrations.MIGRATION_1_2);
// MigrationTestHelper automatically verifies the schema changes,
// but you need to validate that the data was migrated properly.
}
}
gradle.build :
testOptions {
execution 'ANDROIDX_TEST_ORCHESTRATOR'
}
javaCompileOptions {
annotationProcessorOptions {
arguments += ["room.schemaLocation":
"$projectDir/schemas".toString()]
}
}
sourceSets {
// Adds exported schema location as test app assets.
debug.assets.srcDirs += files("$projectDir/schemas".toString())
customDebugType.assets.srcDirs += files("$projectDir/schemas".toString())
androidTest.assets.srcDirs += files("$projectDir/schemas".toString())
test.assets.srcDirs += files("$projectDir/schemas".toString())
}
In schemas location :
The problem is like this one, but the solution not worked for me ...
Speaking from experience, one possible source of this issue is the stripping of assets during packaging, i.e., if you have something like the rule below. It seems like it should apply to the release build only, but, alas, it applies do debug as well and will remove your schema files from view.
buildTypes {
debug {...}
release {
aaptOptions {
ignoreAssetsPattern '!*.json'
}
}
}
Something else you could do is to look at what assets are visible to the various contexts you have available to you in the test itself:
println("Instrumentation context.assets")
var assets = InstrumentationRegistry.getInstrumentation().context.assets
assets.list("")?.forEachIndexed { index, it ->
println("$index -> $it")
}
println("Instrumentation targetContext.assets")
assets = InstrumentationRegistry.getInstrumentation().targetContext.assets
assets.list("")?.forEachIndexed { index, it ->
println("$index -> $it")
}
println("ApplicationProvider context.assets")
assets = ApplicationProvider.getApplicationContext<App>().assets
assets.list("")?.forEachIndexed { index, it ->
println("$index -> $it")
}
I found the problem,
Roboelectric didn't import my Android resources for the tests
you need to add this to Gradle:
testOptions {
unitTests{
includeAndroidResources = true
}
}
Source

Automatically re-run failed only scenario in cucumber java+testng

How can I make only failed scenarios to be run again automatically on failure ?
Here is some clue on what I am doing:
Pass TestRunner class from command line through cucumber-testng.xml file at run-time.
I am able to see rerun.txt file after scenario failed, with feature/GM/TK/payment.feature:71 (pointing to failed scenario) but failed scenario is not automatically re-run.
The "TestRunner" java file
#RunWith(Cucumber.class)
#CucumberOptions(strict = true,
features = { "src/test/resources/" }, //feature file location
glue = { "com/test/stepdefs", "com.test.cucumber.hooks" }, //hooks and stepdef location
plugin = { "json:target/cucumber-report-composite.json", "pretty", "rerun:target/rerun.txt"}
)
public class CucumberTestRunner extends AbstractTestNGCucumberTests
{
}
The "RunFailedTest" Class to re-run from rerun.txt file
#RunWith(Cucumber.class)
#CucumberOptions(
strict = false,
features = { "#target/rerun.txt" }, //rerun location
glue = { "com/test/stepdefs", "com.test.cucumber.hooks" }, //hooks and stepdef location
plugin = {"pretty", "html:target/site/cucumber-pretty", "json:target/cucumber.json"}
)
class RunFailedTest
{
}
you can achieve it by using gherkin with qaf it generates testng XML configuration for failed scenarios that you can use for rerun. It also support scenario rerun on fail by setting retry.count property.
using Cucumber + Maven + TestNG
first, you don't need "#RunWith(Cucumber.class)" as you have mentioned in your question, if you are using TestNG, only "#CucumberOptions" is required.
When you start your test execution, all scenario failures will be written to file "target/rerun.txt" as per the configuration mentioned in your Runner file.
Now, you need to create one more Runner file (for example - "FailureRunner") and in this file provide the path of "#target/rerun.txt" ( this already have the details of the failure scenarios ) as -> features = { "#target/rerun.txt" }
Now, you need to UPDATE your TestNG.xml file and include the "FailureRunner" as below-
<class name="Class path of Your First Runner Class name" />
<class name="class path of FailureRunner Class" />
Once you do all the above steps and run your execution, the first execution will write the failure scenarios in the "target/rerun.txt" and After that, the "FailureRunner" Class will be executed which will pick up the "#target/rerun.txt" file and Hence, Failure scenarios will be executed.
I have executed in the same way and it works fine, let me know if it helps !!

Job DSL script for email notifications for pass/failed Jenkins build?

I would like to configure email notifications using Job DSL instead of email-ext plugin.
The DSL does not provide the capability of other plugins, it merely exposes their capability to the script. The plugins still need to be installed.
As per the DSL API Docs, DSL has support for the Jenkins mailer plugin (included as standard),
job('example') {
publishers {
mailer('me#example.com', true, true)
}
}
This is not particularly customizable - you can't tell it to email after every passing build.
The email extension plugin is also supported by DSL:
job('example') {
publishers {
extendedEmail {
recipientList('me#halfempty.org')
defaultSubject('Oops')
defaultContent('Something broken')
contentType('text/html')
triggers {
beforeBuild()
stillUnstable {
subject('Subject')
content('Body')
sendTo {
developers()
requester()
culprits()
}
}
}
}
}
}
To email after every build regardless of status, using email-ext, you can use the always trigger (in place of stillUnstable trigger in the above example)
(code samples copied from linked documentation for the sake of surviving downtime.)
I'm using the Pipeline/Workflow DSL and got this working:
mail from: "",
to: "yoyo#example.com",
subject: """Jenkins ${env.JOB_NAME} [${env.BUILD_NUMBER}]""",
mimeType: "text/html",
body: """Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]':</p>
<p>Check console output at &QUOT;<a href='${env.BUILD_URL}'>${env.JOB_NAME} [${env.BUILD_NUMBER}]</a>&QUOT;</p>
<pre>${summary}</pre>"""