Add test for mock model policy resolution and refactor `getRepository…#306
Add test for mock model policy resolution and refactor `getRepository…#306mirko-pagliai wants to merge 1 commit intocakephp:3.xfrom
Conversation
…Policy` method in OrmResolver
|
Instead it does not work, because in any case that Do something like: if ($table instanceof MockObject){
}It would be a bad idea, because it would require phpunit as a dependence in production. Instead, this works: if (!str_ends_with($class, 'Table') && str_ends_with(get_parent_class($table) ?: '', 'Table')) {
$class = get_parent_class($table);
}But obviously as an idea is definitely bad, I say it first. Perhaps this implementation is not possible in a simple way. |
|
In the end, the idea was good (allowing to solve the policy also starting from mocks). However, in hindsight the implementation, in addition to being complex, would be very "questionable". After writing some code, I would say that the best solution is to intervene with a mock of the query (rather than the table). So (I'm posting the solution, in case it's useful to someone else, even though the purpose of a repository is not to offer a solution, but as an alternative to PR) class NotificationsTablePolicy {
public function scopeIndex(User $Identity, SelectQuery $Query): SelectQuery
{
return $Query->find('InnerJoinWithUserId', $Identity->id);
}
} public function testScopeIndex(): void
{
$Query = Mockery::mock(SelectQuery::class . '[find]', [$this->fetchTable('Notifications')]);
$Query
->shouldReceive('find')
->once()
->with('InnerJoinWithUserId', 1)
->andReturnSelf();
$this->User->applyScope('index', $Query);
}
PR to be considered resolved as closed. |
This was not possible:
because it caused:
In other words, using a mock, with
get_class($table)it was impossible to determine the corresponding policy.Using
$table->getAlias(). 'Table'not only is the thing simplifies, but the mock of a model can be used.I noticed that this can be useful for testing the Policy Scopes, not being able to use the actual model.
Example:
A mock can now be used and expect that the
find()method is called with those arguments.