More test suite coverage

This commit is contained in:
Dane Everitt 2017-09-26 22:16:26 -05:00
parent 8908a758ca
commit 774c9680a3
No known key found for this signature in database
GPG key ID: EEA66103B3D71F53
14 changed files with 373 additions and 46 deletions

View file

@ -40,7 +40,7 @@ class RunTaskJob extends Job implements ShouldQueue
/**
* @var int
*/
protected $schedule;
public $schedule;
/**
* @var int

View file

@ -83,7 +83,7 @@ class DaemonKeyProviderService
['server_id', '=', $server],
]);
if (! $updateIfExpired || max($this->carbon->now()->diffInSeconds($key->expires_at, false), 0) > 0) {
if (! $updateIfExpired || $this->carbon->now()->diffInSeconds($key->expires_at, false) > 0) {
return $key->secret;
}

View file

@ -10,22 +10,22 @@
namespace Pterodactyl\Services\Helpers;
use Illuminate\Contracts\Hashing\Hasher;
use Illuminate\Database\DatabaseManager;
use Illuminate\Config\Repository as ConfigRepository;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Contracts\Config\Repository as ConfigRepository;
class TemporaryPasswordService
{
const HMAC_ALGO = 'sha256';
/**
* @var \Illuminate\Config\Repository
* @var \Illuminate\Contracts\Config\Repository
*/
protected $config;
/**
* @var \Illuminate\Database\DatabaseManager
* @var \Illuminate\Database\ConnectionInterface
*/
protected $database;
protected $connection;
/**
* @var \Illuminate\Contracts\Hashing\Hasher
@ -35,17 +35,17 @@ class TemporaryPasswordService
/**
* TemporaryPasswordService constructor.
*
* @param \Illuminate\Config\Repository $config
* @param \Illuminate\Database\DatabaseManager $database
* @param \Illuminate\Contracts\Hashing\Hasher $hasher
* @param \Illuminate\Contracts\Config\Repository $config
* @param \Illuminate\Database\ConnectionInterface $connection
* @param \Illuminate\Contracts\Hashing\Hasher $hasher
*/
public function __construct(
ConfigRepository $config,
DatabaseManager $database,
ConnectionInterface $connection,
Hasher $hasher
) {
$this->config = $config;
$this->database = $database;
$this->connection = $connection;
$this->hasher = $hasher;
}
@ -55,11 +55,11 @@ class TemporaryPasswordService
* @param string $email
* @return string
*/
public function generateReset($email)
public function handle($email)
{
$token = hash_hmac(self::HMAC_ALGO, str_random(40), $this->config->get('app.key'));
$this->database->table('password_resets')->insert([
$this->connection->table('password_resets')->insert([
'email' => $email,
'token' => $this->hasher->make($token),
]);

View file

@ -17,14 +17,24 @@ use Pterodactyl\Contracts\Repository\ScheduleRepositoryInterface;
class ProcessScheduleService
{
/**
* @var \Pterodactyl\Contracts\Repository\ScheduleRepositoryInterface
*/
protected $repository;
/**
* @var \Pterodactyl\Services\Schedules\Tasks\RunTaskService
*/
protected $runnerService;
public function __construct(
RunTaskService $runnerService,
ScheduleRepositoryInterface $repository
) {
/**
* ProcessScheduleService constructor.
*
* @param \Pterodactyl\Services\Schedules\Tasks\RunTaskService $runnerService
* @param \Pterodactyl\Contracts\Repository\ScheduleRepositoryInterface $repository
*/
public function __construct(RunTaskService $runnerService, ScheduleRepositoryInterface $repository)
{
$this->repository = $repository;
$this->runnerService = $runnerService;
}

View file

@ -10,16 +10,13 @@
namespace Pterodactyl\Services\Schedules\Tasks;
use Pterodactyl\Models\Task;
use Illuminate\Contracts\Bus\Dispatcher;
use Pterodactyl\Jobs\Schedule\RunTaskJob;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Pterodactyl\Contracts\Repository\TaskRepositoryInterface;
class RunTaskService
{
/**
* @var \Illuminate\Contracts\Bus\Dispatcher
*/
protected $dispatcher;
use DispatchesJobs;
/**
* @var \Pterodactyl\Contracts\Repository\TaskRepositoryInterface
@ -29,14 +26,10 @@ class RunTaskService
/**
* RunTaskService constructor.
*
* @param \Illuminate\Contracts\Bus\Dispatcher $dispatcher
* @param \Pterodactyl\Contracts\Repository\TaskRepositoryInterface $repository
*/
public function __construct(
Dispatcher $dispatcher,
TaskRepositoryInterface $repository
) {
$this->dispatcher = $dispatcher;
public function __construct(TaskRepositoryInterface $repository)
{
$this->repository = $repository;
}
@ -55,6 +48,6 @@ class RunTaskService
}
$this->repository->update($task->id, ['is_queued' => true]);
$this->dispatcher->dispatch((new RunTaskJob($task->id, $task->schedule_id))->delay($task->time_offset));
$this->dispatch((new RunTaskJob($task->id, $task->schedule_id))->delay($task->time_offset));
}
}

View file

@ -93,7 +93,7 @@ class UserCreationService
$this->connection->beginTransaction();
if (! isset($data['password']) || empty($data['password'])) {
$data['password'] = $this->hasher->make(str_random(30));
$token = $this->passwordService->generateReset($data['email']);
$token = $this->passwordService->handle($data['email']);
}
$user = $this->repository->create($data);

View file

@ -202,5 +202,6 @@ $factory->define(Pterodactyl\Models\DaemonKey::class, function (Faker\Generator
'server_id' => $faker->randomNumber(),
'user_id' => $faker->randomNumber(),
'secret' => 'i_' . str_random(40),
'expires_at' => \Carbon\Carbon::now()->addMinutes(10)->toDateTimeString(),
];
});

View file

@ -46,7 +46,9 @@ class DaemonKeyProviderServiceTest extends TestCase
{
parent::setUp();
$this->carbon = m::mock(Carbon::class);
$this->carbon = new Carbon();
$this->carbon->setTestNow();
$this->keyUpdateService = m::mock(DaemonKeyUpdateService::class);
$this->repository = m::mock(DaemonKeyRepositoryInterface::class);
@ -65,9 +67,6 @@ class DaemonKeyProviderServiceTest extends TestCase
['server_id', '=', $key->server_id],
])->once()->andReturn($key);
$this->carbon->shouldReceive('now')->withNoArgs()->once()->andReturnSelf();
$this->carbon->shouldReceive('diffInSeconds')->with($key->expires_at, false)->once()->andReturn(100);
$response = $this->service->handle($key->server_id, $key->user_id);
$this->assertNotEmpty($response);
$this->assertEquals($key->secret, $response);
@ -78,16 +77,15 @@ class DaemonKeyProviderServiceTest extends TestCase
*/
public function testExpiredKeyIsUpdated()
{
$key = factory(DaemonKey::class)->make();
$key = factory(DaemonKey::class)->make([
'expires_at' => $this->carbon->subHour(),
]);
$this->repository->shouldReceive('findFirstWhere')->with([
['user_id', '=', $key->user_id],
['server_id', '=', $key->server_id],
])->once()->andReturn($key);
$this->carbon->shouldReceive('now')->withNoArgs()->once()->andReturnSelf();
$this->carbon->shouldReceive('diffInSeconds')->with($key->expires_at, false)->once()->andReturn(-100);
$this->keyUpdateService->shouldReceive('handle')->with($key->id)->once()->andReturn(true);
$response = $this->service->handle($key->server_id, $key->user_id);
@ -100,7 +98,9 @@ class DaemonKeyProviderServiceTest extends TestCase
*/
public function testExpiredKeyIsNotUpdated()
{
$key = factory(DaemonKey::class)->make();
$key = factory(DaemonKey::class)->make([
'expires_at' => $this->carbon->subHour(),
]);
$this->repository->shouldReceive('findFirstWhere')->with([
['user_id', '=', $key->user_id],

View file

@ -0,0 +1,80 @@
<?php
/*
* Pterodactyl - Panel
* Copyright (c) 2015 - 2017 Dane Everitt <dane@daneeveritt.com>.
*
* This software is licensed under the terms of the MIT license.
* https://opensource.org/licenses/MIT
*/
namespace Tests\Unit\Services\Helpers;
use Mockery as m;
use Tests\TestCase;
use phpmock\phpunit\PHPMock;
use Illuminate\Contracts\Hashing\Hasher;
use Illuminate\Contracts\Config\Repository;
use Illuminate\Database\ConnectionInterface;
use Pterodactyl\Services\Helpers\TemporaryPasswordService;
class TemporaryPasswordServiceTest extends TestCase
{
use PHPMock;
/**
* @var \Illuminate\Contracts\Config\Repository|\Mockery\Mock
*/
protected $config;
/**
* @var \Illuminate\Database\ConnectionInterface|\Mockery\Mock
*/
protected $connection;
/**
* @var \Illuminate\Contracts\Hashing\Hasher|\Mockery\Mock
*/
protected $hasher;
/**
* @var \Pterodactyl\Services\Helpers\TemporaryPasswordService
*/
protected $service;
/**
* Setup tests.
*/
public function setUp()
{
parent::setUp();
$this->config = m::mock(Repository::class);
$this->connection = m::mock(ConnectionInterface::class);
$this->hasher = m::mock(Hasher::class);
$this->service = new TemporaryPasswordService($this->config, $this->connection, $this->hasher);
}
/**
* Test that a temporary password is stored and the token is returned.
*/
public function testTemporaryPasswordIsStored()
{
$this->getFunctionMock('\\Pterodactyl\\Services\\Helpers', 'str_random')
->expects($this->once())->with(40)->willReturn('random_string');
$this->config->shouldReceive('get')->with('app.key')->once()->andReturn('123456');
$token = hash_hmac(TemporaryPasswordService::HMAC_ALGO, 'random_string', '123456');
$this->hasher->shouldReceive('make')->with($token)->once()->andReturn('hashed_token');
$this->connection->shouldReceive('table')->with('password_resets')->once()->andReturnSelf();
$this->connection->shouldReceive('insert')->with([
'email' => 'test@example.com',
'token' => 'hashed_token',
])->once()->andReturnNull();
$response = $this->service->handle('test@example.com');
$this->assertNotEmpty($response);
$this->assertEquals($token, $response);
}
}

View file

@ -0,0 +1,137 @@
<?php
/*
* Pterodactyl - Panel
* Copyright (c) 2015 - 2017 Dane Everitt <dane@daneeveritt.com>.
*
* This software is licensed under the terms of the MIT license.
* https://opensource.org/licenses/MIT
*/
namespace Tests\Unit\Services\Schedules;
use Mockery as m;
use Tests\TestCase;
use Cron\CronExpression;
use Pterodactyl\Models\Task;
use Pterodactyl\Models\Schedule;
use Pterodactyl\Services\Schedules\Tasks\RunTaskService;
use Pterodactyl\Services\Schedules\ProcessScheduleService;
use Pterodactyl\Contracts\Repository\ScheduleRepositoryInterface;
class ProcessScheduleServiceTest extends TestCase
{
/**
* @var \Cron\CronExpression|\Mockery\Mock
*/
protected $cron;
/**
* @var \Pterodactyl\Contracts\Repository\ScheduleRepositoryInterface|\Mockery\Mock
*/
protected $repository;
/**
* @var \Pterodactyl\Services\Schedules\Tasks\RunTaskService|\Mockery\Mock
*/
protected $runnerService;
/**
* @var \Pterodactyl\Services\Schedules\ProcessScheduleService
*/
protected $service;
/**
* Setup tests.
*/
public function setUp()
{
parent::setUp();
$this->cron = m::mock('overload:' . CronExpression::class);
$this->repository = m::mock(ScheduleRepositoryInterface::class);
$this->runnerService = m::mock(RunTaskService::class);
$this->service = new ProcessScheduleService($this->runnerService, $this->repository);
}
/**
* Test that a schedule can be updated and first task set to run.
*/
public function testScheduleIsUpdatedAndRun()
{
$model = factory(Schedule::class)->make();
$model->setRelation('tasks', collect([$task = factory(Task::class)->make([
'sequence_id' => 1,
])]));
$formatted = sprintf('%s %s %s * %s *', $model->cron_minute, $model->cron_hour, $model->cron_day_of_month, $model->cron_day_of_week);
$this->cron->shouldReceive('factory')->with($formatted)->once()->andReturnSelf()
->shouldReceive('getNextRunDate')->withNoArgs()->once()->andReturn('00:00:00');
$this->repository->shouldReceive('update')->with($model->id, [
'is_processing' => true,
'next_run_at' => '00:00:00',
]);
$this->runnerService->shouldReceive('handle')->with($task)->once()->andReturnNull();
$this->service->handle($model);
$this->assertTrue(true);
}
/**
* Test that passing a schedule model without a tasks relation is handled.
*/
public function testScheduleModelWithoutTasksIsHandled()
{
$nonRelationModel = factory(Schedule::class)->make();
$model = clone $nonRelationModel;
$model->setRelation('tasks', collect([$task = factory(Task::class)->make([
'sequence_id' => 1,
])]));
$formatted = sprintf('%s %s %s * %s *', $model->cron_minute, $model->cron_hour, $model->cron_day_of_month, $model->cron_day_of_week);
$this->repository->shouldReceive('getScheduleWithTasks')->with($nonRelationModel->id)->once()->andReturn($model);
$this->cron->shouldReceive('factory')->with($formatted)->once()->andReturnSelf()
->shouldReceive('getNextRunDate')->withNoArgs()->once()->andReturn('00:00:00');
$this->repository->shouldReceive('update')->with($model->id, [
'is_processing' => true,
'next_run_at' => '00:00:00',
]);
$this->runnerService->shouldReceive('handle')->with($task)->once()->andReturnNull();
$this->service->handle($nonRelationModel);
$this->assertTrue(true);
}
/**
* Test that a task ID can be passed in place of the task model.
*/
public function testPassingScheduleIdInPlaceOfModelIsHandled()
{
$model = factory(Schedule::class)->make();
$model->setRelation('tasks', collect([$task = factory(Task::class)->make([
'sequence_id' => 1,
])]));
$formatted = sprintf('%s %s %s * %s *', $model->cron_minute, $model->cron_hour, $model->cron_day_of_month, $model->cron_day_of_week);
$this->repository->shouldReceive('getScheduleWithTasks')->with($model->id)->once()->andReturn($model);
$this->cron->shouldReceive('factory')->with($formatted)->once()->andReturnSelf()
->shouldReceive('getNextRunDate')->withNoArgs()->once()->andReturn('00:00:00');
$this->repository->shouldReceive('update')->with($model->id, [
'is_processing' => true,
'next_run_at' => '00:00:00',
]);
$this->runnerService->shouldReceive('handle')->with($task)->once()->andReturnNull();
$this->service->handle($model->id);
$this->assertTrue(true);
}
}

View file

@ -0,0 +1,90 @@
<?php
/*
* Pterodactyl - Panel
* Copyright (c) 2015 - 2017 Dane Everitt <dane@daneeveritt.com>.
*
* This software is licensed under the terms of the MIT license.
* https://opensource.org/licenses/MIT
*/
namespace Tests\Unit\Services\Schedules\Tasks;
use Mockery as m;
use Tests\TestCase;
use Pterodactyl\Models\Task;
use Illuminate\Support\Facades\Bus;
use Pterodactyl\Jobs\Schedule\RunTaskJob;
use Pterodactyl\Services\Schedules\Tasks\RunTaskService;
use Pterodactyl\Contracts\Repository\TaskRepositoryInterface;
class RunTaskServiceTest extends TestCase
{
/**
* @var \Illuminate\Contracts\Bus\Dispatcher|\Mockery\Mock
*/
protected $dispatcher;
/**
* @var \Pterodactyl\Contracts\Repository\TaskRepositoryInterface|\Mockery\Mock
*/
protected $repository;
/**
* @var \Pterodactyl\Services\Schedules\Tasks\RunTaskService
*/
protected $service;
/**
* Setup tests.
*/
public function setUp()
{
parent::setUp();
Bus::fake();
$this->repository = m::mock(TaskRepositoryInterface::class);
$this->service = new RunTaskService($this->repository);
}
/**
* Test that a job is dispatched.
*/
public function testTaskIsDispatched()
{
$task = factory(Task::class)->make();
$this->repository->shouldReceive('update')->with($task->id, ['is_queued' => true])->once()->andReturnNull();
$this->service->handle($task);
Bus::assertDispatched(RunTaskJob::class, function ($job) use ($task) {
$this->assertEquals($task->id, $job->task, 'Assert job task matches parent task model.');
$this->assertEquals($task->schedule_id, $job->schedule, 'Assert job is linked to correct schedule.');
$this->assertEquals($task->time_offset, $job->delay, 'Assert job delay is set correctly to match task.');
return true;
});
}
/**
* Test that passing an ID in place of a model works.
*/
public function testIdCanBePassedInPlaceOfModel()
{
$task = factory(Task::class)->make();
$this->repository->shouldReceive('find')->with($task->id)->once()->andReturn($task);
$this->repository->shouldReceive('update')->with($task->id, ['is_queued' => true])->once()->andReturnNull();
$this->service->handle($task->id);
Bus::assertDispatched(RunTaskJob::class, function ($job) use ($task) {
$this->assertEquals($task->id, $job->task, 'Assert job task matches parent task model.');
$this->assertEquals($task->schedule_id, $job->schedule, 'Assert job is linked to correct schedule.');
$this->assertEquals($task->time_offset, $job->delay, 'Assert job delay is set correctly to match task.');
return true;
});
}
}

View file

@ -12,7 +12,6 @@ namespace Tests\Unit\Services\Services\Variables;
use Exception;
use Mockery as m;
use Tests\TestCase;
use PhpParser\Node\Expr\Variable;
use Pterodactyl\Models\ServiceVariable;
use Pterodactyl\Exceptions\DisplayException;
use Pterodactyl\Services\Services\Variables\VariableUpdateService;
@ -21,12 +20,12 @@ use Pterodactyl\Contracts\Repository\ServiceVariableRepositoryInterface;
class VariableUpdateServiceTest extends TestCase
{
/**
* @var \Pterodactyl\Models\ServiceVariable
* @var \Pterodactyl\Models\ServiceVariable|\Mockery\Mock
*/
protected $model;
/**
* @var \Pterodactyl\Contracts\Repository\ServiceVariableRepositoryInterface
* @var \Pterodactyl\Contracts\Repository\ServiceVariableRepositoryInterface|\Mockery\Mock
*/
protected $repository;
@ -63,6 +62,22 @@ class VariableUpdateServiceTest extends TestCase
$this->assertTrue($this->service->handle($this->model, ['test-data' => 'test-value']));
}
/**
* Test that a service variable ID can be passed in place of the model.
*/
public function testVariableIdCanBePassedInPlaceOfModel()
{
$this->repository->shouldReceive('find')->with($this->model->id)->once()->andReturn($this->model);
$this->repository->shouldReceive('withoutFresh')->withNoArgs()->once()->andReturnSelf()
->shouldReceive('update')->with($this->model->id, [
'user_viewable' => false,
'user_editable' => false,
'test-data' => 'test-value',
])->once()->andReturn(true);
$this->assertTrue($this->service->handle($this->model->id, ['test-data' => 'test-value']));
}
/**
* Test the function when a valid env_variable key is passed into the function.
*/

View file

@ -141,6 +141,7 @@ class SubuserCreationServiceTest extends TestCase
$user = factory(User::class)->make();
$subuser = factory(Subuser::class)->make(['user_id' => $user->id, 'server_id' => $server->id]);
$this->serverRepository->shouldReceive('find')->with($server->id)->once()->andReturn($server);
$this->connection->shouldReceive('beginTransaction')->withNoArgs()->once()->andReturnNull();
$this->userRepository->shouldReceive('findFirstWhere')->with([['email', '=', $user->email]])->once()->andReturn($user);
$this->subuserRepository->shouldReceive('findCountWhere')->with([
@ -154,7 +155,7 @@ class SubuserCreationServiceTest extends TestCase
$this->permissionService->shouldReceive('handle')->with($subuser->id, $permissions)->once()->andReturnNull();
$this->connection->shouldReceive('commit')->withNoArgs()->once()->andReturnNull();
$response = $this->service->handle($server, $user->email, $permissions);
$response = $this->service->handle($server->id, $user->email, $permissions);
$this->assertInstanceOf(Subuser::class, $response);
$this->assertSame($subuser, $response);
}

View file

@ -94,7 +94,7 @@ class UserCreationServiceTest extends TestCase
$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->passwordService->shouldNotReceive('handle');
$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, [
@ -130,7 +130,7 @@ class UserCreationServiceTest extends TestCase
$this->hasher->shouldNotReceive('make');
$this->database->shouldReceive('beginTransaction')->withNoArgs()->once()->andReturnNull();
$this->hasher->shouldReceive('make')->once()->andReturn('created-enc-password');
$this->passwordService->shouldReceive('generateReset')
$this->passwordService->shouldReceive('handle')
->with('user@example.com')
->once()
->andReturn('random-token');