Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock $_SERVER variables for laravel tests?

I'm using the shibboleth apache module for federated single sign-on. It sets the $_SERVER variable with a user's entitlements from active directory. In my laravel application, I use a custom authentication and user provider which leverages these entitlements for resource authorization.

My simplified user model has something like this:

public function isAdmin()
{
    return Request::server('entitlement') === 'admin';
}

However, I can't figure out how to test this because Request::server always returns nothing for that value.

public function setUp()
{
    $_SERVER['entitlement'] = 'admin';
    parent::setUp();
}

public function test_admin_something()
{
    $user = factory(User::class)->create();

    $response = $this
        ->actingAs($user)
        ->get('/admin/somewhere');

    var_dump($_SERVER['entitlement']);        // string(5) "admin"
    var_dump(Request::server('entitlement')); // NULL

    $response->assertStatus(200); // always fails 403
}

I've also tried setUpBeforeClass and checked all of the other server variables which appear to be ignored during testing in lieu of a custom crafted Request object. I also cannot mock the Request façade, per the documentation.

like image 840
Jeff Puckett Avatar asked Jun 19 '17 22:06

Jeff Puckett


1 Answers

Digging into the source code reveals an undocumented method withServerVariables

public function test_admin_something()
{
    $user = factory(User::class)->create();

    $response = $this
        ->withServerVariables(['entitlement' => 'admin'])
        ->actingAs($user)
        ->get('/admin/somewhere');

    $response->assertStatus(200);
}
like image 56
Jeff Puckett Avatar answered Oct 23 '22 01:10

Jeff Puckett