Kotlin expression giving different results (runtime vs IDE Evaluate expression) - android-studio

val result: Boolean = aList.union(bList).any { it.something?.someOtherFlag == true }
I have two lists I need to join and check if any of the items has some flag set.
This has been giving me some bad results. During debugging:
the data before the line indicates result = true (true should be the right answer)
I get result = false by running the program
directly after the line, when I use the Evaluate expression tool, I get result = true
What is definitely NOT the problem is that there is NO change in the data in between.
Kotlin versions of my app/IDE plugin are different:
Kotlin Plugin: 203-1.5.0
App: 1.4.21
What I am looking for is an explanation: what can be the problem?

The union method returns a set that will keep only distinct elements, and it might discard different elements when running and when evaluating in debugger. I'm not sure how deterministic it's supposed to be, but the order could matter.
This could happen if equals() and/or hashCode() for your elements are defined without using something, or if equals()/hashCode() for something's class is defined without using someOtherFlag. How are these classes defined?
Note that for data classes, only the properties that are present in the primary constructor are taken into account for the generated equals and hashcode methods.

Related

Cypress test: is .contains() equivalent to should('contain')?

Is this: cy.get('[name=planSelect]').contains(dummyPlan)
equivalent to this: cy.get('[name=planSelect]').should('contain', dummyPlan)
And if so, which is preferred? The first is more of an implicit assertion, but it's shorter and cleaner to my mind.
Follow-up question: After looking around to see how best to select elements for e2e testing I found that the Cypress docs recommend using data-cy attributes. Is there a reason this would be better than just adding name attributes to the markup? Should name only be used for forms fields?
The result on your cypress test will be the same if the element with name=planSelect does not contain dummyPlan, that is, the test will fail at this point.
The difference between them is that in the first form, using contains(), you're actually trying to select an element, and the result of cy.get(...).contains() will yield this expected DOM element, allowing for further chaining of methods, like:
cy.get('[name=planSelect]').contains(dummyPlan).click();
In the second form you are making an explicit assertion to verify that dummyPlan exists within the other element, using the Chai chainer contain.
It is a subtle difference and the result is the same, but I would recommend you to use cy.get('[name=planSelect]').contains(dummyPlan) only in case you would like to chain some other method after contains, and use the second form if you want to explicitly assert that this element exists. Logically speaking, the first would represent a generic test failure (cypress tried to find an element that wasn't there) and the second represents an explicit assertion failure (element should contain dummyPlan but it does not).
As for your second question, name is a valid HTML attribute and using it for your tests can lead to confusion if the attribute is being used in its original function (to name input fields) or if the attribute is there just for testing purposes. I would recommend you to use cy-name as the documentation suggests because this way you avoid this ambiguity and make it clear that this attribute cy-name is only there for testing purposes.
Furhtermore, on some situations you might decide to strip all cy-name from your code before sending it to production (during the build process, using some webpack plugin, like string-replace-loader). You would not be able to do the same if using just name because you would also remove the required input name, if there was some inputs in your code.
Answer
.contains(selector, content) is the best selector; it retries
element selection AND allows text matching (not just <tag>
.class #id [attributes])
.should() is just an assertion and only the assertion is retried
(not the element selection)
.should('exist') is implied unless you specify your own -- this is how they allowed .should('not.exist')
Tangent
Browsers support XPath 1.0 which is a pretty cool but obscure way to make complex queries based on DOM tree traversal. There's a contains predicate function:
//*[ contains(normalize-space(.), 'The quick brown fox jumped over the lazy dog.') ]
[not(.//*[contains(normalize-space(.), 'The quick brown fox jumped over the lazy dog.') ])]
This searches from root of the document for any node that contains the text and doesn't contain a descendant node which contains the text.
You can test it in the console with the Chrome $x() shortcut or this polyfill (and helper):
getLowestDomNodesByText("The quick brown fox jumped over the lazy dog.")
function getLowestDomNodesByText (text) {
return x(`//*[contains(normalize-space(.), '${text}')][not(.//*[contains(normalize-space(.), '${text}') ])]`);
};
function x (expression) {
const results = new XPathEvaluator().evaluate(expression, document);
const nodes = [];
let node = null;
while (node = results.iterateNext()) {
nodes.push(node);
}
return nodes;
}
If you need even more performance, you can use a TreeWalker with NodeFilter.SHOW_TEXT as seen in this chrome extension I've worked on for a long time
I recommend to use contains after get then verify existence with should.
cy.get('[name=planSelect]').contains(dummyPlan, {matchCase: false}).should('exist')

How to express validity?

I am creating an Alloy model of the iCalendar data format.
An iCalendar file contains properties. There are a lot of codependencies among the properties. I want to see if anything breaks when a property is removed (i.e., when the property is constrained to zero occurrences).
I want to write an assert and have the Alloy Analyzer search for counterexamples, but I am struggling with how to write the assert. I want the assert to say something like this:
If property X is removed (i.e., property X is constrained to zero
occurrences), there are no instances that are invalid as a result of
removing X.
In pseudocode, I want this:
assert NoProblemFilteringX {
(no prop: X | prop in iCalendar.properties) => all instances are still valid
}
Would you provide some guidance on formulating the desired assert, please?
Suggestion:
Write your codependency checks in a predicate taking as parameter a
set of properties. The predicate holds iff the codependencies are satisfied amongst those properties given in parameter.
Rewrite your fact ensuring those codependencies so as to call this predicate with the set of all iCalendar properties as parameters.
Call this predicate in the assert while this time giving iCalendar.properties - X as parameter

Does groovy ignore the type of null values in method signatures?

To illustrate the following example I created a litte spock test (but it's about groovy itself, not spock):
void "some spock test"() {
given: String value = null
expect: someMethod(value) == 3
}
int someMethod(String s) {
return 3
}
int someMethod(Map s) {
return 5
}
There are two methods who's signatures only differ by the type of the given parameter. I thought that when I give it a null value that is explicitly typed as a string, the string-method will be called.
But that doesn't happen; the test fails, because the map-method is called! Why?
I guess groovy ignores the type and treats all nulls the same. There seems to be some kind of priority of types: When I use Object instead of Map as the parameter type of the wrong-method, its all the same, but when I for instance use Integer, the test succeeds.
But than again: If groovy really ignores the type of nulls, why can the following fix the original test:
expect: someMethod((String) value) == 3
If you read my answer to the question Tim already mentioned you will see that I talk there about runtime types. The static type plays normally no role in this. I also described there how the distance calculation is used and that for null the distance to Object is used to determine the best fitting method. What I did not mention is that you can force method selection by using a cast. Internally Groovy will use a wrapper for the object, that also transports the type. Then the transported type is used instead. But you surely understand, that this means a one additional object creation per method class, which is very inefficient. Thus it is not the standard. In the future Groovy maybe change to include that static type information, but this requires a change to the MOP as well. And that is difficult

Groovy difference between 'any' and 'find' methods

In groovy, there are two methods namely any and find method that can be used in Maps.
Both these methods will "search" for the content that we are interested in (that is, both any and find method return whether the element is in Map or not, that is they need to search).
But within this search how do they differ?
They actually do different things. find returns the actual element that was found whereas any produces a bool value. What makes this confusing for you is the groovy truth.
Any unset (null?) value will resolve to false
def x
assert !x
So if you are just checking for false, then the returned values from both methods will serve the same purpose, since essentially all objects have an implicit existential boolean value.
(!list.find{predicate}) <> (!list.any{predicate})
However :
( list.find{predicate}) >< (list.any{predicate})
If any does not exist in Groovy API and you want to add this feature to List metClass, any implementation will be :
java.util.List.metaClass.any={Closure c->
return delegate.find(c) != null
}
Find is more general than any

How to determine whether a dependency object implements a given dependency property (C# / WPF)

I am working with the classes in the System.Windows.Documents namespace, trying to write some generic code that will conditionally set the value of certain dependency properties, depending on whether these properties exist on a given class.
For example, the following method assigns an arbitrary value to the Padding property of the passed FrameworkContentElement:
void SetElementPadding(FrameworkContentElement element)
{
element.SetValue(Block.PaddingProperty, new Thickness(155d));
}
However, not all concrete implementations of FrameworkContentElement have a Padding property (Paragraph does but Span does not) so I would expect the property assignment to succeed for types that implement this property and to be silently ignored for types that do not.
But it seems that the above property assignment succeeds for instances of all derivatives of FrameworkContentElement, regardless of whether they implement the Padding property. I make this assumption because I have always been able to read back the assigned value.
I assume there is some flaw in the way I am assigning property values. What should I do to ensure that a given dependency property assignment is ignored by classes that do not implement that property?
Many thanks for your advice.
Tim
All classes that derive from Block have the Padding property. You may use the following modification:
void SetElementPadding(FrameworkContentElement element)
{
var block = element as Block;
if (block == null) return;
block.Padding = new Thickness(155d);
}
Even without this modification everything would still work for you because all you want is for Padding to be ignored by classes that do not support it. This is exactly what would happen. The fact that you can read out the value of a Padding dependency property on an instance that does not support it is probably by design but you shouldn't care. Block and derivatives would honor the value and all others would ignore it.

Resources