OPA unit-test failing, How to output response variable? - open-policy-agent

Newbie to OPA, I am writing OPA unit test case.
test_valid_type {
response = evaluate with
input as valid_type
response == "approved"
}
it's failing response == "approved". I want to see the output of response variable, how do i output it?

Try the trace method provided by OPA for debugging.
https://www.openpolicyagent.org/docs/latest/policy-reference/#debugging
This will let you print the output.
In your example you can add trace(response) which will print the response output.

After reading many documention finally found it.
trace(variable)
prints the content of the variable.
[Ref][1]

Related

Jenkinsfile (Groovy) URI validator

I'm fairly new to Groovy and Jenkins, so hopefully this question is coherent.
I have a Jenkinsfile written in Groovy and would like to validate one of the params as a valid URI. Without writing my own regex check, is there a library I could easily invoke during Jenkins startup?
You can try this:
try {
def foo = new java.net.URL("yourURI").openStream()
if (foo.getClass() == sun.net.www.protocol.http.HttpURLConnection$HttpInputStream) {
println 'valid'
foo.close()
}
}
catch (java.io.FileNotFoundException e) {
println 'not valid'
return
}
Unfortunately URL.toUri is not allowed at least in our setup. (It could possibly be allowed with a separate config.) Apparently opening the url (trying to connect to the host) could be possible, but that feels like it could cause other problems.
I ended up with this:
// Validation URLs in Jenkins script is hard (URL.toUri is banned). This regex roughly matches the subset of
// URLs we might want to use (and some invalid but harmless URLs). You can get a rough sense what
// this matches with a generation tool like https://www.browserling.com/tools/text-from-regex .
def saneUrlPattern = ~/^https:\/\/[-\w]{1,32}(\.[-\w]{1,32}){0,4}(:[0-9]{1,5})?(\/|(\/[-\w]{1,32}){1,10})?(\?([-\w]{1,32}=[-\w]{0,40}(&[-\w]{1,32}=[-\w]{0,40}){1,8})?)?(#[-\w]{0,40})?$/
if (!(params.sourceUrl =~ saneUrlPattern)) {
return [error: "Invalid url ${params.sourceUrl}. A simple https URL is expected."]
}
I realise that trying to validate URLs with a regular expression is difficult. I tried to strike a balance between strict and correct enough validation and a regular expression that has some hope of being understood by looking at it and being reasonably convinced as to what it actually matches.

Project Reactor test never completes

I have created a simple Kafka consumer that returns a Flux of objects (the received messages) and I'm trying to test it using the StepVerifier.
In my test, I do something like that:
Flux<Pojo> flux = consumer.start();
StepVerifier.create(flux)
.expectNextMatches(p -> p.getList().size() == 3)
.verifyComplete();
The assertion works ok (if I change the value from 3 to something else, the test fails). But, if the assertion passes, than the test never exit.
I have also tried to use the verify method like so:
StepVerifier.create(flux)
.expectNextMatches(f -> f.getEntitlements().size() == 3)
.expectComplete()
.verify(Duration.ofSeconds(3));
In this case, I get this error:
java.lang.AssertionError: VerifySubscriber timed out on false
Any idea what I'm doing wrong?
The Kafka Flux is probably infinite, so it never emits the onComplete signal, which the test waits for. You can call .thenCancel().verify() if you're only interested in testing that first value.

Output a text file from Ranorex to include just a pass/fail result and a number

I am trying to get Ranorex to output a text file which will look like the following:
Pass
74
The pass/fail result will be obtained based on whether the test running has passed or failed. The number will be hardcoded to all I need to do is store that in a variable and include it in the output.
I would have thought it would have been simple but I'm struggling to get any help from Ranorex. I though I might be able to use the reporting function, change the output file type and alter the report structure but that didn't work either.
Although I am used to Ranorex and writing my own user code, I am new to adapting it in this way.
All my user code is written in C#
Can anyone offer any assistance?
Thanks!
Edit: So I've now managed to get Ranorex to output a text file and I can put any text into it, including a string stored in a variable.
However I'm struggling to store the pass/fail result of my test in a string that I can output.
I've discovered a way to do this however it relies on the following:-
The user code must be in separate test
This separate test must exist in a sibling test case to the one your main test is in
Both this test case and the case containing your main test must both be part of a parent test case
For example:
Parent TC
.....-AddUser TC
.........-MAIN TEST
.....-AddUser FailCheck
.........-USER CODE
You can then set your AddUser TC to 'Continue with sibling on fail'
The user code is as follows:
public static void Output()
{
string result = "";
ITestCase iCase = TestSuite.Current.GetTestCase("Add_User_Test"); // The name of your Test Case
if(iCase.Status == Ranorex.Core.Reporting.ActivityStatus.Failed){
result = "Failed"; }
if(iCase.Status == Ranorex.Core.Reporting.ActivityStatus.Success){
result = "Passed"; }
int testrunID = 79;
using (StreamWriter writer =
new StreamWriter("testresult.txt"))
{
writer.WriteLine(testrunID);
writer.WriteLine(result);
}
}
This will take the testrunID (specific to each test case) and the result of the test and output it to a text file.
The idea is then to read in the file with a custom java application I've developed and push the data into a test case management program such as QA Complete which can mark tests as Passed/Failed automatically
You can run the test suite directly using the TestSuiteRunner.Run() method. This will allow you to look at the return value of that directly and output pass or failure based on the return value.
http://www.ranorex.com/Documentation/Ranorex/html/M_Ranorex_Core_Testing_TestSuiteRunner_Run.htm
if(TestSuiteRunner.Run(typeof({testSuiteclass}),{Command Line Arguments})==0)
{
File.WriteLine("success");
}
else
{
File.WriteLine("failure");
}

How to run multiple lua scripts through a single lua script even if one script fails

dofile("x/y/m.lua")
dofile("x/y/p.lua")
if m.lua fails due to some issue , p.lua will not run at all, please give me some resolution that i can run both files even if the first one fails and have logs for both
Try
function dofile(name)
local f,err=loadfile(name)
if f==nil then print(err) end
local ok,err=pcall(f)
if not ok then print(err) end
end
Use pcall to catch Lua errors, possibly like this:
local success, result = pcall(dofile, "foo.lua")
If success is false, the function failed and the error message will be in result. If success is true, the return values of dofile will be in result. You can add additional result variables. For example:
local success, result1, result2, result3 = pcall(dofile, "foo.lua")

Customizing jUnit AssertFailure Error messages - combined with slf4j logging

I am new to jUnit and Selenium. Currently, we are doing a POC in our project for evaluating the tools' suitability.
One of the key requirements for us would be use friendly messages in case of assertion failures and verify Failures. The objective is to have those analyzed by manual testers by keeping those user intuitive.
I am trying out SLF4J for logging INFO messages for user friendly messages.
The challenge I am facing is that - when assertions fail, how to pass a custom message instead of jUnit default message?
For example, I want to get rid of the following default assertion failure message
expected "Health A-Z" to match glob "Health A-ZZ" (had transformed the glob into regexp "Health A-ZZ"
and frame it as
The title of the Menu Item doesn't match the expected value "Health A-ZZ". The actual value seen is "Health A-Z"
Question1 - Is there a way I override the default message with what I want?
Question2 - Can I pass variable parameters to the message and make it a dynamic message?
Sample Code:
try {
assertEquals("Health A-ZZ", selenium.getText("//div[#id='topnav']/ul/li[2]/a"));
logger.info("SUCCESS: Menu Item {} title verification Passed. EXPECTED : A-Z and Actual: {}",mainCounter, selenium.getText("//div[#id='topnav']/ul/li[2]/a"));
}
catch (AssertionError e) {
logger.error("FAILURE: Menu Item {} title verification Failed. EXPECTED : A-ZZ and Actual: {}",mainCounter, selenium.getText("//div[#id='topnav']/ul/li[2]/a"));
}
I get the assertFailure message printed out twice.. One with the error message in the catch block above and the other, the default junit assertfailre message like the one I mentioned above I wanted to get rid of.
Thanks in Advance.
Regards,
Prakash
You can use the Junit assert function.
assertEquals(message, expected, actual)
This will print the message that has been given in the message String in case of failure.
You can also pass String variable to the "message".

Resources