Addition of repository to ease testing and maintainability

This commit is contained in:
Dane Everitt 2017-07-01 15:29:49 -05:00
parent 2f4ec64f2a
commit 5c3dc60d1e
No known key found for this signature in database
GPG key ID: EEA66103B3D71F53
22 changed files with 617 additions and 853 deletions

View file

@ -1,236 +0,0 @@
<?php
/**
* Pterodactyl - Panel
* Copyright (c) 2015 - 2017 Dane Everitt <dane@daneeveritt.com>.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
namespace Tests\Feature\Services;
use Tests\TestCase;
use Pterodactyl\Models\Node;
use Pterodactyl\Models\Location;
use Pterodactyl\Services\LocationService;
use Pterodactyl\Exceptions\DisplayException;
use Pterodactyl\Exceptions\Model\DataValidationException;
class LocationServiceTest extends TestCase
{
/**
* @var \Pterodactyl\Services\LocationService
*/
protected $service;
/**
* Setup the test instance.
*/
public function setUp()
{
parent::setUp();
$this->service = $this->app->make(LocationService::class);
}
/**
* Test that a new location can be successfully added to the database.
*/
public function testShouldCreateANewLocation()
{
$data = [
'long' => 'Long Name',
'short' => 'short',
];
$response = $this->service->create($data);
$this->assertInstanceOf(Location::class, $response);
$this->assertEquals($data['long'], $response->long);
$this->assertEquals($data['short'], $response->short);
$this->assertDatabaseHas('locations', [
'short' => $data['short'],
'long' => $data['long'],
]);
}
/**
* Test that a validation error is thrown if a required field is missing.
*/
public function testShouldFailToCreateLocationIfMissingParameter()
{
$data = ['long' => 'Long Name'];
try {
$this->service->create($data);
} catch (DataValidationException $ex) {
$this->assertInstanceOf(DataValidationException::class, $ex);
$bag = $ex->getMessageBag()->messages();
$this->assertArraySubset(['short' => [0]], $bag);
$this->assertEquals('The short field is required.', $bag['short'][0]);
}
}
/**
* Test that a validation error is thrown if the short code provided is already in use.
*/
// public function testShouldFailToCreateLocationIfShortCodeIsAlreadyInUse()
// {
// factory(Location::class)->create(['short' => 'inuse']);
// $data = [
// 'long' => 'Long Name',
// 'short' => 'inuse',
// ];
//
// try {
// $this->service->create($data);
// } catch (\Exception $ex) {
// $this->assertInstanceOf(DataValidationException::class, $ex);
//
// $bag = $ex->getMessageBag()->messages();
// $this->assertArraySubset(['short' => [0]], $bag);
// $this->assertEquals('The short has already been taken.', $bag['short'][0]);
// }
// }
/**
* Test that a validation error is thrown if the short code is too long.
*/
public function testShouldFailToCreateLocationIfShortCodeIsTooLong()
{
$data = [
'long' => 'Long Name',
'short' => str_random(200),
];
try {
$this->service->create($data);
} catch (\Exception $ex) {
$this->assertInstanceOf(DataValidationException::class, $ex);
$bag = $ex->getMessageBag()->messages();
$this->assertArraySubset(['short' => [0]], $bag);
$this->assertEquals('The short must be between 1 and 60 characters.', $bag['short'][0]);
}
}
/**
* Test that updating a model returns the updated data in a persisted form.
*/
// public function testShouldUpdateLocationModelInDatabase()
// {
// $location = factory(Location::class)->create();
// $data = ['short' => 'test_short'];
//
// $model = $this->service->update($location->id, $data);
//
// $this->assertInstanceOf(Location::class, $model);
// $this->assertEquals($data['short'], $model->short);
// $this->assertNotEquals($model->short, $location->short);
// $this->assertEquals($location->long, $model->long);
// $this->assertDatabaseHas('locations', [
// 'short' => $data['short'],
// 'long' => $location->long,
// ]);
// }
/**
* Test that passing the same short-code into the update function as the model
* is currently using will not throw a validation exception.
*/
// public function testShouldUpdateModelWithoutErrorWhenValidatingShortCodeIsUnique()
// {
// $location = factory(Location::class)->create();
// $data = ['short' => $location->short];
//
// $model = $this->service->update($location->id, $data);
//
// $this->assertInstanceOf(Location::class, $model);
// $this->assertEquals($model->short, $location->short);
//
// // Timestamps don't change if no data is modified.
// $this->assertEquals($model->updated_at, $location->updated_at);
// }
/**
* Test that passing invalid data to the update method will throw a validation
* exception.
*
* @expectedException \Watson\Validating\ValidationException
*/
// public function testShouldNotUpdateModelIfPassedDataIsInvalid()
// {
// $location = factory(Location::class)->create();
// $data = ['short' => str_random(200)];
//
// $this->service->update($location->id, $data);
// }
/**
* Test that an invalid model exception is thrown if a model doesn't exist.
*
* @expectedException \Illuminate\Database\Eloquent\ModelNotFoundException
*/
public function testShouldThrowExceptionIfInvalidModelIdIsProvided()
{
$this->service->update(0, []);
}
/*
* Test that a location can be deleted normally when no nodes are attached.
*/
// public function testShouldDeleteExistingLocation()
// {
// $location = factory(Location::class)->create();
//
// $this->assertDatabaseHas('locations', [
// 'id' => $location->id,
// ]);
//
// $model = $this->service->delete($location);
//
// $this->assertTrue($model);
// $this->assertDatabaseMissing('locations', [
// 'id' => $location->id,
// ]);
// }
/*
* Test that a location cannot be deleted if a node is attached to it.
*
* @expectedException \Pterodactyl\Exceptions\DisplayException
*/
// public function testShouldFailToDeleteExistingLocationWithAttachedNodes()
// {
// $location = factory(Location::class)->create();
// $node = factory(Node::class)->create(['location_id' => $location->id]);
//
// $this->assertDatabaseHas('locations', ['id' => $location->id]);
// $this->assertDatabaseHas('nodes', ['id' => $node->id]);
//
// try {
// $this->service->delete($location->id);
// } catch (\Exception $ex) {
// $this->assertInstanceOf(DisplayException::class, $ex);
// $this->assertNotEmpty($ex->getMessage());
//
// throw $ex;
// }
// }
}

View file

@ -1,140 +0,0 @@
<?php
/**
* Pterodactyl - Panel
* Copyright (c) 2015 - 2017 Dane Everitt <dane@daneeveritt.com>.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
namespace Tests\Feature\Services;
use Tests\TestCase;
use Pterodactyl\Models\User;
use Pterodactyl\Services\UserService;
use Illuminate\Support\Facades\Notification;
use Pterodactyl\Notifications\AccountCreated;
class UserServiceTest extends TestCase
{
protected $service;
public function setUp()
{
parent::setUp();
$this->service = $this->app->make(UserService::class);
}
public function testShouldReturnNewUserWithValidData()
{
Notification::fake();
$user = $this->service->create([
'email' => 'test_account@example.com',
'username' => 'test_account',
'password' => 'test_password',
'name_first' => 'Test',
'name_last' => 'Account',
'root_admin' => false,
]);
$this->assertNotNull($user->uuid);
$this->assertNotEquals($user->password, 'test_password');
$this->assertDatabaseHas('users', [
'id' => $user->id,
'uuid' => $user->uuid,
'email' => 'test_account@example.com',
'root_admin' => '0',
]);
Notification::assertSentTo($user, AccountCreated::class, function ($notification) use ($user) {
$this->assertEquals($user->username, $notification->user->username);
$this->assertNull($notification->user->token);
return true;
});
}
public function testShouldReturnNewUserWithPasswordTokenIfNoPasswordProvided()
{
Notification::fake();
$user = $this->service->create([
'email' => 'test_account@example.com',
'username' => 'test_account',
'name_first' => 'Test',
'name_last' => 'Account',
'root_admin' => false,
]);
$this->assertNotNull($user->uuid);
$this->assertNotNull($user->password);
$this->assertDatabaseHas('users', [
'id' => $user->id,
'uuid' => $user->uuid,
'email' => 'test_account@example.com',
'root_admin' => '0',
]);
Notification::assertSentTo($user, AccountCreated::class, function ($notification) use ($user) {
$this->assertEquals($user->username, $notification->user->username);
$this->assertNotNull($notification->user->token);
$this->assertDatabaseHas('password_resets', [
'email' => $user->email,
]);
return true;
});
}
public function testShouldUpdateUserModelInDatabase()
{
// $user = factory(User::class)->create();
//
// $response = $this->service->update($user, [
// 'email' => 'test_change@example.com',
// 'password' => 'test_password',
// ]);
//
// $this->assertInstanceOf(User::class, $response);
// $this->assertEquals('test_change@example.com', $response->email);
// $this->assertNotEquals($response->password, 'test_password');
// $this->assertDatabaseHas('users', [
// 'id' => $user->id,
// 'email' => 'test_change@example.com',
// ]);
}
public function testShouldDeleteUserFromDatabase()
{
// $user = factory(User::class)->create();
// $service = $this->app->make(UserService::class);
//
// $response = $service->delete($user);
//
// $this->assertTrue($response);
// $this->assertDatabaseMissing('users', [
// 'id' => $user->id,
// 'uuid' => $user->uuid,
// ]);
}
}

View file

@ -2,15 +2,16 @@
namespace Tests;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Mockery as m;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
abstract class TestCase extends BaseTestCase
{
use CreatesApplication, DatabaseTransactions;
use CreatesApplication;
public function setUp()
{
parent::setUp();
m::close();
}
}

View file

@ -26,85 +26,177 @@ namespace Tests\Unit\Services;
use Mockery as m;
use Tests\TestCase;
use Pterodactyl\Models\User;
use Illuminate\Database\Connection;
use Pterodactyl\Services\UserService;
use Illuminate\Foundation\Application;
use Illuminate\Contracts\Hashing\Hasher;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Notifications\ChannelManager;
use Pterodactyl\Notifications\AccountCreated;
use Pterodactyl\Services\Helpers\TemporaryPasswordService;
use Pterodactyl\Contracts\Repository\UserRepositoryInterface;
class UserServiceTest extends TestCase
{
/**
* @var \Illuminate\Foundation\Application
*/
protected $appMock;
/**
* @var \Illuminate\Database\ConnectionInterface
*/
protected $database;
/**
* @var \Illuminate\Contracts\Hashing\Hasher
*/
protected $hasher;
protected $model;
/**
* @var \Illuminate\Notifications\ChannelManager
*/
protected $notification;
/**
* @var \Pterodactyl\Services\Helpers\TemporaryPasswordService
*/
protected $passwordService;
/**
* @var \Pterodactyl\Contracts\Repository\UserRepositoryInterface
*/
protected $repository;
/**
* @var \Pterodactyl\Services\UserService
*/
protected $service;
/**
* Setup tests.
*/
public function setUp()
{
parent::setUp();
$this->database = m::mock(Connection::class);
$this->appMock = m::mock(Application::class);
$this->database = m::mock(ConnectionInterface::class);
$this->hasher = m::mock(Hasher::class);
$this->notification = m::mock(ChannelManager::class);
$this->passwordService = m::mock(TemporaryPasswordService::class);
$this->model = m::mock(User::class);
$this->app->instance(AccountCreated::class, m::mock(AccountCreated::class));
$this->repository = m::mock(UserRepositoryInterface::class);
$this->service = new UserService(
$this->appMock,
$this->notification,
$this->database,
$this->hasher,
$this->passwordService,
$this->model
$this->repository
);
}
public function tearDown()
/**
* Test that a user is created when a password is passed.
*/
public function test_user_creation_with_password()
{
parent::tearDown();
m::close();
}
$user = (object) [
'name_first' => 'FirstName',
'username' => 'user_name',
];
public function testCreateFunction()
{
$data = ['password' => 'password'];
$this->hasher->shouldReceive('make')->with('raw-password')->once()->andReturn('enc-password');
$this->database->shouldReceive('beginTransaction')->withNoArgs()->once()->andReturnNull();
$this->hasher->shouldNotReceive('make');
$this->passwordService->shouldNotReceive('generateReset');
$this->repository->shouldReceive('create')->with(['password' => 'enc-password'])->once()->andReturn($user);
$this->database->shouldReceive('commit')->withNoArgs()->once()->andReturnNull();
$this->appMock->shouldReceive('makeWith')->with(AccountCreated::class, [
'user' => [
'name' => 'FirstName',
'username' => 'user_name',
'token' => null,
],
])->once()->andReturnNull();
$this->hasher->shouldReceive('make')->once()->with($data['password'])->andReturn('hashString');
$this->database->shouldReceive('transaction')->andReturnNull();
$this->notification->shouldReceive('send')->with($user, null)->once()->andReturnNull();
$this->model->shouldReceive('newInstance')->with(['password' => 'hashString'])->andReturnSelf();
$this->model->shouldReceive('save')->andReturn(true);
$this->model->shouldReceive('notify')->with(m::type(AccountCreated::class))->andReturnNull();
$this->model->shouldReceive('getAttribute')->andReturnSelf();
$response = $this->service->create($data);
$response = $this->service->create([
'password' => 'raw-password',
]);
$this->assertNotNull($response);
$this->assertInstanceOf(User::class, $response);
$this->assertEquals($user->username, $response->username);
$this->assertEquals($user->name_first, 'FirstName');
}
public function testCreateFunctionWithoutPassword()
/**
* Test that a user is created with a random password when no password is provided.
*/
public function test_user_creation_without_password()
{
$data = ['email' => 'user@example.com'];
$user = (object) [
'name_first' => 'FirstName',
'username' => 'user_name',
'email' => 'user@example.com',
];
$this->hasher->shouldNotReceive('make');
$this->model->shouldReceive('newInstance')->with($data)->andReturnSelf();
$this->database->shouldReceive('beginTransaction')->withNoArgs()->once()->andReturnNull();
$this->hasher->shouldReceive('make')->once()->andReturn('created-enc-password');
$this->passwordService->shouldReceive('generateReset')->with('user@example.com')->once()->andReturn('random-token');
$this->database->shouldReceive('transaction')->andReturn('authToken');
$this->hasher->shouldReceive('make')->andReturn('randomString');
$this->passwordService->shouldReceive('generateReset')->with($data['email'])->andReturn('authToken');
$this->model->shouldReceive('save')->withNoArgs()->andReturn(true);
$this->repository->shouldReceive('create')->with([
'password' => 'created-enc-password',
'email' => 'user@example.com',
])->once()->andReturn($user);
$this->model->shouldReceive('notify')->with(m::type(AccountCreated::class))->andReturnNull();
$this->model->shouldReceive('getAttribute')->andReturnSelf();
$this->database->shouldReceive('commit')->withNoArgs()->once()->andReturnNull();
$this->appMock->shouldReceive('makeWith')->with(AccountCreated::class, [
'user' => [
'name' => 'FirstName',
'username' => 'user_name',
'token' => 'random-token',
],
])->once()->andReturnNull();
$response = $this->service->create($data);
$this->notification->shouldReceive('send')->with($user, null)->once()->andReturnNull();
$response = $this->service->create([
'email' => 'user@example.com',
]);
$this->assertNotNull($response);
$this->assertInstanceOf(User::class, $response);
$this->assertEquals($user->username, $response->username);
$this->assertEquals($user->name_first, 'FirstName');
$this->assertEquals($user->email, $response->email);
}
/**
* Test that passing no password will not attempt any hashing.
*/
public function test_user_update_without_password()
{
$this->hasher->shouldNotReceive('make');
$this->repository->shouldReceive('update')->with(1, ['email' => 'new@example.com'])->once()->andReturnNull();
$response = $this->service->update(1, ['email' => 'new@example.com']);
$this->assertNull($response);
}
/**
* Test that passing a password will hash it before storage.
*/
public function test_user_update_with_password()
{
$this->hasher->shouldReceive('make')->with('password')->once()->andReturn('enc-password');
$this->repository->shouldReceive('update')->with(1, ['password' => 'enc-password'])->once()->andReturnNull();
$response = $this->service->update(1, ['password' => 'password']);
$this->assertNull($response);
}
}