Cakephp controller testing - how to check actions requiring authorization?

The name says a lot about everything. I would like to check for example. UsersController::admin_index(), but in order for the user to get permission to access this location, it is required, therefore, when I run the test, it sends me to the login page, and even when I enter the system manully, the tests are not performed.

So, how can I get cake to skip authorization without editing the actual authorization code?

btw, in case this helps, my code is testAdminIndex()as follows:

function testAdminIndex() {     
    $result = $this->testAction('/admin/users/index');      
    debug($result); 
}
+3
source share
2 answers

Here is an article that covers the topic here ...

http://mark-story.com/posts/view/testing-cakephp-controllers-the-hard-way

- "testAction" . :

function testAdminEdit() {
    $this->Posts->Session->write('Auth.User', array(
        'id' => 1,
        'username' => 'markstory',
    ));
    $this->Posts->data = array(
        'Post' => array(
            'id' => 2,
            'title' => 'Best article Evar!',
            'body' => 'some text',
        ),
        'Tag' => array(
            'Tag' => array(1,2,3),
        )
    );
    $this->Posts->params = Router::parse('/admin/posts/edit/2');
    $this->Posts->beforeFilter();
    $this->Posts->Component->startup($this->Posts);
    $this->Posts->admin_edit();
}
+5

cakephp.

http://book.cakephp.org/3.0/en/development/testing.html#testing-actions-that-require-authentication

, AuthComponent, , AuthComponent . IntegrationTestCase. , ArticleController, , , :

public function testAddUnauthenticatedFails()
{
    // No session data set.
    $this->get('/articles/add');

    $this->assertRedirect(['controller' => 'Users', 'action' => 'login']);
}

public function testAddAuthenticated()
{
    // Set session data
    $this->session([
        'Auth' => [
            'User' => [
                'id' => 1,
                'username' => 'testing',
                // other keys.
            ]
        ]
    ]);
    $this->get('/articles/add');

    $this->assertResponseOk();
    // Other assertions.
}

// Set session data
$this->session(['Auth.User.id' => 1]);

, :

public function testDisplay()
{
 $this->session(['Auth.User.id' => 1, 'Auth.User.role' => 'admin']);

    $this->get('/pages/home');
    $this->assertResponseOk();
    $this->assertResponseContains('CakePHP');
    $this->assertResponseContains('<html>');
}
+1

Source: https://habr.com/ru/post/1793911/


All Articles