Getting error when passing parameters from Where block in Groovy-Spock code - groovy

I have written a code for my application.
def "Test for file type #FileFormat"() {
given:
HttpURLConnection connection = getHandlerURL('endpoint')
connection.setDoOutput(true)
connection.setRequestMethod("POST")
connection.setRequestProperty(HttpHeaders.CONTENT_TYPE, "RdfFormat."+RDFFileFormat+".toMIME()")
rdfStatement = ModelFactory.createDefaultModel().read(new ByteArrayInputStream(readRDFfromfile(Filename).bytes), null, "RdfFormat."+RDFFileFormat.toString()).listStatements().nextStatement()
when:
connection.getOutputStream().write(readRDFfromfile(Filename).bytes)
then:
connection.getResponseCode() == HTTP_CREATED
where:
FileFormat | Filename | RDFFileFormat
'N-TRIPLES' | 'n-triples.nt' | "NTRIPLES"
}
When I run my code I am getting error: SampleTest.Test for file type #FileFormat:37 » Riot in last line of Given clause.
The test is passing if I use RdfFormat.NTRIPLES.toString() instead of using the parameter RDFFileFormat passed from Where clause.
Tried assigning def format1 = "RdfFormat."+RDFFileFormat+".toString()" and using format1, but got same error.
Is there any way I can make it work?

I think you probably want:
connection.setRequestProperty(HttpHeaders.CONTENT_TYPE, RdfFormat."$RDFFileFormat".toMIME())

Related

Python Error: Cannot extract data from dictionary

I have a json output (y) like this below.
{
"WebACL":{
"Name":"aBlockKnownBadInputs-WebAcl",
"Id":"4312a5d0-9878-4feb-a083-09d7a9cfcfbb",
"ARN":"arn:aws:wafv2:us-east-1:100467320728:regional/webacl/aBlockKnownBadInputs-WebAcl/4312a5d0-9878-4feb-a083-09d7a9cfcfbb",
"DefaultAction":{
"Allow":{
}
},
"Description":"",
"Rules":[
{
"Name":"AWS-AWSManagedRulesKnownBadInputsRuleSet",
"Priority":500,
"Statement":{
"ManagedRuleGroupStatement":{
"VendorName":"AWS",
"Name":"AWSManagedRulesKnownBadInputsRuleSet"
}
},
"OverrideAction":{
"None":{
}
},
"VisibilityConfig":{
"SampledRequestsEnabled":true,
"CloudWatchMetricsEnabled":true,
"MetricName":"AWS-AWSManagedRulesKnownBadInputsRuleSet"
}
}
]
}
}
I want to extract "AWS-AWSManagedRulesKnownBadInputsRuleSet" from the section:-
"Name":"AWS-AWSManagedRulesKnownBadInputsRuleSet",
"Priority":500,
"Statement":{
"ManagedRuleGroupStatement":{
"VendorName":"AWS",
"Name":"AWSManagedRulesKnownBadInputsRuleSet"*
At the minute my code is returning a key error:
KeyError: 'Rules[].Statement[].ManagedRuleGroupStatement[].Name'
The format of this line is clearly wrong, but I don't know why.
ruleset = y['Rules[].Statement[].ManagedRuleGroupStatement[].Name']
My code block:
respons = client.get_web_acl(Name=(acl),Scope='REGIONAL',Id=(ids))
for y in response['WebACLs']:
ruleset = y['Rules[].Statement[].ManagedRuleGroupStatement[].Name']
Does anyone know what I'm doing wrong here?
UPDATE :- In case anyone else comes up against this problem, I fixed this by doing it a slightly different way.
#Requesting the info from AWS via get_web_acl request
respons = client.get_web_acl(Name=(acl),Scope='REGIONAL',Id=(ids))
#Converting the dict output to a string to make it searchable
result = json.dumps(respons)
#Defining what I want to search for
fullstring = "AWS-AWSManagedRulesKnownBadInputsRuleSet"
#Searching the output & printing the result: if = true / else = false
if fullstring in result:
print("Found WAF ruleset: AWS-AWSManagedRulesKnownBadInputsRuleSet!")
else:
print("WAF ruleset not found!")
Also, as part of my research I found a cool thing called jello.
(https://github.com/kellyjonbrazil/jello).
jello is similar to jq in that it processes JSON and JSON Lines data except it uses standard python dict and list syntax.
So, I copied my json into a file called file.json
Ran cat file.json | jello -s to print a grep-able schema by using the -s option
Found the bit I was interested in - in my case the name of the ManagedRuleGroupStatement and ran the following:
cat file.json | jello -s _.WebACL.Rules[0].Statement.ManagedRuleGroupStatement.Name
This gave me exactly what I wanted!
It doesn't work inside a python script but was something new and interesting to learn!

Getting no response from ProcessBuilder's input stream in some specific case

So I am trying to get battery status from linux, and so far the first command (path variable) returns perfectly and I am able to get its response in form of Sequence from the input stream, but unfortunately the second command (of result variable) returns empty sequence.
fun getLinuxBatteryStatus(): Nothing? {
val path = """upower --enumerate""".runCommand() ?: return null
val parameters = listOf("present", "state", "energy-full", "energy", "energy-rate", "time to empty", "percentage")
val result = """upower -i ${path.first { "battery_BAT" in it }} | grep -E "${parameters.joinToString("|")}""""
.also { println(it) }
.runCommand() ?: return null
result.forEach(::println) // <- no ouput
// println(result.count()) // <- 0
/* Do other thing and return something (that is not related to problem) */
}
Ouput:
upower -i /org/freedesktop/UPower/devices/battery_BAT1 | grep -E "present|state|energy-full|energy|energy-rate|time to empty|percentage"
The above output is from the also block in the last command, just to preview the command's string for debugging. And if I run the above command directly into the terminal I am successfully getting the responses as follows:
present: yes
state: charging
energy: 47.903 Wh
energy-empty: 0 Wh
energy-full: 50.299 Wh
energy-full-design: 48.004 Wh
energy-rate: 17.764 W
percentage: 95%
Why is the last command not working (not returning any response) with the ProcessBuilder?
Note: the extension function runCommand has been taken from here
private fun String.runCommand(
workingDir: File = File("."),
timeoutAmount: Long = 60,
timeoutUnit: TimeUnit = TimeUnit.SECONDS
): Sequence<String>? = try {
ProcessBuilder(split("\\s".toRegex()))
.directory(workingDir)
.redirectOutput(ProcessBuilder.Redirect.PIPE)
.redirectError(ProcessBuilder.Redirect.PIPE)
.start()
.apply { waitFor(timeoutAmount, timeoutUnit) }
.inputStream.bufferedReader().lineSequence()
} catch (e: IOException) {
e.printStackTrace()
null
}
The problem here is the pipe.
You're trying to run a pipeline — a construction involving running multiple programs, that needs a shell to interpret.
But ProcessBuilder runs a single program.  In this case, it's running the program upower and passing it the parameters -i, /org/freedesktop/UPower/devices/battery_BAT1, |, grep, -E, and "present|state|energy-full|energy|energy-rate|time to empty|percentage".  Obviously upower won't know what to do with the | parameter or those after it.
You could use ProcessBuilder to run up a shell instance, which could then run your pipeline; see this answer.
But it would probably be simpler, safer, and more efficient to do the filtering in your own code, and avoid calling grep entirely.
I recommend capturing the process's error output, which would very probably have made the problem clear.

how to go around "keyword can't be an expression" when updating in sqlalchemy?

i have a following statement:
conn = engine.connect()
conn.execute(Somedatabase.update().where(somecriteria==somecriteriavalue).values(name = somevalue))
and it works, but when i try replace it by following:
D={1: "name"}
print(D[1])
conn.execute(Somedatabase.update().where(somecriteria==somecriteriavalue).values(D[1]) = somevalue))
Then, I got an error: "keyword can't be an expression". How can I go around to be able use it in cycle?
So far i figured only
text="conn.execute(Somedatabase.update().where(somecriteria == somecriteriavalue).values("+(D[1])+" = \"somevalue\"))"
eval(text)
But i would prefer to not using eval.
I believe you can use a dictionary as a parameter for values:
D={1: "name"}
print(D[1])
conn.execute(
Somedatabase.update().where(
somecriteria==somecriteriavalue
).values({
D[1]: somevalue,
})
)
https://docs.sqlalchemy.org/en/13/core/dml.html#sqlalchemy.sql.expression.ValuesBase.values

Can't get HTTP headers from request

I'm trying to get the headers from a HTTP request. I've tried echoing them, only to get a compile error. I've tried looping through the headers as well. My code is:
var packet = newMultipartData()
packet["username"] = username
packet["password"] = password
var response = post(BASE & "users/login", multipart=packet)
echo response.headers
And the error I'm getting is: Error: type mismatch: got (HttpHeaders)
Figured it out - Turns out I can call the one I want from the list. Ex: response.headers["X-CSRF-TOKEN"]
The reason your code does not work because there is no $ proc defined for HttpHeaders:
let headers = newHttpHeaders()
headers["foo"] = "bar"
headers["foo2"] = "bar2"
echo headers["foo"] # compiles
echo headers # does _not_ compile
We can quickly implement an own $ proc ourselves:
proc `$`(h: HttpHeaders): string =
result = "{"
for key, value in h:
if result.len > 1: result.add(", ")
result.add(key)
result.add(": ")
result.add(value)
result.add("}")
The implementation is based on https://github.com/nim-lang/Nim/blob/master/lib/pure/collections/tables.nim#L333. Because HttpHeaders is just a type to a table, we can simply reuse the existing proc.
type
HttpHeaders* = ref object
table*: TableRef[string, seq[string]]

Data driven tests in Spock

I'm rewriting some JUnit test into Spock to take advantage of the data driven test style.
I'm struggling a bit with how to provide the verification with something dynamic.
Here's what I have so far:
def "domestic rules"(from, to, oneWay, check) {
expect:
String mealResponse = getMealResponse(new BookingOptions.BookingOptionsBuilder().setFrom(from).setTo(to).setOneWay(oneWay).build());
check(mealResponse)
where:
from | to | oneWay || check
'MNL' | 'PEK' | true || assertNoMeals()
}
def assertNoMeals = {
assert JsonAssert.with(it)
.assertThat('$.links', hasSize(1))
.assertThat('$.links[0].rel', is("http://localhost:9001/api/docs/rels/ink/meal-allocations"))
.assertThat('$.links[0].uri', startsWith("http://localhost:9001/api/tenants/acme/meals/allocations/"));
}
Unfortunately, I get a NullPointerException at the line with the first row of data.
I guess thats because the closure is being run at that point, rather than just declared.
Is there a way to do this better?
Change
def "domestic rules"(from, to, oneWay, check) {
To
#Unroll
def "domestic rules from #from to #to one way #oneWay"() {
def "domestic rules"() {
when: 'get meals using certain parameters'
String mealResponse = getMealResponse(new BookingOptions.BookingOptionsBuilder().setFrom(from).setTo(to).setOneWay(oneWay).build())
then: 'the json response should contain some contents (improve the message here!)'
JsonAssert.with(mealResponse)
.assertThat('$.links', hasSize(1))
.assertThat('$.links[0].rel', is(somethingToUseInAssertions))
where:
from | to | oneWay || somethingToUseInAssertions
'MNL' | 'PEK' | true || 'just some example'
}
The above should help you get in the right track. Notice that you should have some values only in the examples. If you need some logic in the assertions, use a value which indicates what kind of assertion needs to be made... but it's a very bad idea to use a closure as an example.
If you really want to make your test hard to maintain and go ahead and use closures as "values" in your examples, then do something like this:
def "domestic rules"() {
when:
String mealResponse = getMealResponse(new BookingOptions.BookingOptionsBuilder().setFrom(from).setTo(to).setOneWay(oneWay).build())
then:
check(mealResponse)
where:
from | to | oneWay || check
'MNL' | 'PEK' | true || this.&assertNoMeals
}
boolean assertNoMeals(mealResponse) {
assert JsonAssert.with(mealResponse)
.assertThat('$.links', hasSize(1))
.assertThat('$.links[0].rel', is("http://localhost:9001/api/docs/rels/ink/meal-allocations"))
.assertThat('$.links[0].uri', startsWith("http://localhost:9001/api/tenants/acme/meals/allocations/"))
return true // pass!
}
I advise you to learn both Groovy and Spock before writing something that is more reasonable. It's not hard, but it does take at least a few hours!

Resources