Skip to content

Commit

Permalink
#47-fix-callable-plugin-name merge master
Browse files Browse the repository at this point in the history
  • Loading branch information
steinkel committed Aug 20, 2019
2 parents 2b76456 + d2a26fc commit e9524fc
Show file tree
Hide file tree
Showing 10 changed files with 267 additions and 139 deletions.
4 changes: 4 additions & 0 deletions .travis.yml
@@ -1,5 +1,9 @@
language: php

services:
- mysql
- postgresql

php:
- 5.6
- 7.0
Expand Down
4 changes: 3 additions & 1 deletion CHANGELOG.md
Expand Up @@ -3,7 +3,9 @@ Changelog

Releases
--------

* 4.0.2
* Renamed BaseTraitTest to BaseTestTrait with alias from previous name for backwards compatibility
* Deprecated BaseTraitTest you should use BaseTestTrait
* 4.0.1
* Add BaseTraitTest for permissions testing
* 4.0.0
Expand Down
2 changes: 1 addition & 1 deletion Docs/Documentation/Testing.md
Expand Up @@ -10,7 +10,7 @@ Create a new test class and extends to `IntegrationTestCase`
```php
class PermissionsTest extends IntegrationTestCase
{
use \CakeDC\Auth\Test\BaseTraitTest;
use \CakeDC\Auth\Test\BaseTestTrait;
}
```

Expand Down
2 changes: 1 addition & 1 deletion composer.json
Expand Up @@ -29,7 +29,7 @@
"cakephp/cakephp": "^3.7.0"
},
"require-dev": {
"phpunit/phpunit": "^6",
"phpunit/phpunit": "^5.7.14|^6.0",
"league/oauth2-facebook": "@stable",
"league/oauth2-instagram": "@stable",
"league/oauth2-google": "@stable",
Expand Down
119 changes: 119 additions & 0 deletions src/Test/BaseTestTrait.php
@@ -0,0 +1,119 @@
<?php
namespace CakeDC\Auth\Test;

use Cake\Console\ConsoleIo;
use Cake\Core\Configure;
use Cake\ORM\TableRegistry;

trait BaseTestTrait
{
/**
* Sets up the session as a logged in user for an user with id $id
*
* @param string $id User id.
* @return void
*/
public function loginAsUserId($id)
{
$data = TableRegistry::getTableLocator()
->get(Configure::read('Users.table', 'Users'))->get($id)->toArray();
$this->session(['Auth' => ['User' => $data]]);
}

/**
* Login as a username
*
* @param string $username The username to use.
* @return void
*/
public function loginAsUserName($username)
{
$data = TableRegistry::getTableLocator()
->get(Configure::read('Users.table', 'Users'))->findByUsername($username)->first()->toArray();
$this->session(['Auth' => ['User' => $data]]);
}

/**
* @return bool
*/
protected function _isVerboseOrDebug()
{
return !empty(array_intersect(['--debug', '--verbose', '-v'], $_SERVER['argv']));
}

/**
* Test permission of one $url when logged as a specific $username
*
* @param string $url The est url.
* @param string $username The test username.
* @param string $method The test request method, 'post' or 'get'.
* @param string $ajax The test request is ajax or not? 'ajax' for yes and 'no-ajax' if not.
* @param string $responseCode The expected response code.
* @param string $responseContains The expected value to contains in response. When expected response code 302 it
* will check for 'Location' header, otherwise will check body response.
* @throws \PHPUnit\Exception
*/
protected function _testPermissions($url, $username, $method, $ajax, $responseCode, $responseContains)
{
if ($this->_isVerboseOrDebug()) {
(new ConsoleIo())->info(__(
"\nUrl: {0} Username: {1} Method: {2} Ajax?: {3} Response Code: {4} Response Contains: {5} ",
$url,
$username,
$method,
$ajax,
$responseCode,
$responseContains
), 0);
}
$this->loginAsUserName($username);
if ($ajax === 'ajax') {
$_SERVER['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest';
}
if ($method === 'post') {
$this->enableCsrfToken();
$this->enableSecurityToken();
$this->post($url);
} else {
$this->get($url);
}
if ($responseCode === '200') {
$this->assertResponseOk();
} else {
$this->assertResponseCode((int)$responseCode);
}

if ($responseContains) {
$this->assertResponseContains($responseContains);
} else {
$this->assertEmpty((string)$this->_response->getBody());
}
}

/**
* Test permissions based on CSV file content, one test for each row.
*
* @param string $csv CSV name
*
* @return array
* @dataProvider provider
* @throws \PHPUnit\Exception
*/
public function testPermissions($csv)
{
$this->assertTrue(file_exists(TESTS . 'Provider' . DS . $csv));
$rows = array_map('str_getcsv', file(TESTS . 'Provider' . DS . $csv));
foreach ($rows as $row) {
if ($row[0][0] === '#') {
continue;
}
list($url, $username, $method, $ajax, $responseCode, $responseContains) = array_pad($row, 6, null);
$this->setUp();
$this->_testPermissions($url, $username, $method, $ajax, $responseCode, $responseContains);
$this->tearDown();
}
}
}

// @deprecated 4.0.2 Add backwards compatibility alias.
class_alias('CakeDC\Auth\Test\BaseTestTrait', 'CakeDC\Auth\Test\BaseTraitTest');
111 changes: 3 additions & 108 deletions src/Test/BaseTraitTest.php
@@ -1,109 +1,4 @@
<?php
namespace CakeDC\Auth\Test;

use Cake\Console\ConsoleIo;
use Cake\Core\Configure;
use Cake\ORM\TableRegistry;

trait BaseTraitTest
{
/**
* Sets up the session as a logged in user for an user with id $id
*
* @param $id
* @return void
*/
public function loginAsUserId($id)
{
$data = TableRegistry::getTableLocator()
->get(Configure::read('Users.table', 'Users'))->get($id)->toArray();
$this->session(['Auth' => ['User' => $data]]);
}

/**
* Login as a username
*
* @param $username
* @return void
*/
public function loginAsUserName($username)
{
$data = TableRegistry::getTableLocator()
->get(Configure::read('Users.table', 'Users'))->findByUsername($username)->first()->toArray();
$this->session(['Auth' => ['User' => $data]]);
}

/**
* @return bool
*/
protected function _isVerboseOrDebug()
{
return !empty(array_intersect(['--debug', '--verbose', '-v'], $_SERVER['argv']));
}

/**
* @param $url
* @param $username
* @param $method
* @param $ajax
* @param $responseCode
* @param $responseContains
* @throws \PHPUnit\Exception
*/
protected function _testPermissions($url, $username, $method, $ajax, $responseCode, $responseContains)
{
if ($this->_isVerboseOrDebug()) {
(new ConsoleIo())->info(__(
"\nUrl: {0} Username: {1} Method: {2} Ajax?: {3} Response Code: {4} Response Contains: {5} ",
$url,
$username,
$method,
$ajax,
$responseCode,
$responseContains
), 0);
}
$this->loginAsUserName($username);
if ($ajax === 'ajax') {
$_SERVER['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest';
}
if ($method === 'post') {
$this->enableCsrfToken();
$this->enableSecurityToken();
$this->post($url);
} else {
$this->get($url);
}
if ($responseCode === '200') {
$this->assertResponseOk();
} else {
$this->assertResponseCode((int)$responseCode);
}

if ($responseContains) {
$this->assertResponseContains($responseContains);
} else {
$this->assertEmpty((string)$this->_response->getBody());
}
}

/**
* @param $csv
* @return array
* @dataProvider provider
*/
public function testPermissions($csv)
{
$this->assertTrue(file_exists(TESTS . 'Provider' . DS . $csv));
$rows = array_map('str_getcsv', file(TESTS . 'Provider' . DS . $csv));
foreach ($rows as $row) {
if ($row[0][0] === '#') {
continue;
}
list($url, $username, $method, $ajax, $responseCode, $responseContains) = array_pad($row, 6, null);
$this->setUp();
$this->_testPermissions($url, $username, $method, $ajax, $responseCode, $responseContains);
$this->tearDown();
}
}
}
// @deprecated 4.0.2 Load new trait and alias
trait_exists('CakeDC\Auth\Test\BaseTestTrait');
deprecationWarning('Use CakeDC\Auth\Test\BaseTestTrait instead of CakeDC\Auth\Test\BaseTraitTest.');
8 changes: 5 additions & 3 deletions tests/TestCase/Authenticator/CookieAuthenticatorTest.php
Expand Up @@ -53,9 +53,11 @@ public function testPersistIdentity($setCookie, $field, array $post, array $sess
$identifiers = new IdentifierCollection([
'Authentication.Password'
]);
$request = ServerRequestFactory::fromGlobals(
['REQUEST_URI' => '/login']
);
$request = new \Cake\Http\ServerRequest();
$uri = new \Zend\Diactoros\Uri('/login');
$uri->base = null;
$request = $request->withUri($uri);

$request = $request->withParsedBody($post);
$request->getSession()->write('CookieAuth', $session);
$response = new Response();
Expand Down
28 changes: 16 additions & 12 deletions tests/TestCase/Authenticator/TwoFactorAuthenticatorTest.php
Expand Up @@ -26,10 +26,7 @@ class TwoFactorAuthenticatorTest extends TestCase
*/
public function testAuthenticateFailedNoData()
{
$request = ServerRequestFactory::fromGlobals(
['REQUEST_URI' => '/testpath'],
[]
);
$request = $this->requestWithTestPath();
$response = new Response();
$identifiers = new IdentifierCollection([
'Authentication.Password'
Expand All @@ -50,10 +47,8 @@ public function testAuthenticateFailedNoData()
*/
public function testAuthenticateFailedInvalidUrl()
{
$request = ServerRequestFactory::fromGlobals(
['REQUEST_URI' => '/testpath'],
[]
);
$request = $this->requestWithTestPath();

$request->getSession()->write(
TwoFactorAuthenticator::USER_SESSION_KEY,
new Entity([
Expand Down Expand Up @@ -82,10 +77,7 @@ public function testAuthenticateFailedInvalidUrl()
*/
public function testAuthenticate()
{
$request = ServerRequestFactory::fromGlobals(
['REQUEST_URI' => '/testpath'],
[]
);
$request = $this->requestWithTestPath();
$request->getSession()->write(
TwoFactorAuthenticator::USER_SESSION_KEY,
new Entity([
Expand All @@ -106,4 +98,16 @@ public function testAuthenticate()
$this->assertInstanceOf(Result::class, $result);
$this->assertEquals(Result::SUCCESS, $result->getStatus());
}

/**
* @return \Cake\Http\ServerRequest
*/
protected function requestWithTestPath()
{
$request = new \Cake\Http\ServerRequest();
$uri = new \Zend\Diactoros\Uri('/testpath');
$uri->base = null;

return $request->withUri($uri);
}
}
33 changes: 25 additions & 8 deletions tests/TestCase/Rbac/RbacTest.php
Expand Up @@ -14,8 +14,8 @@
use CakeDC\Auth\Rbac\Rbac;
use CakeDC\Auth\Rbac\Rules\Owner;
use Cake\Http\ServerRequest;
use Cake\Routing\Router;
use Cake\TestSuite\TestCase;
use Cake\Utility\Hash;
use Psr\Log\LogLevel;
use ReflectionClass;

Expand Down Expand Up @@ -1122,6 +1122,27 @@ function () {
//expected
true,
],
'named-route' => [
//permissions
[[
'plugin' => 'CakeDC/Users',
'controller' => 'Users',
'action' => '*',
'role' => 'admin',
]],
//user
[
'id' => 1,
'username' => 'luke',
'role' => 'admin',
],
//request
[
'_name' => 'testNamed',
],
//expected
true,
],
];
}

Expand Down Expand Up @@ -1285,14 +1306,10 @@ public function badPermissionProvider()
*/
protected function _requestFromArray($params)
{
$request = new ServerRequest();
$request = new ServerRequest(Router::url($params));
$params = Router::parseRequest($request);

return $request
->withParam('plugin', Hash::get($params, 'plugin'))
->withParam('controller', Hash::get($params, 'controller'))
->withParam('action', Hash::get($params, 'action'))
->withParam('prefix', Hash::get($params, 'prefix'))
->withParam('_ext', Hash::get($params, '_ext'));
return $request->withAttribute('params', $params);
}

public function testGetPermissions()
Expand Down

0 comments on commit e9524fc

Please sign in to comment.