Refactor startup modification and environment variable services

Better setup, more flexibility, more tests.
This commit is contained in:
Dane Everitt 2017-10-26 23:49:54 -05:00
parent 7022ec788f
commit fa62a0982e
No known key found for this signature in database
GPG key ID: EEA66103B3D71F53
19 changed files with 660 additions and 563 deletions

View file

@ -1,11 +1,4 @@
<?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\Servers;
@ -13,25 +6,23 @@ use Mockery as m;
use Tests\TestCase;
use Pterodactyl\Models\Server;
use Pterodactyl\Models\Location;
use Illuminate\Contracts\Config\Repository;
use Pterodactyl\Services\Servers\EnvironmentService;
use Pterodactyl\Contracts\Repository\ServerRepositoryInterface;
class EnvironmentServiceTest extends TestCase
{
/**
* @var \Pterodactyl\Contracts\Repository\ServerRepositoryInterface
*/
protected $repository;
const CONFIG_MAPPING = 'pterodactyl.environment_mappings';
/**
* @var \Pterodactyl\Services\Servers\EnvironmentService
* @var \Illuminate\Contracts\Config\Repository|\Mockery\Mock
*/
protected $service;
private $config;
/**
* @var \Pterodactyl\Models\Server
* @var \Pterodactyl\Contracts\Repository\ServerRepositoryInterface|\Mockery\Mock
*/
protected $server;
private $repository;
/**
* Setup tests.
@ -40,24 +31,23 @@ class EnvironmentServiceTest extends TestCase
{
parent::setUp();
$this->config = m::mock(Repository::class);
$this->repository = m::mock(ServerRepositoryInterface::class);
$this->server = factory(Server::class)->make([
'location' => factory(Location::class)->make(),
]);
$this->service = new EnvironmentService($this->repository);
}
/**
* Test that set environment key function returns an instance of the class.
* Test that set environment key stores the key into a retreviable array.
*/
public function testSettingEnvironmentKeyShouldReturnInstanceOfSelf()
public function testSettingEnvironmentKeyPersistsItInArray()
{
$instance = $this->service->setEnvironmentKey('TEST_KEY', function () {
$service = $this->getService();
$service->setEnvironmentKey('TEST_KEY', function () {
return true;
});
$this->assertInstanceOf(EnvironmentService::class, $instance);
$this->assertNotEmpty($service->getEnvironmentKeys());
$this->assertArrayHasKey('TEST_KEY', $service->getEnvironmentKeys());
}
/**
@ -65,22 +55,17 @@ class EnvironmentServiceTest extends TestCase
*/
public function testProcessShouldReturnDefaultEnvironmentVariablesForAServer()
{
$this->repository->shouldReceive('getVariablesWithValues')->with($this->server->id)->once()->andReturn([
$model = $this->getServerModel();
$this->config->shouldReceive('get')->with(self::CONFIG_MAPPING, [])->once()->andReturn([]);
$this->repository->shouldReceive('getVariablesWithValues')->with($model->id)->once()->andReturn([
'TEST_VARIABLE' => 'Test Variable',
]);
$response = $this->service->process($this->server);
$this->assertEquals(count(EnvironmentService::ENVIRONMENT_CASTS) + 1, count($response), 'Assert response contains correct amount of items.');
$this->assertTrue(is_array($response), 'Assert that response is an array.');
$response = $this->getService()->handle($model);
$this->assertNotEmpty($response);
$this->assertEquals(4, count($response));
$this->assertArrayHasKey('TEST_VARIABLE', $response);
$this->assertEquals('Test Variable', $response['TEST_VARIABLE']);
foreach (EnvironmentService::ENVIRONMENT_CASTS as $key => $value) {
$this->assertArrayHasKey($key, $response);
$this->assertEquals(object_get($this->server, $value), $response[$key]);
}
$this->assertSame('Test Variable', $response['TEST_VARIABLE']);
}
/**
@ -88,43 +73,106 @@ class EnvironmentServiceTest extends TestCase
*/
public function testProcessShouldReturnKeySetAtRuntime()
{
$this->repository->shouldReceive('getVariablesWithValues')->with($this->server->id)->once()->andReturn([]);
$model = $this->getServerModel();
$this->config->shouldReceive('get')->with(self::CONFIG_MAPPING, [])->once()->andReturn([]);
$this->repository->shouldReceive('getVariablesWithValues')->with($model->id)->once()->andReturn([]);
$response = $this->service->setEnvironmentKey('TEST_VARIABLE', function ($server) {
$service = $this->getService();
$service->setEnvironmentKey('TEST_VARIABLE', function ($server) {
return $server->uuidShort;
})->process($this->server);
});
$this->assertTrue(is_array($response), 'Assert response is an array.');
$response = $service->handle($model);
$this->assertNotEmpty($response);
$this->assertArrayHasKey('TEST_VARIABLE', $response);
$this->assertEquals($this->server->uuidShort, $response['TEST_VARIABLE']);
$this->assertSame($model->uuidShort, $response['TEST_VARIABLE']);
}
/**
* Test that duplicate variables provided at run-time override the defaults.
* Test that duplicate variables provided in config override the defaults.
*/
public function testProcessShouldAllowOverwritingVaraiblesWithConfigurationFile()
{
$model = $this->getServerModel();
$this->repository->shouldReceive('getVariablesWithValues')->with($model->id)->once()->andReturn([]);
$this->config->shouldReceive('get')->with(self::CONFIG_MAPPING, [])->once()->andReturn([
'P_SERVER_UUID' => 'name',
]);
$response = $this->getService()->handle($model);
$this->assertNotEmpty($response);
$this->assertSame(3, count($response));
$this->assertArrayHasKey('P_SERVER_UUID', $response);
$this->assertSame($model->name, $response['P_SERVER_UUID']);
}
/**
* Test that config based environment variables can be done using closures.
*/
public function testVariablesSetInConfigurationAllowForClosures()
{
$model = $this->getServerModel();
$this->config->shouldReceive('get')->with(self::CONFIG_MAPPING, [])->once()->andReturn([
'P_SERVER_UUID' => function ($server) {
return $server->id * 2;
},
]);
$this->repository->shouldReceive('getVariablesWithValues')->with($model->id)->once()->andReturn([]);
$response = $this->getService()->handle($model);
$this->assertNotEmpty($response);
$this->assertSame(3, count($response));
$this->assertArrayHasKey('P_SERVER_UUID', $response);
$this->assertSame($model->id * 2, $response['P_SERVER_UUID']);
}
/**
* Test that duplicate variables provided at run-time override the defaults and those
* that are defined in the configuration file.
*/
public function testProcessShouldAllowOverwritingDefaultVariablesWithRuntimeProvided()
{
$this->repository->shouldReceive('getVariablesWithValues')->with($this->server->id)->once()->andReturn([]);
$model = $this->getServerModel();
$this->config->shouldReceive('get')->with(self::CONFIG_MAPPING, [])->once()->andReturn([
'P_SERVER_UUID' => 'overwritten-config',
]);
$this->repository->shouldReceive('getVariablesWithValues')->with($model->id)->once()->andReturn([]);
$response = $this->service->setEnvironmentKey('P_SERVER_UUID', function ($server) {
$service = $this->getService();
$service->setEnvironmentKey('P_SERVER_UUID', function ($model) {
return 'overwritten';
})->process($this->server);
});
$this->assertTrue(is_array($response), 'Assert response is an array.');
$response = $service->handle($model);
$this->assertNotEmpty($response);
$this->assertSame(3, count($response));
$this->assertArrayHasKey('P_SERVER_UUID', $response);
$this->assertEquals('overwritten', $response['P_SERVER_UUID']);
$this->assertSame('overwritten', $response['P_SERVER_UUID']);
}
/**
* Test that function can run when an ID is provided rather than a server model.
* Return an instance of the service with mocked dependencies.
*
* @return \Pterodactyl\Services\Servers\EnvironmentService
*/
public function testProcessShouldAcceptAnIntegerInPlaceOfAServerModel()
private function getService(): EnvironmentService
{
$this->repository->shouldReceive('find')->with($this->server->id)->once()->andReturn($this->server);
$this->repository->shouldReceive('getVariablesWithValues')->with($this->server->id)->once()->andReturn([]);
return new EnvironmentService($this->config, $this->repository);
}
$response = $this->service->process($this->server->id);
$this->assertTrue(is_array($response), 'Assert that response is an array.');
/**
* Return a server model with a location relationship to be used in the tests.
*
* @return \Pterodactyl\Models\Server
*/
private function getServerModel(): Server
{
return factory(Server::class)->make([
'location' => factory(Location::class)->make(),
]);
}
}

View file

@ -50,7 +50,7 @@ class ServerConfigurationStructureServiceTest extends TestCase
})->toArray();
$this->repository->shouldReceive('getDataForCreation')->with($model)->once()->andReturn($model);
$this->environment->shouldReceive('process')->with($model)->once()->andReturn(['environment_array']);
$this->environment->shouldReceive('handle')->with($model)->once()->andReturn(['environment_array']);
$response = $this->getService()->handle($model);
$this->assertNotEmpty($response);

View file

@ -1,18 +1,13 @@
<?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\Servers;
use Mockery as m;
use Tests\TestCase;
use phpmock\phpunit\PHPMock;
use Pterodactyl\Models\User;
use Tests\Traits\MocksUuids;
use Pterodactyl\Models\Server;
use Tests\Traits\MocksRequestException;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Database\ConnectionInterface;
use Pterodactyl\Exceptions\PterodactylException;
@ -32,86 +27,57 @@ use Pterodactyl\Contracts\Repository\Daemon\ServerRepositoryInterface as DaemonS
*/
class ServerCreationServiceTest extends TestCase
{
use MocksUuids, PHPMock;
use MocksRequestException, MocksUuids;
/**
* @var \Pterodactyl\Contracts\Repository\AllocationRepositoryInterface|\Mockery\Mock
*/
protected $allocationRepository;
private $allocationRepository;
/**
* @var \Pterodactyl\Services\Servers\ServerConfigurationStructureService|\Mockery\Mock
*/
protected $configurationStructureService;
private $configurationStructureService;
/**
* @var \Illuminate\Database\ConnectionInterface|\Mockery\Mock
*/
protected $connection;
private $connection;
/**
* @var \Pterodactyl\Contracts\Repository\Daemon\ServerRepositoryInterface|\Mockery\Mock
*/
protected $daemonServerRepository;
/**
* @var array
*/
protected $data = [
'node_id' => 1,
'name' => 'SomeName',
'description' => null,
'owner_id' => 1,
'memory' => 128,
'disk' => 128,
'swap' => 0,
'io' => 500,
'cpu' => 0,
'allocation_id' => 1,
'allocation_additional' => [2, 3],
'environment' => [
'TEST_VAR_1' => 'var1-value',
],
'nest_id' => 1,
'egg_id' => 1,
'startup' => 'startup-param',
'docker_image' => 'some/image',
];
private $daemonServerRepository;
/**
* @var \GuzzleHttp\Exception\RequestException|\Mockery\Mock
*/
protected $exception;
private $exception;
/**
* @var \Pterodactyl\Contracts\Repository\NodeRepositoryInterface|\Mockery\Mock
*/
protected $nodeRepository;
private $nodeRepository;
/**
* @var \Pterodactyl\Contracts\Repository\ServerRepositoryInterface|\Mockery\Mock
*/
protected $repository;
private $repository;
/**
* @var \Pterodactyl\Contracts\Repository\ServerVariableRepositoryInterface|\Mockery\Mock
*/
protected $serverVariableRepository;
/**
* @var \Pterodactyl\Services\Servers\ServerCreationService
*/
protected $service;
private $serverVariableRepository;
/**
* @var \Pterodactyl\Contracts\Repository\UserRepositoryInterface|\Mockery\Mock
*/
protected $userRepository;
private $userRepository;
/**
* @var \Pterodactyl\Services\Servers\VariableValidatorService|\Mockery\Mock
*/
protected $validatorService;
private $validatorService;
/**
* Setup tests.
@ -130,11 +96,87 @@ class ServerCreationServiceTest extends TestCase
$this->serverVariableRepository = m::mock(ServerVariableRepositoryInterface::class);
$this->userRepository = m::mock(UserRepositoryInterface::class);
$this->validatorService = m::mock(VariableValidatorService::class);
}
$this->getFunctionMock('\\Pterodactyl\\Services\\Servers', 'str_random')
->expects($this->any())->willReturn('random_string');
/**
* Test core functionality of the creation process.
*/
public function testCreateShouldHitAllOfTheNecessaryServicesAndStoreTheServer()
{
$model = factory(Server::class)->make([
'uuid' => $this->getKnownUuid(),
]);
$this->service = new ServerCreationService(
$this->connection->shouldReceive('beginTransaction')->withNoArgs()->once()->andReturnNull();
$this->repository->shouldReceive('create')->with(m::subset([
'uuid' => $this->getKnownUuid(),
'node_id' => $model->node_id,
'owner_id' => $model->owner_id,
'nest_id' => $model->nest_id,
'egg_id' => $model->egg_id,
]))->once()->andReturn($model);
$this->allocationRepository->shouldReceive('assignAllocationsToServer')->with($model->id, [$model->allocation_id])->once()->andReturnNull();
$this->validatorService->shouldReceive('setUserLevel')->with(User::USER_LEVEL_ADMIN)->once()->andReturnNull();
$this->validatorService->shouldReceive('handle')->with($model->egg_id, [])->once()->andReturn(
collect([(object) ['id' => 123, 'value' => 'var1-value']])
);
$this->serverVariableRepository->shouldReceive('insert')->with([
[
'server_id' => $model->id,
'variable_id' => 123,
'variable_value' => 'var1-value',
],
])->once()->andReturnNull();
$this->configurationStructureService->shouldReceive('handle')->with($model)->once()->andReturn(['test' => 'struct']);
$this->daemonServerRepository->shouldReceive('setNode')->with($model->node_id)->once()->andReturnSelf();
$this->daemonServerRepository->shouldReceive('create')->with(['test' => 'struct'], ['start_on_completion' => false])->once()->andReturnNull();
$this->connection->shouldReceive('commit')->withNoArgs()->once()->andReturnNull();
$response = $this->getService()->create($model->toArray());
$this->assertSame($model, $response);
}
/**
* Test handling of node timeout or other daemon error.
*/
public function testExceptionShouldBeThrownIfTheRequestFails()
{
$this->configureExceptionMock();
$model = factory(Server::class)->make([
'uuid' => $this->getKnownUuid(),
]);
$this->connection->shouldReceive('beginTransaction')->withNoArgs()->once()->andReturnNull();
$this->repository->shouldReceive('create')->once()->andReturn($model);
$this->allocationRepository->shouldReceive('assignAllocationsToServer')->once()->andReturnNull();
$this->validatorService->shouldReceive('setUserLevel')->once()->andReturnNull();
$this->validatorService->shouldReceive('handle')->once()->andReturn(collect([]));
$this->configurationStructureService->shouldReceive('handle')->once()->andReturn([]);
$this->daemonServerRepository->shouldReceive('setNode')->with($model->node_id)->once()->andThrow($this->exception);
$this->connection->shouldReceive('rollBack')->withNoArgs()->once()->andReturnNull();
try {
$this->getService()->create($model->toArray());
} catch (PterodactylException $exception) {
$this->assertInstanceOf(DaemonConnectionException::class, $exception);
$this->assertInstanceOf(RequestException::class, $exception->getPrevious());
}
}
/**
* Return an instance of the service with mocked dependencies.
*
* @return \Pterodactyl\Services\Servers\ServerCreationService
*/
private function getService(): ServerCreationService
{
return new ServerCreationService(
$this->allocationRepository,
$this->connection,
$this->daemonServerRepository,
@ -146,77 +188,4 @@ class ServerCreationServiceTest extends TestCase
$this->validatorService
);
}
/**
* Test core functionality of the creation process.
*/
public function testCreateShouldHitAllOfTheNecessaryServicesAndStoreTheServer()
{
$this->validatorService->shouldReceive('isAdmin')->withNoArgs()->once()->andReturnSelf()
->shouldReceive('setFields')->with($this->data['environment'])->once()->andReturnSelf()
->shouldReceive('validate')->with($this->data['egg_id'])->once()->andReturnSelf();
$this->connection->shouldReceive('beginTransaction')->withNoArgs()->once()->andReturnNull();
$this->repository->shouldReceive('create')->with(m::subset([
'uuid' => $this->getKnownUuid(),
'node_id' => $this->data['node_id'],
'owner_id' => 1,
'nest_id' => 1,
'egg_id' => 1,
]))->once()->andReturn((object) [
'node_id' => 1,
'id' => 1,
]);
$this->allocationRepository->shouldReceive('assignAllocationsToServer')->with(1, [1, 2, 3])->once()->andReturnNull();
$this->validatorService->shouldReceive('getResults')->withNoArgs()->once()->andReturn([[
'id' => 1,
'key' => 'TEST_VAR_1',
'value' => 'var1-value',
]]);
$this->serverVariableRepository->shouldReceive('insert')->with([[
'server_id' => 1,
'variable_id' => 1,
'variable_value' => 'var1-value',
]])->once()->andReturnNull();
$this->configurationStructureService->shouldReceive('handle')->with(1)->once()->andReturn(['test' => 'struct']);
$this->daemonServerRepository->shouldReceive('setNode')->with(1)->once()->andReturnSelf()
->shouldReceive('create')->with(['test' => 'struct'], ['start_on_completion' => false])->once()->andReturnNull();
$this->connection->shouldReceive('commit')->withNoArgs()->once()->andReturnNull();
$response = $this->service->create($this->data);
$this->assertEquals(1, $response->id);
$this->assertEquals(1, $response->node_id);
}
/**
* Test handling of node timeout or other daemon error.
*/
public function testExceptionShouldBeThrownIfTheRequestFails()
{
$this->validatorService->shouldReceive('isAdmin->setFields->validate->getResults')->once()->andReturn([]);
$this->connection->shouldReceive('beginTransaction')->withNoArgs()->once()->andReturnNull();
$this->repository->shouldReceive('create')->once()->andReturn((object) [
'node_id' => 1,
'id' => 1,
]);
$this->allocationRepository->shouldReceive('assignAllocationsToServer')->once()->andReturnNull();
$this->serverVariableRepository->shouldReceive('insert')->with([])->once()->andReturnNull();
$this->configurationStructureService->shouldReceive('handle')->once()->andReturnNull();
$this->daemonServerRepository->shouldReceive('setNode->create')->once()->andThrow($this->exception);
$this->exception->shouldReceive('getResponse')->withNoArgs()->once()->andReturnNull();
$this->connection->shouldReceive('rollBack')->withNoArgs()->once()->andReturnNull();
try {
$this->service->create($this->data);
} catch (PterodactylException $exception) {
$this->assertInstanceOf(DaemonConnectionException::class, $exception);
}
}
}

View file

@ -11,6 +11,7 @@ namespace Tests\Unit\Services\Servers;
use Mockery as m;
use Tests\TestCase;
use Pterodactyl\Models\User;
use Pterodactyl\Models\Server;
use Illuminate\Database\ConnectionInterface;
use Pterodactyl\Services\Servers\EnvironmentService;
@ -25,37 +26,32 @@ class StartupModificationServiceTest extends TestCase
/**
* @var \Pterodactyl\Contracts\Repository\Daemon\ServerRepositoryInterface|\Mockery\Mock
*/
protected $daemonServerRepository;
private $daemonServerRepository;
/**
* @var \Illuminate\Database\ConnectionInterface|\Mockery\Mock
*/
protected $connection;
private $connection;
/**
* @var \Pterodactyl\Services\Servers\EnvironmentService|\Mockery\Mock
*/
protected $environmentService;
private $environmentService;
/**
* @var \Pterodactyl\Contracts\Repository\ServerRepositoryInterface|\Mockery\Mock
*/
protected $repository;
private $repository;
/**
* @var \Pterodactyl\Contracts\Repository\ServerVariableRepositoryInterface|\Mockery\Mock
*/
protected $serverVariableRepository;
/**
* @var \Pterodactyl\Services\Servers\StartupModificationService
*/
protected $service;
private $serverVariableRepository;
/**
* @var \Pterodactyl\Services\Servers\VariableValidatorService|\Mockery\Mock
*/
protected $validatorService;
private $validatorService;
/**
* Setup tests.
@ -70,8 +66,97 @@ class StartupModificationServiceTest extends TestCase
$this->repository = m::mock(ServerRepositoryInterface::class);
$this->serverVariableRepository = m::mock(ServerVariableRepositoryInterface::class);
$this->validatorService = m::mock(VariableValidatorService::class);
}
$this->service = new StartupModificationService(
/**
* Test startup modification as a non-admin user.
*/
public function testStartupModifiedAsNormalUser()
{
$model = factory(Server::class)->make();
$this->connection->shouldReceive('beginTransaction')->withNoArgs()->once()->andReturnNull();
$this->validatorService->shouldReceive('setUserLevel')->with(User::USER_LEVEL_USER)->once()->andReturnNull();
$this->validatorService->shouldReceive('handle')->with(123, ['test' => 'abcd1234'])->once()->andReturn(
collect([(object) ['id' => 1, 'value' => 'stored-value']])
);
$this->serverVariableRepository->shouldReceive('withoutFresh')->withNoArgs()->once()->andReturnSelf();
$this->serverVariableRepository->shouldReceive('updateOrCreate')->with([
'server_id' => $model->id,
'variable_id' => 1,
], ['variable_value' => 'stored-value'])->once()->andReturnNull();
$this->environmentService->shouldReceive('handle')->with($model)->once()->andReturn(['env']);
$this->daemonServerRepository->shouldReceive('setNode')->with($model->node_id)->once()->andReturnSelf();
$this->daemonServerRepository->shouldReceive('setAccessServer')->with($model->uuid)->once()->andReturnSelf();
$this->daemonServerRepository->shouldReceive('update')->with([
'build' => ['env|overwrite' => ['env']],
])->once()->andReturnSelf();
$this->connection->shouldReceive('commit')->withNoArgs()->once()->andReturnNull();
$this->getService()->handle($model, ['egg_id' => 123, 'environment' => ['test' => 'abcd1234']]);
$this->assertTrue(true);
}
/**
* Test startup modification as an admin user.
*/
public function testStartupModificationAsAdminUser()
{
$model = factory(Server::class)->make([
'egg_id' => 123,
]);
$this->connection->shouldReceive('beginTransaction')->withNoArgs()->once()->andReturnNull();
$this->validatorService->shouldReceive('setUserLevel')->with(User::USER_LEVEL_ADMIN)->once()->andReturnNull();
$this->validatorService->shouldReceive('handle')->with(456, ['test' => 'abcd1234'])->once()->andReturn(
collect([(object) ['id' => 1, 'value' => 'stored-value']])
);
$this->serverVariableRepository->shouldReceive('withoutFresh')->withNoArgs()->once()->andReturnSelf();
$this->serverVariableRepository->shouldReceive('updateOrCreate')->with([
'server_id' => $model->id,
'variable_id' => 1,
], ['variable_value' => 'stored-value'])->once()->andReturnNull();
$this->environmentService->shouldReceive('handle')->with($model)->once()->andReturn(['env']);
$this->repository->shouldReceive('update')->with($model->id, m::subset([
'installed' => 0,
'egg_id' => 456,
'pack_id' => 789,
]))->once()->andReturn($model);
$this->repository->shouldReceive('withColumns->getDaemonServiceData')->with($model->id)->once()->andReturn([]);
$this->daemonServerRepository->shouldReceive('setNode')->with($model->node_id)->once()->andReturnSelf();
$this->daemonServerRepository->shouldReceive('setAccessServer')->with($model->uuid)->once()->andReturnSelf();
$this->daemonServerRepository->shouldReceive('update')->with([
'build' => [
'env|overwrite' => ['env'],
],
'service' => [
'skip_scripts' => false,
],
])->once()->andReturnSelf();
$this->connection->shouldReceive('commit')->withNoArgs()->once()->andReturnNull();
$service = $this->getService();
$service->setUserLevel(User::USER_LEVEL_ADMIN);
$service->handle($model, ['egg_id' => 456, 'pack_id' => 789, 'environment' => ['test' => 'abcd1234']]);
$this->assertTrue(true);
}
/**
* Return an instance of the service with mocked dependencies.
*
* @return \Pterodactyl\Services\Servers\StartupModificationService
*/
private function getService(): StartupModificationService
{
return new StartupModificationService(
$this->connection,
$this->daemonServerRepository,
$this->environmentService,
@ -80,16 +165,4 @@ class StartupModificationServiceTest extends TestCase
$this->validatorService
);
}
/**
* Test startup is modified when user is not an administrator.
*
* @todo this test works, but not for the right reasons...
*/
public function testStartupIsModifiedAsNonAdmin()
{
$model = factory(Server::class)->make();
$this->assertTrue(true);
}
}

View file

@ -11,8 +11,11 @@ namespace Tests\Unit\Services\Servers;
use Mockery as m;
use Tests\TestCase;
use Pterodactyl\Models\User;
use Illuminate\Support\Collection;
use Pterodactyl\Models\EggVariable;
use Illuminate\Contracts\Validation\Factory;
use Pterodactyl\Exceptions\PterodactylException;
use Pterodactyl\Exceptions\DisplayValidationException;
use Pterodactyl\Services\Servers\VariableValidatorService;
use Pterodactyl\Contracts\Repository\ServerRepositoryInterface;
@ -22,35 +25,25 @@ use Pterodactyl\Contracts\Repository\ServerVariableRepositoryInterface;
class VariableValidatorServiceTest extends TestCase
{
/**
* @var \Pterodactyl\Contracts\Repository\EggVariableRepositoryInterface
* @var \Pterodactyl\Contracts\Repository\EggVariableRepositoryInterface|\Mockery\Mock
*/
protected $optionVariableRepository;
/**
* @var \Pterodactyl\Contracts\Repository\ServerRepositoryInterface
* @var \Pterodactyl\Contracts\Repository\ServerRepositoryInterface|\Mockery\Mock
*/
protected $serverRepository;
/**
* @var \Pterodactyl\Contracts\Repository\ServerVariableRepositoryInterface
* @var \Pterodactyl\Contracts\Repository\ServerVariableRepositoryInterface|\Mockery\Mock
*/
protected $serverVariableRepository;
/**
* @var \Pterodactyl\Services\Servers\VariableValidatorService
*/
protected $service;
/**
* @var \Illuminate\Validation\Factory
* @var \Illuminate\Contracts\Validation\Factory|\Mockery\Mock
*/
protected $validator;
/**
* @var \Illuminate\Support\Collection
*/
protected $variables;
/**
* Setup tests.
*/
@ -58,56 +51,10 @@ class VariableValidatorServiceTest extends TestCase
{
parent::setUp();
$this->variables = collect(
[
factory(EggVariable::class)->states('editable', 'viewable')->make(),
factory(EggVariable::class)->states('viewable')->make(),
factory(EggVariable::class)->states('editable')->make(),
factory(EggVariable::class)->make(),
]
);
$this->optionVariableRepository = m::mock(EggVariableRepositoryInterface::class);
$this->serverRepository = m::mock(ServerRepositoryInterface::class);
$this->serverVariableRepository = m::mock(ServerVariableRepositoryInterface::class);
$this->validator = m::mock(Factory::class);
$this->service = new VariableValidatorService(
$this->optionVariableRepository,
$this->serverRepository,
$this->serverVariableRepository,
$this->validator
);
}
/**
* Test that setting fields returns an instance of the class.
*/
public function testSettingFieldsShouldReturnInstanceOfSelf()
{
$response = $this->service->setFields([]);
$this->assertInstanceOf(VariableValidatorService::class, $response);
}
/**
* Test that setting administrator value returns an instance of the class.
*/
public function testSettingAdminShouldReturnInstanceOfSelf()
{
$response = $this->service->isAdmin();
$this->assertInstanceOf(VariableValidatorService::class, $response);
}
/**
* Test that getting the results returns an array of values.
*/
public function testGettingResultsReturnsAnArrayOfValues()
{
$response = $this->service->getResults();
$this->assertTrue(is_array($response));
}
/**
@ -115,13 +62,11 @@ class VariableValidatorServiceTest extends TestCase
*/
public function testEmptyResultSetShouldBeReturnedIfNoVariablesAreFound()
{
$this->optionVariableRepository->shouldReceive('findWhere')->with([['egg_id', '=', 1]])->andReturn([]);
$this->optionVariableRepository->shouldReceive('findWhere')->with([['egg_id', '=', 1]])->andReturn(collect([]));
$response = $this->service->validate(1);
$this->assertInstanceOf(VariableValidatorService::class, $response);
$this->assertTrue(is_array($response->getResults()));
$this->assertEmpty($response->getResults());
$response = $this->getService()->handle(1, []);
$this->assertEmpty($response);
$this->assertInstanceOf(Collection::class, $response);
}
/**
@ -129,31 +74,34 @@ class VariableValidatorServiceTest extends TestCase
*/
public function testValidatorShouldNotProcessVariablesSetAsNotUserEditableWhenAdminFlagIsNotPassed()
{
$this->optionVariableRepository->shouldReceive('findWhere')->with([['egg_id', '=', 1]])->andReturn($this->variables);
$variables = $this->getVariableCollection();
$this->optionVariableRepository->shouldReceive('findWhere')->with([['egg_id', '=', 1]])->andReturn($variables);
$this->validator->shouldReceive('make')->with([
'variable_value' => 'Test_SomeValue_0',
], [
'variable_value' => $this->variables[0]->rules,
])->once()->andReturnSelf()
->shouldReceive('fails')->withNoArgs()->once()->andReturn(false);
'variable_value' => $variables[0]->rules,
])->once()->andReturnSelf();
$this->validator->shouldReceive('fails')->withNoArgs()->once()->andReturn(false);
$response = $this->service->setFields([
$this->variables[0]->env_variable => 'Test_SomeValue_0',
$this->variables[1]->env_variable => 'Test_SomeValue_1',
$this->variables[2]->env_variable => 'Test_SomeValue_2',
$this->variables[3]->env_variable => 'Test_SomeValue_3',
])->validate(1)->getResults();
$response = $this->getService()->handle(1, [
$variables[0]->env_variable => 'Test_SomeValue_0',
$variables[1]->env_variable => 'Test_SomeValue_1',
$variables[2]->env_variable => 'Test_SomeValue_2',
$variables[3]->env_variable => 'Test_SomeValue_3',
]);
$this->assertEquals(1, count($response), 'Assert response has a single item in array.');
$this->assertArrayHasKey('0', $response);
$this->assertArrayHasKey('id', $response[0]);
$this->assertArrayHasKey('key', $response[0]);
$this->assertArrayHasKey('value', $response[0]);
$this->assertNotEmpty($response);
$this->assertInstanceOf(Collection::class, $response);
$this->assertEquals(1, $response->count(), 'Assert response has a single item in collection.');
$this->assertEquals($this->variables[0]->id, $response[0]['id']);
$this->assertEquals($this->variables[0]->env_variable, $response[0]['key']);
$this->assertEquals('Test_SomeValue_0', $response[0]['value']);
$variable = $response->first();
$this->assertObjectHasAttribute('id', $variable);
$this->assertObjectHasAttribute('key', $variable);
$this->assertObjectHasAttribute('value', $variable);
$this->assertSame($variables[0]->id, $variable->id);
$this->assertSame($variables[0]->env_variable, $variable->key);
$this->assertSame('Test_SomeValue_0', $variable->value);
}
/**
@ -161,36 +109,39 @@ class VariableValidatorServiceTest extends TestCase
*/
public function testValidatorShouldProcessAllVariablesWhenAdminFlagIsSet()
{
$this->optionVariableRepository->shouldReceive('findWhere')->with([['egg_id', '=', 1]])->andReturn($this->variables);
$variables = $this->getVariableCollection();
$this->optionVariableRepository->shouldReceive('findWhere')->with([['egg_id', '=', 1]])->andReturn($variables);
foreach ($this->variables as $key => $variable) {
foreach ($variables as $key => $variable) {
$this->validator->shouldReceive('make')->with([
'variable_value' => 'Test_SomeValue_' . $key,
], [
'variable_value' => $this->variables[$key]->rules,
])->andReturnSelf()
->shouldReceive('fails')->withNoArgs()->once()->andReturn(false);
'variable_value' => $variables[$key]->rules,
])->once()->andReturnSelf();
$this->validator->shouldReceive('fails')->withNoArgs()->once()->andReturn(false);
}
$response = $this->service->isAdmin()->setFields([
$this->variables[0]->env_variable => 'Test_SomeValue_0',
$this->variables[1]->env_variable => 'Test_SomeValue_1',
$this->variables[2]->env_variable => 'Test_SomeValue_2',
$this->variables[3]->env_variable => 'Test_SomeValue_3',
])->validate(1)->getResults();
$service = $this->getService();
$service->setUserLevel(User::USER_LEVEL_ADMIN);
$response = $service->handle(1, [
$variables[0]->env_variable => 'Test_SomeValue_0',
$variables[1]->env_variable => 'Test_SomeValue_1',
$variables[2]->env_variable => 'Test_SomeValue_2',
$variables[3]->env_variable => 'Test_SomeValue_3',
]);
$this->assertEquals(4, count($response), 'Assert response has all four items in array.');
$this->assertNotEmpty($response);
$this->assertInstanceOf(Collection::class, $response);
$this->assertEquals(4, $response->count(), 'Assert response has all four items in collection.');
foreach ($response as $key => $values) {
$this->assertArrayHasKey($key, $response);
$this->assertArrayHasKey('id', $response[$key]);
$this->assertArrayHasKey('key', $response[$key]);
$this->assertArrayHasKey('value', $response[$key]);
$this->assertEquals($this->variables[$key]->id, $response[$key]['id']);
$this->assertEquals($this->variables[$key]->env_variable, $response[$key]['key']);
$this->assertEquals('Test_SomeValue_' . $key, $response[$key]['value']);
}
$response->each(function ($variable, $key) use ($variables) {
$this->assertObjectHasAttribute('id', $variable);
$this->assertObjectHasAttribute('key', $variable);
$this->assertObjectHasAttribute('value', $variable);
$this->assertSame($variables[$key]->id, $variable->id);
$this->assertSame($variables[$key]->env_variable, $variable->key);
$this->assertSame('Test_SomeValue_' . $key, $variable->value);
});
}
/**
@ -198,31 +149,63 @@ class VariableValidatorServiceTest extends TestCase
*/
public function testValidatorShouldThrowExceptionWhenAValidationErrorIsEncountered()
{
$this->optionVariableRepository->shouldReceive('findWhere')->with([['egg_id', '=', 1]])->andReturn($this->variables);
$variables = $this->getVariableCollection();
$this->optionVariableRepository->shouldReceive('findWhere')->with([['egg_id', '=', 1]])->andReturn($variables);
$this->validator->shouldReceive('make')->with([
'variable_value' => null,
], [
'variable_value' => $this->variables[0]->rules,
])->once()->andReturnSelf()
->shouldReceive('fails')->withNoArgs()->once()->andReturn(true);
'variable_value' => $variables[0]->rules,
])->once()->andReturnSelf();
$this->validator->shouldReceive('fails')->withNoArgs()->once()->andReturn(true);
$this->validator->shouldReceive('errors')->withNoArgs()->once()->andReturnSelf()
->shouldReceive('toArray')->withNoArgs()->once()->andReturn([]);
$this->validator->shouldReceive('errors')->withNoArgs()->once()->andReturnSelf();
$this->validator->shouldReceive('toArray')->withNoArgs()->once()->andReturn([]);
try {
$this->service->setFields([
$this->variables[0]->env_variable => null,
])->validate(1);
} catch (DisplayValidationException $exception) {
$decoded = json_decode($exception->getMessage());
$this->getService()->handle(1, [$variables[0]->env_variable => null]);
} catch (PterodactylException $exception) {
$this->assertInstanceOf(DisplayValidationException::class, $exception);
$decoded = json_decode($exception->getMessage());
$this->assertEquals(0, json_last_error(), 'Assert that response is decodable JSON.');
$this->assertObjectHasAttribute('notice', $decoded);
$this->assertEquals(
trans('admin/server.exceptions.bad_variable', ['name' => $this->variables[0]->name]),
trans('admin/server.exceptions.bad_variable', ['name' => $variables[0]->name]),
$decoded->notice[0]
);
}
}
/**
* Return a collection of fake variables to use for testing.
*
* @return \Illuminate\Support\Collection
*/
private function getVariableCollection(): Collection
{
return collect(
[
factory(EggVariable::class)->states('editable', 'viewable')->make(),
factory(EggVariable::class)->states('viewable')->make(),
factory(EggVariable::class)->states('editable')->make(),
factory(EggVariable::class)->make(),
]
);
}
/**
* Return an instance of the service with mocked dependencies.
*
* @return \Pterodactyl\Services\Servers\VariableValidatorService
*/
private function getService(): VariableValidatorService
{
return new VariableValidatorService(
$this->optionVariableRepository,
$this->serverRepository,
$this->serverVariableRepository,
$this->validator
);
}
}