Finish unit tests for all server services

This commit is contained in:
Dane Everitt 2017-07-22 20:15:01 -05:00
parent 3add44d342
commit acbc52506c
No known key found for this signature in database
GPG key ID: EEA66103B3D71F53
21 changed files with 1609 additions and 206 deletions

View file

@ -0,0 +1,224 @@
<?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\Unit\Services\Servers;
use Mockery as m;
use phpmock\phpunit\PHPMock;
use Pterodactyl\Contracts\Repository\NodeRepositoryInterface;
use Pterodactyl\Contracts\Repository\ServerRepositoryInterface;
use Pterodactyl\Contracts\Repository\ServerVariableRepositoryInterface;
use Pterodactyl\Contracts\Repository\UserRepositoryInterface;
use Pterodactyl\Services\Servers\CreationService;
use Pterodactyl\Services\Servers\UsernameGenerationService;
use Pterodactyl\Services\Servers\VariableValidatorService;
use Ramsey\Uuid\Uuid;
use Tests\TestCase;
use Illuminate\Database\DatabaseManager;
use Pterodactyl\Contracts\Repository\AllocationRepositoryInterface;
use Pterodactyl\Contracts\Repository\Daemon\ServerRepositoryInterface as DaemonServerRepositoryInterface;
class CreationServiceTest extends TestCase
{
use PHPMock;
/**
* @var \Pterodactyl\Contracts\Repository\AllocationRepositoryInterface
*/
protected $allocationRepository;
/**
* @var \Pterodactyl\Contracts\Repository\Daemon\ServerRepositoryInterface
*/
protected $daemonServerRepository;
/**
* @var \Illuminate\Database\DatabaseManager
*/
protected $database;
/**
* @var \Pterodactyl\Contracts\Repository\NodeRepositoryInterface
*/
protected $nodeRepository;
/**
* @var \Pterodactyl\Contracts\Repository\ServerRepositoryInterface
*/
protected $repository;
/**
* @var \Pterodactyl\Contracts\Repository\ServerVariableRepositoryInterface
*/
protected $serverVariableRepository;
/**
* @var \Pterodactyl\Services\Servers\CreationService
*/
protected $service;
/**
* @var \Pterodactyl\Contracts\Repository\UserRepositoryInterface
*/
protected $userRepository;
/**
* @var \Pterodactyl\Services\Servers\UsernameGenerationService
*/
protected $usernameService;
/**
* @var \Pterodactyl\Services\Servers\VariableValidatorService
*/
protected $validatorService;
/**
* @var \Ramsey\Uuid\Uuid
*/
protected $uuid;
/**
* Setup tests.
*/
public function setUp()
{
parent::setUp();
$this->allocationRepository = m::mock(AllocationRepositoryInterface::class);
$this->daemonServerRepository = m::mock(DaemonServerRepositoryInterface::class);
$this->database = m::mock(DatabaseManager::class);
$this->nodeRepository = m::mock(NodeRepositoryInterface::class);
$this->repository = m::mock(ServerRepositoryInterface::class);
$this->serverVariableRepository = m::mock(ServerVariableRepositoryInterface::class);
$this->userRepository = m::mock(UserRepositoryInterface::class);
$this->usernameService = m::mock(UsernameGenerationService::class);
$this->validatorService = m::mock(VariableValidatorService::class);
$this->uuid = m::mock('overload:Ramsey\Uuid\Uuid');
$this->getFunctionMock('\\Pterodactyl\\Services\\Servers', 'bin2hex')
->expects($this->any())->willReturn('randomstring');
$this->getFunctionMock('\\Ramsey\\Uuid\\Uuid', 'uuid4')
->expects($this->any())->willReturn('s');
$this->service = new CreationService(
$this->allocationRepository,
$this->daemonServerRepository,
$this->database,
$this->nodeRepository,
$this->repository,
$this->serverVariableRepository,
$this->userRepository,
$this->usernameService,
$this->validatorService
);
}
/**
* Test core functionality of the creation process.
*/
public function testCreateShouldHitAllOfTheNecessaryServicesAndStoreTheServer()
{
$data = [
'node_id' => 1,
'name' => 'SomeName',
'description' => null,
'user_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',
],
'service_id' => 1,
'option_id' => 1,
'startup' => 'startup-param',
'docker_image' => 'some/image',
];
$this->validatorService->shouldReceive('setAdmin')->withNoArgs()->once()->andReturnSelf()
->shouldReceive('setFields')->with($data['environment'])->once()->andReturnSelf()
->shouldReceive('validate')->with($data['option_id'])->once()->andReturnSelf();
$this->database->shouldReceive('beginTransaction')->withNoArgs()->once()->andReturnNull();
$this->uuid->shouldReceive('uuid4')->withNoArgs()->once()->andReturnSelf()
->shouldReceive('toString')->withNoArgs()->once()->andReturn('uuid-0000');
$this->usernameService->shouldReceive('generate')->with($data['name'], 'randomstring')
->once()->andReturn('user_name');
$this->repository->shouldReceive('create')->with([
'uuid' => 'uuid-0000',
'uuidShort' => 'randomstring',
'node_id' => $data['node_id'],
'name' => $data['name'],
'description' => $data['description'],
'skip_scripts' => false,
'suspended' => false,
'owner_id' => $data['user_id'],
'memory' => $data['memory'],
'swap' => $data['swap'],
'disk' => $data['disk'],
'io' => $data['io'],
'cpu' => $data['cpu'],
'oom_disabled' => false,
'allocation_id' => $data['allocation_id'],
'service_id' => $data['service_id'],
'option_id' => $data['option_id'],
'pack_id' => null,
'startup' => $data['startup'],
'daemonSecret' => 'randomstring',
'image' => $data['docker_image'],
'username' => 'user_name',
'sftp_password' => null,
])->once()->andReturn((object) [
'node_id' => 1,
'id' => 1,
]);
$this->allocationRepository->shouldReceive('assignAllocationsToServer')->with(1, [1, 2, 3]);
$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->daemonServerRepository->shouldReceive('setNode')->with(1)->once()->andReturnSelf()
->shouldReceive('create')->with(1)->once()->andReturnNull();
$this->database->shouldReceive('commit')->withNoArgs()->once()->andReturnNull();
$response = $this->service->create($data);
$this->assertEquals(1, $response->id);
$this->assertEquals(1, $response->node_id);
}
}

View file

@ -0,0 +1,394 @@
<?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\Unit\Services\Servers;
use Exception;
use Mockery as m;
use Tests\TestCase;
use phpmock\phpunit\PHPMock;
use Pterodactyl\Models\Server;
use Illuminate\Database\DatabaseManager;
use GuzzleHttp\Exception\RequestException;
use Pterodactyl\Exceptions\DisplayException;
use Pterodactyl\Repositories\Eloquent\ServerRepository;
use Pterodactyl\Services\Servers\DetailsModificationService;
use Pterodactyl\Repositories\Daemon\ServerRepository as DaemonServerRepository;
class DetailsModificationServiceTest extends TestCase
{
use PHPMock;
/**
* @var \Illuminate\Database\DatabaseManager
*/
protected $database;
/**
* @var \Pterodactyl\Repositories\Daemon\ServerRepository
*/
protected $daemonServerRepository;
/**
* @var \GuzzleHttp\Exception\RequestException
*/
protected $exception;
/**
* @var \Pterodactyl\Repositories\Eloquent\ServerRepository
*/
protected $repository;
/**
* @var \Pterodactyl\Services\Servers\DetailsModificationService
*/
protected $service;
/**
* Setup tests.
*/
public function setUp()
{
parent::setUp();
$this->database = m::mock(DatabaseManager::class);
$this->exception = m::mock(RequestException::class)->makePartial();
$this->daemonServerRepository = m::mock(DaemonServerRepository::class);
$this->repository = m::mock(ServerRepository::class);
$this->getFunctionMock('\\Pterodactyl\\Services\\Servers', 'bin2hex')
->expects($this->any())->willReturn('randomString');
$this->service = new DetailsModificationService(
$this->database,
$this->daemonServerRepository,
$this->repository
);
}
/**
* Test basic updating of core variables when a model is provided.
*/
public function testEditShouldSkipDatabaseSearchIfModelIsPassed()
{
$server = factory(Server::class)->make([
'owner_id' => 1,
]);
$data = ['owner_id' => 1, 'name' => 'New Name', 'description' => 'New Description'];
$this->repository->shouldNotReceive('find');
$this->database->shouldReceive('beginTransaction')->withNoArgs()->once()->andReturnNull();
$this->repository->shouldReceive('withoutFresh')->withNoArgs()->once()->andReturnSelf()
->shouldReceive('update')->with($server->id, [
'owner_id' => $data['owner_id'],
'name' => $data['name'],
'description' => $data['description'],
'daemonSecret' => $server->daemonSecret,
], true, true)->once()->andReturnNull();
$this->database->shouldReceive('commit')->withNoArgs()->once()->andReturn(true);
$response = $this->service->edit($server, $data);
$this->assertTrue($response);
}
/**
* Test that repository attempts to find model in database if no model is passed.
*/
public function testEditShouldGetModelFromRepositoryIfNotPassed()
{
$server = factory(Server::class)->make([
'owner_id' => 1,
]);
$data = ['owner_id' => 1, 'name' => 'New Name', 'description' => 'New Description'];
$this->repository->shouldReceive('find')->with($server->id)->once()->andReturn($server);
$this->database->shouldReceive('beginTransaction')->withNoArgs()->once()->andReturnNull();
$this->repository->shouldReceive('withoutFresh')->withNoArgs()->once()->andReturnSelf()
->shouldReceive('update')->with($server->id, [
'owner_id' => $data['owner_id'],
'name' => $data['name'],
'description' => $data['description'],
'daemonSecret' => $server->daemonSecret,
], true, true)->once()->andReturnNull();
$this->database->shouldReceive('commit')->withNoArgs()->once()->andReturn(true);
$response = $this->service->edit($server->id, $data);
$this->assertTrue($response);
}
/**
* Test that the daemon secret is reset if the owner id changes.
*/
public function testEditShouldResetDaemonSecretIfOwnerIdIsChanged()
{
$server = factory(Server::class)->make([
'owner_id' => 1,
'node_id' => 1,
]);
$data = ['owner_id' => 2, 'name' => 'New Name', 'description' => 'New Description'];
$this->repository->shouldNotReceive('find');
$this->database->shouldReceive('beginTransaction')->withNoArgs()->once()->andReturnNull();
$this->repository->shouldReceive('withoutFresh')->withNoArgs()->once()->andReturnSelf()
->shouldReceive('update')->with($server->id, [
'owner_id' => $data['owner_id'],
'name' => $data['name'],
'description' => $data['description'],
'daemonSecret' => 'randomString',
], true, true)->once()->andReturnNull();
$this->daemonServerRepository->shouldReceive('setNode')->with($server->node_id)->once()->andReturnSelf()
->shouldReceive('setAccessServer')->with($server->uuid)->once()->andReturnSelf()
->shouldReceive('update')->with([
'keys' => [
$server->daemonSecret => [],
'randomString' => DaemonServerRepository::DAEMON_PERMISSIONS,
],
])->once()->andReturnNull();
$this->database->shouldReceive('commit')->withNoArgs()->once()->andReturn(true);
$response = $this->service->edit($server, $data);
$this->assertTrue($response);
}
public function testEditShouldResetDaemonSecretIfBooleanValueIsPassed()
{
$server = factory(Server::class)->make([
'owner_id' => 1,
'node_id' => 1,
]);
$data = ['owner_id' => 1, 'name' => 'New Name', 'description' => 'New Description', 'reset_token' => true];
$this->repository->shouldNotReceive('find');
$this->database->shouldReceive('beginTransaction')->withNoArgs()->once()->andReturnNull();
$this->repository->shouldReceive('withoutFresh')->withNoArgs()->once()->andReturnSelf()
->shouldReceive('update')->with($server->id, [
'owner_id' => $data['owner_id'],
'name' => $data['name'],
'description' => $data['description'],
'daemonSecret' => 'randomString',
], true, true)->once()->andReturnNull();
$this->daemonServerRepository->shouldReceive('setNode')->with($server->node_id)->once()->andReturnSelf()
->shouldReceive('setAccessServer')->with($server->uuid)->once()->andReturnSelf()
->shouldReceive('update')->with([
'keys' => [
$server->daemonSecret => [],
'randomString' => DaemonServerRepository::DAEMON_PERMISSIONS,
],
])->once()->andReturnNull();
$this->database->shouldReceive('commit')->withNoArgs()->once()->andReturn(true);
$response = $this->service->edit($server, $data);
$this->assertTrue($response);
}
/**
* Test that a displayable exception is thrown if the daemon responds with an error.
*/
public function testEditShouldThrowADisplayableExceptionIfDaemonResponseErrors()
{
$server = factory(Server::class)->make([
'owner_id' => 1,
'node_id' => 1,
]);
$data = ['owner_id' => 2, 'name' => 'New Name', 'description' => 'New Description'];
$this->repository->shouldNotReceive('find');
$this->database->shouldReceive('beginTransaction')->withNoArgs()->once()->andReturnNull();
$this->repository->shouldReceive('withoutFresh')->withNoArgs()->once()->andReturnSelf()
->shouldReceive('update')->with($server->id, [
'owner_id' => $data['owner_id'],
'name' => $data['name'],
'description' => $data['description'],
'daemonSecret' => 'randomString',
], true, true)->once()->andReturnNull();
$this->daemonServerRepository->shouldReceive('setNode')->andThrow($this->exception);
$this->exception->shouldReceive('getResponse')->withNoArgs()->once()->andReturnSelf()
->shouldReceive('getStatusCode')->withNoArgs()->once()->andReturn(400);
$this->database->shouldNotReceive('commit');
try {
$this->service->edit($server, $data);
} catch (Exception $exception) {
$this->assertInstanceOf(DisplayException::class, $exception);
$this->assertEquals(
trans('admin/server.exceptions.daemon_exception', ['code' => 400,]), $exception->getMessage()
);
}
}
/**
* Test that an exception not stemming from Guzzle is not thrown as a displayable exception.
*
* @expectedException \Exception
*/
public function testEditShouldNotThrowDisplayableExceptionIfExceptionIsNotThrownByGuzzle()
{
$server = factory(Server::class)->make([
'owner_id' => 1,
'node_id' => 1,
]);
$data = ['owner_id' => 2, 'name' => 'New Name', 'description' => 'New Description'];
$this->repository->shouldNotReceive('find');
$this->database->shouldReceive('beginTransaction')->withNoArgs()->once()->andReturnNull();
$this->repository->shouldReceive('withoutFresh')->withNoArgs()->once()->andReturnSelf()
->shouldReceive('update')->with($server->id, [
'owner_id' => $data['owner_id'],
'name' => $data['name'],
'description' => $data['description'],
'daemonSecret' => 'randomString',
], true, true)->once()->andReturnNull();
$this->daemonServerRepository->shouldReceive('setNode')->andThrow(new Exception());
$this->database->shouldNotReceive('commit');
$this->service->edit($server, $data);
}
/**
* Test that the docker image for a server can be updated if a model is provided.
*/
public function testDockerImageCanBeUpdatedWhenAServerModelIsProvided()
{
$server = factory(Server::class)->make(['node_id' => 1]);
$this->repository->shouldNotReceive('find');
$this->database->shouldReceive('beginTransaction')->withNoArgs()->once()->andReturnNull();
$this->repository->shouldReceive('withoutFresh')->withNoArgs()->once()->andReturnSelf()
->shouldReceive('update')->with($server->id, [
'image' => 'new/image',
])->once()->andReturnNull();
$this->daemonServerRepository->shouldReceive('setNode')->with($server->node_id)->once()->andReturnSelf()
->shouldReceive('setAccessServer')->with($server->uuid)->once()->andReturnSelf()
->shouldReceive('update')->with([
'build' => [
'image' => 'new/image',
],
])->once()->andReturnNull();
$this->database->shouldReceive('commit')->withNoArgs()->once()->andReturn(true);
$response = $this->service->setDockerImage($server, 'new/image');
$this->assertTrue($response);
}
/**
* Test that the docker image for a server can be updated if a model is provided.
*/
public function testDockerImageCanBeUpdatedWhenNoModelIsProvided()
{
$server = factory(Server::class)->make(['node_id' => 1]);
$this->repository->shouldReceive('find')->with($server->id)->once()->andReturn($server);
$this->database->shouldReceive('beginTransaction')->withNoArgs()->once()->andReturnNull();
$this->repository->shouldReceive('withoutFresh')->withNoArgs()->once()->andReturnSelf()
->shouldReceive('update')->with($server->id, [
'image' => 'new/image',
])->once()->andReturnNull();
$this->daemonServerRepository->shouldReceive('setNode')->with($server->node_id)->once()->andReturnSelf()
->shouldReceive('setAccessServer')->with($server->uuid)->once()->andReturnSelf()
->shouldReceive('update')->with([
'build' => [
'image' => 'new/image',
],
])->once()->andReturnNull();
$this->database->shouldReceive('commit')->withNoArgs()->once()->andReturn(true);
$response = $this->service->setDockerImage($server->id, 'new/image');
$this->assertTrue($response);
}
/**
* Test that an exception thrown by Guzzle is rendered as a displayable exception.
*/
public function testExceptionThrownByGuzzleWhenSettingDockerImageShouldBeRenderedAsADisplayableException()
{
$server = factory(Server::class)->make(['node_id' => 1]);
$this->database->shouldReceive('beginTransaction')->withNoArgs()->once()->andReturnNull();
$this->repository->shouldReceive('withoutFresh')->withNoArgs()->once()->andReturnSelf()
->shouldReceive('update')->with($server->id, [
'image' => 'new/image',
])->once()->andReturnNull();
$this->daemonServerRepository->shouldReceive('setNode')->andThrow($this->exception);
$this->exception->shouldReceive('getResponse')->withNoArgs()->once()->andReturnSelf()
->shouldReceive('getStatusCode')->withNoArgs()->once()->andReturn(400);
$this->database->shouldNotReceive('commit');
try {
$this->service->setDockerImage($server, 'new/image');
} catch (Exception $exception) {
$this->assertInstanceOf(DisplayException::class, $exception);
$this->assertEquals(
trans('admin/server.exceptions.daemon_exception', ['code' => 400,]), $exception->getMessage()
);
}
}
/**
* Test that an exception not thrown by Guzzle is not transformed to a displayable exception.
*
* @expectedException \Exception
*/
public function testExceptionNotThrownByGuzzleWhenSettingDockerImageShouldNotBeRenderedAsADisplayableException()
{
$server = factory(Server::class)->make(['node_id' => 1]);
$this->database->shouldReceive('beginTransaction')->withNoArgs()->once()->andReturnNull();
$this->repository->shouldReceive('withoutFresh')->withNoArgs()->once()->andReturnSelf()
->shouldReceive('update')->with($server->id, [
'image' => 'new/image',
])->once()->andReturnNull();
$this->daemonServerRepository->shouldReceive('setNode')->andThrow(new Exception());
$this->database->shouldNotReceive('commit');
$this->service->setDockerImage($server, 'new/image');
}
}

View file

@ -0,0 +1,155 @@
<?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\Unit\Services\Servers;
use Mockery as m;
use Tests\TestCase;
use Pterodactyl\Models\Server;
use Pterodactyl\Models\Location;
use Pterodactyl\Services\Servers\EnvironmentService;
use Pterodactyl\Contracts\Repository\ServerRepositoryInterface;
class EnvironmentServiceTest extends TestCase
{
/**
* @var \Pterodactyl\Contracts\Repository\ServerRepositoryInterface
*/
protected $repository;
/**
* @var \Pterodactyl\Services\Servers\EnvironmentService
*/
protected $service;
/**
* @var \Pterodactyl\Models\Server
*/
protected $server;
/**
* Setup tests.
*/
public function setUp()
{
parent::setUp();
$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.
*/
public function testSettingEnvironmentKeyShouldReturnInstanceOfSelf()
{
$instance = $this->service->setEnvironmentKey('TEST_KEY', function () {
return true;
});
$this->assertInstanceOf(EnvironmentService::class, $instance);
}
/**
* Test that environment defaults are returned by the process function.
*/
public function testProcessShouldReturnDefaultEnvironmentVariablesForAServer()
{
$this->repository->shouldReceive('getVariablesWithValues')->with($this->server->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.');
$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]);
}
}
/**
* Test that variables included at run-time are also included.
*/
public function testProcessShouldReturnKeySetAtRuntime()
{
$this->repository->shouldReceive('getVariablesWithValues')->with($this->server->id)->once()->andReturn([]);
$response = $this->service->setEnvironmentKey('TEST_VARIABLE', function ($server) {
return $server->uuidShort;
})->process($this->server);
$this->assertTrue(is_array($response), 'Assert response is an array.');
$this->assertArrayHasKey('TEST_VARIABLE', $response);
$this->assertEquals($this->server->uuidShort, $response['TEST_VARIABLE']);
}
/**
* Test that duplicate variables provided at run-time override the defaults.
*/
public function testProcessShouldAllowOverwritingDefaultVariablesWithRuntimeProvided()
{
$this->repository->shouldReceive('getVariablesWithValues')->with($this->server->id)->once()->andReturn([]);
$response = $this->service->setEnvironmentKey('P_SERVER_UUID', function ($server) {
return 'overwritten';
})->process($this->server);
$this->assertTrue(is_array($response), 'Assert response is an array.');
$this->assertArrayHasKey('P_SERVER_UUID', $response);
$this->assertEquals('overwritten', $response['P_SERVER_UUID']);
}
/**
* Test that function can run when an ID is provided rather than a server model.
*/
public function testProcessShouldAcceptAnIntegerInPlaceOfAServerModel()
{
$this->repository->shouldReceive('find')->with($this->server->id)->once()->andReturn($this->server);
$this->repository->shouldReceive('getVariablesWithValues')->with($this->server->id)->once()->andReturn([]);
$response = $this->service->process($this->server->id);
$this->assertTrue(is_array($response), 'Assert that response is an array.');
}
/**
* Test that an exception is thrown when no model or valid ID is provided.
*
* @expectedException \InvalidArgumentException
*/
public function testProcessShouldThrowExceptionIfInvalidServerIsProvided()
{
$this->service->process('abcd');
}
}

View file

@ -0,0 +1,127 @@
<?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\Unit\Services\Servers;
use Tests\TestCase;
use phpmock\phpunit\PHPMock;
use Pterodactyl\Services\Servers\UsernameGenerationService;
class UsernameGenerationServiceTest extends TestCase
{
use PHPMock;
/**
* @var UsernameGenerationService
*/
protected $service;
/**
* Setup tests.
*/
public function setUp()
{
parent::setUp();
$this->service = new UsernameGenerationService();
$this->getFunctionMock('\\Pterodactyl\\Services\\Servers', 'bin2hex')
->expects($this->any())->willReturn('dddddddd');
$this->getFunctionMock('\\Pterodactyl\\Services\\Servers', 'str_random')
->expects($this->any())->willReturnCallback(function ($count) {
return str_pad('', $count, 'a');
});
}
/**
* Test that a valid username is returned and is the correct length.
*/
public function testShouldReturnAValidUsernameWithASelfGeneratedIdentifier()
{
$response = $this->service->generate('testname');
$this->assertEquals('testna_dddddddd', $response);
}
/**
* Test that a name and identifier provided returns the expected username.
*/
public function testShouldReturnAValidUsernameWithAnIdentifierProvided()
{
$response = $this->service->generate('testname', 'identifier');
$this->assertEquals('testna_identifi', $response);
}
/**
* Test that the identifier is extended to 8 characters if it is shorter.
*/
public function testShouldExtendIdentifierToBe8CharactersIfItIsShorter()
{
$response = $this->service->generate('testname', 'xyz');
$this->assertEquals('testna_xyzaaaaa', $response);
}
/**
* Test that special characters are removed from the username.
*/
public function testShouldStripSpecialCharactersFromName()
{
$response = $this->service->generate('te!st_n$ame', 'identifier');
$this->assertEquals('testna_identifi', $response);
}
/**
* Test that an empty name is replaced with 6 random characters.
*/
public function testEmptyNamesShouldBeReplacedWithRandomCharacters()
{
$response = $this->service->generate('');
$this->assertEquals('aaaaaa_dddddddd', $response);
}
/**
* Test that a name consisting entirely of special characters is handled.
*/
public function testNameOfOnlySpecialCharactersIsHandledProperly()
{
$response = $this->service->generate('$%#*#(@#(#*$&#(#!#@');
$this->assertEquals('aaaaaa_dddddddd', $response);
}
/**
* Test that passing a name shorter than 6 characters returns the entire name.
*/
public function testNameShorterThan6CharactersShouldBeRenderedEntirely()
{
$response = $this->service->generate('test', 'identifier');
$this->assertEquals('test_identifi', $response);
}
}

View file

@ -0,0 +1,243 @@
<?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\Unit\Services\Servers;
use Mockery as m;
use Tests\TestCase;
use Pterodactyl\Models\ServiceVariable;
use Illuminate\Contracts\Validation\Factory;
use Pterodactyl\Exceptions\DisplayValidationException;
use Pterodactyl\Services\Servers\VariableValidatorService;
use Pterodactyl\Contracts\Repository\ServerRepositoryInterface;
use Pterodactyl\Contracts\Repository\OptionVariableRepositoryInterface;
use Pterodactyl\Contracts\Repository\ServerVariableRepositoryInterface;
class VariableValidatorServiceTest extends TestCase
{
/**
* @var \Pterodactyl\Contracts\Repository\OptionVariableRepositoryInterface
*/
protected $optionVariableRepository;
/**
* @var \Pterodactyl\Contracts\Repository\ServerRepositoryInterface
*/
protected $serverRepository;
/**
* @var \Pterodactyl\Contracts\Repository\ServerVariableRepositoryInterface
*/
protected $serverVariableRepository;
/**
* @var \Pterodactyl\Services\Servers\VariableValidatorService
*/
protected $service;
/**
* @var \Illuminate\Validation\Factory
*/
protected $validator;
/**
* @var \Illuminate\Support\Collection
*/
protected $variables;
/**
* Setup tests.
*/
public function setUp()
{
parent::setUp();
$this->variables = collect(
[
factory(ServiceVariable::class)->states('editable', 'viewable')->make(),
factory(ServiceVariable::class)->states('viewable')->make(),
factory(ServiceVariable::class)->states('editable')->make(),
factory(ServiceVariable::class)->make(),
]
);
$this->optionVariableRepository = m::mock(OptionVariableRepositoryInterface::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->setAdmin();
$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));
}
/**
* Test that when no variables are found for an option no data is returned.
*/
public function testEmptyResultSetShouldBeReturnedIfNoVariablesAreFound()
{
$this->optionVariableRepository->shouldReceive('findWhere')->with([['option_id', '=', 1]])->andReturn([]);
$response = $this->service->validate(1);
$this->assertInstanceOf(VariableValidatorService::class, $response);
$this->assertTrue(is_array($response->getResults()));
$this->assertEmpty($response->getResults());
}
/**
* Test that variables set as user_editable=0 and/or user_viewable=0 are skipped when admin flag is not set.
*/
public function testValidatorShouldNotProcessVariablesSetAsNotUserEditableWhenAdminFlagIsNotPassed()
{
$this->optionVariableRepository->shouldReceive('findWhere')->with([['option_id', '=', 1]])->andReturn($this->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);
$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();
$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->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']);
}
/**
* Test that all variables are processed correctly if admin flag is set.
*/
public function testValidatorShouldProcessAllVariablesWhenAdminFlagIsSet()
{
$this->optionVariableRepository->shouldReceive('findWhere')->with([['option_id', '=', 1]])->andReturn($this->variables);
foreach($this->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);
}
$response = $this->service->setAdmin()->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();
$this->assertEquals(4, count($response), 'Assert response has all four items in array.');
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']);
}
}
/**
* Test that a DisplayValidationError is thrown when a variable is not validated.
*/
public function testValidatorShouldThrowExceptionWhenAValidationErrorIsEncountered()
{
$this->optionVariableRepository->shouldReceive('findWhere')->with([['option_id', '=', 1]])->andReturn($this->variables);
$this->validator->shouldReceive('make')->with([
'variable_value' => null,
], [
'variable_value' => $this->variables{0}->rules,
])->once()->andReturnSelf()
->shouldReceive('fails')->withNoArgs()->once()->andReturn(true);
$this->validator->shouldReceive('errors')->withNoArgs()->once()->andReturnSelf()
->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->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]),
$decoded->notice[0]
);
}
}
}