Search code examples
phpsymfonyfunctional-testing

Symfony2: Retrieving user credentials from test config


I'm doing some functional testing in my Symfony2 app, and want to assert controller security by checking that only users with appropriate roles can access my controller actions. I've set up two users with different roles, that authenticate with basic credentials:

providers:
    in_memory:
        users:
            basic: { password: basic, roles: ROLE_BASIC }
            admin: { password: admin, roles: ROLE_ADMIN }

I don't want to hard-code these users into every test I write (I'll be writing lots). Ideally I'd like to get the details of the users I've defined in my config from the container. Is this possible? I.E. instead of doing this:

$crawler = $client->request('GET', '/inventory/index', array(), array(), 
    array(
        'PHP_AUTH_USER' => 'admin',
        'PHP_AUTH_PW' => 'admin'
    ));

I want to do this:

// Get the user details from the container
$users = $this->container->get('something');
$user = $users['admin'];

$crawler = $client->request('GET', '/inventory/index', array(), array(), 
    array(
        'PHP_AUTH_USER' => $user->getUsername(),
        'PHP_AUTH_PW' => $user->getPassword()
    ));

Solution

  • Take a look at the LiipFunctionalTestBundle, specifically the base WebTestCase class, here.

    I haven't used this bundle personally, but it claims to account for authentication from within your test cases.

    Update

    You might be better off loading the Users as fixtures rather than in-memory . If you aren't using a database, setup LiipFunctionalTestBundle to use SQLite. This way you can have access to each User from within your tests.

    Also, although probably not recommended, you can alter liip_functional_test.authentication any time by doing something like this:

    $this->getContainer()->setParameter('liip_functional_test.authentication', 'new_value');