In build.gradle I Know you can do this
ext {
dbUsername = System.getenv("DB_USER").toString()
dbPassword = System.getenv("DB_PASS").toString()
libsUserNameNew = System.getenv("LIBS_USERNAME_NEW").toString()
libsPassNew = System.getenv("LIBS_PASS_NEW").toString()
gitShortTag = System.getenv("SHORT_SHA").toString()
repoName = System.getenv("REPO_NAME").toString()
group = "app.test.customerservicepoc"
mainClass = "app.test.customerservicepoc.CustomerServicePOC"
}
How can I achieve the same using build.gradle.kts
This is what I have tried
var dbUsername =""
var dbPassword =""
var LibsUserNameNew = ""
var LibsPassNew = ""
var gitShortTag = ""
var repoName = ""
and then
ext {
dbUsername = System.getenv("DB_USER").toString()
dbPassword = System.getenv("DB_PASS").toString()
kyoskLibsUserNameNew = System.getenv("LIBS_USERNAME_NEW").toString()
LibsPassNew = System.getenv("LIBS_PASS_NEW").toString()
gitShortTag = System.getenv("SHORT_SHA").toString()
repoName = System.getenv("REPO_NAME").toString()
group = "app.test.mms"
}
during build I end up getting errors
What went wrong: 945 Cannot invoke "String.toString()" because the return value of
"org.gradle.internal.classpath.Instrumented.getenv(String, String)" is
null
I am migrating the project to kotlin gradle, how can I define the variables in kotlin gradle?
Well, the issue is shown in the other question, System.getenv is a static java method that doesn't guarantee the nullability of the returned String. In Kotlin, this is a compilation error. So what the compiler is telling you is "I cannot guarantee that calling toString() on the returned string won't crash with a NullPointerException because the JVM method getenv doesn't guarantee it". I'd argue that you don't need the toString() call at all.
lateinit var db: String
// or
var db: String? = null //this can now be null
//then
ext {
db = System.getenv("YOUR_DB") ?: "" //UPDATE: you also need this since getenv can return null, or you need to make the variable `String?`
//or
db = System.getenv("YOUR_DB") ?: "" // since it can be null, set some fallback, like empty or null
}
This should work no problem.
UPDATE
I've created a new empty android project with compose (which uses build.gradle.kt instead of groovy), and added this:
lateinit var something1: String
var something2: String? = null
ext {
something1 = System.getenv("something") ?: ""
something2 = System.getenv("something2") ?: ""
}
It compiled no problem. (And I'd assume it would work if the environment variables were set).
BUILD SUCCESSFUL in 25s
Update 2 a real test
I've actually done this
lateinit var something1: String
var something2: String? = null
ext {
something1 = System.getenv("SHELL") ?: ""
something2 = System.getenv("SHELL") ?: ""
}
tasks.register("printSomething") {
println("Something 1 is $something1")
println("Something 2 is $something2")
}
Then I ran ./gradle printSomething
And here's the result:
Related
I have more than 6 environments against which i have to run the same set of rest api scripts. For that reason i have stored all that test data and the end points/resource paths in a json file. I then try to read this json file into my karate-config.js file, this is because i want to fetch the data corresponding to the environment that is being passed from the command line (karate.env), which am reading into my karate-config.js file
Below is my json file sample
[
{
"qa":{
"username_cm_on":"test_cm_on_qa",
"password_cm_on":"Test123$",
"nonadmin_username_cm_on":"test_non_admin_cm_on_qa",
"nonadmin_password_cm_on":"Test123$",
"username_cm_off":"test_cm_off_qa",
"password_cm_off":"Test123$",
"nonadmin_username_cm_off":"test_non_admin_cm_off_qa",
"nonadmin_password_cm_off":"Test123$",
"zuul_urls":{
"home-sec-uri":"https://qa.abc.com/qa/home-sec-uri",
"home-res-uri":"https://qa.abc.com/qa/home-res-uri"
}
}
},
{
"uat":{
"username_cm_on":"test_cm_on_uat",
"password_cm_on":"Test123$",
"nonadmin_username_cm_on":"test_non_admin_cm_on_uat",
"nonadmin_password_cm_on":"Test123$",
"username_cm_off":"test_cm_off_uat",
"password_cm_off":"Test123$",
"nonadmin_username_cm_off":"test_non_admin_cm_off_uat",
"nonadmin_password_cm_off":"Test123$",
"zuul_urls":{
"home-sec-uri":"https://uat.abc.com/qa/home-sec-uri",
"home-res-uri":"https://uat.abc.com/qa/home-res-uri"
}
}
}
]
and below is my karate-config.js file
function() {
// var env = karate.env; // get system property 'karate.env'
var env = 'qa';
var cm = 'ON';
var envData = call read('classpath:env_data.json'); //require("./env_data.json");
// write logic to read data from the json file _ Done, need testing
karate.log('karate.env system property was:', env);
switch(env) {
case "qa":
if(cm === 'ON'){
config.adminusername_cm_on = getData().username_cm_on;
config.adminpassword_cm_on = "";
config.nonadminusername_cm_on = getData().nonadmin_username_cm_on;
config.nonadminpassword_cm_on = "";
}else if(cm === "OFF") {
config.adminusername_cm_off = getData().username_cm_off;
config.adminpassword_cm_off = "";
config.nonadminusername_cm_off = getData().nonadmin_username_cm_off;
config.nonadminpassword_cm_off = "";
}
break;
case "uat":
break;
default:
break;
}
// This method will return the data from the env_data.json file
var getData = function() {
for(var i = 0; i < obj.length; i++) {
for(var e in obj[i]){
var username_cm_on = obj[i][e]['username_cm_on'];
var nonadmin_username_cm_on = obj[i][e]['nonadmin_username_cm_on'];
var username_cm_off = obj[i][e]['username_cm_off'];
var nonadmin_username_cm_off = obj[i][e]['nonadmin_username_cm_off'];
return {
username_cm_on: username_cm_on,
nonadmin_username_cm_on: nonadmin_username_cm_on,
username_cm_off: username_cm_off,
nonadmin_username_cm_off: nonadmin_username_cm_off
}
}
}
}
var config = {
env: env,
data: getData(),
}
return config;
}
I tried several ways to load the env-data.json file into karate-config.js as below
var envData = call read('classpath:env_data.json');
I know the above is not valid from this stackover flow answer Karate - How to import json data by Peter Thomas
So,tried with the below ones
var envData = read('classpath:env_data.json');
var envData = require("./env_data.json");
var envData = require('./env_data.json');
But, still facing issues with reading the json file. Appreciate help on this.
I think you over-complicated your JSON. You just need one object and no top-level array. Just use this as env_data.json:
{
"qa":{
"username_cm_on":"test_cm_on_qa",
"password_cm_on":"Test123$",
"nonadmin_username_cm_on":"test_non_admin_cm_on_qa",
"nonadmin_password_cm_on":"Test123$",
"username_cm_off":"test_cm_off_qa",
"password_cm_off":"Test123$",
"nonadmin_username_cm_off":"test_non_admin_cm_off_qa",
"nonadmin_password_cm_off":"Test123$",
"zuul_urls":{
"home-sec-uri":"https://qa.abc.com/qa/home-sec-uri",
"home-res-uri":"https://qa.abc.com/qa/home-res-uri"
}
},
"uat":{
"username_cm_on":"test_cm_on_uat",
"password_cm_on":"Test123$",
"nonadmin_username_cm_on":"test_non_admin_cm_on_uat",
"nonadmin_password_cm_on":"Test123$",
"username_cm_off":"test_cm_off_uat",
"password_cm_off":"Test123$",
"nonadmin_username_cm_off":"test_non_admin_cm_off_uat",
"nonadmin_password_cm_off":"Test123$",
"zuul_urls":{
"home-sec-uri":"https://uat.abc.com/qa/home-sec-uri",
"home-res-uri":"https://uat.abc.com/qa/home-res-uri"
}
}
}
And then this karate-config.js will work:
function() {
var env = 'qa'; // karate.env
var temp = read('classpath:env_data.json');
return temp[env];
}
And your tests can be more readable:
Given url zuul_urls['home-sec-uri']
If you have trouble understanding how this works, refer to this answer: https://stackoverflow.com/a/59162760/143475
I am trying to add column to the end of a file without changing the contents using SuperCSV and kotlin.
I cannot use CSVWriter due to limitation of resources.
So, my idea is to read from the original file row by row and add that to a string and have the result be used as a byte array.
fun addColumnToCSV(csvData: ByteArray, columnName: String, columnValue: String): ByteArray {
val prefs = CsvPreference.Builder(CsvPreference.STANDARD_PREFERENCE)
.useQuoteMode(NormalQuoteMode()).build()
val mapReader = CsvMapReader(BufferedReader(InputStreamReader(csvData.inputStream())), prefs)
val readHeader = mapReader.getHeader(true)
var row = mapReader.read(*readHeader)
var csv: String = readHeader.joinToString(",", postfix = ",$columnName\n")
while (row != null) {
val rowValue=readHeader.map { header-> row.getOrDefault(header,"\\s") }
csv += rowValue.joinToString(",", postfix = ",$columnValue\n")
row = mapReader.read(*readHeader)
}
csv = csv.trim()
mapReader.close()
return csv.toByteArray()
}
So, I have an example here and written a test for it.
#Test
fun `should add extra column in csv data when there are missing values`() {
val columnName = "ExtraColumn"
val columnValue = "Value"
val expectedCSV = "Name,LastName,$columnName\n" +
"John,Doe,$columnValue\n" +
"Jane,,$columnValue"
val csvData = "Name,LastName\n" + "John,Doe\n" + "Jane,"
val csv = addColumnToCSV(csvData.toByteArray(), columnName, columnValue)
Assertions.assertThat(String(csv)).isEqualTo(expectedCSV)
}
This test fails because the actual of csv data is
Name,LastName,ExtraColumn
John,Doe,Value
Jane,null,Value
I want it to be this, so that I am not changing the existing values that are present in the csv file.
Name,LastName,ExtraColumn
John,Doe,Value
Jane,,Value
I have tried with row.getOrDefault(header,"") its still the same result. How do I achieve this?
The problem seems to be on this line:
val rowValue=readHeader.map { header-> row.getOrDefault(header,"\\s") }
Without testing this, I would say that there's a null in row at index LastName, hence default value in getOrDefault is not applied because map contains the key.
Please try something like this:
val rowValue=readHeader.map { header-> row.getOrDefault(header,"\\s") ?: "" }
I tried to convert a java file to kotlin file but i'm getting this error : An annotation argument must be a compile-time constant
#StringDef(
BillingEnum.ALL,
BillingEnum.PAID,
BillingEnum.PENDING,
BillingEnum.OVERDUE,
BillingEnum.OPEN,
BillingEnum.DELETED
)
annotation class BillingEnum {
companion object {
var ALL = ""
var PAID = "paid"
var PENDING = "pending"
var OVERDUE = "overdue"
var OPEN = "open"
var DELETED = "deleted"
}
}
Before it looked like this:
#StringDef({
BillingEnum.ALL,
BillingEnum.PAID,
BillingEnum.PENDING,
BillingEnum.OVERDUE,
BillingEnum.OPEN,
BillingEnum.DELETED
})
public #interface BillingEnum {
String ALL = "";
String PAID = "paid";
String PENDING = "pending";
String OVERDUE = "overdue";
String OPEN = "open";
String DELETED = "deleted";
}
You must write
annotation class BillingEnum {
companion object {
const val ALL = ""
const val PAID = "paid"
const val PENDING = "pending"
const val OVERDUE = "overdue"
const val OPEN = "open"
const val DELETED = "deleted"
}
}
I have a question about "getDeclaredMethod" in kotlin.
I have a class:
class WorksheetFreeField : Serializable {
#SerializedName("val_value_1")
var val_value_1: String? = ""
#SerializedName("val_value_2")
var val_value_2: String? = ""
#SerializedName("val_value_3")
var val_value_3: String? = ""
Now I try this:
try {
val c = WorksheetFreeField::class
for (field in fields) {
val method = c.java.getDeclaredMethod("setVal_value_" + field.order)
Now I got this error in my catch:
com.werkbon.objects.WorksheetFreeField.setVal_value_1 []
What did I do wrong?
Take a look at c.java.declaredMethods in debug mode. Method setVal_value_1 exists, but has a parameter of type String.
So to make c.java.getDeclaredMethod work, you have to call it with 2 parameters: method name and String::class.java.
I am trying to introduce a method in my program which should result into a substring. I wrote the following code but why would not this work?
class testmethod {
String FQDN = "TEST.domain.local"
def sname = shortname(FQDN);
println $sname
def shortname(Longname)
{
shortname1 = Longname.substring(0, Longname.indexOf('.'))
return shortname1
}
}
First of all the code should be(for better readability) :-
def shortname(String Longname) not def shortname(Longname).
Also shortname1 = Longname.substring(0, Longname.indexOf('.')) in this shortname1 is not defined.
Moreover you can try :-
def shortname(String Longname)
{
String[] shortnameArr = Longname.split("\\.");
return shortnameArr[0];// will return TEST
}
You're mixing both script and class concepts of the Groovy in one single piece of code.
Just remove the class definition and $ sign to use the script way:
String FQDN = "TEST.domain.local"
def sname = shortname(FQDN);
println sname
def shortname(Longname)
{
shortname1 = Longname.substring(0, Longname.indexOf('.'))
return shortname1
}
Or add class initialization and local variable declaration to use the class way:
class testmethod {
String FQDN = "TEST.domain.local"
def sname = shortname(FQDN);
def shortname(Longname)
{
def shortname1 = Longname.substring(0, Longname.indexOf('.'))
return shortname1
}
}
def tc = new testmethod()
println tc.sname