CakePHP 3.8 - Error PHPUnit with DataProvider & Custom Authenticate

I need help with CakePHP 3.8 unit testing.

I have create a Custom Autheticate in CakePHP:

<?php
namespace Cake\Auth;

use Cake\Network\Exception\UnauthorizedException;
use Cake\Network\Request;
use Cake\Network\Response;

class BasicFixedAuthenticate extends BasicAuthenticate

{

    public function authenticate(Request $request, Response $response)

    {

        return $this->getUser($request);

    }

    public function getUser(Request $request)

    {

        $username = env('PHP_AUTH_USER');

        $pass = env('PHP_AUTH_PW');

        if ((empty($username) || $username === '') || (empty($pass) || $pass === '')) {

            return false;

        }

    

    if ($username == $this->_config['fields']['username'] && $pass == $this->_config['fields']['password']) {

        return ['User' => $username, 'Password' => $pass];

    }

    return false;

}

}

I use this on my Initialize() on my application:

    public function initialize()
        {
            $this->loadComponent('Auth', [
                'authenticate' => [
                    'BasicFixed' => [
                        'fields' => ['username' => env('bot_user'), 'password' => env('bot_pass')],
                        'userModel' => 'Users'
                    ],
                ],
                'storage' => 'Memory',
                'unauthorizedRedirect' => false
            ]); 
            
        }

So, everthing work fine! but in PHPUnit a have a problem using ProviderData:

On my testing, the first time of testing running (XPTO_1), works perfect, using ProviderData.

Example:

    public function WebhookProvider()
    {
        return [
            'XPTO_1' => [['action' => 'XPTO', 'placa' => 'ABC1234']],
            'XPTO_2' => [['action' => 'XPTO', 'placa' => 'ABC5555']],
     
        ];
    }
/**
 * @dataProvider WebhookProvider
 */
public function testWebhook($data)
{
    
    $_SERVER['PHP_AUTH_USER'] = 'bot_chat';
    $_SERVER['PHP_AUTH_PW'] = 'password';

    $this->post('bot_soe/webhook', $data);
    $response = $this->_response->body();
}

but on second test (XPTO_2) i got the error:

Fatal error: Cannot declare class Cake\Auth\BasicFixedAuthenticate, because the name is already in use in /home/sistemas/BtecApiCore/src/Auth/BasicFixedAuthenticate.php on line 32

Someone can help me with this problem?

Your BasicFixedAuthenticate class is in the Cake\Auth namespace; it should presumably be in App\Auth.

1 Like

Zuluru, thanks for help!

i have change the code like this:

<?php

namespace App\Auth;

use Cake\Network\Exception\UnauthorizedException;

use Cake\Network\Request;

use Cake\Network\Response;

use Cake\Auth\BasicAuthenticate;

class BasicFixedAuthenticate extends BasicAuthenticate

{
[...]
}

Now, the unit testing work fine with DataProvider.