How to mock interface method to return the parameter value using closures - closures

Sometimes it happens that we need to mock some method of the interface just to work and we do not really care what it will return, we just need to ensure it is called.
There is an approach to set
->expects(static::once())->method('someMethod')->willReturn('dumbValue');
But it is often necessary to see in the test with which parameter it was called, then we need to use
->expects(static::once())->method('someMethod')->with(static::equalTo('paramvalue'))->willReturn('dumbValue');
It gets longer and longer.
Is there an approach to return the parameter value that is given to the function mocked in willReturn() method?
It would be so simple to test the output with data provider then

We can use closures to process the callback.
$this->translator = $this->createMock(TranslatorInterface::class);
$this->translator->method('translate')->will(
$this->returnCallback(
function ($msgid) {
return (string)$msgid;
}
)
);
Also, we can return not only parameter value but any variable value, generated before:
$variable = 'hello'
$this->returnCallback(
function ($msgid) use $variable {
return $msgid . $variable;
}
)
and the assert will look like:
static::assertEquals(
'key',
$this->translator->translate('key');
);
static::assertEquals(
'some text and translated '. 'key',
'some text and translated ' . $this->translator->translate('key');
);

Related

Chaining method calls

According to official Dart documentation, it is mentioned that:
Chaining method calls
a..b = true..c = 5;
Cascade used for chaining access to methods and other members.
Equivalent:
a.b = true; a.c = 5;
Can someone explain the meaning of the above lines?
Consider user as an instace of following class:
class User {
int age;
String firstName;
String lastName;
}
Now you can update data in user as following:
user.age = 5;
user.firstName = 'John';
user.lastName = 'Doe';
but if you use chaining access as described in the documentation.
Then it will look something like this:
user..age = 5
..firstName = 'John'
..lastName = 'Doe';
Note: sequence of assignment of the properties does not matter, but it might be of importance while calling functions or methods like this.
Just a simple & random example:
painter..computeLayout()
..initializePaint()
..render();
above is same as:
painter.computeLayout();
painter.initializePaint();
painter.render();
in the above example all of the methods were called on painter object/instance but the sequence here must be followed as without paint or layout the render will not work.
Cascades
To perform a sequence of operations on the same object, use cascades (..). We’ve all seen an expression like this:
myObject.someMethod()
It invokes someMethod() on myObject, and the result of the expression is the return value of someMethod().
Here’s the same expression with a cascade:
myObject..someMethod()
Although it still invokes someMethod() on myObject, the result of the expression isn’t the return value — it’s a reference to myObject! Using cascades, you can chain together operations that would otherwise require separate statements. For example, consider this code:
var button = querySelector('#confirm');
button.text = 'Confirm';
button.classes.add('important');
button.onClick.listen((e) => window.alert('Confirmed!'));
With cascades, the code becomes much shorter, and you don’t need the button variable:
querySelector('#confirm')
..text = 'Confirm'
..classes.add('important')
..onClick.listen((e) => window.alert('Confirmed!'));

Calling a function with two same arguments, but setting the second while calling

I am calling a function that expects two arguments. I use the same variable, but at the second argument I set this variable to another thing.
See below:
https://dartpad.dartlang.org/2156442de07f56d90b430bc67f3461ac
void main() {
String s = 'oi';
aa(s, s = 'oi2');
}
void aa(String buf, String buf2){
print('$buf, $buf2');
}
This will print "oi, oi2".
I want this to happen. I am using a modified notification within properties, like:
set title(String n) {
this.modified('title', _title, _title = n);
}
However, I wonder if this can be seen as a bug or it is expected.
thanks, Joe
s is a String which are passed by value, not by reference.
aa(s, s = 'oi2');
evaluates the first parameter s, which is 'oi'
next s = 'oi2' is evaluated, which means s gets 'oi2' assigned
then the result of s = 'oi2' (which is 'oi2') is passed as 2nd parameter.
After aa(s, s = 'oi2'); s has the value oi2.
See also https://gist.github.com/floitschG/b278ada0316dca96e78c1498d15a2bb9
Evaluation order of arguments is left-to-right, so you can rely on the first argument's value being found by evaluation s to "ii", and then second argument's value is the value of the assignment s = 'oi2 - which evaluates to "oi2" (and not, technically, by reading the variable, it just happens that the variable is written to with the same value before the function is called).
It is expected - if any implementation does something else, it's broken.

Validator\Db\RecordExists with multiple columns

ZF2 docs show the following example in terms of using Db\RecordExists validator with multiple columns.
$email = 'user#example.com';
$clause = $dbAdapter->quoteIdentifier('email') . ' = ' . $dbAdapter->quoteValue($email);
$validator = new Zend\Validator\Db\RecordExists(
array(
'table' => 'users',
'field' => 'username',
'adapter' => $dbAdapter,
'exclude' => $clause
)
);
if ($validator->isValid($username)) {
// username appears to be valid
} else {
// username is invalid; print the reason
$messages = $validator->getMessages();
foreach ($messages as $message) {
echo "$message\n";
}
}
I’ve tried this using my own Select object containing a more complex where condition. However, isValid() must be called with a value parameter.
In the example above $username is passed to isValid(). But there seems to be no according field definition.
I tried calling isValid() with an empty string, but this does not produce the desired result, since Zend\Validator\Db\AbstractDb::query() always adds the value to the statement:
$parameters = $statement->getParameterContainer();
$parameters['where1'] = $value;
If I remove the seconds line above, my validator produces the expected results.
Can someone elaborate on how to use RecordExists with the where conditions in my custom Select object? And only those?
The best way to do this is probably by making your own validator that extends one of Zend Framework's, because it doesn't seem like the (No)RecordExists classes were meant to handle multiple fields (I'd be happy to be proven wrong, because it'd be easier if they did).
Since, as you discovered, $parameters['where1'] is overridden with $value, you can deal with this by making sure $value represents what the value of the first where should be. In the case of using a custom $select, $value will replace the value in the first where clause.
Here's a hacky example of using RecordExists with a custom select and multiple where conditions:
$select = new Select();
$select->from('some_table')
->where->equalTo('first_field', 'value1') // this gets overridden
->and->equalTo('second_field', 'value2')
;
$validator = new RecordExists($select);
$validator->setAdapter($someAdapter);
// this overrides value1, but since isValid requires a string,
// the redundantly supplied value allows it to work as expected
$validator->isValid('value1');
The above produces the following query:
SELECT `some_table`.* FROM `some_table` WHERE `first_field` = 'value1' AND `second_field` = 'value2'
...which results in isValid returning true if there was a result.

how to use equalTo method in IOS program

I have a question with iOS block ;
in MASConstraint.h ( a iOS third-party library )
have a method define :
- (MASConstraint * (^)(id attr))equalTo ;
I cannot find the parameter with the method ,
but I can see many people use it with :
[subViews mas_makeConstraints:^(MASConstraintMaker *make) {
make.edges.equalTo(self.view);
}];
I don't understand it ,because I think the method (equalTo method) have not formal parameters.
but why the code make.edges.equalTo(self.view) is true ???
I need you help and thanks very mush .
(MASConstraint * (^)(id attr))equalTo is a function pointer definition, the return value is MASConstraint, and it takes one parameter, which is a 'id' object, could represent any object type, called attr
So equalTo is variable, you could use it like a function, so for make.edges.equalTo(self.view), the parameter is self.view, and equalTo returns MASConstraint object
The method (equalTo method) do have formal parameters,it takes one parameter named attr, and the parameter is a 'id' object.
As the format of block is very hard to remember,I personally like using this website (http://fuckingblocksyntax.com) to help me with the format of block. The name is easier to remember than the block syntax itself:
http://fuckingblocksyntax.com
and if you can't load URLs with bad words in them you can use this mirror: http://goshdarnblocksyntax.com
List of Block Declaration Syntaxes
Throughout, let
return_type be the type of object/primitive/etc. you'd like to return (commonly void)
blockName be the variable name of the block you're creating
var_type be the type object/primitive/etc. you'd like to pass as an argument (leave blank for no parameters)
varName be the variable name of the given parameter
And remember that you can create as many parameters as you'd like.
Blocks as Variables
Possibly the most common for of declaration.
return_type (^blockName)(var_type) = ^return_type (var_type varName)
{
// ...
};
Blocks as Properties
Much like declaring blocks as variables, however subtly different.
#property (copy) return_type (^blockName) (var_type);
Blocks as Parameters
Note that this is distinct from "Blocks as Arguments"; in this instance, you're declaring a method that wants a block argument.
- (void)yourMethod:(return_type (^)(var_type))blockName;
Blocks as Arguments
Note that this is distinct from "Blocks as Parameters"; in this instance, you're calling a method that wants a block argument with an anonymous block. If you have already declared a block variable, it is sufficient to pass the variable name as the argument.
[someObject doSomethingWithBlock: ^return_type (var_type varName)
{
//...
}];
Anonymous Block
This is functionally an anonymous block, however the syntax for assigning blocks to variables is simply to set the variable equal to an anonymous block.
^return_type (var_type varName)
{
//...
};
typedef Block
This allows you to set up a short name that can be referenced just like any other class name during the declaration of blocks.
typedef return_type (^blockName)(var_type);
To then later use blockName instead of the standard block declaration syntax, simply substitute.
Inline Block
This is arguably a less useful utilization of blocks, but may have its place nonetheless. An inline block is an anonymous block called immediately after instantiation.
^return_type (var_type varName)
{
//...
}(var);
Inline blocks are primarily useful for scope offsetting, and are roughly equivalent to simple brace-delimited chunks of code.
{
//...
}
Recursive Blocks
This allows you to call a block from itself, creating a loop that can be used during callbacks and GCD calls. This instantiation method is free of retain cycles in ARC.
__block return_type (^blockName)(var_type) = [^return_type (var_type varName)
{
if (returnCondition)
{
blockName = nil;
return;
}
// ...
} copy];
blockName(varValue);
Returning Blocks
A method can return a block,
- (return_type(^)(var_type))methodName
{
// ...
}
as can a function, if a bit strangely.
return_type (^FunctionName())(var_type)
{
// ...
}
Addendums
If I've missed anything, please let me know in comments, and I'll research/add them.
Oh, and in Swift...
blockName = (varName: var_type) -> (return_type)
It's almost like it's a language feature.

Why is this Groovy closure not returning the value that I expect?

In a Grails application, I am trying to prevent the creation of cycles in a directed graph. The user is able to assign a parent to a node, but no node should be its own parent's ancestor. I have written a simple setup function that calls checkLineageForTarget, which is the recursive function that does the heavy lifting:
boolean checkLineageForTarget(Integer target, Collection<Node>stillToProcess){
// true means that this is a safe addition
// false means that this addition creates a cycle
boolean retVal = stillToProcess.each {
Collection<Node> itsParents = getParentNodes(it)
if (it.id == target){
println("found a loop on " + target);
return false; // loop detected!
}
if (itsParents.empty){ return true; } // end of the line
return checkLineageForTarget(target, itsParents)
}
// at this point, retVal is always true, even when the "found a loop [...]" condition is met
return retVal;
}
This "works," in that it prints the "found a loop [...]" message, but outside of the closure, retVal is true, the calling function attempts to add the new parent/child relationship, and my stack runneth over.
What is my misunderstanding?
The each method returns the same collection it was invoked on, so retVal is probably not the boolean "true", but is evaluated as "truthly" (as it is a collection, it would mean it's not empty).
If you want to check a condition for every element in a collection, you might use every.
boolean checkLineageForTarget(Integer target, Collection<Node>stillToProcess){
stillToProcess.every { node ->
node.id != target && checkLineageForTarget(target, getParentNodes(node))
}
}
Note that I didn't need check the .empty condition on the parent nodes collection because that will be filtered by the recursive call to checkLineageForTarget (i.e. calling .every on an empty collection always returns true). Also, because of the short-circuiting of the && operator, the iteration stops as soon as node.id == target :)
.each appears to return the Object being looped over when it is done. You are assign this to a boolean and it is being coerced to true. You probably want to use .every for your task. It returns true only if each iteration returns true and it will stop looping when it hits the first false. You can find more information in the groovy docs.
When you return inside a Closure, it's like returning inside a method call within the method - it's local to that scope and has no impact on the real method the closure is being called in. In this case you can use one of the other approaches suggested (e.g. every) or use a regular for loop since it works the same as the Groovy each (i.e. it's null-safe and supports but doesn't require types) but you can break out of the loop or return and since you're in a real for loop it will return from the method:
boolean checkLineageForTarget(Integer target, Collection<Node>stillToProcess){
for (Node node in stillToProcess) {
Collection<Node> itsParents = getParentNodes(node)
...
}
...
}

Resources