Fixed whitespace

This commit is contained in:
rr- 2015-11-25 09:48:03 +01:00
parent b8f90dbd95
commit 13d77dd14a
57 changed files with 3545 additions and 3539 deletions

View file

@ -145,12 +145,6 @@
<!-- Indentation --> <!-- Indentation -->
<!-- **************** --> <!-- **************** -->
<!-- Tests to make sure that a line does not contain the tab character. -->
<test name="indentation"> <!-- noTabs -->
<property name="type" value="tabs"/> <!-- tabs or spaces -->
<property name="number" value="4"/> <!-- number of spaces if type = spaces -->
</test>
<!-- Check the position of the open curly brace in a control structure (if) --> <!-- Check the position of the open curly brace in a control structure (if) -->
<!-- sl = same line --> <!-- sl = same line -->
<!-- nl = new line --> <!-- nl = new line -->

View file

@ -70,9 +70,9 @@ class FileDao implements IFileDao
$from = explode('/', str_replace('\\', '/', $from)); $from = explode('/', str_replace('\\', '/', $from));
$to = explode('/', str_replace('\\', '/', $to)); $to = explode('/', str_replace('\\', '/', $to));
$relPath = $to; $relPath = $to;
foreach($from as $depth => $dir) foreach ($from as $depth => $dir)
{ {
if($dir === $to[$depth]) if ($dir === $to[$depth])
{ {
array_shift($relPath); array_shift($relPath);
} }

View file

@ -108,7 +108,7 @@ class EnumHelper
throw new \DomainException(sprintf( throw new \DomainException(sprintf(
'Unrecognized value: %s.' . PHP_EOL . 'Possible values: %s', 'Unrecognized value: %s.' . PHP_EOL . 'Possible values: %s',
$enumString, $enumString,
join(', ', array_keys($lowerEnumMap)))); implode(', ', array_keys($lowerEnumMap))));
} }
return $lowerEnumMap[$key]; return $lowerEnumMap[$key];

View file

@ -39,7 +39,7 @@ class HttpHelper
$result = []; $result = [];
foreach ($_SERVER as $key => $value) foreach ($_SERVER as $key => $value)
{ {
if (substr($key, 0, 5) == "HTTP_") if (substr($key, 0, 5) === "HTTP_")
{ {
$key = str_replace(" ", "-", ucwords(strtolower(str_replace("_", " ", substr($key, 5))))); $key = str_replace(" ", "-", ucwords(strtolower(str_replace("_", " ", substr($key, 5)))));
$result[$key] = $value; $result[$key] = $value;

View file

@ -33,7 +33,12 @@ abstract class AbstractSearchParserConfig
throw new NotSupportedException('Unknown order term: ' . $tokenValue throw new NotSupportedException('Unknown order term: ' . $tokenValue
. '. Possible order terms: ' . '. Possible order terms: '
. join(', ', array_map(function($term) { return join('/', $term[0]); }, $map))); . implode(
', ',
array_map(function($term)
{
return implode('/', $term[0]);
}, $map)));
} }
public function getRequirementForBasicToken(SearchToken $token) public function getRequirementForBasicToken(SearchToken $token)
@ -118,7 +123,7 @@ abstract class AbstractSearchParserConfig
protected function defineOrder($columnName, array $aliases) protected function defineOrder($columnName, array $aliases)
{ {
$this->orderAliasMap []= [$aliases, $columnName]; $this->orderAliasMap[] = [$aliases, $columnName];
} }
protected function defineBasicTokenParser($parser) protected function defineBasicTokenParser($parser)
@ -135,7 +140,7 @@ abstract class AbstractSearchParserConfig
$item->columnName = $columnName; $item->columnName = $columnName;
$item->aliases = $aliases; $item->aliases = $aliases;
$item->flagsOrCallback = $flagsOrCallback; $item->flagsOrCallback = $flagsOrCallback;
$this->namedTokenParsers []= $item; $this->namedTokenParsers[] = $item;
} }
protected function defineSpecialTokenParser( protected function defineSpecialTokenParser(
@ -145,7 +150,7 @@ abstract class AbstractSearchParserConfig
$item = new \StdClass; $item = new \StdClass;
$item->aliases = $aliases; $item->aliases = $aliases;
$item->callback = $callback; $item->callback = $callback;
$this->specialTokenParsers []= $item; $this->specialTokenParsers[] = $item;
} }
protected static function createRequirementValue( protected static function createRequirementValue(
@ -261,6 +266,11 @@ abstract class AbstractSearchParserConfig
throw new NotSupportedException( throw new NotSupportedException(
'Unknown search key: ' . $key 'Unknown search key: ' . $key
. '. Possible search keys: ' . '. Possible search keys: '
. join(', ', array_map(function($item) { return join('/', $item->aliases); }, $parsers))); . implode(
', ',
array_map(function($item)
{
return implode('/', $item->aliases);
}, $parsers)));
} }
} }

View file

@ -90,7 +90,7 @@ class SearchParser
if ($negated) if ($negated)
{ {
$orderDir = $orderDir == IFilter::ORDER_DESC $orderDir = $orderDir === IFilter::ORDER_DESC
? IFilter::ORDER_ASC ? IFilter::ORDER_ASC
: IFilter::ORDER_DESC; : IFilter::ORDER_DESC;
} }

View file

@ -106,7 +106,7 @@ class HistoryService
foreach ($base[$key] as $subValue) foreach ($base[$key] as $subValue)
{ {
if (!isset($other[$key]) || !in_array($subValue, $other[$key])) if (!isset($other[$key]) || !in_array($subValue, $other[$key]))
$result[$key] []= $subValue; $result[$key][] = $subValue;
} }
if (empty($result[$key])) if (empty($result[$key]))
unset($result[$key]); unset($result[$key]);

View file

@ -110,11 +110,11 @@ class ImageConverter
private function convertWithPrograms($programs, $targetPath) private function convertWithPrograms($programs, $targetPath)
{ {
$any_program_available = false; $anyProgramAvailable = false;
foreach ($programs as $program => $args) foreach ($programs as $program => $args)
$any_program_available |= ProgramExecutor::isProgramAvailable($program); $anyProgramAvailable |= ProgramExecutor::isProgramAvailable($program);
if (!$any_program_available) if (!$anyProgramAvailable)
throw new \Exception('No converter available (tried ' . join(', ', array_keys($programs)) . ')'); throw new \Exception('No converter available (tried ' . implode(', ', array_keys($programs)) . ')');
$errors = []; $errors = [];
foreach ($programs as $program => $args) foreach ($programs as $program => $args)
@ -127,7 +127,7 @@ class ImageConverter
} }
} }
throw new \Exception('Error while converting file to image: ' . join(', ', $errors)); throw new \Exception('Error while converting file to image: ' . implode(', ', $errors));
} }
private function deleteIfExists($path) private function deleteIfExists($path)

View file

@ -7,7 +7,7 @@ class ImagickImageManipulator implements IImageManipulator
{ {
$image = new \Imagick(); $image = new \Imagick();
$image->readImageBlob($source); $image->readImageBlob($source);
if ($image->getImageFormat() == 'GIF') if ($image->getImageFormat() === 'GIF')
$image = $image->coalesceImages(); $image = $image->coalesceImages();
return $image; return $image;
} }

View file

@ -22,7 +22,7 @@ class Upgrade34 implements IUpgrade
{ {
if (!is_array($target)) if (!is_array($target))
$target = [$target]; $target = [$target];
$target []= $item[1]; $target[] = $item[1];
} }
else else
{ {

View file

@ -41,7 +41,9 @@ class Upgrade38 implements IUpgrade
$post->setContentType(Post::POST_TYPE_ANIMATED_IMAGE); $post->setContentType(Post::POST_TYPE_ANIMATED_IMAGE);
$this->postDao->save($post); $this->postDao->save($post);
} }
if (++ $progress == 100)
$progress++;
if ($progress === 100)
{ {
echo '.'; echo '.';
$progress = 0; $progress = 0;

View file

@ -11,58 +11,58 @@ use Szurubooru\Tests\AbstractTestCase;
abstract class AbstractDatabaseTestCase extends AbstractTestCase abstract class AbstractDatabaseTestCase extends AbstractTestCase
{ {
protected $databaseConnection; protected $databaseConnection;
public function setUp() public function setUp()
{ {
parent::setUp(); parent::setUp();
$realConfig = Injector::get(Config::class); $realConfig = Injector::get(Config::class);
$config = $this->mockConfig($this->createTestDirectory()); $config = $this->mockConfig($this->createTestDirectory());
$config->set('database/dsn', $realConfig->database->tests->dsn); $config->set('database/dsn', $realConfig->database->tests->dsn);
$config->set('database/user', $realConfig->database->tests->user); $config->set('database/user', $realConfig->database->tests->user);
$config->set('database/password', $realConfig->database->tests->password); $config->set('database/password', $realConfig->database->tests->password);
$this->databaseConnection = new DatabaseConnection($config); $this->databaseConnection = new DatabaseConnection($config);
$this->databaseConnection->getPDO()->exec('USE szuru_test'); $this->databaseConnection->getPDO()->exec('USE szuru_test');
$this->databaseConnection->getPDO()->beginTransaction(); $this->databaseConnection->getPDO()->beginTransaction();
Injector::set(DatabaseConnection::class, $this->databaseConnection); Injector::set(DatabaseConnection::class, $this->databaseConnection);
} }
public function tearDown() public function tearDown()
{ {
$this->databaseConnection->getPDO()->rollBack(); $this->databaseConnection->getPDO()->rollBack();
parent::tearDown(); parent::tearDown();
if ($this->databaseConnection) if ($this->databaseConnection)
$this->databaseConnection->close(); $this->databaseConnection->close();
} }
protected static function getTestTag($name = 'test') protected static function getTestTag($name = 'test')
{ {
$tag = new Tag(); $tag = new Tag();
$tag->setName($name); $tag->setName($name);
$tag->setCreationTime(date('c')); $tag->setCreationTime(date('c'));
return $tag; return $tag;
} }
protected static function getTestPost() protected static function getTestPost()
{ {
$post = new Post(); $post = new Post();
$post->setName('test'); $post->setName('test');
$post->setUploadTime(date('c')); $post->setUploadTime(date('c'));
$post->setSafety(Post::POST_SAFETY_SAFE); $post->setSafety(Post::POST_SAFETY_SAFE);
$post->setContentType(Post::POST_TYPE_YOUTUBE); $post->setContentType(Post::POST_TYPE_YOUTUBE);
$post->setContentChecksum('whatever'); $post->setContentChecksum('whatever');
return $post; return $post;
} }
protected static function getTestUser($userName = 'test') protected static function getTestUser($userName = 'test')
{ {
$user = new User(); $user = new User();
$user->setName($userName); $user->setName($userName);
$user->setPasswordHash('whatever'); $user->setPasswordHash('whatever');
$user->setLastLoginTime(date('c', mktime(1, 2, 3))); $user->setLastLoginTime(date('c', mktime(1, 2, 3)));
$user->setRegistrationTime(date('c', mktime(3, 2, 1))); $user->setRegistrationTime(date('c', mktime(3, 2, 1)));
$user->setAccessRank(User::ACCESS_RANK_REGULAR_USER); $user->setAccessRank(User::ACCESS_RANK_REGULAR_USER);
return $user; return $user;
} }
} }

View file

@ -5,73 +5,73 @@ use Szurubooru\Injector;
abstract class AbstractTestCase extends \PHPUnit_Framework_TestCase abstract class AbstractTestCase extends \PHPUnit_Framework_TestCase
{ {
protected function setUp() protected function setUp()
{ {
Injector::init(); Injector::init();
date_default_timezone_set('UTC'); date_default_timezone_set('UTC');
} }
protected function tearDown() protected function tearDown()
{ {
TestHelper::cleanTestDirectory(); TestHelper::cleanTestDirectory();
} }
protected function mock($className) protected function mock($className)
{ {
return $this->getMockBuilder($className)->disableOriginalConstructor()->getMock(); return $this->getMockBuilder($className)->disableOriginalConstructor()->getMock();
} }
protected function mockTransactionManager() protected function mockTransactionManager()
{ {
return new TransactionManagerMock($this->mock(DatabaseConnection::class)); return new TransactionManagerMock($this->mock(DatabaseConnection::class));
} }
protected function mockConfig($dataPath = null, $publicDataPath = null) protected function mockConfig($dataPath = null, $publicDataPath = null)
{ {
return TestHelper::mockConfig($dataPath, $publicDataPath); return TestHelper::mockConfig($dataPath, $publicDataPath);
} }
protected function createTestDirectory() protected function createTestDirectory()
{ {
return TestHelper::createTestDirectory(); return TestHelper::createTestDirectory();
} }
protected function getTestFile($fileName) protected function getTestFile($fileName)
{ {
return TestHelper::getTestFile($fileName); return TestHelper::getTestFile($fileName);
} }
protected function getTestFilePath($fileName) protected function getTestFilePath($fileName)
{ {
return TestHelper::getTestFilePath($fileName); return TestHelper::getTestFilePath($fileName);
} }
protected function assertEntitiesEqual($expected, $actual) protected function assertEntitiesEqual($expected, $actual)
{ {
if (!is_array($expected)) if (!is_array($expected))
{ {
$expected = [$expected]; $expected = [$expected];
$actual = [$actual]; $actual = [$actual];
} }
$this->assertEquals(count($expected), count($actual), 'Unmatching array sizes'); $this->assertEquals(count($expected), count($actual), 'Unmatching array sizes');
$this->assertEquals(array_keys($expected), array_keys($actual), 'Unmatching array keys'); $this->assertEquals(array_keys($expected), array_keys($actual), 'Unmatching array keys');
foreach (array_keys($expected) as $key) foreach (array_keys($expected) as $key)
{ {
if ($expected[$key] === null) if ($expected[$key] === null)
{ {
$this->assertNull($actual[$key]); $this->assertNull($actual[$key]);
} }
else else
{ {
$this->assertNotNull($actual[$key]); $this->assertNotNull($actual[$key]);
$expectedEntity = clone($expected[$key]); $expectedEntity = clone($expected[$key]);
$actualEntity = clone($actual[$key]); $actualEntity = clone($actual[$key]);
$expectedEntity->resetLazyLoaders(); $expectedEntity->resetLazyLoaders();
$expectedEntity->resetMeta(); $expectedEntity->resetMeta();
$actualEntity->resetLazyLoaders(); $actualEntity->resetLazyLoaders();
$actualEntity->resetMeta(); $actualEntity->resetMeta();
$this->assertEquals($expectedEntity, $actualEntity); $this->assertEquals($expectedEntity, $actualEntity);
} }
} }
} }
} }

View file

@ -4,17 +4,17 @@ use Szurubooru\Config;
final class ConfigMock extends Config final class ConfigMock extends Config
{ {
public function set($key, $value) public function set($key, $value)
{ {
$keys = preg_split('/[\\/]/', $key); $keys = preg_split('/[\\/]/', $key);
$current = $this; $current = $this;
$lastKey = array_pop($keys); $lastKey = array_pop($keys);
foreach ($keys as $key) foreach ($keys as $key)
{ {
if (!isset($current->$key)) if (!isset($current->$key))
$current->$key = new \ArrayObject([], \ArrayObject::ARRAY_AS_PROPS); $current->$key = new \ArrayObject([], \ArrayObject::ARRAY_AS_PROPS);
$current = $current->$key; $current = $current->$key;
} }
$current->$lastKey = $value; $current->$lastKey = $value;
} }
} }

View file

@ -5,81 +5,81 @@ use Szurubooru\Tests\AbstractTestCase;
final class ConfigTest extends AbstractTestCase final class ConfigTest extends AbstractTestCase
{ {
private $testDirectory; private $testDirectory;
private $baseConfigFilePath; private $baseConfigFilePath;
private $localConfigFilePath; private $localConfigFilePath;
public function setUp() public function setUp()
{ {
parent::setUp(); parent::setUp();
$this->testDirectory = $this->createTestDirectory(); $this->testDirectory = $this->createTestDirectory();
$this->baseConfigFilePath = $this->testDirectory . DIRECTORY_SEPARATOR . 'config.ini'; $this->baseConfigFilePath = $this->testDirectory . DIRECTORY_SEPARATOR . 'config.ini';
$this->localConfigFilePath = $this->testDirectory . DIRECTORY_SEPARATOR . 'local.ini'; $this->localConfigFilePath = $this->testDirectory . DIRECTORY_SEPARATOR . 'local.ini';
} }
public function testReadingNonSections() public function testReadingNonSections()
{ {
file_put_contents($this->baseConfigFilePath, 'test=value'); file_put_contents($this->baseConfigFilePath, 'test=value');
$config = $this->getTestConfig(); $config = $this->getTestConfig();
$this->assertEquals('value', $config->test); $this->assertEquals('value', $config->test);
} }
public function testReadingUnnestedSections() public function testReadingUnnestedSections()
{ {
file_put_contents($this->baseConfigFilePath, '[test]' . PHP_EOL . 'key=value'); file_put_contents($this->baseConfigFilePath, '[test]' . PHP_EOL . 'key=value');
$config = $this->getTestConfig(); $config = $this->getTestConfig();
$this->assertEquals('value', $config->test->key); $this->assertEquals('value', $config->test->key);
} }
public function testReadingNestedSections() public function testReadingNestedSections()
{ {
file_put_contents($this->baseConfigFilePath, '[test.subtest]' . PHP_EOL . 'key=value'); file_put_contents($this->baseConfigFilePath, '[test.subtest]' . PHP_EOL . 'key=value');
$config = $this->getTestConfig(); $config = $this->getTestConfig();
$this->assertEquals('value', $config->test->subtest->key); $this->assertEquals('value', $config->test->subtest->key);
} }
public function testReadingMultipleNestedSections() public function testReadingMultipleNestedSections()
{ {
file_put_contents( file_put_contents(
$this->baseConfigFilePath, $this->baseConfigFilePath,
'[test.subtest]' . PHP_EOL . 'key=value' . PHP_EOL . '[test.subtest]' . PHP_EOL . 'key=value' . PHP_EOL .
'[test.subtest.deeptest]' . PHP_EOL . 'key=zombie'); '[test.subtest.deeptest]' . PHP_EOL . 'key=zombie');
$config = $this->getTestConfig(); $config = $this->getTestConfig();
$this->assertEquals('value', $config->test->subtest->key); $this->assertEquals('value', $config->test->subtest->key);
$this->assertEquals('zombie', $config->test->subtest->deeptest->key); $this->assertEquals('zombie', $config->test->subtest->deeptest->key);
} }
public function testReadingNonExistentFiles() public function testReadingNonExistentFiles()
{ {
$config = $this->getTestConfig(); $config = $this->getTestConfig();
$this->assertEquals(0, count(iterator_to_array($config->getIterator()))); $this->assertEquals(0, count(iterator_to_array($config->getIterator())));
} }
public function testMultipleFiles() public function testMultipleFiles()
{ {
file_put_contents($this->baseConfigFilePath, 'test=trash'); file_put_contents($this->baseConfigFilePath, 'test=trash');
file_put_contents($this->localConfigFilePath, 'test=overridden'); file_put_contents($this->localConfigFilePath, 'test=overridden');
$config = $this->getTestConfig(); $config = $this->getTestConfig();
$this->assertEquals('overridden', $config->test); $this->assertEquals('overridden', $config->test);
} }
public function testReadingUnexistingProperties() public function testReadingUnexistingProperties()
{ {
file_put_contents($this->baseConfigFilePath, 'meh=value'); file_put_contents($this->baseConfigFilePath, 'meh=value');
$config = $this->getTestConfig(); $config = $this->getTestConfig();
$this->assertNull($config->unexistingSection); $this->assertNull($config->unexistingSection);
} }
public function testOverwritingValues() public function testOverwritingValues()
{ {
file_put_contents($this->baseConfigFilePath, 'meh=value'); file_put_contents($this->baseConfigFilePath, 'meh=value');
$config = $this->getTestConfig(); $config = $this->getTestConfig();
$config->newKey = 'fast'; $config->newKey = 'fast';
$this->assertEquals('fast', $config->newKey); $this->assertEquals('fast', $config->newKey);
} }
private function getTestConfig() private function getTestConfig()
{ {
return new Config($this->testDirectory, null); return new Config($this->testDirectory, null);
} }
} }

View file

@ -11,115 +11,115 @@ use Szurubooru\Tests\AbstractDatabaseTestCase;
final class CommentDaoTest extends AbstractDatabaseTestCase final class CommentDaoTest extends AbstractDatabaseTestCase
{ {
private $userDaoMock; private $userDaoMock;
private $postDaoMock; private $postDaoMock;
public function setUp() public function setUp()
{ {
parent::setUp(); parent::setUp();
$this->userDaoMock = $this->mock(UserDao::class); $this->userDaoMock = $this->mock(UserDao::class);
$this->postDaoMock = $this->mock(PostDao::class); $this->postDaoMock = $this->mock(PostDao::class);
} }
public function testSaving() public function testSaving()
{ {
$user = new User(1); $user = new User(1);
$user->setName('olivia'); $user->setName('olivia');
$post = new Post(2); $post = new Post(2);
$post->setName('sword'); $post->setName('sword');
$comment = new Comment(); $comment = new Comment();
$comment->setUser($user); $comment->setUser($user);
$comment->setPost($post); $comment->setPost($post);
$comment->setCreationTime(date('c')); $comment->setCreationTime(date('c'));
$comment->setLastEditTime(date('c')); $comment->setLastEditTime(date('c'));
$comment->setText('whatever'); $comment->setText('whatever');
$commentDao = $this->getCommentDao(); $commentDao = $this->getCommentDao();
$commentDao->save($comment); $commentDao->save($comment);
$this->userDaoMock->expects($this->once())->method('findById')->with(1)->willReturn($user); $this->userDaoMock->expects($this->once())->method('findById')->with(1)->willReturn($user);
$this->postDaoMock->expects($this->once())->method('findById')->with(2)->willReturn($post); $this->postDaoMock->expects($this->once())->method('findById')->with(2)->willReturn($post);
$savedComment = $commentDao->findById($comment->getId()); $savedComment = $commentDao->findById($comment->getId());
$this->assertEquals(1, $savedComment->getUserId()); $this->assertEquals(1, $savedComment->getUserId());
$this->assertEquals(2, $savedComment->getPostId()); $this->assertEquals(2, $savedComment->getPostId());
$this->assertEquals($comment->getCreationTime(), $savedComment->getCreationTime()); $this->assertEquals($comment->getCreationTime(), $savedComment->getCreationTime());
$this->assertEquals($comment->getLastEditTime(), $savedComment->getLastEditTime()); $this->assertEquals($comment->getLastEditTime(), $savedComment->getLastEditTime());
$this->assertEquals($comment->getText(), $savedComment->getText()); $this->assertEquals($comment->getText(), $savedComment->getText());
$this->assertEntitiesEqual($user, $savedComment->getUser()); $this->assertEntitiesEqual($user, $savedComment->getUser());
$this->assertEntitiesEqual($post, $savedComment->getPost()); $this->assertEntitiesEqual($post, $savedComment->getPost());
} }
public function testPostMetadataSyncInsert() public function testPostMetadataSyncInsert()
{ {
$userDao = Injector::get(UserDao::class); $userDao = Injector::get(UserDao::class);
$postDao = Injector::get(PostDao::class); $postDao = Injector::get(PostDao::class);
$commentDao = Injector::get(CommentDao::class); $commentDao = Injector::get(CommentDao::class);
$user = self::getTestUser('olivia'); $user = self::getTestUser('olivia');
$userDao->save($user); $userDao->save($user);
$post = self::getTestPost(); $post = self::getTestPost();
$postDao->save($post); $postDao->save($post);
$this->assertEquals(0, $post->getCommentCount()); $this->assertEquals(0, $post->getCommentCount());
$this->assertNotNull($post->getId()); $this->assertNotNull($post->getId());
$comment = new Comment(); $comment = new Comment();
$comment->setUser($user); $comment->setUser($user);
$comment->setPost($post); $comment->setPost($post);
$comment->setCreationTime(date('c')); $comment->setCreationTime(date('c'));
$comment->setLastEditTime(date('c')); $comment->setLastEditTime(date('c'));
$comment->setText('whatever'); $comment->setText('whatever');
$commentDao->save($comment); $commentDao->save($comment);
$post = $postDao->findById($post->getId()); $post = $postDao->findById($post->getId());
$this->assertNotNull($post); $this->assertNotNull($post);
$this->assertEquals(1, $post->getCommentCount()); $this->assertEquals(1, $post->getCommentCount());
} }
public function testPostMetadataSyncDelete() public function testPostMetadataSyncDelete()
{ {
$userDao = Injector::get(UserDao::class); $userDao = Injector::get(UserDao::class);
$postDao = Injector::get(PostDao::class); $postDao = Injector::get(PostDao::class);
$commentDao = Injector::get(CommentDao::class); $commentDao = Injector::get(CommentDao::class);
$user = self::getTestUser('olivia'); $user = self::getTestUser('olivia');
$userDao->save($user); $userDao->save($user);
$post = self::getTestPost(); $post = self::getTestPost();
$postDao->save($post); $postDao->save($post);
$this->assertEquals(0, $post->getCommentCount()); $this->assertEquals(0, $post->getCommentCount());
$this->assertNotNull($post->getId()); $this->assertNotNull($post->getId());
$comment = new Comment(); $comment = new Comment();
$comment->setUser($user); $comment->setUser($user);
$comment->setPost($post); $comment->setPost($post);
$comment->setCreationTime(date('c')); $comment->setCreationTime(date('c'));
$comment->setLastEditTime(date('c')); $comment->setLastEditTime(date('c'));
$comment->setText('whatever'); $comment->setText('whatever');
$commentDao->save($comment); $commentDao->save($comment);
$commentDao->deleteById($comment->getId()); $commentDao->deleteById($comment->getId());
$this->assertNotNull($post->getId()); $this->assertNotNull($post->getId());
$post = $postDao->findById($post->getId()); $post = $postDao->findById($post->getId());
$this->assertNotNull($post); $this->assertNotNull($post);
$this->assertEquals(0, $post->getCommentCount()); $this->assertEquals(0, $post->getCommentCount());
} }
public function findByPost(Post $post) public function findByPost(Post $post)
{ {
return $this->findOneBy('postId', $post->getId()); return $this->findOneBy('postId', $post->getId());
} }
private function getCommentDao() private function getCommentDao()
{ {
return new CommentDao( return new CommentDao(
$this->databaseConnection, $this->databaseConnection,
$this->userDaoMock, $this->userDaoMock,
$this->postDaoMock); $this->postDaoMock);
} }
} }

View file

@ -9,41 +9,41 @@ use Szurubooru\Tests\AbstractDatabaseTestCase;
final class FavoritesDaoTest extends AbstractDatabaseTestCase final class FavoritesDaoTest extends AbstractDatabaseTestCase
{ {
private $timeServiceMock; private $timeServiceMock;
public function setUp() public function setUp()
{ {
parent::setUp(); parent::setUp();
$this->timeServiceMock = $this->mock(TimeService::class); $this->timeServiceMock = $this->mock(TimeService::class);
} }
public function testSaving() public function testSaving()
{ {
$user = new User(1); $user = new User(1);
$user->setName('olivia'); $user->setName('olivia');
$post = new Post(2); $post = new Post(2);
$post->setName('sword'); $post->setName('sword');
$favorite = new Favorite(); $favorite = new Favorite();
$favorite->setUserId($user->getId()); $favorite->setUserId($user->getId());
$favorite->setPostId($post->getId()); $favorite->setPostId($post->getId());
$favorite->setTime(date('c')); $favorite->setTime(date('c'));
$favoritesDao = $this->getFavoritesDao(); $favoritesDao = $this->getFavoritesDao();
$favoritesDao->save($favorite); $favoritesDao->save($favorite);
$savedFavorite = $favoritesDao->findById($favorite->getId()); $savedFavorite = $favoritesDao->findById($favorite->getId());
$this->assertEquals(1, $savedFavorite->getUserId()); $this->assertEquals(1, $savedFavorite->getUserId());
$this->assertEquals(2, $savedFavorite->getPostId()); $this->assertEquals(2, $savedFavorite->getPostId());
$this->assertEquals($favorite->getTime(), $savedFavorite->getTime()); $this->assertEquals($favorite->getTime(), $savedFavorite->getTime());
$this->assertEquals($user->getId(), $savedFavorite->getUserId()); $this->assertEquals($user->getId(), $savedFavorite->getUserId());
$this->assertEquals($post->getId(), $savedFavorite->getPostId()); $this->assertEquals($post->getId(), $savedFavorite->getPostId());
} }
private function getFavoritesDao() private function getFavoritesDao()
{ {
return new FavoritesDao( return new FavoritesDao(
$this->databaseConnection, $this->databaseConnection,
$this->timeServiceMock); $this->timeServiceMock);
} }
} }

View file

@ -5,57 +5,57 @@ use Szurubooru\Tests\AbstractTestCase;
final class FileDaoTest extends AbstractTestCase final class FileDaoTest extends AbstractTestCase
{ {
public function testSaving() public function testSaving()
{ {
$testDirectory = $this->createTestDirectory(); $testDirectory = $this->createTestDirectory();
$fileDao = new FileDao($testDirectory); $fileDao = new FileDao($testDirectory);
$fileDao->save('dog.txt', 'awesome dog'); $fileDao->save('dog.txt', 'awesome dog');
$expected = 'awesome dog'; $expected = 'awesome dog';
$actual = file_get_contents($testDirectory . DIRECTORY_SEPARATOR . 'dog.txt'); $actual = file_get_contents($testDirectory . DIRECTORY_SEPARATOR . 'dog.txt');
$this->assertEquals($expected, $actual); $this->assertEquals($expected, $actual);
} }
public function testSavingSubfolders() public function testSavingSubfolders()
{ {
$testDirectory = $this->createTestDirectory(); $testDirectory = $this->createTestDirectory();
$fileDao = new FileDao($testDirectory); $fileDao = new FileDao($testDirectory);
$fileDao->save('friends/dog.txt', 'hot dog'); $fileDao->save('friends/dog.txt', 'hot dog');
$expected = 'hot dog'; $expected = 'hot dog';
$actual = file_get_contents($testDirectory . DIRECTORY_SEPARATOR . 'friends/dog.txt'); $actual = file_get_contents($testDirectory . DIRECTORY_SEPARATOR . 'friends/dog.txt');
$this->assertEquals($expected, $actual); $this->assertEquals($expected, $actual);
} }
public function testLoading() public function testLoading()
{ {
$testDirectory = $this->createTestDirectory(); $testDirectory = $this->createTestDirectory();
$fileDao = new FileDao($testDirectory); $fileDao = new FileDao($testDirectory);
$fileDao->save('dog.txt', 'awesome dog'); $fileDao->save('dog.txt', 'awesome dog');
$this->assertEquals('awesome dog', $fileDao->load('dog.txt')); $this->assertEquals('awesome dog', $fileDao->load('dog.txt'));
} }
public function testExists() public function testExists()
{ {
$testDirectory = $this->createTestDirectory(); $testDirectory = $this->createTestDirectory();
$fileDao = new FileDao($testDirectory); $fileDao = new FileDao($testDirectory);
$fileDao->save('dog.txt', 'awesome dog'); $fileDao->save('dog.txt', 'awesome dog');
$this->assertTrue($fileDao->exists('dog.txt')); $this->assertTrue($fileDao->exists('dog.txt'));
$this->assertFalse($fileDao->exists('fish.txt')); $this->assertFalse($fileDao->exists('fish.txt'));
} }
public function testLoadingUnexisting() public function testLoadingUnexisting()
{ {
$testDirectory = $this->createTestDirectory(); $testDirectory = $this->createTestDirectory();
$fileDao = new FileDao($testDirectory); $fileDao = new FileDao($testDirectory);
$this->assertNull($fileDao->load('dog.txt')); $this->assertNull($fileDao->load('dog.txt'));
} }
public function testDeleting() public function testDeleting()
{ {
$testDirectory = $this->createTestDirectory(); $testDirectory = $this->createTestDirectory();
$fileDao = new FileDao($testDirectory); $fileDao = new FileDao($testDirectory);
$fileDao->save('dog.txt', 'awesome dog'); $fileDao->save('dog.txt', 'awesome dog');
$this->assertTrue(file_exists($testDirectory . DIRECTORY_SEPARATOR . 'dog.txt')); $this->assertTrue(file_exists($testDirectory . DIRECTORY_SEPARATOR . 'dog.txt'));
$fileDao->delete('dog.txt'); $fileDao->delete('dog.txt');
$this->assertFalse(file_exists($testDirectory . DIRECTORY_SEPARATOR . 'dog.txt')); $this->assertFalse(file_exists($testDirectory . DIRECTORY_SEPARATOR . 'dog.txt'));
} }
} }

View file

@ -6,62 +6,62 @@ use Szurubooru\Tests\AbstractDatabaseTestCase;
final class GlobalParamDaoTest extends AbstractDatabaseTestCase final class GlobalParamDaoTest extends AbstractDatabaseTestCase
{ {
public function testSettingValues() public function testSettingValues()
{ {
$expected = new GlobalParam(); $expected = new GlobalParam();
$expected->setKey('key'); $expected->setKey('key');
$expected->setValue('test'); $expected->setValue('test');
$globalParamDao = $this->getGlobalParamDao(); $globalParamDao = $this->getGlobalParamDao();
$globalParamDao->save($expected); $globalParamDao->save($expected);
$actual = $globalParamDao->findByKey($expected->getKey()); $actual = $globalParamDao->findByKey($expected->getKey());
$this->assertEntitiesEqual($actual, $expected); $this->assertEntitiesEqual($actual, $expected);
} }
public function testInsertingSameKeyTwice() public function testInsertingSameKeyTwice()
{ {
$param1 = new GlobalParam(); $param1 = new GlobalParam();
$param1->setKey('key'); $param1->setKey('key');
$param1->setValue('value1'); $param1->setValue('value1');
$param2 = new GlobalParam(); $param2 = new GlobalParam();
$param2->setKey('key'); $param2->setKey('key');
$param2->setValue('value2'); $param2->setValue('value2');
$globalParamDao = $this->getGlobalParamDao(); $globalParamDao = $this->getGlobalParamDao();
$globalParamDao->save($param1); $globalParamDao->save($param1);
$globalParamDao->save($param2); $globalParamDao->save($param2);
$this->assertEquals([$param2], array_values($globalParamDao->findAll())); $this->assertEquals([$param2], array_values($globalParamDao->findAll()));
} }
public function testUpdatingValues() public function testUpdatingValues()
{ {
$expected = new GlobalParam(); $expected = new GlobalParam();
$expected->setKey('key'); $expected->setKey('key');
$expected->setValue('test'); $expected->setValue('test');
$globalParamDao = $this->getGlobalParamDao(); $globalParamDao = $this->getGlobalParamDao();
$globalParamDao->save($expected); $globalParamDao->save($expected);
$expected->setKey('key2'); $expected->setKey('key2');
$expected->setValue('test2'); $expected->setValue('test2');
$globalParamDao->save($expected); $globalParamDao->save($expected);
$actual = $globalParamDao->findByKey($expected->getKey()); $actual = $globalParamDao->findByKey($expected->getKey());
$this->assertEntitiesEqual($actual, $expected); $this->assertEntitiesEqual($actual, $expected);
} }
public function testRetrievingUnknownKeys() public function testRetrievingUnknownKeys()
{ {
$globalParamDao = $this->getGlobalParamDao(); $globalParamDao = $this->getGlobalParamDao();
$actual = $globalParamDao->findByKey('hey i dont exist'); $actual = $globalParamDao->findByKey('hey i dont exist');
$this->assertNull($actual); $this->assertNull($actual);
} }
private function getGlobalParamDao() private function getGlobalParamDao()
{ {
return new GlobalParamDao($this->databaseConnection); return new GlobalParamDao($this->databaseConnection);
} }
} }

View file

@ -11,323 +11,323 @@ use Szurubooru\Tests\AbstractDatabaseTestCase;
final class PostDaoTest extends AbstractDatabaseTestCase final class PostDaoTest extends AbstractDatabaseTestCase
{ {
private $fileDaoMock; private $fileDaoMock;
private $thumbnailServiceMock; private $thumbnailServiceMock;
private $tagDao; private $tagDao;
private $userDao; private $userDao;
public function setUp() public function setUp()
{ {
parent::setUp(); parent::setUp();
$this->fileDaoMock = $this->mock(PublicFileDao::class); $this->fileDaoMock = $this->mock(PublicFileDao::class);
$this->thumbnailServiceMock = $this->mock(ThumbnailService::class); $this->thumbnailServiceMock = $this->mock(ThumbnailService::class);
$this->tagDao = new TagDao($this->databaseConnection); $this->tagDao = new TagDao($this->databaseConnection);
$this->userDao = new UserDao( $this->userDao = new UserDao(
$this->databaseConnection, $this->databaseConnection,
$this->fileDaoMock, $this->fileDaoMock,
$this->thumbnailServiceMock); $this->thumbnailServiceMock);
} }
public function testCreating() public function testCreating()
{ {
$postDao = $this->getPostDao(); $postDao = $this->getPostDao();
$post = self::getTestPost(); $post = self::getTestPost();
$savedPost = $postDao->save($post); $savedPost = $postDao->save($post);
$this->assertEquals('test', $post->getName()); $this->assertEquals('test', $post->getName());
$this->assertNotNull($savedPost->getId()); $this->assertNotNull($savedPost->getId());
} }
public function testUpdating() public function testUpdating()
{ {
$postDao = $this->getPostDao(); $postDao = $this->getPostDao();
$post = self::getTestPost(); $post = self::getTestPost();
$post = $postDao->save($post); $post = $postDao->save($post);
$this->assertEquals('test', $post->getName()); $this->assertEquals('test', $post->getName());
$id = $post->getId(); $id = $post->getId();
$post->setName($post->getName() . '2'); $post->setName($post->getName() . '2');
$post = $postDao->save($post); $post = $postDao->save($post);
$this->assertEquals('test2', $post->getName()); $this->assertEquals('test2', $post->getName());
$this->assertEquals($id, $post->getId()); $this->assertEquals($id, $post->getId());
} }
public function testGettingAll() public function testGettingAll()
{ {
$postDao = $this->getPostDao(); $postDao = $this->getPostDao();
$post1 = self::getTestPost(); $post1 = self::getTestPost();
$post2 = self::getTestPost(); $post2 = self::getTestPost();
$postDao->save($post1); $postDao->save($post1);
$postDao->save($post2); $postDao->save($post2);
$this->assertNotNull($post1->getId()); $this->assertNotNull($post1->getId());
$this->assertNotNull($post2->getId()); $this->assertNotNull($post2->getId());
$this->assertNotEquals($post1->getId(), $post2->getId()); $this->assertNotEquals($post1->getId(), $post2->getId());
$actual = $postDao->findAll(); $actual = $postDao->findAll();
$expected = [ $expected = [
$post1->getId() => $post1, $post1->getId() => $post1,
$post2->getId() => $post2, $post2->getId() => $post2,
]; ];
$this->assertEntitiesEqual($expected, $actual); $this->assertEntitiesEqual($expected, $actual);
$this->assertEquals(count($expected), $postDao->getCount()); $this->assertEquals(count($expected), $postDao->getCount());
} }
public function testGettingTotalFileSize() public function testGettingTotalFileSize()
{ {
$postDao = $this->getPostDao(); $postDao = $this->getPostDao();
$post1 = self::getTestPost(); $post1 = self::getTestPost();
$post2 = self::getTestPost(); $post2 = self::getTestPost();
$post3 = self::getTestPost(); $post3 = self::getTestPost();
$post1->setOriginalFileSize(1249812); $post1->setOriginalFileSize(1249812);
$post2->setOriginalFileSize(128); $post2->setOriginalFileSize(128);
$post3->setOriginalFileSize(null); $post3->setOriginalFileSize(null);
$postDao->save($post1); $postDao->save($post1);
$postDao->save($post2); $postDao->save($post2);
$postDao->save($post3); $postDao->save($post3);
$expectedFileSize = $expectedFileSize =
$post1->getOriginalFileSize() + $post1->getOriginalFileSize() +
$post2->getOriginalFileSize() + $post2->getOriginalFileSize() +
$post3->getOriginalFileSize(); $post3->getOriginalFileSize();
$this->assertGreaterThan(0, $expectedFileSize); $this->assertGreaterThan(0, $expectedFileSize);
$this->assertEquals($expectedFileSize, $postDao->getTotalFileSize()); $this->assertEquals($expectedFileSize, $postDao->getTotalFileSize());
} }
public function testGettingById() public function testGettingById()
{ {
$postDao = $this->getPostDao(); $postDao = $this->getPostDao();
$post1 = self::getTestPost(); $post1 = self::getTestPost();
$post2 = self::getTestPost(); $post2 = self::getTestPost();
$postDao->save($post1); $postDao->save($post1);
$postDao->save($post2); $postDao->save($post2);
$actualPost1 = $postDao->findById($post1->getId()); $actualPost1 = $postDao->findById($post1->getId());
$actualPost2 = $postDao->findById($post2->getId()); $actualPost2 = $postDao->findById($post2->getId());
$this->assertEntitiesEqual($post1, $actualPost1); $this->assertEntitiesEqual($post1, $actualPost1);
$this->assertEntitiesEqual($post2, $actualPost2); $this->assertEntitiesEqual($post2, $actualPost2);
} }
public function testDeletingAll() public function testDeletingAll()
{ {
$postDao = $this->getPostDao(); $postDao = $this->getPostDao();
$post1 = self::getTestPost(); $post1 = self::getTestPost();
$post2 = self::getTestPost(); $post2 = self::getTestPost();
$postDao->save($post1); $postDao->save($post1);
$postDao->save($post2); $postDao->save($post2);
$postDao->deleteAll(); $postDao->deleteAll();
$actualPost1 = $postDao->findById($post1->getId()); $actualPost1 = $postDao->findById($post1->getId());
$actualPost2 = $postDao->findById($post2->getId()); $actualPost2 = $postDao->findById($post2->getId());
$this->assertNull($actualPost1); $this->assertNull($actualPost1);
$this->assertNull($actualPost2); $this->assertNull($actualPost2);
$this->assertEquals(0, count($postDao->findAll())); $this->assertEquals(0, count($postDao->findAll()));
} }
public function testDeletingById() public function testDeletingById()
{ {
$postDao = $this->getPostDao(); $postDao = $this->getPostDao();
$post1 = self::getTestPost(); $post1 = self::getTestPost();
$post2 = self::getTestPost(); $post2 = self::getTestPost();
$postDao->save($post1); $postDao->save($post1);
$postDao->save($post2); $postDao->save($post2);
$postDao->deleteById($post1->getId()); $postDao->deleteById($post1->getId());
$actualPost1 = $postDao->findById($post1->getId()); $actualPost1 = $postDao->findById($post1->getId());
$actualPost2 = $postDao->findById($post2->getId()); $actualPost2 = $postDao->findById($post2->getId());
$this->assertNull($actualPost1); $this->assertNull($actualPost1);
$this->assertEntitiesEqual($actualPost2, $actualPost2); $this->assertEntitiesEqual($actualPost2, $actualPost2);
$this->assertEquals(1, count($postDao->findAll())); $this->assertEquals(1, count($postDao->findAll()));
} }
public function testFindingByTagName() public function testFindingByTagName()
{ {
$tag1 = new Tag(); $tag1 = new Tag();
$tag1->setName('tag1'); $tag1->setName('tag1');
$tag1->setCreationTime(date('c')); $tag1->setCreationTime(date('c'));
$tag2 = new Tag(); $tag2 = new Tag();
$tag2->setName('tag2'); $tag2->setName('tag2');
$tag2->setCreationTime(date('c')); $tag2->setCreationTime(date('c'));
$this->tagDao->save($tag1); $this->tagDao->save($tag1);
$this->tagDao->save($tag2); $this->tagDao->save($tag2);
$postDao = $this->getPostDao(); $postDao = $this->getPostDao();
$post1 = self::getTestPost(); $post1 = self::getTestPost();
$post1->setTags([$tag1]); $post1->setTags([$tag1]);
$postDao->save($post1); $postDao->save($post1);
$post2 = self::getTestPost(); $post2 = self::getTestPost();
$post2->setTags([$tag2]); $post2->setTags([$tag2]);
$postDao->save($post2); $postDao->save($post2);
$this->assertEntitiesEqual([$post1], array_values($postDao->findByTagName('tag1'))); $this->assertEntitiesEqual([$post1], array_values($postDao->findByTagName('tag1')));
$this->assertEntitiesEqual([$post2], array_values($postDao->findByTagName('tag2'))); $this->assertEntitiesEqual([$post2], array_values($postDao->findByTagName('tag2')));
} }
public function testSavingTags() public function testSavingTags()
{ {
$tag1 = new Tag(); $tag1 = new Tag();
$tag1->setName('tag1'); $tag1->setName('tag1');
$tag1->setCreationTime(date('c')); $tag1->setCreationTime(date('c'));
$tag2 = new Tag(); $tag2 = new Tag();
$tag2->setName('tag2'); $tag2->setName('tag2');
$tag2->setCreationTime(date('c')); $tag2->setCreationTime(date('c'));
$this->tagDao->save($tag1); $this->tagDao->save($tag1);
$this->tagDao->save($tag2); $this->tagDao->save($tag2);
$testTags = ['tag1' => $tag1, 'tag2' => $tag2]; $testTags = ['tag1' => $tag1, 'tag2' => $tag2];
$postDao = $this->getPostDao(); $postDao = $this->getPostDao();
$post = self::getTestPost(); $post = self::getTestPost();
$post->setTags($testTags); $post->setTags($testTags);
$postDao->save($post); $postDao->save($post);
$savedPost = $postDao->findById($post->getId()); $savedPost = $postDao->findById($post->getId());
$this->assertEntitiesEqual($testTags, $post->getTags()); $this->assertEntitiesEqual($testTags, $post->getTags());
$this->assertEquals(2, count($savedPost->getTags())); $this->assertEquals(2, count($savedPost->getTags()));
$this->assertEquals(2, $post->getTagCount()); $this->assertEquals(2, $post->getTagCount());
$this->assertEquals(2, $savedPost->getTagCount()); $this->assertEquals(2, $savedPost->getTagCount());
$tagDao = $this->getTagDao(); $tagDao = $this->getTagDao();
$this->assertEquals(2, count($tagDao->findAll())); $this->assertEquals(2, count($tagDao->findAll()));
} }
public function testSavingUnsavedRelations() public function testSavingUnsavedRelations()
{ {
$post1 = self::getTestPost(); $post1 = self::getTestPost();
$post2 = self::getTestPost(); $post2 = self::getTestPost();
$testPosts = [$post1, $post2]; $testPosts = [$post1, $post2];
$postDao = $this->getPostDao(); $postDao = $this->getPostDao();
$post = self::getTestPost(); $post = self::getTestPost();
$post->setRelatedPosts($testPosts); $post->setRelatedPosts($testPosts);
$this->setExpectedException(\Exception::class, 'Unsaved entities found'); $this->setExpectedException(\Exception::class, 'Unsaved entities found');
$postDao->save($post); $postDao->save($post);
} }
public function testSavingRelations() public function testSavingRelations()
{ {
$post1 = self::getTestPost(); $post1 = self::getTestPost();
$post2 = self::getTestPost(); $post2 = self::getTestPost();
$testPosts = [$post1, $post2]; $testPosts = [$post1, $post2];
$postDao = $this->getPostDao(); $postDao = $this->getPostDao();
$postDao->save($post1); $postDao->save($post1);
$postDao->save($post2); $postDao->save($post2);
$post = self::getTestPost(); $post = self::getTestPost();
$post->setRelatedPosts($testPosts); $post->setRelatedPosts($testPosts);
$postDao->save($post); $postDao->save($post);
$savedPost = $postDao->findById($post->getId()); $savedPost = $postDao->findById($post->getId());
$this->assertEntitiesEqual($testPosts, $post->getRelatedPosts()); $this->assertEntitiesEqual($testPosts, $post->getRelatedPosts());
$this->assertEquals(2, count($savedPost->getRelatedPosts())); $this->assertEquals(2, count($savedPost->getRelatedPosts()));
} }
public function testSavingUser() public function testSavingUser()
{ {
$testUser = new User(5); $testUser = new User(5);
$testUser->setName('it\'s me'); $testUser->setName('it\'s me');
$postDao = $this->getPostDao(); $postDao = $this->getPostDao();
$post = self::getTestPost(); $post = self::getTestPost();
$post->setUser($testUser); $post->setUser($testUser);
$postDao->save($post); $postDao->save($post);
$savedPost = $postDao->findById($post->getId()); $savedPost = $postDao->findById($post->getId());
$this->assertEntitiesEqual($testUser, $post->getUser()); $this->assertEntitiesEqual($testUser, $post->getUser());
$this->assertEquals(5, $post->getUserId()); $this->assertEquals(5, $post->getUserId());
} }
public function testNotLoadingContentForNewPosts() public function testNotLoadingContentForNewPosts()
{ {
$postDao = $this->getPostDao(); $postDao = $this->getPostDao();
$newlyCreatedPost = self::getTestPost(); $newlyCreatedPost = self::getTestPost();
$this->assertNull($newlyCreatedPost->getContent()); $this->assertNull($newlyCreatedPost->getContent());
} }
public function testLoadingContentPostsForExistingPosts() public function testLoadingContentPostsForExistingPosts()
{ {
$postDao = $this->getPostDao(); $postDao = $this->getPostDao();
$post = self::getTestPost(); $post = self::getTestPost();
$postDao->save($post); $postDao->save($post);
$post = $postDao->findById($post->getId()); $post = $postDao->findById($post->getId());
$this->fileDaoMock $this->fileDaoMock
->expects($this->once()) ->expects($this->once())
->method('load') ->method('load')
->with($post->getContentPath()) ->with($post->getContentPath())
->willReturn('whatever'); ->willReturn('whatever');
$this->assertEquals('whatever', $post->getContent()); $this->assertEquals('whatever', $post->getContent());
} }
public function testSavingContent() public function testSavingContent()
{ {
$postDao = $this->getPostDao(); $postDao = $this->getPostDao();
$post = self::getTestPost(); $post = self::getTestPost();
$post->setContent('whatever'); $post->setContent('whatever');
$this->thumbnailServiceMock $this->thumbnailServiceMock
->expects($this->exactly(2)) ->expects($this->exactly(2))
->method('deleteUsedThumbnails') ->method('deleteUsedThumbnails')
->withConsecutive( ->withConsecutive(
[$post->getContentPath()], [$post->getContentPath()],
[$post->getThumbnailSourceContentPath()]); [$post->getThumbnailSourceContentPath()]);
$this->fileDaoMock $this->fileDaoMock
->expects($this->exactly(1)) ->expects($this->exactly(1))
->method('save') ->method('save')
->withConsecutive( ->withConsecutive(
[$post->getContentPath(), 'whatever']); [$post->getContentPath(), 'whatever']);
$postDao->save($post); $postDao->save($post);
} }
public function testSavingContentAndThumbnail() public function testSavingContentAndThumbnail()
{ {
$postDao = $this->getPostDao(); $postDao = $this->getPostDao();
$post = self::getTestPost(); $post = self::getTestPost();
$post->setContent('whatever'); $post->setContent('whatever');
$post->setThumbnailSourceContent('an image of sharks'); $post->setThumbnailSourceContent('an image of sharks');
$this->thumbnailServiceMock $this->thumbnailServiceMock
->expects($this->exactly(2)) ->expects($this->exactly(2))
->method('deleteUsedThumbnails') ->method('deleteUsedThumbnails')
->withConsecutive( ->withConsecutive(
[$post->getContentPath()], [$post->getContentPath()],
[$post->getThumbnailSourceContentPath()]); [$post->getThumbnailSourceContentPath()]);
$this->fileDaoMock $this->fileDaoMock
->expects($this->exactly(2)) ->expects($this->exactly(2))
->method('save') ->method('save')
->withConsecutive( ->withConsecutive(
[$post->getContentPath(), 'whatever'], [$post->getContentPath(), 'whatever'],
[$post->getThumbnailSourceContentPath(), 'an image of sharks']); [$post->getThumbnailSourceContentPath(), 'an image of sharks']);
$postDao->save($post); $postDao->save($post);
} }
private function getPostDao() private function getPostDao()
{ {
return new PostDao( return new PostDao(
$this->databaseConnection, $this->databaseConnection,
$this->tagDao, $this->tagDao,
$this->userDao, $this->userDao,
$this->fileDaoMock, $this->fileDaoMock,
$this->thumbnailServiceMock); $this->thumbnailServiceMock);
} }
private function getTagDao() private function getTagDao()
{ {
return $this->tagDao; return $this->tagDao;
} }
} }

View file

@ -7,38 +7,38 @@ use Szurubooru\Tests\AbstractDatabaseTestCase;
final class PostNoteDaoTest extends AbstractDatabaseTestCase final class PostNoteDaoTest extends AbstractDatabaseTestCase
{ {
private $postDaoMock; private $postDaoMock;
public function setUp() public function setUp()
{ {
parent::setUp(); parent::setUp();
$this->postDaoMock = $this->mock(PostDao::class); $this->postDaoMock = $this->mock(PostDao::class);
} }
public function testSettingValues() public function testSettingValues()
{ {
$expected = new PostNote(); $expected = new PostNote();
$expected->setPostId(5); $expected->setPostId(5);
$expected->setLeft(5); $expected->setLeft(5);
$expected->setTop(10); $expected->setTop(10);
$expected->setWidth(50); $expected->setWidth(50);
$expected->setHeight(50); $expected->setHeight(50);
$expected->setText('text'); $expected->setText('text');
$postNoteDao = $this->getPostNoteDao(); $postNoteDao = $this->getPostNoteDao();
$postNoteDao->save($expected); $postNoteDao->save($expected);
$actual = $postNoteDao->findById($expected->getId()); $actual = $postNoteDao->findById($expected->getId());
$this->assertEntitiesEqual($actual, $expected); $this->assertEntitiesEqual($actual, $expected);
$this->postDaoMock->expects($this->once())->method('findById')->with(5)->willReturn('lazy post'); $this->postDaoMock->expects($this->once())->method('findById')->with(5)->willReturn('lazy post');
$this->assertEquals('lazy post', $actual->getPost()); $this->assertEquals('lazy post', $actual->getPost());
} }
private function getPostNoteDao() private function getPostNoteDao()
{ {
return new PostNoteDao( return new PostNoteDao(
$this->databaseConnection, $this->databaseConnection,
$this->postDaoMock); $this->postDaoMock);
} }
} }

View file

@ -9,83 +9,83 @@ use Szurubooru\Tests\AbstractDatabaseTestCase;
final class ScoreDaoTest extends AbstractDatabaseTestCase final class ScoreDaoTest extends AbstractDatabaseTestCase
{ {
private $timeServiceMock; private $timeServiceMock;
public function setUp() public function setUp()
{ {
parent::setUp(); parent::setUp();
$this->timeServiceMock = $this->mock(TimeService::class); $this->timeServiceMock = $this->mock(TimeService::class);
} }
public function testSaving() public function testSaving()
{ {
$user = new User(1); $user = new User(1);
$user->setName('olivia'); $user->setName('olivia');
$post = new Post(2); $post = new Post(2);
$post->setName('sword'); $post->setName('sword');
$score = new Score(); $score = new Score();
$score->setUserId($user->getId()); $score->setUserId($user->getId());
$score->setPostId($post->getId()); $score->setPostId($post->getId());
$score->setTime(date('c')); $score->setTime(date('c'));
$score->setScore(1); $score->setScore(1);
$scoreDao = $this->getScoreDao(); $scoreDao = $this->getScoreDao();
$scoreDao->save($score); $scoreDao->save($score);
$savedScore = $scoreDao->findById($score->getId()); $savedScore = $scoreDao->findById($score->getId());
$this->assertEquals(1, $savedScore->getUserId()); $this->assertEquals(1, $savedScore->getUserId());
$this->assertEquals(2, $savedScore->getPostId()); $this->assertEquals(2, $savedScore->getPostId());
$this->assertEquals($score->getTime(), $savedScore->getTime()); $this->assertEquals($score->getTime(), $savedScore->getTime());
$this->assertEquals($user->getId(), $savedScore->getUserId()); $this->assertEquals($user->getId(), $savedScore->getUserId());
$this->assertEquals($post->getId(), $savedScore->getPostId()); $this->assertEquals($post->getId(), $savedScore->getPostId());
} }
public function testFindingByUserAndPost() public function testFindingByUserAndPost()
{ {
$post1 = new Post(1); $post1 = new Post(1);
$post2 = new Post(2); $post2 = new Post(2);
$user1 = new User(3); $user1 = new User(3);
$user2 = new User(4); $user2 = new User(4);
$score1 = new Score(); $score1 = new Score();
$score1->setUserId($user1->getId()); $score1->setUserId($user1->getId());
$score1->setPostId($post1->getId()); $score1->setPostId($post1->getId());
$score1->setTime(date('c', mktime(1))); $score1->setTime(date('c', mktime(1)));
$score1->setScore(1); $score1->setScore(1);
$score2 = new Score(); $score2 = new Score();
$score2->setUserId($user2->getId()); $score2->setUserId($user2->getId());
$score2->setPostId($post2->getId()); $score2->setPostId($post2->getId());
$score2->setTime(date('c', mktime(2))); $score2->setTime(date('c', mktime(2)));
$score2->setScore(0); $score2->setScore(0);
$score3 = new Score(); $score3 = new Score();
$score3->setUserId($user1->getId()); $score3->setUserId($user1->getId());
$score3->setPostId($post2->getId()); $score3->setPostId($post2->getId());
$score3->setTime(date('c', mktime(3))); $score3->setTime(date('c', mktime(3)));
$score3->setScore(-1); $score3->setScore(-1);
$scoreDao = $this->getScoreDao(); $scoreDao = $this->getScoreDao();
$scoreDao->save($score1); $scoreDao->save($score1);
$scoreDao->save($score2); $scoreDao->save($score2);
$scoreDao->save($score3); $scoreDao->save($score3);
$this->assertEntitiesEqual($score1, $scoreDao->getUserScore($user1, $post1)); $this->assertEntitiesEqual($score1, $scoreDao->getUserScore($user1, $post1));
$this->assertEntitiesEqual($score2, $scoreDao->getUserScore($user2, $post2)); $this->assertEntitiesEqual($score2, $scoreDao->getUserScore($user2, $post2));
$this->assertEntitiesEqual($score3, $scoreDao->getUserScore($user1, $post2)); $this->assertEntitiesEqual($score3, $scoreDao->getUserScore($user1, $post2));
$this->assertNull($scoreDao->getUserScore($user2, $post1)); $this->assertNull($scoreDao->getUserScore($user2, $post1));
} }
public function findByPost(Post $post) public function findByPost(Post $post)
{ {
return $this->findOneBy('postId', $post->getId()); return $this->findOneBy('postId', $post->getId());
} }
private function getScoreDao() private function getScoreDao()
{ {
return new ScoreDao( return new ScoreDao(
$this->databaseConnection, $this->databaseConnection,
$this->timeServiceMock); $this->timeServiceMock);
} }
} }

View file

@ -8,53 +8,53 @@ use Szurubooru\Tests\AbstractDatabaseTestCase;
final class SnapshotDaoTest extends AbstractDatabaseTestCase final class SnapshotDaoTest extends AbstractDatabaseTestCase
{ {
public function setUp() public function setUp()
{ {
parent::setUp(); parent::setUp();
$this->userDaoMock = $this->mock(UserDao::class); $this->userDaoMock = $this->mock(UserDao::class);
} }
public function testSaving() public function testSaving()
{ {
$snapshot = $this->getTestSnapshot(); $snapshot = $this->getTestSnapshot();
$snapshotDao = $this->getSnapshotDao(); $snapshotDao = $this->getSnapshotDao();
$snapshotDao->save($snapshot); $snapshotDao->save($snapshot);
$this->assertNotNull($snapshot->getId()); $this->assertNotNull($snapshot->getId());
$this->assertEntitiesEqual($snapshot, $snapshotDao->findById($snapshot->getId())); $this->assertEntitiesEqual($snapshot, $snapshotDao->findById($snapshot->getId()));
} }
public function testUserLazyLoader() public function testUserLazyLoader()
{ {
$snapshot = $this->getTestSnapshot(); $snapshot = $this->getTestSnapshot();
$snapshot->setUser(new User(5)); $snapshot->setUser(new User(5));
$this->assertEquals(5, $snapshot->getUserId()); $this->assertEquals(5, $snapshot->getUserId());
$snapshotDao = $this->getSnapshotDao(); $snapshotDao = $this->getSnapshotDao();
$snapshotDao->save($snapshot); $snapshotDao->save($snapshot);
$savedSnapshot = $snapshotDao->findById($snapshot->getId()); $savedSnapshot = $snapshotDao->findById($snapshot->getId());
$this->assertEquals(5, $savedSnapshot->getUserId()); $this->assertEquals(5, $savedSnapshot->getUserId());
$this->userDaoMock $this->userDaoMock
->expects($this->once()) ->expects($this->once())
->method('findById'); ->method('findById');
$savedSnapshot->getUser(); $savedSnapshot->getUser();
} }
private function getTestSnapshot() private function getTestSnapshot()
{ {
$snapshot = new Snapshot(); $snapshot = new Snapshot();
$snapshot->setType(Snapshot::TYPE_POST); $snapshot->setType(Snapshot::TYPE_POST);
$snapshot->setData(['wake up', 'neo', ['follow' => 'white rabbit']]); $snapshot->setData(['wake up', 'neo', ['follow' => 'white rabbit']]);
$snapshot->setPrimaryKey(1); $snapshot->setPrimaryKey(1);
$snapshot->setTime(date('c', mktime(1, 2, 3))); $snapshot->setTime(date('c', mktime(1, 2, 3)));
$snapshot->setUserId(null); $snapshot->setUserId(null);
$snapshot->setOperation(Snapshot::OPERATION_CHANGE); $snapshot->setOperation(Snapshot::OPERATION_CHANGE);
return $snapshot; return $snapshot;
} }
private function getSnapshotDao() private function getSnapshotDao()
{ {
return new SnapshotDao( return new SnapshotDao(
$this->databaseConnection, $this->databaseConnection,
$this->userDaoMock); $this->userDaoMock);
} }
} }

View file

@ -11,54 +11,54 @@ use Szurubooru\Tests\AbstractDatabaseTestCase;
final class TagDaoFilterTest extends AbstractDatabaseTestCase final class TagDaoFilterTest extends AbstractDatabaseTestCase
{ {
public function testCategories() public function testCategories()
{ {
$tag1 = self::getTestTag('test 1'); $tag1 = self::getTestTag('test 1');
$tag2 = self::getTestTag('test 2'); $tag2 = self::getTestTag('test 2');
$tag3 = self::getTestTag('test 3'); $tag3 = self::getTestTag('test 3');
$tag2->setCategory('misc'); $tag2->setCategory('misc');
$tag3->setCategory('other'); $tag3->setCategory('other');
$tagDao = $this->getTagDao(); $tagDao = $this->getTagDao();
$tagDao->save($tag1); $tagDao->save($tag1);
$tagDao->save($tag2); $tagDao->save($tag2);
$tagDao->save($tag3); $tagDao->save($tag3);
$searchFilter = new TagFilter(); $searchFilter = new TagFilter();
$requirement = new Requirement(); $requirement = new Requirement();
$requirement->setType(TagFilter::REQUIREMENT_CATEGORY); $requirement->setType(TagFilter::REQUIREMENT_CATEGORY);
$requirement->setValue(new RequirementSingleValue('misc')); $requirement->setValue(new RequirementSingleValue('misc'));
$requirement->setNegated(true); $requirement->setNegated(true);
$searchFilter->addRequirement($requirement); $searchFilter->addRequirement($requirement);
$result = $tagDao->findFiltered($searchFilter); $result = $tagDao->findFiltered($searchFilter);
$this->assertEquals(2, $result->getTotalRecords()); $this->assertEquals(2, $result->getTotalRecords());
$this->assertEntitiesEqual([$tag3, $tag1], array_values($result->getEntities())); $this->assertEntitiesEqual([$tag3, $tag1], array_values($result->getEntities()));
} }
public function testCompositeCategories() public function testCompositeCategories()
{ {
$tag1 = self::getTestTag('test 1'); $tag1 = self::getTestTag('test 1');
$tag2 = self::getTestTag('test 2'); $tag2 = self::getTestTag('test 2');
$tag3 = self::getTestTag('test 3'); $tag3 = self::getTestTag('test 3');
$tag2->setCategory('misc'); $tag2->setCategory('misc');
$tag3->setCategory('other'); $tag3->setCategory('other');
$tagDao = $this->getTagDao(); $tagDao = $this->getTagDao();
$tagDao->save($tag1); $tagDao->save($tag1);
$tagDao->save($tag2); $tagDao->save($tag2);
$tagDao->save($tag3); $tagDao->save($tag3);
$searchFilter = new TagFilter(); $searchFilter = new TagFilter();
$requirement = new Requirement(); $requirement = new Requirement();
$requirement->setType(TagFilter::REQUIREMENT_CATEGORY); $requirement->setType(TagFilter::REQUIREMENT_CATEGORY);
$requirement->setValue(new RequirementCompositeValue(['misc', 'other'])); $requirement->setValue(new RequirementCompositeValue(['misc', 'other']));
$requirement->setNegated(true); $requirement->setNegated(true);
$searchFilter->addRequirement($requirement); $searchFilter->addRequirement($requirement);
$result = $tagDao->findFiltered($searchFilter); $result = $tagDao->findFiltered($searchFilter);
$this->assertEquals(1, $result->getTotalRecords()); $this->assertEquals(1, $result->getTotalRecords());
$this->assertEntitiesEqual([$tag1], array_values($result->getEntities())); $this->assertEntitiesEqual([$tag1], array_values($result->getEntities()));
} }
private function getTagDao() private function getTagDao()
{ {
return new TagDao($this->databaseConnection); return new TagDao($this->databaseConnection);
} }
} }

View file

@ -6,82 +6,82 @@ use Szurubooru\Tests\AbstractDatabaseTestCase;
final class TagDaoTest extends AbstractDatabaseTestCase final class TagDaoTest extends AbstractDatabaseTestCase
{ {
public function setUp() public function setUp()
{ {
parent::setUp(); parent::setUp();
} }
public function testSaving() public function testSaving()
{ {
$tag = self::getTestTag('test'); $tag = self::getTestTag('test');
$tag->setCreationTime(date('c', mktime(0, 0, 0, 10, 1, 2014))); $tag->setCreationTime(date('c', mktime(0, 0, 0, 10, 1, 2014)));
$this->assertFalse($tag->isBanned()); $this->assertFalse($tag->isBanned());
$tag->setBanned(true); $tag->setBanned(true);
$tagDao = $this->getTagDao(); $tagDao = $this->getTagDao();
$tagDao->save($tag); $tagDao->save($tag);
$actualTag = $tagDao->findById($tag->getId()); $actualTag = $tagDao->findById($tag->getId());
$this->assertEntitiesEqual($tag, $actualTag); $this->assertEntitiesEqual($tag, $actualTag);
} }
public function testSavingRelations() public function testSavingRelations()
{ {
$tag1 = self::getTestTag('test 1'); $tag1 = self::getTestTag('test 1');
$tag2 = self::getTestTag('test 2'); $tag2 = self::getTestTag('test 2');
$tag3 = self::getTestTag('test 3'); $tag3 = self::getTestTag('test 3');
$tag4 = self::getTestTag('test 4'); $tag4 = self::getTestTag('test 4');
$tagDao = $this->getTagDao(); $tagDao = $this->getTagDao();
$tagDao->save($tag1); $tagDao->save($tag1);
$tagDao->save($tag2); $tagDao->save($tag2);
$tagDao->save($tag3); $tagDao->save($tag3);
$tagDao->save($tag4); $tagDao->save($tag4);
$tag = self::getTestTag('test'); $tag = self::getTestTag('test');
$tag->setImpliedTags([$tag1, $tag3]); $tag->setImpliedTags([$tag1, $tag3]);
$tag->setSuggestedTags([$tag2, $tag4]); $tag->setSuggestedTags([$tag2, $tag4]);
$this->assertGreaterThan(0, count($tag->getImpliedTags())); $this->assertGreaterThan(0, count($tag->getImpliedTags()));
$this->assertGreaterThan(0, count($tag->getSuggestedTags())); $this->assertGreaterThan(0, count($tag->getSuggestedTags()));
$tagDao->save($tag); $tagDao->save($tag);
$actualTag = $tagDao->findById($tag->getId()); $actualTag = $tagDao->findById($tag->getId());
$this->assertEntitiesEqual($tag, $actualTag); $this->assertEntitiesEqual($tag, $actualTag);
$this->assertEntitiesEqual(array_values($tag->getImpliedTags()), array_values($actualTag->getImpliedTags())); $this->assertEntitiesEqual(array_values($tag->getImpliedTags()), array_values($actualTag->getImpliedTags()));
$this->assertEntitiesEqual(array_values($tag->getSuggestedTags()), array_values($actualTag->getSuggestedTags())); $this->assertEntitiesEqual(array_values($tag->getSuggestedTags()), array_values($actualTag->getSuggestedTags()));
$this->assertGreaterThan(0, count($actualTag->getImpliedTags())); $this->assertGreaterThan(0, count($actualTag->getImpliedTags()));
$this->assertGreaterThan(0, count($actualTag->getSuggestedTags())); $this->assertGreaterThan(0, count($actualTag->getSuggestedTags()));
} }
public function testFindByPostIds() public function testFindByPostIds()
{ {
$pdo = $this->databaseConnection->getPDO(); $pdo = $this->databaseConnection->getPDO();
$pdo->exec('INSERT INTO tags(id, name, creationTime) VALUES (1, \'test1\', \'2014-10-01 00:00:00\')'); $pdo->exec('INSERT INTO tags(id, name, creationTime) VALUES (1, \'test1\', \'2014-10-01 00:00:00\')');
$pdo->exec('INSERT INTO tags(id, name, creationTime) VALUES (2, \'test2\', \'2014-10-01 00:00:00\')'); $pdo->exec('INSERT INTO tags(id, name, creationTime) VALUES (2, \'test2\', \'2014-10-01 00:00:00\')');
$pdo->exec('INSERT INTO postTags(postId, tagId) VALUES (5, 1)'); $pdo->exec('INSERT INTO postTags(postId, tagId) VALUES (5, 1)');
$pdo->exec('INSERT INTO postTags(postId, tagId) VALUES (6, 1)'); $pdo->exec('INSERT INTO postTags(postId, tagId) VALUES (6, 1)');
$pdo->exec('INSERT INTO postTags(postId, tagId) VALUES (5, 2)'); $pdo->exec('INSERT INTO postTags(postId, tagId) VALUES (5, 2)');
$pdo->exec('INSERT INTO postTags(postId, tagId) VALUES (6, 2)'); $pdo->exec('INSERT INTO postTags(postId, tagId) VALUES (6, 2)');
$tag1 = new Tag(1); $tag1 = new Tag(1);
$tag1->setName('test1'); $tag1->setName('test1');
$tag1->setCreationTime(date('c', mktime(0, 0, 0, 10, 1, 2014))); $tag1->setCreationTime(date('c', mktime(0, 0, 0, 10, 1, 2014)));
$tag2 = new Tag(2); $tag2 = new Tag(2);
$tag2->setName('test2'); $tag2->setName('test2');
$tag2->setCreationTime(date('c', mktime(0, 0, 0, 10, 1, 2014))); $tag2->setCreationTime(date('c', mktime(0, 0, 0, 10, 1, 2014)));
$expected = [ $expected = [
$tag1->getId() => $tag1, $tag1->getId() => $tag1,
$tag2->getId() => $tag2, $tag2->getId() => $tag2,
]; ];
$tagDao = $this->getTagDao(); $tagDao = $this->getTagDao();
$actual = $tagDao->findByPostId(5); $actual = $tagDao->findByPostId(5);
$this->assertEntitiesEqual($expected, $actual); $this->assertEntitiesEqual($expected, $actual);
} }
private function getTagDao() private function getTagDao()
{ {
return new TagDao($this->databaseConnection); return new TagDao($this->databaseConnection);
} }
} }

View file

@ -6,44 +6,44 @@ use Szurubooru\Tests\AbstractDatabaseTestCase;
final class TokenDaoTest extends AbstractDatabaseTestCase final class TokenDaoTest extends AbstractDatabaseTestCase
{ {
public function testRetrievingByValidName() public function testRetrievingByValidName()
{ {
$token = new Token(); $token = new Token();
$token->setName('test'); $token->setName('test');
$token->setPurpose(Token::PURPOSE_LOGIN); $token->setPurpose(Token::PURPOSE_LOGIN);
$tokenDao = $this->getTokenDao(); $tokenDao = $this->getTokenDao();
$tokenDao->save($token); $tokenDao->save($token);
$expected = $token; $expected = $token;
$actual = $tokenDao->findByName($token->getName()); $actual = $tokenDao->findByName($token->getName());
$this->assertEntitiesEqual($actual, $expected); $this->assertEntitiesEqual($actual, $expected);
} }
public function testRetrievingByInvalidName() public function testRetrievingByInvalidName()
{ {
$tokenDao = $this->getTokenDao(); $tokenDao = $this->getTokenDao();
$actual = $tokenDao->findByName('rubbish'); $actual = $tokenDao->findByName('rubbish');
$this->assertNull($actual); $this->assertNull($actual);
} }
public function testRetrievingByAdditionalDataAndPurpose() public function testRetrievingByAdditionalDataAndPurpose()
{ {
$token = new Token(); $token = new Token();
$token->setName('test'); $token->setName('test');
$token->setPurpose(Token::PURPOSE_LOGIN); $token->setPurpose(Token::PURPOSE_LOGIN);
$tokenDao = $this->getTokenDao(); $tokenDao = $this->getTokenDao();
$tokenDao->save($token); $tokenDao->save($token);
$expected = $token; $expected = $token;
$this->assertEntitiesEqual($expected, $tokenDao->findByAdditionalDataAndPurpose(null, Token::PURPOSE_LOGIN)); $this->assertEntitiesEqual($expected, $tokenDao->findByAdditionalDataAndPurpose(null, Token::PURPOSE_LOGIN));
$this->assertNull($tokenDao->findByAdditionalDataAndPurpose(null, Token::PURPOSE_ACTIVATE)); $this->assertNull($tokenDao->findByAdditionalDataAndPurpose(null, Token::PURPOSE_ACTIVATE));
} }
private function getTokenDao() private function getTokenDao()
{ {
return new TokenDao($this->databaseConnection); return new TokenDao($this->databaseConnection);
} }
} }

View file

@ -7,78 +7,78 @@ use Szurubooru\Tests\AbstractDatabaseTestCase;
final class TransactionManagerTest extends AbstractDatabaseTestCase final class TransactionManagerTest extends AbstractDatabaseTestCase
{ {
public function testCommit() public function testCommit()
{ {
$testEntity = $this->getTestEntity(); $testEntity = $this->getTestEntity();
$testDao = $this->getTestDao(); $testDao = $this->getTestDao();
$transactionManager = $this->getTransactionManager(); $transactionManager = $this->getTransactionManager();
$transactionManager->commit(function() use ($testDao, &$testEntity) $transactionManager->commit(function() use ($testDao, &$testEntity)
{ {
$testDao->save($testEntity); $testDao->save($testEntity);
$this->assertNotNull($testEntity->getId()); $this->assertNotNull($testEntity->getId());
}); });
$this->assertNotNull($testEntity->getId()); $this->assertNotNull($testEntity->getId());
$this->assertEntitiesEqual($testEntity, $testDao->findById($testEntity->getId())); $this->assertEntitiesEqual($testEntity, $testDao->findById($testEntity->getId()));
} }
public function testRollback() public function testRollback()
{ {
$testEntity = $this->getTestEntity(); $testEntity = $this->getTestEntity();
$testDao = $this->getTestDao(); $testDao = $this->getTestDao();
$transactionManager = $this->getTransactionManager(); $transactionManager = $this->getTransactionManager();
$transactionManager->rollback(function() use ($testDao, &$testEntity) $transactionManager->rollback(function() use ($testDao, &$testEntity)
{ {
$testDao->save($testEntity); $testDao->save($testEntity);
$this->assertNotNull($testEntity->getId()); $this->assertNotNull($testEntity->getId());
}); });
//ids that could be forged in transaction get left behind after rollback //ids that could be forged in transaction get left behind after rollback
$this->assertNotNull($testEntity->getId()); $this->assertNotNull($testEntity->getId());
$this->databaseConnection->getPDO()->rollBack(); $this->databaseConnection->getPDO()->rollBack();
$this->databaseConnection->getPDO()->beginTransaction(); $this->databaseConnection->getPDO()->beginTransaction();
//but entities shouldn't be saved to database //but entities shouldn't be saved to database
$this->assertNull($testDao->findById($testEntity->getId())); $this->assertNull($testDao->findById($testEntity->getId()));
} }
public function testNestedTransactions() public function testNestedTransactions()
{ {
$testEntity = $this->getTestEntity(); $testEntity = $this->getTestEntity();
$testDao = $this->getTestDao(); $testDao = $this->getTestDao();
$transactionManager = $this->getTransactionManager(); $transactionManager = $this->getTransactionManager();
$transactionManager->commit(function() use ($transactionManager, $testDao, &$testEntity) $transactionManager->commit(function() use ($transactionManager, $testDao, &$testEntity)
{ {
$transactionManager->commit(function() use ($testDao, &$testEntity) $transactionManager->commit(function() use ($testDao, &$testEntity)
{ {
$testDao->save($testEntity); $testDao->save($testEntity);
$this->assertNotNull($testEntity->getId()); $this->assertNotNull($testEntity->getId());
}); });
}); });
$this->assertNotNull($testEntity->getId()); $this->assertNotNull($testEntity->getId());
$this->assertEntitiesEqual($testEntity, $testDao->findById($testEntity->getId())); $this->assertEntitiesEqual($testEntity, $testDao->findById($testEntity->getId()));
} }
private function getTestEntity() private function getTestEntity()
{ {
$token = new Token(); $token = new Token();
$token->setName('yo'); $token->setName('yo');
$token->setPurpose(Token::PURPOSE_ACTIVATE); $token->setPurpose(Token::PURPOSE_ACTIVATE);
return $token; return $token;
} }
private function getTestDao() private function getTestDao()
{ {
return new TokenDao($this->databaseConnection); return new TokenDao($this->databaseConnection);
} }
private function getTransactionManager() private function getTransactionManager()
{ {
return new TransactionManager($this->databaseConnection); return new TransactionManager($this->databaseConnection);
} }
} }

View file

@ -9,146 +9,146 @@ use Szurubooru\Tests\AbstractDatabaseTestCase;
final class UserDaoFilterTest extends AbstractDatabaseTestCase final class UserDaoFilterTest extends AbstractDatabaseTestCase
{ {
private $fileDaoMock; private $fileDaoMock;
private $thumbnailServiceMock; private $thumbnailServiceMock;
public function setUp() public function setUp()
{ {
parent::setUp(); parent::setUp();
$this->fileDaoMock = $this->mock(PublicFileDao::class); $this->fileDaoMock = $this->mock(PublicFileDao::class);
$this->thumbnailServiceMock = $this->mock(ThumbnailService::class); $this->thumbnailServiceMock = $this->mock(ThumbnailService::class);
} }
public function pagingProvider() public function pagingProvider()
{ {
$allUsers = ['xena', 'gabrielle']; $allUsers = ['xena', 'gabrielle'];
list ($user1, $user2) = $allUsers; list ($user1, $user2) = $allUsers;
return [ return [
[1, 1, [$user1], $allUsers], [1, 1, [$user1], $allUsers],
[1, 2, [$user1, $user2], $allUsers], [1, 2, [$user1, $user2], $allUsers],
[2, 1, [$user2], $allUsers], [2, 1, [$user2], $allUsers],
[2, 2, [], $allUsers], [2, 2, [], $allUsers],
]; ];
} }
public function testNothing() public function testNothing()
{ {
$searchFilter = new UserFilter(); $searchFilter = new UserFilter();
$searchFilter->setPageNumber(1); $searchFilter->setPageNumber(1);
$searchFilter->setPageSize(2); $searchFilter->setPageSize(2);
$userDao = $this->getUserDao(); $userDao = $this->getUserDao();
$result = $userDao->findFiltered($searchFilter); $result = $userDao->findFiltered($searchFilter);
$this->assertEmpty($result->getEntities()); $this->assertEmpty($result->getEntities());
$this->assertEquals(0, $result->getTotalRecords()); $this->assertEquals(0, $result->getTotalRecords());
$this->assertEquals(1, $result->getPageNumber()); $this->assertEquals(1, $result->getPageNumber());
$this->assertEquals(2, $result->getPageSize()); $this->assertEquals(2, $result->getPageSize());
} }
/** /**
* @dataProvider pagingProvider * @dataProvider pagingProvider
*/ */
public function testPaging($pageNumber, $pageSize, $expectedUserNames, $allUserNames) public function testPaging($pageNumber, $pageSize, $expectedUserNames, $allUserNames)
{ {
$userDao = $this->getUserDao(); $userDao = $this->getUserDao();
$expectedUsers = []; $expectedUsers = [];
foreach ($allUserNames as $userName) foreach ($allUserNames as $userName)
{ {
$user = self::getTestUser($userName); $user = self::getTestUser($userName);
$userDao->save($user); $userDao->save($user);
if (in_array($userName, $expectedUserNames)) if (in_array($userName, $expectedUserNames))
$expectedUsers[] = $user; $expectedUsers[] = $user;
} }
$searchFilter = new UserFilter(); $searchFilter = new UserFilter();
$searchFilter->setOrder([ $searchFilter->setOrder([
UserFilter::ORDER_NAME => UserFilter::ORDER_NAME =>
UserFilter::ORDER_DESC]); UserFilter::ORDER_DESC]);
$searchFilter->setPageNumber($pageNumber); $searchFilter->setPageNumber($pageNumber);
$searchFilter->setPageSize($pageSize); $searchFilter->setPageSize($pageSize);
$result = $userDao->findFiltered($searchFilter); $result = $userDao->findFiltered($searchFilter);
$this->assertEquals(count($allUserNames), $result->getTotalRecords()); $this->assertEquals(count($allUserNames), $result->getTotalRecords());
$this->assertEquals($pageNumber, $result->getPageNumber()); $this->assertEquals($pageNumber, $result->getPageNumber());
$this->assertEquals($pageSize, $result->getPageSize()); $this->assertEquals($pageSize, $result->getPageSize());
$this->assertEntitiesEqual($expectedUsers, array_values($result->getEntities())); $this->assertEntitiesEqual($expectedUsers, array_values($result->getEntities()));
} }
public function testDefaultOrder() public function testDefaultOrder()
{ {
list ($user1, $user2) = $this->prepareUsers(); list ($user1, $user2) = $this->prepareUsers();
$this->doTestSorting(null, null, [$user1, $user2]); $this->doTestSorting(null, null, [$user1, $user2]);
} }
public function testOrderByNameAscending() public function testOrderByNameAscending()
{ {
list ($user1, $user2) = $this->prepareUsers(); list ($user1, $user2) = $this->prepareUsers();
$this->doTestSorting( $this->doTestSorting(
UserFilter::ORDER_NAME, UserFilter::ORDER_NAME,
UserFilter::ORDER_ASC, UserFilter::ORDER_ASC,
[$user1, $user2]); [$user1, $user2]);
} }
public function testOrderByNameDescending() public function testOrderByNameDescending()
{ {
list ($user1, $user2) = $this->prepareUsers(); list ($user1, $user2) = $this->prepareUsers();
$this->doTestSorting( $this->doTestSorting(
UserFilter::ORDER_NAME, UserFilter::ORDER_NAME,
UserFilter::ORDER_DESC, UserFilter::ORDER_DESC,
[$user2, $user1]); [$user2, $user1]);
} }
public function testOrderByRegistrationTimeAscending() public function testOrderByRegistrationTimeAscending()
{ {
list ($user1, $user2) = $this->prepareUsers(); list ($user1, $user2) = $this->prepareUsers();
$this->doTestSorting( $this->doTestSorting(
UserFilter::ORDER_REGISTRATION_TIME, UserFilter::ORDER_REGISTRATION_TIME,
UserFilter::ORDER_ASC, UserFilter::ORDER_ASC,
[$user2, $user1]); [$user2, $user1]);
} }
public function testOrderByRegistrationTimeDescending() public function testOrderByRegistrationTimeDescending()
{ {
list ($user1, $user2) = $this->prepareUsers(); list ($user1, $user2) = $this->prepareUsers();
$this->doTestSorting( $this->doTestSorting(
UserFilter::ORDER_REGISTRATION_TIME, UserFilter::ORDER_REGISTRATION_TIME,
UserFilter::ORDER_DESC, UserFilter::ORDER_DESC,
[$user1, $user2]); [$user1, $user2]);
} }
private function prepareUsers() private function prepareUsers()
{ {
$user1 = self::getTestUser('beartato'); $user1 = self::getTestUser('beartato');
$user2 = self::getTestUser('reginald'); $user2 = self::getTestUser('reginald');
$user1->setRegistrationTime(date('c', mktime(3, 2, 1))); $user1->setRegistrationTime(date('c', mktime(3, 2, 1)));
$user2->setRegistrationTime(date('c', mktime(1, 2, 3))); $user2->setRegistrationTime(date('c', mktime(1, 2, 3)));
$userDao = $this->getUserDao(); $userDao = $this->getUserDao();
$userDao->save($user1); $userDao->save($user1);
$userDao->save($user2); $userDao->save($user2);
return [$user1, $user2]; return [$user1, $user2];
} }
private function doTestSorting($order, $orderDirection, $expectedUsers) private function doTestSorting($order, $orderDirection, $expectedUsers)
{ {
$userDao = $this->getUserDao(); $userDao = $this->getUserDao();
$searchFilter = new UserFilter(); $searchFilter = new UserFilter();
if ($order !== null) if ($order !== null)
$searchFilter->setOrder([$order => $orderDirection]); $searchFilter->setOrder([$order => $orderDirection]);
$result = $userDao->findFiltered($searchFilter, 1, 10); $result = $userDao->findFiltered($searchFilter, 1, 10);
$this->assertInstanceOf(Result::class, $result); $this->assertInstanceOf(Result::class, $result);
$this->assertEquals($searchFilter, $result->getSearchFilter()); $this->assertEquals($searchFilter, $result->getSearchFilter());
$this->assertEntitiesEqual(array_values($expectedUsers), array_values($result->getEntities())); $this->assertEntitiesEqual(array_values($expectedUsers), array_values($result->getEntities()));
$this->assertEquals(count($expectedUsers), $result->getTotalRecords()); $this->assertEquals(count($expectedUsers), $result->getTotalRecords());
$this->assertNull($result->getPageNumber()); $this->assertNull($result->getPageNumber());
$this->assertNull($result->getPageSize()); $this->assertNull($result->getPageSize());
} }
private function getUserDao() private function getUserDao()
{ {
return new UserDao( return new UserDao(
$this->databaseConnection, $this->databaseConnection,
$this->fileDaoMock, $this->fileDaoMock,
$this->thumbnailServiceMock); $this->thumbnailServiceMock);
} }
} }

View file

@ -8,109 +8,109 @@ use Szurubooru\Tests\AbstractDatabaseTestCase;
final class UserDaoTest extends AbstractDatabaseTestCase final class UserDaoTest extends AbstractDatabaseTestCase
{ {
private $fileDaoMock; private $fileDaoMock;
private $thumbnailServiceMock; private $thumbnailServiceMock;
public function setUp() public function setUp()
{ {
parent::setUp(); parent::setUp();
$this->fileDaoMock = $this->mock(PublicFileDao::class); $this->fileDaoMock = $this->mock(PublicFileDao::class);
$this->thumbnailServiceMock = $this->mock(ThumbnailService::class); $this->thumbnailServiceMock = $this->mock(ThumbnailService::class);
} }
public function testRetrievingByValidName() public function testRetrievingByValidName()
{ {
$userDao = $this->getUserDao(); $userDao = $this->getUserDao();
$user = self::getTestUser(); $user = self::getTestUser();
$userDao->save($user); $userDao->save($user);
$expected = $user; $expected = $user;
$actual = $userDao->findByName($user->getName()); $actual = $userDao->findByName($user->getName());
$this->assertEntitiesEqual($actual, $expected); $this->assertEntitiesEqual($actual, $expected);
} }
public function testRetrievingByInvalidName() public function testRetrievingByInvalidName()
{ {
$userDao = $this->getUserDao(); $userDao = $this->getUserDao();
$actual = $userDao->findByName('rubbish'); $actual = $userDao->findByName('rubbish');
$this->assertNull($actual); $this->assertNull($actual);
} }
public function testCheckingUserPresence() public function testCheckingUserPresence()
{ {
$userDao = $this->getUserDao(); $userDao = $this->getUserDao();
$this->assertFalse($userDao->hasAnyUsers()); $this->assertFalse($userDao->hasAnyUsers());
$user = self::getTestUser(); $user = self::getTestUser();
$userDao->save($user); $userDao->save($user);
$this->assertTrue($userDao->hasAnyUsers()); $this->assertTrue($userDao->hasAnyUsers());
} }
public function testNotLoadingAvatarContentForNewUsers() public function testNotLoadingAvatarContentForNewUsers()
{ {
$userDao = $this->getUserDao(); $userDao = $this->getUserDao();
$user = self::getTestUser(); $user = self::getTestUser();
$user->setAvatarStyle(User::AVATAR_STYLE_MANUAL); $user->setAvatarStyle(User::AVATAR_STYLE_MANUAL);
$userDao->save($user); $userDao->save($user);
$this->assertNull($user->getCustomAvatarSourceContent()); $this->assertNull($user->getCustomAvatarSourceContent());
} }
public function testLoadingContentUsersForExistingUsers() public function testLoadingContentUsersForExistingUsers()
{ {
$userDao = $this->getUserDao(); $userDao = $this->getUserDao();
$user = self::getTestUser(); $user = self::getTestUser();
$user->setAvatarStyle(User::AVATAR_STYLE_MANUAL); $user->setAvatarStyle(User::AVATAR_STYLE_MANUAL);
$userDao->save($user); $userDao->save($user);
$user = $userDao->findById($user->getId()); $user = $userDao->findById($user->getId());
$this->fileDaoMock $this->fileDaoMock
->expects($this->once()) ->expects($this->once())
->method('load') ->method('load')
->with($user->getCustomAvatarSourceContentPath())->willReturn('whatever'); ->with($user->getCustomAvatarSourceContentPath())->willReturn('whatever');
$this->assertEquals('whatever', $user->getCustomAvatarSourceContent()); $this->assertEquals('whatever', $user->getCustomAvatarSourceContent());
} }
public function testSavingContent() public function testSavingContent()
{ {
$userDao = $this->getUserDao(); $userDao = $this->getUserDao();
$user = self::getTestUser(); $user = self::getTestUser();
$user->setAvatarStyle(User::AVATAR_STYLE_MANUAL); $user->setAvatarStyle(User::AVATAR_STYLE_MANUAL);
$user->setCustomAvatarSourceContent('whatever'); $user->setCustomAvatarSourceContent('whatever');
$this->thumbnailServiceMock $this->thumbnailServiceMock
->expects($this->once()) ->expects($this->once())
->method('deleteUsedThumbnails') ->method('deleteUsedThumbnails')
->with($this->callback( ->with($this->callback(
function($subject) use ($user) function($subject) use ($user)
{ {
return $subject == $user->getCustomAvatarSourceContentPath(); return $subject == $user->getCustomAvatarSourceContentPath();
})); }));
$this->fileDaoMock $this->fileDaoMock
->expects($this->once()) ->expects($this->once())
->method('save') ->method('save')
->with($this->callback( ->with($this->callback(
function($subject) use ($user) function($subject) use ($user)
{ {
//callback is used because ->save() will create id, which is going to be used by the function below //callback is used because ->save() will create id, which is going to be used by the function below
return $subject == $user->getCustomAvatarSourceContentPath(); return $subject == $user->getCustomAvatarSourceContentPath();
}), 'whatever'); }), 'whatever');
$userDao->save($user); $userDao->save($user);
} }
private function getUserDao() private function getUserDao()
{ {
return new UserDao( return new UserDao(
$this->databaseConnection, $this->databaseConnection,
$this->fileDaoMock, $this->fileDaoMock,
$this->thumbnailServiceMock); $this->thumbnailServiceMock);
} }
} }

View file

@ -10,78 +10,78 @@ use Szurubooru\Tests\AbstractDatabaseTestCase;
final class DispatcherTest extends AbstractDatabaseTestCase final class DispatcherTest extends AbstractDatabaseTestCase
{ {
private $routerMock; private $routerMock;
private $configMock; private $configMock;
private $httpHelperMock; private $httpHelperMock;
private $authServiceMock; private $authServiceMock;
private $tokenServiceMock; private $tokenServiceMock;
private $routeRepositoryMock; private $routeRepositoryMock;
public function setUp() public function setUp()
{ {
parent::setUp(); parent::setUp();
$this->routerMock = $this->mock(Router::class); $this->routerMock = $this->mock(Router::class);
$this->configMock = $this->mockConfig(); $this->configMock = $this->mockConfig();
$this->httpHelperMock = $this->mock(HttpHelper::class); $this->httpHelperMock = $this->mock(HttpHelper::class);
$this->authServiceMock = $this->mock(AuthService::class); $this->authServiceMock = $this->mock(AuthService::class);
$this->tokenServiceMock = $this->mock(TokenService::class); $this->tokenServiceMock = $this->mock(TokenService::class);
$this->routeRepositoryMock = $this->mock(RouteRepository::class); $this->routeRepositoryMock = $this->mock(RouteRepository::class);
$this->configMock->set('misc/dumpSqlIntoQueries', 0); $this->configMock->set('misc/dumpSqlIntoQueries', 0);
} }
public function testDispatchingArrays() public function testDispatchingArrays()
{ {
$expected = ['test' => 'toy']; $expected = ['test' => 'toy'];
$this->httpHelperMock $this->httpHelperMock
->expects($this->exactly(2)) ->expects($this->exactly(2))
->method('setResponseCode') ->method('setResponseCode')
->withConsecutive([$this->equalTo(500)], [$this->equalTo(200)]); ->withConsecutive([$this->equalTo(500)], [$this->equalTo(200)]);
$this->routerMock->expects($this->once())->method('handle')->willReturn($expected); $this->routerMock->expects($this->once())->method('handle')->willReturn($expected);
$this->routeRepositoryMock->expects($this->once())->method('injectRoutes'); $this->routeRepositoryMock->expects($this->once())->method('injectRoutes');
$dispatcher = $this->getDispatcher(); $dispatcher = $this->getDispatcher();
$actual = $dispatcher->run('GET', '/'); $actual = $dispatcher->run('GET', '/');
unset($actual['__time']); unset($actual['__time']);
$this->assertEquals($expected, $actual); $this->assertEquals($expected, $actual);
} }
public function testDispatchingObjects() public function testDispatchingObjects()
{ {
$classData = new \StdClass; $classData = new \StdClass;
$classData->bunny = 5; $classData->bunny = 5;
$expected = ['bunny' => 5]; $expected = ['bunny' => 5];
$this->routerMock->expects($this->once())->method('handle')->willReturn($classData); $this->routerMock->expects($this->once())->method('handle')->willReturn($classData);
$this->routeRepositoryMock->expects($this->once())->method('injectRoutes'); $this->routeRepositoryMock->expects($this->once())->method('injectRoutes');
$dispatcher = $this->getDispatcher(); $dispatcher = $this->getDispatcher();
$actual = $dispatcher->run('GET', '/'); $actual = $dispatcher->run('GET', '/');
unset($actual['__time']); unset($actual['__time']);
$this->assertEquals($expected, $actual); $this->assertEquals($expected, $actual);
} }
public function testAuthorization() public function testAuthorization()
{ {
$this->httpHelperMock->expects($this->once())->method('getRequestHeader')->with($this->equalTo('X-Authorization-Token'))->willReturn('test'); $this->httpHelperMock->expects($this->once())->method('getRequestHeader')->with($this->equalTo('X-Authorization-Token'))->willReturn('test');
$this->tokenServiceMock->expects($this->once())->method('getByName'); $this->tokenServiceMock->expects($this->once())->method('getByName');
$this->routeRepositoryMock->expects($this->once())->method('injectRoutes'); $this->routeRepositoryMock->expects($this->once())->method('injectRoutes');
$dispatcher = $this->getDispatcher(); $dispatcher = $this->getDispatcher();
$dispatcher->run('GET', '/'); $dispatcher->run('GET', '/');
} }
private function getDispatcher() private function getDispatcher()
{ {
return new Dispatcher( return new Dispatcher(
$this->routerMock, $this->routerMock,
$this->configMock, $this->configMock,
$this->databaseConnection, $this->databaseConnection,
$this->httpHelperMock, $this->httpHelperMock,
$this->authServiceMock, $this->authServiceMock,
$this->tokenServiceMock, $this->tokenServiceMock,
$this->routeRepositoryMock); $this->routeRepositoryMock);
} }
} }

View file

@ -5,62 +5,62 @@ use Szurubooru\Tests\AbstractTestCase;
final class MimeHelperTest extends AbstractTestCase final class MimeHelperTest extends AbstractTestCase
{ {
public static function animatedGifProvider() public static function animatedGifProvider()
{ {
return return
[ [
['test_files/video.mp4', false], ['test_files/video.mp4', false],
['test_files/static.gif', false], ['test_files/static.gif', false],
['test_files/animated.gif', true], ['test_files/animated.gif', true],
['test_files/animated2.gif', true], ['test_files/animated2.gif', true],
['test_files/animated3.gif', true], ['test_files/animated3.gif', true],
['test_files/animated4.gif', true], ['test_files/animated4.gif', true],
]; ];
} }
public function testGettingMime() public function testGettingMime()
{ {
$expected = 'image/jpeg'; $expected = 'image/jpeg';
$actual = MimeHelper::getMimeTypeFromBuffer($this->getTestFile('image.jpg')); $actual = MimeHelper::getMimeTypeFromBuffer($this->getTestFile('image.jpg'));
$this->assertEquals($expected, $actual); $this->assertEquals($expected, $actual);
} }
public function testIsFlash() public function testIsFlash()
{ {
$this->assertTrue(MimeHelper::isFlash('application/x-shockwave-flash')); $this->assertTrue(MimeHelper::isFlash('application/x-shockwave-flash'));
$this->assertTrue(MimeHelper::isFlash('APPLICATION/X-SHOCKWAVE-FLASH')); $this->assertTrue(MimeHelper::isFlash('APPLICATION/X-SHOCKWAVE-FLASH'));
$this->assertFalse(MimeHelper::isFlash('something else')); $this->assertFalse(MimeHelper::isFlash('something else'));
} }
public function testIsImage() public function testIsImage()
{ {
$this->assertTrue(MimeHelper::isImage('IMAGE/JPEG')); $this->assertTrue(MimeHelper::isImage('IMAGE/JPEG'));
$this->assertTrue(MimeHelper::isImage('IMAGE/PNG')); $this->assertTrue(MimeHelper::isImage('IMAGE/PNG'));
$this->assertTrue(MimeHelper::isImage('IMAGE/GIF')); $this->assertTrue(MimeHelper::isImage('IMAGE/GIF'));
$this->assertTrue(MimeHelper::isImage('image/jpeg')); $this->assertTrue(MimeHelper::isImage('image/jpeg'));
$this->assertTrue(MimeHelper::isImage('image/png')); $this->assertTrue(MimeHelper::isImage('image/png'));
$this->assertTrue(MimeHelper::isImage('image/gif')); $this->assertTrue(MimeHelper::isImage('image/gif'));
$this->assertFalse(MimeHelper::isImage('something else')); $this->assertFalse(MimeHelper::isImage('something else'));
} }
public function testIsVideo() public function testIsVideo()
{ {
$this->assertTrue(MimeHelper::isVideo('VIDEO/MP4')); $this->assertTrue(MimeHelper::isVideo('VIDEO/MP4'));
$this->assertTrue(MimeHelper::isVideo('video/mp4')); $this->assertTrue(MimeHelper::isVideo('video/mp4'));
$this->assertTrue(MimeHelper::isVideo('APPLICATION/OGG')); $this->assertTrue(MimeHelper::isVideo('APPLICATION/OGG'));
$this->assertTrue(MimeHelper::isVideo('application/ogg')); $this->assertTrue(MimeHelper::isVideo('application/ogg'));
$this->assertFalse(MimeHelper::isVideo('something else')); $this->assertFalse(MimeHelper::isVideo('something else'));
} }
/** /**
* @dataProvider animatedGifProvider * @dataProvider animatedGifProvider
*/ */
public function testIsAnimatedGif($path, $expected) public function testIsAnimatedGif($path, $expected)
{ {
$fullPath = __DIR__ $fullPath = __DIR__
. DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..'
. DIRECTORY_SEPARATOR . $path; . DIRECTORY_SEPARATOR . $path;
$actual = MimeHelper::isBufferAnimatedGif(file_get_contents($fullPath)); $actual = MimeHelper::isBufferAnimatedGif(file_get_contents($fullPath));
$this->assertEquals($expected, $actual); $this->assertEquals($expected, $actual);
} }
} }

View file

@ -5,8 +5,8 @@ use Szurubooru\Tests\AbstractTestCase;
final class ProgramExecutorTest extends AbstractTestCase final class ProgramExecutorTest extends AbstractTestCase
{ {
public function testIsProgramAvailable() public function testIsProgramAvailable()
{ {
$this->assertFalse(ProgramExecutor::isProgramAvailable('there_is_no_way_my_os_can_have_this_program')); $this->assertFalse(ProgramExecutor::isProgramAvailable('there_is_no_way_my_os_can_have_this_program'));
} }
} }

View file

@ -6,22 +6,22 @@ use Szurubooru\Tests\AbstractTestCase;
final class DeleteQueryTest extends AbstractTestCase final class DeleteQueryTest extends AbstractTestCase
{ {
public function testDefault() public function testDefault()
{ {
$query = $this->getDeleteQuery(); $query = $this->getDeleteQuery();
$this->assertEquals('DELETE FROM test', $query->getQuery()); $this->assertEquals('DELETE FROM test', $query->getQuery());
} }
public function testBasicWhere() public function testBasicWhere()
{ {
$query = $this->getDeleteQuery(); $query = $this->getDeleteQuery();
$query->where('column', 'value'); $query->where('column', 'value');
$this->assertRegExp('/^DELETE FROM test WHERE column = :[\w]*$/', $query->getQuery()); $this->assertRegExp('/^DELETE FROM test WHERE column = :[\w]*$/', $query->getQuery());
} }
private function getDeleteQuery() private function getDeleteQuery()
{ {
$pdoMock = $this->mock(PDOEx::class); $pdoMock = $this->mock(PDOEx::class);
return new DeleteQuery($pdoMock, 'test'); return new DeleteQuery($pdoMock, 'test');
} }
} }

View file

@ -6,16 +6,16 @@ use Szurubooru\Tests\AbstractTestCase;
final class InsertQueryTest extends AbstractTestCase final class InsertQueryTest extends AbstractTestCase
{ {
public function testDefault() public function testDefault()
{ {
$query = $this->getInsertQuery(); $query = $this->getInsertQuery();
$query->values(['key1' => 'value', 'key2' => 'value2']); $query->values(['key1' => 'value', 'key2' => 'value2']);
$this->assertRegExp('/^INSERT INTO test \(key1, key2\) VALUES \(:\w*, :\w*\)$/', $query->getQuery()); $this->assertRegExp('/^INSERT INTO test \(key1, key2\) VALUES \(:\w*, :\w*\)$/', $query->getQuery());
} }
private function getInsertQuery() private function getInsertQuery()
{ {
$pdoMock = $this->mock(PDOEx::class); $pdoMock = $this->mock(PDOEx::class);
return new InsertQuery($pdoMock, 'test'); return new InsertQuery($pdoMock, 'test');
} }
} }

View file

@ -6,183 +6,183 @@ use Szurubooru\Tests\AbstractTestCase;
final class SelectQueryTest extends AbstractTestCase final class SelectQueryTest extends AbstractTestCase
{ {
public function testDefault() public function testDefault()
{ {
$query = $this->getSelectQuery(); $query = $this->getSelectQuery();
$this->assertEquals('SELECT test.* FROM test', $query->getQuery()); $this->assertEquals('SELECT test.* FROM test', $query->getQuery());
} }
public function testAdditionalColumns() public function testAdditionalColumns()
{ {
$query = $this->getSelectQuery(); $query = $this->getSelectQuery();
$query->select('SUM(1) AS sum'); $query->select('SUM(1) AS sum');
$query->select('something else'); $query->select('something else');
$this->assertEquals('SELECT test.*, SUM(1) AS sum, something else FROM test', $query->getQuery()); $this->assertEquals('SELECT test.*, SUM(1) AS sum, something else FROM test', $query->getQuery());
} }
public function testResettingAdditionalColumns() public function testResettingAdditionalColumns()
{ {
$query = $this->getSelectQuery(); $query = $this->getSelectQuery();
$query->select(null); $query->select(null);
$query->select('SUM(1) AS sum'); $query->select('SUM(1) AS sum');
$this->assertEquals('SELECT SUM(1) AS sum FROM test', $query->getQuery()); $this->assertEquals('SELECT SUM(1) AS sum FROM test', $query->getQuery());
} }
public function testInnerJoin() public function testInnerJoin()
{ {
$query = $this->getSelectQuery(); $query = $this->getSelectQuery();
$query->innerJoin('test2', 'test2.id = test.foreignId'); $query->innerJoin('test2', 'test2.id = test.foreignId');
$this->assertEquals('SELECT test.* FROM test INNER JOIN test2 ON test2.id = test.foreignId', $query->getQuery()); $this->assertEquals('SELECT test.* FROM test INNER JOIN test2 ON test2.id = test.foreignId', $query->getQuery());
} }
public function testMultipleInnerJoins() public function testMultipleInnerJoins()
{ {
$query = $this->getSelectQuery(); $query = $this->getSelectQuery();
$query->innerJoin('test2', 'test2.id = test.foreignId'); $query->innerJoin('test2', 'test2.id = test.foreignId');
$query->innerJoin('test3', 'test3.id = test2.foreignId'); $query->innerJoin('test3', 'test3.id = test2.foreignId');
$this->assertEquals('SELECT test.* FROM test INNER JOIN test2 ON test2.id = test.foreignId INNER JOIN test3 ON test3.id = test2.foreignId', $query->getQuery()); $this->assertEquals('SELECT test.* FROM test INNER JOIN test2 ON test2.id = test.foreignId INNER JOIN test3 ON test3.id = test2.foreignId', $query->getQuery());
} }
public function testSelectAfterInnerJoin() public function testSelectAfterInnerJoin()
{ {
$query = $this->getSelectQuery(); $query = $this->getSelectQuery();
$query->innerJoin('test2', 'test2.id = test.foreignId'); $query->innerJoin('test2', 'test2.id = test.foreignId');
$query->select('whatever'); $query->select('whatever');
$this->assertEquals('SELECT test.*, whatever FROM test INNER JOIN test2 ON test2.id = test.foreignId', $query->getQuery()); $this->assertEquals('SELECT test.*, whatever FROM test INNER JOIN test2 ON test2.id = test.foreignId', $query->getQuery());
} }
public function testBasicWhere() public function testBasicWhere()
{ {
$query = $this->getSelectQuery(); $query = $this->getSelectQuery();
$query->where('column', 'value'); $query->where('column', 'value');
$this->assertRegExp('/^SELECT test\.\* FROM test WHERE column = :[\w]*$/', $query->getQuery()); $this->assertRegExp('/^SELECT test\.\* FROM test WHERE column = :[\w]*$/', $query->getQuery());
} }
public function testMultipleWhere() public function testMultipleWhere()
{ {
$query = $this->getSelectQuery(); $query = $this->getSelectQuery();
$query->where('column1', 'value1'); $query->where('column1', 'value1');
$query->where('column2', 'value2'); $query->where('column2', 'value2');
$this->assertRegExp('/^SELECT test\.\* FROM test WHERE column1 = :\w* AND column2 = :\w*$/', $query->getQuery()); $this->assertRegExp('/^SELECT test\.\* FROM test WHERE column1 = :\w* AND column2 = :\w*$/', $query->getQuery());
} }
public function testManualWhere() public function testManualWhere()
{ {
$query = $this->getSelectQuery(); $query = $this->getSelectQuery();
$query->where('column1 >= ? AND column2 <= ?', ['value1', 'value2']); $query->where('column1 >= ? AND column2 <= ?', ['value1', 'value2']);
$this->assertRegExp('/^SELECT test\.\* FROM test WHERE column1 >= :\w* AND column2 <= :\w*$/', $query->getQuery()); $this->assertRegExp('/^SELECT test\.\* FROM test WHERE column1 >= :\w* AND column2 <= :\w*$/', $query->getQuery());
} }
public function testWhereNull() public function testWhereNull()
{ {
$query = $this->getSelectQuery(); $query = $this->getSelectQuery();
$query->where('column', null); $query->where('column', null);
$this->assertRegExp('/^SELECT test\.\* FROM test WHERE column IS NULL$/', $query->getQuery()); $this->assertRegExp('/^SELECT test\.\* FROM test WHERE column IS NULL$/', $query->getQuery());
} }
public function testResettingWhere() public function testResettingWhere()
{ {
$query = $this->getSelectQuery(); $query = $this->getSelectQuery();
$query->where('column1', 'value1'); $query->where('column1', 'value1');
$query->where(null); $query->where(null);
$query->where('column2', 'value2'); $query->where('column2', 'value2');
$this->assertRegExp('/^SELECT test\.\* FROM test WHERE column2 = :\w*$/', $query->getQuery()); $this->assertRegExp('/^SELECT test\.\* FROM test WHERE column2 = :\w*$/', $query->getQuery());
} }
public function testEmptyIn() public function testEmptyIn()
{ {
$query = $this->getSelectQuery(); $query = $this->getSelectQuery();
$query->where('column', []); $query->where('column', []);
$this->assertRegExp('/^SELECT test\.\* FROM test WHERE 0$/', $query->getQuery()); $this->assertRegExp('/^SELECT test\.\* FROM test WHERE 0$/', $query->getQuery());
} }
public function testIn() public function testIn()
{ {
$query = $this->getSelectQuery(); $query = $this->getSelectQuery();
$query->where('column', ['val1', 'val2']); $query->where('column', ['val1', 'val2']);
$this->assertRegExp('/^SELECT test\.\* FROM test WHERE column IN \(:\w*, :\w*\)$/', $query->getQuery()); $this->assertRegExp('/^SELECT test\.\* FROM test WHERE column IN \(:\w*, :\w*\)$/', $query->getQuery());
} }
public function testMixedInAndWhere() public function testMixedInAndWhere()
{ {
$query = $this->getSelectQuery(); $query = $this->getSelectQuery();
$query->where('column1', ['val1', 'val2']); $query->where('column1', ['val1', 'val2']);
$query->where('column2', 'val3'); $query->where('column2', 'val3');
$this->assertRegExp('/^SELECT test\.\* FROM test WHERE column1 IN \(:\w*, :\w*\) AND column2 = :\w*$/', $query->getQuery()); $this->assertRegExp('/^SELECT test\.\* FROM test WHERE column1 IN \(:\w*, :\w*\) AND column2 = :\w*$/', $query->getQuery());
} }
public function testGroupBy() public function testGroupBy()
{ {
$query = $this->getSelectQuery(); $query = $this->getSelectQuery();
$query->groupBy('test.id'); $query->groupBy('test.id');
$this->assertEquals('SELECT test.* FROM test GROUP BY test.id', $query->getQuery()); $this->assertEquals('SELECT test.* FROM test GROUP BY test.id', $query->getQuery());
} }
public function testGroupByAndOrderBy() public function testGroupByAndOrderBy()
{ {
$query = $this->getSelectQuery(); $query = $this->getSelectQuery();
$query->groupBy('test.id'); $query->groupBy('test.id');
$query->orderBy('test.whatever'); $query->orderBy('test.whatever');
$this->assertEquals('SELECT test.* FROM test GROUP BY test.id ORDER BY test.whatever', $query->getQuery()); $this->assertEquals('SELECT test.* FROM test GROUP BY test.id ORDER BY test.whatever', $query->getQuery());
} }
public function testOrderBy() public function testOrderBy()
{ {
$query = $this->getSelectQuery(); $query = $this->getSelectQuery();
$query->orderBy('id DESC'); $query->orderBy('id DESC');
$this->assertEquals('SELECT test.* FROM test ORDER BY id DESC', $query->getQuery()); $this->assertEquals('SELECT test.* FROM test ORDER BY id DESC', $query->getQuery());
} }
public function testOrderByFlavor2() public function testOrderByFlavor2()
{ {
$query = $this->getSelectQuery(); $query = $this->getSelectQuery();
$query->orderBy('id', 'DESC'); $query->orderBy('id', 'DESC');
$this->assertEquals('SELECT test.* FROM test ORDER BY id DESC', $query->getQuery()); $this->assertEquals('SELECT test.* FROM test ORDER BY id DESC', $query->getQuery());
} }
public function testOrderByMultiple() public function testOrderByMultiple()
{ {
$query = $this->getSelectQuery(); $query = $this->getSelectQuery();
$query->orderBy('id', 'DESC'); $query->orderBy('id', 'DESC');
$query->orderBy('id2', 'ASC'); $query->orderBy('id2', 'ASC');
$this->assertEquals('SELECT test.* FROM test ORDER BY id DESC, id2 ASC', $query->getQuery()); $this->assertEquals('SELECT test.* FROM test ORDER BY id DESC, id2 ASC', $query->getQuery());
} }
public function testResettingOrderBy() public function testResettingOrderBy()
{ {
$query = $this->getSelectQuery(); $query = $this->getSelectQuery();
$query->orderBy('id', 'DESC'); $query->orderBy('id', 'DESC');
$query->orderBy(null); $query->orderBy(null);
$query->orderBy('id2', 'ASC'); $query->orderBy('id2', 'ASC');
$this->assertEquals('SELECT test.* FROM test ORDER BY id2 ASC', $query->getQuery()); $this->assertEquals('SELECT test.* FROM test ORDER BY id2 ASC', $query->getQuery());
} }
public function testLimit() public function testLimit()
{ {
$query = $this->getSelectQuery(); $query = $this->getSelectQuery();
$query->limit(5); $query->limit(5);
$this->assertEquals('SELECT test.* FROM test LIMIT 5', $query->getQuery()); $this->assertEquals('SELECT test.* FROM test LIMIT 5', $query->getQuery());
} }
public function testLimitWithOffset() public function testLimitWithOffset()
{ {
$query = $this->getSelectQuery(); $query = $this->getSelectQuery();
$query->offset(2); $query->offset(2);
$query->limit(5); $query->limit(5);
$this->assertEquals('SELECT test.* FROM test LIMIT 5 OFFSET 2', $query->getQuery()); $this->assertEquals('SELECT test.* FROM test LIMIT 5 OFFSET 2', $query->getQuery());
} }
public function testOffsetWithoutLimit() public function testOffsetWithoutLimit()
{ {
$query = $this->getSelectQuery(); $query = $this->getSelectQuery();
$query->offset(2); $query->offset(2);
$query->limit(null); $query->limit(null);
$this->assertEquals('SELECT test.* FROM test', $query->getQuery()); $this->assertEquals('SELECT test.* FROM test', $query->getQuery());
} }
private function getSelectQuery() private function getSelectQuery()
{ {
$pdoMock = $this->mock(PDOEx::class); $pdoMock = $this->mock(PDOEx::class);
return new SelectQuery($pdoMock, 'test'); return new SelectQuery($pdoMock, 'test');
} }
} }

View file

@ -6,16 +6,16 @@ use Szurubooru\Tests\AbstractTestCase;
final class UpdateQueryTest extends AbstractTestCase final class UpdateQueryTest extends AbstractTestCase
{ {
public function testDefault() public function testDefault()
{ {
$query = $this->getUpdateQuery(); $query = $this->getUpdateQuery();
$query->set(['key1' => 'value', 'key2' => 'value2']); $query->set(['key1' => 'value', 'key2' => 'value2']);
$this->assertRegExp('/^UPDATE test SET key1 = :\w*, key2 = :\w*$/', $query->getQuery()); $this->assertRegExp('/^UPDATE test SET key1 = :\w*, key2 = :\w*$/', $query->getQuery());
} }
private function getUpdateQuery() private function getUpdateQuery()
{ {
$pdoMock = $this->mock(PDOEx::class); $pdoMock = $this->mock(PDOEx::class);
return new UpdateQuery($pdoMock, 'test'); return new UpdateQuery($pdoMock, 'test');
} }
} }

View file

@ -7,25 +7,25 @@ use Szurubooru\Tests\AbstractTestCase;
final class PrivilegeTest extends AbstractTestCase final class PrivilegeTest extends AbstractTestCase
{ {
public function testConstNaming() public function testConstNaming()
{ {
$refl = new \ReflectionClass(Privilege::class); $refl = new \ReflectionClass(Privilege::class);
foreach ($refl->getConstants() as $key => $value) foreach ($refl->getConstants() as $key => $value)
{ {
$value = strtoupper(ltrim(preg_replace('/[A-Z]/', '_\0', $value), '_')); $value = strtoupper(ltrim(preg_replace('/[A-Z]/', '_\0', $value), '_'));
$this->assertEquals($key, $value); $this->assertEquals($key, $value);
} }
} }
public function testConfigSectionNaming() public function testConfigSectionNaming()
{ {
$refl = new \ReflectionClass(Privilege::class); $refl = new \ReflectionClass(Privilege::class);
$constants = array_values($refl->getConstants()); $constants = array_values($refl->getConstants());
$config = Injector::get(Config::class); $config = Injector::get(Config::class);
foreach ($config->security->privileges as $key => $value) foreach ($config->security->privileges as $key => $value)
{ {
$this->assertTrue(in_array($key, $constants), "$key not in constants"); $this->assertTrue(in_array($key, $constants), "$key not in constants");
} }
} }
} }

View file

@ -8,54 +8,54 @@ use Szurubooru\Tests\AbstractDatabaseTestCase;
final class RouteRepositoryTest extends AbstractDatabaseTestCase final class RouteRepositoryTest extends AbstractDatabaseTestCase
{ {
public function testFactory() public function testFactory()
{ {
$routeRepository = Injector::get(RouteRepository::class); $routeRepository = Injector::get(RouteRepository::class);
$this->assertNotEmpty($routeRepository->getRoutes()); $this->assertNotEmpty($routeRepository->getRoutes());
} }
public function testRouteMethods() public function testRouteMethods()
{ {
$routeRepository = Injector::get(RouteRepository::class); $routeRepository = Injector::get(RouteRepository::class);
foreach ($routeRepository->getRoutes() as $route) foreach ($routeRepository->getRoutes() as $route)
{ {
foreach ($route->getMethods() as $method) foreach ($route->getMethods() as $method)
{ {
$this->assertContains($method, ['GET', 'POST', 'PUT', 'DELETE']); $this->assertContains($method, ['GET', 'POST', 'PUT', 'DELETE']);
} }
} }
} }
public function testRouteUrls() public function testRouteUrls()
{ {
$routeRepository = Injector::get(RouteRepository::class); $routeRepository = Injector::get(RouteRepository::class);
foreach ($routeRepository->getRoutes() as $route) foreach ($routeRepository->getRoutes() as $route)
{ {
$this->assertEquals(0, strpos($route->getUrl(), '/api/')); $this->assertEquals(0, strpos($route->getUrl(), '/api/'));
} }
} }
public function testRouteInjection() public function testRouteInjection()
{ {
$routerMock = $this->mock(Router::class); $routerMock = $this->mock(Router::class);
$routeMock = $this->mock(AbstractRoute::class); $routeMock = $this->mock(AbstractRoute::class);
$routeMock->expects($this->once())->method('getMethods')->willReturn(['POST', 'GET']); $routeMock->expects($this->once())->method('getMethods')->willReturn(['POST', 'GET']);
$routeMock->expects($this->atLeast(1))->method('getUrl')->willReturn('/test'); $routeMock->expects($this->atLeast(1))->method('getUrl')->willReturn('/test');
$routerMock->expects($this->once())->method('post')->with('/test', $this->anything()); $routerMock->expects($this->once())->method('post')->with('/test', $this->anything());
$routerMock->expects($this->once())->method('get')->with('/test', $this->anything()); $routerMock->expects($this->once())->method('get')->with('/test', $this->anything());
$routeRepository = new RouteRepository([$routeMock]); $routeRepository = new RouteRepository([$routeMock]);
$routeRepository->injectRoutes($routerMock); $routeRepository->injectRoutes($routerMock);
} }
public function testRouteCallbackInjection() public function testRouteCallbackInjection()
{ {
$router = new Router(); $router = new Router();
$routeMock = $this->mock(AbstractRoute::class); $routeMock = $this->mock(AbstractRoute::class);
$routeMock->expects($this->once())->method('getMethods')->willReturn(['POST', 'GET']); $routeMock->expects($this->once())->method('getMethods')->willReturn(['POST', 'GET']);
$routeMock->expects($this->atLeast(1))->method('getUrl')->willReturn('/test'); $routeMock->expects($this->atLeast(1))->method('getUrl')->willReturn('/test');
$routeMock->expects($this->atLeast(1))->method('work'); $routeMock->expects($this->atLeast(1))->method('work');
$routeRepository = new RouteRepository([$routeMock]); $routeRepository = new RouteRepository([$routeMock]);
$routeRepository->injectRoutes($router); $routeRepository->injectRoutes($router);
$router->handle('GET', '/test'); $router->handle('GET', '/test');
} }
} }

View file

@ -6,119 +6,119 @@ use Szurubooru\Tests\TestController;
final class PostDaoTest extends AbstractTestCase final class PostDaoTest extends AbstractTestCase
{ {
public function testParameterlessHandling() public function testParameterlessHandling()
{ {
$router = new Router; $router = new Router;
$testOk = false; $testOk = false;
$router->get('/test', function() use (&$testOk) { $testOk = true; }); $router->get('/test', function() use (&$testOk) { $testOk = true; });
$router->handle('GET', '/test'); $router->handle('GET', '/test');
$this->assertTrue($testOk); $this->assertTrue($testOk);
} }
public function testTrailingSlashes() public function testTrailingSlashes()
{ {
$router = new Router; $router = new Router;
$testOk = false; $testOk = false;
$router->get('/test', function() use (&$testOk) { $testOk = true; }); $router->get('/test', function() use (&$testOk) { $testOk = true; });
$router->handle('GET', '/test/'); $router->handle('GET', '/test/');
$this->assertTrue($testOk); $this->assertTrue($testOk);
} }
public function testUnhandledMethod() public function testUnhandledMethod()
{ {
$router = new Router; $router = new Router;
$router->get('/test', function() { $this->fail('Route shouldn\'t be executed'); }); $router->get('/test', function() { $this->fail('Route shouldn\'t be executed'); });
$this->setExpectedException(\DomainException::class); $this->setExpectedException(\DomainException::class);
$router->handle('POST', '/test'); $router->handle('POST', '/test');
} }
public function testUnhandledQuery() public function testUnhandledQuery()
{ {
$router = new Router; $router = new Router;
$router->get('/test', function() { $this->fail('Route shouldn\'t be executed'); }); $router->get('/test', function() { $this->fail('Route shouldn\'t be executed'); });
$this->setExpectedException(\DomainException::class); $this->setExpectedException(\DomainException::class);
$router->handle('GET', '/test2'); $router->handle('GET', '/test2');
} }
public function testTwoMethodsHandling() public function testTwoMethodsHandling()
{ {
$router = new Router; $router = new Router;
$testOk = false; $testOk = false;
$router->get('/test', function() { $this->fail('Route shouldn\'t be executed'); }); $router->get('/test', function() { $this->fail('Route shouldn\'t be executed'); });
$router->post('/test', function() use (&$testOk) { $testOk = true; }); $router->post('/test', function() use (&$testOk) { $testOk = true; });
$router->handle('POST', '/test'); $router->handle('POST', '/test');
$this->assertTrue($testOk); $this->assertTrue($testOk);
} }
public function testParameterHandling() public function testParameterHandling()
{ {
$router = new Router; $router = new Router;
$testOk = false; $testOk = false;
$router->get('/tests/:id', function($args) use (&$testOk) { $router->get('/tests/:id', function($args) use (&$testOk) {
extract($args); extract($args);
$this->assertEquals($id, 'test_id'); $this->assertEquals($id, 'test_id');
$testOk = true; }); $testOk = true; });
$router->handle('GET', '/tests/test_id'); $router->handle('GET', '/tests/test_id');
$this->assertTrue($testOk); $this->assertTrue($testOk);
} }
public function testTwoParameterHandling() public function testTwoParameterHandling()
{ {
$router = new Router; $router = new Router;
$testOk = false; $testOk = false;
$router->get('/tests/:id/:page', function($args) use (&$testOk) { $router->get('/tests/:id/:page', function($args) use (&$testOk) {
extract($args); extract($args);
$this->assertEquals($id, 'test_id'); $this->assertEquals($id, 'test_id');
$this->assertEquals($page, 'test_page'); $this->assertEquals($page, 'test_page');
$testOk = true; }); $testOk = true; });
$router->handle('GET', '/tests/test_id/test_page'); $router->handle('GET', '/tests/test_id/test_page');
$this->assertTrue($testOk); $this->assertTrue($testOk);
} }
public function testMissingParameterHandling() public function testMissingParameterHandling()
{ {
$router = new Router; $router = new Router;
$testOk = false; $testOk = false;
$router->get('/tests/:id', function($args) use (&$testOk) { $router->get('/tests/:id', function($args) use (&$testOk) {
extract($args); extract($args);
$this->assertEquals($id, 'test_id'); $this->assertEquals($id, 'test_id');
$this->assertFalse(isset($page)); $this->assertFalse(isset($page));
$testOk = true; }); $testOk = true; });
$router->handle('GET', '/tests/test_id'); $router->handle('GET', '/tests/test_id');
$this->assertTrue($testOk); $this->assertTrue($testOk);
} }
public function testOutputHandling() public function testOutputHandling()
{ {
$router = new Router; $router = new Router;
$router->get('/test', function() { return 'ok'; }); $router->get('/test', function() { return 'ok'; });
$output = $router->handle('GET', '/test'); $output = $router->handle('GET', '/test');
$this->assertEquals('ok', $output); $this->assertEquals('ok', $output);
} }
public function testRoutingToClassMethods() public function testRoutingToClassMethods()
{ {
$router = new Router; $router = new Router;
$testController = new TestController(); $testController = new TestController();
$router->get('/normal', [$testController, 'normalRoute']); $router->get('/normal', [$testController, 'normalRoute']);
$router->get('/static', [TestController::class, 'staticRoute']); $router->get('/static', [TestController::class, 'staticRoute']);
$this->assertEquals('normal', $router->handle('GET', '/normal')); $this->assertEquals('normal', $router->handle('GET', '/normal'));
$this->assertEquals('static', $router->handle('GET', '/static')); $this->assertEquals('static', $router->handle('GET', '/static'));
} }
} }
class TestController class TestController
{ {
public function normalRoute() public function normalRoute()
{ {
return 'normal'; return 'normal';
} }
public static function staticRoute() public static function staticRoute()
{ {
return 'static'; return 'static';
} }
} }

View file

@ -7,76 +7,76 @@ use \Szurubooru\Tests\AbstractTestCase;
final class UserSearchParserTest extends AbstractTestCase final class UserSearchParserTest extends AbstractTestCase
{ {
private $inputReader; private $inputReader;
private $userSearchParser; private $userSearchParser;
public function setUp() public function setUp()
{ {
parent::setUp(); parent::setUp();
$this->inputReader = new InputReader; $this->inputReader = new InputReader;
$this->userSearchParser = new UserSearchParser(); $this->userSearchParser = new UserSearchParser();
} }
public function testDefaultOrder() public function testDefaultOrder()
{ {
$filter = $this->userSearchParser->createFilterFromInputReader($this->inputReader); $filter = $this->userSearchParser->createFilterFromInputReader($this->inputReader);
$this->assertOrderEquals([UserFilter::ORDER_NAME => UserFilter::ORDER_ASC], $filter->getOrder()); $this->assertOrderEquals([UserFilter::ORDER_NAME => UserFilter::ORDER_ASC], $filter->getOrder());
} }
public function testInvalidOrder() public function testInvalidOrder()
{ {
$this->inputReader->order = 'invalid,desc'; $this->inputReader->order = 'invalid,desc';
$this->setExpectedException(\Exception::class); $this->setExpectedException(\Exception::class);
$filter = $this->userSearchParser->createFilterFromInputReader($this->inputReader); $filter = $this->userSearchParser->createFilterFromInputReader($this->inputReader);
} }
public function testInvalidOrderDirection() public function testInvalidOrderDirection()
{ {
$this->inputReader->order = 'name,invalid'; $this->inputReader->order = 'name,invalid';
$this->setExpectedException(\Exception::class); $this->setExpectedException(\Exception::class);
$filter = $this->userSearchParser->createFilterFromInputReader($this->inputReader); $filter = $this->userSearchParser->createFilterFromInputReader($this->inputReader);
} }
public function testParamOrder() public function testParamOrder()
{ {
$this->inputReader->order = 'name,desc'; $this->inputReader->order = 'name,desc';
$filter = $this->userSearchParser->createFilterFromInputReader($this->inputReader); $filter = $this->userSearchParser->createFilterFromInputReader($this->inputReader);
$this->assertOrderEquals([UserFilter::ORDER_NAME => UserFilter::ORDER_DESC], $filter->getOrder()); $this->assertOrderEquals([UserFilter::ORDER_NAME => UserFilter::ORDER_DESC], $filter->getOrder());
} }
public function testTokenOverwriteDefaultOrder() public function testTokenOverwriteDefaultOrder()
{ {
$this->inputReader->query = 'order:name,desc'; $this->inputReader->query = 'order:name,desc';
$filter = $this->userSearchParser->createFilterFromInputReader($this->inputReader); $filter = $this->userSearchParser->createFilterFromInputReader($this->inputReader);
$this->assertOrderEquals([UserFilter::ORDER_NAME => UserFilter::ORDER_DESC], $filter->getOrder()); $this->assertOrderEquals([UserFilter::ORDER_NAME => UserFilter::ORDER_DESC], $filter->getOrder());
} }
public function testTokenOrder() public function testTokenOrder()
{ {
$this->inputReader->query = 'order:registration_time,desc'; $this->inputReader->query = 'order:registration_time,desc';
$filter = $this->userSearchParser->createFilterFromInputReader($this->inputReader); $filter = $this->userSearchParser->createFilterFromInputReader($this->inputReader);
$this->assertOrderEquals([ $this->assertOrderEquals([
UserFilter::ORDER_REGISTRATION_TIME => UserFilter::ORDER_DESC, UserFilter::ORDER_REGISTRATION_TIME => UserFilter::ORDER_DESC,
UserFilter::ORDER_NAME => UserFilter::ORDER_ASC], UserFilter::ORDER_NAME => UserFilter::ORDER_ASC],
$filter->getOrder()); $filter->getOrder());
} }
public function testParamAndTokenOrder() public function testParamAndTokenOrder()
{ {
$this->inputReader->order = 'name,desc'; $this->inputReader->order = 'name,desc';
$this->inputReader->query = 'order:registration_time,desc'; $this->inputReader->query = 'order:registration_time,desc';
$filter = $this->userSearchParser->createFilterFromInputReader($this->inputReader); $filter = $this->userSearchParser->createFilterFromInputReader($this->inputReader);
$this->assertOrderEquals([ $this->assertOrderEquals([
UserFilter::ORDER_REGISTRATION_TIME => UserFilter::ORDER_DESC, UserFilter::ORDER_REGISTRATION_TIME => UserFilter::ORDER_DESC,
UserFilter::ORDER_NAME => UserFilter::ORDER_DESC], UserFilter::ORDER_NAME => UserFilter::ORDER_DESC],
$filter->getOrder()); $filter->getOrder());
} }
private function assertOrderEquals($expected, $actual) private function assertOrderEquals($expected, $actual)
{ {
$this->assertEquals($expected, $actual); $this->assertEquals($expected, $actual);
//also test associative array's key order - something that PHPUnit doesn't seem to do //also test associative array's key order - something that PHPUnit doesn't seem to do
$this->assertEquals(array_values($expected), array_values($actual)); $this->assertEquals(array_values($expected), array_values($actual));
$this->assertEquals(array_keys($expected), array_keys($actual)); $this->assertEquals(array_keys($expected), array_keys($actual));
} }
} }

View file

@ -12,168 +12,168 @@ use Szurubooru\Tests\AbstractTestCase;
final class AuthServiceTest extends AbstractTestCase final class AuthServiceTest extends AbstractTestCase
{ {
private $configMock; private $configMock;
private $passwordServiceMock; private $passwordServiceMock;
private $timeServiceMock; private $timeServiceMock;
private $tokenServiceMock; private $tokenServiceMock;
private $userServiceMock; private $userServiceMock;
public function setUp() public function setUp()
{ {
parent::setUp(); parent::setUp();
$this->configMock = $this->mockConfig(); $this->configMock = $this->mockConfig();
$this->passwordServiceMock = $this->mock(PasswordService::class); $this->passwordServiceMock = $this->mock(PasswordService::class);
$this->timeServiceMock = $this->mock(TimeService::class); $this->timeServiceMock = $this->mock(TimeService::class);
$this->tokenServiceMock = $this->mock(TokenService::class); $this->tokenServiceMock = $this->mock(TokenService::class);
$this->userServiceMock = $this->mock(UserService::class); $this->userServiceMock = $this->mock(UserService::class);
} }
public function testInvalidPassword() public function testInvalidPassword()
{ {
$this->configMock->set('security/needEmailActivationToRegister', false); $this->configMock->set('security/needEmailActivationToRegister', false);
$this->passwordServiceMock->expects($this->once())->method('isHashValid')->with('godzilla', 'salt', 'hash')->willReturn(false); $this->passwordServiceMock->expects($this->once())->method('isHashValid')->with('godzilla', 'salt', 'hash')->willReturn(false);
$testUser = new User(); $testUser = new User();
$testUser->setName('dummy'); $testUser->setName('dummy');
$testUser->setPasswordHash('hash'); $testUser->setPasswordHash('hash');
$testUser->setPasswordSalt('salt'); $testUser->setPasswordSalt('salt');
$this->userServiceMock->expects($this->once())->method('getByNameOrEmail')->willReturn($testUser); $this->userServiceMock->expects($this->once())->method('getByNameOrEmail')->willReturn($testUser);
$this->setExpectedException(\Exception::class, 'Specified password is invalid'); $this->setExpectedException(\Exception::class, 'Specified password is invalid');
$authService = $this->getAuthService(); $authService = $this->getAuthService();
$formData = new LoginFormData(); $formData = new LoginFormData();
$formData->userNameOrEmail = 'dummy'; $formData->userNameOrEmail = 'dummy';
$formData->password = 'godzilla'; $formData->password = 'godzilla';
$authService->loginFromCredentials($formData); $authService->loginFromCredentials($formData);
} }
public function testValidCredentials() public function testValidCredentials()
{ {
$this->configMock->set('security/needEmailActivationToRegister', false); $this->configMock->set('security/needEmailActivationToRegister', false);
$this->passwordServiceMock->expects($this->once())->method('isHashValid')->with('godzilla', 'salt', 'hash')->willReturn(true); $this->passwordServiceMock->expects($this->once())->method('isHashValid')->with('godzilla', 'salt', 'hash')->willReturn(true);
$testUser = new User('an unusual database identifier'); $testUser = new User('an unusual database identifier');
$testUser->setName('dummy'); $testUser->setName('dummy');
$testUser->setPasswordHash('hash'); $testUser->setPasswordHash('hash');
$testUser->setPasswordSalt('salt'); $testUser->setPasswordSalt('salt');
$this->userServiceMock->expects($this->once())->method('getByNameOrEmail')->willReturn($testUser); $this->userServiceMock->expects($this->once())->method('getByNameOrEmail')->willReturn($testUser);
$testToken = new Token(); $testToken = new Token();
$testToken->setName('mummy'); $testToken->setName('mummy');
$this->tokenServiceMock->expects($this->once())->method('createAndSaveToken')->with( $this->tokenServiceMock->expects($this->once())->method('createAndSaveToken')->with(
$testUser->getId(), $testUser->getId(),
Token::PURPOSE_LOGIN)->willReturn($testToken); Token::PURPOSE_LOGIN)->willReturn($testToken);
$authService = $this->getAuthService(); $authService = $this->getAuthService();
$formData = new LoginFormData(); $formData = new LoginFormData();
$formData->userNameOrEmail = 'dummy'; $formData->userNameOrEmail = 'dummy';
$formData->password = 'godzilla'; $formData->password = 'godzilla';
$authService->loginFromCredentials($formData); $authService->loginFromCredentials($formData);
$this->assertTrue($authService->isLoggedIn()); $this->assertTrue($authService->isLoggedIn());
$this->assertEquals($testUser, $authService->getLoggedInUser()); $this->assertEquals($testUser, $authService->getLoggedInUser());
$this->assertNotNull($authService->getLoginToken()); $this->assertNotNull($authService->getLoginToken());
$this->assertEquals('mummy', $authService->getLoginToken()->getName()); $this->assertEquals('mummy', $authService->getLoginToken()->getName());
} }
public function testValidCredentialsUnconfirmedEmail() public function testValidCredentialsUnconfirmedEmail()
{ {
$this->configMock->set('security/needEmailActivationToRegister', true); $this->configMock->set('security/needEmailActivationToRegister', true);
$this->passwordServiceMock->expects($this->never())->method('isHashValid')->willReturn('hash'); $this->passwordServiceMock->expects($this->never())->method('isHashValid')->willReturn('hash');
$testUser = new User(); $testUser = new User();
$testUser->setName('dummy'); $testUser->setName('dummy');
$testUser->setPasswordHash('hash'); $testUser->setPasswordHash('hash');
$this->userServiceMock->expects($this->once())->method('getByNameOrEmail')->willReturn($testUser); $this->userServiceMock->expects($this->once())->method('getByNameOrEmail')->willReturn($testUser);
$this->setExpectedException(\Exception::class, 'User didn\'t confirm account yet'); $this->setExpectedException(\Exception::class, 'User didn\'t confirm account yet');
$authService = $this->getAuthService(); $authService = $this->getAuthService();
$formData = new LoginFormData(); $formData = new LoginFormData();
$formData->userNameOrEmail = 'dummy'; $formData->userNameOrEmail = 'dummy';
$formData->password = 'godzilla'; $formData->password = 'godzilla';
$authService->loginFromCredentials($formData); $authService->loginFromCredentials($formData);
$this->assertFalse($authService->isLoggedIn()); $this->assertFalse($authService->isLoggedIn());
$this->assertNull($testUser, $authService->getLoggedInUser()); $this->assertNull($testUser, $authService->getLoggedInUser());
$this->assertNull($authService->getLoginToken()); $this->assertNull($authService->getLoginToken());
} }
public function testInvalidToken() public function testInvalidToken()
{ {
$this->configMock->set('security/needEmailActivationToRegister', false); $this->configMock->set('security/needEmailActivationToRegister', false);
$this->setExpectedException(\Exception::class); $this->setExpectedException(\Exception::class);
$authService = $this->getAuthService(); $authService = $this->getAuthService();
$testToken = new Token(); $testToken = new Token();
$authService->loginFromToken($testToken); $authService->loginFromToken($testToken);
} }
public function testValidToken() public function testValidToken()
{ {
$this->configMock->set('security/needEmailActivationToRegister', false); $this->configMock->set('security/needEmailActivationToRegister', false);
$testUser = new User(5); $testUser = new User(5);
$testUser->setName('dummy'); $testUser->setName('dummy');
$this->userServiceMock->expects($this->once())->method('getById')->willReturn($testUser); $this->userServiceMock->expects($this->once())->method('getById')->willReturn($testUser);
$testToken = new Token(); $testToken = new Token();
$testToken->setName('dummy_token'); $testToken->setName('dummy_token');
$testToken->setAdditionalData($testUser->getId()); $testToken->setAdditionalData($testUser->getId());
$testToken->setPurpose(Token::PURPOSE_LOGIN); $testToken->setPurpose(Token::PURPOSE_LOGIN);
$authService = $this->getAuthService(); $authService = $this->getAuthService();
$authService->loginFromToken($testToken); $authService->loginFromToken($testToken);
$this->assertTrue($authService->isLoggedIn()); $this->assertTrue($authService->isLoggedIn());
$this->assertEquals($testUser, $authService->getLoggedInUser()); $this->assertEquals($testUser, $authService->getLoggedInUser());
$this->assertNotNull($authService->getLoginToken()); $this->assertNotNull($authService->getLoginToken());
$this->assertEquals('dummy_token', $authService->getLoginToken()->getName()); $this->assertEquals('dummy_token', $authService->getLoginToken()->getName());
} }
public function testValidTokenInvalidPurpose() public function testValidTokenInvalidPurpose()
{ {
$this->configMock->set('security/needEmailActivationToRegister', false); $this->configMock->set('security/needEmailActivationToRegister', false);
$testToken = new Token(); $testToken = new Token();
$testToken->setName('dummy_token'); $testToken->setName('dummy_token');
$testToken->setAdditionalData('whatever'); $testToken->setAdditionalData('whatever');
$testToken->setPurpose(null); $testToken->setPurpose(null);
$this->setExpectedException(\Exception::class, 'This token is not a login token'); $this->setExpectedException(\Exception::class, 'This token is not a login token');
$authService = $this->getAuthService(); $authService = $this->getAuthService();
$authService->loginFromToken($testToken); $authService->loginFromToken($testToken);
$this->assertFalse($authService->isLoggedIn()); $this->assertFalse($authService->isLoggedIn());
$this->assertNull($authService->getLoggedInUser()); $this->assertNull($authService->getLoggedInUser());
$this->assertNull($authService->getLoginToken()); $this->assertNull($authService->getLoginToken());
} }
public function testValidTokenUnconfirmedEmail() public function testValidTokenUnconfirmedEmail()
{ {
$this->configMock->set('security/needEmailActivationToRegister', true); $this->configMock->set('security/needEmailActivationToRegister', true);
$testUser = new User(5); $testUser = new User(5);
$testUser->setName('dummy'); $testUser->setName('dummy');
$this->userServiceMock->expects($this->once())->method('getById')->willReturn($testUser); $this->userServiceMock->expects($this->once())->method('getById')->willReturn($testUser);
$testToken = new Token(); $testToken = new Token();
$testToken->setName('dummy_token'); $testToken->setName('dummy_token');
$testToken->setAdditionalData($testUser->getId()); $testToken->setAdditionalData($testUser->getId());
$testToken->setPurpose(Token::PURPOSE_LOGIN); $testToken->setPurpose(Token::PURPOSE_LOGIN);
$this->setExpectedException(\Exception::class, 'User didn\'t confirm account yet'); $this->setExpectedException(\Exception::class, 'User didn\'t confirm account yet');
$authService = $this->getAuthService(); $authService = $this->getAuthService();
$authService->loginFromToken($testToken); $authService->loginFromToken($testToken);
$this->assertFalse($authService->isLoggedIn()); $this->assertFalse($authService->isLoggedIn());
$this->assertNull($testUser, $authService->getLoggedInUser()); $this->assertNull($testUser, $authService->getLoggedInUser());
$this->assertNull($authService->getLoginToken()); $this->assertNull($authService->getLoginToken());
} }
private function getAuthService() private function getAuthService()
{ {
return new AuthService( return new AuthService(
$this->configMock, $this->configMock,
$this->passwordServiceMock, $this->passwordServiceMock,
$this->timeServiceMock, $this->timeServiceMock,
$this->tokenServiceMock, $this->tokenServiceMock,
$this->userServiceMock); $this->userServiceMock);
} }
} }

View file

@ -12,68 +12,68 @@ use Szurubooru\Tests\AbstractTestCase;
final class FavoritesServiceTest extends AbstractTestCase final class FavoritesServiceTest extends AbstractTestCase
{ {
private $favoritesDaoMock; private $favoritesDaoMock;
private $scoreDaoMock; private $scoreDaoMock;
private $userDaoMock; private $userDaoMock;
private $transactionManagerMock; private $transactionManagerMock;
private $timeServiceMock; private $timeServiceMock;
public function setUp() public function setUp()
{ {
parent::setUp(); parent::setUp();
$this->favoritesDaoMock = $this->mock(FavoritesDao::class); $this->favoritesDaoMock = $this->mock(FavoritesDao::class);
$this->scoreDaoMock = $this->mock(ScoreDao::class); $this->scoreDaoMock = $this->mock(ScoreDao::class);
$this->userDaoMock = $this->mock(UserDao::class); $this->userDaoMock = $this->mock(UserDao::class);
$this->transactionManagerMock = $this->mockTransactionManager(); $this->transactionManagerMock = $this->mockTransactionManager();
$this->timeServiceMock = $this->mock(TimeService::class); $this->timeServiceMock = $this->mock(TimeService::class);
} }
public function testAdding() public function testAdding()
{ {
$user = new User(1); $user = new User(1);
$post = new Post(2); $post = new Post(2);
$fav = new Favorite(); $fav = new Favorite();
$fav->setUserId($user->getId()); $fav->setUserId($user->getId());
$fav->setPostId($post->getId()); $fav->setPostId($post->getId());
$this->favoritesDaoMock->expects($this->once())->method('set')->with($user, $post); $this->favoritesDaoMock->expects($this->once())->method('set')->with($user, $post);
$favoritesService = $this->getFavoritesService(); $favoritesService = $this->getFavoritesService();
$favoritesService->addFavorite($user, $post); $favoritesService->addFavorite($user, $post);
} }
public function testDeleting() public function testDeleting()
{ {
$user = new User(); $user = new User();
$post = new Post(); $post = new Post();
$fav = new Favorite(3); $fav = new Favorite(3);
$this->favoritesDaoMock->expects($this->once())->method('delete')->with($user, $post); $this->favoritesDaoMock->expects($this->once())->method('delete')->with($user, $post);
$favoritesService = $this->getFavoritesService(); $favoritesService = $this->getFavoritesService();
$favoritesService->deleteFavorite($user, $post); $favoritesService->deleteFavorite($user, $post);
} }
public function testGettingByPost() public function testGettingByPost()
{ {
$post = new Post(); $post = new Post();
$fav1 = new Favorite(); $fav1 = new Favorite();
$fav2 = new Favorite(); $fav2 = new Favorite();
$fav1->setUser(new User(1)); $fav1->setUser(new User(1));
$fav2->setUser(new User(2)); $fav2->setUser(new User(2));
$this->favoritesDaoMock->expects($this->once())->method('findByEntity')->with($post)->willReturn([$fav1, $fav2]); $this->favoritesDaoMock->expects($this->once())->method('findByEntity')->with($post)->willReturn([$fav1, $fav2]);
$this->userDaoMock->expects($this->once())->method('findByIds')->with([1, 2]); $this->userDaoMock->expects($this->once())->method('findByIds')->with([1, 2]);
$favoritesService = $this->getFavoritesService(); $favoritesService = $this->getFavoritesService();
$favoritesService->getFavoriteUsers($post); $favoritesService->getFavoriteUsers($post);
} }
private function getFavoritesService() private function getFavoritesService()
{ {
return new FavoritesService( return new FavoritesService(
$this->favoritesDaoMock, $this->favoritesDaoMock,
$this->scoreDaoMock, $this->scoreDaoMock,
$this->userDaoMock, $this->userDaoMock,
$this->transactionManagerMock, $this->transactionManagerMock,
$this->timeServiceMock); $this->timeServiceMock);
} }
} }

View file

@ -10,285 +10,285 @@ use Szurubooru\Tests\AbstractTestCase;
final class HistoryServiceTest extends AbstractTestCase final class HistoryServiceTest extends AbstractTestCase
{ {
private $snapshotDaoMock; private $snapshotDaoMock;
private $timeServiceMock; private $timeServiceMock;
private $authServiceMock; private $authServiceMock;
private $transactionManagerMock; private $transactionManagerMock;
public static function dataDifferenceProvider() public static function dataDifferenceProvider()
{ {
yield yield
[ [
[], [],
[], [],
['+' => [], '-' => []] ['+' => [], '-' => []]
]; ];
yield yield
[ [
['key' => 'unchangedValue'], ['key' => 'unchangedValue'],
['key' => 'unchangedValue'], ['key' => 'unchangedValue'],
['+' => [], '-' => []] ['+' => [], '-' => []]
]; ];
yield yield
[ [
['key' => 'newValue'], ['key' => 'newValue'],
[], [],
[ [
'+' => ['key' => 'newValue'], '+' => ['key' => 'newValue'],
'-' => [] '-' => []
] ]
]; ];
yield yield
[ [
[], [],
['key' => 'deletedValue'], ['key' => 'deletedValue'],
[ [
'+' => [], '+' => [],
'-' => ['key' => 'deletedValue'] '-' => ['key' => 'deletedValue']
] ]
]; ];
yield yield
[ [
['key' => 'changedValue'], ['key' => 'changedValue'],
['key' => 'oldValue'], ['key' => 'oldValue'],
[ [
'+' => ['key' => 'changedValue'], '+' => ['key' => 'changedValue'],
'-' => ['key' => 'oldValue'] '-' => ['key' => 'oldValue']
] ]
]; ];
yield yield
[ [
['key' => []], ['key' => []],
['key' => []], ['key' => []],
[ [
'+' => [], '+' => [],
'-' => [] '-' => []
] ]
]; ];
yield yield
[ [
['key' => ['newArrayElement']], ['key' => ['newArrayElement']],
['key' => []], ['key' => []],
[ [
'+' => ['key' => ['newArrayElement']], '+' => ['key' => ['newArrayElement']],
'-' => [] '-' => []
] ]
]; ];
yield yield
[ [
['key' => []], ['key' => []],
['key' => ['removedArrayElement']], ['key' => ['removedArrayElement']],
[ [
'+' => [], '+' => [],
'-' => ['key' => ['removedArrayElement']] '-' => ['key' => ['removedArrayElement']]
] ]
]; ];
yield yield
[ [
['key' => ['unchangedArrayElement', 'newArrayElement']], ['key' => ['unchangedArrayElement', 'newArrayElement']],
['key' => ['unchangedArrayElement', 'oldArrayElement']], ['key' => ['unchangedArrayElement', 'oldArrayElement']],
[ [
'+' => ['key' => ['newArrayElement']], '+' => ['key' => ['newArrayElement']],
'-' => ['key' => ['oldArrayElement']] '-' => ['key' => ['oldArrayElement']]
] ]
]; ];
} }
public function setUp() public function setUp()
{ {
parent::setUp(); parent::setUp();
$this->snapshotDaoMock = $this->mock(SnapshotDao::class); $this->snapshotDaoMock = $this->mock(SnapshotDao::class);
$this->transactionManagerMock = $this->mockTransactionManager(); $this->transactionManagerMock = $this->mockTransactionManager();
$this->timeServiceMock = $this->mock(TimeService::class); $this->timeServiceMock = $this->mock(TimeService::class);
$this->authServiceMock = $this->mock(AuthService::class); $this->authServiceMock = $this->mock(AuthService::class);
} }
/** /**
* @dataProvider dataDifferenceProvider * @dataProvider dataDifferenceProvider
*/ */
public function testDataDifference($newData, $oldData, $expectedResult) public function testDataDifference($newData, $oldData, $expectedResult)
{ {
$historyService = $this->getHistoryService(); $historyService = $this->getHistoryService();
$this->assertEquals($expectedResult, $historyService->getDataDifference($newData, $oldData)); $this->assertEquals($expectedResult, $historyService->getDataDifference($newData, $oldData));
} }
public static function mergingProvider() public static function mergingProvider()
{ {
{ {
//basic merging //basic merging
$oldSnapshot = new Snapshot(1); $oldSnapshot = new Snapshot(1);
$oldSnapshot->setTime(date('c', 1)); $oldSnapshot->setTime(date('c', 1));
$oldSnapshot->setOperation(Snapshot::OPERATION_CREATION); $oldSnapshot->setOperation(Snapshot::OPERATION_CREATION);
$oldSnapshot->setData(['old' => '1']); $oldSnapshot->setData(['old' => '1']);
$newSnapshot = new Snapshot(2); $newSnapshot = new Snapshot(2);
$newSnapshot->setTime(date('c', 2)); $newSnapshot->setTime(date('c', 2));
$newSnapshot->setOperation(Snapshot::OPERATION_CHANGE); $newSnapshot->setOperation(Snapshot::OPERATION_CHANGE);
$newSnapshot->setData(['new' => '2']); $newSnapshot->setData(['new' => '2']);
$expectedSnapshot = new Snapshot(1); $expectedSnapshot = new Snapshot(1);
$expectedSnapshot->setTime(date('c', 3)); $expectedSnapshot->setTime(date('c', 3));
$expectedSnapshot->setOperation(Snapshot::OPERATION_CREATION); $expectedSnapshot->setOperation(Snapshot::OPERATION_CREATION);
$expectedSnapshot->setData(['new' => '2']); $expectedSnapshot->setData(['new' => '2']);
$expectedSnapshot->setDataDifference(['+' => ['new' => '2'], '-' => []]); $expectedSnapshot->setDataDifference(['+' => ['new' => '2'], '-' => []]);
yield [[$oldSnapshot], $newSnapshot, $expectedSnapshot, date('c', 3), [2]]; yield [[$oldSnapshot], $newSnapshot, $expectedSnapshot, date('c', 3), [2]];
} }
{ {
//too big time gap for merge //too big time gap for merge
$oldSnapshot = new Snapshot(1); $oldSnapshot = new Snapshot(1);
$oldSnapshot->setOperation(Snapshot::OPERATION_CREATION); $oldSnapshot->setOperation(Snapshot::OPERATION_CREATION);
$oldSnapshot->setData(['old' => '1']); $oldSnapshot->setData(['old' => '1']);
$newSnapshot = new Snapshot(2); $newSnapshot = new Snapshot(2);
$newSnapshot->setOperation(Snapshot::OPERATION_CHANGE); $newSnapshot->setOperation(Snapshot::OPERATION_CHANGE);
$newSnapshot->setData(['new' => '2']); $newSnapshot->setData(['new' => '2']);
$expectedSnapshot = new Snapshot(2); $expectedSnapshot = new Snapshot(2);
$expectedSnapshot->setTime(date('c', 3000)); $expectedSnapshot->setTime(date('c', 3000));
$expectedSnapshot->setOperation(Snapshot::OPERATION_CHANGE); $expectedSnapshot->setOperation(Snapshot::OPERATION_CHANGE);
$expectedSnapshot->setData(['new' => '2']); $expectedSnapshot->setData(['new' => '2']);
$expectedSnapshot->setDataDifference(['+' => ['new' => '2'], '-' => ['old' => '1']]); $expectedSnapshot->setDataDifference(['+' => ['new' => '2'], '-' => ['old' => '1']]);
yield [[$oldSnapshot], $newSnapshot, $expectedSnapshot, date('c', 3000), []]; yield [[$oldSnapshot], $newSnapshot, $expectedSnapshot, date('c', 3000), []];
} }
{ {
//operations done by different user shouldn't be merged //operations done by different user shouldn't be merged
$oldSnapshot = new Snapshot(1); $oldSnapshot = new Snapshot(1);
$oldSnapshot->setOperation(Snapshot::OPERATION_CREATION); $oldSnapshot->setOperation(Snapshot::OPERATION_CREATION);
$oldSnapshot->setData(['old' => '1']); $oldSnapshot->setData(['old' => '1']);
$oldSnapshot->setUserId(1); $oldSnapshot->setUserId(1);
$newSnapshot = new Snapshot(2); $newSnapshot = new Snapshot(2);
$newSnapshot->setOperation(Snapshot::OPERATION_CHANGE); $newSnapshot->setOperation(Snapshot::OPERATION_CHANGE);
$newSnapshot->setData(['new' => '2']); $newSnapshot->setData(['new' => '2']);
$newSnapshot->setUserId(2); $newSnapshot->setUserId(2);
$expectedSnapshot = new Snapshot(2); $expectedSnapshot = new Snapshot(2);
$expectedSnapshot->setOperation(Snapshot::OPERATION_CHANGE); $expectedSnapshot->setOperation(Snapshot::OPERATION_CHANGE);
$expectedSnapshot->setData(['new' => '2']); $expectedSnapshot->setData(['new' => '2']);
$expectedSnapshot->setDataDifference(['+' => ['new' => '2'], '-' => ['old' => '1']]); $expectedSnapshot->setDataDifference(['+' => ['new' => '2'], '-' => ['old' => '1']]);
$expectedSnapshot->setUserId(null); $expectedSnapshot->setUserId(null);
yield [[$oldSnapshot], $newSnapshot, $expectedSnapshot, null, []]; yield [[$oldSnapshot], $newSnapshot, $expectedSnapshot, null, []];
} }
{ {
//merge that leaves only delete snapshot should be removed altogether //merge that leaves only delete snapshot should be removed altogether
$oldSnapshot = new Snapshot(1); $oldSnapshot = new Snapshot(1);
$oldSnapshot->setOperation(Snapshot::OPERATION_CREATION); $oldSnapshot->setOperation(Snapshot::OPERATION_CREATION);
$oldSnapshot->setData(['old' => '1']); $oldSnapshot->setData(['old' => '1']);
$newSnapshot = new Snapshot(2); $newSnapshot = new Snapshot(2);
$newSnapshot->setOperation(Snapshot::OPERATION_DELETE); $newSnapshot->setOperation(Snapshot::OPERATION_DELETE);
$newSnapshot->setData(['new' => '2']); $newSnapshot->setData(['new' => '2']);
yield [[$oldSnapshot], $newSnapshot, null, null, [2, 1]]; yield [[$oldSnapshot], $newSnapshot, null, null, [2, 1]];
} }
{ {
//chaining to creation snapshot should preserve operation type //chaining to creation snapshot should preserve operation type
$oldestSnapshot = new Snapshot(1); $oldestSnapshot = new Snapshot(1);
$oldestSnapshot->setOperation(Snapshot::OPERATION_CREATION); $oldestSnapshot->setOperation(Snapshot::OPERATION_CREATION);
$oldestSnapshot->setData(['oldest' => '0']); $oldestSnapshot->setData(['oldest' => '0']);
$oldSnapshot = new Snapshot(2); $oldSnapshot = new Snapshot(2);
$oldSnapshot->setOperation(Snapshot::OPERATION_CHANGE); $oldSnapshot->setOperation(Snapshot::OPERATION_CHANGE);
$oldSnapshot->setData(['old' => '1']); $oldSnapshot->setData(['old' => '1']);
$newSnapshot = new Snapshot(3); $newSnapshot = new Snapshot(3);
$newSnapshot->setOperation(Snapshot::OPERATION_CHANGE); $newSnapshot->setOperation(Snapshot::OPERATION_CHANGE);
$newSnapshot->setData(['oldest' => '0', 'new' => '2']); $newSnapshot->setData(['oldest' => '0', 'new' => '2']);
$expectedSnapshot = new Snapshot(1); $expectedSnapshot = new Snapshot(1);
$expectedSnapshot->setOperation(Snapshot::OPERATION_CREATION); $expectedSnapshot->setOperation(Snapshot::OPERATION_CREATION);
$expectedSnapshot->setData(['oldest' => '0', 'new' => '2']); $expectedSnapshot->setData(['oldest' => '0', 'new' => '2']);
$expectedSnapshot->setDataDifference(['+' => ['oldest' => '0', 'new' => '2'], '-' => []]); $expectedSnapshot->setDataDifference(['+' => ['oldest' => '0', 'new' => '2'], '-' => []]);
yield [[$oldSnapshot, $oldestSnapshot], $newSnapshot, $expectedSnapshot, null, [3, 2]]; yield [[$oldSnapshot, $oldestSnapshot], $newSnapshot, $expectedSnapshot, null, [3, 2]];
$newSnapshot = clone($newSnapshot); $newSnapshot = clone($newSnapshot);
$newSnapshot->setId(null); $newSnapshot->setId(null);
yield [[$oldSnapshot, $oldestSnapshot], $newSnapshot, $expectedSnapshot, null, [2]]; yield [[$oldSnapshot, $oldestSnapshot], $newSnapshot, $expectedSnapshot, null, [2]];
} }
{ {
//chaining to edit snapshot should update operation type //chaining to edit snapshot should update operation type
$oldestSnapshot = new Snapshot(1); $oldestSnapshot = new Snapshot(1);
$oldestSnapshot->setOperation(Snapshot::OPERATION_CREATION); $oldestSnapshot->setOperation(Snapshot::OPERATION_CREATION);
$oldestSnapshot->setData(['oldest' => '0']); $oldestSnapshot->setData(['oldest' => '0']);
$oldestSnapshot->setTime(date('c', 1)); $oldestSnapshot->setTime(date('c', 1));
$oldSnapshot = new Snapshot(2); $oldSnapshot = new Snapshot(2);
$oldSnapshot->setOperation(Snapshot::OPERATION_CHANGE); $oldSnapshot->setOperation(Snapshot::OPERATION_CHANGE);
$oldSnapshot->setData(['old' => '1']); $oldSnapshot->setData(['old' => '1']);
$oldSnapshot->setTime(date('c', 400)); $oldSnapshot->setTime(date('c', 400));
$newSnapshot = new Snapshot(3); $newSnapshot = new Snapshot(3);
$newSnapshot->setOperation(Snapshot::OPERATION_DELETE); $newSnapshot->setOperation(Snapshot::OPERATION_DELETE);
$newSnapshot->setData(['new' => '2']); $newSnapshot->setData(['new' => '2']);
$newSnapshot->setTime(date('c', 401)); $newSnapshot->setTime(date('c', 401));
$expectedSnapshot = new Snapshot(2); $expectedSnapshot = new Snapshot(2);
$expectedSnapshot->setOperation(Snapshot::OPERATION_DELETE); $expectedSnapshot->setOperation(Snapshot::OPERATION_DELETE);
$expectedSnapshot->setData(['new' => '2']); $expectedSnapshot->setData(['new' => '2']);
$expectedSnapshot->setDataDifference(['+' => ['new' => '2'], '-' => ['oldest' => '0']]); $expectedSnapshot->setDataDifference(['+' => ['new' => '2'], '-' => ['oldest' => '0']]);
$expectedSnapshot->setTime(date('c', 402)); $expectedSnapshot->setTime(date('c', 402));
yield [[$oldSnapshot, $oldestSnapshot], $newSnapshot, $expectedSnapshot, date('c', 402), [3]]; yield [[$oldSnapshot, $oldestSnapshot], $newSnapshot, $expectedSnapshot, date('c', 402), [3]];
$newSnapshot = clone($newSnapshot); $newSnapshot = clone($newSnapshot);
$newSnapshot->setId(null); $newSnapshot->setId(null);
yield [[$oldSnapshot, $oldestSnapshot], $newSnapshot, $expectedSnapshot, date('c', 402), []]; yield [[$oldSnapshot, $oldestSnapshot], $newSnapshot, $expectedSnapshot, date('c', 402), []];
} }
} }
/** /**
* @dataProvider mergingProvider * @dataProvider mergingProvider
*/ */
public function testMerging($earlierSnapshots, $newSnapshot, $expectedSnapshot, $currentTime, $expectedDeletions = []) public function testMerging($earlierSnapshots, $newSnapshot, $expectedSnapshot, $currentTime, $expectedDeletions = [])
{ {
$this->timeServiceMock->method('getCurrentTime')->willReturn($currentTime); $this->timeServiceMock->method('getCurrentTime')->willReturn($currentTime);
$this->snapshotDaoMock $this->snapshotDaoMock
->expects($this->once()) ->expects($this->once())
->method('findEarlierSnapshots') ->method('findEarlierSnapshots')
->willReturn($earlierSnapshots); ->willReturn($earlierSnapshots);
$this->snapshotDaoMock $this->snapshotDaoMock
->expects($this->exactly($expectedSnapshot === null ? 0 : 1)) ->expects($this->exactly($expectedSnapshot === null ? 0 : 1))
->method('save') ->method('save')
->will($this->returnCallback(function($param) use (&$actualSnapshot) ->will($this->returnCallback(function($param) use (&$actualSnapshot)
{ {
$actualSnapshot = $param; $actualSnapshot = $param;
})); }));
$this->snapshotDaoMock $this->snapshotDaoMock
->expects($this->exactly(count($expectedDeletions))) ->expects($this->exactly(count($expectedDeletions)))
->method('deleteById') ->method('deleteById')
->withConsecutive(...array_map(function($del) { return [$del]; }, $expectedDeletions)); ->withConsecutive(...array_map(function($del) { return [$del]; }, $expectedDeletions));
$historyService = $this->getHistoryService(); $historyService = $this->getHistoryService();
$historyService->saveSnapshot($newSnapshot); $historyService->saveSnapshot($newSnapshot);
$this->assertEntitiesEqual($expectedSnapshot, $actualSnapshot); $this->assertEntitiesEqual($expectedSnapshot, $actualSnapshot);
} }
private function getHistoryService() private function getHistoryService()
{ {
return new HistoryService( return new HistoryService(
$this->snapshotDaoMock, $this->snapshotDaoMock,
$this->transactionManagerMock, $this->transactionManagerMock,
$this->timeServiceMock, $this->timeServiceMock,
$this->authServiceMock); $this->authServiceMock);
} }
} }

View file

@ -9,141 +9,141 @@ use Szurubooru\Tests\AbstractTestCase;
final class ImageManipulatorTest extends AbstractTestCase final class ImageManipulatorTest extends AbstractTestCase
{ {
public static function imageManipulatorProvider() public static function imageManipulatorProvider()
{ {
$manipulators = []; $manipulators = [];
$manipulators[] = self::getImagickImageManipulator(); $manipulators[] = self::getImagickImageManipulator();
$manipulators[] = self::getGdImageManipulator(); $manipulators[] = self::getGdImageManipulator();
$manipulators[] = self::getAutoImageManipulator(); $manipulators[] = self::getAutoImageManipulator();
return array_map(function($manipulator) return array_map(function($manipulator)
{ {
return [$manipulator]; return [$manipulator];
}, array_filter($manipulators)); }, array_filter($manipulators));
} }
public function testImagickAvailability() public function testImagickAvailability()
{ {
if (!self::getImagickImageManipulator()) if (!self::getImagickImageManipulator())
$this->markTestSkipped('Imagick is not installed'); $this->markTestSkipped('Imagick is not installed');
$this->assertTrue(true); $this->assertTrue(true);
} }
public function testGdAvailability() public function testGdAvailability()
{ {
if (!self::getGdImageManipulator()) if (!self::getGdImageManipulator())
$this->markTestSkipped('Gd is not installed'); $this->markTestSkipped('Gd is not installed');
$this->assertTrue(true); $this->assertTrue(true);
} }
/** /**
* @dataProvider imageManipulatorProvider * @dataProvider imageManipulatorProvider
*/ */
public function testImageSize($imageManipulator) public function testImageSize($imageManipulator)
{ {
$image = $imageManipulator->loadFromBuffer($this->getTestFile('image.jpg')); $image = $imageManipulator->loadFromBuffer($this->getTestFile('image.jpg'));
$this->assertEquals(640, $imageManipulator->getImageWidth($image)); $this->assertEquals(640, $imageManipulator->getImageWidth($image));
$this->assertEquals(480, $imageManipulator->getImageHeight($image)); $this->assertEquals(480, $imageManipulator->getImageHeight($image));
} }
/** /**
* @dataProvider imageManipulatorProvider * @dataProvider imageManipulatorProvider
*/ */
public function testNonImage($imageManipulator) public function testNonImage($imageManipulator)
{ {
$this->assertNull($imageManipulator->loadFromBuffer($this->getTestFile('flash.swf'))); $this->assertNull($imageManipulator->loadFromBuffer($this->getTestFile('flash.swf')));
} }
/** /**
* @dataProvider imageManipulatorProvider * @dataProvider imageManipulatorProvider
*/ */
public function testImageResizing($imageManipulator) public function testImageResizing($imageManipulator)
{ {
$image = $imageManipulator->loadFromBuffer($this->getTestFile('image.jpg')); $image = $imageManipulator->loadFromBuffer($this->getTestFile('image.jpg'));
$imageManipulator->resizeImage($image, 400, 500); $imageManipulator->resizeImage($image, 400, 500);
$this->assertEquals(400, $imageManipulator->getImageWidth($image)); $this->assertEquals(400, $imageManipulator->getImageWidth($image));
$this->assertEquals(500, $imageManipulator->getImageHeight($image)); $this->assertEquals(500, $imageManipulator->getImageHeight($image));
} }
/** /**
* @dataProvider imageManipulatorProvider * @dataProvider imageManipulatorProvider
*/ */
public function testImageCroppingBleedWidth($imageManipulator) public function testImageCroppingBleedWidth($imageManipulator)
{ {
$image = $imageManipulator->loadFromBuffer($this->getTestFile('image.jpg')); $image = $imageManipulator->loadFromBuffer($this->getTestFile('image.jpg'));
$imageManipulator->cropImage($image, 640, 480, 200, 200); $imageManipulator->cropImage($image, 640, 480, 200, 200);
$this->assertEquals(440, $imageManipulator->getImageWidth($image)); $this->assertEquals(440, $imageManipulator->getImageWidth($image));
$this->assertEquals(280, $imageManipulator->getImageHeight($image)); $this->assertEquals(280, $imageManipulator->getImageHeight($image));
} }
/** /**
* @dataProvider imageManipulatorProvider * @dataProvider imageManipulatorProvider
*/ */
public function testImageCroppingBleedPosition($imageManipulator) public function testImageCroppingBleedPosition($imageManipulator)
{ {
$image = $imageManipulator->loadFromBuffer($this->getTestFile('image.jpg')); $image = $imageManipulator->loadFromBuffer($this->getTestFile('image.jpg'));
$imageManipulator->cropImage($image, 640, 480, -200, -200); $imageManipulator->cropImage($image, 640, 480, -200, -200);
$this->assertEquals(440, $imageManipulator->getImageWidth($image)); $this->assertEquals(440, $imageManipulator->getImageWidth($image));
$this->assertEquals(280, $imageManipulator->getImageHeight($image)); $this->assertEquals(280, $imageManipulator->getImageHeight($image));
} }
/** /**
* @dataProvider imageManipulatorProvider * @dataProvider imageManipulatorProvider
*/ */
public function testImageCroppingBleedBoth($imageManipulator) public function testImageCroppingBleedBoth($imageManipulator)
{ {
$image = $imageManipulator->loadFromBuffer($this->getTestFile('image.jpg')); $image = $imageManipulator->loadFromBuffer($this->getTestFile('image.jpg'));
$imageManipulator->cropImage($image, 642, 481, -1, -1); $imageManipulator->cropImage($image, 642, 481, -1, -1);
$this->assertEquals(640, $imageManipulator->getImageWidth($image)); $this->assertEquals(640, $imageManipulator->getImageWidth($image));
$this->assertEquals(480, $imageManipulator->getImageHeight($image)); $this->assertEquals(480, $imageManipulator->getImageHeight($image));
} }
/** /**
* @dataProvider imageManipulatorProvider * @dataProvider imageManipulatorProvider
*/ */
public function testImageCroppingMaxBleeding($imageManipulator) public function testImageCroppingMaxBleeding($imageManipulator)
{ {
$image = $imageManipulator->loadFromBuffer($this->getTestFile('image.jpg')); $image = $imageManipulator->loadFromBuffer($this->getTestFile('image.jpg'));
$imageManipulator->cropImage($image, 100, 100, 1000, 1000); $imageManipulator->cropImage($image, 100, 100, 1000, 1000);
$this->assertEquals(1, $imageManipulator->getImageWidth($image)); $this->assertEquals(1, $imageManipulator->getImageWidth($image));
$this->assertEquals(1, $imageManipulator->getImageHeight($image)); $this->assertEquals(1, $imageManipulator->getImageHeight($image));
} }
/** /**
* @dataProvider imageManipulatorProvider * @dataProvider imageManipulatorProvider
*/ */
public function testSaving($imageManipulator) public function testSaving($imageManipulator)
{ {
$image = $imageManipulator->loadFromBuffer($this->getTestFile('image.jpg')); $image = $imageManipulator->loadFromBuffer($this->getTestFile('image.jpg'));
$jpegBuffer = $imageManipulator->saveToBuffer($image, IImageManipulator::FORMAT_JPEG); $jpegBuffer = $imageManipulator->saveToBuffer($image, IImageManipulator::FORMAT_JPEG);
$pngBuffer = $imageManipulator->saveToBuffer($image, IImageManipulator::FORMAT_PNG); $pngBuffer = $imageManipulator->saveToBuffer($image, IImageManipulator::FORMAT_PNG);
$this->assertEquals('image/jpeg', MimeHelper::getMimeTypeFromBuffer($jpegBuffer)); $this->assertEquals('image/jpeg', MimeHelper::getMimeTypeFromBuffer($jpegBuffer));
$this->assertEquals('image/png', MimeHelper::getMimeTypeFromBuffer($pngBuffer)); $this->assertEquals('image/png', MimeHelper::getMimeTypeFromBuffer($pngBuffer));
} }
private static function getImagickImageManipulator() private static function getImagickImageManipulator()
{ {
if (extension_loaded('imagick')) if (extension_loaded('imagick'))
return new ImagickImageManipulator(); return new ImagickImageManipulator();
else else
return null; return null;
} }
private static function getGdImageManipulator() private static function getGdImageManipulator()
{ {
if (extension_loaded('gd')) if (extension_loaded('gd'))
return new GdImageManipulator(); return new GdImageManipulator();
else else
return null; return null;
} }
private static function getAutoImageManipulator() private static function getAutoImageManipulator()
{ {
if (extension_loaded('gd') && extension_loaded('imagick')) if (extension_loaded('gd') && extension_loaded('imagick'))
{ {
return new ImageManipulator( return new ImageManipulator(
self::getImagickImageManipulator(), self::getImagickImageManipulator(),
self::getGdImageManipulator()); self::getGdImageManipulator());
} }
return null; return null;
} }
} }

View file

@ -6,11 +6,11 @@ use Szurubooru\Tests\AbstractTestCase;
final class NetworkingServiceTest extends AbstractTestCase final class NetworkingServiceTest extends AbstractTestCase
{ {
public function testDownload() public function testDownload()
{ {
$httpHelper = $this->mock(HttpHelper::class); $httpHelper = $this->mock(HttpHelper::class);
$networkingService = new NetworkingService($httpHelper); $networkingService = new NetworkingService($httpHelper);
$content = $networkingService->download('http://modernseoul.files.wordpress.com/2012/04/korean-alphabet-chart-modern-seoul.jpg'); $content = $networkingService->download('http://modernseoul.files.wordpress.com/2012/04/korean-alphabet-chart-modern-seoul.jpg');
$this->assertGreaterThan(0, strlen($content)); $this->assertGreaterThan(0, strlen($content));
} }
} }

View file

@ -5,71 +5,71 @@ use Szurubooru\Tests\AbstractTestCase;
final class PasswordServiceTest extends AbstractTestCase final class PasswordServiceTest extends AbstractTestCase
{ {
private $configMock; private $configMock;
public function setUp() public function setUp()
{ {
parent::setUp(); parent::setUp();
$this->configMock = $this->mockConfig(); $this->configMock = $this->mockConfig();
} }
public function testLegacyPasswordValidation() public function testLegacyPasswordValidation()
{ {
$passwordService = $this->getPasswordService(); $passwordService = $this->getPasswordService();
$this->configMock->set('security/secret', 'doesnt matter'); $this->configMock->set('security/secret', 'doesnt matter');
$this->assertTrue($passwordService->isHashValid('testt', 'ac63e0bcdf20b82db509d123166c4592', '2602572e077d48b35af39d1cff84bfcaa5363116')); $this->assertTrue($passwordService->isHashValid('testt', 'ac63e0bcdf20b82db509d123166c4592', '2602572e077d48b35af39d1cff84bfcaa5363116'));
} }
public function testPasswordValidation() public function testPasswordValidation()
{ {
$passwordService = $this->getPasswordService(); $passwordService = $this->getPasswordService();
$this->configMock->set('security/secret', 'change'); $this->configMock->set('security/secret', 'change');
$this->assertTrue($passwordService->isHashValid('testt', '/', '4f4f8b836cd65f3f1d0b7751fc442f79595c23439cd8a928af15e10807bf08cc')); $this->assertTrue($passwordService->isHashValid('testt', '/', '4f4f8b836cd65f3f1d0b7751fc442f79595c23439cd8a928af15e10807bf08cc'));
} }
public function testGeneratingPasswords() public function testGeneratingPasswords()
{ {
$passwordService = $this->getPasswordService(); $passwordService = $this->getPasswordService();
$sampleCount = 10000; $sampleCount = 10000;
$distribution = []; $distribution = [];
for ($i = 0; $i < $sampleCount; $i ++) for ($i = 0; $i < $sampleCount; $i ++)
{ {
$password = $passwordService->getRandomPassword(); $password = $passwordService->getRandomPassword();
for ($j = 0; $j < strlen($password); $j ++) for ($j = 0; $j < strlen($password); $j ++)
{ {
$c = $password{$j}; $c = $password{$j};
if (!isset($distribution[$j])) if (!isset($distribution[$j]))
$distribution[$j] = [$c => 1]; $distribution[$j] = [$c => 1];
elseif (!isset($distribution[$j][$c])) elseif (!isset($distribution[$j][$c]))
$distribution[$j][$c] = 1; $distribution[$j][$c] = 1;
else else
$distribution[$j][$c] ++; $distribution[$j][$c] ++;
} }
} }
foreach ($distribution as $index => $characterDistribution) foreach ($distribution as $index => $characterDistribution)
{ {
$this->assertLessThan(10, $this->getRelativeStandardDeviation($characterDistribution)); $this->assertLessThan(10, $this->getRelativeStandardDeviation($characterDistribution));
} }
} }
private function getStandardDeviation($sample) private function getStandardDeviation($sample)
{ {
$mean = array_sum($sample) / count($sample); $mean = array_sum($sample) / count($sample);
foreach ($sample as $key => $num) foreach ($sample as $key => $num)
$devs[$key] = pow($num - $mean, 2); $devs[$key] = pow($num - $mean, 2);
return sqrt(array_sum($devs) / (count($devs))); return sqrt(array_sum($devs) / (count($devs)));
} }
private function getRelativeStandardDeviation($sample) private function getRelativeStandardDeviation($sample)
{ {
$mean = array_sum($sample) / count($sample); $mean = array_sum($sample) / count($sample);
return 100 * $this->getStandardDeviation($sample) / $mean; return 100 * $this->getStandardDeviation($sample) / $mean;
} }
private function getPasswordService() private function getPasswordService()
{ {
return new PasswordService($this->configMock); return new PasswordService($this->configMock);
} }
} }

View file

@ -20,203 +20,203 @@ use Szurubooru\Validator;
final class PostServiceTest extends AbstractDatabaseTestCase final class PostServiceTest extends AbstractDatabaseTestCase
{ {
private $configMock; private $configMock;
private $validatorMock; private $validatorMock;
private $transactionManagerMock; private $transactionManagerMock;
private $postDaoMock; private $postDaoMock;
private $globalParamDaoMock; private $globalParamDaoMock;
private $authServiceMock; private $authServiceMock;
private $timeServiceMock; private $timeServiceMock;
private $networkingServiceMock; private $networkingServiceMock;
private $tagService; private $tagService;
private $postHistoryServiceMock; private $postHistoryServiceMock;
private $imageConverterMock; private $imageConverterMock;
private $imageManipulatorMock; private $imageManipulatorMock;
public function setUp() public function setUp()
{ {
parent::setUp(); parent::setUp();
$this->configMock = $this->mockConfig(); $this->configMock = $this->mockConfig();
$this->validatorMock = $this->mock(Validator::class); $this->validatorMock = $this->mock(Validator::class);
$this->transactionManagerMock = $this->mockTransactionManager(); $this->transactionManagerMock = $this->mockTransactionManager();
$this->postDaoMock = $this->mock(PostDao::class); $this->postDaoMock = $this->mock(PostDao::class);
$this->globalParamDaoMock = $this->mock(GlobalParamDao::class); $this->globalParamDaoMock = $this->mock(GlobalParamDao::class);
$this->authServiceMock = $this->mock(AuthService::class); $this->authServiceMock = $this->mock(AuthService::class);
$this->timeServiceMock = $this->mock(TimeService::class); $this->timeServiceMock = $this->mock(TimeService::class);
$this->networkingServiceMock = $this->mock(NetworkingService::class); $this->networkingServiceMock = $this->mock(NetworkingService::class);
$this->tagService = Injector::get(TagService::class); $this->tagService = Injector::get(TagService::class);
$this->postHistoryServiceMock = $this->mock(PostHistoryService::class); $this->postHistoryServiceMock = $this->mock(PostHistoryService::class);
$this->configMock->set('database/maxPostSize', 1000000); $this->configMock->set('database/maxPostSize', 1000000);
$this->imageConverterMock = $this->mock(ImageConverter::class); $this->imageConverterMock = $this->mock(ImageConverter::class);
$this->imageManipulatorMock = $this->mock(ImageManipulator::class); $this->imageManipulatorMock = $this->mock(ImageManipulator::class);
} }
public function testCreatingYoutubePost() public function testCreatingYoutubePost()
{ {
$formData = new UploadFormData; $formData = new UploadFormData;
$formData->safety = Post::POST_SAFETY_SAFE; $formData->safety = Post::POST_SAFETY_SAFE;
$formData->source = 'source'; $formData->source = 'source';
$formData->tags = ['test', 'test2']; $formData->tags = ['test', 'test2'];
$formData->url = 'https://www.youtube.com/watch?v=QYK2c4OVG6s'; $formData->url = 'https://www.youtube.com/watch?v=QYK2c4OVG6s';
$this->postDaoMock->expects($this->once())->method('save')->will($this->returnArgument(0)); $this->postDaoMock->expects($this->once())->method('save')->will($this->returnArgument(0));
$this->authServiceMock->expects($this->once())->method('getLoggedInUser')->willReturn(new User(5)); $this->authServiceMock->expects($this->once())->method('getLoggedInUser')->willReturn(new User(5));
$this->postHistoryServiceMock->expects($this->once())->method('savePostCreation')->willReturn(new Snapshot()); $this->postHistoryServiceMock->expects($this->once())->method('savePostCreation')->willReturn(new Snapshot());
$this->imageConverterMock->expects($this->never())->method('createImageFromBuffer'); $this->imageConverterMock->expects($this->never())->method('createImageFromBuffer');
$this->postService = $this->getPostService(); $this->postService = $this->getPostService();
$savedPost = $this->postService->createPost($formData); $savedPost = $this->postService->createPost($formData);
$this->assertEquals(Post::POST_SAFETY_SAFE, $savedPost->getSafety()); $this->assertEquals(Post::POST_SAFETY_SAFE, $savedPost->getSafety());
$this->assertEquals(5, $savedPost->getUserId()); $this->assertEquals(5, $savedPost->getUserId());
$this->assertEquals(Post::POST_TYPE_YOUTUBE, $savedPost->getContentType()); $this->assertEquals(Post::POST_TYPE_YOUTUBE, $savedPost->getContentType());
$this->assertEquals('QYK2c4OVG6s', $savedPost->getContentChecksum()); $this->assertEquals('QYK2c4OVG6s', $savedPost->getContentChecksum());
$this->assertEquals('source', $savedPost->getSource()); $this->assertEquals('source', $savedPost->getSource());
$this->assertNull($savedPost->getImageWidth()); $this->assertNull($savedPost->getImageWidth());
$this->assertNull($savedPost->getImageHeight()); $this->assertNull($savedPost->getImageHeight());
$this->assertEquals($formData->url, $savedPost->getOriginalFileName()); $this->assertEquals($formData->url, $savedPost->getOriginalFileName());
$this->assertNull($savedPost->getOriginalFileSize()); $this->assertNull($savedPost->getOriginalFileSize());
$this->assertEquals(2, count($savedPost->getTags())); $this->assertEquals(2, count($savedPost->getTags()));
$this->assertEquals('test', $savedPost->getTags()[0]->getName()); $this->assertEquals('test', $savedPost->getTags()[0]->getName());
$this->assertEquals('test2', $savedPost->getTags()[1]->getName()); $this->assertEquals('test2', $savedPost->getTags()[1]->getName());
} }
public function testCreatingPosts() public function testCreatingPosts()
{ {
$formData = new UploadFormData; $formData = new UploadFormData;
$formData->safety = Post::POST_SAFETY_SAFE; $formData->safety = Post::POST_SAFETY_SAFE;
$formData->tags = ['test']; $formData->tags = ['test'];
$formData->content = $this->getTestFile('image.jpg'); $formData->content = $this->getTestFile('image.jpg');
$formData->contentFileName = 'blah'; $formData->contentFileName = 'blah';
$this->postDaoMock->expects($this->once())->method('save')->will($this->returnArgument(0)); $this->postDaoMock->expects($this->once())->method('save')->will($this->returnArgument(0));
$this->imageManipulatorMock->expects($this->once())->method('getImageWidth')->willReturn(640); $this->imageManipulatorMock->expects($this->once())->method('getImageWidth')->willReturn(640);
$this->imageManipulatorMock->expects($this->once())->method('getImageHeight')->willReturn(480); $this->imageManipulatorMock->expects($this->once())->method('getImageHeight')->willReturn(480);
$this->postHistoryServiceMock->expects($this->once())->method('savePostCreation')->willReturn(new Snapshot()); $this->postHistoryServiceMock->expects($this->once())->method('savePostCreation')->willReturn(new Snapshot());
$this->postService = $this->getPostService(); $this->postService = $this->getPostService();
$savedPost = $this->postService->createPost($formData); $savedPost = $this->postService->createPost($formData);
$this->assertEquals(Post::POST_TYPE_IMAGE, $savedPost->getContentType()); $this->assertEquals(Post::POST_TYPE_IMAGE, $savedPost->getContentType());
$this->assertEquals('24216edd12328de3a3c55e2f98220ee7613e3be1', $savedPost->getContentChecksum()); $this->assertEquals('24216edd12328de3a3c55e2f98220ee7613e3be1', $savedPost->getContentChecksum());
$this->assertEquals($formData->contentFileName, $savedPost->getOriginalFileName()); $this->assertEquals($formData->contentFileName, $savedPost->getOriginalFileName());
$this->assertEquals(687645, $savedPost->getOriginalFileSize()); $this->assertEquals(687645, $savedPost->getOriginalFileSize());
$this->assertEquals(640, $savedPost->getImageWidth()); $this->assertEquals(640, $savedPost->getImageWidth());
$this->assertEquals(480, $savedPost->getImageHeight()); $this->assertEquals(480, $savedPost->getImageHeight());
} }
public function testCreatingVideos() public function testCreatingVideos()
{ {
$formData = new UploadFormData; $formData = new UploadFormData;
$formData->safety = Post::POST_SAFETY_SAFE; $formData->safety = Post::POST_SAFETY_SAFE;
$formData->tags = ['test']; $formData->tags = ['test'];
$formData->content = $this->getTestFile('video.mp4'); $formData->content = $this->getTestFile('video.mp4');
$formData->contentFileName = 'blah'; $formData->contentFileName = 'blah';
$this->postDaoMock->expects($this->once())->method('save')->will($this->returnArgument(0)); $this->postDaoMock->expects($this->once())->method('save')->will($this->returnArgument(0));
$this->postHistoryServiceMock->expects($this->once())->method('savePostCreation')->willReturn(new Snapshot()); $this->postHistoryServiceMock->expects($this->once())->method('savePostCreation')->willReturn(new Snapshot());
$this->imageConverterMock->expects($this->once())->method('createImageFromBuffer'); $this->imageConverterMock->expects($this->once())->method('createImageFromBuffer');
$this->postService = $this->getPostService(); $this->postService = $this->getPostService();
$savedPost = $this->postService->createPost($formData); $savedPost = $this->postService->createPost($formData);
$this->assertEquals(Post::POST_TYPE_VIDEO, $savedPost->getContentType()); $this->assertEquals(Post::POST_TYPE_VIDEO, $savedPost->getContentType());
$this->assertEquals('16dafaa07cda194d03d590529c06c6ec1a5b80b0', $savedPost->getContentChecksum()); $this->assertEquals('16dafaa07cda194d03d590529c06c6ec1a5b80b0', $savedPost->getContentChecksum());
$this->assertEquals($formData->contentFileName, $savedPost->getOriginalFileName()); $this->assertEquals($formData->contentFileName, $savedPost->getOriginalFileName());
$this->assertEquals(14667, $savedPost->getOriginalFileSize()); $this->assertEquals(14667, $savedPost->getOriginalFileSize());
} }
public function testCreatingFlashes() public function testCreatingFlashes()
{ {
$formData = new UploadFormData; $formData = new UploadFormData;
$formData->safety = Post::POST_SAFETY_SAFE; $formData->safety = Post::POST_SAFETY_SAFE;
$formData->tags = ['test']; $formData->tags = ['test'];
$formData->content = $this->getTestFile('flash.swf'); $formData->content = $this->getTestFile('flash.swf');
$formData->contentFileName = 'blah'; $formData->contentFileName = 'blah';
$this->postDaoMock->expects($this->once())->method('save')->will($this->returnArgument(0)); $this->postDaoMock->expects($this->once())->method('save')->will($this->returnArgument(0));
$this->postHistoryServiceMock->expects($this->once())->method('savePostCreation')->willReturn(new Snapshot()); $this->postHistoryServiceMock->expects($this->once())->method('savePostCreation')->willReturn(new Snapshot());
$this->imageConverterMock->expects($this->once())->method('createImageFromBuffer'); $this->imageConverterMock->expects($this->once())->method('createImageFromBuffer');
$this->postService = $this->getPostService(); $this->postService = $this->getPostService();
$savedPost = $this->postService->createPost($formData); $savedPost = $this->postService->createPost($formData);
$this->assertEquals(Post::POST_TYPE_FLASH, $savedPost->getContentType()); $this->assertEquals(Post::POST_TYPE_FLASH, $savedPost->getContentType());
$this->assertEquals('d897e044b801d892291b440534c3be3739034f68', $savedPost->getContentChecksum()); $this->assertEquals('d897e044b801d892291b440534c3be3739034f68', $savedPost->getContentChecksum());
$this->assertEquals($formData->contentFileName, $savedPost->getOriginalFileName()); $this->assertEquals($formData->contentFileName, $savedPost->getOriginalFileName());
$this->assertEquals(226172, $savedPost->getOriginalFileSize()); $this->assertEquals(226172, $savedPost->getOriginalFileSize());
} }
public function testFileDuplicates() public function testFileDuplicates()
{ {
$formData = new UploadFormData; $formData = new UploadFormData;
$formData->safety = Post::POST_SAFETY_SAFE; $formData->safety = Post::POST_SAFETY_SAFE;
$formData->tags = ['test']; $formData->tags = ['test'];
$formData->content = $this->getTestFile('flash.swf'); $formData->content = $this->getTestFile('flash.swf');
$formData->contentFileName = 'blah'; $formData->contentFileName = 'blah';
$this->postDaoMock->expects($this->once())->method('findByContentChecksum')->willReturn(new Post(5)); $this->postDaoMock->expects($this->once())->method('findByContentChecksum')->willReturn(new Post(5));
$this->setExpectedException(\Exception::class, 'Duplicate post: @5'); $this->setExpectedException(\Exception::class, 'Duplicate post: @5');
$this->postService = $this->getPostService(); $this->postService = $this->getPostService();
$this->postService->createPost($formData); $this->postService->createPost($formData);
} }
public function testYoutubeDuplicates() public function testYoutubeDuplicates()
{ {
$formData = new UploadFormData; $formData = new UploadFormData;
$formData->safety = Post::POST_SAFETY_SAFE; $formData->safety = Post::POST_SAFETY_SAFE;
$formData->tags = ['test']; $formData->tags = ['test'];
$formData->url = 'https://www.youtube.com/watch?v=QYK2c4OVG6s'; $formData->url = 'https://www.youtube.com/watch?v=QYK2c4OVG6s';
$this->postDaoMock->expects($this->once())->method('findByContentChecksum')->with('QYK2c4OVG6s')->willReturn(new Post(5)); $this->postDaoMock->expects($this->once())->method('findByContentChecksum')->with('QYK2c4OVG6s')->willReturn(new Post(5));
$this->setExpectedException(\Exception::class, 'Duplicate post: @5'); $this->setExpectedException(\Exception::class, 'Duplicate post: @5');
$this->postService = $this->getPostService(); $this->postService = $this->getPostService();
$this->postService->createPost($formData); $this->postService->createPost($formData);
} }
public function testTooBigUpload() public function testTooBigUpload()
{ {
$formData = new UploadFormData; $formData = new UploadFormData;
$formData->safety = Post::POST_SAFETY_SAFE; $formData->safety = Post::POST_SAFETY_SAFE;
$formData->tags = ['test']; $formData->tags = ['test'];
$formData->content = 'aa'; $formData->content = 'aa';
$this->configMock->set('database/maxPostSize', 1); $this->configMock->set('database/maxPostSize', 1);
$this->setExpectedException(\Exception::class, 'Upload is too big'); $this->setExpectedException(\Exception::class, 'Upload is too big');
$this->postService = $this->getPostService(); $this->postService = $this->getPostService();
$this->postService->createPost($formData); $this->postService->createPost($formData);
} }
public function testAnonymousUploads() public function testAnonymousUploads()
{ {
$formData = new UploadFormData; $formData = new UploadFormData;
$formData->safety = Post::POST_SAFETY_SAFE; $formData->safety = Post::POST_SAFETY_SAFE;
$formData->tags = ['test']; $formData->tags = ['test'];
$formData->url = 'https://www.youtube.com/watch?v=QYK2c4OVG6s'; $formData->url = 'https://www.youtube.com/watch?v=QYK2c4OVG6s';
$formData->anonymous = true; $formData->anonymous = true;
$this->postDaoMock->expects($this->once())->method('save')->will($this->returnArgument(0)); $this->postDaoMock->expects($this->once())->method('save')->will($this->returnArgument(0));
$this->authServiceMock->expects($this->once())->method('loginAnonymous'); $this->authServiceMock->expects($this->once())->method('loginAnonymous');
$this->postHistoryServiceMock->expects($this->once())->method('savePostCreation')->willReturn(new Snapshot()); $this->postHistoryServiceMock->expects($this->once())->method('savePostCreation')->willReturn(new Snapshot());
$this->postService = $this->getPostService(); $this->postService = $this->getPostService();
$savedPost = $this->postService->createPost($formData); $savedPost = $this->postService->createPost($formData);
$this->assertNull($savedPost->getUserId()); $this->assertNull($savedPost->getUserId());
} }
private function getPostService() private function getPostService()
{ {
return new PostService( return new PostService(
$this->configMock, $this->configMock,
$this->validatorMock, $this->validatorMock,
$this->transactionManagerMock, $this->transactionManagerMock,
$this->postDaoMock, $this->postDaoMock,
$this->globalParamDaoMock, $this->globalParamDaoMock,
$this->authServiceMock, $this->authServiceMock,
$this->timeServiceMock, $this->timeServiceMock,
$this->networkingServiceMock, $this->networkingServiceMock,
$this->tagService, $this->tagService,
$this->postHistoryServiceMock, $this->postHistoryServiceMock,
$this->imageConverterMock, $this->imageConverterMock,
$this->imageManipulatorMock); $this->imageManipulatorMock);
} }
} }

View file

@ -12,94 +12,94 @@ use Szurubooru\Tests\AbstractTestCase;
class PostSnapshotProviderTest extends AbstractTestCase class PostSnapshotProviderTest extends AbstractTestCase
{ {
private $globalParamDaoMock; private $globalParamDaoMock;
public function setUp() public function setUp()
{ {
parent::setUp(); parent::setUp();
$this->globalParamDaoMock = $this->mock(GlobalParamDao::class); $this->globalParamDaoMock = $this->mock(GlobalParamDao::class);
$this->postNoteDaoMock = $this->mock(PostNoteDao::class); $this->postNoteDaoMock = $this->mock(PostNoteDao::class);
} }
public function testPostChangeSnapshot() public function testPostChangeSnapshot()
{ {
$tag1 = new Tag(); $tag1 = new Tag();
$tag2 = new Tag(); $tag2 = new Tag();
$tag1->setName('tag1'); $tag1->setName('tag1');
$tag2->setName('tag2'); $tag2->setName('tag2');
$post1 = new Post(1); $post1 = new Post(1);
$post2 = new Post(2); $post2 = new Post(2);
$post = new Post(5); $post = new Post(5);
$post->setTags([$tag1, $tag2]); $post->setTags([$tag1, $tag2]);
$post->setRelatedPosts([$post1, $post2]); $post->setRelatedPosts([$post1, $post2]);
$post->setContentChecksum('checksum'); $post->setContentChecksum('checksum');
$post->setSafety(Post::POST_SAFETY_SKETCHY); $post->setSafety(Post::POST_SAFETY_SKETCHY);
$post->setSource('amazing source'); $post->setSource('amazing source');
$post->setFlags(Post::FLAG_LOOP); $post->setFlags(Post::FLAG_LOOP);
$this->postNoteDaoMock $this->postNoteDaoMock
->method('findByPostId') ->method('findByPostId')
->with($post->getId()) ->with($post->getId())
->willReturn([$this->getTestPostNote()]); ->willReturn([$this->getTestPostNote()]);
$postSnapshotProvider = $this->getPostSnapshotProvider(); $postSnapshotProvider = $this->getPostSnapshotProvider();
$snapshot = $postSnapshotProvider->getChangeSnapshot($post); $snapshot = $postSnapshotProvider->getChangeSnapshot($post);
$this->assertEquals([ $this->assertEquals([
'source' => 'amazing source', 'source' => 'amazing source',
'safety' => 'sketchy', 'safety' => 'sketchy',
'contentChecksum' => 'checksum', 'contentChecksum' => 'checksum',
'featured' => false, 'featured' => false,
'tags' => ['tag1', 'tag2'], 'tags' => ['tag1', 'tag2'],
'relations' => [1, 2], 'relations' => [1, 2],
'flags' => ['loop'], 'flags' => ['loop'],
'notes' => [['x' => 5, 'y' => 6, 'w' => 7, 'h' => 8, 'text' => 'text']], 'notes' => [['x' => 5, 'y' => 6, 'w' => 7, 'h' => 8, 'text' => 'text']],
], $snapshot->getData()); ], $snapshot->getData());
$this->assertEquals(Snapshot::TYPE_POST, $snapshot->getType()); $this->assertEquals(Snapshot::TYPE_POST, $snapshot->getType());
$this->assertEquals(5, $snapshot->getPrimaryKey()); $this->assertEquals(5, $snapshot->getPrimaryKey());
return $post; return $post;
} }
/** /**
* @depends testPostChangeSnapshot * @depends testPostChangeSnapshot
*/ */
public function testPostChangeSnapshotFeature($post) public function testPostChangeSnapshotFeature($post)
{ {
$param = new GlobalParam; $param = new GlobalParam;
$param->setValue($post->getId()); $param->setValue($post->getId());
$this->globalParamDaoMock $this->globalParamDaoMock
->expects($this->once()) ->expects($this->once())
->method('findByKey') ->method('findByKey')
->with(GlobalParam::KEY_FEATURED_POST) ->with(GlobalParam::KEY_FEATURED_POST)
->willReturn($param); ->willReturn($param);
$this->postNoteDaoMock $this->postNoteDaoMock
->method('findByPostId') ->method('findByPostId')
->with($post->getId()) ->with($post->getId())
->willReturn([]); ->willReturn([]);
$postSnapshotProvider = $this->getPostSnapshotProvider(); $postSnapshotProvider = $this->getPostSnapshotProvider();
$snapshot = $postSnapshotProvider->getChangeSnapshot($post); $snapshot = $postSnapshotProvider->getChangeSnapshot($post);
$this->assertTrue($snapshot->getData()['featured']); $this->assertTrue($snapshot->getData()['featured']);
} }
private function getPostSnapshotProvider() private function getPostSnapshotProvider()
{ {
return new PostSnapshotProvider($this->globalParamDaoMock, $this->postNoteDaoMock); return new PostSnapshotProvider($this->globalParamDaoMock, $this->postNoteDaoMock);
} }
private function getTestPostNote() private function getTestPostNote()
{ {
$postNote = new PostNote(); $postNote = new PostNote();
$postNote->setLeft(5); $postNote->setLeft(5);
$postNote->setTop(6); $postNote->setTop(6);
$postNote->setWidth(7); $postNote->setWidth(7);
$postNote->setHeight(8); $postNote->setHeight(8);
$postNote->setText('text'); $postNote->setText('text');
return $postNote; return $postNote;
} }
} }

View file

@ -8,99 +8,99 @@ use Szurubooru\Tests\AbstractTestCase;
final class PrivilegeServiceTest extends AbstractTestCase final class PrivilegeServiceTest extends AbstractTestCase
{ {
private $configMock; private $configMock;
private $authServiceMock; private $authServiceMock;
public function setUp() public function setUp()
{ {
parent::setUp(); parent::setUp();
$this->configMock = $this->mockConfig(); $this->configMock = $this->mockConfig();
$this->authServiceMock = $this->mock(AuthService::class); $this->authServiceMock = $this->mock(AuthService::class);
} }
public function testReadingConfig() public function testReadingConfig()
{ {
$testUser = new User(); $testUser = new User();
$testUser->setName('dummy'); $testUser->setName('dummy');
$testUser->setAccessRank(User::ACCESS_RANK_POWER_USER); $testUser->setAccessRank(User::ACCESS_RANK_POWER_USER);
$this->authServiceMock->expects($this->atLeastOnce())->method('getLoggedInUser')->willReturn($testUser); $this->authServiceMock->expects($this->atLeastOnce())->method('getLoggedInUser')->willReturn($testUser);
$privilege = Privilege::LIST_USERS; $privilege = Privilege::LIST_USERS;
$this->configMock->set('security/privileges/' . $privilege, 'powerUser'); $this->configMock->set('security/privileges/' . $privilege, 'powerUser');
$privilegeService = $this->getPrivilegeService(); $privilegeService = $this->getPrivilegeService();
$this->assertEquals([$privilege], $privilegeService->getCurrentPrivileges()); $this->assertEquals([$privilege], $privilegeService->getCurrentPrivileges());
$this->assertTrue($privilegeService->hasPrivilege($privilege)); $this->assertTrue($privilegeService->hasPrivilege($privilege));
} }
public function testIsLoggedInByNameString() public function testIsLoggedInByNameString()
{ {
$testUser1 = new User(); $testUser1 = new User();
$testUser1->setName('dummy'); $testUser1->setName('dummy');
$testUser2 = new User(); $testUser2 = new User();
$testUser2->setName('godzilla'); $testUser2->setName('godzilla');
$this->authServiceMock->expects($this->atLeastOnce())->method('getLoggedInUser')->willReturn($testUser1); $this->authServiceMock->expects($this->atLeastOnce())->method('getLoggedInUser')->willReturn($testUser1);
$privilegeService = $this->getPrivilegeService(); $privilegeService = $this->getPrivilegeService();
$this->assertTrue($privilegeService->isLoggedIn($testUser1->getName())); $this->assertTrue($privilegeService->isLoggedIn($testUser1->getName()));
$this->assertFalse($privilegeService->isLoggedIn($testUser2->getName())); $this->assertFalse($privilegeService->isLoggedIn($testUser2->getName()));
} }
public function testIsLoggedInByEmailString() public function testIsLoggedInByEmailString()
{ {
$testUser1 = new User(); $testUser1 = new User();
$testUser1->setName('user1'); $testUser1->setName('user1');
$testUser1->setEmail('dummy'); $testUser1->setEmail('dummy');
$testUser2 = new User(); $testUser2 = new User();
$testUser2->setName('user2'); $testUser2->setName('user2');
$testUser2->setEmail('godzilla'); $testUser2->setEmail('godzilla');
$this->authServiceMock->expects($this->atLeastOnce())->method('getLoggedInUser')->willReturn($testUser1); $this->authServiceMock->expects($this->atLeastOnce())->method('getLoggedInUser')->willReturn($testUser1);
$privilegeService = $this->getPrivilegeService(); $privilegeService = $this->getPrivilegeService();
$this->assertTrue($privilegeService->isLoggedIn($testUser1->getEmail())); $this->assertTrue($privilegeService->isLoggedIn($testUser1->getEmail()));
$this->assertFalse($privilegeService->isLoggedIn($testUser2->getEmail())); $this->assertFalse($privilegeService->isLoggedIn($testUser2->getEmail()));
} }
public function testIsLoggedInByUserId() public function testIsLoggedInByUserId()
{ {
$testUser1 = new User(5); $testUser1 = new User(5);
$testUser2 = new User(13); $testUser2 = new User(13);
$this->authServiceMock->expects($this->atLeastOnce())->method('getLoggedInUser')->willReturn($testUser1); $this->authServiceMock->expects($this->atLeastOnce())->method('getLoggedInUser')->willReturn($testUser1);
$privilegeService = $this->getPrivilegeService(); $privilegeService = $this->getPrivilegeService();
$this->assertTrue($privilegeService->isLoggedIn($testUser1)); $this->assertTrue($privilegeService->isLoggedIn($testUser1));
$this->assertFalse($privilegeService->isLoggedIn($testUser2)); $this->assertFalse($privilegeService->isLoggedIn($testUser2));
} }
public function testIsLoggedInByUserName() public function testIsLoggedInByUserName()
{ {
$testUser1 = new User(); $testUser1 = new User();
$testUser1->setName('dummy'); $testUser1->setName('dummy');
$testUser2 = new User(); $testUser2 = new User();
$testUser2->setName('godzilla'); $testUser2->setName('godzilla');
$this->authServiceMock->expects($this->atLeastOnce())->method('getLoggedInUser')->willReturn($testUser1); $this->authServiceMock->expects($this->atLeastOnce())->method('getLoggedInUser')->willReturn($testUser1);
$privilegeService = $this->getPrivilegeService(); $privilegeService = $this->getPrivilegeService();
$this->assertFalse($privilegeService->isLoggedIn($testUser1)); $this->assertFalse($privilegeService->isLoggedIn($testUser1));
$this->assertFalse($privilegeService->isLoggedIn($testUser2)); $this->assertFalse($privilegeService->isLoggedIn($testUser2));
} }
public function testIsLoggedInByInvalidObject() public function testIsLoggedInByInvalidObject()
{ {
$testUser = new User(); $testUser = new User();
$testUser->setName('dummy'); $testUser->setName('dummy');
$this->authServiceMock->expects($this->atLeastOnce())->method('getLoggedInUser')->willReturn($testUser); $this->authServiceMock->expects($this->atLeastOnce())->method('getLoggedInUser')->willReturn($testUser);
$rubbish = new \StdClass; $rubbish = new \StdClass;
$privilegeService = $this->getPrivilegeService(); $privilegeService = $this->getPrivilegeService();
$this->setExpectedException(\InvalidArgumentException::class); $this->setExpectedException(\InvalidArgumentException::class);
$this->assertTrue($privilegeService->isLoggedIn($rubbish)); $this->assertTrue($privilegeService->isLoggedIn($rubbish));
} }
private function getPrivilegeService() private function getPrivilegeService()
{ {
return new PrivilegeService( return new PrivilegeService(
$this->configMock, $this->configMock,
$this->authServiceMock); $this->authServiceMock);
} }
} }

View file

@ -12,64 +12,64 @@ use Szurubooru\Tests\AbstractTestCase;
final class ScoreServiceTest extends AbstractTestCase final class ScoreServiceTest extends AbstractTestCase
{ {
private $scoreDaoMock; private $scoreDaoMock;
private $favoritesDaoMock; private $favoritesDaoMock;
private $userDaoMock; private $userDaoMock;
private $transactionManagerMock; private $transactionManagerMock;
private $timeServiceMock; private $timeServiceMock;
public function setUp() public function setUp()
{ {
parent::setUp(); parent::setUp();
$this->scoreDaoMock = $this->mock(ScoreDao::class); $this->scoreDaoMock = $this->mock(ScoreDao::class);
$this->favoritesDaoMock = $this->mock(FavoritesDao::class); $this->favoritesDaoMock = $this->mock(FavoritesDao::class);
$this->userDaoMock = $this->mock(UserDao::class); $this->userDaoMock = $this->mock(UserDao::class);
$this->transactionManagerMock = $this->mockTransactionManager(); $this->transactionManagerMock = $this->mockTransactionManager();
$this->timeServiceMock = $this->mock(TimeService::class); $this->timeServiceMock = $this->mock(TimeService::class);
} }
public function testSetting() public function testSetting()
{ {
$user = new User(1); $user = new User(1);
$post = new Post(2); $post = new Post(2);
$score = new Score(); $score = new Score();
$score->setUserId($user->getId()); $score->setUserId($user->getId());
$score->setPostId($post->getId()); $score->setPostId($post->getId());
$score->setScore(1); $score->setScore(1);
$this->scoreDaoMock->expects($this->once())->method('setUserScore')->with($user, $post)->willReturn(null); $this->scoreDaoMock->expects($this->once())->method('setUserScore')->with($user, $post)->willReturn(null);
$scoreService = $this->getScoreService(); $scoreService = $this->getScoreService();
$scoreService->setUserScore($user, $post, 1); $scoreService->setUserScore($user, $post, 1);
} }
public function testSettingInvalid() public function testSettingInvalid()
{ {
$user = new User(1); $user = new User(1);
$post = new Post(2); $post = new Post(2);
$this->setExpectedException(\Exception::class); $this->setExpectedException(\Exception::class);
$scoreService = $this->getScoreService(); $scoreService = $this->getScoreService();
$scoreService->setUserScore($user, $post, 2); $scoreService->setUserScore($user, $post, 2);
} }
public function testGetting() public function testGetting()
{ {
$user = new User(); $user = new User();
$post = new Post(); $post = new Post();
$score = new Score(3); $score = new Score(3);
$this->scoreDaoMock->expects($this->once())->method('getUserScore')->with($user, $post)->willReturn($score); $this->scoreDaoMock->expects($this->once())->method('getUserScore')->with($user, $post)->willReturn($score);
$scoreService = $this->getScoreService(); $scoreService = $this->getScoreService();
$retrievedScore = $scoreService->getUserScore($user, $post); $retrievedScore = $scoreService->getUserScore($user, $post);
$this->assertEquals($score, $retrievedScore); $this->assertEquals($score, $retrievedScore);
} }
private function getScoreService() private function getScoreService()
{ {
return new ScoreService( return new ScoreService(
$this->scoreDaoMock, $this->scoreDaoMock,
$this->favoritesDaoMock, $this->favoritesDaoMock,
$this->userDaoMock, $this->userDaoMock,
$this->transactionManagerMock, $this->transactionManagerMock,
$this->timeServiceMock); $this->timeServiceMock);
} }
} }

View file

@ -11,174 +11,174 @@ use Szurubooru\Tests\AbstractDatabaseTestCase;
final class TagServiceTest extends AbstractDatabaseTestCase final class TagServiceTest extends AbstractDatabaseTestCase
{ {
public function testCreatingEmpty() public function testCreatingEmpty()
{ {
$pdo = $this->databaseConnection->getPDO(); $pdo = $this->databaseConnection->getPDO();
$tagService = $this->getTagService(); $tagService = $this->getTagService();
$result = $tagService->createTags([]); $result = $tagService->createTags([]);
$this->assertEquals(0, count($result)); $this->assertEquals(0, count($result));
} }
public function testCreatingTagsWhenNoneExist() public function testCreatingTagsWhenNoneExist()
{ {
$pdo = $this->databaseConnection->getPDO(); $pdo = $this->databaseConnection->getPDO();
$tag = new Tag(); $tag = new Tag();
$tag->setName('test'); $tag->setName('test');
$tagService = $this->getTagService(); $tagService = $this->getTagService();
$result = $tagService->createTags([$tag]); $result = $tagService->createTags([$tag]);
$this->assertEquals(1, count($result)); $this->assertEquals(1, count($result));
$this->assertNotNull($result[0]->getId()); $this->assertNotNull($result[0]->getId());
$this->assertEquals('test', $result[0]->getName()); $this->assertEquals('test', $result[0]->getName());
} }
public function testCreatingTagsWhenAllExist() public function testCreatingTagsWhenAllExist()
{ {
$pdo = $this->databaseConnection->getPDO(); $pdo = $this->databaseConnection->getPDO();
$pdo->exec('INSERT INTO tags(id, name, creationTime) VALUES (1, \'test1\', \'2014-10-01 00:00:00\')'); $pdo->exec('INSERT INTO tags(id, name, creationTime) VALUES (1, \'test1\', \'2014-10-01 00:00:00\')');
$pdo->exec('INSERT INTO tags(id, name, creationTime) VALUES (2, \'test2\', \'2014-10-01 00:00:00\')'); $pdo->exec('INSERT INTO tags(id, name, creationTime) VALUES (2, \'test2\', \'2014-10-01 00:00:00\')');
$pdo->exec('UPDATE sequencer SET lastUsedId = 2 WHERE tableName = \'tags\''); $pdo->exec('UPDATE sequencer SET lastUsedId = 2 WHERE tableName = \'tags\'');
$tag1 = new Tag(); $tag1 = new Tag();
$tag1->setName('test1'); $tag1->setName('test1');
$tag2 = new Tag(); $tag2 = new Tag();
$tag2->setName('test2'); $tag2->setName('test2');
$tagService = $this->getTagService(); $tagService = $this->getTagService();
$result = $tagService->createTags([$tag1, $tag2]); $result = $tagService->createTags([$tag1, $tag2]);
$this->assertEquals(2, count($result)); $this->assertEquals(2, count($result));
$this->assertEquals(1, $result[0]->getId()); $this->assertEquals(1, $result[0]->getId());
$this->assertEquals(2, $result[1]->getId()); $this->assertEquals(2, $result[1]->getId());
$this->assertEquals('test1', $result[0]->getName()); $this->assertEquals('test1', $result[0]->getName());
$this->assertEquals('test2', $result[1]->getName()); $this->assertEquals('test2', $result[1]->getName());
} }
public function testCreatingTagsWhenSomeExist() public function testCreatingTagsWhenSomeExist()
{ {
$pdo = $this->databaseConnection->getPDO(); $pdo = $this->databaseConnection->getPDO();
$pdo->exec('INSERT INTO tags(id, name, creationTime) VALUES (1, \'test1\', \'2014-10-01 00:00:00\')'); $pdo->exec('INSERT INTO tags(id, name, creationTime) VALUES (1, \'test1\', \'2014-10-01 00:00:00\')');
$pdo->exec('INSERT INTO tags(id, name, creationTime) VALUES (2, \'test2\', \'2014-10-01 00:00:00\')'); $pdo->exec('INSERT INTO tags(id, name, creationTime) VALUES (2, \'test2\', \'2014-10-01 00:00:00\')');
$pdo->exec('UPDATE sequencer SET lastUsedId = 2 WHERE tableName = \'tags\''); $pdo->exec('UPDATE sequencer SET lastUsedId = 2 WHERE tableName = \'tags\'');
$tag1 = new Tag(); $tag1 = new Tag();
$tag1->setName('test1'); $tag1->setName('test1');
$tag2 = new Tag(); $tag2 = new Tag();
$tag2->setName('test3'); $tag2->setName('test3');
$tagService = $this->getTagService(); $tagService = $this->getTagService();
$result = $tagService->createTags([$tag1, $tag2]); $result = $tagService->createTags([$tag1, $tag2]);
$this->assertEquals(2, count($result)); $this->assertEquals(2, count($result));
$this->assertEquals(1, $result[0]->getId()); $this->assertEquals(1, $result[0]->getId());
$this->assertNotNull($result[1]->getId()); $this->assertNotNull($result[1]->getId());
$this->assertEquals('test1', $result[0]->getName()); $this->assertEquals('test1', $result[0]->getName());
$this->assertEquals('test3', $result[1]->getName()); $this->assertEquals('test3', $result[1]->getName());
} }
public function testExportRelations() public function testExportRelations()
{ {
$fileDao = $this->getPublicFileDao(); $fileDao = $this->getPublicFileDao();
$tagService = $this->getTagService(); $tagService = $this->getTagService();
$tag1 = new Tag(); $tag1 = new Tag();
$tag1->setName('test'); $tag1->setName('test');
$tag1->setCreationTime(date('c')); $tag1->setCreationTime(date('c'));
$tag2 = new Tag(); $tag2 = new Tag();
$tag2->setName('test 2'); $tag2->setName('test 2');
$tag3 = new Tag(); $tag3 = new Tag();
$tag3->setName('test 3'); $tag3->setName('test 3');
$tag4 = new Tag(); $tag4 = new Tag();
$tag4->setName('test 4'); $tag4->setName('test 4');
$tag5 = new Tag(); $tag5 = new Tag();
$tag5->setName('test 5'); $tag5->setName('test 5');
$tagService->createTags([$tag2, $tag3, $tag4, $tag5]); $tagService->createTags([$tag2, $tag3, $tag4, $tag5]);
$tag1->setImpliedTags([$tag2, $tag3]); $tag1->setImpliedTags([$tag2, $tag3]);
$tag1->setSuggestedTags([$tag4, $tag5]); $tag1->setSuggestedTags([$tag4, $tag5]);
$tagService->createTags([$tag1]); $tagService->createTags([$tag1]);
$tagService->exportJson(); $tagService->exportJson();
$this->assertEquals('[' . $this->assertEquals('[' .
'{"name":"test 2","usages":0,"banned":false},' . '{"name":"test 2","usages":0,"banned":false},' .
'{"name":"test 3","usages":0,"banned":false},' . '{"name":"test 3","usages":0,"banned":false},' .
'{"name":"test 4","usages":0,"banned":false},' . '{"name":"test 4","usages":0,"banned":false},' .
'{"name":"test 5","usages":0,"banned":false},' . '{"name":"test 5","usages":0,"banned":false},' .
'{"name":"test","usages":0,"banned":false,"implications":["test 2","test 3"],"suggestions":["test 4","test 5"]}]', '{"name":"test","usages":0,"banned":false,"implications":["test 2","test 3"],"suggestions":["test 4","test 5"]}]',
$fileDao->load('tags.json')); $fileDao->load('tags.json'));
} }
public function testExportSingle() public function testExportSingle()
{ {
$tag1 = new Tag(); $tag1 = new Tag();
$tag1->setName('test'); $tag1->setName('test');
$tag1->setCreationTime(date('c')); $tag1->setCreationTime(date('c'));
$fileDao = $this->getPublicFileDao(); $fileDao = $this->getPublicFileDao();
$tagService = $this->getTagService(); $tagService = $this->getTagService();
$tagService->createTags([$tag1]); $tagService->createTags([$tag1]);
$tagService->exportJson(); $tagService->exportJson();
$this->assertEquals('[{"name":"test","usages":0,"banned":false}]', $fileDao->load('tags.json')); $this->assertEquals('[{"name":"test","usages":0,"banned":false}]', $fileDao->load('tags.json'));
} }
public function testMerging() public function testMerging()
{ {
$tag1 = self::getTestTag('test 1'); $tag1 = self::getTestTag('test 1');
$tag2 = self::getTestTag('test 2'); $tag2 = self::getTestTag('test 2');
$tag3 = self::getTestTag('test 3'); $tag3 = self::getTestTag('test 3');
$tagDao = Injector::get(TagDao::class); $tagDao = Injector::get(TagDao::class);
$tagDao->save($tag1); $tagDao->save($tag1);
$tagDao->save($tag2); $tagDao->save($tag2);
$tagDao->save($tag3); $tagDao->save($tag3);
$post1 = self::getTestPost(); $post1 = self::getTestPost();
$post2 = self::getTestPost(); $post2 = self::getTestPost();
$post3 = self::getTestPost(); $post3 = self::getTestPost();
$post1->setTags([$tag1]); $post1->setTags([$tag1]);
$post2->setTags([$tag1, $tag3]); $post2->setTags([$tag1, $tag3]);
$post3->setTags([$tag2, $tag3]); $post3->setTags([$tag2, $tag3]);
$postDao = Injector::get(PostDao::class); $postDao = Injector::get(PostDao::class);
$postDao->save($post1); $postDao->save($post1);
$postDao->save($post2); $postDao->save($post2);
$postDao->save($post3); $postDao->save($post3);
$tagService = $this->getTagService(); $tagService = $this->getTagService();
$tagService->mergeTag($tag1, $tag2); $tagService->mergeTag($tag1, $tag2);
$this->assertNull($tagDao->findByName($tag1->getName())); $this->assertNull($tagDao->findByName($tag1->getName()));
$this->assertNotNull($tagDao->findByName($tag2->getName())); $this->assertNotNull($tagDao->findByName($tag2->getName()));
$post1 = $postDao->findById($post1->getId()); $post1 = $postDao->findById($post1->getId());
$post2 = $postDao->findById($post2->getId()); $post2 = $postDao->findById($post2->getId());
$post3 = $postDao->findById($post3->getId()); $post3 = $postDao->findById($post3->getId());
$this->assertEntitiesEqual([$tag2], array_values($post1->getTags())); $this->assertEntitiesEqual([$tag2], array_values($post1->getTags()));
$this->assertEntitiesEqual([$tag2, $tag3], array_values($post2->getTags())); $this->assertEntitiesEqual([$tag2, $tag3], array_values($post2->getTags()));
$this->assertEntitiesEqual([$tag2, $tag3], array_values($post3->getTags())); $this->assertEntitiesEqual([$tag2, $tag3], array_values($post3->getTags()));
} }
public function testExportMultiple() public function testExportMultiple()
{ {
$tag1 = new Tag(); $tag1 = new Tag();
$tag1->setName('test1'); $tag1->setName('test1');
$tag1->setCreationTime(date('c')); $tag1->setCreationTime(date('c'));
$tag2 = new Tag(); $tag2 = new Tag();
$tag2->setName('test2'); $tag2->setName('test2');
$tag2->setCreationTime(date('c')); $tag2->setCreationTime(date('c'));
$tag2->setBanned(true); $tag2->setBanned(true);
$fileDao = $this->getPublicFileDao(); $fileDao = $this->getPublicFileDao();
$tagService = $this->getTagService(); $tagService = $this->getTagService();
$tagService->createTags([$tag1, $tag2]); $tagService->createTags([$tag1, $tag2]);
$tagService->exportJson(); $tagService->exportJson();
$this->assertEquals('[{"name":"test1","usages":0,"banned":false},{"name":"test2","usages":0,"banned":true}]', $fileDao->load('tags.json')); $this->assertEquals('[{"name":"test1","usages":0,"banned":false},{"name":"test2","usages":0,"banned":true}]', $fileDao->load('tags.json'));
} }
private function getPublicFileDao() private function getPublicFileDao()
{ {
return Injector::get(PublicFileDao::class); return Injector::get(PublicFileDao::class);
} }
private function getTagService() private function getTagService()
{ {
return Injector::get(TagService::class); return Injector::get(TagService::class);
} }
} }

View file

@ -10,101 +10,101 @@ use Szurubooru\Tests\AbstractTestCase;
final class ThumbnailGeneratorTest extends AbstractTestCase final class ThumbnailGeneratorTest extends AbstractTestCase
{ {
public function testFlashThumbnails() public function testFlashThumbnails()
{ {
if (!ProgramExecutor::isProgramAvailable(ImageConverter::PROGRAM_NAME_DUMP_GNASH) if (!ProgramExecutor::isProgramAvailable(ImageConverter::PROGRAM_NAME_DUMP_GNASH)
and !ProgramExecutor::isProgramAvailable(ImageConverter::PROGRAM_NAME_SWFRENDER)) and !ProgramExecutor::isProgramAvailable(ImageConverter::PROGRAM_NAME_SWFRENDER))
{ {
$this->markTestSkipped('External software necessary to run this test is missing.'); $this->markTestSkipped('External software necessary to run this test is missing.');
} }
$thumbnailGenerator = $this->getThumbnailGenerator(); $thumbnailGenerator = $this->getThumbnailGenerator();
$imageManipulator = $this->getImageManipulator(); $imageManipulator = $this->getImageManipulator();
$result = $thumbnailGenerator->generate( $result = $thumbnailGenerator->generate(
$this->getTestFile('flash.swf'), $this->getTestFile('flash.swf'),
150, 150,
150, 150,
ThumbnailGenerator::CROP_OUTSIDE, ThumbnailGenerator::CROP_OUTSIDE,
IImageManipulator::FORMAT_PNG); IImageManipulator::FORMAT_PNG);
$image = $imageManipulator->loadFromBuffer($result); $image = $imageManipulator->loadFromBuffer($result);
$this->assertEquals(150, $imageManipulator->getImageWidth($image)); $this->assertEquals(150, $imageManipulator->getImageWidth($image));
$this->assertEquals(150, $imageManipulator->getImageHeight($image)); $this->assertEquals(150, $imageManipulator->getImageHeight($image));
} }
public function testVideoThumbnails() public function testVideoThumbnails()
{ {
if (!ProgramExecutor::isProgramAvailable(ImageConverter::PROGRAM_NAME_FFMPEG) if (!ProgramExecutor::isProgramAvailable(ImageConverter::PROGRAM_NAME_FFMPEG)
and !ProgramExecutor::isProgramAvailable(ImageConverter::PROGRAM_NAME_FFMPEGTHUMBNAILER)) and !ProgramExecutor::isProgramAvailable(ImageConverter::PROGRAM_NAME_FFMPEGTHUMBNAILER))
{ {
$this->markTestSkipped('External software necessary to run this test is missing.'); $this->markTestSkipped('External software necessary to run this test is missing.');
} }
$thumbnailGenerator = $this->getThumbnailGenerator(); $thumbnailGenerator = $this->getThumbnailGenerator();
$imageManipulator = $this->getImageManipulator(); $imageManipulator = $this->getImageManipulator();
$result = $thumbnailGenerator->generate( $result = $thumbnailGenerator->generate(
$this->getTestFile('video.mp4'), $this->getTestFile('video.mp4'),
150, 150,
150, 150,
ThumbnailGenerator::CROP_OUTSIDE, ThumbnailGenerator::CROP_OUTSIDE,
IImageManipulator::FORMAT_PNG); IImageManipulator::FORMAT_PNG);
$image = $imageManipulator->loadFromBuffer($result); $image = $imageManipulator->loadFromBuffer($result);
$this->assertEquals(150, $imageManipulator->getImageWidth($image)); $this->assertEquals(150, $imageManipulator->getImageWidth($image));
$this->assertEquals(150, $imageManipulator->getImageHeight($image)); $this->assertEquals(150, $imageManipulator->getImageHeight($image));
} }
public function testImageThumbnails() public function testImageThumbnails()
{ {
$thumbnailGenerator = $this->getThumbnailGenerator(); $thumbnailGenerator = $this->getThumbnailGenerator();
$imageManipulator = $this->getImageManipulator(); $imageManipulator = $this->getImageManipulator();
$result = $thumbnailGenerator->generate( $result = $thumbnailGenerator->generate(
$this->getTestFile('image.jpg'), $this->getTestFile('image.jpg'),
150, 150,
150, 150,
ThumbnailGenerator::CROP_OUTSIDE, ThumbnailGenerator::CROP_OUTSIDE,
IImageManipulator::FORMAT_PNG); IImageManipulator::FORMAT_PNG);
$image = $imageManipulator->loadFromBuffer($result); $image = $imageManipulator->loadFromBuffer($result);
$this->assertEquals(150, $imageManipulator->getImageWidth($image)); $this->assertEquals(150, $imageManipulator->getImageWidth($image));
$this->assertEquals(150, $imageManipulator->getImageHeight($image)); $this->assertEquals(150, $imageManipulator->getImageHeight($image));
$result = $thumbnailGenerator->generate( $result = $thumbnailGenerator->generate(
$this->getTestFile('image.jpg'), $this->getTestFile('image.jpg'),
150, 150,
150, 150,
ThumbnailGenerator::CROP_INSIDE, ThumbnailGenerator::CROP_INSIDE,
IImageManipulator::FORMAT_PNG); IImageManipulator::FORMAT_PNG);
$image = $imageManipulator->loadFromBuffer($result); $image = $imageManipulator->loadFromBuffer($result);
$this->assertEquals(150, $imageManipulator->getImageWidth($image)); $this->assertEquals(150, $imageManipulator->getImageWidth($image));
$this->assertEquals(112, $imageManipulator->getImageHeight($image)); $this->assertEquals(112, $imageManipulator->getImageHeight($image));
} }
public function testBadThumbnails() public function testBadThumbnails()
{ {
$thumbnailGenerator = $this->getThumbnailGenerator(); $thumbnailGenerator = $this->getThumbnailGenerator();
$imageManipulator = $this->getImageManipulator(); $imageManipulator = $this->getImageManipulator();
$this->setExpectedException(\Exception::class); $this->setExpectedException(\Exception::class);
$thumbnailGenerator->generate( $thumbnailGenerator->generate(
$this->getTestFile('text.txt'), $this->getTestFile('text.txt'),
150, 150,
150, 150,
ThumbnailGenerator::CROP_OUTSIDE, ThumbnailGenerator::CROP_OUTSIDE,
IImageManipulator::FORMAT_PNG); IImageManipulator::FORMAT_PNG);
} }
public function getImageManipulator() public function getImageManipulator()
{ {
return Injector::get(ImageManipulator::class); return Injector::get(ImageManipulator::class);
} }
public function getThumbnailGenerator() public function getThumbnailGenerator()
{ {
return Injector::get(ThumbnailGenerator::class); return Injector::get(ThumbnailGenerator::class);
} }
} }

View file

@ -7,149 +7,149 @@ use Szurubooru\Tests\AbstractTestCase;
final class ThumbnailServiceTest extends AbstractTestCase final class ThumbnailServiceTest extends AbstractTestCase
{ {
private $configMock; private $configMock;
private $fileDaoMock; private $fileDaoMock;
private $thumbnailGeneratorMock; private $thumbnailGeneratorMock;
public function setUp() public function setUp()
{ {
parent::setUp(); parent::setUp();
$this->configMock = $this->mockConfig(); $this->configMock = $this->mockConfig();
$this->fileDaoMock = $this->mock(PublicFileDao::class); $this->fileDaoMock = $this->mock(PublicFileDao::class);
$this->thumbnailServiceMock = $this->mock(ThumbnailService::class); $this->thumbnailServiceMock = $this->mock(ThumbnailService::class);
$this->thumbnailGeneratorMock = $this->mock(ThumbnailGenerator::class); $this->thumbnailGeneratorMock = $this->mock(ThumbnailGenerator::class);
} }
public function testGetUsedThumbnailSizes() public function testGetUsedThumbnailSizes()
{ {
$tempDirectory = $this->createTestDirectory(); $tempDirectory = $this->createTestDirectory();
mkdir($tempDirectory . DIRECTORY_SEPARATOR . '5x5'); mkdir($tempDirectory . DIRECTORY_SEPARATOR . '5x5');
mkdir($tempDirectory . DIRECTORY_SEPARATOR . '10x10'); mkdir($tempDirectory . DIRECTORY_SEPARATOR . '10x10');
mkdir($tempDirectory . DIRECTORY_SEPARATOR . 'something unexpected'); mkdir($tempDirectory . DIRECTORY_SEPARATOR . 'something unexpected');
touch($tempDirectory . DIRECTORY_SEPARATOR . '15x15'); touch($tempDirectory . DIRECTORY_SEPARATOR . '15x15');
$this->fileDaoMock->expects($this->once())->method('getFullPath')->with('thumbnails')->willReturn($tempDirectory); $this->fileDaoMock->expects($this->once())->method('getFullPath')->with('thumbnails')->willReturn($tempDirectory);
$thumbnailService = $this->getThumbnailService(); $thumbnailService = $this->getThumbnailService();
$expected = [[5, 5], [10, 10]]; $expected = [[5, 5], [10, 10]];
$actual = iterator_to_array($thumbnailService->getUsedThumbnailSizes()); $actual = iterator_to_array($thumbnailService->getUsedThumbnailSizes());
$this->assertEquals(count($expected), count($actual)); $this->assertEquals(count($expected), count($actual));
foreach ($expected as $v) foreach ($expected as $v)
$this->assertContains($v, $actual); $this->assertContains($v, $actual);
} }
public function testDeleteUsedThumbnails() public function testDeleteUsedThumbnails()
{ {
$tempDirectory = $this->createTestDirectory(); $tempDirectory = $this->createTestDirectory();
mkdir($tempDirectory . DIRECTORY_SEPARATOR . '5x5'); mkdir($tempDirectory . DIRECTORY_SEPARATOR . '5x5');
mkdir($tempDirectory . DIRECTORY_SEPARATOR . '10x10'); mkdir($tempDirectory . DIRECTORY_SEPARATOR . '10x10');
touch($tempDirectory . DIRECTORY_SEPARATOR . '5x5' . DIRECTORY_SEPARATOR . 'remove'); touch($tempDirectory . DIRECTORY_SEPARATOR . '5x5' . DIRECTORY_SEPARATOR . 'remove');
touch($tempDirectory . DIRECTORY_SEPARATOR . '5x5' . DIRECTORY_SEPARATOR . 'keep'); touch($tempDirectory . DIRECTORY_SEPARATOR . '5x5' . DIRECTORY_SEPARATOR . 'keep');
touch($tempDirectory . DIRECTORY_SEPARATOR . '10x10' . DIRECTORY_SEPARATOR . 'remove'); touch($tempDirectory . DIRECTORY_SEPARATOR . '10x10' . DIRECTORY_SEPARATOR . 'remove');
$this->fileDaoMock->expects($this->once())->method('getFullPath')->with('thumbnails')->willReturn($tempDirectory); $this->fileDaoMock->expects($this->once())->method('getFullPath')->with('thumbnails')->willReturn($tempDirectory);
$this->fileDaoMock->expects($this->exactly(2))->method('delete')->withConsecutive( $this->fileDaoMock->expects($this->exactly(2))->method('delete')->withConsecutive(
['thumbnails' . DIRECTORY_SEPARATOR . '10x10' . DIRECTORY_SEPARATOR . 'remove'], ['thumbnails' . DIRECTORY_SEPARATOR . '10x10' . DIRECTORY_SEPARATOR . 'remove'],
['thumbnails' . DIRECTORY_SEPARATOR . '5x5' . DIRECTORY_SEPARATOR . 'remove']); ['thumbnails' . DIRECTORY_SEPARATOR . '5x5' . DIRECTORY_SEPARATOR . 'remove']);
$thumbnailService = $this->getThumbnailService(); $thumbnailService = $this->getThumbnailService();
$thumbnailService->deleteUsedThumbnails('remove'); $thumbnailService->deleteUsedThumbnails('remove');
} }
public function testGeneratingFromNonExistingSource() public function testGeneratingFromNonExistingSource()
{ {
$this->configMock->set('misc/thumbnailCropStyle', 'outside'); $this->configMock->set('misc/thumbnailCropStyle', 'outside');
$this->fileDaoMock $this->fileDaoMock
->expects($this->once()) ->expects($this->once())
->method('load') ->method('load')
->with('nope') ->with('nope')
->willReturn(null); ->willReturn(null);
$this->thumbnailGeneratorMock $this->thumbnailGeneratorMock
->expects($this->never()) ->expects($this->never())
->method('generate'); ->method('generate');
$this->fileDaoMock $this->fileDaoMock
->expects($this->never()) ->expects($this->never())
->method('save'); ->method('save');
$thumbnailService = $this->getThumbnailService(); $thumbnailService = $this->getThumbnailService();
$this->assertEquals( $this->assertEquals(
'thumbnails' . DIRECTORY_SEPARATOR . 'blank.png', 'thumbnails' . DIRECTORY_SEPARATOR . 'blank.png',
$thumbnailService->generate('nope', 100, 100)); $thumbnailService->generate('nope', 100, 100));
} }
public function testThumbnailGeneratingFail() public function testThumbnailGeneratingFail()
{ {
$this->configMock->set('misc/thumbnailCropStyle', 'outside'); $this->configMock->set('misc/thumbnailCropStyle', 'outside');
$this->fileDaoMock $this->fileDaoMock
->expects($this->once()) ->expects($this->once())
->method('load') ->method('load')
->with('nope') ->with('nope')
->willReturn('content of file'); ->willReturn('content of file');
$this->thumbnailGeneratorMock $this->thumbnailGeneratorMock
->expects($this->once()) ->expects($this->once())
->method('generate') ->method('generate')
->with( ->with(
'content of file', 'content of file',
100, 100,
100, 100,
ThumbnailGenerator::CROP_OUTSIDE) ThumbnailGenerator::CROP_OUTSIDE)
->willReturn(null); ->willReturn(null);
$this->fileDaoMock $this->fileDaoMock
->expects($this->never()) ->expects($this->never())
->method('save'); ->method('save');
$thumbnailService = $this->getThumbnailService(); $thumbnailService = $this->getThumbnailService();
$this->assertEquals( $this->assertEquals(
'thumbnails' . DIRECTORY_SEPARATOR . 'blank.png', 'thumbnails' . DIRECTORY_SEPARATOR . 'blank.png',
$thumbnailService->generate('nope', 100, 100)); $thumbnailService->generate('nope', 100, 100));
} }
public function testThumbnailGeneratingSuccess() public function testThumbnailGeneratingSuccess()
{ {
$this->configMock->set('misc/thumbnailCropStyle', 'outside'); $this->configMock->set('misc/thumbnailCropStyle', 'outside');
$this->fileDaoMock $this->fileDaoMock
->expects($this->once()) ->expects($this->once())
->method('load') ->method('load')
->with('okay') ->with('okay')
->willReturn('content of file'); ->willReturn('content of file');
$this->thumbnailGeneratorMock $this->thumbnailGeneratorMock
->expects($this->once()) ->expects($this->once())
->method('generate') ->method('generate')
->with( ->with(
'content of file', 'content of file',
100, 100,
100, 100,
ThumbnailGenerator::CROP_OUTSIDE) ThumbnailGenerator::CROP_OUTSIDE)
->willReturn('content of thumbnail'); ->willReturn('content of thumbnail');
$this->fileDaoMock $this->fileDaoMock
->expects($this->once()) ->expects($this->once())
->method('save') ->method('save')
->with( ->with(
'thumbnails' . DIRECTORY_SEPARATOR . '100x100' . DIRECTORY_SEPARATOR . 'okay', 'thumbnails' . DIRECTORY_SEPARATOR . '100x100' . DIRECTORY_SEPARATOR . 'okay',
'content of thumbnail'); 'content of thumbnail');
$thumbnailService = $this->getThumbnailService(); $thumbnailService = $this->getThumbnailService();
$this->assertEquals( $this->assertEquals(
'thumbnails' . DIRECTORY_SEPARATOR . '100x100' . DIRECTORY_SEPARATOR . 'okay', 'thumbnails' . DIRECTORY_SEPARATOR . '100x100' . DIRECTORY_SEPARATOR . 'okay',
$thumbnailService->generate('okay', 100, 100)); $thumbnailService->generate('okay', 100, 100));
} }
private function getThumbnailService() private function getThumbnailService()
{ {
return new ThumbnailService( return new ThumbnailService(
$this->configMock, $this->configMock,
$this->fileDaoMock, $this->fileDaoMock,
$this->thumbnailGeneratorMock); $this->thumbnailGeneratorMock);
} }
} }

View file

@ -15,279 +15,279 @@ use Szurubooru\Validator;
final class UserServiceTest extends AbstractTestCase final class UserServiceTest extends AbstractTestCase
{ {
private $configMock; private $configMock;
private $validatorMock; private $validatorMock;
private $transactionManagerMock; private $transactionManagerMock;
private $userDaoMock; private $userDaoMock;
private $passwordServiceMock; private $passwordServiceMock;
private $emailServiceMock; private $emailServiceMock;
private $timeServiceMock; private $timeServiceMock;
private $tokenServiceMock; private $tokenServiceMock;
public function setUp() public function setUp()
{ {
parent::setUp(); parent::setUp();
$this->configMock = $this->mockConfig(); $this->configMock = $this->mockConfig();
$this->transactionManagerMock = $this->mockTransactionManager(); $this->transactionManagerMock = $this->mockTransactionManager();
$this->validatorMock = $this->mock(Validator::class); $this->validatorMock = $this->mock(Validator::class);
$this->userDaoMock = $this->mock(UserDao::class); $this->userDaoMock = $this->mock(UserDao::class);
$this->passwordServiceMock = $this->mock(PasswordService::class); $this->passwordServiceMock = $this->mock(PasswordService::class);
$this->emailServiceMock = $this->mock(EmailService::class); $this->emailServiceMock = $this->mock(EmailService::class);
$this->timeServiceMock = $this->mock(TimeService::class); $this->timeServiceMock = $this->mock(TimeService::class);
$this->tokenServiceMock = $this->mock(TokenService::class); $this->tokenServiceMock = $this->mock(TokenService::class);
} }
public function testGettingByName() public function testGettingByName()
{ {
$testUser = new User; $testUser = new User;
$testUser->setName('godzilla'); $testUser->setName('godzilla');
$this->userDaoMock->expects($this->once())->method('findByName')->willReturn($testUser); $this->userDaoMock->expects($this->once())->method('findByName')->willReturn($testUser);
$userService = $this->getUserService(); $userService = $this->getUserService();
$expected = $testUser; $expected = $testUser;
$actual = $userService->getByName('godzilla'); $actual = $userService->getByName('godzilla');
$this->assertEquals($expected, $actual); $this->assertEquals($expected, $actual);
} }
public function testGettingByNameNonExistentUsers() public function testGettingByNameNonExistentUsers()
{ {
$this->setExpectedException(\Exception::class, 'User with name "godzilla" was not found.'); $this->setExpectedException(\Exception::class, 'User with name "godzilla" was not found.');
$userService = $this->getUserService(); $userService = $this->getUserService();
$userService->getByName('godzilla'); $userService->getByName('godzilla');
} }
public function testGettingById() public function testGettingById()
{ {
$testUser = new User; $testUser = new User;
$testUser->setName('godzilla'); $testUser->setName('godzilla');
$this->userDaoMock->expects($this->once())->method('findById')->willReturn($testUser); $this->userDaoMock->expects($this->once())->method('findById')->willReturn($testUser);
$userService = $this->getUserService(); $userService = $this->getUserService();
$expected = $testUser; $expected = $testUser;
$actual = $userService->getById('godzilla'); $actual = $userService->getById('godzilla');
$this->assertEquals($expected, $actual); $this->assertEquals($expected, $actual);
} }
public function testGettingByIdNonExistentUsers() public function testGettingByIdNonExistentUsers()
{ {
$this->setExpectedException(\Exception::class, 'User with id "godzilla" was not found.'); $this->setExpectedException(\Exception::class, 'User with id "godzilla" was not found.');
$userService = $this->getUserService(); $userService = $this->getUserService();
$userService->getById('godzilla'); $userService->getById('godzilla');
} }
public function testValidRegistrationWithoutMailActivation() public function testValidRegistrationWithoutMailActivation()
{ {
$formData = new RegistrationFormData; $formData = new RegistrationFormData;
$formData->userName = 'user'; $formData->userName = 'user';
$formData->password = 'password'; $formData->password = 'password';
$formData->email = 'human@people.gov'; $formData->email = 'human@people.gov';
$this->configMock->set('security/needEmailActivationToRegister', false); $this->configMock->set('security/needEmailActivationToRegister', false);
$this->configMock->set('security/defaultAccessRank', 'regularUser'); $this->configMock->set('security/defaultAccessRank', 'regularUser');
$this->passwordServiceMock->expects($this->once())->method('getRandomPassword')->willReturn('salt'); $this->passwordServiceMock->expects($this->once())->method('getRandomPassword')->willReturn('salt');
$this->passwordServiceMock->expects($this->once())->method('getHash')->with('password', 'salt')->willReturn('hash'); $this->passwordServiceMock->expects($this->once())->method('getHash')->with('password', 'salt')->willReturn('hash');
$this->timeServiceMock->expects($this->once())->method('getCurrentTime')->willReturn('now'); $this->timeServiceMock->expects($this->once())->method('getCurrentTime')->willReturn('now');
$this->userDaoMock->expects($this->once())->method('hasAnyUsers')->willReturn(true); $this->userDaoMock->expects($this->once())->method('hasAnyUsers')->willReturn(true);
$this->userDaoMock->expects($this->once())->method('save')->will($this->returnArgument(0)); $this->userDaoMock->expects($this->once())->method('save')->will($this->returnArgument(0));
$this->emailServiceMock->expects($this->never())->method('sendActivationEmail'); $this->emailServiceMock->expects($this->never())->method('sendActivationEmail');
$userService = $this->getUserService(); $userService = $this->getUserService();
$savedUser = $userService->createUser($formData); $savedUser = $userService->createUser($formData);
$this->assertEquals('user', $savedUser->getName()); $this->assertEquals('user', $savedUser->getName());
$this->assertEquals('human@people.gov', $savedUser->getEmail()); $this->assertEquals('human@people.gov', $savedUser->getEmail());
$this->assertNull($savedUser->getEmailUnconfirmed()); $this->assertNull($savedUser->getEmailUnconfirmed());
$this->assertEquals('hash', $savedUser->getPasswordHash()); $this->assertEquals('hash', $savedUser->getPasswordHash());
$this->assertEquals(User::ACCESS_RANK_REGULAR_USER, $savedUser->getAccessRank()); $this->assertEquals(User::ACCESS_RANK_REGULAR_USER, $savedUser->getAccessRank());
$this->assertEquals('now', $savedUser->getRegistrationTime()); $this->assertEquals('now', $savedUser->getRegistrationTime());
$this->assertTrue($savedUser->isAccountConfirmed()); $this->assertTrue($savedUser->isAccountConfirmed());
} }
public function testValidRegistrationWithMailActivation() public function testValidRegistrationWithMailActivation()
{ {
$formData = new RegistrationFormData; $formData = new RegistrationFormData;
$formData->userName = 'user'; $formData->userName = 'user';
$formData->password = 'password'; $formData->password = 'password';
$formData->email = 'human@people.gov'; $formData->email = 'human@people.gov';
$this->configMock->set('security/needEmailActivationToRegister', true); $this->configMock->set('security/needEmailActivationToRegister', true);
$this->configMock->set('security/defaultAccessRank', 'powerUser'); $this->configMock->set('security/defaultAccessRank', 'powerUser');
$this->passwordServiceMock->expects($this->once())->method('getRandomPassword')->willReturn('salt'); $this->passwordServiceMock->expects($this->once())->method('getRandomPassword')->willReturn('salt');
$this->passwordServiceMock->expects($this->once())->method('getHash')->with('password', 'salt')->willReturn('hash'); $this->passwordServiceMock->expects($this->once())->method('getHash')->with('password', 'salt')->willReturn('hash');
$this->timeServiceMock->expects($this->once())->method('getCurrentTime')->willReturn('now'); $this->timeServiceMock->expects($this->once())->method('getCurrentTime')->willReturn('now');
$this->userDaoMock->expects($this->once())->method('hasAnyUsers')->willReturn(true); $this->userDaoMock->expects($this->once())->method('hasAnyUsers')->willReturn(true);
$this->userDaoMock->expects($this->once())->method('save')->will($this->returnArgument(0)); $this->userDaoMock->expects($this->once())->method('save')->will($this->returnArgument(0));
$testToken = new Token; $testToken = new Token;
$this->tokenServiceMock->expects($this->once())->method('createAndSaveToken')->willReturn($testToken); $this->tokenServiceMock->expects($this->once())->method('createAndSaveToken')->willReturn($testToken);
$this->emailServiceMock->expects($this->once())->method('sendActivationEmail')->with( $this->emailServiceMock->expects($this->once())->method('sendActivationEmail')->with(
$this->anything(), $this->anything(),
$testToken); $testToken);
$userService = $this->getUserService(); $userService = $this->getUserService();
$savedUser = $userService->createUser($formData); $savedUser = $userService->createUser($formData);
$this->assertEquals('user', $savedUser->getName()); $this->assertEquals('user', $savedUser->getName());
$this->assertNull($savedUser->getEmail()); $this->assertNull($savedUser->getEmail());
$this->assertEquals('human@people.gov', $savedUser->getEmailUnconfirmed()); $this->assertEquals('human@people.gov', $savedUser->getEmailUnconfirmed());
$this->assertEquals('hash', $savedUser->getPasswordHash()); $this->assertEquals('hash', $savedUser->getPasswordHash());
$this->assertEquals(User::ACCESS_RANK_POWER_USER, $savedUser->getAccessRank()); $this->assertEquals(User::ACCESS_RANK_POWER_USER, $savedUser->getAccessRank());
$this->assertEquals('now', $savedUser->getRegistrationTime()); $this->assertEquals('now', $savedUser->getRegistrationTime());
$this->assertFalse($savedUser->isAccountConfirmed()); $this->assertFalse($savedUser->isAccountConfirmed());
} }
public function testAccessRankOfFirstUser() public function testAccessRankOfFirstUser()
{ {
$formData = new RegistrationFormData; $formData = new RegistrationFormData;
$formData->userName = 'user'; $formData->userName = 'user';
$formData->password = 'password'; $formData->password = 'password';
$formData->email = 'email'; $formData->email = 'email';
$this->configMock->set('security/needEmailActivationToRegister', false); $this->configMock->set('security/needEmailActivationToRegister', false);
$this->userDaoMock->expects($this->once())->method('hasAnyUsers')->willReturn(false); $this->userDaoMock->expects($this->once())->method('hasAnyUsers')->willReturn(false);
$this->userDaoMock->expects($this->once())->method('save')->will($this->returnArgument(0)); $this->userDaoMock->expects($this->once())->method('save')->will($this->returnArgument(0));
$userService = $this->getUserService(); $userService = $this->getUserService();
$savedUser = $userService->createUser($formData); $savedUser = $userService->createUser($formData);
$this->assertEquals(User::ACCESS_RANK_ADMINISTRATOR, $savedUser->getAccessRank()); $this->assertEquals(User::ACCESS_RANK_ADMINISTRATOR, $savedUser->getAccessRank());
} }
public function testRegistrationWhenUserExists() public function testRegistrationWhenUserExists()
{ {
$formData = new RegistrationFormData; $formData = new RegistrationFormData;
$formData->userName = 'user'; $formData->userName = 'user';
$formData->password = 'password'; $formData->password = 'password';
$formData->email = 'email'; $formData->email = 'email';
$otherUser = new User('yes, i exist in database'); $otherUser = new User('yes, i exist in database');
$this->configMock->set('security/defaultAccessRank', 'restrictedUser'); $this->configMock->set('security/defaultAccessRank', 'restrictedUser');
$this->userDaoMock->expects($this->once())->method('hasAnyUsers')->willReturn(true); $this->userDaoMock->expects($this->once())->method('hasAnyUsers')->willReturn(true);
$this->userDaoMock->expects($this->once())->method('findByName')->willReturn($otherUser); $this->userDaoMock->expects($this->once())->method('findByName')->willReturn($otherUser);
$this->userDaoMock->expects($this->never())->method('save'); $this->userDaoMock->expects($this->never())->method('save');
$userService = $this->getUserService(); $userService = $this->getUserService();
$this->setExpectedException(\Exception::class, 'User with this name already exists'); $this->setExpectedException(\Exception::class, 'User with this name already exists');
$savedUser = $userService->createUser($formData); $savedUser = $userService->createUser($formData);
} }
public function testUpdatingName() public function testUpdatingName()
{ {
$testUser = new User; $testUser = new User;
$testUser->setName('wojtek'); $testUser->setName('wojtek');
$formData = new UserEditFormData; $formData = new UserEditFormData;
$formData->userName = 'sebastian'; $formData->userName = 'sebastian';
$this->userDaoMock->expects($this->once())->method('save')->will($this->returnArgument(0)); $this->userDaoMock->expects($this->once())->method('save')->will($this->returnArgument(0));
$userService = $this->getUserService(); $userService = $this->getUserService();
$savedUser = $userService->updateUser($testUser, $formData); $savedUser = $userService->updateUser($testUser, $formData);
$this->assertEquals('sebastian', $savedUser->getName()); $this->assertEquals('sebastian', $savedUser->getName());
} }
public function testUpdatingNameToExisting() public function testUpdatingNameToExisting()
{ {
$testUser = new User; $testUser = new User;
$testUser->setName('wojtek'); $testUser->setName('wojtek');
$formData = new UserEditFormData; $formData = new UserEditFormData;
$formData->userName = 'sebastian'; $formData->userName = 'sebastian';
$otherUser = new User('yes, i exist in database'); $otherUser = new User('yes, i exist in database');
$this->userDaoMock->expects($this->once())->method('findByName')->willReturn($otherUser); $this->userDaoMock->expects($this->once())->method('findByName')->willReturn($otherUser);
$this->userDaoMock->expects($this->never())->method('save'); $this->userDaoMock->expects($this->never())->method('save');
$this->setExpectedException(\Exception::class, 'User with this name already exists'); $this->setExpectedException(\Exception::class, 'User with this name already exists');
$userService = $this->getUserService(); $userService = $this->getUserService();
$savedUser = $userService->updateUser($testUser, $formData); $savedUser = $userService->updateUser($testUser, $formData);
} }
public function testUpdatingEmailWithoutConfirmation() public function testUpdatingEmailWithoutConfirmation()
{ {
$testUser = new User; $testUser = new User;
$this->configMock->set('security/needEmailActivationToRegister', false); $this->configMock->set('security/needEmailActivationToRegister', false);
$formData = new UserEditFormData; $formData = new UserEditFormData;
$formData->email = 'hikari@geofront.gov'; $formData->email = 'hikari@geofront.gov';
$this->userDaoMock->expects($this->once())->method('save')->will($this->returnArgument(0)); $this->userDaoMock->expects($this->once())->method('save')->will($this->returnArgument(0));
$userService = $this->getUserService(); $userService = $this->getUserService();
$savedUser = $userService->updateUser($testUser, $formData); $savedUser = $userService->updateUser($testUser, $formData);
$this->assertEquals('hikari@geofront.gov', $savedUser->getEmail()); $this->assertEquals('hikari@geofront.gov', $savedUser->getEmail());
$this->assertNull($savedUser->getEmailUnconfirmed()); $this->assertNull($savedUser->getEmailUnconfirmed());
$this->assertTrue($savedUser->isAccountConfirmed()); $this->assertTrue($savedUser->isAccountConfirmed());
} }
public function testUpdatingEmailWithConfirmation() public function testUpdatingEmailWithConfirmation()
{ {
$testUser = new User; $testUser = new User;
$this->configMock->set('security/needEmailActivationToRegister', true); $this->configMock->set('security/needEmailActivationToRegister', true);
$formData = new UserEditFormData; $formData = new UserEditFormData;
$formData->email = 'hikari@geofront.gov'; $formData->email = 'hikari@geofront.gov';
$this->tokenServiceMock->expects($this->once())->method('createAndSaveToken')->willReturn(new Token()); $this->tokenServiceMock->expects($this->once())->method('createAndSaveToken')->willReturn(new Token());
$this->userDaoMock->expects($this->once())->method('save')->will($this->returnArgument(0)); $this->userDaoMock->expects($this->once())->method('save')->will($this->returnArgument(0));
$userService = $this->getUserService(); $userService = $this->getUserService();
$savedUser = $userService->updateUser($testUser, $formData); $savedUser = $userService->updateUser($testUser, $formData);
$this->assertNull($savedUser->getEmail()); $this->assertNull($savedUser->getEmail());
$this->assertEquals('hikari@geofront.gov', $savedUser->getEmailUnconfirmed()); $this->assertEquals('hikari@geofront.gov', $savedUser->getEmailUnconfirmed());
$this->assertFalse($savedUser->isAccountConfirmed()); $this->assertFalse($savedUser->isAccountConfirmed());
} }
public function testUpdatingEmailWithConfirmationToExisting() public function testUpdatingEmailWithConfirmationToExisting()
{ {
$testUser = new User; $testUser = new User;
$this->configMock->set('security/needEmailActivationToRegister', true); $this->configMock->set('security/needEmailActivationToRegister', true);
$formData = new UserEditFormData; $formData = new UserEditFormData;
$formData->email = 'hikari@geofront.gov'; $formData->email = 'hikari@geofront.gov';
$otherUser = new User('yes, i exist in database'); $otherUser = new User('yes, i exist in database');
$this->tokenServiceMock->expects($this->never())->method('createAndSaveToken'); $this->tokenServiceMock->expects($this->never())->method('createAndSaveToken');
$this->userDaoMock->expects($this->once())->method('findByEmail')->willReturn($otherUser); $this->userDaoMock->expects($this->once())->method('findByEmail')->willReturn($otherUser);
$this->userDaoMock->expects($this->never())->method('save'); $this->userDaoMock->expects($this->never())->method('save');
$this->setExpectedException(\Exception::class, 'User with this e-mail already exists'); $this->setExpectedException(\Exception::class, 'User with this e-mail already exists');
$userService = $this->getUserService(); $userService = $this->getUserService();
$userService->updateUser($testUser, $formData); $userService->updateUser($testUser, $formData);
} }
public function testUpdatingEmailToAlreadyConfirmed() public function testUpdatingEmailToAlreadyConfirmed()
{ {
$testUser = new User('yep, still me'); $testUser = new User('yep, still me');
$testUser->setEmail('hikari@geofront.gov'); $testUser->setEmail('hikari@geofront.gov');
$testUser->setAccountConfirmed(true); $testUser->setAccountConfirmed(true);
$testUser->setEmailUnconfirmed('coolcat32@sakura.ne.jp'); $testUser->setEmailUnconfirmed('coolcat32@sakura.ne.jp');
$formData = new UserEditFormData; $formData = new UserEditFormData;
$formData->email = 'hikari@geofront.gov'; $formData->email = 'hikari@geofront.gov';
$otherUser = new User('yep, still me'); $otherUser = new User('yep, still me');
$this->tokenServiceMock->expects($this->never())->method('createAndSaveToken'); $this->tokenServiceMock->expects($this->never())->method('createAndSaveToken');
$this->userDaoMock->expects($this->never())->method('findByEmail'); $this->userDaoMock->expects($this->never())->method('findByEmail');
$this->userDaoMock->expects($this->once())->method('save')->will($this->returnArgument(0)); $this->userDaoMock->expects($this->once())->method('save')->will($this->returnArgument(0));
$userService = $this->getUserService(); $userService = $this->getUserService();
$savedUser = $userService->updateUser($testUser, $formData); $savedUser = $userService->updateUser($testUser, $formData);
$this->assertEquals('hikari@geofront.gov', $savedUser->getEmail()); $this->assertEquals('hikari@geofront.gov', $savedUser->getEmail());
$this->assertNull($savedUser->getEmailUnconfirmed()); $this->assertNull($savedUser->getEmailUnconfirmed());
$this->assertTrue($savedUser->isAccountConfirmed()); $this->assertTrue($savedUser->isAccountConfirmed());
} }
private function getUserService() private function getUserService()
{ {
return new UserService( return new UserService(
$this->configMock, $this->configMock,
$this->validatorMock, $this->validatorMock,
$this->transactionManagerMock, $this->transactionManagerMock,
$this->userDaoMock, $this->userDaoMock,
$this->passwordServiceMock, $this->passwordServiceMock,
$this->emailServiceMock, $this->emailServiceMock,
$this->timeServiceMock, $this->timeServiceMock,
$this->tokenServiceMock); $this->tokenServiceMock);
} }
} }

View file

@ -3,53 +3,53 @@ namespace Szurubooru\Tests;
class TestHelper class TestHelper
{ {
public static function createTestDirectory() public static function createTestDirectory()
{ {
$path = self::getTestDirectoryPath(); $path = self::getTestDirectoryPath();
if (!file_exists($path)) if (!file_exists($path))
mkdir($path, 0777, true); mkdir($path, 0777, true);
return $path; return $path;
} }
public static function mockConfig($dataPath = null, $publicDataPath = null) public static function mockConfig($dataPath = null, $publicDataPath = null)
{ {
return new ConfigMock($dataPath, $publicDataPath); return new ConfigMock($dataPath, $publicDataPath);
} }
public static function getTestFile($fileName) public static function getTestFile($fileName)
{ {
return file_get_contents(self::getTestFilePath($fileName)); return file_get_contents(self::getTestFilePath($fileName));
} }
public static function getTestFilePath($fileName) public static function getTestFilePath($fileName)
{ {
return __DIR__ . DIRECTORY_SEPARATOR . 'test_files' . DIRECTORY_SEPARATOR . $fileName; return __DIR__ . DIRECTORY_SEPARATOR . 'test_files' . DIRECTORY_SEPARATOR . $fileName;
} }
public static function cleanTestDirectory() public static function cleanTestDirectory()
{ {
if (!file_exists(self::getTestDirectoryPath())) if (!file_exists(self::getTestDirectoryPath()))
return; return;
$dirIterator = new \RecursiveDirectoryIterator( $dirIterator = new \RecursiveDirectoryIterator(
self::getTestDirectoryPath(), self::getTestDirectoryPath(),
\RecursiveDirectoryIterator::SKIP_DOTS); \RecursiveDirectoryIterator::SKIP_DOTS);
$files = new \RecursiveIteratorIterator( $files = new \RecursiveIteratorIterator(
$dirIterator, $dirIterator,
\RecursiveIteratorIterator::CHILD_FIRST); \RecursiveIteratorIterator::CHILD_FIRST);
foreach ($files as $fileInfo) foreach ($files as $fileInfo)
{ {
if ($fileInfo->isDir()) if ($fileInfo->isDir())
rmdir($fileInfo->getRealPath()); rmdir($fileInfo->getRealPath());
else else
unlink($fileInfo->getRealPath()); unlink($fileInfo->getRealPath());
} }
} }
private static function getTestDirectoryPath() private static function getTestDirectoryPath()
{ {
return __DIR__ . DIRECTORY_SEPARATOR . 'files'; return __DIR__ . DIRECTORY_SEPARATOR . 'files';
} }
} }

View file

@ -4,13 +4,13 @@ use Szurubooru\Dao\TransactionManager;
final class TransactionManagerMock extends TransactionManager final class TransactionManagerMock extends TransactionManager
{ {
public function rollback($callback) public function rollback($callback)
{ {
return $callback(); return $callback();
} }
public function commit($callback) public function commit($callback)
{ {
return $callback(); return $callback();
} }
} }

View file

@ -4,156 +4,156 @@ use Szurubooru\Tests\AbstractTestCase;
final class ValidatorTest extends AbstractTestCase final class ValidatorTest extends AbstractTestCase
{ {
private $configMock; private $configMock;
public function setUp() public function setUp()
{ {
parent::setUp(); parent::setUp();
$this->configMock = $this->mockConfig(); $this->configMock = $this->mockConfig();
} }
public function testMinLengthName() public function testMinLengthName()
{ {
$validator = $this->getValidator(); $validator = $this->getValidator();
$this->setExpectedException(\Exception::class, 'Object must have at least 50 character(s)'); $this->setExpectedException(\Exception::class, 'Object must have at least 50 character(s)');
$validator->validateMinLength('too short', 50); $validator->validateMinLength('too short', 50);
} }
public function testMaxLengthName() public function testMaxLengthName()
{ {
$validator = $this->getValidator(); $validator = $this->getValidator();
$this->setExpectedException(\Exception::class, 'Object must have at most 1 character(s)'); $this->setExpectedException(\Exception::class, 'Object must have at most 1 character(s)');
$validator->validateMaxLength('too long', 1); $validator->validateMaxLength('too long', 1);
} }
public function testValidLengthName() public function testValidLengthName()
{ {
$validator = $this->getValidator(); $validator = $this->getValidator();
$this->assertNull($validator->validateLength('fitting', 1, 50)); $this->assertNull($validator->validateLength('fitting', 1, 50));
$this->assertNull($validator->validateMaxLength('fitting', 50)); $this->assertNull($validator->validateMaxLength('fitting', 50));
$this->assertNull($validator->validateMinLength('fitting', 1)); $this->assertNull($validator->validateMinLength('fitting', 1));
} }
public function testEmptyUserName() public function testEmptyUserName()
{ {
$this->configMock->set('users/minUserNameLength', 0); $this->configMock->set('users/minUserNameLength', 0);
$this->configMock->set('users/maxUserNameLength', 1); $this->configMock->set('users/maxUserNameLength', 1);
$this->setExpectedException(\Exception::class, 'User name cannot be empty'); $this->setExpectedException(\Exception::class, 'User name cannot be empty');
$userName = ''; $userName = '';
$validator = $this->getValidator(); $validator = $this->getValidator();
$validator->validateUserName($userName); $validator->validateUserName($userName);
} }
public function testTooShortUserName() public function testTooShortUserName()
{ {
$this->configMock->set('users/minUserNameLength', 30); $this->configMock->set('users/minUserNameLength', 30);
$this->configMock->set('users/maxUserNameLength', 50); $this->configMock->set('users/maxUserNameLength', 50);
$this->setExpectedException(\Exception::class, 'User name must have at least 30 character(s)'); $this->setExpectedException(\Exception::class, 'User name must have at least 30 character(s)');
$userName = 'godzilla'; $userName = 'godzilla';
$validator = $this->getValidator(); $validator = $this->getValidator();
$validator->validateUserName($userName); $validator->validateUserName($userName);
} }
public function testTooLongUserName() public function testTooLongUserName()
{ {
$this->configMock->set('users/minUserNameLength', 30); $this->configMock->set('users/minUserNameLength', 30);
$this->configMock->set('users/maxUserNameLength', 50); $this->configMock->set('users/maxUserNameLength', 50);
$this->setExpectedException(\Exception::class, 'User name must have at most 50 character(s)'); $this->setExpectedException(\Exception::class, 'User name must have at most 50 character(s)');
$userName = 'godzilla' . str_repeat('a', 50); $userName = 'godzilla' . str_repeat('a', 50);
$validator = $this->getValidator(); $validator = $this->getValidator();
$validator->validateUserName($userName); $validator->validateUserName($userName);
} }
public function testUserNameWithInvalidCharacters() public function testUserNameWithInvalidCharacters()
{ {
$this->configMock->set('users/minUserNameLength', 0); $this->configMock->set('users/minUserNameLength', 0);
$this->configMock->set('users/maxUserNameLength', 100); $this->configMock->set('users/maxUserNameLength', 100);
$userName = '..:xXx:godzilla:xXx:..'; $userName = '..:xXx:godzilla:xXx:..';
$this->setExpectedException(\Exception::class, 'User name may contain only'); $this->setExpectedException(\Exception::class, 'User name may contain only');
$validator = $this->getValidator(); $validator = $this->getValidator();
$validator->validateUserName($userName); $validator->validateUserName($userName);
} }
public function testEmailWithoutAt() public function testEmailWithoutAt()
{ {
$validator = $this->getValidator(); $validator = $this->getValidator();
$this->setExpectedException(\DomainException::class); $this->setExpectedException(\DomainException::class);
$validator->validateEmail('ghost'); $validator->validateEmail('ghost');
} }
public function testEmailWithoutDotInDomain() public function testEmailWithoutDotInDomain()
{ {
$validator = $this->getValidator(); $validator = $this->getValidator();
$this->setExpectedException(\DomainException::class); $this->setExpectedException(\DomainException::class);
$validator->validateEmail('ghost@cemetery'); $validator->validateEmail('ghost@cemetery');
} }
public function testValidEmail() public function testValidEmail()
{ {
$validator = $this->getValidator(); $validator = $this->getValidator();
$this->assertNull($validator->validateEmail('ghost@cemetery.consulting')); $this->assertNull($validator->validateEmail('ghost@cemetery.consulting'));
} }
public function testEmptyPassword() public function testEmptyPassword()
{ {
$this->configMock->set('security/minPasswordLength', 0); $this->configMock->set('security/minPasswordLength', 0);
$this->setExpectedException(\Exception::class, 'Password cannot be empty'); $this->setExpectedException(\Exception::class, 'Password cannot be empty');
$validator = $this->getValidator(); $validator = $this->getValidator();
$validator->validatePassword(''); $validator->validatePassword('');
} }
public function testTooShortPassword() public function testTooShortPassword()
{ {
$this->configMock->set('security/minPasswordLength', 10000); $this->configMock->set('security/minPasswordLength', 10000);
$this->setExpectedException(\Exception::class, 'Password must have at least 10000 character(s)'); $this->setExpectedException(\Exception::class, 'Password must have at least 10000 character(s)');
$validator = $this->getValidator(); $validator = $this->getValidator();
$validator->validatePassword('password123'); $validator->validatePassword('password123');
} }
public function testNonAsciiPassword() public function testNonAsciiPassword()
{ {
$this->configMock->set('security/minPasswordLength', 0); $this->configMock->set('security/minPasswordLength', 0);
$this->setExpectedException(\Exception::class, 'Password may contain only'); $this->setExpectedException(\Exception::class, 'Password may contain only');
$validator = $this->getValidator(); $validator = $this->getValidator();
$validator->validatePassword('良いパスワード'); $validator->validatePassword('良いパスワード');
} }
public function testValidPassword() public function testValidPassword()
{ {
$this->configMock->set('security/minPasswordLength', 0); $this->configMock->set('security/minPasswordLength', 0);
$validator = $this->getValidator(); $validator = $this->getValidator();
$this->assertNull($validator->validatePassword('password')); $this->assertNull($validator->validatePassword('password'));
} }
public function testNoTags() public function testNoTags()
{ {
$this->setExpectedException(\Exception::class, 'Tags cannot be empty'); $this->setExpectedException(\Exception::class, 'Tags cannot be empty');
$validator = $this->getValidator(); $validator = $this->getValidator();
$validator->validatePostTags([]); $validator->validatePostTags([]);
} }
public function testEmptyTags() public function testEmptyTags()
{ {
$this->setExpectedException(\Exception::class, 'Tags cannot be empty'); $this->setExpectedException(\Exception::class, 'Tags cannot be empty');
$validator = $this->getValidator(); $validator = $this->getValidator();
$validator->validatePostTags(['good_tag', '']); $validator->validatePostTags(['good_tag', '']);
} }
public function testTagsWithInvalidCharacters() public function testTagsWithInvalidCharacters()
{ {
$this->setExpectedException(\Exception::class, 'Tags cannot contain any of following'); $this->setExpectedException(\Exception::class, 'Tags cannot contain any of following');
$validator = $this->getValidator(); $validator = $this->getValidator();
$validator->validatePostTags(['good_tag', 'bad' . chr(160) . 'tag']); $validator->validatePostTags(['good_tag', 'bad' . chr(160) . 'tag']);
} }
public function testValidTags() public function testValidTags()
{ {
$validator = $this->getValidator(); $validator = $this->getValidator();
$this->assertNull($validator->validatePostTags(['good_tag', 'good_tag2', 'góód_as_well', ':3'])); $this->assertNull($validator->validatePostTags(['good_tag', 'good_tag2', 'góód_as_well', ':3']));
} }
private function getValidator() private function getValidator()
{ {
return new \Szurubooru\Validator($this->configMock); return new \Szurubooru\Validator($this->configMock);
} }
} }