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 -->
<!-- **************** -->
<!-- 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) -->
<!-- sl = same line -->
<!-- nl = new line -->

View file

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

View file

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

View file

@ -39,7 +39,7 @@ class HttpHelper
$result = [];
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)))));
$result[$key] = $value;

View file

@ -33,7 +33,12 @@ abstract class AbstractSearchParserConfig
throw new NotSupportedException('Unknown order term: ' . $tokenValue
. '. 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)
@ -118,7 +123,7 @@ abstract class AbstractSearchParserConfig
protected function defineOrder($columnName, array $aliases)
{
$this->orderAliasMap []= [$aliases, $columnName];
$this->orderAliasMap[] = [$aliases, $columnName];
}
protected function defineBasicTokenParser($parser)
@ -135,7 +140,7 @@ abstract class AbstractSearchParserConfig
$item->columnName = $columnName;
$item->aliases = $aliases;
$item->flagsOrCallback = $flagsOrCallback;
$this->namedTokenParsers []= $item;
$this->namedTokenParsers[] = $item;
}
protected function defineSpecialTokenParser(
@ -145,7 +150,7 @@ abstract class AbstractSearchParserConfig
$item = new \StdClass;
$item->aliases = $aliases;
$item->callback = $callback;
$this->specialTokenParsers []= $item;
$this->specialTokenParsers[] = $item;
}
protected static function createRequirementValue(
@ -261,6 +266,11 @@ abstract class AbstractSearchParserConfig
throw new NotSupportedException(
'Unknown search key: ' . $key
. '. 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)
{
$orderDir = $orderDir == IFilter::ORDER_DESC
$orderDir = $orderDir === IFilter::ORDER_DESC
? IFilter::ORDER_ASC
: IFilter::ORDER_DESC;
}

View file

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

View file

@ -110,11 +110,11 @@ class ImageConverter
private function convertWithPrograms($programs, $targetPath)
{
$any_program_available = false;
$anyProgramAvailable = false;
foreach ($programs as $program => $args)
$any_program_available |= ProgramExecutor::isProgramAvailable($program);
if (!$any_program_available)
throw new \Exception('No converter available (tried ' . join(', ', array_keys($programs)) . ')');
$anyProgramAvailable |= ProgramExecutor::isProgramAvailable($program);
if (!$anyProgramAvailable)
throw new \Exception('No converter available (tried ' . implode(', ', array_keys($programs)) . ')');
$errors = [];
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)

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -5,57 +5,57 @@ use Szurubooru\Tests\AbstractTestCase;
final class FileDaoTest extends AbstractTestCase
{
public function testSaving()
{
$testDirectory = $this->createTestDirectory();
$fileDao = new FileDao($testDirectory);
$fileDao->save('dog.txt', 'awesome dog');
$expected = 'awesome dog';
$actual = file_get_contents($testDirectory . DIRECTORY_SEPARATOR . 'dog.txt');
$this->assertEquals($expected, $actual);
}
public function testSaving()
{
$testDirectory = $this->createTestDirectory();
$fileDao = new FileDao($testDirectory);
$fileDao->save('dog.txt', 'awesome dog');
$expected = 'awesome dog';
$actual = file_get_contents($testDirectory . DIRECTORY_SEPARATOR . 'dog.txt');
$this->assertEquals($expected, $actual);
}
public function testSavingSubfolders()
{
$testDirectory = $this->createTestDirectory();
$fileDao = new FileDao($testDirectory);
$fileDao->save('friends/dog.txt', 'hot dog');
$expected = 'hot dog';
$actual = file_get_contents($testDirectory . DIRECTORY_SEPARATOR . 'friends/dog.txt');
$this->assertEquals($expected, $actual);
}
public function testSavingSubfolders()
{
$testDirectory = $this->createTestDirectory();
$fileDao = new FileDao($testDirectory);
$fileDao->save('friends/dog.txt', 'hot dog');
$expected = 'hot dog';
$actual = file_get_contents($testDirectory . DIRECTORY_SEPARATOR . 'friends/dog.txt');
$this->assertEquals($expected, $actual);
}
public function testLoading()
{
$testDirectory = $this->createTestDirectory();
$fileDao = new FileDao($testDirectory);
$fileDao->save('dog.txt', 'awesome dog');
$this->assertEquals('awesome dog', $fileDao->load('dog.txt'));
}
public function testLoading()
{
$testDirectory = $this->createTestDirectory();
$fileDao = new FileDao($testDirectory);
$fileDao->save('dog.txt', 'awesome dog');
$this->assertEquals('awesome dog', $fileDao->load('dog.txt'));
}
public function testExists()
{
$testDirectory = $this->createTestDirectory();
$fileDao = new FileDao($testDirectory);
$fileDao->save('dog.txt', 'awesome dog');
$this->assertTrue($fileDao->exists('dog.txt'));
$this->assertFalse($fileDao->exists('fish.txt'));
}
public function testExists()
{
$testDirectory = $this->createTestDirectory();
$fileDao = new FileDao($testDirectory);
$fileDao->save('dog.txt', 'awesome dog');
$this->assertTrue($fileDao->exists('dog.txt'));
$this->assertFalse($fileDao->exists('fish.txt'));
}
public function testLoadingUnexisting()
{
$testDirectory = $this->createTestDirectory();
$fileDao = new FileDao($testDirectory);
$this->assertNull($fileDao->load('dog.txt'));
}
public function testLoadingUnexisting()
{
$testDirectory = $this->createTestDirectory();
$fileDao = new FileDao($testDirectory);
$this->assertNull($fileDao->load('dog.txt'));
}
public function testDeleting()
{
$testDirectory = $this->createTestDirectory();
$fileDao = new FileDao($testDirectory);
$fileDao->save('dog.txt', 'awesome dog');
$this->assertTrue(file_exists($testDirectory . DIRECTORY_SEPARATOR . 'dog.txt'));
$fileDao->delete('dog.txt');
$this->assertFalse(file_exists($testDirectory . DIRECTORY_SEPARATOR . 'dog.txt'));
}
public function testDeleting()
{
$testDirectory = $this->createTestDirectory();
$fileDao = new FileDao($testDirectory);
$fileDao->save('dog.txt', 'awesome dog');
$this->assertTrue(file_exists($testDirectory . DIRECTORY_SEPARATOR . 'dog.txt'));
$fileDao->delete('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
{
public function testSettingValues()
{
$expected = new GlobalParam();
$expected->setKey('key');
$expected->setValue('test');
public function testSettingValues()
{
$expected = new GlobalParam();
$expected->setKey('key');
$expected->setValue('test');
$globalParamDao = $this->getGlobalParamDao();
$globalParamDao->save($expected);
$globalParamDao = $this->getGlobalParamDao();
$globalParamDao->save($expected);
$actual = $globalParamDao->findByKey($expected->getKey());
$this->assertEntitiesEqual($actual, $expected);
}
$actual = $globalParamDao->findByKey($expected->getKey());
$this->assertEntitiesEqual($actual, $expected);
}
public function testInsertingSameKeyTwice()
{
$param1 = new GlobalParam();
$param1->setKey('key');
$param1->setValue('value1');
public function testInsertingSameKeyTwice()
{
$param1 = new GlobalParam();
$param1->setKey('key');
$param1->setValue('value1');
$param2 = new GlobalParam();
$param2->setKey('key');
$param2->setValue('value2');
$param2 = new GlobalParam();
$param2->setKey('key');
$param2->setValue('value2');
$globalParamDao = $this->getGlobalParamDao();
$globalParamDao->save($param1);
$globalParamDao->save($param2);
$globalParamDao = $this->getGlobalParamDao();
$globalParamDao->save($param1);
$globalParamDao->save($param2);
$this->assertEquals([$param2], array_values($globalParamDao->findAll()));
}
$this->assertEquals([$param2], array_values($globalParamDao->findAll()));
}
public function testUpdatingValues()
{
$expected = new GlobalParam();
$expected->setKey('key');
$expected->setValue('test');
public function testUpdatingValues()
{
$expected = new GlobalParam();
$expected->setKey('key');
$expected->setValue('test');
$globalParamDao = $this->getGlobalParamDao();
$globalParamDao->save($expected);
$globalParamDao = $this->getGlobalParamDao();
$globalParamDao->save($expected);
$expected->setKey('key2');
$expected->setValue('test2');
$globalParamDao->save($expected);
$expected->setKey('key2');
$expected->setValue('test2');
$globalParamDao->save($expected);
$actual = $globalParamDao->findByKey($expected->getKey());
$this->assertEntitiesEqual($actual, $expected);
}
$actual = $globalParamDao->findByKey($expected->getKey());
$this->assertEntitiesEqual($actual, $expected);
}
public function testRetrievingUnknownKeys()
{
$globalParamDao = $this->getGlobalParamDao();
$actual = $globalParamDao->findByKey('hey i dont exist');
$this->assertNull($actual);
}
public function testRetrievingUnknownKeys()
{
$globalParamDao = $this->getGlobalParamDao();
$actual = $globalParamDao->findByKey('hey i dont exist');
$this->assertNull($actual);
}
private function getGlobalParamDao()
{
return new GlobalParamDao($this->databaseConnection);
}
private function getGlobalParamDao()
{
return new GlobalParamDao($this->databaseConnection);
}
}

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -5,8 +5,8 @@ use Szurubooru\Tests\AbstractTestCase;
final class ProgramExecutorTest extends AbstractTestCase
{
public function testIsProgramAvailable()
{
$this->assertFalse(ProgramExecutor::isProgramAvailable('there_is_no_way_my_os_can_have_this_program'));
}
public function testIsProgramAvailable()
{
$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
{
public function testDefault()
{
$query = $this->getDeleteQuery();
$this->assertEquals('DELETE FROM test', $query->getQuery());
}
public function testDefault()
{
$query = $this->getDeleteQuery();
$this->assertEquals('DELETE FROM test', $query->getQuery());
}
public function testBasicWhere()
{
$query = $this->getDeleteQuery();
$query->where('column', 'value');
$this->assertRegExp('/^DELETE FROM test WHERE column = :[\w]*$/', $query->getQuery());
}
public function testBasicWhere()
{
$query = $this->getDeleteQuery();
$query->where('column', 'value');
$this->assertRegExp('/^DELETE FROM test WHERE column = :[\w]*$/', $query->getQuery());
}
private function getDeleteQuery()
{
$pdoMock = $this->mock(PDOEx::class);
return new DeleteQuery($pdoMock, 'test');
}
private function getDeleteQuery()
{
$pdoMock = $this->mock(PDOEx::class);
return new DeleteQuery($pdoMock, 'test');
}
}

View file

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

View file

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

View file

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

View file

@ -7,25 +7,25 @@ use Szurubooru\Tests\AbstractTestCase;
final class PrivilegeTest extends AbstractTestCase
{
public function testConstNaming()
{
$refl = new \ReflectionClass(Privilege::class);
foreach ($refl->getConstants() as $key => $value)
{
$value = strtoupper(ltrim(preg_replace('/[A-Z]/', '_\0', $value), '_'));
$this->assertEquals($key, $value);
}
}
public function testConstNaming()
{
$refl = new \ReflectionClass(Privilege::class);
foreach ($refl->getConstants() as $key => $value)
{
$value = strtoupper(ltrim(preg_replace('/[A-Z]/', '_\0', $value), '_'));
$this->assertEquals($key, $value);
}
}
public function testConfigSectionNaming()
{
$refl = new \ReflectionClass(Privilege::class);
$constants = array_values($refl->getConstants());
public function testConfigSectionNaming()
{
$refl = new \ReflectionClass(Privilege::class);
$constants = array_values($refl->getConstants());
$config = Injector::get(Config::class);
foreach ($config->security->privileges as $key => $value)
{
$this->assertTrue(in_array($key, $constants), "$key not in constants");
}
}
$config = Injector::get(Config::class);
foreach ($config->security->privileges as $key => $value)
{
$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
{
public function testFactory()
{
$routeRepository = Injector::get(RouteRepository::class);
$this->assertNotEmpty($routeRepository->getRoutes());
}
public function testFactory()
{
$routeRepository = Injector::get(RouteRepository::class);
$this->assertNotEmpty($routeRepository->getRoutes());
}
public function testRouteMethods()
{
$routeRepository = Injector::get(RouteRepository::class);
foreach ($routeRepository->getRoutes() as $route)
{
foreach ($route->getMethods() as $method)
{
$this->assertContains($method, ['GET', 'POST', 'PUT', 'DELETE']);
}
}
}
public function testRouteMethods()
{
$routeRepository = Injector::get(RouteRepository::class);
foreach ($routeRepository->getRoutes() as $route)
{
foreach ($route->getMethods() as $method)
{
$this->assertContains($method, ['GET', 'POST', 'PUT', 'DELETE']);
}
}
}
public function testRouteUrls()
{
$routeRepository = Injector::get(RouteRepository::class);
foreach ($routeRepository->getRoutes() as $route)
{
$this->assertEquals(0, strpos($route->getUrl(), '/api/'));
}
}
public function testRouteUrls()
{
$routeRepository = Injector::get(RouteRepository::class);
foreach ($routeRepository->getRoutes() as $route)
{
$this->assertEquals(0, strpos($route->getUrl(), '/api/'));
}
}
public function testRouteInjection()
{
$routerMock = $this->mock(Router::class);
$routeMock = $this->mock(AbstractRoute::class);
$routeMock->expects($this->once())->method('getMethods')->willReturn(['POST', 'GET']);
$routeMock->expects($this->atLeast(1))->method('getUrl')->willReturn('/test');
$routerMock->expects($this->once())->method('post')->with('/test', $this->anything());
$routerMock->expects($this->once())->method('get')->with('/test', $this->anything());
$routeRepository = new RouteRepository([$routeMock]);
$routeRepository->injectRoutes($routerMock);
}
public function testRouteInjection()
{
$routerMock = $this->mock(Router::class);
$routeMock = $this->mock(AbstractRoute::class);
$routeMock->expects($this->once())->method('getMethods')->willReturn(['POST', 'GET']);
$routeMock->expects($this->atLeast(1))->method('getUrl')->willReturn('/test');
$routerMock->expects($this->once())->method('post')->with('/test', $this->anything());
$routerMock->expects($this->once())->method('get')->with('/test', $this->anything());
$routeRepository = new RouteRepository([$routeMock]);
$routeRepository->injectRoutes($routerMock);
}
public function testRouteCallbackInjection()
{
$router = new Router();
$routeMock = $this->mock(AbstractRoute::class);
$routeMock->expects($this->once())->method('getMethods')->willReturn(['POST', 'GET']);
$routeMock->expects($this->atLeast(1))->method('getUrl')->willReturn('/test');
$routeMock->expects($this->atLeast(1))->method('work');
$routeRepository = new RouteRepository([$routeMock]);
$routeRepository->injectRoutes($router);
$router->handle('GET', '/test');
}
public function testRouteCallbackInjection()
{
$router = new Router();
$routeMock = $this->mock(AbstractRoute::class);
$routeMock->expects($this->once())->method('getMethods')->willReturn(['POST', 'GET']);
$routeMock->expects($this->atLeast(1))->method('getUrl')->willReturn('/test');
$routeMock->expects($this->atLeast(1))->method('work');
$routeRepository = new RouteRepository([$routeMock]);
$routeRepository->injectRoutes($router);
$router->handle('GET', '/test');
}
}

View file

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

View file

@ -7,76 +7,76 @@ use \Szurubooru\Tests\AbstractTestCase;
final class UserSearchParserTest extends AbstractTestCase
{
private $inputReader;
private $userSearchParser;
private $inputReader;
private $userSearchParser;
public function setUp()
{
parent::setUp();
$this->inputReader = new InputReader;
$this->userSearchParser = new UserSearchParser();
}
public function setUp()
{
parent::setUp();
$this->inputReader = new InputReader;
$this->userSearchParser = new UserSearchParser();
}
public function testDefaultOrder()
{
$filter = $this->userSearchParser->createFilterFromInputReader($this->inputReader);
$this->assertOrderEquals([UserFilter::ORDER_NAME => UserFilter::ORDER_ASC], $filter->getOrder());
}
public function testDefaultOrder()
{
$filter = $this->userSearchParser->createFilterFromInputReader($this->inputReader);
$this->assertOrderEquals([UserFilter::ORDER_NAME => UserFilter::ORDER_ASC], $filter->getOrder());
}
public function testInvalidOrder()
{
$this->inputReader->order = 'invalid,desc';
$this->setExpectedException(\Exception::class);
$filter = $this->userSearchParser->createFilterFromInputReader($this->inputReader);
}
public function testInvalidOrder()
{
$this->inputReader->order = 'invalid,desc';
$this->setExpectedException(\Exception::class);
$filter = $this->userSearchParser->createFilterFromInputReader($this->inputReader);
}
public function testInvalidOrderDirection()
{
$this->inputReader->order = 'name,invalid';
$this->setExpectedException(\Exception::class);
$filter = $this->userSearchParser->createFilterFromInputReader($this->inputReader);
}
public function testInvalidOrderDirection()
{
$this->inputReader->order = 'name,invalid';
$this->setExpectedException(\Exception::class);
$filter = $this->userSearchParser->createFilterFromInputReader($this->inputReader);
}
public function testParamOrder()
{
$this->inputReader->order = 'name,desc';
$filter = $this->userSearchParser->createFilterFromInputReader($this->inputReader);
$this->assertOrderEquals([UserFilter::ORDER_NAME => UserFilter::ORDER_DESC], $filter->getOrder());
}
public function testParamOrder()
{
$this->inputReader->order = 'name,desc';
$filter = $this->userSearchParser->createFilterFromInputReader($this->inputReader);
$this->assertOrderEquals([UserFilter::ORDER_NAME => UserFilter::ORDER_DESC], $filter->getOrder());
}
public function testTokenOverwriteDefaultOrder()
{
$this->inputReader->query = 'order:name,desc';
$filter = $this->userSearchParser->createFilterFromInputReader($this->inputReader);
$this->assertOrderEquals([UserFilter::ORDER_NAME => UserFilter::ORDER_DESC], $filter->getOrder());
}
public function testTokenOverwriteDefaultOrder()
{
$this->inputReader->query = 'order:name,desc';
$filter = $this->userSearchParser->createFilterFromInputReader($this->inputReader);
$this->assertOrderEquals([UserFilter::ORDER_NAME => UserFilter::ORDER_DESC], $filter->getOrder());
}
public function testTokenOrder()
{
$this->inputReader->query = 'order:registration_time,desc';
$filter = $this->userSearchParser->createFilterFromInputReader($this->inputReader);
$this->assertOrderEquals([
UserFilter::ORDER_REGISTRATION_TIME => UserFilter::ORDER_DESC,
UserFilter::ORDER_NAME => UserFilter::ORDER_ASC],
$filter->getOrder());
}
public function testTokenOrder()
{
$this->inputReader->query = 'order:registration_time,desc';
$filter = $this->userSearchParser->createFilterFromInputReader($this->inputReader);
$this->assertOrderEquals([
UserFilter::ORDER_REGISTRATION_TIME => UserFilter::ORDER_DESC,
UserFilter::ORDER_NAME => UserFilter::ORDER_ASC],
$filter->getOrder());
}
public function testParamAndTokenOrder()
{
$this->inputReader->order = 'name,desc';
$this->inputReader->query = 'order:registration_time,desc';
$filter = $this->userSearchParser->createFilterFromInputReader($this->inputReader);
$this->assertOrderEquals([
UserFilter::ORDER_REGISTRATION_TIME => UserFilter::ORDER_DESC,
UserFilter::ORDER_NAME => UserFilter::ORDER_DESC],
$filter->getOrder());
}
public function testParamAndTokenOrder()
{
$this->inputReader->order = 'name,desc';
$this->inputReader->query = 'order:registration_time,desc';
$filter = $this->userSearchParser->createFilterFromInputReader($this->inputReader);
$this->assertOrderEquals([
UserFilter::ORDER_REGISTRATION_TIME => UserFilter::ORDER_DESC,
UserFilter::ORDER_NAME => UserFilter::ORDER_DESC],
$filter->getOrder());
}
private function assertOrderEquals($expected, $actual)
{
$this->assertEquals($expected, $actual);
//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_keys($expected), array_keys($actual));
}
private function assertOrderEquals($expected, $actual)
{
$this->assertEquals($expected, $actual);
//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_keys($expected), array_keys($actual));
}
}

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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