Unable to match exception instance in test case - scala

The following piece of code returns an instance of an exception if a configuration is missing
if (host == "" || redirectUrl == "" || successUrlParameter == "" || failUrlParameter == "") {
//checktest-USerTransactionService-finishResetCredentials-return exception if host configuration parameters are present
(Some(MissingConfigurationException()),errorRediectedUrl,None)
} else {...}
I am testing this and am matching it like the following
errorThrown mustBe Some(MissingConfigurationException())
The test case fails even though the values seem to be equal.
Expected :Some(utilities.MissingConfigurationException: Server Error. Missing Configuration)
Actual :Some(utilities.MissingConfigurationException: Server Error. Missing Configuration)
how should I compare the expected vs actual value?

Exceptions are compared by reference not by value. Thus, two identical values will always be different, unless they are the same instance.
So, you have to check for the class of the instance.
However. Scalatest provides a better syntax for checking for class and using options.
errorThrown.value shouldBe a [MissingConfigurationException]
Reference:
https://www.scalatest.org/user_guide/using_matchers#checkingAnObjectsClass
https://www.scalatest.org/user_guide/using_OptionValues

Related

EF Dynamic Filters delegate expression

We are using EF Dynamic filters (ASP.NET MVC 5 app)
https://entityframework-dynamicfilters.net/overview
The filter below is working, but set only once.
builder.Filter("IMultiOrganization", (IMultOrganization d) => ((d.TenantId == GlobalAppVariables.IssuerId) && (d.IsShared == true)) || ((d.IsShared == false && d.AzureObjIdentifier == GlobalAppVariables.AzureObjIdentifier)));
The variables 'IssuerId' and 'AzureObjIdentifier' are dynamic session variables, those are changing all the time. This causes problems and I would like the filter to use those variables straight from the session.
According to the documentation this is caused because this filer isn't a delegate expression.
Filters can be defined on a specific entity class or an interface by providing a specific value, e.g. an IsDeleted filter created on an ISoftDelete interface which will automatically filter those entities by applying the condition "IsDeleted==false".
Filter values can also be provided via a delegate/expression instead of a specific value which allows you to change the parameter value dynamically. For example, a filter can be created on the UserID and provided per HTTP request.
We also use delegate filters what indeed is working fine.
builder.EnableFilter("IMultiTenant", () => GlobalAppVariables.AzureObjIdentifier != null || GlobalAppVariables.IssuerId != Guid.Empty);
But I can't get the first filter work as a delegate expression and need a bit help on that.
I found the solution by using parameters within the filter.
First of all I changed the filter which now supports parameters.
builder.Filter("IMultiOrganization", (IMultiOrganization d, Guid tenantId, string azureId) => (d.TenantId == tenantId && d.IsShared == true) || (d.AzureObjIdentifier == azureId && d.IsShared == false), GlobalAppVariables.IssuerId, GlobalAppVariables.AzureObjIdentifier);
Then I call method below in the db context constructor
private void SetMultiOrganizationFilterParams()
{
if (GetFilterEnabled("IMultiOrganization"))
{
this.SetFilterScopedParameterValue("IMultiOrganization", "azureId", GlobalAppVariables.AzureObjIdentifier);
this.SetFilterScopedParameterValue("IMultiOrganization", "tenantId", GlobalAppVariables.IssuerId);
}
}
Source: https://github.com/zzzprojects/EntityFramework.DynamicFilters#changing-filter-parameter-values

building a function to add checks to amazon deequ framework

Using amazon deequ library I'm trying to build a function that takes 3 parameters, the check object, a string telling what constraint needs to be run and another string that provides the constraint criteria. I have a bunch of checks that I want to read from a mysql table. My intention is to iterate through all the checks that I get from the mysql table and build a check object using the function I described above and run the checks on a source dataframe
Here a example of the amazon deequ
https://towardsdatascience.com/automated-data-quality-testing-at-scale-using-apache-spark-93bb1e2c5cd0
So the function call looks something like this,
var _check = build_check_object_function(check_object, "hasSize", "10000")
This function should add a new hasSize check to the check_object and return that.
The part where I'm stuck is how to translate the hasSize string to the hasSize function.
var _check = Check(CheckLevel.Error, "Data Validation Check")
val listOfFunctions= _check.getClass.getMethods.filter(!_.getName().contains('$'))
for (function <- listOfFunctions) {
if( function.getName().toLowerCase().contains(row(2).asInstanceOf[String].toLowerCase())) {
_check = _check.function(row(3))
}else{
println("Not a match")}
}
Here is the error that I'm getting
<console>:38: error: value function is not a member of com.amazon.deequ.checks.Check
if( function.getName().toLowerCase().contains(row(2).asInstanceOf[String].toLowerCase())) {_check = _check.function(row(3))
You can either use runtime reflection or build a thin translation layer between your database and the deequ declarations.
I would suggest you go with translating database constraint/check strings explicitly to deequ declarations, e.g.:
if (constraint == "hasSize") {
// as Constraint
Constraint.sizeConstraint(_ <= 10)
// as Check
Check(CheckLevel.Error, "name").hasSize(_ <= 10)
}

Preconditions checknotnull annotations produce null warnings

The following line
final ProgramObject data =
Preconditions.checkNotNull(datas.get(name), TEMPLATE, name);
gives a warning in android studio
Warning:(291, 44) Argument 'data.get(name)' might be null
When looking at the source code of Preconditions:
#CanIgnoreReturnValue
#NonNullDecl
public static <T extends Object> T checkNotNull(
#NonNullDecl T obj, #NullableDecl String errorMessageTemplate, #NullableDecl Object p1) {
if (obj == null) {
throw new NullPointerException(lenientFormat(errorMessageTemplate, p1));
}
return obj;
}
It looks like the first parameter is not allowed to get null.
Here is the PR connected to it:
https://github.com/google/guava/commit/a890c444e55973384d1370b56afe1a02e7db9c3c
So i wonder:
Is there something in Android studio which i did not configure well
Is this a bug in guava?
Obviously if i make a null check i suspect that the parameter can be null
The intent of Preconditions.checkNotNull is that it should only be used on variables that you believe can never be null -- and you want to make sure your belief is correct, and have an exception thrown if you were wrong.
Guava's setup is working as it intended. It may be appropriate for you to suppress the warning.

How to compute a value from the src::branch property when definition a build step

I must compute a value for a build step based on the src::branch property and based on the available documentation this only seems to be possible by defining custom renderables.
I created a custom renderable defined as follows:
#implementer(IRenderable)
class DetermineVersion(object):
def getRenderingFor(self, props):
if props.hasProperty("src::branch"):
return "--version=" + props['src::branch'].lower().replace("tag/", "")
else:
raise Exception("The property 'branch' (tag/version) must be set")
and used it as follows in a build step:
f.addStep(steps.ShellCommand(
name="create_tag",
command=["python", "createTag.py", DetermineVersion()],
))
Unfortunately this does not seem to work as expected and regardless of the fact of the "branch" property is set or not, I always see the exception thrown by my getRenderingFor function.
I used wrong property name src::branch instead of branch:
This works as expected:
#implementer(IRenderable)
class DetermineVersion(object):
def getRenderingFor(self, props):
if props.hasProperty("branch"):
return "--version=" + props['branch'].lower().replace("tag/", "")
else:
raise Exception("The property 'branch' (tag/version) must be set")

Early return from a Scala constructor

I am writing the constructor for my "main" class. The first thing it does is call a method to use commons-cli to parse the command line. If the parseOptions method returns false, an error has occurred, and the constructor should exit.
I tried writing the following code
if (!parseOptions(args)) return
but the compiler complains that I have a "Return statement outside method definition".
Short of calling System.exit(1) or inverting the boolean (and putting all of the rest of my logic inside the if statement, is there any way to return "early" from a constructor?
I suppose I could have the parseOptions method throw an IllegalArgumentException and catch that in my Main object.
Thanks.
Dont try to do a early/premature return, this makes your code harder more complex, since the side effects of the return can be hard to understand. Instead use a exception to signal that something is wrong.
You can use require in the constructor. This doesn't return. But it seems like throwing an exception actually fits his situation better.
As in:
class MyTest(
private var myValue: Int ){
require(myValue > 0) // Connected to constructor
}
defined class MyTest
scala> val x = new MyTest(10)
x: MyTest = MyTest#49ff4282
scala> val y = new MyTest(-10)
java.lang.IllegalArgumentException: requirement failed
at scala.Predef$.require(Predef.scala:133)
is there any way to return "early" from a constructor
No. But in your case it sounds like bad design, anyway.
If the parseOptions method returns false, an error has occurred
In this case the constructor should throw an exception, not return normally.
A constructor should always either complete fully, or abort (throw an exception). Anything else leaves your object "half constructed" and thus impossible to reason about.
If in your case, the object is valid even if parseOptions failed, then you can change the condition and continue:
if (parseOptions(args)) {
// rest of constructor
}