Skip to content

Instantly share code, notes, and snippets.

@JannieT
Last active June 24, 2018 16:41
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JannieT/9659047 to your computer and use it in GitHub Desktop.
Save JannieT/9659047 to your computer and use it in GitHub Desktop.
Unit tests with oauth2-server-laravel
<?php
class MockRequest implements League\OAuth2\Server\Util\RequestInterface
{
public static function buildFromGlobals()
{
}
public function __construct(array $get = array(), array $post = array(), array $cookies = array(), array $files = array(), array $server = array(), $headers = array())
{
$this->get = $get;
$this->post = $post;
$this->cookies = $cookies;
$this->files = $files;
$this->server = $server;
$this->headers = $headers;
}
public function get($index = null)
{
return array_key_exists($index, $this->get) ? $this->get[$index] : null;
}
public function post($index = null)
{
return array_key_exists($index, $this->post) ? $this->post[$index] : null;
}
public function cookie($index = null)
{
return array_key_exists($index, $this->cookies) ? $this->cookies[$index] : null;
}
public function file($index = null)
{
return array_key_exists($index, $this->files) ? $this->files[$index] : null;
}
public function server($index = null)
{
return array_key_exists($index, $this->server) ? $this->server[$index] : null;
}
public function header($index = null)
{
return array_key_exists($index, $this->headers) ? $this->headers[$index] : null;
}
/**
* Convenient factory method
*/
public static function newRequest($verb, $parameters)
{
$server = array("REQUEST_METHOD" => $verb);
$empty = array();
if ($verb == 'GET')
{
return new MockRequest($parameters, $empty, $empty, $empty, $server,
$empty);
}
// POST
return new MockRequest($empty, $parameters, $empty, $empty, $server,
$empty);
}
}
/* End of app/models/MockRequest.php file */
<?php
class CreateCircleTest extends TestCase
{
public function setUp()
{
parent::setUp();
$this->prepareTheDatabase();
Route::enableFilters();
}
public function testTheEndpointIsProtected()
{
$this->areWeTalkingToStrangersOn('POST', '/api/circles/new');
}
public function testMissingParameters()
{
$this->checkForMissingParametersOn('POST', '/api/circles/new');
}
public function testWellFormedButNotValid()
{
$parameters = array('name' => ' '); // empty name
$this->prepAothServer('POST', $parameters);
$response = $this->call('POST', '/api/circles/new', $parameters);
$data = json_decode($response->getContent());
$this->assertFalse($response->isOk());
$this->assertResponseStatus(400); // Bad Request
$this->assertCount(1, $data->messages); // the client is told why
/* test that duplicate cicle names for the same user is rejected */
$duplicateName = "Friends";
$circle = Circle::newFrom($duplicateName, 1);
$parameters = array('name' => $duplicateName);
$this->prepAothServer('POST', $parameters);
$response = $this->call('POST', '/api/circles/new', $parameters);
$data = json_decode($response->getContent());
$this->assertFalse($response->isOk());
$this->assertResponseStatus(400); // Bad Request
$this->assertCount(1, $data->messages); // the client is told why
}
public function testAddValidNewCircle()
{
$newCircleName = 'Buddies';
$parameters = array('name' => $newCircleName);
$this->prepAothServer('POST', $parameters);
$response = $this->call('POST', '/api/circles/new', $parameters);
$data = json_decode($response->getContent());
/* test the response */
$this->assertTrue($response->isOk());
$this->assertResponseStatus(200);
$this->assertObjectHasAttribute('id', $data);
$this->assertEquals($newCircleName, $data->name);
/* test if the circle was actually added */
$owner = Circle::getCircleOwner($data->id);
$this->assertEquals(1, $owner);
}
}
/* end of file app/tests/CreateCircleTest.php */
<?php
class OAuthTestSeeder extends Illuminate\Database\Seeder
{
const ACCESS_TOKEN = 'NOSnsXqNDFHDGXrSe8B8e8LdNFNIqCGjcJvJa1jp';
const USER_NAME = 'Test User';
public function run()
{
$expire = new DateTime();
$expire->add(new DateInterval('P1M')); // one month
$now = date('Y-m-d H:i:s');
DB::table('users')->delete();
//password is password
$values = array(1, self::USER_NAME, 'test@paa.local', '5f4dcc3b5aa765d61d8327deb882cf99', 1, $now, $now);
DB::insert('INSERT INTO users (id, name, email, password, active, created_at, updated_at) values (?, ?, ?, ?, ?, ?, ?)', $values);
DB::table('oauth_clients')->delete();
$values = array(1, '226655d5e7bf98a0d31602557d23f194', 'browser', $now, $now);
DB::insert('insert into oauth_clients (id, secret, name, created_at, updated_at) values (?, ?, ?, ?, ?)', $values);
DB::table('oauth_scopes')->delete();
$values = array(1, 'basic', 'basic', 'normal user', $now, $now);
DB::insert('insert into oauth_scopes (id, scope, name, description, created_at, updated_at) values (?, ?, ?, ?,?,?)', $values);
DB::table('oauth_sessions')->delete();
$values = array(1, 1, 'user', 1, $now, $now);
DB::insert('INSERT INTO `oauth_sessions` (`id`, `client_id`, `owner_type`, `owner_id`, created_at, updated_at) VALUES (?, ?, ?, ?,?,?)', $values);
DB::table('oauth_session_access_tokens')->delete();
$values = array(1, 1, self::ACCESS_TOKEN , $expire->getTimestamp(), $now, $now);
DB::insert('INSERT INTO `oauth_session_access_tokens` (`id`, `session_id`, `access_token`, `access_token_expires`, created_at, updated_at) VALUES (?, ?, ?, ?,?,?)', $values);
DB::table('oauth_session_token_scopes')->delete();
$values = array(1, 1, 1, $now, $now);
DB::insert('INSERT INTO `oauth_session_token_scopes` (`id`, `session_access_token_id`, `scope_id`, created_at, updated_at) VALUES (?, ?, ?,?,?)', $values);
$this->command->info('OAuth tables seeded');
}
}
/* End of app/database/seeds/OAuthSeeder.php file */
<?php
class TestCase extends Illuminate\Foundation\Testing\TestCase
{
/**
* Creates the application.
*
* @return \Symfony\Component\HttpKernel\HttpKernelInterface
*/
public function createApplication()
{
$unitTesting = true;
$testEnvironment = 'testing';
return require __DIR__ . '/../../bootstrap/start.php';
}
/**
* Migrate the database
*
* This migrates our database into memory so we can test against a dataset in a known state
*/
protected function prepareTheDatabase()
{
Artisan::call("migrate");
/* vendor migrations */
$packages = array(
"lucadegasperi/oauth2-server-laravel",
);
foreach ($packages as $packageName)
{
Artisan::call("migrate",
array("--package" => $packageName, "--env" => "testing"));
}
/* do seeding */
$seeders = array(
"OAuthTestSeeder",
);
foreach ($seeders as $seedClass)
{
Artisan::call("db:seed", array("--class" => $seedClass));
}
}
protected function prepAothServer($verb, &$parameters)
{
/* sign the request */
$parameters['access_token'] = OAuthTestSeeder::ACCESS_TOKEN;
$request = MockRequest::newRequest($verb, $parameters);
ResourceServer::setRequest($request);
}
protected function areWeTalkingToStrangersOn($verb, $route)
{
$parameters = array('access_token' => "some wild hacker's guess");
$request = MockRequest::newRequest($verb, $parameters);
ResourceServer::setRequest($request);
$response = $this->call($verb, $route, $parameters);
$this->assertFalse($response->isOk());
$this->assertResponseStatus(401); // Bad Request
}
protected function checkForMissingParametersOn($verb, $route)
{
$parameters = array();
$this->prepAothServer($verb, $parameters);
$response = $this->call($verb, $route, $parameters);
$data = json_decode($response->getContent());
$this->assertFalse($response->isOk());
$this->assertResponseStatus(400); // Bad Request
$this->assertGreaterThanOrEqual(1, $data->messages); // the client is told why
}
}
@robert-dinu
Copy link

There are some errors in the seeder, the tables and columns does not match anymore for tests.

@arivasvera
Copy link

PHP Fatal error: Class 'MockRequest' not found in /Applications/MAMP/htdocs/l4/app/tests/TestCase.php on line 64

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment