How to use `Which` in FluentAssertions? - fluent-assertions

I'm using fluent assertions and I have this test:
result.Should().NotBeNull();
result.Link.Should().Equals("https://someinvoiceurl.com");
which works fine but when I try this
result.Should().NotBeNull().Which.Link.Equals("https://someinvoiceurl.com");
I got this error
'AndConstraint<ObjectAssertions>' does not contain a definition for 'Which' and no accessible extension method 'Which' accepting a first argument of type 'AndConstraint<ObjectAssertions>' could be found (are you missing a using directive or an assembly reference?)
What I'm doing wrong?

The problem here is that .NotBeNull() is not generic (it is an extension on ObjectAssertions rather than GenericObjectAssertions), so it can't chain the type information to later calls.
I think this is a flaw in the library design, personally, but it is easily worked around by substituting .NotBeNull() with .BeOfType<T>() as so:
result.Should().BeOfType<ThingWithLink>() // assertion fails if `result` is null
.Which.Link.Should().Be("https://someinvoiceurl.com");
Of course, if you assert on your ThingWithLink type a lot, it could be worth writing a custom assertion so that you can be "more fluent":
result.Should().BeOfType<ThingWithLink>()
.And.HaveLink("https://someinvoiceurl.com");
If you need something more ad-hoc, you can always just use .BeEquivalentTo() to do structural comparison:
result.Should().NotBeNull()
.And.BeEquivalentTo(new { Link = "https://someinvoiceurl.com" }); // ignores all members on `result` except for `result.Link`

Related

How can one invoke the non-extension `run` function (the one without scope / "object reference") in environments where there is an object scope?

Example:
data class T(val flag: Boolean) {
constructor(n: Int) : this(run {
// Some computation here...
<Boolean result>
})
}
In this example, the custom constructor needs to run some computation in order to determine which value to pass to the primary constructor, but the compiler does not accept the run, citing Cannot access 'run' before superclass constructor has been called, which, if I understand correctly, means instead of interpreting it as the non-extension run (the variant with no object reference in https://kotlinlang.org/docs/reference/scope-functions.html#function-selection), it construes it as a call to this.run (the variant with an object reference in the above table) - which is invalid as the object has not completely instantiated yet.
What can I do in order to let the compiler know I mean the run function which is not an extension method and doesn't take a scope?
Clarification: I am interested in an answer to the question as asked, not in a workaround.
I can think of several workarounds - ways to rewrite this code in a way that works as intended without calling run: extracting the code to a function; rewriting it as a (possibly highly nested) let expression; removing the run and invoking the lambda (with () after it) instead (funnily enough, IntelliJ IDEA tags that as Redundant lambda creation and suggests to Inline the body, which reinstates the non-compiling run). But the question is not how to rewrite this without using run - it's how to make run work in this context.
A good answer should do one of the following things:
Explain how to instruct the compiler to call a function rather than an extension method when a name is overloaded, in general; or
Explain how to do that specifically for run; or
Explain that (and ideally also why) it is not possible to do (ideally with supporting references); or
Explain what I got wrong, in case I got something wrong and the whole question is irrelevant (e.g. if my analysis is incorrect, and the problem is something other than the compiler construing the call to run as this.run).
If someone has a neat workaround not mentioned above they're welcome to post it in a comment - not as an answer.
In case it matters: I'm using multi-platform Kotlin 1.4.20.
Kotlin favors the receiver overload if it is in scope. The solution is to use the fully qualified name of the non-receiver function:
kotlin.run { //...
The specification is explained here.
Another option when the overloads are not in the same package is to use import renaming, but that won't work in this case since both run functions are in the same package.

BeEquivalentTo doesn't work with Anonymous Methods

I have an xunit test using FA 4.19.3. I have recently upgraded to 5.3.0 without too many issues, except for some Object graph comparisons.
Old test:
var result = await MyClass.GetResultAsync();
result.ShouldBeEquivalentTo(new
{
StatusCode = 200,
Exception = (Exception)null
}, options => options.Excluding(o => o.Context));
But because the expectation is an anonymous method the Excluding errors with:
'IMemberInfo' does not contain a definition for 'Context' and no
extension method 'Context' accepting a first argument of type
'IMemberInfo' could be found (are you missing a using directive or an
assembly reference?)
I even tried defining the generic:
result.Should().BeEquivalentTo<MyResult>(
but this did not help.
How can I continue to use the anon method as I have many tests using this method.
Actually, we introduced some pretty big breaking changes in 5.0 just to make it possible to compare against an anonymous type. The Excluding method is there to exclude properties from the expectation. Since your expectation doesn't have an Context object, FA will complain about that. Check out https://www.continuousimprover.com/2018/02/fluent-assertions-50-best-unit-test.html#redefining-equivalency

What is indirect object notation, why is it bad, and how does one avoid it?

The title pretty much sums it up, but here's the long version anyway.
After posting a small snippet of perl code, I was told to avoid indirect object notation, "as it has several side effects". The comment referenced this particular line:
my $some_object = new Some::Module(FIELD => 'value');
As this is how I've always done it, in an effort to get with the times I therefore ask:
What's so bad about it? (specifically)
What are the potential (presumably negative) side effects?
How should that line be rewritten?
I was about to ask the commenter, but to me this is worthy of its own post.
The main problem is that it's ambiguous. Does
my $some_object = new Some::Module(FIELD => 'value');
mean to call the new method in the Some::Module package, or does it mean to call the new function in the current package with the result of calling the Module function in the Some package with the given parameters?
i.e, it could be parsed as:
# method call
my $some_object = Some::Module->new(FIELD => 'value');
# or function call
my $some_object = new(Some::Module(FIELD => 'value'));
The alternative is to use the explicit method call notation Some::Module->new(...).
Normally, the parser guesses correctly, but the best practice is to avoid the ambiguity.
What's so bad about it?
The problems with Indirect Method Notation are avoidable, but it's far easier to tell people to avoid Indirect Method Notation.
The main problem it's very easy to call the wrong function by accident. Take the following code, for example:
package Widget;
sub new { ... }
sub foo { ... }
sub bar { ... }
sub method {
...;
my $o = new SubWidget;
...;
}
1;
In that code, new SubWidget is expected to mean
SubWidget->new()
Instead, it actually means
new("SubWidget")
That said, using strict will catch most of these instances of this error. Were use strict; to be added to the above snippet, the following error would be produced:
Bareword "SubWidget" not allowed while "strict subs" in use at Widget.pm line 11.
That said, there are cases where using strict would not catch the error. They primarily involve the use of parens around the arguments of the method call (e.g. new SubWidget($x)).
So that means
Using Indirect Object Notation without parens can result in odd error messages.
Using Indirect Object Notation with parens can result in the wrong code being called.
The former is bearable, and the latter is avoidable. But rather than telling people "avoid using parens around the arguments of method calls using Indirect Method Notation", we simply tell people "avoid using Indirect Method Notation". It's just too fragile.
There's another issue. It's not just using Indirect Object Notation that's a problem, it's supporting it in Perl. The existence of the feature causes multiple problems. Primarily,
It causes some syntax errors to result in very odd/misleading error messages because the code appeared to be using ION when it wasn't.
It prevents useful features from being implemented since they clash with valid ION syntax.
On the plus side, using no indirect; helps the first problem.
How should that line be rewritten?
The correct way to write the method call is the following:
my $some_object = Some::Module->new(FIELD => 'value');
That said, even this syntax is ambiguous. It will first check if a function named Some::Module exists. But that's so very unlikely that very few people protect themselves from such problems. If you wanted to protect yourself, you could use the following:
my $some_object = Some::Module::->new(FIELD => 'value');
As to how to avoid it: There's a CPAN module that forbids the notation, acting like a pragma module:
no indirect;
http://metacpan.org/pod/indirect
The commenter just wanted to see Some::Module->new(FIELD => 'value'); as the constructor.
Perl can use indirect object syntax for other bare words that look like they might be methods, but nowadays the perlobj documentation suggests not to use it.
The general problem with it is that code written this way is ambiguous and exercises Perl's parser to test the namespace to e.g. check when you write method Namespace whether Namespace::method exists.

Dart serialization error: Invalid reference

I have a wrapped Serialization class from the serialization package in my class MySerialization. In the constroctor of MySerialization, I add a bunch of rules. Consumer classes have seperate instances of the wrapper MySerialization class to (de)serialize objects.
This setup, with a seperate instance of MySerialization in consumer classes throws an error in the Reference class constructor:
Reference(this.parent, this.ruleNumber, this.objectNumber) {
if (ruleNumber == null || objectNumber == null) {
throw new SerializationException("Invalid Reference");
}
if (parent.rules.length < ruleNumber) {
throw new SerializationException("Invalid Reference"); // <---- here
}
}
thus spawnes error in the console
Breaking on exception: SerializationException(Invalid Reference)
This means a rule cannot be found which is referenced. The starnge thing howver is, that I have the same rules applied in all Serialization instances through the MySerialization wrapper.
I tried serializing with only one instance of MySerialization. This does not spawn the error. When I debug in DartEditor, I get the <optimized out> message in the debugger window.
I have CustomRule subclasses rules defined. The behavior does not change when I enable/disabled these CustomRules
What cuases the invalid reference, and how to solve & workaround this error?
Dart Editor version 1.5.3.release (STABLE)
Dart SDK version 1.5.3
It's difficult to answer without a little more detail on your setup. However, I'm going to guess that you're using the default setup in which it will automatically generate instances of BasicRule when it encounters a class that it doesn't know about, and those are added to the list of rules. Your other instance doesn't know about those, so it fails.
You can try examining (or just printing) the list of rules in your original serialization after it has written out the objects and see if this is the case.
To fix this, you would need to write rules for the other objects that are being serialized and weren't in your original list. Or you could use the "selfDescribing" option, in which case it will send the rules that were used along with the original. But that won't work if you have hard-coded custom rules which it can't serialize.

I cannot understand how Dart Editor analyze source code

Dart Editor version 1.2.0.release (STABLE). Dart SDK version 1.2.0.
This source code produces runtime exception.
void main() {
test(new Base());
}
void test(Child child) {
}
class Base {
}
class Child extends Base {
}
I assumed that the analyzer generates something like this.
The argument type 'Base' cannot be assigned to the parameter type 'Child'
But I can only detect this error at runtime when occurred this exception (post factum).
Unhandled exception:
type 'Base' is not a subtype of type 'Child' of 'child'.
The analyzer is following the language specification here.
It only warns if a the static type of the argument expression is not assignable to the type of function the parameter.
In Dart, expressions of one type is assignable to variables of another type if either type is a subtype of the other.
That is not a safe type check. It does not find all possible errors. On the other hand, it also does not disallow some correct uses like:
Base foo = new Child();
void action(Child c) { ... }
action(foo); // Perfectly correct code at runtime.
Other languages have safe assignment checks, but they also prevent some correct programs. You then have to add (unsafe/runtime checked) cast operators to tell the compiler that you know the program is safe. It's a trade-off where Dart has chosen to be permissive and avoid most casts.
Let's try to be polite and answer the question without any prejudice.
I think I understand what you expected and here my angle on what the error means:
You are invoking the method with the argument of type Base
The method is expecting an argument of type Child
The Child is not equal to the Base, neither is a subtype of it (as a fact it is the Child that is a subtype of the Base)
It is working as expected as it makes only sense to provide object of the expected type (or it's subtypes - specialisations).
Update:
After reading again your question I realised that you are pointing out that editor is not finding the type problem. I assume this is due to the point that Dart programs are dynamic and hence certain checks are not done before the runtime.
Hope it helps ;-)