protected $connection;
protected $driver;
protected $emulate_prepares = false;
+ protected $pdo_emulate_prepares = false;
private $error = false;
private $errorno = 0;
private $affected_rows = 0;
use Friendica\App;
use Friendica\Core\Config;
use Friendica\DI;
+use Friendica\Network\HTTPException\InternalServerErrorException;
use Friendica\Render\FriendicaSmartyEngine;
use Friendica\Util\Profiler;
use Mockery\MockInterface;
* Mock the App
*
* @param vfsStreamDirectory $root The root directory
- * @param bool $raw If true, no config mocking will be done
+ * @param bool $raw If true, no config mocking will be done
+ *
+ * @throws InternalServerErrorException
*/
public function mockApp(vfsStreamDirectory $root, $raw = false)
{
/**
* Mocking DBA::fetchFirst()
*
- * @param string $arg The argument of fetchFirst
- * @param bool $return True, if the DB is connected, otherwise false
- * @param null|int $times How often the method will get used
+ * @param string $arg The argument of fetchFirst
+ * @param bool $return True, if the DB is connected, otherwise false
+ * @param null|int $times How often the method will get used
*/
- public function mockFetchFirst($arg, $return = true, $times = null)
+ public function mockFetchFirst(string $arg, bool $return = true, int $times = null)
{
$this->checkMock();
/**
* Mocking DBA::select()
*
- * @param string $tableName The name of the table
- * @param array $select The Select Array (Default is [])
- * @param array $where The Where Array (Default is [])
- * @param object $return The array to return (Default is [])
- * @param null|int $times How often the method will get used
+ * @param string $tableName The name of the table
+ * @param array $select The Select Array (Default is [])
+ * @param array $where The Where Array (Default is [])
+ * @param object $return The array to return (Default is [])
+ * @param null|int $times How often the method will get used
*/
- public function mockSelect($tableName, $select = [], $where = [], $return = null, $times = null)
+ public function mockSelect(string $tableName, array $select = [], array $where = [], $return = null, int $times = null)
{
$this->checkMock();
/**
* Mocking DBA::delete()
*
- * @param string $tableName The name of the table
- * @param array $where The Where Array (Default is [])
- * @param bool $return The array to return (Default is true)
- * @param null|int $times How often the method will get used
+ * @param string $tableName The name of the table
+ * @param array $where The Where Array (Default is [])
+ * @param bool $return The array to return (Default is true)
+ * @param null|int $times How often the method will get used
*/
- public function mockDBADelete($tableName, $where = [], $return = true, $times = null)
+ public function mockDBADelete(string $tableName, array $where = [], bool $return = true, int $times = null)
{
$this->checkMock();
/**
* Mocking DBA::update()
*
- * @param string $expTableName The name of the table
- * @param array $expFields The Fields Array
- * @param array $expCondition The Condition Array
- * @param array $expOld_fields The Old Fieldnames (Default is [])
- * @param bool $return true if the update was successful
- * @param null|int $times How often the method will get used
+ * @param string $expTableName The name of the table
+ * @param array $expFields The Fields Array
+ * @param array $expCondition The Condition Array
+ * @param array $expOld_fields The Old Fieldnames (Default is [])
+ * @param bool $return true if the update was successful
+ * @param null|int $times How often the method will get used
*/
- public function mockDBAUpdate($expTableName, $expFields, $expCondition, $expOld_fields = [], $return = true, $times = null)
+ public function mockDBAUpdate(string $expTableName, array $expFields, array $expCondition, array $expOld_fields = [], bool $return = true, int $times = null)
{
$this->checkMock();
/**
* Mocking DBA::insert()
*
- * @param string $expTableName The name of the table
- * @param array $expParam The Parameters Array
- * @param bool $expOnDuplUpdate Update on a duplicated entry
- * @param bool $return True if the insert was successful
- * @param null|int $times How often the method will get used
+ * @param string $expTableName The name of the table
+ * @param array $expParam The Parameters Array
+ * @param bool $expOnDuplUpdate Update on a duplicated entry
+ * @param bool $return True if the insert was successful
+ * @param null|int $times How often the method will get used
*/
- public function mockDBAInsert($expTableName, $expParam, $expOnDuplUpdate = false, $return = true, $times = null)
+ public function mockDBAInsert(string $expTableName, array $expParam, bool $expOnDuplUpdate = false, bool $return = true, int $times = null)
{
$this->checkMock();
/**
* Mocking DBA::selectFirst()
*
- * @param string $expTableName The name of the table
- * @param array $expSelect The Select Array (Default is [])
- * @param array $expWhere The Where Array (Default is [])
- * @param array $return The array to return (Default is [])
- * @param null|int $times How often the method will get used
+ * @param string $expTableName The name of the table
+ * @param array $expSelect The Select Array (Default is [])
+ * @param array $expWhere The Where Array (Default is [])
+ * @param array $return The array to return (Default is [])
+ * @param null|int $times How often the method will get used
*/
- public function mockSelectFirst($expTableName, $expSelect = [], $expWhere = [], $return = [], $times = null)
+ public function mockSelectFirst(string $expTableName, array $expSelect = [], array $expWhere = [], array $return = [], int $times = null)
{
$this->checkMock();
/**
* Mocking DBA::lock()
*
- * @param string $table The table to lock
- * @param bool $return True, if the lock is set successful
- * @param null|int $times How often the method will get used
+ * @param string $table The table to lock
+ * @param bool $return True, if the lock is set successful
+ * @param null|int $times How often the method will get used
*/
- public function mockDbaLock($table, $return = true, $times = null)
+ public function mockDbaLock(string $table, bool $return = true, int $times = null)
{
$this->checkMock();
* @param bool $return True, if the connect was successful, otherwise false
* @param null|int $times How often the method will get used
*/
- public function mockUpdate($args = [], $return = true, $times = null)
+ public function mockUpdate(array $args = [], bool $return = true, int $times = null)
{
if (!isset($this->dbStructure)) {
$this->dbStructure = \Mockery::mock('alias:' . DBStructure::class);
/**
* Mocking DBStructure::existsTable()
*
- * @param string $tableName The name of the table to check
- * @param bool $return True, if the connect was successful, otherwise false
- * @param null|int $times How often the method will get used
+ * @param string $tableName The name of the table to check
+ * @param bool $return True, if the connect was successful, otherwise false
+ * @param null|int $times How often the method will get used
*/
- public function mockExistsTable($tableName, $return = true, $times = null)
+ public function mockExistsTable(string $tableName, bool $return = true, int $times = null)
{
if (!isset($this->dbStructure)) {
$this->dbStructure = \Mockery::mock('alias:' . DBStructure::class);
/**
* @var array Database drivers that support SAVEPOINT * statements.
*/
- protected static $_supportedDrivers = array("pgsql", "mysql");
+ protected static $_supportedDrivers = ["pgsql", "mysql"];
/**
* @var int the current transaction depth
namespace Friendica\Test\Util\Database;
use Friendica\Database\Database;
+use Friendica\Database\DatabaseException;
use PDO;
use PDOException;
/**
* Does a commit
*
- * @return boolean Was the command executed successfully?
+ * @return bool Was the command executed successfully?
*/
public function commit()
{
* Either through explicit calling or through implicit using the Database
*
* @param array $server $_SERVER variables
+ *
+ * @throws \Exception
*/
public static function statConnect(array $server)
{
$db_data = $server['MYSQL_DATABASE'];
}
+ if (empty($db_host) || empty($db_user) || empty($db_data)) {
+ throw new DatabaseException('Either one of the following settings are missing: Host, User or Database', 999, 'CONNECT');
+ }
+
$port = 0;
$serveraddr = trim($db_host);
$serverdata = explode(':', $serveraddr);
}
$server = trim($server);
$user = trim($db_user);
- $pass = trim($db_pw);
+ $pass = trim($db_pw ?? '');
$db = trim($db_data);
if (!(strlen($server) && strlen($user))) {
+++ /dev/null
-<?php
-/**
- * @copyright Copyright (C) 2020, Friendica
- *
- * @license GNU AGPL version 3 or any later version
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <https://www.gnu.org/licenses/>.
- *
- */
-
-namespace Friendica\Test\Util;
-
-use Friendica\Core\Cache\Duration;
-
-trait DbaCacheMockTrait
-{
- /**
- * @var
- */
- protected $dba;
-
- public function __construct()
- {
- }
-
- protected function mockDelete($key, $return = true, $times = null)
- {
- $this->mockDBADelete('cache', ['k' => $key], $return, $times);
- }
-
- protected function mockGet($key, $return = null, $time = null, $times = null)
- {
- if ($time === null) {
- $time = time();
- }
-
- $value = @serialize($return);
-
- $this->mockSelectFirst('cache', ['v'], ['`k` = ? AND (`expires` >= ? OR `expires` = -1)', $key, $time], ['v' => $value], $times);
- $this->mockIsResult(['v' => $value], isset($return), $times);
- }
-
- protected function mockSet($key, $value, $ttl = Duration::FIVE_MINUTES, $time = null, $return = true, $times = null)
- {
- if ($time === null) {
- $time = time();
- }
-
- if ($ttl > 0) {
- $this->mockUtc('now + ' . $ttl . 'seconds', $time + $ttl, $times);
- $fields = [
- 'v' => serialize($value),
- 'expires' => $time + $ttl,
- 'updated' => $time
- ];
- } else {
- $fields = [
- 'v' => serialize($value),
- 'expires' => -1,
- 'updated' => $time
- ];
- }
-
- $this->mockDBAUpdate('cache', $fields, ['k' => $key], true, $return, $times);
- }
-
- protected function mockClear($outdated = true, $return = true, $times = null)
- {
- if ($outdated) {
- $this->mockDBADelete('cache', ['`expires` < NOW()'], $return, $times);
- } else {
- $this->mockDBADelete('cache', ['`k` IS NOT NULL '], $return, $times);
- }
- }
-
- protected function mockGetAllKeys($prefix = null, $return = [], $time = null, $times = null)
- {
- if ($time === null) {
- $time = time();
- }
-
- if (empty($prefix)) {
- $where = ['`expires` >= ?', $time];
- } else {
- $where = ['`expires` >= ? AND `k` LIKE CONCAT(?, \'%\')', $time, $prefix];
- }
-
- $this->mockSelect('cache', ['k'], $where, $return, $times);
- $this->mockFetchLoop($return, $times);
- $this->mockDbaClose(true, $times);
- }
-}
+++ /dev/null
-<?php
-/**
- * @copyright Copyright (C) 2020, Friendica
- *
- * @license GNU AGPL version 3 or any later version
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <https://www.gnu.org/licenses/>.
- *
- */
-
-namespace Friendica\Test\Util;
-
-use Friendica\Core\Cache\Duration;
-use Friendica\Core\Lock\DatabaseLock;
-
-trait DbaLockMockTrait
-{
- use DBAMockTrait;
- use DateTimeFormatMockTrait;
-
- /**
- * Mocking acquireLock with DBA-backend
- *
- * @param mixed $key The key to lock
- * @param int $ttl The TimeToLive
- *
- * @param bool $locked Was the lock already set?
- * @param null $pid The PID which was set
- * @param bool $rowExists True, if a row already exists in the lock table
- * @param null $time The current timestamp
- * @param null|int $times How often the method will get used
- *
- *@see DatabaseLock::acquire()
- *
- */
- public function mockAcquireLock($key, $ttl = Duration::FIVE_MINUTES, $locked = false, $pid = null, $rowExists = true, $time = null, $times = null)
- {
- if ($time === null) {
- $time = time();
- }
-
- if ($pid === null) {
- $pid = getmypid();
- }
-
- $this->mockDbaLock('locks', true, $times);
-
- $this->mockUtcNow($time, $times);
- $result = ['locked' => $locked, 'pid' => $pid];
- $this->mockSelectFirst('locks', ['locked', 'pid'], ['`name` = ? AND `expires` >= ?', $key, $time], $result, $times);
- $this->mockIsResult($result, $rowExists, $times);
-
- if ($rowExists) {
- if (!$locked ) {
- $this->mockUtc('now + ' . $ttl . 'seconds', $time, $times);
- $this->mockDBAUpdate('locks', ['locked' => true, 'pid' => $pid, 'expires' => $time], ['name' => $key], [], true, $times);
- }
- } else {
- $this->mockUtc('now + ' . $ttl . 'seconds', $time, $times);
- $this->mockDBAInsert('locks', ['name' => $key, 'locked' => true, 'pid' => $pid, 'expires' => $time], false, true, $times);
- }
-
- $this->mockDbaUnlock($times);
- }
-
- /**
- * Mocking isLocked with DBA-backend
- *
- * @param mixed $key The key of the lock
- * @param null|bool $return True, if the key is already locked
- * @param null $time The current timestamp
- * @param null|int $times How often the method will get used
- *
- *@see DatabaseLock::isLocked()
- *
- */
- public function mockIsLocked($key, $return = true, $time = null, $times = null)
- {
- if ($time === null) {
- $time = time();
- }
-
- $this->mockUtcNow($time, $times);
- $return = ((isset($return)) ? ['locked' => $return] : null);
- $this->mockSelectFirst('locks', ['locked'], ['`name` = ? AND `expires` >= ?', $key, $time], $return, $times);
- $this->mockIsResult($return, (isset($return) && $return), $times);
- }
-
- /**
- * Mocking releaseAll with DBA-backend
- *
- * @param null $pid The PID which was set
- * @param null|int $times How often the method will get used
- *
- *@see DatabaseLock::releaseAll()
- *
- */
- public function mockReleaseAll($pid = null, $times = null)
- {
- if ($pid === null) {
- $pid = getmypid();
- }
-
- $this->mockDBADelete('locks', ['pid' => $pid], true, $times);
- }
-
- /**
- * Mocking ReleaseLock with DBA-backend
- *
- * @param mixed $key The key to release
- * @param null|int $pid The PID which was set
- * @param null|int $times How often the method will get used
- *
- *@see DatabaseLock::release()
- *
- */
- public function mockReleaseLock($key, $pid = null, $times = null)
- {
- if ($pid === null) {
- $pid = getmypid();
- }
-
- $this->mockDBADelete('locks', ['name' => $key, 'pid' => $pid], true, $times);
- }
-}
{
public static $MAIL_DATA;
+ /**
+ * Wrapper around the mail() method (mainly used to overwrite for tests)
+ * @see mail()
+ *
+ * @param string $to Recipient of this mail
+ * @param string $subject Subject of this mail
+ * @param string $body Message body of this mail
+ * @param string $headers Headers of this mail
+ * @param string $parameters Additional (sendmail) parameters of this mail
+ *
+ * @return bool true if the mail was successfully accepted for delivery, false otherwise.
+ */
protected function mail(string $to, string $subject, string $body, string $headers, string $parameters)
{
self::$MAIL_DATA = [
/**
* Mocking a method 'Hook::call()' call
*
+ * @param string $name
+ * @param mixed $capture
*/
public function mockHookCallAll(string $name, &$capture)
{
*/
public static $cache = '';
+ /** @noinspection PhpMissingParentCallCommonInspection */
public function filter($in, $out, &$consumed, $closing)
{
while ($bucket = stream_bucket_make_writeable($in)) {
* @param string $return the return value of the mock (should be defined to have it later for followUp use)
* @param null|int $times How often the method will get used
*/
- public function mockGetMarkupTemplate($templateName, $return = '', $times = null)
+ public function mockGetMarkupTemplate(string $templateName, string $return = '', int $times = null)
{
if (!isset($this->rendererMock)) {
$this->rendererMock = \Mockery::mock('alias:' . Renderer::class);
/**
* Mocking the method 'Renderer::replaceMacros()'
*
- * @param string $template The template to use (normally, it is the mock result of 'mockGetMarkupTemplate()'
- * @param array|\Closure|null $args The arguments to pass to the macro
- * @param string $return the return value of the mock
- * @param null|int $times How often the method will get used
+ * @param string $template The template to use (normally, it is the mock result of 'mockGetMarkupTemplate()'
+ * @param array|\Closure|null $args The arguments to pass to the macro
+ * @param string $return the return value of the mock
+ * @param null|int $times How often the method will get used
*/
- public function mockReplaceMacros($template, $args = null, $return = '', $times = null)
+ public function mockReplaceMacros(string $template, $args = null, string $return = '', int $times = null)
{
if (!isset($this->rendererMock)) {
$this->rendererMock = \Mockery::mock('alias:' . Renderer::class);
/** @var int The last expire time set */
public static $_EXPIRE;
+ /**
+ * Send a cookie - protected, internal function for test-mocking possibility
+ * @see Cookie::setCookie()
+ *
+ * @link https://php.net/manual/en/function.setcookie.php
+ *
+ * @param string $name
+ * @param string $value [optional]
+ * @param int $expire [optional]
+ * @param bool $secure [optional]
+ *
+ * @noinspection PhpMissingParentCallCommonInspection
+ *
+ */
protected function setCookie(string $name, string $value = null, int $expire = null, bool $secure = null)
{
self::$_COOKIE[$name] = $value;
* Copying a config file from the file system to the Virtual File System
*
* @param string $filename The filename of the config file
- * @param bool $static True, if the folder `static` instead of `config` should be used
+ * @param bool $static True, if the folder `static` instead of `config` should be used
*/
- protected function setConfigFile($filename, bool $static = false)
+ protected function setConfigFile(string $filename, bool $static = false)
{
$file = dirname(__DIR__) . DIRECTORY_SEPARATOR .
'..' . DIRECTORY_SEPARATOR .
* Delets a config file from the Virtual File System
*
* @param string $filename The filename of the config file
- * @param bool $static True, if the folder `static` instead of `config` should be used
+ * @param bool $static True, if the folder `static` instead of `config` should be used
*/
- protected function delConfigFile($filename, bool $static = false)
+ protected function delConfigFile(string $filename, bool $static = false)
{
if ($this->root->hasChild(($static ? 'static' : 'config') . '/' . $filename)) {
$this->root->getChild(($static ? 'static' : 'config'))->removeChild($filename);
use PHPUnit\Framework\TestCase;
use Psr\Log\LoggerInterface;
-class dependencyCheck extends TestCase
+class DependencyCheckTest extends TestCase
{
use VFSTrait;
use Detection\MobileDetect;
use Friendica\App\Mode;
use Friendica\App\Module;
-use Friendica\Core\Config;
+use Friendica\Core\Config\Cache;
use Friendica\Database\Database;
use Friendica\Test\MockedTest;
use Friendica\Test\Util\DBAMockTrait;
use Friendica\Test\Util\VFSTrait;
use Friendica\Util\BasePath;
+use Mockery;
use Mockery\MockInterface;
class ModeTest extends MockedTest
private $databaseMock;
/**
- * @var \Friendica\Core\Config\Cache|MockInterface
+ * @var Cache|MockInterface
*/
private $configCacheMock;
- public function setUp()
+ protected function setUp()
{
parent::setUp();
$this->setUpVfsDir();
- $this->basePathMock = \Mockery::mock(BasePath::class);
- $this->databaseMock = \Mockery::mock(Database::class);
- $this->configCacheMock = \Mockery::mock(Config\Cache::class);
+ $this->basePathMock = Mockery::mock(BasePath::class);
+ $this->databaseMock = Mockery::mock(Database::class);
+ $this->configCacheMock = Mockery::mock(Cache::class);
}
public function testItEmpty()
{
$server = [];
$module = new Module(Module::DEFAULT, Module::DEFAULT_CLASS, [], false);
- $mobileDetect = \Mockery::mock(MobileDetect::class);
+ $mobileDetect = Mockery::mock(MobileDetect::class);
$mobileDetect->shouldReceive('isMobile')->andReturn(true);
$mobileDetect->shouldReceive('isTablet')->andReturn(true);
{
$server = [];
$module = new Module(Module::DEFAULT, Module::DEFAULT_CLASS, [], false);
- $mobileDetect = \Mockery::mock(MobileDetect::class);
+ $mobileDetect = Mockery::mock(MobileDetect::class);
$mobileDetect->shouldReceive('isMobile')->andReturn(false);
$mobileDetect->shouldReceive('isTablet')->andReturn(false);
use Friendica\Module\HTTPException\PageNotFound;
use Friendica\Module\WellKnown\HostMeta;
use Friendica\Test\DatabaseTest;
+use Mockery;
class ModuleTest extends DatabaseTest
{
*/
public function testModuleClass($assert, string $name, string $command, bool $privAdd)
{
- $config = \Mockery::mock(IConfig::class);
+ $config = Mockery::mock(IConfig::class);
$config->shouldReceive('get')->with('config', 'private_addons', false)->andReturn($privAdd)->atMost()->once();
- $l10n = \Mockery::mock(L10n::class);
+ $l10n = Mockery::mock(L10n::class);
$l10n->shouldReceive('t')->andReturnUsing(function ($args) { return $args; });
- $cache = \Mockery::mock(ICache::class);
+ $cache = Mockery::mock(ICache::class);
$cache->shouldReceive('get')->with('routerDispatchData')->andReturn('')->atMost()->once();
$cache->shouldReceive('get')->with('lastRoutesFileModifiedTime')->andReturn('')->atMost()->once();
$cache->shouldReceive('set')->withAnyArgs()->andReturn(false)->atMost()->twice();
use Friendica\Module;
use Friendica\Network\HTTPException\MethodNotAllowedException;
use Friendica\Network\HTTPException\NotFoundException;
+use Mockery;
use Mockery\MockInterface;
use PHPUnit\Framework\TestCase;
{
parent::setUp();
- $this->l10n = \Mockery::mock(L10n::class);
+ $this->l10n = Mockery::mock(L10n::class);
$this->l10n->shouldReceive('t')->andReturnUsing(function ($args) { return $args; });
- $this->cache = \Mockery::mock(ICache::class);
+ $this->cache = Mockery::mock(ICache::class);
$this->cache->shouldReceive('get')->andReturn(null);
$this->cache->shouldReceive('set')->andReturn(false);
}
use Friendica\Test\Util\RendererMockTrait;
use Friendica\Test\Util\VFSTrait;
use Friendica\Util\Logger\VoidLogger;
+use Mockery;
use Mockery\MockInterface;
use org\bovigo\vfs\vfsStream;
use org\bovigo\vfs\vfsStreamFile;
public function setUp()
{
- $this->markTestSkipped('Needs class \'Installer\' as constructing argument for console tests');
+ static::markTestSkipped('Needs class \'Installer\' as constructing argument for console tests');
parent::setUp();
$this->root->getChild('config')
->removeChild('local.config.php');
}
- $this->dice = \Mockery::mock(Dice::class)->makePartial();
+ $this->dice = Mockery::mock(Dice::class)->makePartial();
- $l10nMock = \Mockery::mock(L10n::class);
+ $l10nMock = Mockery::mock(L10n::class);
$l10nMock->shouldReceive('t')->andReturnUsing(function ($args) { return $args; });
$this->dice->shouldReceive('create')
$this->mockUpdate([$this->root->url(), false, true, true], null, 1);
$this->mockGetMarkupTemplate('local.config.tpl', 'testTemplate', 1);
- $this->mockReplaceMacros('testTemplate', \Mockery::any(), '', 1);
+ $this->mockReplaceMacros('testTemplate', Mockery::any(), '', 1);
$console = new AutomaticInstallation($this->consoleArgv);
$console->setOption('url', 'http://friendica.local');
$this->mockUpdate([$this->root->url(), false, true, true], null, 1);
$this->mockGetMarkupTemplate('local.config.tpl', 'testTemplate', 1);
- $this->mockReplaceMacros('testTemplate', \Mockery::any(), '', 1);
+ $this->mockReplaceMacros('testTemplate', Mockery::any(), '', 1);
self::assertTrue(putenv('MYSQL_HOST=' . $data['database']['hostname']));
self::assertTrue(putenv('MYSQL_PORT=' . $data['database']['port']));
$this->mockUpdate([$this->root->url(), false, true, true], null, 1);
$this->mockGetMarkupTemplate('local.config.tpl', 'testTemplate', 1);
- $this->mockReplaceMacros('testTemplate', \Mockery::any(), '', 1);
+ $this->mockReplaceMacros('testTemplate', Mockery::any(), '', 1);
self::assertTrue(putenv('MYSQL_HOST=' . $data['database']['hostname']));
self::assertTrue(putenv('MYSQL_PORT=' . $data['database']['port']));
$this->mockUpdate([$this->root->url(), false, true, true], null, 1);
$this->mockGetMarkupTemplate('local.config.tpl', 'testTemplate', 1);
- $this->mockReplaceMacros('testTemplate', \Mockery::any(), '', 1);
+ $this->mockReplaceMacros('testTemplate', Mockery::any(), '', 1);
$console = new AutomaticInstallation($this->consoleArgv);
$this->mockConnect(false, 1);
$this->mockGetMarkupTemplate('local.config.tpl', 'testTemplate', 1);
- $this->mockReplaceMacros('testTemplate', \Mockery::any(), '', 1);
+ $this->mockReplaceMacros('testTemplate', Mockery::any(), '', 1);
$console = new AutomaticInstallation($this->consoleArgv);
$console->setOption('url', 'http://friendica.local');
use Friendica\App\Mode;
use Friendica\Console\Config;
use Friendica\Core\Config\IConfig;
+use Mockery;
+use Mockery\LegacyMockInterface;
use Mockery\MockInterface;
class ConfigConsoleTest extends ConsoleTest
* @var App\Mode|MockInterface $appMode
*/
private $appMode;
- /** @var IConfig|\Mockery\LegacyMockInterface|MockInterface */
+ /** @var IConfig|LegacyMockInterface|MockInterface */
private $configMock;
protected function setUp()
{
parent::setUp();
- \Mockery::getConfiguration()->setConstantsMap([
+ Mockery::getConfiguration()->setConstantsMap([
Mode::class => [
- 'DBCONFIGAVAILABLE' => 0
- ]
+ 'DBCONFIGAVAILABLE' => 0,
+ ],
]);
- $this->appMode = \Mockery::mock(App\Mode::class);
+ $this->appMode = Mockery::mock(App\Mode::class);
$this->appMode->shouldReceive('has')
- ->andReturn(true);
+ ->andReturn(true);
- $this->configMock = \Mockery::mock(IConfig::class);
+ $this->configMock = Mockery::mock(IConfig::class);
}
- function testSetGetKeyValue()
+ public function testSetGetKeyValue()
{
$this->configMock
->shouldReceive('set')
self::assertEquals("config.test => \n", $txt);
}
- function testSetArrayValue() {
+ public function testSetArrayValue()
+ {
$testArray = [1, 2, 3];
$this->configMock
->shouldReceive('get')
self::assertEquals("[Error] config.test is an array and can't be set using this command.\n", $txt);
}
- function testTooManyArguments() {
+ public function testTooManyArguments()
+ {
$console = new Config($this->appMode, $this->configMock, $this->consoleArgv);
$console->setArgument(0, 'config');
$console->setArgument(1, 'test');
$console->setArgument(2, 'it');
$console->setArgument(3, 'now');
- $txt = $this->dumpExecute($console);
+ $txt = $this->dumpExecute($console);
$assertion = '[Warning] Too many arguments';
$firstline = substr($txt, 0, strlen($assertion));
self::assertEquals($assertion, $firstline);
}
- function testVerbose() {
+ public function testVerbose()
+ {
$this->configMock
->shouldReceive('get')
->with('test', 'it')
$console->setArgument(1, 'it');
$console->setOption('v', 1);
$executable = $this->consoleArgv[0];
- $assertion = <<<CONF
+ $assertion = <<<CONF
Executable: {$executable}
Class: Friendica\Console\Config
Arguments: array (
test.it => now
CONF;
- $txt = $this->dumpExecute($console);
+ $txt = $this->dumpExecute($console);
self::assertEquals($assertion, $txt);
}
- function testUnableToSet() {
+ public function testUnableToSet()
+ {
$this->configMock
->shouldReceive('set')
->with('test', 'it', 'now')
$this->configMock
->shouldReceive('get')
->with('test', 'it')
- ->andReturn(NULL)
+ ->andReturn(null)
->once();
$console = new Config($this->appMode, $this->configMock, [$this->consoleArgv]);
$console->setArgument(0, 'test');
*
* @return string the output of the execution
*/
- protected function dumpExecute($console)
+ protected function dumpExecute(Console $console)
{
Intercept::reset();
$console->execute();
use Friendica\App\Mode;
use Friendica\Console\Lock;
use Friendica\Core\Lock\ILock;
+use Mockery;
use Mockery\MockInterface;
class LockConsoleTest extends ConsoleTest
{
parent::setUp();
- \Mockery::getConfiguration()->setConstantsMap([
+ Mockery::getConfiguration()->setConstantsMap([
Mode::class => [
'DBCONFIGAVAILABLE' => 0
]
]);
- $this->appMode = \Mockery::mock(App\Mode::class);
+ $this->appMode = Mockery::mock(App\Mode::class);
$this->appMode->shouldReceive('has')
->andReturn(true);
- $this->lockMock = \Mockery::mock(ILock::class);
+ $this->lockMock = Mockery::mock(ILock::class);
}
public function testList()
use Friendica\Console\ServerBlock;
use Friendica\Core\Config\IConfig;
+use Mockery;
class ServerBlockConsoleTest extends ConsoleTest
{
'reason' => 'Illegal content',
]
];
+ /**
+ * @var IConfig|Mockery\LegacyMockInterface|Mockery\MockInterface
+ */
+ private $configMock;
protected function setUp()
{
parent::setUp();
- $this->configMock = \Mockery::mock(IConfig::class);
+ $this->configMock = Mockery::mock(IConfig::class);
}
/**
{
public function testDetermineCategoriesTerms()
{
- $this->markTestIncomplete('Test data needed.');
+ static::markTestIncomplete('Test data needed.');
}
}
namespace Friendica\Test\src\Content;
+use Friendica\Content\PageInfo;
+
/**
* Class PageInfoMock
*
* @method static string|null getRelevantUrlFromBody(string $body, $searchNakedUrls = false)
* @method static string stripTrailingUrlFromBody(string $body, string $url)
*/
-class PageInfoMock extends \Friendica\Content\PageInfo
+class PageInfoMock extends PageInfo
{
public static function __callStatic($name, $arguments)
{
namespace Friendica\Test\src\Content;
use Friendica\Content\Smilies;
+use Friendica\Network\HTTPException\InternalServerErrorException;
use Friendica\Test\MockedTest;
use Friendica\Test\Util\AppMockTrait;
use Friendica\Test\Util\VFSTrait;
/**
* Test replace smilies in different texts
+ *
* @dataProvider dataLinks
*
* @param string $text Test string
* @param array $smilies List of smilies to replace
* @param string $expected Expected result
- * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+ *
+ * @throws InternalServerErrorException
*/
- public function testReplaceFromArray($text, $smilies, $expected)
+ public function testReplaceFromArray(string $text, array $smilies, string $expected)
{
$output = Smilies::replaceFromArray($text, $smilies);
self::assertEquals($expected, $output);
use Friendica\App\BaseURL;
use Friendica\Content\Text\BBCode;
use Friendica\Core\L10n;
+use Friendica\Network\HTTPException\InternalServerErrorException;
use Friendica\Test\MockedTest;
use Friendica\Test\Util\AppMockTrait;
use Friendica\Test\Util\VFSTrait;
+use Mockery;
class BBCodeTest extends MockedTest
{
->with('system', 'big_emojis')
->andReturn(false);
- $l10nMock = \Mockery::mock(L10n::class);
+ $l10nMock = Mockery::mock(L10n::class);
$l10nMock->shouldReceive('t')->withAnyArgs()->andReturnUsing(function ($args) { return $args; });
$this->dice->shouldReceive('create')
->with(L10n::class)
->andReturn($l10nMock);
- $baseUrlMock = \Mockery::mock(BaseURL::class);
+ $baseUrlMock = Mockery::mock(BaseURL::class);
$baseUrlMock->shouldReceive('get')->withAnyArgs()->andReturn('friendica.local');
$this->dice->shouldReceive('create')
->with(BaseURL::class)
/**
* Test convert different links inside a text
+ *
* @dataProvider dataLinks
*
- * @param string $data The data to text
- * @param bool $assertHTML True, if the link is a HTML link (<a href...>...</a>)
- * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+ * @param string $data The data to text
+ * @param bool $assertHTML True, if the link is a HTML link (<a href...>...</a>)
+ *
+ * @throws InternalServerErrorException
*/
- public function testAutoLinking($data, $assertHTML)
+ public function testAutoLinking(string $data, bool $assertHTML)
{
$output = BBCode::convert($data);
$assert = '<a href="' . $data . '" target="_blank" rel="noopener noreferrer">' . $data . '</a>';
* @param bool $try_oembed Whether to convert multimedia BBCode tag
* @param int $simpleHtml BBCode::convert method $simple_html parameter value, optional.
* @param bool $forPlaintext BBCode::convert method $for_plaintext parameter value, optional.
- * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+ *
+ * @throws InternalServerErrorException
*/
- public function testConvert($expectedHtml, $text, $try_oembed = false, $simpleHtml = 0, $forPlaintext = false)
+ public function testConvert(string $expectedHtml, string $text, $try_oembed = false, int $simpleHtml = 0, bool $forPlaintext = false)
{
$actual = BBCode::convert($text, $try_oembed, $simpleHtml, $forPlaintext);
*
* @dataProvider dataBBCodesToMarkdown
*
- * @param string $expected Expected Markdown output
- * @param string $text BBCode text
+ * @param string $expected Expected Markdown output
+ * @param string $text BBCode text
* @param bool $for_diaspora
- * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+ *
+ * @throws InternalServerErrorException
*/
- public function testToMarkdown($expected, $text, $for_diaspora = false)
+ public function testToMarkdown(string $expected, string $text, $for_diaspora = false)
{
$actual = BBCode::toMarkdown($text, $for_diaspora);
namespace Friendica\Test\src\Content\Text;
+use Exception;
use Friendica\Content\Text\HTML;
+use Friendica\Network\HTTPException\InternalServerErrorException;
use Friendica\Test\MockedTest;
use Friendica\Test\Util\AppMockTrait;
use Friendica\Test\Util\VFSTrait;
*
* @param string $input The Markdown text to test
* @param string $expected The expected HTML output
- * @throws \Exception
+ *
+ * @throws Exception
*/
- public function testToPlaintext($input, $expected)
+ public function testToPlaintext(string $input, string $expected)
{
$output = HTML::toPlaintext($input, 0);
*
* @param string $expectedBBCode Expected BBCode output
* @param string $html HTML text
- * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+ *
+ * @throws InternalServerErrorException
*/
- public function testToBBCode($expectedBBCode, $html)
+ public function testToBBCode(string $expectedBBCode, string $html)
{
$actual = HTML::toBBCode($html);
namespace Friendica\Test\src\Content\Text;
-use Friendica\Content\Text\HTML;
+use Exception;
use Friendica\Content\Text\Markdown;
use Friendica\Test\MockedTest;
use Friendica\Test\Util\AppMockTrait;
/**
* Test convert different input Markdown text into HTML
+ *
* @dataProvider dataMarkdown
*
* @param string $input The Markdown text to test
* @param string $expected The expected HTML output
- * @throws \Exception
+ *
+ * @throws Exception
*/
- public function testConvert($input, $expected)
+ public function testConvert(string $input, string $expected)
{
$output = Markdown::convert($input);
*
* @param string $expectedBBCode Expected BBCode output
* @param string $html Markdown text
- * @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
- public function testToBBCode($expectedBBCode, $html)
+ public function testToBBCode(string $expectedBBCode, string $html)
{
$actual = Markdown::toBBCode($html);
protected function setUp()
{
if (!APCuCache::isAvailable()) {
- $this->markTestSkipped('APCu is not available');
+ static::markTestSkipped('APCu is not available');
}
parent::setUp();
return $this->cache;
}
- public function tearDown()
+ protected function tearDown()
{
$this->cache->clear(false);
parent::tearDown();
return $this->cache;
}
- public function tearDown()
+ protected function tearDown()
{
$this->cache->clear(false);
parent::tearDown();
namespace Friendica\Test\src\Core\Cache;
+use Friendica\Core\Cache\ICache;
+use Friendica\Core\Cache\IMemoryCache;
use Friendica\Test\MockedTest;
use Friendica\Util\PidFile;
protected $startTime = 1417011228;
/**
- * @var \Friendica\Core\Cache\ICache
+ * @var ICache
*/
protected $instance;
/**
- * @var \Friendica\Core\Cache\IMemoryCache
+ * @var IMemoryCache
*/
protected $cache;
* @param mixed $value1 a first
* @param mixed $value2 a second
*/
- function testSimple($value1, $value2)
+ public function testSimple($value1, $value2)
{
self::assertNull($this->instance->get('value1'));
* @param mixed $value3 a third
* @param mixed $value4 a fourth
*/
- function testClear($value1, $value2, $value3, $value4)
+ public function testClear($value1, $value2, $value3, $value4)
{
- $value = 'ipsum lorum';
$this->instance->set('1_value1', $value1);
$this->instance->set('1_value2', $value2);
$this->instance->set('2_value1', $value3);
/**
* @medium
*/
- function testTTL()
+ public function testTTL()
{
- $this->markTestSkipped('taking too much time without mocking');
+ static::markTestSkipped('taking too much time without mocking');
self::assertNull($this->instance->get('value1'));
/**
* @small
*
- * @param $data mixed the data to store in the cache
+ * @param mixed $data the data to store in the cache
*
* @dataProvider dataTypesInCache
*/
- function testDifferentTypesInCache($data)
+ public function testDifferentTypesInCache($data)
{
$this->instance->set('val', $data);
$received = $this->instance->get('val');
use Friendica\Test\Util\VFSTrait;
use Friendica\Util\ConfigFileLoader;
use Friendica\Util\Profiler;
+use Mockery;
use Psr\Log\NullLogger;
class DatabaseCacheTest extends CacheTest
protected function getInstance()
{
$logger = new NullLogger();
- $profiler = \Mockery::mock(Profiler::class);
+ $profiler = Mockery::mock(Profiler::class);
$profiler->shouldReceive('saveTimestamp')->withAnyArgs()->andReturn(true);
// load real config to avoid mocking every config-entry which is related to the Database class
return $this->cache;
}
- public function tearDown()
+ protected function tearDown()
{
$this->cache->clear(false);
parent::tearDown();
namespace Friendica\Test\src\Core\Cache;
+use Exception;
use Friendica\Core\Cache\MemcacheCache;
use Friendica\Core\Config\IConfig;
+use Mockery;
/**
* @requires extension memcache
{
protected function getInstance()
{
- $configMock = \Mockery::mock(IConfig::class);
+ $configMock = Mockery::mock(IConfig::class);
$host = $_SERVER['MEMCACHE_HOST'] ?? 'localhost';
$port = $_SERVER['MEMCACHE_PORT'] ?? '11211';
try {
$this->cache = new MemcacheCache($host, $configMock);
- } catch (\Exception $e) {
- $this->markTestSkipped('Memcache is not available');
+ } catch (Exception $e) {
+ static::markTestSkipped('Memcache is not available');
}
return $this->cache;
}
- public function tearDown()
+ protected function tearDown()
{
$this->cache->clear(false);
parent::tearDown();
*/
public function testGetAllKeys($value1, $value2, $value3)
{
- $this->markTestIncomplete('Race condition because of too fast getAllKeys() which uses a workaround');
+ static::markTestIncomplete('Race condition because of too fast getAllKeys() which uses a workaround');
}
}
namespace Friendica\Test\src\Core\Cache;
+use Exception;
use Friendica\Core\Cache\MemcachedCache;
use Friendica\Core\Config\IConfig;
+use Mockery;
use Psr\Log\NullLogger;
/**
{
protected function getInstance()
{
- $configMock = \Mockery::mock(IConfig::class);
+ $configMock = Mockery::mock(IConfig::class);
$host = $_SERVER['MEMCACHED_HOST'] ?? 'localhost';
$port = $_SERVER['MEMCACHED_PORT'] ?? '11211';
try {
$this->cache = new MemcachedCache($host, $configMock, $logger);
- } catch (\Exception $exception) {
- $this->markTestSkipped('Memcached is not available');
+ } catch (Exception $exception) {
+ static::markTestSkipped('Memcached is not available');
}
return $this->cache;
}
- public function tearDown()
+ protected function tearDown()
{
$this->cache->clear(false);
parent::tearDown();
*/
public function testGetAllKeys($value1, $value2, $value3)
{
- $this->markTestIncomplete('Race condition because of too fast getAllKeys() which uses a workaround');
+ static::markTestIncomplete('Race condition because of too fast getAllKeys() which uses a workaround');
}
}
namespace Friendica\Test\src\Core\Cache;
+use Exception;
use Friendica\Core\Cache\IMemoryCache;
abstract class MemoryCacheTest extends CacheTest
{
/**
- * @var \Friendica\Core\Cache\IMemoryCache
+ * @var IMemoryCache
*/
protected $instance;
parent::setUp();
if (!($this->instance instanceof IMemoryCache)) {
- throw new \Exception('MemoryCacheTest unsupported');
+ throw new Exception('MemoryCacheTest unsupported');
}
}
* @small
* @dataProvider dataSimple
*/
- function testCompareSet($value1, $value2)
+ public function testCompareSet($value1, $value2)
{
self::assertNull($this->instance->get('value1'));
* @small
* @dataProvider dataSimple
*/
- function testNegativeCompareSet($value1, $value2)
+ public function testNegativeCompareSet($value1, $value2)
{
self::assertNull($this->instance->get('value1'));
* @small
* @dataProvider dataSimple
*/
- function testCompareDelete($data)
+ public function testCompareDelete($data)
{
self::assertNull($this->instance->get('value1'));
* @small
* @dataProvider dataSimple
*/
- function testNegativeCompareDelete($data)
+ public function testNegativeCompareDelete($data)
{
self::assertNull($this->instance->get('value1'));
* @small
* @dataProvider dataSimple
*/
- function testAdd($value1, $value2)
+ public function testAdd($value1, $value2)
{
self::assertNull($this->instance->get('value1'));
namespace Friendica\Test\src\Core\Cache;
+use Exception;
use Friendica\Core\Cache\RedisCache;
use Friendica\Core\Config\IConfig;
+use Mockery;
/**
* @requires extension redis
{
protected function getInstance()
{
- $configMock = \Mockery::mock(IConfig::class);
+ $configMock = Mockery::mock(IConfig::class);
$host = $_SERVER['REDIS_HOST'] ?? 'localhost';
$port = $_SERVER['REDIS_PORT'] ?? null;
try {
$this->cache = new RedisCache($host, $configMock);
- } catch (\Exception $e) {
- $this->markTestSkipped('Redis is not available.');
+ } catch (Exception $e) {
+ static::markTestSkipped('Redis is not available.');
}
return $this->cache;
}
- public function tearDown()
+ protected function tearDown()
{
$this->cache->clear(false);
parent::tearDown();
use Friendica\Core\Config\Cache;
use Friendica\Test\MockedTest;
use ParagonIE\HiddenString\HiddenString;
+use stdClass;
class CacheTest extends MockedTest
{
{
$configCache = new Cache([
'database' => [
- 'password' => new \stdClass(),
+ 'password' => new stdClass(),
'username' => '',
]
]);
/**
* @return IConfig
*/
- public abstract function getInstance();
+ abstract public function getInstance();
public function dataTests()
{
/**
* Test the configuration load() method
+ *
+ * @param array $data
+ * @param array $load
*/
- public function testLoad(array $data, array $possibleCats, array $load)
+ public function testLoad(array $data, array $load)
{
$this->testedConfig = $this->getInstance();
self::assertInstanceOf(Cache::class, $this->testedConfig->getCache());
/**
* Test the configuration load() method with overwrite
*/
- public function testCacheLoadDouble(array $data1, array $data2, array $expect)
+ public function testCacheLoadDouble(array $data1, array $data2, array $expect = [])
{
$this->testedConfig = $this->getInstance();
self::assertInstanceOf(Cache::class, $this->testedConfig->getCache());
/**
* @dataProvider dataConfigLoad
+ *
+ * @param array $data
+ * @param array $load
*/
- public function testLoad(array $data, array $possibleCats, array $load)
+ public function testLoad(array $data, array $load)
{
$this->configModel->shouldReceive('isConnected')
->andReturn(true)
->once();
}
- parent::testLoad($data, $possibleCats, $load);
+ parent::testLoad($data, $load);
}
/**
* @dataProvider dataDoubleLoad
*/
- public function testCacheLoadDouble(array $data1, array $data2, array $expect)
+ public function testCacheLoadDouble(array $data1, array $data2, array $expect = [])
{
$this->configModel->shouldReceive('isConnected')
->andReturn(true)
->once();
}
- parent::testCacheLoadDouble($data1, $data2, $expect);
+ parent::testCacheLoadDouble($data1, $data2);
// Assert the expected categories
foreach ($data2 as $cat => $data) {
/**
* @dataProvider dataConfigLoad
+ *
+ * @param array $data
+ * @param array $load
*/
- public function testLoad(array $data, array $possibleCats, array $load)
+ public function testLoad(array $data, array $load)
{
$this->configModel->shouldReceive('isConnected')
->andReturn(true)
->andReturn($data)
->once();
- parent::testLoad($data, $possibleCats, $load);
+ parent::testLoad($data, $load);
// Assert that every category is loaded everytime
foreach ($data as $cat => $values) {
/**
* @dataProvider dataDoubleLoad
+ *
+ * @param array $data1
+ * @param array $data2
*/
- public function testCacheLoadDouble(array $data1, array $data2, array $expect)
+ public function testCacheLoadDouble(array $data1, array $data2, array $expect = [])
{
$this->configModel->shouldReceive('isConnected')
->andReturn(true)
->andReturn($data1)
->once();
- parent::testCacheLoadDouble($data1, $data2, $expect);
+ parent::testCacheLoadDouble($data1, $data2);
// Assert that every category is loaded everytime and is NOT overwritten
foreach ($data1 as $cat => $values) {
*
*/
-// this is in the same namespace as Install for mocking 'function_exists'
+/// @todo this is in the same namespace as Install for mocking 'function_exists'
namespace Friendica\Core;
use Dice\Dice;
use Friendica\Network\IHTTPRequest;
use Friendica\Test\MockedTest;
use Friendica\Test\Util\VFSTrait;
+use Mockery;
use Mockery\MockInterface;
class InstallerTest extends MockedTest
use VFSTrait;
/**
- * @var \Friendica\Core\L10n|MockInterface
+ * @var L10n|MockInterface
*/
private $l10nMock;
/**
*/
private $dice;
- public function setUp()
+ protected function setUp()
{
parent::setUp();
$this->setUpVfsDir();
- $this->l10nMock = \Mockery::mock(\Friendica\Core\L10n::class);
+ $this->l10nMock = Mockery::mock(L10n::class);
/** @var Dice|MockInterface $dice */
- $this->dice = \Mockery::mock(Dice::class)->makePartial();
+ $this->dice = Mockery::mock(Dice::class)->makePartial();
$this->dice = $this->dice->addRules(include __DIR__ . '/../../../static/dependencies.config.php');
$this->dice->shouldReceive('create')
- ->with(\Friendica\Core\L10n::class)
+ ->with(L10n::class)
->andReturn($this->l10nMock);
DI::init($this->dice);
*
* @param array $functions a list from function names and their result
*/
- private function setFunctions($functions)
+ private function setFunctions(array $functions)
{
global $phpMock;
$phpMock['function_exists'] = function($function) use ($functions) {
*
* @param array $classes a list from class names and their results
*/
- private function setClasses($classes)
+ private function setClasses(array $classes)
{
global $phpMock;
$phpMock['class_exists'] = function($class) use ($classes) {
$this->l10nMock->shouldReceive('t')->andReturnUsing(function ($args) { return $args; });
// Mocking the CURL Response
- $curlResult = \Mockery::mock(CurlResult::class);
+ $curlResult = Mockery::mock(CurlResult::class);
$curlResult
->shouldReceive('getReturnCode')
->andReturn('404');
->andReturn('test Error');
// Mocking the CURL Request
- $networkMock = \Mockery::mock(IHTTPRequest::class);
+ $networkMock = Mockery::mock(IHTTPRequest::class);
$networkMock
->shouldReceive('fetchFull')
->with('https://test/install/testrewrite')
$this->l10nMock->shouldReceive('t')->andReturnUsing(function ($args) { return $args; });
// Mocking the failed CURL Response
- $curlResultF = \Mockery::mock(CurlResult::class);
+ $curlResultF = Mockery::mock(CurlResult::class);
$curlResultF
->shouldReceive('getReturnCode')
->andReturn('404');
// Mocking the working CURL Response
- $curlResultW = \Mockery::mock(CurlResult::class);
+ $curlResultW = Mockery::mock(CurlResult::class);
$curlResultW
->shouldReceive('getReturnCode')
->andReturn('204');
// Mocking the CURL Request
- $networkMock = \Mockery::mock(IHTTPRequest::class);
+ $networkMock = Mockery::mock(IHTTPRequest::class);
$networkMock
->shouldReceive('fetchFull')
->with('https://test/install/testrewrite')
*/
public function testImagick()
{
- $this->markTestIncomplete('needs adapted class_exists() mock');
+ static::markTestIncomplete('needs adapted class_exists() mock');
$this->l10nMock->shouldReceive('t')->andReturnUsing(function ($args) { return $args; });
*/
public function testImagickNotFound()
{
- $this->markTestIncomplete('Disabled due not working/difficult mocking global functions - needs more care!');
+ static::markTestIncomplete('Disabled due not working/difficult mocking global functions - needs more care!');
$this->l10nMock->shouldReceive('t')->andReturnUsing(function ($args) { return $args; });
$this->l10nMock->shouldReceive('t')->andReturnUsing(function ($args) { return $args; });
$install = new Installer();
- $configCache = \Mockery::mock(Cache::class);
- $configCache->shouldReceive('set')->with('config', 'php_path', \Mockery::any())->once();
+ $configCache = Mockery::mock(Cache::class);
+ $configCache->shouldReceive('set')->with('config', 'php_path', Mockery::any())->once();
$configCache->shouldReceive('set')->with('system', 'basepath', '/test/')->once();
$install->setUpCache($configCache, '/test/');
*
* @return bool true or false
*/
-function function_exists($function_name)
+function function_exists(string $function_name)
{
global $phpMock;
if (isset($phpMock['function_exists'])) {
protected function setUp()
{
if (!APCuCache::isAvailable()) {
- $this->markTestSkipped('APCu is not available');
+ static::markTestSkipped('APCu is not available');
}
parent::setUp();
use Friendica\Test\Util\VFSTrait;
use Friendica\Util\ConfigFileLoader;
use Friendica\Util\Profiler;
+use Mockery;
use Psr\Log\NullLogger;
class DatabaseLockDriverTest extends LockTest
protected function getInstance()
{
$logger = new NullLogger();
- $profiler = \Mockery::mock(Profiler::class);
+ $profiler = Mockery::mock(Profiler::class);
$profiler->shouldReceive('saveTimestamp')->withAnyArgs()->andReturn(true);
// load real config to avoid mocking every config-entry which is related to the Database class
namespace Friendica\Test\src\Core\Lock;
+use Friendica\Core\Lock\ILock;
use Friendica\Test\MockedTest;
abstract class LockTest extends MockedTest
protected $startTime = 1417011228;
/**
- * @var \Friendica\Core\Lock\ILock
+ * @var ILock
*/
protected $instance;
/**
* @medium
*/
- function testLockTTL()
+ public function testLockTTL()
{
- $this->markTestSkipped('taking too much time without mocking');
+ static::markTestSkipped('taking too much time without mocking');
self::assertFalse($this->instance->isLocked('foo'));
self::assertFalse($this->instance->isLocked('bar'));
namespace Friendica\Test\src\Core\Lock;
+use Exception;
use Friendica\Core\Cache\MemcacheCache;
use Friendica\Core\Config\IConfig;
use Friendica\Core\Lock\CacheLock;
+use Mockery;
/**
* @requires extension Memcache
{
protected function getInstance()
{
- $configMock = \Mockery::mock(IConfig::class);
+ $configMock = Mockery::mock(IConfig::class);
$host = $_SERVER['MEMCACHE_HOST'] ?? 'localhost';
$port = $_SERVER['MEMCACHE_PORT'] ?? '11211';
try {
$cache = new MemcacheCache($host, $configMock);
$lock = new CacheLock($cache);
- } catch (\Exception $e) {
- $this->markTestSkipped('Memcache is not available');
+ } catch (Exception $e) {
+ static::markTestSkipped('Memcache is not available');
}
return $lock;
*/
public function testGetLocks()
{
- $this->markTestIncomplete('Race condition because of too fast getAllKeys() which uses a workaround');
+ static::markTestIncomplete('Race condition because of too fast getAllKeys() which uses a workaround');
}
/**
*/
public function testGetLocksWithPrefix()
{
- $this->markTestIncomplete('Race condition because of too fast getAllKeys() which uses a workaround');
+ static::markTestIncomplete('Race condition because of too fast getAllKeys() which uses a workaround');
}
}
namespace Friendica\Test\src\Core\Lock;
+use Exception;
use Friendica\Core\Cache\MemcachedCache;
use Friendica\Core\Config\IConfig;
use Friendica\Core\Lock\CacheLock;
+use Mockery;
use Psr\Log\NullLogger;
/**
{
protected function getInstance()
{
- $configMock = \Mockery::mock(IConfig::class);
+ $configMock = Mockery::mock(IConfig::class);
$host = $_SERVER['MEMCACHED_HOST'] ?? 'localhost';
$port = $_SERVER['MEMCACHED_PORT'] ?? '11211';
try {
$cache = new MemcachedCache($host, $configMock, $logger);
$lock = new CacheLock($cache);
- } catch (\Exception $e) {
- $this->markTestSkipped('Memcached is not available');
+ } catch (Exception $e) {
+ static::markTestSkipped('Memcached is not available');
}
return $lock;
public function testGetLocks()
{
- $this->markTestIncomplete('Race condition because of too fast getLocks() which uses a workaround');
+ static::markTestIncomplete('Race condition because of too fast getLocks() which uses a workaround');
}
public function testGetLocksWithPrefix()
{
- $this->markTestIncomplete('Race condition because of too fast getLocks() which uses a workaround');
+ static::markTestIncomplete('Race condition because of too fast getLocks() which uses a workaround');
}
}
namespace Friendica\Test\src\Core\Lock;
+use Exception;
use Friendica\Core\Cache\RedisCache;
use Friendica\Core\Config\IConfig;
use Friendica\Core\Lock\CacheLock;
+use Mockery;
/**
* @requires extension redis
{
protected function getInstance()
{
- $configMock = \Mockery::mock(IConfig::class);
+ $configMock = Mockery::mock(IConfig::class);
$host = $_SERVER['REDIS_HOST'] ?? 'localhost';
$port = $_SERVER['REDIS_PORT'] ?? null;
try {
$cache = new RedisCache($host, $configMock);
$lock = new CacheLock($cache);
- } catch (\Exception $e) {
- $this->markTestSkipped('Redis is not available');
+ } catch (Exception $e) {
+ static::markTestSkipped('Redis is not available');
}
return $lock;
use Friendica\Core\Config\JitConfig;
use Friendica\Core\Lock\SemaphoreLock;
use Friendica\DI;
+use Mockery;
use Mockery\MockInterface;
class SemaphoreLockTest extends LockTest
{
- public function setUp()
+ protected function setUp()
{
/** @var MockInterface|Dice $dice */
- $dice = \Mockery::mock(Dice::class)->makePartial();
+ $dice = Mockery::mock(Dice::class)->makePartial();
- $app = \Mockery::mock(App::class);
+ $app = Mockery::mock(App::class);
$app->shouldReceive('getHostname')->andReturn('friendica.local');
$dice->shouldReceive('create')->with(App::class)->andReturn($app);
- $configMock = \Mockery::mock(JitConfig::class);
+ $configMock = Mockery::mock(JitConfig::class);
$configMock
->shouldReceive('get')
->with('system', 'temppath')
return new SemaphoreLock();
}
- function testLockTTL()
+ public function testLockTTL()
{
// Semaphore doesn't work with TTL
return true;
* This test proves that semaphore locks cannot get released by other instances except themselves
*
* Check for Bug https://github.com/friendica/friendica/issues/7298#issuecomment-521996540
+ *
* @see https://github.com/friendica/friendica/issues/7298#issuecomment-521996540
*/
public function testMissingFileOverriding()
/**
* Test the keyDiff() method with result
- *
- * @dataProvider dataTests
*/
- public function testKeyDiffWithResult($data)
+ public function testKeyDiffWithResult()
{
$configCache = new Cache();
namespace Friendica\Test\src\Core\PConfig;
use Friendica\Core\PConfig\JitPConfig;
-use Friendica\Test\src\Core\PConfig\PConfigTest;
class JitPConfigTest extends PConfigTest
{
/**
* @return BasePConfig
*/
- public abstract function getInstance();
+ abstract public function getInstance();
public function dataTests()
{
/**
* Test the configuration initialization
- * @dataProvider dataConfigLoad
*/
- public function testSetUp(int $uid, array $data)
+ public function testSetUp()
{
$this->testedConfig = $this->getInstance();
self::assertInstanceOf(Cache::class, $this->testedConfig->getCache());
namespace Friendica\Test\src\Core\PConfig;
use Friendica\Core\PConfig\PreloadPConfig;
-use Friendica\Test\src\Core\PConfig\PConfigTest;
class PreloadPConfigTest extends PConfigTest
{
use Friendica\Model\Config\Config;
use Friendica\Model\Storage;
use Friendica\Core\Session;
+use Friendica\Model\Storage\StorageException;
use Friendica\Test\DatabaseTest;
use Friendica\Test\Util\Database\StaticDatabase;
use Friendica\Test\Util\VFSTrait;
use VFSTrait;
- public function setUp()
+ protected function setUp()
{
parent::setUp();
/**
* Test moving data to a WRONG storage
- *
- * @expectedException \Friendica\Model\Storage\StorageException
- * @expectedExceptionMessage Can't move to storage backend 'SystemResource'
*/
public function testMoveStorageWrong()
{
+ $this->expectExceptionMessage("Can't move to storage backend 'SystemResource'");
+ $this->expectException(StorageException::class);
+
$storageManager = new StorageManager($this->dba, $this->config, $this->logger, $this->l10n);
$storage = $storageManager->getByName(Storage\SystemResource::getName());
$storageManager->move($storage);
self::assertRegExp("/^" . $prefix . "[a-z0-9]{" . $length . "}?$/", $guid);
}
- function testGuidWithoutParameter()
+ public function testGuidWithoutParameter()
{
$this->useBaseUrl();
$guid = System::createGUID();
self::assertGuid($guid, 16);
}
- function testGuidWithSize32()
+ public function testGuidWithSize32()
{
$this->useBaseUrl();
$guid = System::createGUID(32);
self::assertGuid($guid, 32);
}
- function testGuidWithSize64()
+ public function testGuidWithSize64()
{
$this->useBaseUrl();
$guid = System::createGUID(64);
self::assertGuid($guid, 64);
}
- function testGuidWithPrefix()
+ public function testGuidWithPrefix()
{
$guid = System::createGUID(23, 'test');
self::assertGuid($guid, 23, 'test');
class DBATest extends DatabaseTest
{
- public function setUp()
+ protected function setUp()
{
parent::setUp();
* @small
*/
public function testChangePrimaryKey() {
- $this->markTestSkipped('rename primary key with autoincrement and foreign key support necessary first');
+ static::markTestSkipped('rename primary key with autoincrement and foreign key support necessary first');
$oldID = 'client_id';
$newID = 'pw';
$this->setUpVfsDir();
- $this->logger = new NullLogger();
+ $logger = new NullLogger();
$profiler = \Mockery::mock(Profiler::class);
$profiler->shouldReceive('saveTimestamp')->withAnyArgs()->andReturn(true);
$loader = new ConfigFileLoader($this->root->url());
$configCache = $configFactory->createCache($loader);
- $this->dba = new StaticDatabase($configCache, $profiler, $this->logger);
+ $this->dba = new StaticDatabase($configCache, $profiler, $logger);
}
public function testInsertDelete()
use Friendica\Core\L10n;
use Friendica\Model\Storage\Filesystem;
use Friendica\Model\Storage\IStorage;
+use Friendica\Model\Storage\StorageException;
use Friendica\Test\Util\VFSTrait;
use Friendica\Util\Profiler;
use Mockery\MockInterface;
use org\bovigo\vfs\vfsStream;
use Psr\Log\NullLogger;
-use function GuzzleHttp\Psr7\uri_for;
class FilesystemStorageTest extends StorageTest
{
/**
* Test the exception in case of missing directorsy permissions
- *
- * @expectedException \Friendica\Model\Storage\StorageException
- * @expectedExceptionMessageRegExp /Filesystem storage failed to create \".*\". Check you write permissions./
*/
public function testMissingDirPermissions()
{
+ $this->expectException(StorageException::class);
+ $this->expectExceptionMessageRegExp("/Filesystem storage failed to create \".*\". Check you write permissions./");
$this->root->getChild('storage')->chmod(000);
$instance = $this->getInstance();
/**
* Test the exception in case of missing file permissions
*
- * @expectedException \Friendica\Model\Storage\StorageException
- * @expectedExceptionMessageRegExp /Filesystem storage failed to save data to \".*\". Check your write permissions/
*/
public function testMissingFilePermissions()
{
- $this->markTestIncomplete("Cannot catch file_put_content() error due vfsStream failure");
+ static::markTestIncomplete("Cannot catch file_put_content() error due vfsStream failure");
+
+ $this->expectException(StorageException::class);
+ $this->expectExceptionMessageRegExp("/Filesystem storage failed to save data to \".*\". Check your write permissions/");
vfsStream::create(['storage' => ['f0' => ['c0' => ['k0i0' => '']]]], $this->root);
protected function tearDown()
{
StaticCookie::clearStatic();
+
+ parent::tearDown();
}
/**
namespace Friendica\Test\src\Module\Api\Twitter;
+use Friendica\Module\Api\Twitter\ContactEndpoint;
+
/**
* Class ContactEndpointMock
*
*
* @package Friendica\Test\Mock\Module\Api\Twitter
*/
-class ContactEndpointMock extends \Friendica\Module\Api\Twitter\ContactEndpoint
+class ContactEndpointMock extends ContactEndpoint
{
public static function __callStatic($name, $arguments)
{
use Friendica\Model\Contact;
use Friendica\Module\Api\Twitter\ContactEndpoint;
+use Friendica\Network\HTTPException\InternalServerErrorException;
use Friendica\Network\HTTPException\NotFoundException;
use Friendica\Object\Api\Twitter\User;
use Friendica\Test\FixtureTest;
* @depends testIds
*
* @throws NotFoundException
- * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+ * @throws InternalServerErrorException
* @throws \ImagickException
*/
public function testList()
namespace Friendica\Test\src\Util;
-use Error;
use Friendica\Model\Group;
use Friendica\Util\ACLFormatter;
use PHPUnit\Framework\TestCase;
/**
* Test the basepath determination with a complete wrong path
- * @expectedException \Exception
- * @expectedExceptionMessageRegExp /(.*) is not a valid basepath/
*/
public function testFailedBasePath()
{
+ $this->expectException(\Exception::class);
+ $this->expectExceptionMessageRegExp("/(.*) is not a valid basepath/");
+
$basepath = new BasePath('/now23452sgfgas', []);
$basepath->getPath();
}
self::assertFalse($baseUrl->save('test', 10, 'nope'));
// nothing should have changed because we never successfully saved anything
- self::assertEquals($baseUrl->getHostname(), 'friendica.local');
- self::assertEquals($baseUrl->getUrlPath(), 'new/test');
- self::assertEquals($baseUrl->getSSLPolicy(), BaseURL::DEFAULT_SSL_SCHEME);
- self::assertEquals($baseUrl->get(), 'http://friendica.local/new/test');
+ self::assertEquals('friendica.local', $baseUrl->getHostname());
+ self::assertEquals('new/test', $baseUrl->getUrlPath());
+ self::assertEquals(BaseURL::DEFAULT_SSL_SCHEME, $baseUrl->getSSLPolicy());
+ self::assertEquals('http://friendica.local/new/test', $baseUrl->get());
}
}
/**
* Test the loadConfigFiles() method with a wrong local.config.php
- * @expectedException \Exception
- * @expectedExceptionMessageRegExp /Error loading config file \w+/
+ *
*/
public function testLoadConfigWrong()
{
+ $this->expectExceptionMessageRegExp("/Error loading config file \w+/");
+ $this->expectException(\Exception::class);
$this->delConfigFile('local.config.php');
vfsStream::newFile('local.config.php')
*
* This is in the same namespace as Crypto for mocking 'rand' and 'random_init'
*/
+
+/// @todo Use right namespace - needs alternative way of mocking random_int()
namespace Friendica\Util;
use phpseclib\Crypt\RSA;
{
global $phpMock;
if (isset($phpMock['random_int'])) {
- $result = call_user_func_array($phpMock['random_int'], func_get_args());
- return $result;
+ return call_user_func_array($phpMock['random_int'], func_get_args());
}
}
/** @var BaseURL|MockInterface */
private $baseUrl;
- /** @var string */
- private $defaultHeaders;
-
protected function setUp()
{
parent::setUp();
$this->baseUrl = \Mockery::mock(BaseURL::class);
$this->baseUrl->shouldReceive('getHostname')->andReturn('friendica.local');
$this->baseUrl->shouldReceive('get')->andReturn('http://friendica.local');
-
- $this->defaultHeaders = [];
}
protected function tearDown()
use Friendica\App\BaseURL;
use Friendica\Core\Config\IConfig;
use Friendica\Core\L10n;
+use Friendica\Network\HTTPException\InternalServerErrorException;
use Friendica\Object\EMail\IEmail;
use Friendica\Test\MockedTest;
use Friendica\Test\Util\SampleMailBuilder;
/** @var string */
private $defaultHeaders;
- public function setUp()
+ protected function setUp()
{
parent::setUp();
*/
public function testBuilderWithNonRawEmail()
{
- $this->markTestIncomplete('Cannot easily mock Renderer and BBCode, so skipping tests wit them');
+ static::markTestIncomplete('Cannot easily mock Renderer and BBCode, so skipping tests wit them');
}
/**
/**
* Test if the builder throws an exception in case no recipient
*
- * @expectedException \Friendica\Network\HTTPException\InternalServerErrorException
- * @expectedExceptionMessage Recipient address is missing.
*/
public function testBuilderWithEmptyMail()
{
+ $this->expectException(InternalServerErrorException::class);
+ $this->expectExceptionMessage("Recipient address is missing.");
+
$builder = new SampleMailBuilder($this->l10n, $this->baseUrl, $this->config, new NullLogger());
$builder->build(true);
/**
* Test if the builder throws an exception in case no sender
- *
- * @expectedException \Friendica\Network\HTTPException\InternalServerErrorException
- * @expectedExceptionMessage Sender address or name is missing.
*/
public function testBuilderWithEmptySender()
{
+ $this->expectException(InternalServerErrorException::class);
+ $this->expectExceptionMessage("Sender address or name is missing.");
+
$builder = new SampleMailBuilder($this->l10n, $this->baseUrl, $this->config, new NullLogger());
$builder
/** @var BaseURL */
private $baseUrl;
- /** @var string[] */
- private $defaultHeaders;
-
- public function setUp()
+ protected function setUp()
{
parent::setUp();
$this->baseUrl = \Mockery::mock(BaseURL::class);
$this->baseUrl->shouldReceive('getHostname')->andReturn('friendica.local');
$this->baseUrl->shouldReceive('get')->andReturn('http://friendica.local');
-
- $this->defaultHeaders = [];
}
/**
{
use VFSTrait;
- /**
- * @var StreamLogger
- */
- private $logger;
-
/**
* @var vfsStreamFile
*/
$this->setUpVfsDir();
- $this->fileSystem = new Filesystem();
+ $this->fileSystem = new FileSystem();
}
/**
$this->logfile = vfsStream::newFile('friendica.log')
->at($this->root);
- $this->logger = new StreamLogger('test', $this->logfile->url(), $this->introspection, $this->fileSystem, $level);
+ $logger = new StreamLogger('test', $this->logfile->url(), $this->introspection, $this->fileSystem, $level);
- return $this->logger;
+ return $logger;
}
/**
/**
* Test when a file isn't set
- * @expectedException \LogicException
- * @expectedExceptionMessage Missing stream URL.
*/
public function testNoUrl()
{
+ $this->expectException(\LogicException::class);
+ $this->expectExceptionMessage("Missing stream URL.");
+
$logger = new StreamLogger('test', '', $this->introspection, $this->fileSystem);
$logger->emergency('not working');
/**
* Test when a file cannot be opened
- * @expectedException \UnexpectedValueException
- * @expectedExceptionMessageRegExp /The stream or file .* could not be opened: .* /
*/
public function testWrongUrl()
{
+ $this->expectException(\UnexpectedValueException::class);
+ $this->expectExceptionMessageRegExp("/The stream or file .* could not be opened: .* /");
+
$logfile = vfsStream::newFile('friendica.log')
->at($this->root)->chmod(0);
/**
* Test when the directory cannot get created
- * @expectedException \UnexpectedValueException
- * @expectedExceptionMessageRegExp /Directory .* cannot get created: .* /
*/
public function testWrongDir()
{
- $this->markTestIncomplete('We need a platform independent way to set directory to readonly');
+ $this->expectException(\UnexpectedValueException::class);
+ $this->expectExceptionMessageRegExp("/Directory .* cannot get created: .* /");
+
+ static::markTestIncomplete('We need a platform independent way to set directory to readonly');
$logger = new StreamLogger('test', '/$%/wrong/directory/file.txt', $this->introspection, $this->fileSystem);
/**
* Test when the minimum level is not valid
- * @expectedException \InvalidArgumentException
- * @expectedExceptionMessageRegExp /The level ".*" is not valid./
*/
public function testWrongMinimumLevel()
{
+ $this->expectException(\InvalidArgumentException::class);
+ $this->expectExceptionMessageRegExp("/The level \".*\" is not valid./");
+
$logger = new StreamLogger('test', 'file.text', $this->introspection, $this->fileSystem, 'NOPE');
}
/**
* Test when the minimum level is not valid
- * @expectedException \InvalidArgumentException
- * @expectedExceptionMessageRegExp /The level ".*" is not valid./
*/
public function testWrongLogLevel()
{
+ $this->expectException(\InvalidArgumentException::class);
+ $this->expectExceptionMessageRegExp("/The level \".*\" is not valid./");
+
$logfile = vfsStream::newFile('friendica.log')
->at($this->root);
/**
* Test when the file is null
- * @expectedException \InvalidArgumentException
- * @expectedExceptionMessage A stream must either be a resource or a string.
*/
public function testWrongFile()
{
+ $this->expectException(\InvalidArgumentException::class);
+ $this->expectExceptionMessage("A stream must either be a resource or a string.");
+
$logger = new StreamLogger('test', null, $this->introspection, $this->fileSystem);
}
*/
public function testRealPath()
{
- $this->markTestSkipped('vfsStream isn\'t compatible with chdir, so not testable.');
+ static::markTestSkipped('vfsStream isn\'t compatible with chdir, so not testable.');
$logfile = vfsStream::newFile('friendica.log')
->at($this->root);
/**
* Test when the minimum level is not valid
- * @expectedException \InvalidArgumentException
- * @expectedExceptionMessageRegExp /The level ".*" is not valid./
*/
public function testWrongMinimumLevel()
{
+ $this->expectException(\InvalidArgumentException::class);
+ $this->expectExceptionMessageRegExp("/The level \".*\" is not valid./");
+
$logger = new SyslogLoggerWrapper('test', $this->introspection, 'NOPE');
}
/**
* Test when the minimum level is not valid
- * @expectedException \InvalidArgumentException
- * @expectedExceptionMessageRegExp /The level ".*" is not valid./
*/
public function testWrongLogLevel()
{
+ $this->expectException(\InvalidArgumentException::class);
+ $this->expectExceptionMessageRegExp("/The level \".*\" is not valid./");
+
$logger = new SyslogLoggerWrapper('test', $this->introspection);
$logger->log('NOPE', 'a test');
/**
* Test when the logfacility is wrong (string)
- * @expectedException \UnexpectedValueException
- * @expectedExceptionMessageRegExp /Can\'t open syslog for ident ".*" and facility ".*": .* /
*/
public function testServerException()
{
+ $this->expectException(\UnexpectedValueException::class);
+ $this->expectExceptionMessageRegExp("/Can\'t open syslog for ident \".*\" and facility \".*\": .* /");
+
$logger = new SyslogLoggerWrapper('test', $this->introspection, LogLevel::DEBUG, null, 'a string');
$logger->emergency('not working');
}
/**
* {@inheritdoc}
+ * @noinspection PhpMissingParentCallCommonInspection
*/
protected function syslogWrapper($level, $entry)
{
/**
* Test the a id with length zero
- * @expectedException \Error
+ *
*/
public function testGetWorkerIdZero()
{
+ $this->expectException(\Error::class);
+
$logger = \Mockery::mock(LoggerInterface::class);
new WorkerLogger($logger, 'test', 0);
}
->andReturn(true)
->twice();
$profiler = new Profiler($configCache);
+
+ self::assertInstanceOf(Profiler::class, $profiler);
}
/**
* Test the Profiler reset
* @dataProvider dataPerformance
*/
- public function testReset($timestamp, $name, array $functions)
+ public function testReset($timestamp, $name)
{
$configCache = \Mockery::mock(Cache::class);
$configCache->shouldReceive('get')
* Tests if the string is a valid hexadecimal value
*
* @param string $input
- * @param bool $valid
+ * @param bool $valid
*
* @dataProvider dataIsHex
*/
- public function testIsHex($input, $valid)
+ public function testIsHex(string $input, bool $valid)
{
self::assertEquals($valid, Strings::isHex($input));
}
*/
class XmlTest extends TestCase
{
- /**
- * escape and unescape
- */
+ /**
+ * escape and unescape
+ */
public function testEscapeUnescape()
{
- $text="<tag>I want to break\n this!11!<?hard?></tag>";
- $xml=XML::escape($text);
- $retext=XML::unescape($text);
+ $text = "<tag>I want to break\n this!11!<?hard?></tag>";
+ $xml = XML::escape($text);
+ $retext = XML::unescape($text);
self::assertEquals($text, $retext);
- }
-
+ }
+
/**
* escape and put in a document
*/
public function testEscapeDocument()
{
- $tag="<tag>I want to break</tag>";
- $xml=XML::escape($tag);
- $text='<text>'.$xml.'</text>';
- $xml_parser=xml_parser_create();
+ $tag = "<tag>I want to break</tag>";
+ $xml = XML::escape($tag);
+ $text = '<text>' . $xml . '</text>';
+ $xml_parser = xml_parser_create();
//should be possible to parse it
- $values=array();
- $index=array();
+ $values = [];
+ $index = [];
self::assertEquals(1, xml_parse_into_struct($xml_parser, $text, $values, $index));
self::assertEquals(
- array('TEXT'=>array(0)),
+ ['TEXT' => [0]],
$index
);
self::assertEquals(
- array(array('tag'=>'TEXT', 'type'=>'complete', 'level'=>1, 'value'=>$tag)),
+ [['tag' => 'TEXT', 'type' => 'complete', 'level' => 1, 'value' => $tag]],
$values
);
xml_parser_free($xml_parser);