Merge pull request #9436 from nupplaphil/task/test_notices

Fix notices/deprecation notes/wrong calls in "test" directory
This commit is contained in:
Hypolite Petovan 2020-10-19 07:26:16 -04:00 committed by GitHub
commit 5232a8583f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
95 changed files with 1622 additions and 1751 deletions

View file

@ -91,6 +91,7 @@ jobs:
MYSQL_PASSWORD: test MYSQL_PASSWORD: test
MYSQL_USER: test MYSQL_USER: test
REDIS_PORT: ${{ job.services.redis.ports[6379] }} REDIS_PORT: ${{ job.services.redis.ports[6379] }}
REDIS_HOST: 127.0.0.1
MEMCACHED_PORT: ${{ job.services.memcached.ports[11211] }} MEMCACHED_PORT: ${{ job.services.memcached.ports[11211] }}
MEMCACHE_PORT: ${{ job.services.memcached.ports[11211] }} MEMCACHE_PORT: ${{ job.services.memcached.ports[11211] }}

View file

@ -58,6 +58,7 @@ class Database
protected $connection; protected $connection;
protected $driver; protected $driver;
protected $emulate_prepares = false; protected $emulate_prepares = false;
protected $pdo_emulate_prepares = false;
private $error = false; private $error = false;
private $errorno = 0; private $errorno = 0;
private $affected_rows = 0; private $affected_rows = 0;

View file

@ -25,6 +25,7 @@ use Dice\Dice;
use Friendica\App; use Friendica\App;
use Friendica\Core\Config; use Friendica\Core\Config;
use Friendica\DI; use Friendica\DI;
use Friendica\Network\HTTPException\InternalServerErrorException;
use Friendica\Render\FriendicaSmartyEngine; use Friendica\Render\FriendicaSmartyEngine;
use Friendica\Util\Profiler; use Friendica\Util\Profiler;
use Mockery\MockInterface; use Mockery\MockInterface;
@ -64,7 +65,9 @@ trait AppMockTrait
* Mock the App * Mock the App
* *
* @param vfsStreamDirectory $root The root directory * @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) public function mockApp(vfsStreamDirectory $root, $raw = false)
{ {

View file

@ -81,11 +81,11 @@ trait DBAMockTrait
/** /**
* Mocking DBA::fetchFirst() * Mocking DBA::fetchFirst()
* *
* @param string $arg The argument of fetchFirst * @param string $arg The argument of fetchFirst
* @param bool $return True, if the DB is connected, otherwise false * @param bool $return True, if the DB is connected, otherwise false
* @param null|int $times How often the method will get used * @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(); $this->checkMock();
@ -139,13 +139,13 @@ trait DBAMockTrait
/** /**
* Mocking DBA::select() * Mocking DBA::select()
* *
* @param string $tableName The name of the table * @param string $tableName The name of the table
* @param array $select The Select Array (Default is []) * @param array $select The Select Array (Default is [])
* @param array $where The Where Array (Default is []) * @param array $where The Where Array (Default is [])
* @param object $return The array to return (Default is []) * @param object $return The array to return (Default is [])
* @param null|int $times How often the method will get used * @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(); $this->checkMock();
@ -159,12 +159,12 @@ trait DBAMockTrait
/** /**
* Mocking DBA::delete() * Mocking DBA::delete()
* *
* @param string $tableName The name of the table * @param string $tableName The name of the table
* @param array $where The Where Array (Default is []) * @param array $where The Where Array (Default is [])
* @param bool $return The array to return (Default is true) * @param bool $return The array to return (Default is true)
* @param null|int $times How often the method will get used * @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(); $this->checkMock();
@ -178,14 +178,14 @@ trait DBAMockTrait
/** /**
* Mocking DBA::update() * Mocking DBA::update()
* *
* @param string $expTableName The name of the table * @param string $expTableName The name of the table
* @param array $expFields The Fields Array * @param array $expFields The Fields Array
* @param array $expCondition The Condition Array * @param array $expCondition The Condition Array
* @param array $expOld_fields The Old Fieldnames (Default is []) * @param array $expOld_fields The Old Fieldnames (Default is [])
* @param bool $return true if the update was successful * @param bool $return true if the update was successful
* @param null|int $times How often the method will get used * @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(); $this->checkMock();
@ -207,13 +207,13 @@ trait DBAMockTrait
/** /**
* Mocking DBA::insert() * Mocking DBA::insert()
* *
* @param string $expTableName The name of the table * @param string $expTableName The name of the table
* @param array $expParam The Parameters Array * @param array $expParam The Parameters Array
* @param bool $expOnDuplUpdate Update on a duplicated entry * @param bool $expOnDuplUpdate Update on a duplicated entry
* @param bool $return True if the insert was successful * @param bool $return True if the insert was successful
* @param null|int $times How often the method will get used * @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(); $this->checkMock();
@ -234,13 +234,13 @@ trait DBAMockTrait
/** /**
* Mocking DBA::selectFirst() * Mocking DBA::selectFirst()
* *
* @param string $expTableName The name of the table * @param string $expTableName The name of the table
* @param array $expSelect The Select Array (Default is []) * @param array $expSelect The Select Array (Default is [])
* @param array $expWhere The Where Array (Default is []) * @param array $expWhere The Where Array (Default is [])
* @param array $return The array to return (Default is []) * @param array $return The array to return (Default is [])
* @param null|int $times How often the method will get used * @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(); $this->checkMock();
@ -321,11 +321,11 @@ trait DBAMockTrait
/** /**
* Mocking DBA::lock() * Mocking DBA::lock()
* *
* @param string $table The table to lock * @param string $table The table to lock
* @param bool $return True, if the lock is set successful * @param bool $return True, if the lock is set successful
* @param null|int $times How often the method will get used * @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(); $this->checkMock();

View file

@ -42,7 +42,7 @@ trait DBStructureMockTrait
* @param bool $return True, if the connect was successful, otherwise false * @param bool $return True, if the connect was successful, otherwise false
* @param null|int $times How often the method will get used * @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)) { if (!isset($this->dbStructure)) {
$this->dbStructure = \Mockery::mock('alias:' . DBStructure::class); $this->dbStructure = \Mockery::mock('alias:' . DBStructure::class);
@ -58,11 +58,11 @@ trait DBStructureMockTrait
/** /**
* Mocking DBStructure::existsTable() * Mocking DBStructure::existsTable()
* *
* @param string $tableName The name of the table to check * @param string $tableName The name of the table to check
* @param bool $return True, if the connect was successful, otherwise false * @param bool $return True, if the connect was successful, otherwise false
* @param null|int $times How often the method will get used * @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)) { if (!isset($this->dbStructure)) {
$this->dbStructure = \Mockery::mock('alias:' . DBStructure::class); $this->dbStructure = \Mockery::mock('alias:' . DBStructure::class);

View file

@ -33,7 +33,7 @@ class ExtendedPDO extends PDO
/** /**
* @var array Database drivers that support SAVEPOINT * statements. * @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 * @var int the current transaction depth

View file

@ -22,6 +22,7 @@
namespace Friendica\Test\Util\Database; namespace Friendica\Test\Util\Database;
use Friendica\Database\Database; use Friendica\Database\Database;
use Friendica\Database\DatabaseException;
use PDO; use PDO;
use PDOException; use PDOException;
@ -80,7 +81,7 @@ class StaticDatabase extends Database
/** /**
* Does a commit * Does a commit
* *
* @return boolean Was the command executed successfully? * @return bool Was the command executed successfully?
*/ */
public function commit() public function commit()
{ {
@ -96,6 +97,8 @@ class StaticDatabase extends Database
* Either through explicit calling or through implicit using the Database * Either through explicit calling or through implicit using the Database
* *
* @param array $server $_SERVER variables * @param array $server $_SERVER variables
*
* @throws \Exception
*/ */
public static function statConnect(array $server) public static function statConnect(array $server)
{ {
@ -119,6 +122,10 @@ class StaticDatabase extends Database
$db_data = $server['MYSQL_DATABASE']; $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; $port = 0;
$serveraddr = trim($db_host); $serveraddr = trim($db_host);
$serverdata = explode(':', $serveraddr); $serverdata = explode(':', $serveraddr);
@ -128,7 +135,7 @@ class StaticDatabase extends Database
} }
$server = trim($server); $server = trim($server);
$user = trim($db_user); $user = trim($db_user);
$pass = trim($db_pw); $pass = trim($db_pw ?? '');
$db = trim($db_data); $db = trim($db_data);
if (!(strlen($server) && strlen($user))) { if (!(strlen($server) && strlen($user))) {

View file

@ -1,103 +0,0 @@
<?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);
}
}

View file

@ -1,136 +0,0 @@
<?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);
}
}

View file

@ -8,6 +8,18 @@ class EmailerSpy extends Emailer
{ {
public static $MAIL_DATA; 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) protected function mail(string $to, string $subject, string $body, string $headers, string $parameters)
{ {
self::$MAIL_DATA = [ self::$MAIL_DATA = [

View file

@ -16,6 +16,8 @@ trait HookMockTrait
/** /**
* Mocking a method 'Hook::call()' call * Mocking a method 'Hook::call()' call
* *
* @param string $name
* @param mixed $capture
*/ */
public function mockHookCallAll(string $name, &$capture) public function mockHookCallAll(string $name, &$capture)
{ {

View file

@ -36,6 +36,7 @@ class Intercept extends php_user_filter
*/ */
public static $cache = ''; public static $cache = '';
/** @noinspection PhpMissingParentCallCommonInspection */
public function filter($in, $out, &$consumed, $closing) public function filter($in, $out, &$consumed, $closing)
{ {
while ($bucket = stream_bucket_make_writeable($in)) { while ($bucket = stream_bucket_make_writeable($in)) {

View file

@ -38,7 +38,7 @@ trait RendererMockTrait
* @param string $return the return value of the mock (should be defined to have it later for followUp use) * @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 * @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)) { if (!isset($this->rendererMock)) {
$this->rendererMock = \Mockery::mock('alias:' . Renderer::class); $this->rendererMock = \Mockery::mock('alias:' . Renderer::class);
@ -54,12 +54,12 @@ trait RendererMockTrait
/** /**
* Mocking the method 'Renderer::replaceMacros()' * Mocking the method 'Renderer::replaceMacros()'
* *
* @param string $template The template to use (normally, it is the mock result of 'mockGetMarkupTemplate()' * @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 array|\Closure|null $args The arguments to pass to the macro
* @param string $return the return value of the mock * @param string $return the return value of the mock
* @param null|int $times How often the method will get used * @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)) { if (!isset($this->rendererMock)) {
$this->rendererMock = \Mockery::mock('alias:' . Renderer::class); $this->rendererMock = \Mockery::mock('alias:' . Renderer::class);

View file

@ -33,6 +33,20 @@ class StaticCookie extends Cookie
/** @var int The last expire time set */ /** @var int The last expire time set */
public static $_EXPIRE; 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) protected function setCookie(string $name, string $value = null, int $expire = null, bool $secure = null)
{ {
self::$_COOKIE[$name] = $value; self::$_COOKIE[$name] = $value;

View file

@ -58,9 +58,9 @@ trait VFSTrait
* Copying a config file from the file system to the Virtual File System * Copying a config file from the file system to the Virtual File System
* *
* @param string $filename The filename of the config file * @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 . $file = dirname(__DIR__) . DIRECTORY_SEPARATOR .
'..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR .
@ -78,9 +78,9 @@ trait VFSTrait
* Delets a config file from the Virtual File System * Delets a config file from the Virtual File System
* *
* @param string $filename The filename of the config file * @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)) { if ($this->root->hasChild(($static ? 'static' : 'config') . '/' . $filename)) {
$this->root->getChild(($static ? 'static' : 'config'))->removeChild($filename); $this->root->getChild(($static ? 'static' : 'config'))->removeChild($filename);

View file

@ -19,7 +19,7 @@
* *
*/ */
namespace functional; namespace Friendica\Test\functional;
use Dice\Dice; use Dice\Dice;
use Friendica\App; use Friendica\App;
@ -36,7 +36,7 @@ use Friendica\Util\Profiler;
use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCase;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
class dependencyCheck extends TestCase class DependencyCheckTest extends TestCase
{ {
use VFSTrait; use VFSTrait;
@ -63,8 +63,8 @@ class dependencyCheck extends TestCase
/** @var BasePath $basePath */ /** @var BasePath $basePath */
$basePath = $this->dice->create(BasePath::class, [$this->root->url()]); $basePath = $this->dice->create(BasePath::class, [$this->root->url()]);
$this->assertInstanceOf(BasePath::class, $basePath); self::assertInstanceOf(BasePath::class, $basePath);
$this->assertEquals($this->root->url(), $basePath->getPath()); self::assertEquals($this->root->url(), $basePath->getPath());
} }
/** /**
@ -76,14 +76,14 @@ class dependencyCheck extends TestCase
/** @var ConfigFileLoader $configFileLoader */ /** @var ConfigFileLoader $configFileLoader */
$configFileLoader = $this->dice->create(ConfigFileLoader::class); $configFileLoader = $this->dice->create(ConfigFileLoader::class);
$this->assertInstanceOf(ConfigFileLoader::class, $configFileLoader); self::assertInstanceOf(ConfigFileLoader::class, $configFileLoader);
$configCache = new Cache(); $configCache = new Cache();
$configFileLoader->setupCache($configCache); $configFileLoader->setupCache($configCache);
$this->assertNotEmpty($configCache->getAll()); self::assertNotEmpty($configCache->getAll());
$this->assertArrayHasKey('database', $configCache->getAll()); self::assertArrayHasKey('database', $configCache->getAll());
$this->assertArrayHasKey('system', $configCache->getAll()); self::assertArrayHasKey('system', $configCache->getAll());
} }
/** /**
@ -94,7 +94,7 @@ class dependencyCheck extends TestCase
/** @var Profiler $profiler */ /** @var Profiler $profiler */
$profiler = $this->dice->create(Profiler::class); $profiler = $this->dice->create(Profiler::class);
$this->assertInstanceOf(Profiler::class, $profiler); self::assertInstanceOf(Profiler::class, $profiler);
$configCache = new Cache([ $configCache = new Cache([
'system' => [ 'system' => [
@ -109,8 +109,8 @@ class dependencyCheck extends TestCase
$this->dice = new Dice(); $this->dice = new Dice();
$profiler = $this->dice->create(Profiler::class, [$configCache]); $profiler = $this->dice->create(Profiler::class, [$configCache]);
$this->assertInstanceOf(Profiler::class, $profiler); self::assertInstanceOf(Profiler::class, $profiler);
$this->assertTrue($profiler->isRendertime()); self::assertTrue($profiler->isRendertime());
} }
public function testDatabase() public function testDatabase()
@ -118,8 +118,8 @@ class dependencyCheck extends TestCase
/** @var Database $database */ /** @var Database $database */
$database = $this->dice->create(Database::class); $database = $this->dice->create(Database::class);
$this->assertInstanceOf(Database::class, $database); self::assertInstanceOf(Database::class, $database);
$this->assertTrue($database->connected()); self::assertTrue($database->connected());
} }
public function testAppMode() public function testAppMode()
@ -127,9 +127,9 @@ class dependencyCheck extends TestCase
/** @var App\Mode $mode */ /** @var App\Mode $mode */
$mode = $this->dice->create(App\Mode::class); $mode = $this->dice->create(App\Mode::class);
$this->assertInstanceOf(App\Mode::class, $mode); self::assertInstanceOf(App\Mode::class, $mode);
$this->assertTrue($mode->isNormal()); self::assertTrue($mode->isNormal());
} }
public function testConfiguration() public function testConfiguration()
@ -137,9 +137,9 @@ class dependencyCheck extends TestCase
/** @var IConfig $config */ /** @var IConfig $config */
$config = $this->dice->create(IConfig::class); $config = $this->dice->create(IConfig::class);
$this->assertInstanceOf(IConfig::class, $config); self::assertInstanceOf(IConfig::class, $config);
$this->assertNotEmpty($config->get('database', 'username')); self::assertNotEmpty($config->get('database', 'username'));
} }
public function testLogger() public function testLogger()
@ -147,7 +147,7 @@ class dependencyCheck extends TestCase
/** @var LoggerInterface $logger */ /** @var LoggerInterface $logger */
$logger = $this->dice->create(LoggerInterface::class, ['test']); $logger = $this->dice->create(LoggerInterface::class, ['test']);
$this->assertInstanceOf(LoggerInterface::class, $logger); self::assertInstanceOf(LoggerInterface::class, $logger);
} }
public function testDevLogger() public function testDevLogger()
@ -159,7 +159,7 @@ class dependencyCheck extends TestCase
/** @var LoggerInterface $logger */ /** @var LoggerInterface $logger */
$logger = $this->dice->create('$devLogger', ['dev']); $logger = $this->dice->create('$devLogger', ['dev']);
$this->assertInstanceOf(LoggerInterface::class, $logger); self::assertInstanceOf(LoggerInterface::class, $logger);
} }
public function testCache() public function testCache()
@ -167,7 +167,7 @@ class dependencyCheck extends TestCase
/** @var ICache $cache */ /** @var ICache $cache */
$cache = $this->dice->create(ICache::class); $cache = $this->dice->create(ICache::class);
$this->assertInstanceOf(ICache::class, $cache); self::assertInstanceOf(ICache::class, $cache);
} }
public function testMemoryCache() public function testMemoryCache()
@ -176,7 +176,7 @@ class dependencyCheck extends TestCase
$cache = $this->dice->create(IMemoryCache::class); $cache = $this->dice->create(IMemoryCache::class);
// We need to check "just" ICache, because the default Cache is DB-Cache, which isn't a memorycache // We need to check "just" ICache, because the default Cache is DB-Cache, which isn't a memorycache
$this->assertInstanceOf(ICache::class, $cache); self::assertInstanceOf(ICache::class, $cache);
} }
public function testLock() public function testLock()
@ -184,6 +184,6 @@ class dependencyCheck extends TestCase
/** @var ILock $cache */ /** @var ILock $cache */
$lock = $this->dice->create(ILock::class); $lock = $this->dice->create(ILock::class);
$this->assertInstanceOf(ILock::class, $lock); self::assertInstanceOf(ILock::class, $lock);
} }
} }

File diff suppressed because it is too large Load diff

View file

@ -28,11 +28,11 @@ class ArgumentsTest extends TestCase
{ {
private function assertArguments(array $assert, App\Arguments $arguments) private function assertArguments(array $assert, App\Arguments $arguments)
{ {
$this->assertEquals($assert['queryString'], $arguments->getQueryString()); self::assertEquals($assert['queryString'], $arguments->getQueryString());
$this->assertEquals($assert['command'], $arguments->getCommand()); self::assertEquals($assert['command'], $arguments->getCommand());
$this->assertEquals($assert['argv'], $arguments->getArgv()); self::assertEquals($assert['argv'], $arguments->getArgv());
$this->assertEquals($assert['argc'], $arguments->getArgc()); self::assertEquals($assert['argc'], $arguments->getArgc());
$this->assertCount($assert['argc'], $arguments->getArgv()); self::assertCount($assert['argc'], $arguments->getArgv());
} }
/** /**
@ -42,7 +42,7 @@ class ArgumentsTest extends TestCase
{ {
$arguments = new App\Arguments(); $arguments = new App\Arguments();
$this->assertArguments([ self::assertArguments([
'queryString' => '', 'queryString' => '',
'command' => '', 'command' => '',
'argv' => [], 'argv' => [],
@ -177,7 +177,7 @@ class ArgumentsTest extends TestCase
$arguments = (new App\Arguments()) $arguments = (new App\Arguments())
->determine($server, $get); ->determine($server, $get);
$this->assertArguments($assert, $arguments); self::assertArguments($assert, $arguments);
} }
/** /**
@ -191,13 +191,13 @@ class ArgumentsTest extends TestCase
->determine($server, $get); ->determine($server, $get);
for ($i = 0; $i < $arguments->getArgc(); $i++) { for ($i = 0; $i < $arguments->getArgc(); $i++) {
$this->assertTrue($arguments->has($i)); self::assertTrue($arguments->has($i));
$this->assertEquals($assert['argv'][$i], $arguments->get($i)); self::assertEquals($assert['argv'][$i], $arguments->get($i));
} }
$this->assertFalse($arguments->has($arguments->getArgc())); self::assertFalse($arguments->has($arguments->getArgc()));
$this->assertEmpty($arguments->get($arguments->getArgc())); self::assertEmpty($arguments->get($arguments->getArgc()));
$this->assertEquals('default', $arguments->get($arguments->getArgc(), 'default')); self::assertEquals('default', $arguments->get($arguments->getArgc(), 'default'));
} }
public function dataStripped() public function dataStripped()
@ -242,7 +242,7 @@ class ArgumentsTest extends TestCase
$arguments = (new App\Arguments()) $arguments = (new App\Arguments())
->determine(['QUERY_STRING' => 'pagename=' . $command . $input,], ['pagename' => $command]); ->determine(['QUERY_STRING' => 'pagename=' . $command . $input,], ['pagename' => $command]);
$this->assertEquals($command . $assert, $arguments->getQueryString()); self::assertEquals($command . $assert, $arguments->getQueryString());
} }
/** /**
@ -254,6 +254,6 @@ class ArgumentsTest extends TestCase
$argNew = $argument->determine([], []); $argNew = $argument->determine([], []);
$this->assertNotSame($argument, $argNew); self::assertNotSame($argument, $argNew);
} }
} }

View file

@ -24,12 +24,13 @@ namespace Friendica\Test\src\App;
use Detection\MobileDetect; use Detection\MobileDetect;
use Friendica\App\Mode; use Friendica\App\Mode;
use Friendica\App\Module; use Friendica\App\Module;
use Friendica\Core\Config; use Friendica\Core\Config\Cache;
use Friendica\Database\Database; use Friendica\Database\Database;
use Friendica\Test\MockedTest; use Friendica\Test\MockedTest;
use Friendica\Test\Util\DBAMockTrait; use Friendica\Test\Util\DBAMockTrait;
use Friendica\Test\Util\VFSTrait; use Friendica\Test\Util\VFSTrait;
use Friendica\Util\BasePath; use Friendica\Util\BasePath;
use Mockery;
use Mockery\MockInterface; use Mockery\MockInterface;
class ModeTest extends MockedTest class ModeTest extends MockedTest
@ -48,44 +49,44 @@ class ModeTest extends MockedTest
private $databaseMock; private $databaseMock;
/** /**
* @var \Friendica\Core\Config\Cache|MockInterface * @var Cache|MockInterface
*/ */
private $configCacheMock; private $configCacheMock;
public function setUp() protected function setUp()
{ {
parent::setUp(); parent::setUp();
$this->setUpVfsDir(); $this->setUpVfsDir();
$this->basePathMock = \Mockery::mock(BasePath::class); $this->basePathMock = Mockery::mock(BasePath::class);
$this->databaseMock = \Mockery::mock(Database::class); $this->databaseMock = Mockery::mock(Database::class);
$this->configCacheMock = \Mockery::mock(Config\Cache::class); $this->configCacheMock = Mockery::mock(Cache::class);
} }
public function testItEmpty() public function testItEmpty()
{ {
$mode = new Mode(); $mode = new Mode();
$this->assertTrue($mode->isInstall()); self::assertTrue($mode->isInstall());
$this->assertFalse($mode->isNormal()); self::assertFalse($mode->isNormal());
} }
public function testWithoutConfig() public function testWithoutConfig()
{ {
$this->basePathMock->shouldReceive('getPath')->andReturn($this->root->url())->once(); $this->basePathMock->shouldReceive('getPath')->andReturn($this->root->url())->once();
$this->assertTrue($this->root->hasChild('config/local.config.php')); self::assertTrue($this->root->hasChild('config/local.config.php'));
$this->delConfigFile('local.config.php'); $this->delConfigFile('local.config.php');
$this->assertFalse($this->root->hasChild('config/local.config.php')); self::assertFalse($this->root->hasChild('config/local.config.php'));
$mode = (new Mode())->determine($this->basePathMock, $this->databaseMock, $this->configCacheMock); $mode = (new Mode())->determine($this->basePathMock, $this->databaseMock, $this->configCacheMock);
$this->assertTrue($mode->isInstall()); self::assertTrue($mode->isInstall());
$this->assertFalse($mode->isNormal()); self::assertFalse($mode->isNormal());
$this->assertFalse($mode->has(Mode::LOCALCONFIGPRESENT)); self::assertFalse($mode->has(Mode::LOCALCONFIGPRESENT));
} }
public function testWithoutDatabase() public function testWithoutDatabase()
@ -96,11 +97,11 @@ class ModeTest extends MockedTest
$mode = (new Mode())->determine($this->basePathMock, $this->databaseMock, $this->configCacheMock); $mode = (new Mode())->determine($this->basePathMock, $this->databaseMock, $this->configCacheMock);
$this->assertFalse($mode->isNormal()); self::assertFalse($mode->isNormal());
$this->assertTrue($mode->isInstall()); self::assertTrue($mode->isInstall());
$this->assertTrue($mode->has(Mode::LOCALCONFIGPRESENT)); self::assertTrue($mode->has(Mode::LOCALCONFIGPRESENT));
$this->assertFalse($mode->has(Mode::DBAVAILABLE)); self::assertFalse($mode->has(Mode::DBAVAILABLE));
} }
public function testWithoutDatabaseSetup() public function testWithoutDatabaseSetup()
@ -113,10 +114,10 @@ class ModeTest extends MockedTest
$mode = (new Mode())->determine($this->basePathMock, $this->databaseMock, $this->configCacheMock); $mode = (new Mode())->determine($this->basePathMock, $this->databaseMock, $this->configCacheMock);
$this->assertFalse($mode->isNormal()); self::assertFalse($mode->isNormal());
$this->assertTrue($mode->isInstall()); self::assertTrue($mode->isInstall());
$this->assertTrue($mode->has(Mode::LOCALCONFIGPRESENT)); self::assertTrue($mode->has(Mode::LOCALCONFIGPRESENT));
} }
public function testWithMaintenanceMode() public function testWithMaintenanceMode()
@ -131,11 +132,11 @@ class ModeTest extends MockedTest
$mode = (new Mode())->determine($this->basePathMock, $this->databaseMock, $this->configCacheMock); $mode = (new Mode())->determine($this->basePathMock, $this->databaseMock, $this->configCacheMock);
$this->assertFalse($mode->isNormal()); self::assertFalse($mode->isNormal());
$this->assertFalse($mode->isInstall()); self::assertFalse($mode->isInstall());
$this->assertTrue($mode->has(Mode::DBCONFIGAVAILABLE)); self::assertTrue($mode->has(Mode::DBCONFIGAVAILABLE));
$this->assertFalse($mode->has(Mode::MAINTENANCEDISABLED)); self::assertFalse($mode->has(Mode::MAINTENANCEDISABLED));
} }
public function testNormalMode() public function testNormalMode()
@ -153,11 +154,11 @@ class ModeTest extends MockedTest
$mode = (new Mode())->determine($this->basePathMock, $this->databaseMock, $this->configCacheMock); $mode = (new Mode())->determine($this->basePathMock, $this->databaseMock, $this->configCacheMock);
$this->assertTrue($mode->isNormal()); self::assertTrue($mode->isNormal());
$this->assertFalse($mode->isInstall()); self::assertFalse($mode->isInstall());
$this->assertTrue($mode->has(Mode::DBCONFIGAVAILABLE)); self::assertTrue($mode->has(Mode::DBCONFIGAVAILABLE));
$this->assertTrue($mode->has(Mode::MAINTENANCEDISABLED)); self::assertTrue($mode->has(Mode::MAINTENANCEDISABLED));
} }
/** /**
@ -178,11 +179,11 @@ class ModeTest extends MockedTest
$mode = (new Mode())->determine($this->basePathMock, $this->databaseMock, $this->configCacheMock); $mode = (new Mode())->determine($this->basePathMock, $this->databaseMock, $this->configCacheMock);
$this->assertTrue($mode->isNormal()); self::assertTrue($mode->isNormal());
$this->assertFalse($mode->isInstall()); self::assertFalse($mode->isInstall());
$this->assertTrue($mode->has(Mode::DBCONFIGAVAILABLE)); self::assertTrue($mode->has(Mode::DBCONFIGAVAILABLE));
$this->assertTrue($mode->has(Mode::MAINTENANCEDISABLED)); self::assertTrue($mode->has(Mode::MAINTENANCEDISABLED));
} }
/** /**
@ -196,7 +197,7 @@ class ModeTest extends MockedTest
$modeNew = $mode->determine($this->basePathMock, $this->databaseMock, $this->configCacheMock); $modeNew = $mode->determine($this->basePathMock, $this->databaseMock, $this->configCacheMock);
$this->assertNotSame($modeNew, $mode); self::assertNotSame($modeNew, $mode);
} }
/** /**
@ -210,7 +211,7 @@ class ModeTest extends MockedTest
$mode = (new Mode())->determineRunMode(true, $module, $server, $mobileDetect); $mode = (new Mode())->determineRunMode(true, $module, $server, $mobileDetect);
$this->assertTrue($mode->isBackend()); self::assertTrue($mode->isBackend());
} }
/** /**
@ -224,7 +225,7 @@ class ModeTest extends MockedTest
$mode = (new Mode())->determineRunMode(false, $module, $server, $mobileDetect); $mode = (new Mode())->determineRunMode(false, $module, $server, $mobileDetect);
$this->assertTrue($mode->isBackend()); self::assertTrue($mode->isBackend());
} }
/** /**
@ -238,7 +239,7 @@ class ModeTest extends MockedTest
$mode = (new Mode())->determineRunMode(false, $module, $server, $mobileDetect); $mode = (new Mode())->determineRunMode(false, $module, $server, $mobileDetect);
$this->assertFalse($mode->isBackend()); self::assertFalse($mode->isBackend());
} }
/** /**
@ -256,7 +257,7 @@ class ModeTest extends MockedTest
$mode = (new Mode())->determineRunMode(true, $module, $server, $mobileDetect); $mode = (new Mode())->determineRunMode(true, $module, $server, $mobileDetect);
$this->assertTrue($mode->isAjax()); self::assertTrue($mode->isAjax());
} }
/** /**
@ -270,7 +271,7 @@ class ModeTest extends MockedTest
$mode = (new Mode())->determineRunMode(true, $module, $server, $mobileDetect); $mode = (new Mode())->determineRunMode(true, $module, $server, $mobileDetect);
$this->assertFalse($mode->isAjax()); self::assertFalse($mode->isAjax());
} }
/** /**
@ -280,14 +281,14 @@ class ModeTest extends MockedTest
{ {
$server = []; $server = [];
$module = new Module(Module::DEFAULT, Module::DEFAULT_CLASS, [], false); $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('isMobile')->andReturn(true);
$mobileDetect->shouldReceive('isTablet')->andReturn(true); $mobileDetect->shouldReceive('isTablet')->andReturn(true);
$mode = (new Mode())->determineRunMode(true, $module, $server, $mobileDetect); $mode = (new Mode())->determineRunMode(true, $module, $server, $mobileDetect);
$this->assertTrue($mode->isMobile()); self::assertTrue($mode->isMobile());
$this->assertTrue($mode->isTablet()); self::assertTrue($mode->isTablet());
} }
@ -298,13 +299,13 @@ class ModeTest extends MockedTest
{ {
$server = []; $server = [];
$module = new Module(Module::DEFAULT, Module::DEFAULT_CLASS, [], false); $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('isMobile')->andReturn(false);
$mobileDetect->shouldReceive('isTablet')->andReturn(false); $mobileDetect->shouldReceive('isTablet')->andReturn(false);
$mode = (new Mode())->determineRunMode(true, $module, $server, $mobileDetect); $mode = (new Mode())->determineRunMode(true, $module, $server, $mobileDetect);
$this->assertFalse($mode->isMobile()); self::assertFalse($mode->isMobile());
$this->assertFalse($mode->isTablet()); self::assertFalse($mode->isTablet());
} }
} }

View file

@ -29,14 +29,15 @@ use Friendica\LegacyModule;
use Friendica\Module\HTTPException\PageNotFound; use Friendica\Module\HTTPException\PageNotFound;
use Friendica\Module\WellKnown\HostMeta; use Friendica\Module\WellKnown\HostMeta;
use Friendica\Test\DatabaseTest; use Friendica\Test\DatabaseTest;
use Mockery;
class ModuleTest extends DatabaseTest class ModuleTest extends DatabaseTest
{ {
private function assertModule(array $assert, App\Module $module) private function assertModule(array $assert, App\Module $module)
{ {
$this->assertEquals($assert['isBackend'], $module->isBackend()); self::assertEquals($assert['isBackend'], $module->isBackend());
$this->assertEquals($assert['name'], $module->getName()); self::assertEquals($assert['name'], $module->getName());
$this->assertEquals($assert['class'], $module->getClassName()); self::assertEquals($assert['class'], $module->getClassName());
} }
/** /**
@ -46,7 +47,7 @@ class ModuleTest extends DatabaseTest
{ {
$module = new App\Module(); $module = new App\Module();
$this->assertModule([ self::assertModule([
'isBackend' => false, 'isBackend' => false,
'name' => App\Module::DEFAULT, 'name' => App\Module::DEFAULT,
'class' => App\Module::DEFAULT_CLASS, 'class' => App\Module::DEFAULT_CLASS,
@ -128,7 +129,7 @@ class ModuleTest extends DatabaseTest
{ {
$module = (new App\Module())->determineModule($args); $module = (new App\Module())->determineModule($args);
$this->assertModule($assert, $module); self::assertModule($assert, $module);
} }
public function dataModuleClass() public function dataModuleClass()
@ -170,13 +171,13 @@ class ModuleTest extends DatabaseTest
*/ */
public function testModuleClass($assert, string $name, string $command, bool $privAdd) 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(); $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; }); $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('routerDispatchData')->andReturn('')->atMost()->once();
$cache->shouldReceive('get')->with('lastRoutesFileModifiedTime')->andReturn('')->atMost()->once(); $cache->shouldReceive('get')->with('lastRoutesFileModifiedTime')->andReturn('')->atMost()->once();
$cache->shouldReceive('set')->withAnyArgs()->andReturn(false)->atMost()->twice(); $cache->shouldReceive('set')->withAnyArgs()->andReturn(false)->atMost()->twice();
@ -185,7 +186,7 @@ class ModuleTest extends DatabaseTest
$module = (new App\Module($name))->determineClass(new App\Arguments('', $command), $router, $config); $module = (new App\Module($name))->determineClass(new App\Arguments('', $command), $router, $config);
$this->assertEquals($assert, $module->getClassName()); self::assertEquals($assert, $module->getClassName());
} }
/** /**
@ -197,6 +198,6 @@ class ModuleTest extends DatabaseTest
$moduleNew = $module->determineModule(new App\Arguments()); $moduleNew = $module->determineModule(new App\Arguments());
$this->assertNotSame($moduleNew, $module); self::assertNotSame($moduleNew, $module);
} }
} }

View file

@ -27,6 +27,7 @@ use Friendica\Core\L10n;
use Friendica\Module; use Friendica\Module;
use Friendica\Network\HTTPException\MethodNotAllowedException; use Friendica\Network\HTTPException\MethodNotAllowedException;
use Friendica\Network\HTTPException\NotFoundException; use Friendica\Network\HTTPException\NotFoundException;
use Mockery;
use Mockery\MockInterface; use Mockery\MockInterface;
use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCase;
@ -43,10 +44,10 @@ class RouterTest extends TestCase
{ {
parent::setUp(); parent::setUp();
$this->l10n = \Mockery::mock(L10n::class); $this->l10n = Mockery::mock(L10n::class);
$this->l10n->shouldReceive('t')->andReturnUsing(function ($args) { return $args; }); $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('get')->andReturn(null);
$this->cache->shouldReceive('set')->andReturn(false); $this->cache->shouldReceive('set')->andReturn(false);
} }
@ -64,15 +65,15 @@ class RouterTest extends TestCase
$routeCollector->addRoute([Router::GET], '/variable/{var}', 'VariableModuleClassName'); $routeCollector->addRoute([Router::GET], '/variable/{var}', 'VariableModuleClassName');
$routeCollector->addRoute([Router::GET], '/optionalvariable[/{option}]', 'OptionalVariableModuleClassName'); $routeCollector->addRoute([Router::GET], '/optionalvariable[/{option}]', 'OptionalVariableModuleClassName');
$this->assertEquals('IndexModuleClassName', $router->getModuleClass('/')); self::assertEquals('IndexModuleClassName', $router->getModuleClass('/'));
$this->assertEquals('TestModuleClassName', $router->getModuleClass('/test')); self::assertEquals('TestModuleClassName', $router->getModuleClass('/test'));
$this->assertEquals('TestGetPostModuleClassName', $router->getModuleClass('/testgetpost')); self::assertEquals('TestGetPostModuleClassName', $router->getModuleClass('/testgetpost'));
$this->assertEquals('TestSubModuleClassName', $router->getModuleClass('/test/sub')); self::assertEquals('TestSubModuleClassName', $router->getModuleClass('/test/sub'));
$this->assertEquals('OptionalModuleClassName', $router->getModuleClass('/optional')); self::assertEquals('OptionalModuleClassName', $router->getModuleClass('/optional'));
$this->assertEquals('OptionalModuleClassName', $router->getModuleClass('/optional/option')); self::assertEquals('OptionalModuleClassName', $router->getModuleClass('/optional/option'));
$this->assertEquals('VariableModuleClassName', $router->getModuleClass('/variable/123abc')); self::assertEquals('VariableModuleClassName', $router->getModuleClass('/variable/123abc'));
$this->assertEquals('OptionalVariableModuleClassName', $router->getModuleClass('/optionalvariable')); self::assertEquals('OptionalVariableModuleClassName', $router->getModuleClass('/optionalvariable'));
$this->assertEquals('OptionalVariableModuleClassName', $router->getModuleClass('/optionalvariable/123abc')); self::assertEquals('OptionalVariableModuleClassName', $router->getModuleClass('/optionalvariable/123abc'));
} }
public function testPostModuleClass() public function testPostModuleClass()
@ -88,15 +89,15 @@ class RouterTest extends TestCase
$routeCollector->addRoute([Router::POST], '/variable/{var}', 'VariableModuleClassName'); $routeCollector->addRoute([Router::POST], '/variable/{var}', 'VariableModuleClassName');
$routeCollector->addRoute([Router::POST], '/optionalvariable[/{option}]', 'OptionalVariableModuleClassName'); $routeCollector->addRoute([Router::POST], '/optionalvariable[/{option}]', 'OptionalVariableModuleClassName');
$this->assertEquals('IndexModuleClassName', $router->getModuleClass('/')); self::assertEquals('IndexModuleClassName', $router->getModuleClass('/'));
$this->assertEquals('TestModuleClassName', $router->getModuleClass('/test')); self::assertEquals('TestModuleClassName', $router->getModuleClass('/test'));
$this->assertEquals('TestGetPostModuleClassName', $router->getModuleClass('/testgetpost')); self::assertEquals('TestGetPostModuleClassName', $router->getModuleClass('/testgetpost'));
$this->assertEquals('TestSubModuleClassName', $router->getModuleClass('/test/sub')); self::assertEquals('TestSubModuleClassName', $router->getModuleClass('/test/sub'));
$this->assertEquals('OptionalModuleClassName', $router->getModuleClass('/optional')); self::assertEquals('OptionalModuleClassName', $router->getModuleClass('/optional'));
$this->assertEquals('OptionalModuleClassName', $router->getModuleClass('/optional/option')); self::assertEquals('OptionalModuleClassName', $router->getModuleClass('/optional/option'));
$this->assertEquals('VariableModuleClassName', $router->getModuleClass('/variable/123abc')); self::assertEquals('VariableModuleClassName', $router->getModuleClass('/variable/123abc'));
$this->assertEquals('OptionalVariableModuleClassName', $router->getModuleClass('/optionalvariable')); self::assertEquals('OptionalVariableModuleClassName', $router->getModuleClass('/optionalvariable'));
$this->assertEquals('OptionalVariableModuleClassName', $router->getModuleClass('/optionalvariable/123abc')); self::assertEquals('OptionalVariableModuleClassName', $router->getModuleClass('/optionalvariable/123abc'));
} }
public function testGetModuleClassNotFound() public function testGetModuleClassNotFound()
@ -205,10 +206,10 @@ class RouterTest extends TestCase
$this->cache $this->cache
))->loadRoutes($routes); ))->loadRoutes($routes);
$this->assertEquals(Module\Home::class, $router->getModuleClass('/')); self::assertEquals(Module\Home::class, $router->getModuleClass('/'));
$this->assertEquals(Module\Friendica::class, $router->getModuleClass('/group/route')); self::assertEquals(Module\Friendica::class, $router->getModuleClass('/group/route'));
$this->assertEquals(Module\Xrd::class, $router->getModuleClass('/group2/group3/route')); self::assertEquals(Module\Xrd::class, $router->getModuleClass('/group2/group3/route'));
$this->assertEquals(Module\Profile\Index::class, $router->getModuleClass('/double')); self::assertEquals(Module\Profile\Index::class, $router->getModuleClass('/double'));
} }
/** /**
@ -221,7 +222,7 @@ class RouterTest extends TestCase
], '', $this->l10n, $this->cache))->loadRoutes($routes); ], '', $this->l10n, $this->cache))->loadRoutes($routes);
// Don't find GET // Don't find GET
$this->assertEquals(Module\WellKnown\NodeInfo::class, $router->getModuleClass('/post/it')); self::assertEquals(Module\WellKnown\NodeInfo::class, $router->getModuleClass('/post/it'));
$this->assertEquals(Module\Profile\Index::class, $router->getModuleClass('/double')); self::assertEquals(Module\Profile\Index::class, $router->getModuleClass('/double'));
} }
} }

View file

@ -35,6 +35,7 @@ use Friendica\Test\Util\DBStructureMockTrait;
use Friendica\Test\Util\RendererMockTrait; use Friendica\Test\Util\RendererMockTrait;
use Friendica\Test\Util\VFSTrait; use Friendica\Test\Util\VFSTrait;
use Friendica\Util\Logger\VoidLogger; use Friendica\Util\Logger\VoidLogger;
use Mockery;
use Mockery\MockInterface; use Mockery\MockInterface;
use org\bovigo\vfs\vfsStream; use org\bovigo\vfs\vfsStream;
use org\bovigo\vfs\vfsStreamFile; use org\bovigo\vfs\vfsStreamFile;
@ -77,7 +78,7 @@ class AutomaticInstallationConsoleTest extends ConsoleTest
public function setUp() 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(); parent::setUp();
@ -87,9 +88,9 @@ class AutomaticInstallationConsoleTest extends ConsoleTest
$this->root->getChild('config') $this->root->getChild('config')
->removeChild('local.config.php'); ->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; }); $l10nMock->shouldReceive('t')->andReturnUsing(function ($args) { return $args; });
$this->dice->shouldReceive('create') $this->dice->shouldReceive('create')
@ -264,7 +265,7 @@ Installation is finished
FIN; FIN;
$this->assertEquals($finished, $txt); self::assertEquals($finished, $txt);
} }
private function assertStuckDB($txt) private function assertStuckDB($txt)
@ -295,7 +296,7 @@ Could not connect to database.:
FIN; FIN;
$this->assertEquals($finished, $txt); self::assertEquals($finished, $txt);
} }
private function assertStuckURL($txt) private function assertStuckURL($txt)
@ -319,7 +320,7 @@ The Friendica URL has to be set during CLI installation.
FIN; FIN;
$this->assertEquals($finished, $txt); self::assertEquals($finished, $txt);
} }
/** /**
@ -333,13 +334,13 @@ FIN;
public function assertConfigEntry($cat, $key, $assertion = null, $default_value = null) public function assertConfigEntry($cat, $key, $assertion = null, $default_value = null)
{ {
if (!empty($assertion[$cat][$key])) { if (!empty($assertion[$cat][$key])) {
$this->assertEquals($assertion[$cat][$key], $this->configCache->get($cat, $key)); self::assertEquals($assertion[$cat][$key], $this->configCache->get($cat, $key));
} elseif (!empty($assertion) && !is_array($assertion)) { } elseif (!empty($assertion) && !is_array($assertion)) {
$this->assertEquals($assertion, $this->configCache->get($cat, $key)); self::assertEquals($assertion, $this->configCache->get($cat, $key));
} elseif (!empty($default_value)) { } elseif (!empty($default_value)) {
$this->assertEquals($default_value, $this->configCache->get($cat, $key)); self::assertEquals($default_value, $this->configCache->get($cat, $key));
} else { } else {
$this->assertEmpty($this->configCache->get($cat, $key), $this->configCache->get($cat, $key)); self::assertEmpty($this->configCache->get($cat, $key), $this->configCache->get($cat, $key));
} }
} }
@ -358,21 +359,21 @@ FIN;
$assertion['database']['hostname'] .= (!empty($assertion['database']['port']) ? ':' . $assertion['database']['port'] : ''); $assertion['database']['hostname'] .= (!empty($assertion['database']['port']) ? ':' . $assertion['database']['port'] : '');
} }
$this->assertConfigEntry('database', 'hostname', ($saveDb) ? $assertion : null, (!$saveDb || $defaultDb) ? Installer::DEFAULT_HOST : null); self::assertConfigEntry('database', 'hostname', ($saveDb) ? $assertion : null, (!$saveDb || $defaultDb) ? Installer::DEFAULT_HOST : null);
$this->assertConfigEntry('database', 'username', ($saveDb) ? $assertion : null); self::assertConfigEntry('database', 'username', ($saveDb) ? $assertion : null);
$this->assertConfigEntry('database', 'password', ($saveDb) ? $assertion : null); self::assertConfigEntry('database', 'password', ($saveDb) ? $assertion : null);
$this->assertConfigEntry('database', 'database', ($saveDb) ? $assertion : null); self::assertConfigEntry('database', 'database', ($saveDb) ? $assertion : null);
$this->assertConfigEntry('config', 'admin_email', $assertion); self::assertConfigEntry('config', 'admin_email', $assertion);
$this->assertConfigEntry('config', 'php_path', trim(shell_exec('which php'))); self::assertConfigEntry('config', 'php_path', trim(shell_exec('which php')));
$this->assertConfigEntry('config', 'hostname', $assertion); self::assertConfigEntry('config', 'hostname', $assertion);
$this->assertConfigEntry('system', 'default_timezone', $assertion, ($default) ? Installer::DEFAULT_TZ : null); self::assertConfigEntry('system', 'default_timezone', $assertion, ($default) ? Installer::DEFAULT_TZ : null);
$this->assertConfigEntry('system', 'language', $assertion, ($default) ? Installer::DEFAULT_LANG : null); self::assertConfigEntry('system', 'language', $assertion, ($default) ? Installer::DEFAULT_LANG : null);
$this->assertConfigEntry('system', 'url', $assertion); self::assertConfigEntry('system', 'url', $assertion);
$this->assertConfigEntry('system', 'urlpath', $assertion); self::assertConfigEntry('system', 'urlpath', $assertion);
$this->assertConfigEntry('system', 'ssl_policy', $assertion, ($default) ? App\BaseURL::DEFAULT_SSL_SCHEME : null); self::assertConfigEntry('system', 'ssl_policy', $assertion, ($default) ? App\BaseURL::DEFAULT_SSL_SCHEME : null);
$this->assertConfigEntry('system', 'basepath', ($realBasepath) ? $this->root->url() : $assertion); self::assertConfigEntry('system', 'basepath', ($realBasepath) ? $this->root->url() : $assertion);
} }
/** /**
@ -385,7 +386,7 @@ FIN;
$txt = $this->dumpExecute($console); $txt = $this->dumpExecute($console);
$this->assertStuckURL($txt); self::assertStuckURL($txt);
} }
/** /**
@ -400,17 +401,17 @@ FIN;
$this->mockUpdate([$this->root->url(), false, true, true], null, 1); $this->mockUpdate([$this->root->url(), false, true, true], null, 1);
$this->mockGetMarkupTemplate('local.config.tpl', 'testTemplate', 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 = new AutomaticInstallation($this->consoleArgv);
$console->setOption('url', 'http://friendica.local'); $console->setOption('url', 'http://friendica.local');
$txt = $this->dumpExecute($console); $txt = $this->dumpExecute($console);
$this->assertFinished($txt, true, false); self::assertFinished($txt, true, false);
$this->assertTrue($this->root->hasChild('config' . DIRECTORY_SEPARATOR . 'local.config.php')); self::assertTrue($this->root->hasChild('config' . DIRECTORY_SEPARATOR . 'local.config.php'));
$this->assertConfig(['config' => ['hostname' => 'friendica.local'], 'system' => ['url' => 'http://friendica.local', 'ssl_policy' => 0, 'urlPath' => '']], false, true, true, true); self::assertConfig(['config' => ['hostname' => 'friendica.local'], 'system' => ['url' => 'http://friendica.local', 'ssl_policy' => 0, 'urlPath' => '']], false, true, true, true);
} }
/** /**
@ -481,12 +482,12 @@ CONF;
$txt = $this->dumpExecute($console); $txt = $this->dumpExecute($console);
$this->assertFinished($txt, false, true); self::assertFinished($txt, false, true);
$this->assertTrue($this->root->hasChild('config' . DIRECTORY_SEPARATOR . 'local.config.php')); self::assertTrue($this->root->hasChild('config' . DIRECTORY_SEPARATOR . 'local.config.php'));
$this->assertEquals($config, file_get_contents($this->root->getChild('config' . DIRECTORY_SEPARATOR . 'local.config.php')->url())); self::assertEquals($config, file_get_contents($this->root->getChild('config' . DIRECTORY_SEPARATOR . 'local.config.php')->url()));
$this->assertConfig($data, true, false, false); self::assertConfig($data, true, false, false);
} }
/** /**
@ -502,29 +503,29 @@ CONF;
$this->mockUpdate([$this->root->url(), false, true, true], null, 1); $this->mockUpdate([$this->root->url(), false, true, true], null, 1);
$this->mockGetMarkupTemplate('local.config.tpl', 'testTemplate', 1); $this->mockGetMarkupTemplate('local.config.tpl', 'testTemplate', 1);
$this->mockReplaceMacros('testTemplate', \Mockery::any(), '', 1); $this->mockReplaceMacros('testTemplate', Mockery::any(), '', 1);
$this->assertTrue(putenv('MYSQL_HOST=' . $data['database']['hostname'])); self::assertTrue(putenv('MYSQL_HOST=' . $data['database']['hostname']));
$this->assertTrue(putenv('MYSQL_PORT=' . $data['database']['port'])); self::assertTrue(putenv('MYSQL_PORT=' . $data['database']['port']));
$this->assertTrue(putenv('MYSQL_DATABASE=' . $data['database']['database'])); self::assertTrue(putenv('MYSQL_DATABASE=' . $data['database']['database']));
$this->assertTrue(putenv('MYSQL_USERNAME=' . $data['database']['username'])); self::assertTrue(putenv('MYSQL_USERNAME=' . $data['database']['username']));
$this->assertTrue(putenv('MYSQL_PASSWORD=' . $data['database']['password'])); self::assertTrue(putenv('MYSQL_PASSWORD=' . $data['database']['password']));
$this->assertTrue(putenv('FRIENDICA_HOSTNAME=' . $data['config']['hostname'])); self::assertTrue(putenv('FRIENDICA_HOSTNAME=' . $data['config']['hostname']));
$this->assertTrue(putenv('FRIENDICA_BASE_PATH=' . $data['system']['basepath'])); self::assertTrue(putenv('FRIENDICA_BASE_PATH=' . $data['system']['basepath']));
$this->assertTrue(putenv('FRIENDICA_URL=' . $data['system']['url'])); self::assertTrue(putenv('FRIENDICA_URL=' . $data['system']['url']));
$this->assertTrue(putenv('FRIENDICA_PHP_PATH=' . $data['config']['php_path'])); self::assertTrue(putenv('FRIENDICA_PHP_PATH=' . $data['config']['php_path']));
$this->assertTrue(putenv('FRIENDICA_ADMIN_MAIL=' . $data['config']['admin_email'])); self::assertTrue(putenv('FRIENDICA_ADMIN_MAIL=' . $data['config']['admin_email']));
$this->assertTrue(putenv('FRIENDICA_TZ=' . $data['system']['default_timezone'])); self::assertTrue(putenv('FRIENDICA_TZ=' . $data['system']['default_timezone']));
$this->assertTrue(putenv('FRIENDICA_LANG=' . $data['system']['language'])); self::assertTrue(putenv('FRIENDICA_LANG=' . $data['system']['language']));
$console = new AutomaticInstallation($this->consoleArgv); $console = new AutomaticInstallation($this->consoleArgv);
$console->setOption('savedb', true); $console->setOption('savedb', true);
$txt = $this->dumpExecute($console); $txt = $this->dumpExecute($console);
$this->assertFinished($txt, true); self::assertFinished($txt, true);
$this->assertConfig($data, true, true, false, true); self::assertConfig($data, true, true, false, true);
} }
/** /**
@ -540,28 +541,28 @@ CONF;
$this->mockUpdate([$this->root->url(), false, true, true], null, 1); $this->mockUpdate([$this->root->url(), false, true, true], null, 1);
$this->mockGetMarkupTemplate('local.config.tpl', 'testTemplate', 1); $this->mockGetMarkupTemplate('local.config.tpl', 'testTemplate', 1);
$this->mockReplaceMacros('testTemplate', \Mockery::any(), '', 1); $this->mockReplaceMacros('testTemplate', Mockery::any(), '', 1);
$this->assertTrue(putenv('MYSQL_HOST=' . $data['database']['hostname'])); self::assertTrue(putenv('MYSQL_HOST=' . $data['database']['hostname']));
$this->assertTrue(putenv('MYSQL_PORT=' . $data['database']['port'])); self::assertTrue(putenv('MYSQL_PORT=' . $data['database']['port']));
$this->assertTrue(putenv('MYSQL_DATABASE=' . $data['database']['database'])); self::assertTrue(putenv('MYSQL_DATABASE=' . $data['database']['database']));
$this->assertTrue(putenv('MYSQL_USERNAME=' . $data['database']['username'])); self::assertTrue(putenv('MYSQL_USERNAME=' . $data['database']['username']));
$this->assertTrue(putenv('MYSQL_PASSWORD=' . $data['database']['password'])); self::assertTrue(putenv('MYSQL_PASSWORD=' . $data['database']['password']));
$this->assertTrue(putenv('FRIENDICA_HOSTNAME=' . $data['config']['hostname'])); self::assertTrue(putenv('FRIENDICA_HOSTNAME=' . $data['config']['hostname']));
$this->assertTrue(putenv('FRIENDICA_BASE_PATH=' . $data['system']['basepath'])); self::assertTrue(putenv('FRIENDICA_BASE_PATH=' . $data['system']['basepath']));
$this->assertTrue(putenv('FRIENDICA_URL=' . $data['system']['url'])); self::assertTrue(putenv('FRIENDICA_URL=' . $data['system']['url']));
$this->assertTrue(putenv('FRIENDICA_PHP_PATH=' . $data['config']['php_path'])); self::assertTrue(putenv('FRIENDICA_PHP_PATH=' . $data['config']['php_path']));
$this->assertTrue(putenv('FRIENDICA_ADMIN_MAIL=' . $data['config']['admin_email'])); self::assertTrue(putenv('FRIENDICA_ADMIN_MAIL=' . $data['config']['admin_email']));
$this->assertTrue(putenv('FRIENDICA_TZ=' . $data['system']['default_timezone'])); self::assertTrue(putenv('FRIENDICA_TZ=' . $data['system']['default_timezone']));
$this->assertTrue(putenv('FRIENDICA_LANG=' . $data['system']['language'])); self::assertTrue(putenv('FRIENDICA_LANG=' . $data['system']['language']));
$console = new AutomaticInstallation($this->consoleArgv); $console = new AutomaticInstallation($this->consoleArgv);
$txt = $this->dumpExecute($console); $txt = $this->dumpExecute($console);
$this->assertFinished($txt, true); self::assertFinished($txt, true);
$this->assertConfig($data, false, true, false, true); self::assertConfig($data, false, true, false, true);
} }
/** /**
@ -576,7 +577,7 @@ CONF;
$this->mockUpdate([$this->root->url(), false, true, true], null, 1); $this->mockUpdate([$this->root->url(), false, true, true], null, 1);
$this->mockGetMarkupTemplate('local.config.tpl', 'testTemplate', 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 = new AutomaticInstallation($this->consoleArgv);
@ -599,8 +600,8 @@ CONF;
$txt = $this->dumpExecute($console); $txt = $this->dumpExecute($console);
$this->assertFinished($txt, true); self::assertFinished($txt, true);
$this->assertConfig($data, true, true, true, true); self::assertConfig($data, true, true, true, true);
} }
/** /**
@ -611,17 +612,17 @@ CONF;
$this->mockConnect(false, 1); $this->mockConnect(false, 1);
$this->mockGetMarkupTemplate('local.config.tpl', 'testTemplate', 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 = new AutomaticInstallation($this->consoleArgv);
$console->setOption('url', 'http://friendica.local'); $console->setOption('url', 'http://friendica.local');
$txt = $this->dumpExecute($console); $txt = $this->dumpExecute($console);
$this->assertStuckDB($txt); self::assertStuckDB($txt);
$this->assertTrue($this->root->hasChild('config' . DIRECTORY_SEPARATOR . 'local.config.php')); self::assertTrue($this->root->hasChild('config' . DIRECTORY_SEPARATOR . 'local.config.php'));
$this->assertConfig(['config' => ['hostname' => 'friendica.local'], 'system' => ['url' => 'http://friendica.local', 'ssl_policy' => 0, 'urlpath' => '']], false, true, false, true); self::assertConfig(['config' => ['hostname' => 'friendica.local'], 'system' => ['url' => 'http://friendica.local', 'ssl_policy' => 0, 'urlpath' => '']], false, true, false, true);
} }
public function testGetHelp() public function testGetHelp()
@ -685,6 +686,6 @@ HELP;
$txt = $this->dumpExecute($console); $txt = $this->dumpExecute($console);
$this->assertEquals($theHelp, $txt); self::assertEquals($theHelp, $txt);
} }
} }

View file

@ -25,6 +25,8 @@ use Friendica\App;
use Friendica\App\Mode; use Friendica\App\Mode;
use Friendica\Console\Config; use Friendica\Console\Config;
use Friendica\Core\Config\IConfig; use Friendica\Core\Config\IConfig;
use Mockery;
use Mockery\LegacyMockInterface;
use Mockery\MockInterface; use Mockery\MockInterface;
class ConfigConsoleTest extends ConsoleTest class ConfigConsoleTest extends ConsoleTest
@ -33,27 +35,27 @@ class ConfigConsoleTest extends ConsoleTest
* @var App\Mode|MockInterface $appMode * @var App\Mode|MockInterface $appMode
*/ */
private $appMode; private $appMode;
/** @var IConfig|\Mockery\LegacyMockInterface|MockInterface */ /** @var IConfig|LegacyMockInterface|MockInterface */
private $configMock; private $configMock;
protected function setUp() protected function setUp()
{ {
parent::setUp(); parent::setUp();
\Mockery::getConfiguration()->setConstantsMap([ Mockery::getConfiguration()->setConstantsMap([
Mode::class => [ Mode::class => [
'DBCONFIGAVAILABLE' => 0 'DBCONFIGAVAILABLE' => 0,
] ],
]); ]);
$this->appMode = \Mockery::mock(App\Mode::class); $this->appMode = Mockery::mock(App\Mode::class);
$this->appMode->shouldReceive('has') $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 $this->configMock
->shouldReceive('set') ->shouldReceive('set')
@ -71,7 +73,7 @@ class ConfigConsoleTest extends ConsoleTest
$console->setArgument(1, 'test'); $console->setArgument(1, 'test');
$console->setArgument(2, 'now'); $console->setArgument(2, 'now');
$txt = $this->dumpExecute($console); $txt = $this->dumpExecute($console);
$this->assertEquals("config.test <= now\n", $txt); self::assertEquals("config.test <= now\n", $txt);
$this->configMock $this->configMock
->shouldReceive('get') ->shouldReceive('get')
@ -83,7 +85,7 @@ class ConfigConsoleTest extends ConsoleTest
$console->setArgument(0, 'config'); $console->setArgument(0, 'config');
$console->setArgument(1, 'test'); $console->setArgument(1, 'test');
$txt = $this->dumpExecute($console); $txt = $this->dumpExecute($console);
$this->assertEquals("config.test => now\n", $txt); self::assertEquals("config.test => now\n", $txt);
$this->configMock $this->configMock
->shouldReceive('get') ->shouldReceive('get')
@ -95,10 +97,11 @@ class ConfigConsoleTest extends ConsoleTest
$console->setArgument(0, 'config'); $console->setArgument(0, 'config');
$console->setArgument(1, 'test'); $console->setArgument(1, 'test');
$txt = $this->dumpExecute($console); $txt = $this->dumpExecute($console);
$this->assertEquals("config.test => \n", $txt); self::assertEquals("config.test => \n", $txt);
} }
function testSetArrayValue() { public function testSetArrayValue()
{
$testArray = [1, 2, 3]; $testArray = [1, 2, 3];
$this->configMock $this->configMock
->shouldReceive('get') ->shouldReceive('get')
@ -112,22 +115,24 @@ class ConfigConsoleTest extends ConsoleTest
$console->setArgument(2, 'now'); $console->setArgument(2, 'now');
$txt = $this->dumpExecute($console); $txt = $this->dumpExecute($console);
$this->assertEquals("[Error] config.test is an array and can't be set using this command.\n", $txt); 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 = new Config($this->appMode, $this->configMock, $this->consoleArgv);
$console->setArgument(0, 'config'); $console->setArgument(0, 'config');
$console->setArgument(1, 'test'); $console->setArgument(1, 'test');
$console->setArgument(2, 'it'); $console->setArgument(2, 'it');
$console->setArgument(3, 'now'); $console->setArgument(3, 'now');
$txt = $this->dumpExecute($console); $txt = $this->dumpExecute($console);
$assertion = '[Warning] Too many arguments'; $assertion = '[Warning] Too many arguments';
$firstline = substr($txt, 0, strlen($assertion)); $firstline = substr($txt, 0, strlen($assertion));
$this->assertEquals($assertion, $firstline); self::assertEquals($assertion, $firstline);
} }
function testVerbose() { public function testVerbose()
{
$this->configMock $this->configMock
->shouldReceive('get') ->shouldReceive('get')
->with('test', 'it') ->with('test', 'it')
@ -138,7 +143,7 @@ class ConfigConsoleTest extends ConsoleTest
$console->setArgument(1, 'it'); $console->setArgument(1, 'it');
$console->setOption('v', 1); $console->setOption('v', 1);
$executable = $this->consoleArgv[0]; $executable = $this->consoleArgv[0];
$assertion = <<<CONF $assertion = <<<CONF
Executable: {$executable} Executable: {$executable}
Class: Friendica\Console\Config Class: Friendica\Console\Config
Arguments: array ( Arguments: array (
@ -151,11 +156,12 @@ Options: array (
test.it => now test.it => now
CONF; CONF;
$txt = $this->dumpExecute($console); $txt = $this->dumpExecute($console);
$this->assertEquals($assertion, $txt); self::assertEquals($assertion, $txt);
} }
function testUnableToSet() { public function testUnableToSet()
{
$this->configMock $this->configMock
->shouldReceive('set') ->shouldReceive('set')
->with('test', 'it', 'now') ->with('test', 'it', 'now')
@ -164,14 +170,14 @@ CONF;
$this->configMock $this->configMock
->shouldReceive('get') ->shouldReceive('get')
->with('test', 'it') ->with('test', 'it')
->andReturn(NULL) ->andReturn(null)
->once(); ->once();
$console = new Config($this->appMode, $this->configMock, [$this->consoleArgv]); $console = new Config($this->appMode, $this->configMock, [$this->consoleArgv]);
$console->setArgument(0, 'test'); $console->setArgument(0, 'test');
$console->setArgument(1, 'it'); $console->setArgument(1, 'it');
$console->setArgument(2, 'now'); $console->setArgument(2, 'now');
$txt = $this->dumpExecute($console); $txt = $this->dumpExecute($console);
$this->assertSame("Unable to set test.it\n", $txt); self::assertSame("Unable to set test.it\n", $txt);
} }
public function testGetHelp() public function testGetHelp()
@ -212,6 +218,6 @@ HELP;
$txt = $this->dumpExecute($console); $txt = $this->dumpExecute($console);
$this->assertEquals($txt, $theHelp); self::assertEquals($txt, $theHelp);
} }
} }

View file

@ -46,7 +46,7 @@ abstract class ConsoleTest extends MockedTest
* *
* @return string the output of the execution * @return string the output of the execution
*/ */
protected function dumpExecute($console) protected function dumpExecute(Console $console)
{ {
Intercept::reset(); Intercept::reset();
$console->execute(); $console->execute();

View file

@ -25,6 +25,7 @@ use Friendica\App;
use Friendica\App\Mode; use Friendica\App\Mode;
use Friendica\Console\Lock; use Friendica\Console\Lock;
use Friendica\Core\Lock\ILock; use Friendica\Core\Lock\ILock;
use Mockery;
use Mockery\MockInterface; use Mockery\MockInterface;
class LockConsoleTest extends ConsoleTest class LockConsoleTest extends ConsoleTest
@ -43,17 +44,17 @@ class LockConsoleTest extends ConsoleTest
{ {
parent::setUp(); parent::setUp();
\Mockery::getConfiguration()->setConstantsMap([ Mockery::getConfiguration()->setConstantsMap([
Mode::class => [ Mode::class => [
'DBCONFIGAVAILABLE' => 0 'DBCONFIGAVAILABLE' => 0
] ]
]); ]);
$this->appMode = \Mockery::mock(App\Mode::class); $this->appMode = Mockery::mock(App\Mode::class);
$this->appMode->shouldReceive('has') $this->appMode->shouldReceive('has')
->andReturn(true); ->andReturn(true);
$this->lockMock = \Mockery::mock(ILock::class); $this->lockMock = Mockery::mock(ILock::class);
} }
public function testList() public function testList()
@ -66,7 +67,7 @@ class LockConsoleTest extends ConsoleTest
$console = new Lock($this->appMode, $this->lockMock, $this->consoleArgv); $console = new Lock($this->appMode, $this->lockMock, $this->consoleArgv);
$console->setArgument(0, 'list'); $console->setArgument(0, 'list');
$txt = $this->dumpExecute($console); $txt = $this->dumpExecute($console);
$this->assertEquals("Listing all Locks:\ntest\ntest2\n2 locks found\n", $txt); self::assertEquals("Listing all Locks:\ntest\ntest2\n2 locks found\n", $txt);
} }
public function testListPrefix() public function testListPrefix()
@ -81,7 +82,7 @@ class LockConsoleTest extends ConsoleTest
$console->setArgument(0, 'list'); $console->setArgument(0, 'list');
$console->setArgument(1, 'test'); $console->setArgument(1, 'test');
$txt = $this->dumpExecute($console); $txt = $this->dumpExecute($console);
$this->assertEquals("Listing all Locks starting with \"test\":\ntest\ntest2\n2 locks found\n", $txt); self::assertEquals("Listing all Locks starting with \"test\":\ntest\ntest2\n2 locks found\n", $txt);
} }
public function testDelLock() public function testDelLock()
@ -96,7 +97,7 @@ class LockConsoleTest extends ConsoleTest
$console->setArgument(0, 'del'); $console->setArgument(0, 'del');
$console->setArgument(1, 'test'); $console->setArgument(1, 'test');
$txt = $this->dumpExecute($console); $txt = $this->dumpExecute($console);
$this->assertEquals("Lock 'test' released.\n", $txt); self::assertEquals("Lock 'test' released.\n", $txt);
} }
public function testDelUnknownLock() public function testDelUnknownLock()
@ -111,7 +112,7 @@ class LockConsoleTest extends ConsoleTest
$console->setArgument(0, 'del'); $console->setArgument(0, 'del');
$console->setArgument(1, 'test'); $console->setArgument(1, 'test');
$txt = $this->dumpExecute($console); $txt = $this->dumpExecute($console);
$this->assertEquals("Couldn't release Lock 'test'\n", $txt); self::assertEquals("Couldn't release Lock 'test'\n", $txt);
} }
public function testSetLock() public function testSetLock()
@ -131,7 +132,7 @@ class LockConsoleTest extends ConsoleTest
$console->setArgument(0, 'set'); $console->setArgument(0, 'set');
$console->setArgument(1, 'test'); $console->setArgument(1, 'test');
$txt = $this->dumpExecute($console); $txt = $this->dumpExecute($console);
$this->assertEquals("Lock 'test' acquired.\n", $txt); self::assertEquals("Lock 'test' acquired.\n", $txt);
} }
public function testSetLockIsLocked() public function testSetLockIsLocked()
@ -146,7 +147,7 @@ class LockConsoleTest extends ConsoleTest
$console->setArgument(0, 'set'); $console->setArgument(0, 'set');
$console->setArgument(1, 'test'); $console->setArgument(1, 'test');
$txt = $this->dumpExecute($console); $txt = $this->dumpExecute($console);
$this->assertEquals("[Error] 'test' is already set.\n", $txt); self::assertEquals("[Error] 'test' is already set.\n", $txt);
} }
public function testSetLockNotWorking() public function testSetLockNotWorking()
@ -166,7 +167,7 @@ class LockConsoleTest extends ConsoleTest
$console->setArgument(0, 'set'); $console->setArgument(0, 'set');
$console->setArgument(1, 'test'); $console->setArgument(1, 'test');
$txt = $this->dumpExecute($console); $txt = $this->dumpExecute($console);
$this->assertEquals("[Error] Unable to lock 'test'.\n", $txt); self::assertEquals("[Error] Unable to lock 'test'.\n", $txt);
} }
public function testReleaseAll() public function testReleaseAll()
@ -179,7 +180,7 @@ class LockConsoleTest extends ConsoleTest
$console = new Lock($this->appMode, $this->lockMock, $this->consoleArgv); $console = new Lock($this->appMode, $this->lockMock, $this->consoleArgv);
$console->setArgument(0, 'clear'); $console->setArgument(0, 'clear');
$txt = $this->dumpExecute($console); $txt = $this->dumpExecute($console);
$this->assertEquals("Locks successfully cleared.\n", $txt); self::assertEquals("Locks successfully cleared.\n", $txt);
} }
public function testReleaseAllFailed() public function testReleaseAllFailed()
@ -192,7 +193,7 @@ class LockConsoleTest extends ConsoleTest
$console = new Lock($this->appMode, $this->lockMock, $this->consoleArgv); $console = new Lock($this->appMode, $this->lockMock, $this->consoleArgv);
$console->setArgument(0, 'clear'); $console->setArgument(0, 'clear');
$txt = $this->dumpExecute($console); $txt = $this->dumpExecute($console);
$this->assertEquals("[Error] Unable to clear the locks.\n", $txt); self::assertEquals("[Error] Unable to clear the locks.\n", $txt);
} }
public function testGetHelp() public function testGetHelp()
@ -229,6 +230,6 @@ HELP;
$txt = $this->dumpExecute($console); $txt = $this->dumpExecute($console);
$this->assertEquals($txt, $theHelp); self::assertEquals($txt, $theHelp);
} }
} }

View file

@ -23,6 +23,7 @@ namespace Friendica\Test\src\Console;
use Friendica\Console\ServerBlock; use Friendica\Console\ServerBlock;
use Friendica\Core\Config\IConfig; use Friendica\Core\Config\IConfig;
use Mockery;
class ServerBlockConsoleTest extends ConsoleTest class ServerBlockConsoleTest extends ConsoleTest
{ {
@ -36,12 +37,16 @@ class ServerBlockConsoleTest extends ConsoleTest
'reason' => 'Illegal content', 'reason' => 'Illegal content',
] ]
]; ];
/**
* @var IConfig|Mockery\LegacyMockInterface|Mockery\MockInterface
*/
private $configMock;
protected function setUp() protected function setUp()
{ {
parent::setUp(); parent::setUp();
$this->configMock = \Mockery::mock(IConfig::class); $this->configMock = Mockery::mock(IConfig::class);
} }
/** /**
@ -69,7 +74,7 @@ class ServerBlockConsoleTest extends ConsoleTest
CONS; CONS;
$this->assertEquals($output, $txt); self::assertEquals($output, $txt);
} }
/** /**
@ -101,7 +106,7 @@ CONS;
$console->setArgument(2, 'I like it!'); $console->setArgument(2, 'I like it!');
$txt = $this->dumpExecute($console); $txt = $this->dumpExecute($console);
$this->assertEquals('The domain \'testme.now\' is now blocked. (Reason: \'I like it!\')' . PHP_EOL, $txt); self::assertEquals('The domain \'testme.now\' is now blocked. (Reason: \'I like it!\')' . PHP_EOL, $txt);
} }
/** /**
@ -132,7 +137,7 @@ CONS;
$console->setArgument(1, 'testme.now'); $console->setArgument(1, 'testme.now');
$txt = $this->dumpExecute($console); $txt = $this->dumpExecute($console);
$this->assertEquals('The domain \'testme.now\' is now blocked. (Reason: \'' . ServerBlock::DEFAULT_REASON . '\')' . PHP_EOL, $txt); self::assertEquals('The domain \'testme.now\' is now blocked. (Reason: \'' . ServerBlock::DEFAULT_REASON . '\')' . PHP_EOL, $txt);
} }
/** /**
@ -169,7 +174,7 @@ CONS;
$console->setArgument(2, 'Other reason'); $console->setArgument(2, 'Other reason');
$txt = $this->dumpExecute($console); $txt = $this->dumpExecute($console);
$this->assertEquals('The domain \'pod.ordoevangelistarum.com\' is now updated. (Reason: \'Other reason\')' . PHP_EOL, $txt); self::assertEquals('The domain \'pod.ordoevangelistarum.com\' is now updated. (Reason: \'Other reason\')' . PHP_EOL, $txt);
} }
/** /**
@ -201,7 +206,7 @@ CONS;
$console->setArgument(1, 'pod.ordoevangelistarum.com'); $console->setArgument(1, 'pod.ordoevangelistarum.com');
$txt = $this->dumpExecute($console); $txt = $this->dumpExecute($console);
$this->assertEquals('The domain \'pod.ordoevangelistarum.com\' is not more blocked' . PHP_EOL, $txt); self::assertEquals('The domain \'pod.ordoevangelistarum.com\' is not more blocked' . PHP_EOL, $txt);
} }
/** /**
@ -213,7 +218,7 @@ CONS;
$console->setArgument(0, 'wrongcommand'); $console->setArgument(0, 'wrongcommand');
$txt = $this->dumpExecute($console); $txt = $this->dumpExecute($console);
$this->assertStringStartsWith('[Warning] Unknown command', $txt); self::assertStringStartsWith('[Warning] Unknown command', $txt);
} }
/** /**
@ -232,7 +237,7 @@ CONS;
$console->setArgument(1, 'not.exiting'); $console->setArgument(1, 'not.exiting');
$txt = $this->dumpExecute($console); $txt = $this->dumpExecute($console);
$this->assertEquals('The domain \'not.exiting\' is not blocked.' . PHP_EOL, $txt); self::assertEquals('The domain \'not.exiting\' is not blocked.' . PHP_EOL, $txt);
} }
/** /**
@ -244,7 +249,7 @@ CONS;
$console->setArgument(0, 'add'); $console->setArgument(0, 'add');
$txt = $this->dumpExecute($console); $txt = $this->dumpExecute($console);
$this->assertStringStartsWith('[Warning] Add needs a domain and optional a reason.', $txt); self::assertStringStartsWith('[Warning] Add needs a domain and optional a reason.', $txt);
} }
/** /**
@ -275,7 +280,7 @@ CONS;
$console->setArgument(1, 'testme.now'); $console->setArgument(1, 'testme.now');
$txt = $this->dumpExecute($console); $txt = $this->dumpExecute($console);
$this->assertEquals('Couldn\'t save \'testme.now\' as blocked server' . PHP_EOL, $txt); self::assertEquals('Couldn\'t save \'testme.now\' as blocked server' . PHP_EOL, $txt);
} }
/** /**
@ -307,7 +312,7 @@ CONS;
$console->setArgument(1, 'pod.ordoevangelistarum.com'); $console->setArgument(1, 'pod.ordoevangelistarum.com');
$txt = $this->dumpExecute($console); $txt = $this->dumpExecute($console);
$this->assertEquals('Couldn\'t remove \'pod.ordoevangelistarum.com\' from blocked servers' . PHP_EOL, $txt); self::assertEquals('Couldn\'t remove \'pod.ordoevangelistarum.com\' from blocked servers' . PHP_EOL, $txt);
} }
/** /**
@ -319,7 +324,7 @@ CONS;
$console->setArgument(0, 'remove'); $console->setArgument(0, 'remove');
$txt = $this->dumpExecute($console); $txt = $this->dumpExecute($console);
$this->assertStringStartsWith('[Warning] Remove needs a second parameter.', $txt); self::assertStringStartsWith('[Warning] Remove needs a second parameter.', $txt);
} }
/** /**
@ -357,6 +362,6 @@ Options
HELP; HELP;
$this->assertEquals($help, $txt); self::assertEquals($help, $txt);
} }
} }

View file

@ -27,6 +27,6 @@ class ItemTest extends MockedTest
{ {
public function testDetermineCategoriesTerms() public function testDetermineCategoriesTerms()
{ {
$this->markTestIncomplete('Test data needed.'); static::markTestIncomplete('Test data needed.');
} }
} }

View file

@ -21,6 +21,8 @@
namespace Friendica\Test\src\Content; namespace Friendica\Test\src\Content;
use Friendica\Content\PageInfo;
/** /**
* Class PageInfoMock * Class PageInfoMock
* *
@ -29,7 +31,7 @@ namespace Friendica\Test\src\Content;
* @method static string|null getRelevantUrlFromBody(string $body, $searchNakedUrls = false) * @method static string|null getRelevantUrlFromBody(string $body, $searchNakedUrls = false)
* @method static string stripTrailingUrlFromBody(string $body, string $url) * @method static string stripTrailingUrlFromBody(string $body, string $url)
*/ */
class PageInfoMock extends \Friendica\Content\PageInfo class PageInfoMock extends PageInfo
{ {
public static function __callStatic($name, $arguments) public static function __callStatic($name, $arguments)
{ {

View file

@ -87,7 +87,7 @@ class PageInfoTest extends MockedTest
*/ */
public function testGetRelevantUrlFromBody($expected, string $body, bool $searchNakedUrls = false) public function testGetRelevantUrlFromBody($expected, string $body, bool $searchNakedUrls = false)
{ {
$this->assertSame($expected, PageInfoMock::getRelevantUrlFromBody($body, $searchNakedUrls)); self::assertSame($expected, PageInfoMock::getRelevantUrlFromBody($body, $searchNakedUrls));
} }
public function dataStripTrailingUrlFromBody() public function dataStripTrailingUrlFromBody()
@ -135,6 +135,6 @@ class PageInfoTest extends MockedTest
*/ */
public function testStripTrailingUrlFromBody(string $expected, string $body, string $url) public function testStripTrailingUrlFromBody(string $expected, string $body, string $url)
{ {
$this->assertSame($expected, PageInfoMock::stripTrailingUrlFromBody($body, $url)); self::assertSame($expected, PageInfoMock::stripTrailingUrlFromBody($body, $url));
} }
} }

View file

@ -9,6 +9,7 @@
namespace Friendica\Test\src\Content; namespace Friendica\Test\src\Content;
use Friendica\Content\Smilies; use Friendica\Content\Smilies;
use Friendica\Network\HTTPException\InternalServerErrorException;
use Friendica\Test\MockedTest; use Friendica\Test\MockedTest;
use Friendica\Test\Util\AppMockTrait; use Friendica\Test\Util\AppMockTrait;
use Friendica\Test\Util\VFSTrait; use Friendica\Test\Util\VFSTrait;
@ -52,16 +53,18 @@ class SmiliesTest extends MockedTest
/** /**
* Test replace smilies in different texts * Test replace smilies in different texts
*
* @dataProvider dataLinks * @dataProvider dataLinks
* *
* @param string $text Test string * @param string $text Test string
* @param array $smilies List of smilies to replace * @param array $smilies List of smilies to replace
* @param string $expected Expected result * @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); $output = Smilies::replaceFromArray($text, $smilies);
$this->assertEquals($expected, $output); self::assertEquals($expected, $output);
} }
} }

View file

@ -57,6 +57,6 @@ class VideoTest extends MockedTest
{ {
$bbCodeVideo = new Video(); $bbCodeVideo = new Video();
$this->assertEquals($assert, $bbCodeVideo->transform($input)); self::assertEquals($assert, $bbCodeVideo->transform($input));
} }
} }

View file

@ -24,9 +24,11 @@ namespace Friendica\Test\src\Content\Text;
use Friendica\App\BaseURL; use Friendica\App\BaseURL;
use Friendica\Content\Text\BBCode; use Friendica\Content\Text\BBCode;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Network\HTTPException\InternalServerErrorException;
use Friendica\Test\MockedTest; use Friendica\Test\MockedTest;
use Friendica\Test\Util\AppMockTrait; use Friendica\Test\Util\AppMockTrait;
use Friendica\Test\Util\VFSTrait; use Friendica\Test\Util\VFSTrait;
use Mockery;
class BBCodeTest extends MockedTest class BBCodeTest extends MockedTest
{ {
@ -62,13 +64,13 @@ class BBCodeTest extends MockedTest
->with('system', 'big_emojis') ->with('system', 'big_emojis')
->andReturn(false); ->andReturn(false);
$l10nMock = \Mockery::mock(L10n::class); $l10nMock = Mockery::mock(L10n::class);
$l10nMock->shouldReceive('t')->withAnyArgs()->andReturnUsing(function ($args) { return $args; }); $l10nMock->shouldReceive('t')->withAnyArgs()->andReturnUsing(function ($args) { return $args; });
$this->dice->shouldReceive('create') $this->dice->shouldReceive('create')
->with(L10n::class) ->with(L10n::class)
->andReturn($l10nMock); ->andReturn($l10nMock);
$baseUrlMock = \Mockery::mock(BaseURL::class); $baseUrlMock = Mockery::mock(BaseURL::class);
$baseUrlMock->shouldReceive('get')->withAnyArgs()->andReturn('friendica.local'); $baseUrlMock->shouldReceive('get')->withAnyArgs()->andReturn('friendica.local');
$this->dice->shouldReceive('create') $this->dice->shouldReceive('create')
->with(BaseURL::class) ->with(BaseURL::class)
@ -158,20 +160,22 @@ class BBCodeTest extends MockedTest
/** /**
* Test convert different links inside a text * Test convert different links inside a text
*
* @dataProvider dataLinks * @dataProvider dataLinks
* *
* @param string $data The data to text * @param string $data The data to text
* @param bool $assertHTML True, if the link is a HTML link (<a href...>...</a>) * @param bool $assertHTML True, if the link is a HTML link (<a href...>...</a>)
* @throws \Friendica\Network\HTTPException\InternalServerErrorException *
* @throws InternalServerErrorException
*/ */
public function testAutoLinking($data, $assertHTML) public function testAutoLinking(string $data, bool $assertHTML)
{ {
$output = BBCode::convert($data); $output = BBCode::convert($data);
$assert = '<a href="' . $data . '" target="_blank" rel="noopener noreferrer">' . $data . '</a>'; $assert = '<a href="' . $data . '" target="_blank" rel="noopener noreferrer">' . $data . '</a>';
if ($assertHTML) { if ($assertHTML) {
$this->assertEquals($assert, $output); self::assertEquals($assert, $output);
} else { } else {
$this->assertNotEquals($assert, $output); self::assertNotEquals($assert, $output);
} }
} }
@ -258,13 +262,14 @@ class BBCodeTest extends MockedTest
* @param bool $try_oembed Whether to convert multimedia BBCode tag * @param bool $try_oembed Whether to convert multimedia BBCode tag
* @param int $simpleHtml BBCode::convert method $simple_html parameter value, optional. * @param int $simpleHtml BBCode::convert method $simple_html parameter value, optional.
* @param bool $forPlaintext BBCode::convert method $for_plaintext 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); $actual = BBCode::convert($text, $try_oembed, $simpleHtml, $forPlaintext);
$this->assertEquals($expectedHtml, $actual); self::assertEquals($expectedHtml, $actual);
} }
public function dataBBCodesToMarkdown() public function dataBBCodesToMarkdown()
@ -290,15 +295,16 @@ class BBCodeTest extends MockedTest
* *
* @dataProvider dataBBCodesToMarkdown * @dataProvider dataBBCodesToMarkdown
* *
* @param string $expected Expected Markdown output * @param string $expected Expected Markdown output
* @param string $text BBCode text * @param string $text BBCode text
* @param bool $for_diaspora * @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); $actual = BBCode::toMarkdown($text, $for_diaspora);
$this->assertEquals($expected, $actual); self::assertEquals($expected, $actual);
} }
} }

View file

@ -21,7 +21,9 @@
namespace Friendica\Test\src\Content\Text; namespace Friendica\Test\src\Content\Text;
use Exception;
use Friendica\Content\Text\HTML; use Friendica\Content\Text\HTML;
use Friendica\Network\HTTPException\InternalServerErrorException;
use Friendica\Test\MockedTest; use Friendica\Test\MockedTest;
use Friendica\Test\Util\AppMockTrait; use Friendica\Test\Util\AppMockTrait;
use Friendica\Test\Util\VFSTrait; use Friendica\Test\Util\VFSTrait;
@ -61,13 +63,14 @@ class HTMLTest extends MockedTest
* *
* @param string $input The Markdown text to test * @param string $input The Markdown text to test
* @param string $expected The expected HTML output * @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); $output = HTML::toPlaintext($input, 0);
$this->assertEquals($expected, $output); self::assertEquals($expected, $output);
} }
public function dataHTMLText() public function dataHTMLText()
@ -91,12 +94,13 @@ class HTMLTest extends MockedTest
* *
* @param string $expectedBBCode Expected BBCode output * @param string $expectedBBCode Expected BBCode output
* @param string $html HTML text * @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); $actual = HTML::toBBCode($html);
$this->assertEquals($expectedBBCode, $actual); self::assertEquals($expectedBBCode, $actual);
} }
} }

View file

@ -21,7 +21,7 @@
namespace Friendica\Test\src\Content\Text; namespace Friendica\Test\src\Content\Text;
use Friendica\Content\Text\HTML; use Exception;
use Friendica\Content\Text\Markdown; use Friendica\Content\Text\Markdown;
use Friendica\Test\MockedTest; use Friendica\Test\MockedTest;
use Friendica\Test\Util\AppMockTrait; use Friendica\Test\Util\AppMockTrait;
@ -57,17 +57,19 @@ class MarkdownTest extends MockedTest
/** /**
* Test convert different input Markdown text into HTML * Test convert different input Markdown text into HTML
*
* @dataProvider dataMarkdown * @dataProvider dataMarkdown
* *
* @param string $input The Markdown text to test * @param string $input The Markdown text to test
* @param string $expected The expected HTML output * @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); $output = Markdown::convert($input);
$this->assertEquals($expected, $output); self::assertEquals($expected, $output);
} }
public function dataMarkdownText() public function dataMarkdownText()
@ -87,12 +89,11 @@ class MarkdownTest extends MockedTest
* *
* @param string $expectedBBCode Expected BBCode output * @param string $expectedBBCode Expected BBCode output
* @param string $html Markdown text * @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); $actual = Markdown::toBBCode($html);
$this->assertEquals($expectedBBCode, $actual); self::assertEquals($expectedBBCode, $actual);
} }
} }

View file

@ -31,7 +31,7 @@ class APCuCacheTest extends MemoryCacheTest
protected function setUp() protected function setUp()
{ {
if (!APCuCache::isAvailable()) { if (!APCuCache::isAvailable()) {
$this->markTestSkipped('APCu is not available'); static::markTestSkipped('APCu is not available');
} }
parent::setUp(); parent::setUp();
@ -43,7 +43,7 @@ class APCuCacheTest extends MemoryCacheTest
return $this->cache; return $this->cache;
} }
public function tearDown() protected function tearDown()
{ {
$this->cache->clear(false); $this->cache->clear(false);
parent::tearDown(); parent::tearDown();

View file

@ -31,7 +31,7 @@ class ArrayCacheTest extends MemoryCacheTest
return $this->cache; return $this->cache;
} }
public function tearDown() protected function tearDown()
{ {
$this->cache->clear(false); $this->cache->clear(false);
parent::tearDown(); parent::tearDown();

View file

@ -21,6 +21,8 @@
namespace Friendica\Test\src\Core\Cache; namespace Friendica\Test\src\Core\Cache;
use Friendica\Core\Cache\ICache;
use Friendica\Core\Cache\IMemoryCache;
use Friendica\Test\MockedTest; use Friendica\Test\MockedTest;
use Friendica\Util\PidFile; use Friendica\Util\PidFile;
@ -32,12 +34,12 @@ abstract class CacheTest extends MockedTest
protected $startTime = 1417011228; protected $startTime = 1417011228;
/** /**
* @var \Friendica\Core\Cache\ICache * @var ICache
*/ */
protected $instance; protected $instance;
/** /**
* @var \Friendica\Core\Cache\IMemoryCache * @var IMemoryCache
*/ */
protected $cache; protected $cache;
@ -95,27 +97,27 @@ abstract class CacheTest extends MockedTest
* @param mixed $value1 a first * @param mixed $value1 a first
* @param mixed $value2 a second * @param mixed $value2 a second
*/ */
function testSimple($value1, $value2) public function testSimple($value1, $value2)
{ {
$this->assertNull($this->instance->get('value1')); self::assertNull($this->instance->get('value1'));
$this->instance->set('value1', $value1); $this->instance->set('value1', $value1);
$received = $this->instance->get('value1'); $received = $this->instance->get('value1');
$this->assertEquals($value1, $received, 'Value received from cache not equal to the original'); self::assertEquals($value1, $received, 'Value received from cache not equal to the original');
$this->instance->set('value1', $value2); $this->instance->set('value1', $value2);
$received = $this->instance->get('value1'); $received = $this->instance->get('value1');
$this->assertEquals($value2, $received, 'Value not overwritten by second set'); self::assertEquals($value2, $received, 'Value not overwritten by second set');
$this->instance->set('value2', $value1); $this->instance->set('value2', $value1);
$received2 = $this->instance->get('value2'); $received2 = $this->instance->get('value2');
$this->assertEquals($value2, $received, 'Value changed while setting other variable'); self::assertEquals($value2, $received, 'Value changed while setting other variable');
$this->assertEquals($value1, $received2, 'Second value not equal to original'); self::assertEquals($value1, $received2, 'Second value not equal to original');
$this->assertNull($this->instance->get('not_set'), 'Unset value not equal to null'); self::assertNull($this->instance->get('not_set'), 'Unset value not equal to null');
$this->assertTrue($this->instance->delete('value1')); self::assertTrue($this->instance->delete('value1'));
$this->assertNull($this->instance->get('value1')); self::assertNull($this->instance->get('value1'));
} }
/** /**
@ -127,15 +129,14 @@ abstract class CacheTest extends MockedTest
* @param mixed $value3 a third * @param mixed $value3 a third
* @param mixed $value4 a fourth * @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_value1', $value1);
$this->instance->set('1_value2', $value2); $this->instance->set('1_value2', $value2);
$this->instance->set('2_value1', $value3); $this->instance->set('2_value1', $value3);
$this->instance->set('3_value1', $value4); $this->instance->set('3_value1', $value4);
$this->assertEquals([ self::assertEquals([
'1_value1' => $value1, '1_value1' => $value1,
'1_value2' => $value2, '1_value2' => $value2,
'2_value1' => $value3, '2_value1' => $value3,
@ -147,9 +148,9 @@ abstract class CacheTest extends MockedTest
'3_value1' => $this->instance->get('3_value1'), '3_value1' => $this->instance->get('3_value1'),
]); ]);
$this->assertTrue($this->instance->clear()); self::assertTrue($this->instance->clear());
$this->assertEquals([ self::assertEquals([
'1_value1' => $value1, '1_value1' => $value1,
'1_value2' => $value2, '1_value2' => $value2,
'2_value1' => $value3, '2_value1' => $value3,
@ -161,9 +162,9 @@ abstract class CacheTest extends MockedTest
'3_value1' => $this->instance->get('3_value1'), '3_value1' => $this->instance->get('3_value1'),
]); ]);
$this->assertTrue($this->instance->clear(false)); self::assertTrue($this->instance->clear(false));
$this->assertEquals([ self::assertEquals([
'1_value1' => null, '1_value1' => null,
'1_value2' => null, '1_value2' => null,
'2_value3' => null, '2_value3' => null,
@ -179,34 +180,34 @@ abstract class CacheTest extends MockedTest
/** /**
* @medium * @medium
*/ */
function testTTL() public function testTTL()
{ {
$this->markTestSkipped('taking too much time without mocking'); static::markTestSkipped('taking too much time without mocking');
$this->assertNull($this->instance->get('value1')); self::assertNull($this->instance->get('value1'));
$value = 'foobar'; $value = 'foobar';
$this->instance->set('value1', $value, 1); $this->instance->set('value1', $value, 1);
$received = $this->instance->get('value1'); $received = $this->instance->get('value1');
$this->assertEquals($value, $received, 'Value received from cache not equal to the original'); self::assertEquals($value, $received, 'Value received from cache not equal to the original');
sleep(2); sleep(2);
$this->assertNull($this->instance->get('value1')); self::assertNull($this->instance->get('value1'));
} }
/** /**
* @small * @small
* *
* @param $data mixed the data to store in the cache * @param mixed $data the data to store in the cache
* *
* @dataProvider dataTypesInCache * @dataProvider dataTypesInCache
*/ */
function testDifferentTypesInCache($data) public function testDifferentTypesInCache($data)
{ {
$this->instance->set('val', $data); $this->instance->set('val', $data);
$received = $this->instance->get('val'); $received = $this->instance->get('val');
$this->assertEquals($data, $received, 'Value type changed from ' . gettype($data) . ' to ' . gettype($received)); self::assertEquals($data, $received, 'Value type changed from ' . gettype($data) . ' to ' . gettype($received));
} }
/** /**
@ -220,20 +221,20 @@ abstract class CacheTest extends MockedTest
*/ */
public function testGetAllKeys($value1, $value2, $value3) public function testGetAllKeys($value1, $value2, $value3)
{ {
$this->assertTrue($this->instance->set('value1', $value1)); self::assertTrue($this->instance->set('value1', $value1));
$this->assertTrue($this->instance->set('value2', $value2)); self::assertTrue($this->instance->set('value2', $value2));
$this->assertTrue($this->instance->set('test_value3', $value3)); self::assertTrue($this->instance->set('test_value3', $value3));
$list = $this->instance->getAllKeys(); $list = $this->instance->getAllKeys();
$this->assertContains('value1', $list); self::assertContains('value1', $list);
$this->assertContains('value2', $list); self::assertContains('value2', $list);
$this->assertContains('test_value3', $list); self::assertContains('test_value3', $list);
$list = $this->instance->getAllKeys('test'); $list = $this->instance->getAllKeys('test');
$this->assertContains('test_value3', $list); self::assertContains('test_value3', $list);
$this->assertNotContains('value1', $list); self::assertNotContains('value1', $list);
$this->assertNotContains('value2', $list); self::assertNotContains('value2', $list);
} }
} }

View file

@ -28,6 +28,7 @@ use Friendica\Test\Util\Database\StaticDatabase;
use Friendica\Test\Util\VFSTrait; use Friendica\Test\Util\VFSTrait;
use Friendica\Util\ConfigFileLoader; use Friendica\Util\ConfigFileLoader;
use Friendica\Util\Profiler; use Friendica\Util\Profiler;
use Mockery;
use Psr\Log\NullLogger; use Psr\Log\NullLogger;
class DatabaseCacheTest extends CacheTest class DatabaseCacheTest extends CacheTest
@ -45,7 +46,7 @@ class DatabaseCacheTest extends CacheTest
protected function getInstance() protected function getInstance()
{ {
$logger = new NullLogger(); $logger = new NullLogger();
$profiler = \Mockery::mock(Profiler::class); $profiler = Mockery::mock(Profiler::class);
$profiler->shouldReceive('saveTimestamp')->withAnyArgs()->andReturn(true); $profiler->shouldReceive('saveTimestamp')->withAnyArgs()->andReturn(true);
// load real config to avoid mocking every config-entry which is related to the Database class // load real config to avoid mocking every config-entry which is related to the Database class
@ -59,7 +60,7 @@ class DatabaseCacheTest extends CacheTest
return $this->cache; return $this->cache;
} }
public function tearDown() protected function tearDown()
{ {
$this->cache->clear(false); $this->cache->clear(false);
parent::tearDown(); parent::tearDown();

View file

@ -21,8 +21,10 @@
namespace Friendica\Test\src\Core\Cache; namespace Friendica\Test\src\Core\Cache;
use Exception;
use Friendica\Core\Cache\MemcacheCache; use Friendica\Core\Cache\MemcacheCache;
use Friendica\Core\Config\IConfig; use Friendica\Core\Config\IConfig;
use Mockery;
/** /**
* @requires extension memcache * @requires extension memcache
@ -32,7 +34,7 @@ class MemcacheCacheTest extends MemoryCacheTest
{ {
protected function getInstance() protected function getInstance()
{ {
$configMock = \Mockery::mock(IConfig::class); $configMock = Mockery::mock(IConfig::class);
$host = $_SERVER['MEMCACHE_HOST'] ?? 'localhost'; $host = $_SERVER['MEMCACHE_HOST'] ?? 'localhost';
$port = $_SERVER['MEMCACHE_PORT'] ?? '11211'; $port = $_SERVER['MEMCACHE_PORT'] ?? '11211';
@ -48,13 +50,13 @@ class MemcacheCacheTest extends MemoryCacheTest
try { try {
$this->cache = new MemcacheCache($host, $configMock); $this->cache = new MemcacheCache($host, $configMock);
} catch (\Exception $e) { } catch (Exception $e) {
$this->markTestSkipped('Memcache is not available'); static::markTestSkipped('Memcache is not available');
} }
return $this->cache; return $this->cache;
} }
public function tearDown() protected function tearDown()
{ {
$this->cache->clear(false); $this->cache->clear(false);
parent::tearDown(); parent::tearDown();
@ -67,6 +69,6 @@ class MemcacheCacheTest extends MemoryCacheTest
*/ */
public function testGetAllKeys($value1, $value2, $value3) 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');
} }
} }

View file

@ -21,8 +21,10 @@
namespace Friendica\Test\src\Core\Cache; namespace Friendica\Test\src\Core\Cache;
use Exception;
use Friendica\Core\Cache\MemcachedCache; use Friendica\Core\Cache\MemcachedCache;
use Friendica\Core\Config\IConfig; use Friendica\Core\Config\IConfig;
use Mockery;
use Psr\Log\NullLogger; use Psr\Log\NullLogger;
/** /**
@ -33,7 +35,7 @@ class MemcachedCacheTest extends MemoryCacheTest
{ {
protected function getInstance() protected function getInstance()
{ {
$configMock = \Mockery::mock(IConfig::class); $configMock = Mockery::mock(IConfig::class);
$host = $_SERVER['MEMCACHED_HOST'] ?? 'localhost'; $host = $_SERVER['MEMCACHED_HOST'] ?? 'localhost';
$port = $_SERVER['MEMCACHED_PORT'] ?? '11211'; $port = $_SERVER['MEMCACHED_PORT'] ?? '11211';
@ -47,13 +49,13 @@ class MemcachedCacheTest extends MemoryCacheTest
try { try {
$this->cache = new MemcachedCache($host, $configMock, $logger); $this->cache = new MemcachedCache($host, $configMock, $logger);
} catch (\Exception $exception) { } catch (Exception $exception) {
$this->markTestSkipped('Memcached is not available'); static::markTestSkipped('Memcached is not available');
} }
return $this->cache; return $this->cache;
} }
public function tearDown() protected function tearDown()
{ {
$this->cache->clear(false); $this->cache->clear(false);
parent::tearDown(); parent::tearDown();
@ -66,6 +68,6 @@ class MemcachedCacheTest extends MemoryCacheTest
*/ */
public function testGetAllKeys($value1, $value2, $value3) 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');
} }
} }

View file

@ -21,12 +21,13 @@
namespace Friendica\Test\src\Core\Cache; namespace Friendica\Test\src\Core\Cache;
use Exception;
use Friendica\Core\Cache\IMemoryCache; use Friendica\Core\Cache\IMemoryCache;
abstract class MemoryCacheTest extends CacheTest abstract class MemoryCacheTest extends CacheTest
{ {
/** /**
* @var \Friendica\Core\Cache\IMemoryCache * @var IMemoryCache
*/ */
protected $instance; protected $instance;
@ -35,7 +36,7 @@ abstract class MemoryCacheTest extends CacheTest
parent::setUp(); parent::setUp();
if (!($this->instance instanceof IMemoryCache)) { if (!($this->instance instanceof IMemoryCache)) {
throw new \Exception('MemoryCacheTest unsupported'); throw new Exception('MemoryCacheTest unsupported');
} }
} }
@ -43,89 +44,89 @@ abstract class MemoryCacheTest extends CacheTest
* @small * @small
* @dataProvider dataSimple * @dataProvider dataSimple
*/ */
function testCompareSet($value1, $value2) public function testCompareSet($value1, $value2)
{ {
$this->assertNull($this->instance->get('value1')); self::assertNull($this->instance->get('value1'));
$this->instance->add('value1', $value1); $this->instance->add('value1', $value1);
$received = $this->instance->get('value1'); $received = $this->instance->get('value1');
$this->assertEquals($value1, $received, 'Value received from cache not equal to the original'); self::assertEquals($value1, $received, 'Value received from cache not equal to the original');
$this->instance->compareSet('value1', $value1, $value2); $this->instance->compareSet('value1', $value1, $value2);
$received = $this->instance->get('value1'); $received = $this->instance->get('value1');
$this->assertEquals($value2, $received, 'Value not overwritten by compareSet'); self::assertEquals($value2, $received, 'Value not overwritten by compareSet');
} }
/** /**
* @small * @small
* @dataProvider dataSimple * @dataProvider dataSimple
*/ */
function testNegativeCompareSet($value1, $value2) public function testNegativeCompareSet($value1, $value2)
{ {
$this->assertNull($this->instance->get('value1')); self::assertNull($this->instance->get('value1'));
$this->instance->add('value1', $value1); $this->instance->add('value1', $value1);
$received = $this->instance->get('value1'); $received = $this->instance->get('value1');
$this->assertEquals($value1, $received, 'Value received from cache not equal to the original'); self::assertEquals($value1, $received, 'Value received from cache not equal to the original');
$this->instance->compareSet('value1', 'wrong', $value2); $this->instance->compareSet('value1', 'wrong', $value2);
$received = $this->instance->get('value1'); $received = $this->instance->get('value1');
$this->assertNotEquals($value2, $received, 'Value was wrongly overwritten by compareSet'); self::assertNotEquals($value2, $received, 'Value was wrongly overwritten by compareSet');
$this->assertEquals($value1, $received, 'Value was wrongly overwritten by any other value'); self::assertEquals($value1, $received, 'Value was wrongly overwritten by any other value');
} }
/** /**
* @small * @small
* @dataProvider dataSimple * @dataProvider dataSimple
*/ */
function testCompareDelete($data) public function testCompareDelete($data)
{ {
$this->assertNull($this->instance->get('value1')); self::assertNull($this->instance->get('value1'));
$this->instance->add('value1', $data); $this->instance->add('value1', $data);
$received = $this->instance->get('value1'); $received = $this->instance->get('value1');
$this->assertEquals($data, $received, 'Value received from cache not equal to the original'); self::assertEquals($data, $received, 'Value received from cache not equal to the original');
$this->instance->compareDelete('value1', $data); $this->instance->compareDelete('value1', $data);
$this->assertNull($this->instance->get('value1'), 'Value was not deleted by compareDelete'); self::assertNull($this->instance->get('value1'), 'Value was not deleted by compareDelete');
} }
/** /**
* @small * @small
* @dataProvider dataSimple * @dataProvider dataSimple
*/ */
function testNegativeCompareDelete($data) public function testNegativeCompareDelete($data)
{ {
$this->assertNull($this->instance->get('value1')); self::assertNull($this->instance->get('value1'));
$this->instance->add('value1', $data); $this->instance->add('value1', $data);
$received = $this->instance->get('value1'); $received = $this->instance->get('value1');
$this->assertEquals($data, $received, 'Value received from cache not equal to the original'); self::assertEquals($data, $received, 'Value received from cache not equal to the original');
$this->instance->compareDelete('value1', 'wrong'); $this->instance->compareDelete('value1', 'wrong');
$this->assertNotNull($this->instance->get('value1'), 'Value was wrongly compareDeleted'); self::assertNotNull($this->instance->get('value1'), 'Value was wrongly compareDeleted');
$this->instance->compareDelete('value1', $data); $this->instance->compareDelete('value1', $data);
$this->assertNull($this->instance->get('value1'), 'Value was wrongly NOT deleted by compareDelete'); self::assertNull($this->instance->get('value1'), 'Value was wrongly NOT deleted by compareDelete');
} }
/** /**
* @small * @small
* @dataProvider dataSimple * @dataProvider dataSimple
*/ */
function testAdd($value1, $value2) public function testAdd($value1, $value2)
{ {
$this->assertNull($this->instance->get('value1')); self::assertNull($this->instance->get('value1'));
$this->instance->add('value1', $value1); $this->instance->add('value1', $value1);
$this->instance->add('value1', $value2); $this->instance->add('value1', $value2);
$received = $this->instance->get('value1'); $received = $this->instance->get('value1');
$this->assertNotEquals($value2, $received, 'Value was wrongly overwritten by add'); self::assertNotEquals($value2, $received, 'Value was wrongly overwritten by add');
$this->assertEquals($value1, $received, 'Value was wrongly overwritten by any other value'); self::assertEquals($value1, $received, 'Value was wrongly overwritten by any other value');
$this->instance->delete('value1'); $this->instance->delete('value1');
$this->instance->add('value1', $value2); $this->instance->add('value1', $value2);
$received = $this->instance->get('value1'); $received = $this->instance->get('value1');
$this->assertEquals($value2, $received, 'Value was not overwritten by add'); self::assertEquals($value2, $received, 'Value was not overwritten by add');
$this->assertNotEquals($value1, $received, 'Value was not overwritten by any other value'); self::assertNotEquals($value1, $received, 'Value was not overwritten by any other value');
} }
} }

View file

@ -21,8 +21,10 @@
namespace Friendica\Test\src\Core\Cache; namespace Friendica\Test\src\Core\Cache;
use Exception;
use Friendica\Core\Cache\RedisCache; use Friendica\Core\Cache\RedisCache;
use Friendica\Core\Config\IConfig; use Friendica\Core\Config\IConfig;
use Mockery;
/** /**
* @requires extension redis * @requires extension redis
@ -32,10 +34,10 @@ class RedisCacheTest extends MemoryCacheTest
{ {
protected function getInstance() protected function getInstance()
{ {
$configMock = \Mockery::mock(IConfig::class); $configMock = Mockery::mock(IConfig::class);
$host = $_SERVER['REDIS_HOST'] ?? 'localhost'; $host = $_SERVER['REDIS_HOST'] ?? 'localhost';
$port = $_SERVER['REDIS_PORT'] ?? null; $port = $_SERVER['REDIS_PORT'] ?? 6379;
$configMock $configMock
->shouldReceive('get') ->shouldReceive('get')
@ -49,7 +51,7 @@ class RedisCacheTest extends MemoryCacheTest
$configMock $configMock
->shouldReceive('get') ->shouldReceive('get')
->with('system', 'redis_db', 0) ->with('system', 'redis_db', 0)
->andReturn(3); ->andReturn(0);
$configMock $configMock
->shouldReceive('get') ->shouldReceive('get')
->with('system', 'redis_password') ->with('system', 'redis_password')
@ -57,13 +59,13 @@ class RedisCacheTest extends MemoryCacheTest
try { try {
$this->cache = new RedisCache($host, $configMock); $this->cache = new RedisCache($host, $configMock);
} catch (\Exception $e) { } catch (Exception $e) {
$this->markTestSkipped('Redis is not available.'); static::markTestSkipped('Redis is not available. Failure: ' . $e->getMessage());
} }
return $this->cache; return $this->cache;
} }
public function tearDown() protected function tearDown()
{ {
$this->cache->clear(false); $this->cache->clear(false);
parent::tearDown(); parent::tearDown();

View file

@ -24,6 +24,7 @@ namespace Friendica\Test\src\Core\Config;
use Friendica\Core\Config\Cache; use Friendica\Core\Config\Cache;
use Friendica\Test\MockedTest; use Friendica\Test\MockedTest;
use ParagonIE\HiddenString\HiddenString; use ParagonIE\HiddenString\HiddenString;
use stdClass;
class CacheTest extends MockedTest class CacheTest extends MockedTest
{ {
@ -52,7 +53,7 @@ class CacheTest extends MockedTest
{ {
foreach ($data as $cat => $values) { foreach ($data as $cat => $values) {
foreach ($values as $key => $value) { foreach ($values as $key => $value) {
$this->assertEquals($data[$cat][$key], $configCache->get($cat, $key)); self::assertEquals($data[$cat][$key], $configCache->get($cat, $key));
} }
} }
} }
@ -66,7 +67,7 @@ class CacheTest extends MockedTest
$configCache = new Cache(); $configCache = new Cache();
$configCache->load($data); $configCache->load($data);
$this->assertConfigValues($data, $configCache); self::assertConfigValues($data, $configCache);
} }
/** /**
@ -87,26 +88,26 @@ class CacheTest extends MockedTest
// doesn't override - Low Priority due Config file // doesn't override - Low Priority due Config file
$configCache->load($override, Cache::SOURCE_FILE); $configCache->load($override, Cache::SOURCE_FILE);
$this->assertConfigValues($data, $configCache); self::assertConfigValues($data, $configCache);
// override the value - High Prio due Server Env // override the value - High Prio due Server Env
$configCache->load($override, Cache::SOURCE_ENV); $configCache->load($override, Cache::SOURCE_ENV);
$this->assertEquals($override['system']['test'], $configCache->get('system', 'test')); self::assertEquals($override['system']['test'], $configCache->get('system', 'test'));
$this->assertEquals($override['system']['boolTrue'], $configCache->get('system', 'boolTrue')); self::assertEquals($override['system']['boolTrue'], $configCache->get('system', 'boolTrue'));
// Don't overwrite server ENV variables - even in load mode // Don't overwrite server ENV variables - even in load mode
$configCache->load($data, Cache::SOURCE_DB); $configCache->load($data, Cache::SOURCE_DB);
$this->assertEquals($override['system']['test'], $configCache->get('system', 'test')); self::assertEquals($override['system']['test'], $configCache->get('system', 'test'));
$this->assertEquals($override['system']['boolTrue'], $configCache->get('system', 'boolTrue')); self::assertEquals($override['system']['boolTrue'], $configCache->get('system', 'boolTrue'));
// Overwrite ENV variables with ENV variables // Overwrite ENV variables with ENV variables
$configCache->load($data, Cache::SOURCE_ENV); $configCache->load($data, Cache::SOURCE_ENV);
$this->assertConfigValues($data, $configCache); self::assertConfigValues($data, $configCache);
$this->assertNotEquals($override['system']['test'], $configCache->get('system', 'test')); self::assertNotEquals($override['system']['test'], $configCache->get('system', 'test'));
$this->assertNotEquals($override['system']['boolTrue'], $configCache->get('system', 'boolTrue')); self::assertNotEquals($override['system']['boolTrue'], $configCache->get('system', 'boolTrue'));
} }
/** /**
@ -118,15 +119,15 @@ class CacheTest extends MockedTest
// empty dataset // empty dataset
$configCache->load([]); $configCache->load([]);
$this->assertEmpty($configCache->getAll()); self::assertEmpty($configCache->getAll());
// wrong dataset // wrong dataset
$configCache->load(['system' => 'not_array']); $configCache->load(['system' => 'not_array']);
$this->assertEmpty($configCache->getAll()); self::assertEmpty($configCache->getAll());
// incomplete dataset (key is integer ID of the array) // incomplete dataset (key is integer ID of the array)
$configCache->load(['system' => ['value']]); $configCache->load(['system' => ['value']]);
$this->assertEquals('value', $configCache->get('system', 0)); self::assertEquals('value', $configCache->get('system', 0));
} }
/** /**
@ -140,8 +141,8 @@ class CacheTest extends MockedTest
$all = $configCache->getAll(); $all = $configCache->getAll();
$this->assertContains($data['system'], $all); self::assertContains($data['system'], $all);
$this->assertContains($data['config'], $all); self::assertContains($data['config'], $all);
} }
/** /**
@ -158,7 +159,7 @@ class CacheTest extends MockedTest
} }
} }
$this->assertConfigValues($data, $configCache); self::assertConfigValues($data, $configCache);
} }
/** /**
@ -168,7 +169,7 @@ class CacheTest extends MockedTest
{ {
$configCache = new Cache(); $configCache = new Cache();
$this->assertNull($configCache->get('something', 'value')); self::assertNull($configCache->get('something', 'value'));
} }
/** /**
@ -186,13 +187,13 @@ class CacheTest extends MockedTest
], ],
]); ]);
$this->assertEquals([ self::assertEquals([
'key1' => 'value1', 'key1' => 'value1',
'key2' => 'value2', 'key2' => 'value2',
], $configCache->get('system')); ], $configCache->get('system'));
// explicit null as key // explicit null as key
$this->assertEquals([ self::assertEquals([
'key1' => 'value1', 'key1' => 'value1',
'key2' => 'value2', 'key2' => 'value2',
], $configCache->get('system', null)); ], $configCache->get('system', null));
@ -212,7 +213,7 @@ class CacheTest extends MockedTest
} }
} }
$this->assertEmpty($configCache->getAll()); self::assertEmpty($configCache->getAll());
} }
/** /**
@ -229,7 +230,7 @@ class CacheTest extends MockedTest
] ]
]; ];
$this->assertEquals($diffConfig, $configCache->keyDiff($diffConfig)); self::assertEquals($diffConfig, $configCache->keyDiff($diffConfig));
} }
/** /**
@ -242,7 +243,7 @@ class CacheTest extends MockedTest
$diffConfig = $configCache->getAll(); $diffConfig = $configCache->getAll();
$this->assertEmpty($configCache->keyDiff($diffConfig)); self::assertEmpty($configCache->keyDiff($diffConfig));
} }
/** /**
@ -257,9 +258,9 @@ class CacheTest extends MockedTest
], ],
]); ]);
$this->assertEquals('supersecure', $configCache->get('database', 'password')); self::assertEquals('supersecure', $configCache->get('database', 'password'));
$this->assertNotEquals('supersecure', print_r($configCache->get('database', 'password'), true)); self::assertNotEquals('supersecure', print_r($configCache->get('database', 'password'), true));
$this->assertEquals('notsecured', print_r($configCache->get('database', 'username'), true)); self::assertEquals('notsecured', print_r($configCache->get('database', 'username'), true));
} }
/** /**
@ -274,9 +275,9 @@ class CacheTest extends MockedTest
], ],
], false); ], false);
$this->assertEquals('supersecure', $configCache->get('database', 'password')); self::assertEquals('supersecure', $configCache->get('database', 'password'));
$this->assertEquals('supersecure', print_r($configCache->get('database', 'password'), true)); self::assertEquals('supersecure', print_r($configCache->get('database', 'password'), true));
$this->assertEquals('notsecured', print_r($configCache->get('database', 'username'), true)); self::assertEquals('notsecured', print_r($configCache->get('database', 'username'), true));
} }
/** /**
@ -291,22 +292,22 @@ class CacheTest extends MockedTest
] ]
]); ]);
$this->assertNotEmpty($configCache->get('database', 'password')); self::assertNotEmpty($configCache->get('database', 'password'));
$this->assertInstanceOf(HiddenString::class, $configCache->get('database', 'password')); self::assertInstanceOf(HiddenString::class, $configCache->get('database', 'password'));
$this->assertEmpty($configCache->get('database', 'username')); self::assertEmpty($configCache->get('database', 'username'));
} }
public function testWrongTypePassword() public function testWrongTypePassword()
{ {
$configCache = new Cache([ $configCache = new Cache([
'database' => [ 'database' => [
'password' => new \stdClass(), 'password' => new stdClass(),
'username' => '', 'username' => '',
] ]
]); ]);
$this->assertNotEmpty($configCache->get('database', 'password')); self::assertNotEmpty($configCache->get('database', 'password'));
$this->assertEmpty($configCache->get('database', 'username')); self::assertEmpty($configCache->get('database', 'username'));
$configCache = new Cache([ $configCache = new Cache([
'database' => [ 'database' => [
@ -315,7 +316,7 @@ class CacheTest extends MockedTest
] ]
]); ]);
$this->assertEquals(23, $configCache->get('database', 'password')); self::assertEquals(23, $configCache->get('database', 'password'));
$this->assertEmpty($configCache->get('database', 'username')); self::assertEmpty($configCache->get('database', 'username'));
} }
} }

View file

@ -49,9 +49,9 @@ abstract class ConfigTest extends MockedTest
{ {
$result = $this->testedConfig->getCache()->getAll(); $result = $this->testedConfig->getCache()->getAll();
$this->assertNotEmpty($result); self::assertNotEmpty($result);
$this->assertArrayHasKey($cat, $result); self::assertArrayHasKey($cat, $result);
$this->assertArraySubset($data, $result[$cat]); self::assertArraySubset($data, $result[$cat]);
} }
@ -67,7 +67,7 @@ abstract class ConfigTest extends MockedTest
/** /**
* @return IConfig * @return IConfig
*/ */
public abstract function getInstance(); abstract public function getInstance();
public function dataTests() public function dataTests()
{ {
@ -161,19 +161,22 @@ abstract class ConfigTest extends MockedTest
->once(); ->once();
$this->testedConfig = $this->getInstance(); $this->testedConfig = $this->getInstance();
$this->assertInstanceOf(Cache::class, $this->testedConfig->getCache()); self::assertInstanceOf(Cache::class, $this->testedConfig->getCache());
// assert config is loaded everytime // assert config is loaded everytime
$this->assertConfig('config', $data['config']); self::assertConfig('config', $data['config']);
} }
/** /**
* Test the configuration load() method * 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(); $this->testedConfig = $this->getInstance();
$this->assertInstanceOf(Cache::class, $this->testedConfig->getCache()); self::assertInstanceOf(Cache::class, $this->testedConfig->getCache());
foreach ($load as $loadedCats) { foreach ($load as $loadedCats) {
$this->testedConfig->load($loadedCats); $this->testedConfig->load($loadedCats);
@ -181,7 +184,7 @@ abstract class ConfigTest extends MockedTest
// Assert at least loaded cats are loaded // Assert at least loaded cats are loaded
foreach ($load as $loadedCats) { foreach ($load as $loadedCats) {
$this->assertConfig($loadedCats, $data[$loadedCats]); self::assertConfig($loadedCats, $data[$loadedCats]);
} }
} }
@ -251,10 +254,10 @@ abstract class ConfigTest extends MockedTest
/** /**
* Test the configuration load() method with overwrite * 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(); $this->testedConfig = $this->getInstance();
$this->assertInstanceOf(Cache::class, $this->testedConfig->getCache()); self::assertInstanceOf(Cache::class, $this->testedConfig->getCache());
foreach ($data1 as $cat => $data) { foreach ($data1 as $cat => $data) {
$this->testedConfig->load($cat); $this->testedConfig->load($cat);
@ -262,7 +265,7 @@ abstract class ConfigTest extends MockedTest
// Assert at least loaded cats are loaded // Assert at least loaded cats are loaded
foreach ($data1 as $cat => $data) { foreach ($data1 as $cat => $data) {
$this->assertConfig($cat, $data); self::assertConfig($cat, $data);
} }
foreach ($data2 as $cat => $data) { foreach ($data2 as $cat => $data) {
@ -279,9 +282,9 @@ abstract class ConfigTest extends MockedTest
$this->configModel->shouldReceive('load')->withAnyArgs()->andReturn([])->once(); $this->configModel->shouldReceive('load')->withAnyArgs()->andReturn([])->once();
$this->testedConfig = $this->getInstance(); $this->testedConfig = $this->getInstance();
$this->assertInstanceOf(Cache::class, $this->testedConfig->getCache()); self::assertInstanceOf(Cache::class, $this->testedConfig->getCache());
$this->assertEmpty($this->testedConfig->getCache()->getAll()); self::assertEmpty($this->testedConfig->getCache()->getAll());
} }
/** /**
@ -296,12 +299,12 @@ abstract class ConfigTest extends MockedTest
->times(3); ->times(3);
$this->testedConfig = $this->getInstance(); $this->testedConfig = $this->getInstance();
$this->assertInstanceOf(Cache::class, $this->testedConfig->getCache()); self::assertInstanceOf(Cache::class, $this->testedConfig->getCache());
$this->assertTrue($this->testedConfig->set('test', 'it', $data)); self::assertTrue($this->testedConfig->set('test', 'it', $data));
$this->assertEquals($data, $this->testedConfig->get('test', 'it')); self::assertEquals($data, $this->testedConfig->get('test', 'it'));
$this->assertEquals($data, $this->testedConfig->getCache()->get('test', 'it')); self::assertEquals($data, $this->testedConfig->getCache()->get('test', 'it'));
} }
/** /**
@ -314,12 +317,12 @@ abstract class ConfigTest extends MockedTest
$this->configModel->shouldReceive('set')->with('test', 'it', $data)->andReturn(true)->once(); $this->configModel->shouldReceive('set')->with('test', 'it', $data)->andReturn(true)->once();
$this->testedConfig = $this->getInstance(); $this->testedConfig = $this->getInstance();
$this->assertInstanceOf(Cache::class, $this->testedConfig->getCache()); self::assertInstanceOf(Cache::class, $this->testedConfig->getCache());
$this->assertTrue($this->testedConfig->set('test', 'it', $data)); self::assertTrue($this->testedConfig->set('test', 'it', $data));
$this->assertEquals($data, $this->testedConfig->get('test', 'it')); self::assertEquals($data, $this->testedConfig->get('test', 'it'));
$this->assertEquals($data, $this->testedConfig->getCache()->get('test', 'it')); self::assertEquals($data, $this->testedConfig->getCache()->get('test', 'it'));
} }
/** /**
@ -328,19 +331,19 @@ abstract class ConfigTest extends MockedTest
public function testGetWrongWithoutDB() public function testGetWrongWithoutDB()
{ {
$this->testedConfig = $this->getInstance(); $this->testedConfig = $this->getInstance();
$this->assertInstanceOf(Cache::class, $this->testedConfig->getCache()); self::assertInstanceOf(Cache::class, $this->testedConfig->getCache());
// without refresh // without refresh
$this->assertNull($this->testedConfig->get('test', 'it')); self::assertNull($this->testedConfig->get('test', 'it'));
/// beware that the cache returns '!<unset>!' and not null for a non existing value /// beware that the cache returns '!<unset>!' and not null for a non existing value
$this->assertNull($this->testedConfig->getCache()->get('test', 'it')); self::assertNull($this->testedConfig->getCache()->get('test', 'it'));
// with default value // with default value
$this->assertEquals('default', $this->testedConfig->get('test', 'it', 'default')); self::assertEquals('default', $this->testedConfig->get('test', 'it', 'default'));
// with default value and refresh // with default value and refresh
$this->assertEquals('default', $this->testedConfig->get('test', 'it', 'default', true)); self::assertEquals('default', $this->testedConfig->get('test', 'it', 'default', true));
} }
/** /**
@ -353,19 +356,19 @@ abstract class ConfigTest extends MockedTest
$this->configCache->load(['test' => ['it' => 'now']], Cache::SOURCE_FILE); $this->configCache->load(['test' => ['it' => 'now']], Cache::SOURCE_FILE);
$this->testedConfig = $this->getInstance(); $this->testedConfig = $this->getInstance();
$this->assertInstanceOf(Cache::class, $this->testedConfig->getCache()); self::assertInstanceOf(Cache::class, $this->testedConfig->getCache());
// without refresh // without refresh
$this->assertEquals('now', $this->testedConfig->get('test', 'it')); self::assertEquals('now', $this->testedConfig->get('test', 'it'));
$this->assertEquals('now', $this->testedConfig->getCache()->get('test', 'it')); self::assertEquals('now', $this->testedConfig->getCache()->get('test', 'it'));
// with refresh // with refresh
$this->assertEquals($data, $this->testedConfig->get('test', 'it', null, true)); self::assertEquals($data, $this->testedConfig->get('test', 'it', null, true));
$this->assertEquals($data, $this->testedConfig->getCache()->get('test', 'it')); self::assertEquals($data, $this->testedConfig->getCache()->get('test', 'it'));
// without refresh and wrong value and default // without refresh and wrong value and default
$this->assertEquals('default', $this->testedConfig->get('test', 'not', 'default')); self::assertEquals('default', $this->testedConfig->get('test', 'not', 'default'));
$this->assertNull($this->testedConfig->getCache()->get('test', 'not')); self::assertNull($this->testedConfig->getCache()->get('test', 'not'));
} }
/** /**
@ -378,16 +381,16 @@ abstract class ConfigTest extends MockedTest
$this->configCache->load(['test' => ['it' => $data]], Cache::SOURCE_FILE); $this->configCache->load(['test' => ['it' => $data]], Cache::SOURCE_FILE);
$this->testedConfig = $this->getInstance(); $this->testedConfig = $this->getInstance();
$this->assertInstanceOf(Cache::class, $this->testedConfig->getCache()); self::assertInstanceOf(Cache::class, $this->testedConfig->getCache());
$this->assertEquals($data, $this->testedConfig->get('test', 'it')); self::assertEquals($data, $this->testedConfig->get('test', 'it'));
$this->assertEquals($data, $this->testedConfig->getCache()->get('test', 'it')); self::assertEquals($data, $this->testedConfig->getCache()->get('test', 'it'));
$this->assertTrue($this->testedConfig->delete('test', 'it')); self::assertTrue($this->testedConfig->delete('test', 'it'));
$this->assertNull($this->testedConfig->get('test', 'it')); self::assertNull($this->testedConfig->get('test', 'it'));
$this->assertNull($this->testedConfig->getCache()->get('test', 'it')); self::assertNull($this->testedConfig->getCache()->get('test', 'it'));
$this->assertEmpty($this->testedConfig->getCache()->getAll()); self::assertEmpty($this->testedConfig->getCache()->getAll());
} }
/** /**
@ -415,23 +418,23 @@ abstract class ConfigTest extends MockedTest
->once(); ->once();
$this->testedConfig = $this->getInstance(); $this->testedConfig = $this->getInstance();
$this->assertInstanceOf(Cache::class, $this->testedConfig->getCache()); self::assertInstanceOf(Cache::class, $this->testedConfig->getCache());
// directly set the value to the cache // directly set the value to the cache
$this->testedConfig->getCache()->set('test', 'it', 'now'); $this->testedConfig->getCache()->set('test', 'it', 'now');
$this->assertEquals('now', $this->testedConfig->get('test', 'it')); self::assertEquals('now', $this->testedConfig->get('test', 'it'));
$this->assertEquals('now', $this->testedConfig->getCache()->get('test', 'it')); self::assertEquals('now', $this->testedConfig->getCache()->get('test', 'it'));
// delete from cache only // delete from cache only
$this->assertTrue($this->testedConfig->delete('test', 'it')); self::assertTrue($this->testedConfig->delete('test', 'it'));
// delete from db only // delete from db only
$this->assertTrue($this->testedConfig->delete('test', 'second')); self::assertTrue($this->testedConfig->delete('test', 'second'));
// no delete // no delete
$this->assertFalse($this->testedConfig->delete('test', 'third')); self::assertFalse($this->testedConfig->delete('test', 'third'));
// delete both // delete both
$this->assertTrue($this->testedConfig->delete('test', 'quarter')); self::assertTrue($this->testedConfig->delete('test', 'quarter'));
$this->assertEmpty($this->testedConfig->getCache()->getAll()); self::assertEmpty($this->testedConfig->getCache()->getAll());
} }
} }

View file

@ -45,8 +45,11 @@ class JitConfigTest extends ConfigTest
/** /**
* @dataProvider dataConfigLoad * @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') $this->configModel->shouldReceive('isConnected')
->andReturn(true) ->andReturn(true)
@ -64,13 +67,13 @@ class JitConfigTest extends ConfigTest
->once(); ->once();
} }
parent::testLoad($data, $possibleCats, $load); parent::testLoad($data, $load);
} }
/** /**
* @dataProvider dataDoubleLoad * @dataProvider dataDoubleLoad
*/ */
public function testCacheLoadDouble(array $data1, array $data2, array $expect) public function testCacheLoadDouble(array $data1, array $data2, array $expect = [])
{ {
$this->configModel->shouldReceive('isConnected') $this->configModel->shouldReceive('isConnected')
->andReturn(true) ->andReturn(true)
@ -96,11 +99,11 @@ class JitConfigTest extends ConfigTest
->once(); ->once();
} }
parent::testCacheLoadDouble($data1, $data2, $expect); parent::testCacheLoadDouble($data1, $data2);
// Assert the expected categories // Assert the expected categories
foreach ($data2 as $cat => $data) { foreach ($data2 as $cat => $data) {
$this->assertConfig($cat, $expect[$cat]); self::assertConfig($cat, $expect[$cat]);
} }
} }

View file

@ -44,8 +44,11 @@ class PreloadConfigTest extends ConfigTest
/** /**
* @dataProvider dataConfigLoad * @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') $this->configModel->shouldReceive('isConnected')
->andReturn(true) ->andReturn(true)
@ -55,18 +58,21 @@ class PreloadConfigTest extends ConfigTest
->andReturn($data) ->andReturn($data)
->once(); ->once();
parent::testLoad($data, $possibleCats, $load); parent::testLoad($data, $load);
// Assert that every category is loaded everytime // Assert that every category is loaded everytime
foreach ($data as $cat => $values) { foreach ($data as $cat => $values) {
$this->assertConfig($cat, $values); self::assertConfig($cat, $values);
} }
} }
/** /**
* @dataProvider dataDoubleLoad * @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') $this->configModel->shouldReceive('isConnected')
->andReturn(true) ->andReturn(true)
@ -76,11 +82,11 @@ class PreloadConfigTest extends ConfigTest
->andReturn($data1) ->andReturn($data1)
->once(); ->once();
parent::testCacheLoadDouble($data1, $data2, $expect); parent::testCacheLoadDouble($data1, $data2);
// Assert that every category is loaded everytime and is NOT overwritten // Assert that every category is loaded everytime and is NOT overwritten
foreach ($data1 as $cat => $values) { foreach ($data1 as $cat => $values) {
$this->assertConfig($cat, $values); self::assertConfig($cat, $values);
} }
} }

View file

@ -19,7 +19,7 @@
* *
*/ */
// 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; namespace Friendica\Core;
use Dice\Dice; use Dice\Dice;
@ -29,6 +29,7 @@ use Friendica\Network\CurlResult;
use Friendica\Network\IHTTPRequest; use Friendica\Network\IHTTPRequest;
use Friendica\Test\MockedTest; use Friendica\Test\MockedTest;
use Friendica\Test\Util\VFSTrait; use Friendica\Test\Util\VFSTrait;
use Mockery;
use Mockery\MockInterface; use Mockery\MockInterface;
class InstallerTest extends MockedTest class InstallerTest extends MockedTest
@ -36,7 +37,7 @@ class InstallerTest extends MockedTest
use VFSTrait; use VFSTrait;
/** /**
* @var \Friendica\Core\L10n|MockInterface * @var L10n|MockInterface
*/ */
private $l10nMock; private $l10nMock;
/** /**
@ -44,20 +45,20 @@ class InstallerTest extends MockedTest
*/ */
private $dice; private $dice;
public function setUp() protected function setUp()
{ {
parent::setUp(); parent::setUp();
$this->setUpVfsDir(); $this->setUpVfsDir();
$this->l10nMock = \Mockery::mock(\Friendica\Core\L10n::class); $this->l10nMock = Mockery::mock(L10n::class);
/** @var Dice|MockInterface $dice */ /** @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 = $this->dice->addRules(include __DIR__ . '/../../../static/dependencies.config.php');
$this->dice->shouldReceive('create') $this->dice->shouldReceive('create')
->with(\Friendica\Core\L10n::class) ->with(L10n::class)
->andReturn($this->l10nMock); ->andReturn($this->l10nMock);
DI::init($this->dice); DI::init($this->dice);
@ -104,7 +105,7 @@ class InstallerTest extends MockedTest
'help' => $help] 'help' => $help]
]; ];
$this->assertArraySubset($subSet, $assertionArray, false, "expected subset: " . PHP_EOL . print_r($subSet, true) . PHP_EOL . "current subset: " . print_r($assertionArray, true)); self::assertArraySubset($subSet, $assertionArray, false, "expected subset: " . PHP_EOL . print_r($subSet, true) . PHP_EOL . "current subset: " . print_r($assertionArray, true));
} }
/** /**
@ -112,7 +113,7 @@ class InstallerTest extends MockedTest
* *
* @param array $functions a list from function names and their result * @param array $functions a list from function names and their result
*/ */
private function setFunctions($functions) private function setFunctions(array $functions)
{ {
global $phpMock; global $phpMock;
$phpMock['function_exists'] = function($function) use ($functions) { $phpMock['function_exists'] = function($function) use ($functions) {
@ -130,7 +131,7 @@ class InstallerTest extends MockedTest
* *
* @param array $classes a list from class names and their results * @param array $classes a list from class names and their results
*/ */
private function setClasses($classes) private function setClasses(array $classes)
{ {
global $phpMock; global $phpMock;
$phpMock['class_exists'] = function($class) use ($classes) { $phpMock['class_exists'] = function($class) use ($classes) {
@ -152,11 +153,11 @@ class InstallerTest extends MockedTest
$this->setFunctions(['openssl_pkey_new' => false]); $this->setFunctions(['openssl_pkey_new' => false]);
$install = new Installer(); $install = new Installer();
$this->assertFalse($install->checkKeys()); self::assertFalse($install->checkKeys());
$this->setFunctions(['openssl_pkey_new' => true]); $this->setFunctions(['openssl_pkey_new' => true]);
$install = new Installer(); $install = new Installer();
$this->assertTrue($install->checkKeys()); self::assertTrue($install->checkKeys());
} }
/** /**
@ -167,8 +168,8 @@ class InstallerTest extends MockedTest
$this->mockFunctionL10TCalls(); $this->mockFunctionL10TCalls();
$this->setFunctions(['curl_init' => false, 'imagecreatefromjpeg' => true]); $this->setFunctions(['curl_init' => false, 'imagecreatefromjpeg' => true]);
$install = new Installer(); $install = new Installer();
$this->assertFalse($install->checkFunctions()); self::assertFalse($install->checkFunctions());
$this->assertCheckExist(3, self::assertCheckExist(3,
'libCurl PHP module', 'libCurl PHP module',
'Error: libCURL PHP module required but not installed.', 'Error: libCURL PHP module required but not installed.',
false, false,
@ -178,8 +179,8 @@ class InstallerTest extends MockedTest
$this->mockFunctionL10TCalls(); $this->mockFunctionL10TCalls();
$this->setFunctions(['imagecreatefromjpeg' => false]); $this->setFunctions(['imagecreatefromjpeg' => false]);
$install = new Installer(); $install = new Installer();
$this->assertFalse($install->checkFunctions()); self::assertFalse($install->checkFunctions());
$this->assertCheckExist(4, self::assertCheckExist(4,
'GD graphics PHP module', 'GD graphics PHP module',
'Error: GD graphics PHP module with JPEG support required but not installed.', 'Error: GD graphics PHP module with JPEG support required but not installed.',
false, false,
@ -189,8 +190,8 @@ class InstallerTest extends MockedTest
$this->mockFunctionL10TCalls(); $this->mockFunctionL10TCalls();
$this->setFunctions(['openssl_public_encrypt' => false]); $this->setFunctions(['openssl_public_encrypt' => false]);
$install = new Installer(); $install = new Installer();
$this->assertFalse($install->checkFunctions()); self::assertFalse($install->checkFunctions());
$this->assertCheckExist(5, self::assertCheckExist(5,
'OpenSSL PHP module', 'OpenSSL PHP module',
'Error: openssl PHP module required but not installed.', 'Error: openssl PHP module required but not installed.',
false, false,
@ -200,8 +201,8 @@ class InstallerTest extends MockedTest
$this->mockFunctionL10TCalls(); $this->mockFunctionL10TCalls();
$this->setFunctions(['mb_strlen' => false]); $this->setFunctions(['mb_strlen' => false]);
$install = new Installer(); $install = new Installer();
$this->assertFalse($install->checkFunctions()); self::assertFalse($install->checkFunctions());
$this->assertCheckExist(6, self::assertCheckExist(6,
'mb_string PHP module', 'mb_string PHP module',
'Error: mb_string PHP module required but not installed.', 'Error: mb_string PHP module required but not installed.',
false, false,
@ -211,8 +212,8 @@ class InstallerTest extends MockedTest
$this->mockFunctionL10TCalls(); $this->mockFunctionL10TCalls();
$this->setFunctions(['iconv_strlen' => false]); $this->setFunctions(['iconv_strlen' => false]);
$install = new Installer(); $install = new Installer();
$this->assertFalse($install->checkFunctions()); self::assertFalse($install->checkFunctions());
$this->assertCheckExist(7, self::assertCheckExist(7,
'iconv PHP module', 'iconv PHP module',
'Error: iconv PHP module required but not installed.', 'Error: iconv PHP module required but not installed.',
false, false,
@ -222,8 +223,8 @@ class InstallerTest extends MockedTest
$this->mockFunctionL10TCalls(); $this->mockFunctionL10TCalls();
$this->setFunctions(['posix_kill' => false]); $this->setFunctions(['posix_kill' => false]);
$install = new Installer(); $install = new Installer();
$this->assertFalse($install->checkFunctions()); self::assertFalse($install->checkFunctions());
$this->assertCheckExist(8, self::assertCheckExist(8,
'POSIX PHP module', 'POSIX PHP module',
'Error: POSIX PHP module required but not installed.', 'Error: POSIX PHP module required but not installed.',
false, false,
@ -233,8 +234,8 @@ class InstallerTest extends MockedTest
$this->mockFunctionL10TCalls(); $this->mockFunctionL10TCalls();
$this->setFunctions(['json_encode' => false]); $this->setFunctions(['json_encode' => false]);
$install = new Installer(); $install = new Installer();
$this->assertFalse($install->checkFunctions()); self::assertFalse($install->checkFunctions());
$this->assertCheckExist(9, self::assertCheckExist(9,
'JSON PHP module', 'JSON PHP module',
'Error: JSON PHP module required but not installed.', 'Error: JSON PHP module required but not installed.',
false, false,
@ -244,8 +245,8 @@ class InstallerTest extends MockedTest
$this->mockFunctionL10TCalls(); $this->mockFunctionL10TCalls();
$this->setFunctions(['finfo_open' => false]); $this->setFunctions(['finfo_open' => false]);
$install = new Installer(); $install = new Installer();
$this->assertFalse($install->checkFunctions()); self::assertFalse($install->checkFunctions());
$this->assertCheckExist(10, self::assertCheckExist(10,
'File Information PHP module', 'File Information PHP module',
'Error: File Information PHP module required but not installed.', 'Error: File Information PHP module required but not installed.',
false, false,
@ -264,7 +265,7 @@ class InstallerTest extends MockedTest
'finfo_open' => true, 'finfo_open' => true,
]); ]);
$install = new Installer(); $install = new Installer();
$this->assertTrue($install->checkFunctions()); self::assertTrue($install->checkFunctions());
} }
/** /**
@ -274,17 +275,17 @@ class InstallerTest extends MockedTest
{ {
$this->l10nMock->shouldReceive('t')->andReturnUsing(function ($args) { return $args; }); $this->l10nMock->shouldReceive('t')->andReturnUsing(function ($args) { return $args; });
$this->assertTrue($this->root->hasChild('config/local.config.php')); self::assertTrue($this->root->hasChild('config/local.config.php'));
$install = new Installer(); $install = new Installer();
$this->assertTrue($install->checkLocalIni()); self::assertTrue($install->checkLocalIni());
$this->delConfigFile('local.config.php'); $this->delConfigFile('local.config.php');
$this->assertFalse($this->root->hasChild('config/local.config.php')); self::assertFalse($this->root->hasChild('config/local.config.php'));
$install = new Installer(); $install = new Installer();
$this->assertTrue($install->checkLocalIni()); self::assertTrue($install->checkLocalIni());
} }
/** /**
@ -297,7 +298,7 @@ class InstallerTest extends MockedTest
$this->l10nMock->shouldReceive('t')->andReturnUsing(function ($args) { return $args; }); $this->l10nMock->shouldReceive('t')->andReturnUsing(function ($args) { return $args; });
// Mocking the CURL Response // Mocking the CURL Response
$curlResult = \Mockery::mock(CurlResult::class); $curlResult = Mockery::mock(CurlResult::class);
$curlResult $curlResult
->shouldReceive('getReturnCode') ->shouldReceive('getReturnCode')
->andReturn('404'); ->andReturn('404');
@ -309,7 +310,7 @@ class InstallerTest extends MockedTest
->andReturn('test Error'); ->andReturn('test Error');
// Mocking the CURL Request // Mocking the CURL Request
$networkMock = \Mockery::mock(IHTTPRequest::class); $networkMock = Mockery::mock(IHTTPRequest::class);
$networkMock $networkMock
->shouldReceive('fetchFull') ->shouldReceive('fetchFull')
->with('https://test/install/testrewrite') ->with('https://test/install/testrewrite')
@ -330,8 +331,8 @@ class InstallerTest extends MockedTest
$install = new Installer(); $install = new Installer();
$this->assertFalse($install->checkHtAccess('https://test')); self::assertFalse($install->checkHtAccess('https://test'));
$this->assertSame('test Error', $install->getChecks()[0]['error_msg']['msg']); self::assertSame('test Error', $install->getChecks()[0]['error_msg']['msg']);
} }
/** /**
@ -344,19 +345,19 @@ class InstallerTest extends MockedTest
$this->l10nMock->shouldReceive('t')->andReturnUsing(function ($args) { return $args; }); $this->l10nMock->shouldReceive('t')->andReturnUsing(function ($args) { return $args; });
// Mocking the failed CURL Response // Mocking the failed CURL Response
$curlResultF = \Mockery::mock(CurlResult::class); $curlResultF = Mockery::mock(CurlResult::class);
$curlResultF $curlResultF
->shouldReceive('getReturnCode') ->shouldReceive('getReturnCode')
->andReturn('404'); ->andReturn('404');
// Mocking the working CURL Response // Mocking the working CURL Response
$curlResultW = \Mockery::mock(CurlResult::class); $curlResultW = Mockery::mock(CurlResult::class);
$curlResultW $curlResultW
->shouldReceive('getReturnCode') ->shouldReceive('getReturnCode')
->andReturn('204'); ->andReturn('204');
// Mocking the CURL Request // Mocking the CURL Request
$networkMock = \Mockery::mock(IHTTPRequest::class); $networkMock = Mockery::mock(IHTTPRequest::class);
$networkMock $networkMock
->shouldReceive('fetchFull') ->shouldReceive('fetchFull')
->with('https://test/install/testrewrite') ->with('https://test/install/testrewrite')
@ -377,7 +378,7 @@ class InstallerTest extends MockedTest
$install = new Installer(); $install = new Installer();
$this->assertTrue($install->checkHtAccess('https://test')); self::assertTrue($install->checkHtAccess('https://test'));
} }
/** /**
@ -387,7 +388,7 @@ class InstallerTest extends MockedTest
*/ */
public function testImagick() 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; }); $this->l10nMock->shouldReceive('t')->andReturnUsing(function ($args) { return $args; });
@ -396,9 +397,9 @@ class InstallerTest extends MockedTest
$install = new Installer(); $install = new Installer();
// even there is no supported type, Imagick should return true (because it is not required) // even there is no supported type, Imagick should return true (because it is not required)
$this->assertTrue($install->checkImagick()); self::assertTrue($install->checkImagick());
$this->assertCheckExist(1, self::assertCheckExist(1,
$this->l10nMock->t('ImageMagick supports GIF'), $this->l10nMock->t('ImageMagick supports GIF'),
'', '',
true, true,
@ -413,7 +414,7 @@ class InstallerTest extends MockedTest
*/ */
public function testImagickNotFound() 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; });
@ -422,8 +423,8 @@ class InstallerTest extends MockedTest
$install = new Installer(); $install = new Installer();
// even there is no supported type, Imagick should return true (because it is not required) // even there is no supported type, Imagick should return true (because it is not required)
$this->assertTrue($install->checkImagick()); self::assertTrue($install->checkImagick());
$this->assertCheckExist(1, self::assertCheckExist(1,
$this->l10nMock->t('ImageMagick supports GIF'), $this->l10nMock->t('ImageMagick supports GIF'),
'', '',
false, false,
@ -439,8 +440,8 @@ class InstallerTest extends MockedTest
$install = new Installer(); $install = new Installer();
// even there is no supported type, Imagick should return true (because it is not required) // even there is no supported type, Imagick should return true (because it is not required)
$this->assertTrue($install->checkImagick()); self::assertTrue($install->checkImagick());
$this->assertCheckExist(0, self::assertCheckExist(0,
'ImageMagick PHP extension is not installed', 'ImageMagick PHP extension is not installed',
'', '',
false, false,
@ -456,8 +457,8 @@ class InstallerTest extends MockedTest
$this->l10nMock->shouldReceive('t')->andReturnUsing(function ($args) { return $args; }); $this->l10nMock->shouldReceive('t')->andReturnUsing(function ($args) { return $args; });
$install = new Installer(); $install = new Installer();
$configCache = \Mockery::mock(Cache::class); $configCache = Mockery::mock(Cache::class);
$configCache->shouldReceive('set')->with('config', 'php_path', \Mockery::any())->once(); $configCache->shouldReceive('set')->with('config', 'php_path', Mockery::any())->once();
$configCache->shouldReceive('set')->with('system', 'basepath', '/test/')->once(); $configCache->shouldReceive('set')->with('system', 'basepath', '/test/')->once();
$install->setUpCache($configCache, '/test/'); $install->setUpCache($configCache, '/test/');
@ -471,7 +472,7 @@ class InstallerTest extends MockedTest
* *
* @return bool true or false * @return bool true or false
*/ */
function function_exists($function_name) function function_exists(string $function_name)
{ {
global $phpMock; global $phpMock;
if (isset($phpMock['function_exists'])) { if (isset($phpMock['function_exists'])) {

View file

@ -109,6 +109,6 @@ class L10nTest extends MockedTest
*/ */
public function testDetectLanguage(array $server, array $get, string $default, string $assert) public function testDetectLanguage(array $server, array $get, string $default, string $assert)
{ {
$this->assertEquals($assert, L10n::detectLanguage($server, $get, $default)); self::assertEquals($assert, L10n::detectLanguage($server, $get, $default));
} }
} }

View file

@ -32,7 +32,7 @@ class APCuCacheLockTest extends LockTest
protected function setUp() protected function setUp()
{ {
if (!APCuCache::isAvailable()) { if (!APCuCache::isAvailable()) {
$this->markTestSkipped('APCu is not available'); static::markTestSkipped('APCu is not available');
} }
parent::setUp(); parent::setUp();

View file

@ -28,6 +28,7 @@ use Friendica\Test\Util\Database\StaticDatabase;
use Friendica\Test\Util\VFSTrait; use Friendica\Test\Util\VFSTrait;
use Friendica\Util\ConfigFileLoader; use Friendica\Util\ConfigFileLoader;
use Friendica\Util\Profiler; use Friendica\Util\Profiler;
use Mockery;
use Psr\Log\NullLogger; use Psr\Log\NullLogger;
class DatabaseLockDriverTest extends LockTest class DatabaseLockDriverTest extends LockTest
@ -47,7 +48,7 @@ class DatabaseLockDriverTest extends LockTest
protected function getInstance() protected function getInstance()
{ {
$logger = new NullLogger(); $logger = new NullLogger();
$profiler = \Mockery::mock(Profiler::class); $profiler = Mockery::mock(Profiler::class);
$profiler->shouldReceive('saveTimestamp')->withAnyArgs()->andReturn(true); $profiler->shouldReceive('saveTimestamp')->withAnyArgs()->andReturn(true);
// load real config to avoid mocking every config-entry which is related to the Database class // load real config to avoid mocking every config-entry which is related to the Database class

View file

@ -21,6 +21,7 @@
namespace Friendica\Test\src\Core\Lock; namespace Friendica\Test\src\Core\Lock;
use Friendica\Core\Lock\ILock;
use Friendica\Test\MockedTest; use Friendica\Test\MockedTest;
abstract class LockTest extends MockedTest abstract class LockTest extends MockedTest
@ -31,7 +32,7 @@ abstract class LockTest extends MockedTest
protected $startTime = 1417011228; protected $startTime = 1417011228;
/** /**
* @var \Friendica\Core\Lock\ILock * @var ILock
*/ */
protected $instance; protected $instance;
@ -56,10 +57,10 @@ abstract class LockTest extends MockedTest
*/ */
public function testLock() public function testLock()
{ {
$this->assertFalse($this->instance->isLocked('foo')); self::assertFalse($this->instance->isLocked('foo'));
$this->assertTrue($this->instance->acquire('foo', 1)); self::assertTrue($this->instance->acquire('foo', 1));
$this->assertTrue($this->instance->isLocked('foo')); self::assertTrue($this->instance->isLocked('foo'));
$this->assertFalse($this->instance->isLocked('bar')); self::assertFalse($this->instance->isLocked('bar'));
} }
/** /**
@ -67,11 +68,11 @@ abstract class LockTest extends MockedTest
*/ */
public function testDoubleLock() public function testDoubleLock()
{ {
$this->assertFalse($this->instance->isLocked('foo')); self::assertFalse($this->instance->isLocked('foo'));
$this->assertTrue($this->instance->acquire('foo', 1)); self::assertTrue($this->instance->acquire('foo', 1));
$this->assertTrue($this->instance->isLocked('foo')); self::assertTrue($this->instance->isLocked('foo'));
// We already locked it // We already locked it
$this->assertTrue($this->instance->acquire('foo', 1)); self::assertTrue($this->instance->acquire('foo', 1));
} }
/** /**
@ -79,11 +80,11 @@ abstract class LockTest extends MockedTest
*/ */
public function testReleaseLock() public function testReleaseLock()
{ {
$this->assertFalse($this->instance->isLocked('foo')); self::assertFalse($this->instance->isLocked('foo'));
$this->assertTrue($this->instance->acquire('foo', 1)); self::assertTrue($this->instance->acquire('foo', 1));
$this->assertTrue($this->instance->isLocked('foo')); self::assertTrue($this->instance->isLocked('foo'));
$this->instance->release('foo'); $this->instance->release('foo');
$this->assertFalse($this->instance->isLocked('foo')); self::assertFalse($this->instance->isLocked('foo'));
} }
/** /**
@ -91,19 +92,19 @@ abstract class LockTest extends MockedTest
*/ */
public function testReleaseAll() public function testReleaseAll()
{ {
$this->assertTrue($this->instance->acquire('foo', 1)); self::assertTrue($this->instance->acquire('foo', 1));
$this->assertTrue($this->instance->acquire('bar', 1)); self::assertTrue($this->instance->acquire('bar', 1));
$this->assertTrue($this->instance->acquire('nice', 1)); self::assertTrue($this->instance->acquire('nice', 1));
$this->assertTrue($this->instance->isLocked('foo')); self::assertTrue($this->instance->isLocked('foo'));
$this->assertTrue($this->instance->isLocked('bar')); self::assertTrue($this->instance->isLocked('bar'));
$this->assertTrue($this->instance->isLocked('nice')); self::assertTrue($this->instance->isLocked('nice'));
$this->assertTrue($this->instance->releaseAll()); self::assertTrue($this->instance->releaseAll());
$this->assertFalse($this->instance->isLocked('foo')); self::assertFalse($this->instance->isLocked('foo'));
$this->assertFalse($this->instance->isLocked('bar')); self::assertFalse($this->instance->isLocked('bar'));
$this->assertFalse($this->instance->isLocked('nice')); self::assertFalse($this->instance->isLocked('nice'));
} }
/** /**
@ -111,23 +112,23 @@ abstract class LockTest extends MockedTest
*/ */
public function testReleaseAfterUnlock() public function testReleaseAfterUnlock()
{ {
$this->assertFalse($this->instance->isLocked('foo')); self::assertFalse($this->instance->isLocked('foo'));
$this->assertFalse($this->instance->isLocked('bar')); self::assertFalse($this->instance->isLocked('bar'));
$this->assertFalse($this->instance->isLocked('nice')); self::assertFalse($this->instance->isLocked('nice'));
$this->assertTrue($this->instance->acquire('foo', 1)); self::assertTrue($this->instance->acquire('foo', 1));
$this->assertTrue($this->instance->acquire('bar', 1)); self::assertTrue($this->instance->acquire('bar', 1));
$this->assertTrue($this->instance->acquire('nice', 1)); self::assertTrue($this->instance->acquire('nice', 1));
$this->assertTrue($this->instance->release('foo')); self::assertTrue($this->instance->release('foo'));
$this->assertFalse($this->instance->isLocked('foo')); self::assertFalse($this->instance->isLocked('foo'));
$this->assertTrue($this->instance->isLocked('bar')); self::assertTrue($this->instance->isLocked('bar'));
$this->assertTrue($this->instance->isLocked('nice')); self::assertTrue($this->instance->isLocked('nice'));
$this->assertTrue($this->instance->releaseAll()); self::assertTrue($this->instance->releaseAll());
$this->assertFalse($this->instance->isLocked('bar')); self::assertFalse($this->instance->isLocked('bar'));
$this->assertFalse($this->instance->isLocked('nice')); self::assertFalse($this->instance->isLocked('nice'));
} }
/** /**
@ -135,11 +136,11 @@ abstract class LockTest extends MockedTest
*/ */
public function testReleaseWitTTL() public function testReleaseWitTTL()
{ {
$this->assertFalse($this->instance->isLocked('test')); self::assertFalse($this->instance->isLocked('test'));
$this->assertTrue($this->instance->acquire('test', 1, 10)); self::assertTrue($this->instance->acquire('test', 1, 10));
$this->assertTrue($this->instance->isLocked('test')); self::assertTrue($this->instance->isLocked('test'));
$this->assertTrue($this->instance->release('test')); self::assertTrue($this->instance->release('test'));
$this->assertFalse($this->instance->isLocked('test')); self::assertFalse($this->instance->isLocked('test'));
} }
/** /**
@ -147,19 +148,19 @@ abstract class LockTest extends MockedTest
*/ */
public function testGetLocks() public function testGetLocks()
{ {
$this->assertTrue($this->instance->acquire('foo', 1)); self::assertTrue($this->instance->acquire('foo', 1));
$this->assertTrue($this->instance->acquire('bar', 1)); self::assertTrue($this->instance->acquire('bar', 1));
$this->assertTrue($this->instance->acquire('nice', 1)); self::assertTrue($this->instance->acquire('nice', 1));
$this->assertTrue($this->instance->isLocked('foo')); self::assertTrue($this->instance->isLocked('foo'));
$this->assertTrue($this->instance->isLocked('bar')); self::assertTrue($this->instance->isLocked('bar'));
$this->assertTrue($this->instance->isLocked('nice')); self::assertTrue($this->instance->isLocked('nice'));
$locks = $this->instance->getLocks(); $locks = $this->instance->getLocks();
$this->assertContains('foo', $locks); self::assertContains('foo', $locks);
$this->assertContains('bar', $locks); self::assertContains('bar', $locks);
$this->assertContains('nice', $locks); self::assertContains('nice', $locks);
} }
/** /**
@ -167,47 +168,47 @@ abstract class LockTest extends MockedTest
*/ */
public function testGetLocksWithPrefix() public function testGetLocksWithPrefix()
{ {
$this->assertTrue($this->instance->acquire('foo', 1)); self::assertTrue($this->instance->acquire('foo', 1));
$this->assertTrue($this->instance->acquire('test1', 1)); self::assertTrue($this->instance->acquire('test1', 1));
$this->assertTrue($this->instance->acquire('test2', 1)); self::assertTrue($this->instance->acquire('test2', 1));
$this->assertTrue($this->instance->isLocked('foo')); self::assertTrue($this->instance->isLocked('foo'));
$this->assertTrue($this->instance->isLocked('test1')); self::assertTrue($this->instance->isLocked('test1'));
$this->assertTrue($this->instance->isLocked('test2')); self::assertTrue($this->instance->isLocked('test2'));
$locks = $this->instance->getLocks('test'); $locks = $this->instance->getLocks('test');
$this->assertContains('test1', $locks); self::assertContains('test1', $locks);
$this->assertContains('test2', $locks); self::assertContains('test2', $locks);
$this->assertNotContains('foo', $locks); self::assertNotContains('foo', $locks);
} }
/** /**
* @medium * @medium
*/ */
function testLockTTL() public function testLockTTL()
{ {
$this->markTestSkipped('taking too much time without mocking'); static::markTestSkipped('taking too much time without mocking');
$this->assertFalse($this->instance->isLocked('foo')); self::assertFalse($this->instance->isLocked('foo'));
$this->assertFalse($this->instance->isLocked('bar')); self::assertFalse($this->instance->isLocked('bar'));
// TODO [nupplaphil] - Because of the Datetime-Utils for the database, we have to wait a FULL second between the checks to invalidate the db-locks/cache // TODO [nupplaphil] - Because of the Datetime-Utils for the database, we have to wait a FULL second between the checks to invalidate the db-locks/cache
$this->assertTrue($this->instance->acquire('foo', 2, 1)); self::assertTrue($this->instance->acquire('foo', 2, 1));
$this->assertTrue($this->instance->acquire('bar', 2, 3)); self::assertTrue($this->instance->acquire('bar', 2, 3));
$this->assertTrue($this->instance->isLocked('foo')); self::assertTrue($this->instance->isLocked('foo'));
$this->assertTrue($this->instance->isLocked('bar')); self::assertTrue($this->instance->isLocked('bar'));
sleep(2); sleep(2);
$this->assertFalse($this->instance->isLocked('foo')); self::assertFalse($this->instance->isLocked('foo'));
$this->assertTrue($this->instance->isLocked('bar')); self::assertTrue($this->instance->isLocked('bar'));
sleep(2); sleep(2);
$this->assertFalse($this->instance->isLocked('foo')); self::assertFalse($this->instance->isLocked('foo'));
$this->assertFalse($this->instance->isLocked('bar')); self::assertFalse($this->instance->isLocked('bar'));
} }
/** /**
@ -215,7 +216,7 @@ abstract class LockTest extends MockedTest
*/ */
public function testReleaseLockWithoutLock() public function testReleaseLockWithoutLock()
{ {
$this->assertFalse($this->instance->isLocked('wrongLock')); self::assertFalse($this->instance->isLocked('wrongLock'));
$this->assertFalse($this->instance->release('wrongLock')); self::assertFalse($this->instance->release('wrongLock'));
} }
} }

View file

@ -21,9 +21,11 @@
namespace Friendica\Test\src\Core\Lock; namespace Friendica\Test\src\Core\Lock;
use Exception;
use Friendica\Core\Cache\MemcacheCache; use Friendica\Core\Cache\MemcacheCache;
use Friendica\Core\Config\IConfig; use Friendica\Core\Config\IConfig;
use Friendica\Core\Lock\CacheLock; use Friendica\Core\Lock\CacheLock;
use Mockery;
/** /**
* @requires extension Memcache * @requires extension Memcache
@ -33,7 +35,7 @@ class MemcacheCacheLockTest extends LockTest
{ {
protected function getInstance() protected function getInstance()
{ {
$configMock = \Mockery::mock(IConfig::class); $configMock = Mockery::mock(IConfig::class);
$host = $_SERVER['MEMCACHE_HOST'] ?? 'localhost'; $host = $_SERVER['MEMCACHE_HOST'] ?? 'localhost';
$port = $_SERVER['MEMCACHE_PORT'] ?? '11211'; $port = $_SERVER['MEMCACHE_PORT'] ?? '11211';
@ -52,8 +54,8 @@ class MemcacheCacheLockTest extends LockTest
try { try {
$cache = new MemcacheCache($host, $configMock); $cache = new MemcacheCache($host, $configMock);
$lock = new CacheLock($cache); $lock = new CacheLock($cache);
} catch (\Exception $e) { } catch (Exception $e) {
$this->markTestSkipped('Memcache is not available'); static::markTestSkipped('Memcache is not available');
} }
return $lock; return $lock;
@ -64,7 +66,7 @@ class MemcacheCacheLockTest extends LockTest
*/ */
public function testGetLocks() 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');
} }
/** /**
@ -72,6 +74,6 @@ class MemcacheCacheLockTest extends LockTest
*/ */
public function testGetLocksWithPrefix() 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');
} }
} }

View file

@ -21,9 +21,11 @@
namespace Friendica\Test\src\Core\Lock; namespace Friendica\Test\src\Core\Lock;
use Exception;
use Friendica\Core\Cache\MemcachedCache; use Friendica\Core\Cache\MemcachedCache;
use Friendica\Core\Config\IConfig; use Friendica\Core\Config\IConfig;
use Friendica\Core\Lock\CacheLock; use Friendica\Core\Lock\CacheLock;
use Mockery;
use Psr\Log\NullLogger; use Psr\Log\NullLogger;
/** /**
@ -34,7 +36,7 @@ class MemcachedCacheLockTest extends LockTest
{ {
protected function getInstance() protected function getInstance()
{ {
$configMock = \Mockery::mock(IConfig::class); $configMock = Mockery::mock(IConfig::class);
$host = $_SERVER['MEMCACHED_HOST'] ?? 'localhost'; $host = $_SERVER['MEMCACHED_HOST'] ?? 'localhost';
$port = $_SERVER['MEMCACHED_PORT'] ?? '11211'; $port = $_SERVER['MEMCACHED_PORT'] ?? '11211';
@ -51,8 +53,8 @@ class MemcachedCacheLockTest extends LockTest
try { try {
$cache = new MemcachedCache($host, $configMock, $logger); $cache = new MemcachedCache($host, $configMock, $logger);
$lock = new CacheLock($cache); $lock = new CacheLock($cache);
} catch (\Exception $e) { } catch (Exception $e) {
$this->markTestSkipped('Memcached is not available'); static::markTestSkipped('Memcached is not available');
} }
return $lock; return $lock;
@ -60,11 +62,11 @@ class MemcachedCacheLockTest extends LockTest
public function testGetLocks() 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() 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');
} }
} }

View file

@ -21,9 +21,11 @@
namespace Friendica\Test\src\Core\Lock; namespace Friendica\Test\src\Core\Lock;
use Exception;
use Friendica\Core\Cache\RedisCache; use Friendica\Core\Cache\RedisCache;
use Friendica\Core\Config\IConfig; use Friendica\Core\Config\IConfig;
use Friendica\Core\Lock\CacheLock; use Friendica\Core\Lock\CacheLock;
use Mockery;
/** /**
* @requires extension redis * @requires extension redis
@ -33,10 +35,10 @@ class RedisCacheLockTest extends LockTest
{ {
protected function getInstance() protected function getInstance()
{ {
$configMock = \Mockery::mock(IConfig::class); $configMock = Mockery::mock(IConfig::class);
$host = $_SERVER['REDIS_HOST'] ?? 'localhost'; $host = $_SERVER['REDIS_HOST'] ?? 'localhost';
$port = $_SERVER['REDIS_PORT'] ?? null; $port = $_SERVER['REDIS_PORT'] ?? 6379;
$configMock $configMock
->shouldReceive('get') ->shouldReceive('get')
@ -50,7 +52,7 @@ class RedisCacheLockTest extends LockTest
$configMock $configMock
->shouldReceive('get') ->shouldReceive('get')
->with('system', 'redis_db', 0) ->with('system', 'redis_db', 0)
->andReturn(3); ->andReturn(0);
$configMock $configMock
->shouldReceive('get') ->shouldReceive('get')
->with('system', 'redis_password') ->with('system', 'redis_password')
@ -61,8 +63,8 @@ class RedisCacheLockTest extends LockTest
try { try {
$cache = new RedisCache($host, $configMock); $cache = new RedisCache($host, $configMock);
$lock = new CacheLock($cache); $lock = new CacheLock($cache);
} catch (\Exception $e) { } catch (Exception $e) {
$this->markTestSkipped('Redis is not available'); static::markTestSkipped('Redis is not available. Error: ' . $e->getMessage());
} }
return $lock; return $lock;

View file

@ -27,20 +27,21 @@ use Friendica\Core\Config\IConfig;
use Friendica\Core\Config\JitConfig; use Friendica\Core\Config\JitConfig;
use Friendica\Core\Lock\SemaphoreLock; use Friendica\Core\Lock\SemaphoreLock;
use Friendica\DI; use Friendica\DI;
use Mockery;
use Mockery\MockInterface; use Mockery\MockInterface;
class SemaphoreLockTest extends LockTest class SemaphoreLockTest extends LockTest
{ {
public function setUp() protected function setUp()
{ {
/** @var MockInterface|Dice $dice */ /** @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'); $app->shouldReceive('getHostname')->andReturn('friendica.local');
$dice->shouldReceive('create')->with(App::class)->andReturn($app); $dice->shouldReceive('create')->with(App::class)->andReturn($app);
$configMock = \Mockery::mock(JitConfig::class); $configMock = Mockery::mock(JitConfig::class);
$configMock $configMock
->shouldReceive('get') ->shouldReceive('get')
->with('system', 'temppath') ->with('system', 'temppath')
@ -58,7 +59,7 @@ class SemaphoreLockTest extends LockTest
return new SemaphoreLock(); return new SemaphoreLock();
} }
function testLockTTL() public function testLockTTL()
{ {
// Semaphore doesn't work with TTL // Semaphore doesn't work with TTL
return true; return true;
@ -73,9 +74,9 @@ class SemaphoreLockTest extends LockTest
$file = get_temppath() . '/test.sem'; $file = get_temppath() . '/test.sem';
touch($file); touch($file);
$this->assertTrue(file_exists($file)); self::assertTrue(file_exists($file));
$this->assertFalse($this->instance->release('test', false)); self::assertFalse($this->instance->release('test', false));
$this->assertTrue(file_exists($file)); self::assertTrue(file_exists($file));
} }
/** /**
@ -83,6 +84,7 @@ class SemaphoreLockTest extends LockTest
* This test proves that semaphore locks cannot get released by other instances except themselves * 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 * Check for Bug https://github.com/friendica/friendica/issues/7298#issuecomment-521996540
*
* @see https://github.com/friendica/friendica/issues/7298#issuecomment-521996540 * @see https://github.com/friendica/friendica/issues/7298#issuecomment-521996540
*/ */
public function testMissingFileOverriding() public function testMissingFileOverriding()
@ -90,9 +92,9 @@ class SemaphoreLockTest extends LockTest
$file = get_temppath() . '/test.sem'; $file = get_temppath() . '/test.sem';
touch($file); touch($file);
$this->assertTrue(file_exists($file)); self::assertTrue(file_exists($file));
$this->assertFalse($this->instance->release('test', true)); self::assertFalse($this->instance->release('test', true));
$this->assertTrue(file_exists($file)); self::assertTrue(file_exists($file));
} }
/** /**
@ -103,9 +105,9 @@ class SemaphoreLockTest extends LockTest
$file = get_temppath() . '/test.sem'; $file = get_temppath() . '/test.sem';
touch($file); touch($file);
$this->assertTrue(file_exists($file)); self::assertTrue(file_exists($file));
$this->assertTrue($this->instance->acquire('test')); self::assertTrue($this->instance->acquire('test'));
$this->assertTrue($this->instance->isLocked('test')); self::assertTrue($this->instance->isLocked('test'));
$this->assertTrue($this->instance->release('test')); self::assertTrue($this->instance->release('test'));
} }
} }

View file

@ -51,7 +51,7 @@ class CacheTest extends MockedTest
{ {
foreach ($data as $cat => $values) { foreach ($data as $cat => $values) {
foreach ($values as $key => $value) { foreach ($values as $key => $value) {
$this->assertEquals($data[$cat][$key], $configCache->get($uid, $cat, $key)); self::assertEquals($data[$cat][$key], $configCache->get($uid, $cat, $key));
} }
} }
} }
@ -72,7 +72,7 @@ class CacheTest extends MockedTest
} }
} }
$this->assertConfigValues($data, $configCache, $uid); self::assertConfigValues($data, $configCache, $uid);
} }
@ -94,13 +94,13 @@ class CacheTest extends MockedTest
], ],
]); ]);
$this->assertEquals([ self::assertEquals([
'key1' => 'value1', 'key1' => 'value1',
'key2' => 'value2', 'key2' => 'value2',
], $configCache->get($uid, 'system')); ], $configCache->get($uid, 'system'));
// test explicit cat with null as key // test explicit cat with null as key
$this->assertEquals([ self::assertEquals([
'key1' => 'value1', 'key1' => 'value1',
'key2' => 'value2', 'key2' => 'value2',
], $configCache->get($uid, 'system', null)); ], $configCache->get($uid, 'system', null));
@ -128,15 +128,13 @@ class CacheTest extends MockedTest
} }
} }
$this->assertEmpty($configCache->getAll()); self::assertEmpty($configCache->getAll());
} }
/** /**
* Test the keyDiff() method with result * Test the keyDiff() method with result
*
* @dataProvider dataTests
*/ */
public function testKeyDiffWithResult($data) public function testKeyDiffWithResult()
{ {
$configCache = new Cache(); $configCache = new Cache();
@ -146,7 +144,7 @@ class CacheTest extends MockedTest
] ]
]; ];
$this->assertEquals($diffConfig, $configCache->keyDiff($diffConfig)); self::assertEquals($diffConfig, $configCache->keyDiff($diffConfig));
} }
/** /**
@ -162,7 +160,7 @@ class CacheTest extends MockedTest
$diffConfig = $configCache->getAll(); $diffConfig = $configCache->getAll();
$this->assertEmpty($configCache->keyDiff($diffConfig)); self::assertEmpty($configCache->keyDiff($diffConfig));
} }
/** /**
@ -179,9 +177,9 @@ class CacheTest extends MockedTest
] ]
]); ]);
$this->assertEquals('supersecure', $configCache->get(1, 'database', 'password')); self::assertEquals('supersecure', $configCache->get(1, 'database', 'password'));
$this->assertNotEquals('supersecure', print_r($configCache->get(1, 'database', 'password'), true)); self::assertNotEquals('supersecure', print_r($configCache->get(1, 'database', 'password'), true));
$this->assertEquals('notsecured', print_r($configCache->get(1, 'database', 'username'), true)); self::assertEquals('notsecured', print_r($configCache->get(1, 'database', 'username'), true));
} }
/** /**
@ -198,9 +196,9 @@ class CacheTest extends MockedTest
] ]
]); ]);
$this->assertEquals('supersecure', $configCache->get(1, 'database', 'password')); self::assertEquals('supersecure', $configCache->get(1, 'database', 'password'));
$this->assertEquals('supersecure', print_r($configCache->get(1, 'database', 'password'), true)); self::assertEquals('supersecure', print_r($configCache->get(1, 'database', 'password'), true));
$this->assertEquals('notsecured', print_r($configCache->get(1, 'database', 'username'), true)); self::assertEquals('notsecured', print_r($configCache->get(1, 'database', 'username'), true));
} }
/** /**
@ -217,8 +215,8 @@ class CacheTest extends MockedTest
] ]
]); ]);
$this->assertEmpty($configCache->get(1, 'database', 'password')); self::assertEmpty($configCache->get(1, 'database', 'password'));
$this->assertEmpty($configCache->get(1, 'database', 'username')); self::assertEmpty($configCache->get(1, 'database', 'username'));
} }
public function testWrongTypePassword() public function testWrongTypePassword()
@ -232,8 +230,8 @@ class CacheTest extends MockedTest
] ]
]); ]);
$this->assertNotEmpty($configCache->get(1, 'database', 'password')); self::assertNotEmpty($configCache->get(1, 'database', 'password'));
$this->assertEmpty($configCache->get(1, 'database', 'username')); self::assertEmpty($configCache->get(1, 'database', 'username'));
$configCache = new Cache(); $configCache = new Cache();
@ -244,8 +242,8 @@ class CacheTest extends MockedTest
], ],
]); ]);
$this->assertEquals(23, $configCache->get(1, 'database', 'password')); self::assertEquals(23, $configCache->get(1, 'database', 'password'));
$this->assertEmpty($configCache->get(1, 'database', 'username')); self::assertEmpty($configCache->get(1, 'database', 'username'));
} }
/** /**
@ -268,11 +266,11 @@ class CacheTest extends MockedTest
], ],
]); ]);
$this->assertEquals('value1', $configCache->get(1, 'cat1', 'key1')); self::assertEquals('value1', $configCache->get(1, 'cat1', 'key1'));
$this->assertEquals('value2', $configCache->get(2, 'cat2', 'key2')); self::assertEquals('value2', $configCache->get(2, 'cat2', 'key2'));
$this->assertNull($configCache->get(1, 'cat2', 'key2')); self::assertNull($configCache->get(1, 'cat2', 'key2'));
$this->assertNull($configCache->get(2, 'cat1', 'key1')); self::assertNull($configCache->get(2, 'cat1', 'key1'));
} }
/** /**
@ -286,9 +284,9 @@ class CacheTest extends MockedTest
$configCache = new Cache(); $configCache = new Cache();
$this->assertNull($configCache->get($uid, 'cat1', 'cat2')); self::assertNull($configCache->get($uid, 'cat1', 'cat2'));
$this->assertFalse($configCache->set($uid, 'cat1', 'key1', 'doesn\'t matter!')); self::assertFalse($configCache->set($uid, 'cat1', 'key1', 'doesn\'t matter!'));
$this->assertFalse($configCache->delete($uid, 'cat1', 'key1')); self::assertFalse($configCache->delete($uid, 'cat1', 'key1'));
} }
} }

View file

@ -22,7 +22,6 @@
namespace Friendica\Test\src\Core\PConfig; namespace Friendica\Test\src\Core\PConfig;
use Friendica\Core\PConfig\JitPConfig; use Friendica\Core\PConfig\JitPConfig;
use Friendica\Test\src\Core\PConfig\PConfigTest;
class JitPConfigTest extends PConfigTest class JitPConfigTest extends PConfigTest
{ {
@ -78,7 +77,7 @@ class JitPConfigTest extends PConfigTest
// Assert the expected categories // Assert the expected categories
foreach ($data2 as $cat => $data) { foreach ($data2 as $cat => $data) {
$this->assertConfig($uid, $cat, $expect[$cat]); self::assertConfig($uid, $cat, $expect[$cat]);
} }
} }

View file

@ -50,10 +50,10 @@ abstract class PConfigTest extends MockedTest
{ {
$result = $this->testedConfig->getCache()->getAll(); $result = $this->testedConfig->getCache()->getAll();
$this->assertNotEmpty($result); self::assertNotEmpty($result);
$this->assertArrayHasKey($uid, $result); self::assertArrayHasKey($uid, $result);
$this->assertArrayHasKey($cat, $result[$uid]); self::assertArrayHasKey($cat, $result[$uid]);
$this->assertArraySubset($data, $result[$uid][$cat]); self::assertArraySubset($data, $result[$uid][$cat]);
} }
@ -69,7 +69,7 @@ abstract class PConfigTest extends MockedTest
/** /**
* @return BasePConfig * @return BasePConfig
*/ */
public abstract function getInstance(); abstract public function getInstance();
public function dataTests() public function dataTests()
{ {
@ -159,14 +159,13 @@ abstract class PConfigTest extends MockedTest
/** /**
* Test the configuration initialization * Test the configuration initialization
* @dataProvider dataConfigLoad
*/ */
public function testSetUp(int $uid, array $data) public function testSetUp()
{ {
$this->testedConfig = $this->getInstance(); $this->testedConfig = $this->getInstance();
$this->assertInstanceOf(Cache::class, $this->testedConfig->getCache()); self::assertInstanceOf(Cache::class, $this->testedConfig->getCache());
$this->assertEmpty($this->testedConfig->getCache()->getAll()); self::assertEmpty($this->testedConfig->getCache()->getAll());
} }
/** /**
@ -175,7 +174,7 @@ abstract class PConfigTest extends MockedTest
public function testLoad(int $uid, array $data, array $possibleCats, array $load) public function testLoad(int $uid, array $data, array $possibleCats, array $load)
{ {
$this->testedConfig = $this->getInstance(); $this->testedConfig = $this->getInstance();
$this->assertInstanceOf(Cache::class, $this->testedConfig->getCache()); self::assertInstanceOf(Cache::class, $this->testedConfig->getCache());
foreach ($load as $loadedCats) { foreach ($load as $loadedCats) {
$this->testedConfig->load($uid, $loadedCats); $this->testedConfig->load($uid, $loadedCats);
@ -183,7 +182,7 @@ abstract class PConfigTest extends MockedTest
// Assert at least loaded cats are loaded // Assert at least loaded cats are loaded
foreach ($load as $loadedCats) { foreach ($load as $loadedCats) {
$this->assertConfig($uid, $loadedCats, $data[$loadedCats]); self::assertConfig($uid, $loadedCats, $data[$loadedCats]);
} }
} }
@ -258,7 +257,7 @@ abstract class PConfigTest extends MockedTest
public function testCacheLoadDouble(int $uid, array $data1, array $data2, array $expect) public function testCacheLoadDouble(int $uid, array $data1, array $data2, array $expect)
{ {
$this->testedConfig = $this->getInstance(); $this->testedConfig = $this->getInstance();
$this->assertInstanceOf(Cache::class, $this->testedConfig->getCache()); self::assertInstanceOf(Cache::class, $this->testedConfig->getCache());
foreach ($data1 as $cat => $data) { foreach ($data1 as $cat => $data) {
$this->testedConfig->load($uid, $cat); $this->testedConfig->load($uid, $cat);
@ -266,7 +265,7 @@ abstract class PConfigTest extends MockedTest
// Assert at least loaded cats are loaded // Assert at least loaded cats are loaded
foreach ($data1 as $cat => $data) { foreach ($data1 as $cat => $data) {
$this->assertConfig($uid, $cat, $data); self::assertConfig($uid, $cat, $data);
} }
foreach ($data2 as $cat => $data) { foreach ($data2 as $cat => $data) {
@ -282,12 +281,12 @@ abstract class PConfigTest extends MockedTest
public function testSetGetWithoutDB(int $uid, $data) public function testSetGetWithoutDB(int $uid, $data)
{ {
$this->testedConfig = $this->getInstance(); $this->testedConfig = $this->getInstance();
$this->assertInstanceOf(Cache::class, $this->testedConfig->getCache()); self::assertInstanceOf(Cache::class, $this->testedConfig->getCache());
$this->assertTrue($this->testedConfig->set($uid, 'test', 'it', $data)); self::assertTrue($this->testedConfig->set($uid, 'test', 'it', $data));
$this->assertEquals($data, $this->testedConfig->get($uid, 'test', 'it')); self::assertEquals($data, $this->testedConfig->get($uid, 'test', 'it'));
$this->assertEquals($data, $this->testedConfig->getCache()->get($uid, 'test', 'it')); self::assertEquals($data, $this->testedConfig->getCache()->get($uid, 'test', 'it'));
} }
/** /**
@ -303,12 +302,12 @@ abstract class PConfigTest extends MockedTest
->once(); ->once();
$this->testedConfig = $this->getInstance(); $this->testedConfig = $this->getInstance();
$this->assertInstanceOf(Cache::class, $this->testedConfig->getCache()); self::assertInstanceOf(Cache::class, $this->testedConfig->getCache());
$this->assertTrue($this->testedConfig->set($uid, 'test', 'it', $data)); self::assertTrue($this->testedConfig->set($uid, 'test', 'it', $data));
$this->assertEquals($data, $this->testedConfig->get($uid, 'test', 'it')); self::assertEquals($data, $this->testedConfig->get($uid, 'test', 'it'));
$this->assertEquals($data, $this->testedConfig->getCache()->get($uid, 'test', 'it')); self::assertEquals($data, $this->testedConfig->getCache()->get($uid, 'test', 'it'));
} }
/** /**
@ -317,19 +316,19 @@ abstract class PConfigTest extends MockedTest
public function testGetWrongWithoutDB() public function testGetWrongWithoutDB()
{ {
$this->testedConfig = $this->getInstance(); $this->testedConfig = $this->getInstance();
$this->assertInstanceOf(Cache::class, $this->testedConfig->getCache()); self::assertInstanceOf(Cache::class, $this->testedConfig->getCache());
// without refresh // without refresh
$this->assertNull($this->testedConfig->get(0, 'test', 'it')); self::assertNull($this->testedConfig->get(0, 'test', 'it'));
/// beware that the cache returns '!<unset>!' and not null for a non existing value /// beware that the cache returns '!<unset>!' and not null for a non existing value
$this->assertNull($this->testedConfig->getCache()->get(0, 'test', 'it')); self::assertNull($this->testedConfig->getCache()->get(0, 'test', 'it'));
// with default value // with default value
$this->assertEquals('default', $this->testedConfig->get(0, 'test', 'it', 'default')); self::assertEquals('default', $this->testedConfig->get(0, 'test', 'it', 'default'));
// with default value and refresh // with default value and refresh
$this->assertEquals('default', $this->testedConfig->get(0, 'test', 'it', 'default', true)); self::assertEquals('default', $this->testedConfig->get(0, 'test', 'it', 'default', true));
} }
/** /**
@ -342,19 +341,19 @@ abstract class PConfigTest extends MockedTest
$this->configCache->load($uid, ['test' => ['it' => 'now']]); $this->configCache->load($uid, ['test' => ['it' => 'now']]);
$this->testedConfig = $this->getInstance(); $this->testedConfig = $this->getInstance();
$this->assertInstanceOf(Cache::class, $this->testedConfig->getCache()); self::assertInstanceOf(Cache::class, $this->testedConfig->getCache());
// without refresh // without refresh
$this->assertEquals('now', $this->testedConfig->get($uid, 'test', 'it')); self::assertEquals('now', $this->testedConfig->get($uid, 'test', 'it'));
$this->assertEquals('now', $this->testedConfig->getCache()->get($uid, 'test', 'it')); self::assertEquals('now', $this->testedConfig->getCache()->get($uid, 'test', 'it'));
// with refresh // with refresh
$this->assertEquals($data, $this->testedConfig->get($uid, 'test', 'it', null, true)); self::assertEquals($data, $this->testedConfig->get($uid, 'test', 'it', null, true));
$this->assertEquals($data, $this->testedConfig->getCache()->get($uid, 'test', 'it')); self::assertEquals($data, $this->testedConfig->getCache()->get($uid, 'test', 'it'));
// without refresh and wrong value and default // without refresh and wrong value and default
$this->assertEquals('default', $this->testedConfig->get($uid, 'test', 'not', 'default')); self::assertEquals('default', $this->testedConfig->get($uid, 'test', 'not', 'default'));
$this->assertNull($this->testedConfig->getCache()->get($uid, 'test', 'not')); self::assertNull($this->testedConfig->getCache()->get($uid, 'test', 'not'));
} }
/** /**
@ -367,16 +366,16 @@ abstract class PConfigTest extends MockedTest
$this->configCache->load($uid, ['test' => ['it' => $data]]); $this->configCache->load($uid, ['test' => ['it' => $data]]);
$this->testedConfig = $this->getInstance(); $this->testedConfig = $this->getInstance();
$this->assertInstanceOf(Cache::class, $this->testedConfig->getCache()); self::assertInstanceOf(Cache::class, $this->testedConfig->getCache());
$this->assertEquals($data, $this->testedConfig->get($uid, 'test', 'it')); self::assertEquals($data, $this->testedConfig->get($uid, 'test', 'it'));
$this->assertEquals($data, $this->testedConfig->getCache()->get($uid, 'test', 'it')); self::assertEquals($data, $this->testedConfig->getCache()->get($uid, 'test', 'it'));
$this->assertTrue($this->testedConfig->delete($uid, 'test', 'it')); self::assertTrue($this->testedConfig->delete($uid, 'test', 'it'));
$this->assertNull($this->testedConfig->get($uid, 'test', 'it')); self::assertNull($this->testedConfig->get($uid, 'test', 'it'));
$this->assertNull($this->testedConfig->getCache()->get($uid, 'test', 'it')); self::assertNull($this->testedConfig->getCache()->get($uid, 'test', 'it'));
$this->assertEmpty($this->testedConfig->getCache()->getAll()); self::assertEmpty($this->testedConfig->getCache()->getAll());
} }
/** /**
@ -406,24 +405,24 @@ abstract class PConfigTest extends MockedTest
->once(); ->once();
$this->testedConfig = $this->getInstance(); $this->testedConfig = $this->getInstance();
$this->assertInstanceOf(Cache::class, $this->testedConfig->getCache()); self::assertInstanceOf(Cache::class, $this->testedConfig->getCache());
// directly set the value to the cache // directly set the value to the cache
$this->testedConfig->getCache()->set($uid, 'test', 'it', 'now'); $this->testedConfig->getCache()->set($uid, 'test', 'it', 'now');
$this->assertEquals('now', $this->testedConfig->get($uid, 'test', 'it')); self::assertEquals('now', $this->testedConfig->get($uid, 'test', 'it'));
$this->assertEquals('now', $this->testedConfig->getCache()->get($uid, 'test', 'it')); self::assertEquals('now', $this->testedConfig->getCache()->get($uid, 'test', 'it'));
// delete from cache only // delete from cache only
$this->assertTrue($this->testedConfig->delete($uid, 'test', 'it')); self::assertTrue($this->testedConfig->delete($uid, 'test', 'it'));
// delete from db only // delete from db only
$this->assertTrue($this->testedConfig->delete($uid, 'test', 'second')); self::assertTrue($this->testedConfig->delete($uid, 'test', 'second'));
// no delete // no delete
$this->assertFalse($this->testedConfig->delete($uid, 'test', 'third')); self::assertFalse($this->testedConfig->delete($uid, 'test', 'third'));
// delete both // delete both
$this->assertTrue($this->testedConfig->delete($uid, 'test', 'quarter')); self::assertTrue($this->testedConfig->delete($uid, 'test', 'quarter'));
$this->assertEmpty($this->testedConfig->getCache()->getAll()); self::assertEmpty($this->testedConfig->getCache()->getAll());
} }
public function dataMultiUid() public function dataMultiUid()
@ -466,12 +465,12 @@ abstract class PConfigTest extends MockedTest
$this->configCache->load($data2['uid'], $data2['data']); $this->configCache->load($data2['uid'], $data2['data']);
$this->testedConfig = $this->getInstance(); $this->testedConfig = $this->getInstance();
$this->assertInstanceOf(Cache::class, $this->testedConfig->getCache()); self::assertInstanceOf(Cache::class, $this->testedConfig->getCache());
$this->assertConfig($data1['uid'], 'cat1', $data1['data']['cat1']); self::assertConfig($data1['uid'], 'cat1', $data1['data']['cat1']);
$this->assertConfig($data1['uid'], 'cat2', $data1['data']['cat2']); self::assertConfig($data1['uid'], 'cat2', $data1['data']['cat2']);
$this->assertConfig($data2['uid'], 'cat1', $data2['data']['cat1']); self::assertConfig($data2['uid'], 'cat1', $data2['data']['cat1']);
$this->assertConfig($data2['uid'], 'cat2', $data2['data']['cat2']); self::assertConfig($data2['uid'], 'cat2', $data2['data']['cat2']);
} }
/** /**
@ -485,10 +484,10 @@ abstract class PConfigTest extends MockedTest
$this->testedConfig = $this->getInstance(); $this->testedConfig = $this->getInstance();
$this->assertNull($this->testedConfig->get($uid, 'cat1', 'cat2')); self::assertNull($this->testedConfig->get($uid, 'cat1', 'cat2'));
$this->assertEquals('fallback!', $this->testedConfig->get($uid, 'cat1', 'cat2', 'fallback!')); self::assertEquals('fallback!', $this->testedConfig->get($uid, 'cat1', 'cat2', 'fallback!'));
$this->assertFalse($this->testedConfig->set($uid, 'cat1', 'key1', 'doesn\'t matter!')); self::assertFalse($this->testedConfig->set($uid, 'cat1', 'key1', 'doesn\'t matter!'));
$this->assertFalse($this->testedConfig->delete($uid, 'cat1', 'key1')); self::assertFalse($this->testedConfig->delete($uid, 'cat1', 'key1'));
} }
} }

View file

@ -22,7 +22,6 @@
namespace Friendica\Test\src\Core\PConfig; namespace Friendica\Test\src\Core\PConfig;
use Friendica\Core\PConfig\PreloadPConfig; use Friendica\Core\PConfig\PreloadPConfig;
use Friendica\Test\src\Core\PConfig\PConfigTest;
class PreloadPConfigTest extends PConfigTest class PreloadPConfigTest extends PConfigTest
{ {
@ -49,7 +48,7 @@ class PreloadPConfigTest extends PConfigTest
// Assert that every category is loaded everytime // Assert that every category is loaded everytime
foreach ($data as $cat => $values) { foreach ($data as $cat => $values) {
$this->assertConfig($uid, $cat, $values); self::assertConfig($uid, $cat, $values);
} }
} }
@ -71,7 +70,7 @@ class PreloadPConfigTest extends PConfigTest
// Assert that every category is loaded everytime and is NOT overwritten // Assert that every category is loaded everytime and is NOT overwritten
foreach ($data1 as $cat => $values) { foreach ($data1 as $cat => $values) {
$this->assertConfig($uid, $cat, $values); self::assertConfig($uid, $cat, $values);
} }
} }

View file

@ -34,6 +34,7 @@ use Friendica\Factory\ConfigFactory;
use Friendica\Model\Config\Config; use Friendica\Model\Config\Config;
use Friendica\Model\Storage; use Friendica\Model\Storage;
use Friendica\Core\Session; use Friendica\Core\Session;
use Friendica\Model\Storage\StorageException;
use Friendica\Test\DatabaseTest; use Friendica\Test\DatabaseTest;
use Friendica\Test\Util\Database\StaticDatabase; use Friendica\Test\Util\Database\StaticDatabase;
use Friendica\Test\Util\VFSTrait; use Friendica\Test\Util\VFSTrait;
@ -56,7 +57,7 @@ class StorageManagerTest extends DatabaseTest
use VFSTrait; use VFSTrait;
public function setUp() protected function setUp()
{ {
parent::setUp(); parent::setUp();
@ -87,7 +88,7 @@ class StorageManagerTest extends DatabaseTest
{ {
$storageManager = new StorageManager($this->dba, $this->config, $this->logger, $this->l10n); $storageManager = new StorageManager($this->dba, $this->config, $this->logger, $this->l10n);
$this->assertInstanceOf(StorageManager::class, $storageManager); self::assertInstanceOf(StorageManager::class, $storageManager);
} }
public function dataStorages() public function dataStorages()
@ -172,12 +173,12 @@ class StorageManagerTest extends DatabaseTest
$storage = $storageManager->getByName($name, $userBackend); $storage = $storageManager->getByName($name, $userBackend);
if (!empty($assert)) { if (!empty($assert)) {
$this->assertInstanceOf(Storage\IStorage::class, $storage); self::assertInstanceOf(Storage\IStorage::class, $storage);
$this->assertInstanceOf($assert, $storage); self::assertInstanceOf($assert, $storage);
} else { } else {
$this->assertNull($storage); self::assertNull($storage);
} }
$this->assertEquals($assertName, $storage); self::assertEquals($assertName, $storage);
} }
/** /**
@ -190,10 +191,10 @@ class StorageManagerTest extends DatabaseTest
$storageManager = new StorageManager($this->dba, $this->config, $this->logger, $this->l10n); $storageManager = new StorageManager($this->dba, $this->config, $this->logger, $this->l10n);
// true in every of the backends // true in every of the backends
$this->assertEquals(!empty($assertName), $storageManager->isValidBackend($name)); self::assertEquals(!empty($assertName), $storageManager->isValidBackend($name));
// if userBackend is set to true, filter out e.g. SystemRessource // if userBackend is set to true, filter out e.g. SystemRessource
$this->assertEquals($userBackend, $storageManager->isValidBackend($name, true)); self::assertEquals($userBackend, $storageManager->isValidBackend($name, true));
} }
/** /**
@ -203,7 +204,7 @@ class StorageManagerTest extends DatabaseTest
{ {
$storageManager = new StorageManager($this->dba, $this->config, $this->logger, $this->l10n); $storageManager = new StorageManager($this->dba, $this->config, $this->logger, $this->l10n);
$this->assertEquals(StorageManager::DEFAULT_BACKENDS, $storageManager->listBackends()); self::assertEquals(StorageManager::DEFAULT_BACKENDS, $storageManager->listBackends());
} }
/** /**
@ -215,12 +216,12 @@ class StorageManagerTest extends DatabaseTest
{ {
$storageManager = new StorageManager($this->dba, $this->config, $this->logger, $this->l10n); $storageManager = new StorageManager($this->dba, $this->config, $this->logger, $this->l10n);
$this->assertNull($storageManager->getBackend()); self::assertNull($storageManager->getBackend());
if ($userBackend) { if ($userBackend) {
$storageManager->setBackend($name); $storageManager->setBackend($name);
$this->assertInstanceOf($assert, $storageManager->getBackend()); self::assertInstanceOf($assert, $storageManager->getBackend());
} }
} }
@ -237,9 +238,9 @@ class StorageManagerTest extends DatabaseTest
$storageManager = new StorageManager($this->dba, $this->config, $this->logger, $this->l10n); $storageManager = new StorageManager($this->dba, $this->config, $this->logger, $this->l10n);
if ($userBackend) { if ($userBackend) {
$this->assertInstanceOf($assert, $storageManager->getBackend()); self::assertInstanceOf($assert, $storageManager->getBackend());
} else { } else {
$this->assertNull($storageManager->getBackend()); self::assertNull($storageManager->getBackend());
} }
} }
@ -261,12 +262,12 @@ class StorageManagerTest extends DatabaseTest
$storageManager = new StorageManager($this->dba, $this->config, $this->logger, $this->l10n); $storageManager = new StorageManager($this->dba, $this->config, $this->logger, $this->l10n);
$this->assertTrue($storageManager->register(SampleStorageBackend::class)); self::assertTrue($storageManager->register(SampleStorageBackend::class));
$this->assertEquals(array_merge(StorageManager::DEFAULT_BACKENDS, [ self::assertEquals(array_merge(StorageManager::DEFAULT_BACKENDS, [
SampleStorageBackend::getName() => SampleStorageBackend::class, SampleStorageBackend::getName() => SampleStorageBackend::class,
]), $storageManager->listBackends()); ]), $storageManager->listBackends());
$this->assertEquals(array_merge(StorageManager::DEFAULT_BACKENDS, [ self::assertEquals(array_merge(StorageManager::DEFAULT_BACKENDS, [
SampleStorageBackend::getName() => SampleStorageBackend::class, SampleStorageBackend::getName() => SampleStorageBackend::class,
]), $this->config->get('storage', 'backends')); ]), $this->config->get('storage', 'backends'));
@ -274,17 +275,17 @@ class StorageManagerTest extends DatabaseTest
SampleStorageBackend::registerHook(); SampleStorageBackend::registerHook();
Hook::loadHooks(); Hook::loadHooks();
$this->assertTrue($storageManager->setBackend(SampleStorageBackend::NAME)); self::assertTrue($storageManager->setBackend(SampleStorageBackend::NAME));
$this->assertEquals(SampleStorageBackend::NAME, $this->config->get('storage', 'name')); self::assertEquals(SampleStorageBackend::NAME, $this->config->get('storage', 'name'));
$this->assertInstanceOf(SampleStorageBackend::class, $storageManager->getBackend()); self::assertInstanceOf(SampleStorageBackend::class, $storageManager->getBackend());
$this->assertTrue($storageManager->unregister(SampleStorageBackend::class)); self::assertTrue($storageManager->unregister(SampleStorageBackend::class));
$this->assertEquals(StorageManager::DEFAULT_BACKENDS, $this->config->get('storage', 'backends')); self::assertEquals(StorageManager::DEFAULT_BACKENDS, $this->config->get('storage', 'backends'));
$this->assertEquals(StorageManager::DEFAULT_BACKENDS, $storageManager->listBackends()); self::assertEquals(StorageManager::DEFAULT_BACKENDS, $storageManager->listBackends());
$this->assertNull($storageManager->getBackend()); self::assertNull($storageManager->getBackend());
$this->assertNull($this->config->get('storage', 'name')); self::assertNull($this->config->get('storage', 'name'));
} }
/** /**
@ -308,23 +309,23 @@ class StorageManagerTest extends DatabaseTest
while ($photo = $this->dba->fetch($photos)) { while ($photo = $this->dba->fetch($photos)) {
$this->assertEmpty($photo['data']); self::assertEmpty($photo['data']);
$storage = $storageManager->getByName($photo['backend-class']); $storage = $storageManager->getByName($photo['backend-class']);
$data = $storage->get($photo['backend-ref']); $data = $storage->get($photo['backend-ref']);
$this->assertNotEmpty($data); self::assertNotEmpty($data);
} }
} }
/** /**
* Test moving data to a WRONG storage * Test moving data to a WRONG storage
*
* @expectedException \Friendica\Model\Storage\StorageException
* @expectedExceptionMessage Can't move to storage backend 'SystemResource'
*/ */
public function testMoveStorageWrong() 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); $storageManager = new StorageManager($this->dba, $this->config, $this->logger, $this->l10n);
$storage = $storageManager->getByName(Storage\SystemResource::getName()); $storage = $storageManager->getByName(Storage\SystemResource::getName());
$storageManager->move($storage); $storageManager->move($storage);

View file

@ -42,33 +42,33 @@ class SystemTest extends TestCase
private function assertGuid($guid, $length, $prefix = '') private function assertGuid($guid, $length, $prefix = '')
{ {
$length -= strlen($prefix); $length -= strlen($prefix);
$this->assertRegExp("/^" . $prefix . "[a-z0-9]{" . $length . "}?$/", $guid); self::assertRegExp("/^" . $prefix . "[a-z0-9]{" . $length . "}?$/", $guid);
} }
function testGuidWithoutParameter() public function testGuidWithoutParameter()
{ {
$this->useBaseUrl(); $this->useBaseUrl();
$guid = System::createGUID(); $guid = System::createGUID();
$this->assertGuid($guid, 16); self::assertGuid($guid, 16);
} }
function testGuidWithSize32() public function testGuidWithSize32()
{ {
$this->useBaseUrl(); $this->useBaseUrl();
$guid = System::createGUID(32); $guid = System::createGUID(32);
$this->assertGuid($guid, 32); self::assertGuid($guid, 32);
} }
function testGuidWithSize64() public function testGuidWithSize64()
{ {
$this->useBaseUrl(); $this->useBaseUrl();
$guid = System::createGUID(64); $guid = System::createGUID(64);
$this->assertGuid($guid, 64); self::assertGuid($guid, 64);
} }
function testGuidWithPrefix() public function testGuidWithPrefix()
{ {
$guid = System::createGUID(23, 'test'); $guid = System::createGUID(23, 'test');
$this->assertGuid($guid, 23, 'test'); self::assertGuid($guid, 23, 'test');
} }
} }

View file

@ -10,7 +10,7 @@ use Friendica\Test\Util\Database\StaticDatabase;
class DBATest extends DatabaseTest class DBATest extends DatabaseTest
{ {
public function setUp() protected function setUp()
{ {
parent::setUp(); parent::setUp();
@ -32,13 +32,13 @@ class DBATest extends DatabaseTest
*/ */
public function testExists() { public function testExists() {
$this->assertTrue(DBA::exists('config', [])); self::assertTrue(DBA::exists('config', []));
$this->assertFalse(DBA::exists('notable', [])); self::assertFalse(DBA::exists('notable', []));
$this->assertTrue(DBA::exists('config', null)); self::assertTrue(DBA::exists('config', null));
$this->assertFalse(DBA::exists('notable', null)); self::assertFalse(DBA::exists('notable', null));
$this->assertTrue(DBA::exists('config', ['k' => 'hostname'])); self::assertTrue(DBA::exists('config', ['k' => 'hostname']));
$this->assertFalse(DBA::exists('config', ['k' => 'nonsense'])); self::assertFalse(DBA::exists('config', ['k' => 'nonsense']));
} }
} }

View file

@ -44,13 +44,13 @@ class DBStructureTest extends DatabaseTest
* @small * @small
*/ */
public function testExists() { public function testExists() {
$this->assertTrue(DBStructure::existsTable('config')); self::assertTrue(DBStructure::existsTable('config'));
$this->assertFalse(DBStructure::existsTable('notatable')); self::assertFalse(DBStructure::existsTable('notatable'));
$this->assertTrue(DBStructure::existsColumn('config', ['k'])); self::assertTrue(DBStructure::existsColumn('config', ['k']));
$this->assertFalse(DBStructure::existsColumn('config', ['nonsense'])); self::assertFalse(DBStructure::existsColumn('config', ['nonsense']));
$this->assertFalse(DBStructure::existsColumn('config', ['k', 'nonsense'])); self::assertFalse(DBStructure::existsColumn('config', ['k', 'nonsense']));
} }
/** /**
@ -62,24 +62,24 @@ class DBStructureTest extends DatabaseTest
$fromType = 'varbinary(255) not null'; $fromType = 'varbinary(255) not null';
$toType = 'varbinary(255) not null comment \'Test To Type\''; $toType = 'varbinary(255) not null comment \'Test To Type\'';
$this->assertTrue(DBStructure::rename('config', [ $fromColumn => [ $toColumn, $toType ]])); self::assertTrue(DBStructure::rename('config', [ $fromColumn => [ $toColumn, $toType ]]));
$this->assertTrue(DBStructure::existsColumn('config', [ $toColumn ])); self::assertTrue(DBStructure::existsColumn('config', [ $toColumn ]));
$this->assertFalse(DBStructure::existsColumn('config', [ $fromColumn ])); self::assertFalse(DBStructure::existsColumn('config', [ $fromColumn ]));
$this->assertTrue(DBStructure::rename('config', [ $toColumn => [ $fromColumn, $fromType ]])); self::assertTrue(DBStructure::rename('config', [ $toColumn => [ $fromColumn, $fromType ]]));
$this->assertTrue(DBStructure::existsColumn('config', [ $fromColumn ])); self::assertTrue(DBStructure::existsColumn('config', [ $fromColumn ]));
$this->assertFalse(DBStructure::existsColumn('config', [ $toColumn ])); self::assertFalse(DBStructure::existsColumn('config', [ $toColumn ]));
} }
/** /**
* @small * @small
*/ */
public function testChangePrimaryKey() { 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'; $oldID = 'client_id';
$newID = 'pw'; $newID = 'pw';
$this->assertTrue(DBStructure::rename('clients', [ $newID ], DBStructure::RENAME_PRIMARY_KEY)); self::assertTrue(DBStructure::rename('clients', [ $newID ], DBStructure::RENAME_PRIMARY_KEY));
$this->assertTrue(DBStructure::rename('clients', [ $oldID ], DBStructure::RENAME_PRIMARY_KEY)); self::assertTrue(DBStructure::rename('clients', [ $oldID ], DBStructure::RENAME_PRIMARY_KEY));
} }
} }

View file

@ -73,7 +73,7 @@ class FileTagTest extends TestCase
*/ */
public function testArrayToFile(array $array, string $type, string $file) public function testArrayToFile(array $array, string $type, string $file)
{ {
$this->assertEquals($file, FileTag::arrayToFile($array, $type)); self::assertEquals($file, FileTag::arrayToFile($array, $type));
} }
public function dataFileToArray() public function dataFileToArray()
@ -133,6 +133,6 @@ class FileTagTest extends TestCase
*/ */
public function testFileToArray(string $file, string $type, array $array) public function testFileToArray(string $file, string $type, array $array)
{ {
$this->assertEquals($array, FileTag::fileToArray($file, $type)); self::assertEquals($array, FileTag::fileToArray($file, $type));
} }
} }

View file

@ -24,7 +24,7 @@ class ProcessTest extends DatabaseTest
$this->setUpVfsDir(); $this->setUpVfsDir();
$this->logger = new NullLogger(); $logger = new NullLogger();
$profiler = \Mockery::mock(Profiler::class); $profiler = \Mockery::mock(Profiler::class);
$profiler->shouldReceive('saveTimestamp')->withAnyArgs()->andReturn(true); $profiler->shouldReceive('saveTimestamp')->withAnyArgs()->andReturn(true);
@ -34,29 +34,29 @@ class ProcessTest extends DatabaseTest
$loader = new ConfigFileLoader($this->root->url()); $loader = new ConfigFileLoader($this->root->url());
$configCache = $configFactory->createCache($loader); $configCache = $configFactory->createCache($loader);
$this->dba = new StaticDatabase($configCache, $profiler, $this->logger); $this->dba = new StaticDatabase($configCache, $profiler, $logger);
} }
public function testInsertDelete() public function testInsertDelete()
{ {
$process = new Process($this->dba); $process = new Process($this->dba);
$this->assertEquals(0, $this->dba->count('process')); self::assertEquals(0, $this->dba->count('process'));
$process->insert('test', 1); $process->insert('test', 1);
$process->insert('test2', 2); $process->insert('test2', 2);
$process->insert('test3', 3); $process->insert('test3', 3);
$this->assertEquals(3, $this->dba->count('process')); self::assertEquals(3, $this->dba->count('process'));
$this->assertEquals([ self::assertEquals([
['command' => 'test'] ['command' => 'test']
], $this->dba->selectToArray('process', ['command'], ['pid' => 1])); ], $this->dba->selectToArray('process', ['command'], ['pid' => 1]));
$process->deleteByPid(1); $process->deleteByPid(1);
$this->assertEmpty($this->dba->selectToArray('process', ['command'], ['pid' => 1])); self::assertEmpty($this->dba->selectToArray('process', ['command'], ['pid' => 1]));
$this->assertEquals(2, $this->dba->count('process')); self::assertEquals(2, $this->dba->count('process'));
} }
public function testDoubleInsert() public function testDoubleInsert()
@ -68,7 +68,7 @@ class ProcessTest extends DatabaseTest
// double insert doesn't work // double insert doesn't work
$process->insert('test23', 1); $process->insert('test23', 1);
$this->assertEquals([['command' => 'test']], $this->dba->selectToArray('process', ['command'], ['pid' => 1])); self::assertEquals([['command' => 'test']], $this->dba->selectToArray('process', ['command'], ['pid' => 1]));
} }
public function testWrongDelete() public function testWrongDelete()

View file

@ -66,6 +66,6 @@ class DatabaseStorageTest extends StorageTest
protected function assertOption(IStorage $storage) protected function assertOption(IStorage $storage)
{ {
$this->assertEmpty($storage->getOptions()); self::assertEmpty($storage->getOptions());
} }
} }

View file

@ -25,12 +25,12 @@ use Friendica\Core\Config\IConfig;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Model\Storage\Filesystem; use Friendica\Model\Storage\Filesystem;
use Friendica\Model\Storage\IStorage; use Friendica\Model\Storage\IStorage;
use Friendica\Model\Storage\StorageException;
use Friendica\Test\Util\VFSTrait; use Friendica\Test\Util\VFSTrait;
use Friendica\Util\Profiler; use Friendica\Util\Profiler;
use Mockery\MockInterface; use Mockery\MockInterface;
use org\bovigo\vfs\vfsStream; use org\bovigo\vfs\vfsStream;
use Psr\Log\NullLogger; use Psr\Log\NullLogger;
use function GuzzleHttp\Psr7\uri_for;
class FilesystemStorageTest extends StorageTest class FilesystemStorageTest extends StorageTest
{ {
@ -66,7 +66,7 @@ class FilesystemStorageTest extends StorageTest
protected function assertOption(IStorage $storage) protected function assertOption(IStorage $storage)
{ {
$this->assertEquals([ self::assertEquals([
'storagepath' => [ 'storagepath' => [
'input', 'Storage base path', 'input', 'Storage base path',
$this->root->getChild('storage')->url(), $this->root->getChild('storage')->url(),
@ -77,12 +77,11 @@ class FilesystemStorageTest extends StorageTest
/** /**
* Test the exception in case of missing directorsy permissions * 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() public function testMissingDirPermissions()
{ {
$this->expectException(StorageException::class);
$this->expectExceptionMessageRegExp("/Filesystem storage failed to create \".*\". Check you write permissions./");
$this->root->getChild('storage')->chmod(000); $this->root->getChild('storage')->chmod(000);
$instance = $this->getInstance(); $instance = $this->getInstance();
@ -92,12 +91,13 @@ class FilesystemStorageTest extends StorageTest
/** /**
* Test the exception in case of missing file permissions * 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() 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); vfsStream::create(['storage' => ['f0' => ['c0' => ['k0i0' => '']]]], $this->root);
@ -119,12 +119,12 @@ class FilesystemStorageTest extends StorageTest
$dir = $this->root->getChild('storage/f0/c0')->url(); $dir = $this->root->getChild('storage/f0/c0')->url();
$file = $this->root->getChild('storage/f0/c0/d0i0')->url(); $file = $this->root->getChild('storage/f0/c0/d0i0')->url();
$this->assertDirectoryExists($dir); self::assertDirectoryExists($dir);
$this->assertFileExists($file); self::assertFileExists($file);
$this->assertDirectoryIsWritable($dir); self::assertDirectoryIsWritable($dir);
$this->assertFileIsWritable($file); self::assertFileIsWritable($file);
$this->assertEquals('test', file_get_contents($file)); self::assertEquals('test', file_get_contents($file));
} }
} }

View file

@ -37,7 +37,7 @@ abstract class StorageTest extends MockedTest
public function testInstance() public function testInstance()
{ {
$instance = $this->getInstance(); $instance = $this->getInstance();
$this->assertInstanceOf(IStorage::class, $instance); self::assertInstanceOf(IStorage::class, $instance);
} }
/** /**
@ -58,11 +58,11 @@ abstract class StorageTest extends MockedTest
$instance = $this->getInstance(); $instance = $this->getInstance();
$ref = $instance->put('data12345'); $ref = $instance->put('data12345');
$this->assertNotEmpty($ref); self::assertNotEmpty($ref);
$this->assertEquals('data12345', $instance->get($ref)); self::assertEquals('data12345', $instance->get($ref));
$this->assertTrue($instance->delete($ref)); self::assertTrue($instance->delete($ref));
} }
/** /**
@ -73,7 +73,7 @@ abstract class StorageTest extends MockedTest
$instance = $this->getInstance(); $instance = $this->getInstance();
// Even deleting not existing references should return "true" // Even deleting not existing references should return "true"
$this->assertTrue($instance->delete(-1234456)); self::assertTrue($instance->delete(-1234456));
} }
/** /**
@ -84,7 +84,7 @@ abstract class StorageTest extends MockedTest
$instance = $this->getInstance(); $instance = $this->getInstance();
// Invalid references return an empty string // Invalid references return an empty string
$this->assertEmpty($instance->get(-123456)); self::assertEmpty($instance->get(-123456));
} }
/** /**
@ -95,12 +95,12 @@ abstract class StorageTest extends MockedTest
$instance = $this->getInstance(); $instance = $this->getInstance();
$ref = $instance->put('data12345'); $ref = $instance->put('data12345');
$this->assertNotEmpty($ref); self::assertNotEmpty($ref);
$this->assertEquals('data12345', $instance->get($ref)); self::assertEquals('data12345', $instance->get($ref));
$this->assertEquals($ref, $instance->put('data5432', $ref)); self::assertEquals($ref, $instance->put('data5432', $ref));
$this->assertEquals('data5432', $instance->get($ref)); self::assertEquals('data5432', $instance->get($ref));
} }
/** /**
@ -110,6 +110,6 @@ abstract class StorageTest extends MockedTest
{ {
$instance = $this->getInstance(); $instance = $this->getInstance();
$this->assertEquals(-123, $instance->put('data12345', -123)); self::assertEquals(-123, $instance->put('data12345', -123));
} }
} }

View file

@ -48,6 +48,8 @@ class CookieTest extends MockedTest
protected function tearDown() protected function tearDown()
{ {
StaticCookie::clearStatic(); StaticCookie::clearStatic();
parent::tearDown();
} }
/** /**
@ -60,7 +62,7 @@ class CookieTest extends MockedTest
$this->config->shouldReceive('get')->with('system', 'auth_cookie_lifetime', Cookie::DEFAULT_EXPIRE)->andReturn('7')->once(); $this->config->shouldReceive('get')->with('system', 'auth_cookie_lifetime', Cookie::DEFAULT_EXPIRE)->andReturn('7')->once();
$cookie = new Cookie($this->config, $this->baseUrl); $cookie = new Cookie($this->config, $this->baseUrl);
$this->assertInstanceOf(Cookie::class, $cookie); self::assertInstanceOf(Cookie::class, $cookie);
} }
public function dataGet() public function dataGet()
@ -124,31 +126,31 @@ class CookieTest extends MockedTest
$this->config->shouldReceive('get')->with('system', 'auth_cookie_lifetime', Cookie::DEFAULT_EXPIRE)->andReturn('7')->once(); $this->config->shouldReceive('get')->with('system', 'auth_cookie_lifetime', Cookie::DEFAULT_EXPIRE)->andReturn('7')->once();
$cookie = new Cookie($this->config, $this->baseUrl, [], $cookieData); $cookie = new Cookie($this->config, $this->baseUrl, [], $cookieData);
$this->assertInstanceOf(Cookie::class, $cookie); self::assertInstanceOf(Cookie::class, $cookie);
$assertData = $cookie->getData(); $assertData = $cookie->getData();
if (!$hasValues) { if (!$hasValues) {
$this->assertEmpty($assertData); self::assertEmpty($assertData);
} else { } else {
$this->assertNotEmpty($assertData); self::assertNotEmpty($assertData);
if (isset($uid)) { if (isset($uid)) {
$this->assertObjectHasAttribute('uid', $assertData); self::assertObjectHasAttribute('uid', $assertData);
$this->assertEquals($uid, $assertData->uid); self::assertEquals($uid, $assertData->uid);
} else { } else {
$this->assertObjectNotHasAttribute('uid', $assertData); self::assertObjectNotHasAttribute('uid', $assertData);
} }
if (isset($hash)) { if (isset($hash)) {
$this->assertObjectHasAttribute('hash', $assertData); self::assertObjectHasAttribute('hash', $assertData);
$this->assertEquals($hash, $assertData->hash); self::assertEquals($hash, $assertData->hash);
} else { } else {
$this->assertObjectNotHasAttribute('hash', $assertData); self::assertObjectNotHasAttribute('hash', $assertData);
} }
if (isset($ip)) { if (isset($ip)) {
$this->assertObjectHasAttribute('ip', $assertData); self::assertObjectHasAttribute('ip', $assertData);
$this->assertEquals($ip, $assertData->ip); self::assertEquals($ip, $assertData->ip);
} else { } else {
$this->assertObjectNotHasAttribute('ip', $assertData); self::assertObjectNotHasAttribute('ip', $assertData);
} }
} }
} }
@ -192,9 +194,9 @@ class CookieTest extends MockedTest
$this->config->shouldReceive('get')->with('system', 'auth_cookie_lifetime', Cookie::DEFAULT_EXPIRE)->andReturn('7')->once(); $this->config->shouldReceive('get')->with('system', 'auth_cookie_lifetime', Cookie::DEFAULT_EXPIRE)->andReturn('7')->once();
$cookie = new Cookie($this->config, $this->baseUrl); $cookie = new Cookie($this->config, $this->baseUrl);
$this->assertInstanceOf(Cookie::class, $cookie); self::assertInstanceOf(Cookie::class, $cookie);
$this->assertEquals($assertTrue, $cookie->check($assertHash, $password, $userPrivateKey)); self::assertEquals($assertTrue, $cookie->check($assertHash, $password, $userPrivateKey));
} }
public function dataSet() public function dataSet()
@ -245,21 +247,21 @@ class CookieTest extends MockedTest
public function assertCookie($uid, $hash, $remoteIp, $lifetime) public function assertCookie($uid, $hash, $remoteIp, $lifetime)
{ {
$this->assertArrayHasKey(Cookie::NAME, StaticCookie::$_COOKIE); self::assertArrayHasKey(Cookie::NAME, StaticCookie::$_COOKIE);
$data = json_decode(StaticCookie::$_COOKIE[Cookie::NAME]); $data = json_decode(StaticCookie::$_COOKIE[Cookie::NAME]);
$this->assertObjectHasAttribute('uid', $data); self::assertObjectHasAttribute('uid', $data);
$this->assertEquals($uid, $data->uid); self::assertEquals($uid, $data->uid);
$this->assertObjectHasAttribute('hash', $data); self::assertObjectHasAttribute('hash', $data);
$this->assertEquals($hash, $data->hash); self::assertEquals($hash, $data->hash);
$this->assertObjectHasAttribute('ip', $data); self::assertObjectHasAttribute('ip', $data);
$this->assertEquals($remoteIp, $data->ip); self::assertEquals($remoteIp, $data->ip);
if (isset($lifetime) && $lifetime !== 0) { if (isset($lifetime) && $lifetime !== 0) {
$this->assertLessThanOrEqual(time() + $lifetime, StaticCookie::$_EXPIRE); self::assertLessThanOrEqual(time() + $lifetime, StaticCookie::$_EXPIRE);
} else { } else {
$this->assertLessThanOrEqual(time() + Cookie::DEFAULT_EXPIRE * 24 * 60 * 60, StaticCookie::$_EXPIRE); self::assertLessThanOrEqual(time() + Cookie::DEFAULT_EXPIRE * 24 * 60 * 60, StaticCookie::$_EXPIRE);
} }
} }
@ -275,11 +277,11 @@ class CookieTest extends MockedTest
$this->config->shouldReceive('get')->with('system', 'auth_cookie_lifetime', Cookie::DEFAULT_EXPIRE)->andReturn(Cookie::DEFAULT_EXPIRE)->once(); $this->config->shouldReceive('get')->with('system', 'auth_cookie_lifetime', Cookie::DEFAULT_EXPIRE)->andReturn(Cookie::DEFAULT_EXPIRE)->once();
$cookie = new StaticCookie($this->config, $this->baseUrl, $serverArray); $cookie = new StaticCookie($this->config, $this->baseUrl, $serverArray);
$this->assertInstanceOf(Cookie::class, $cookie); self::assertInstanceOf(Cookie::class, $cookie);
$cookie->set($uid, $password, $privateKey, $lifetime); $cookie->set($uid, $password, $privateKey, $lifetime);
$this->assertCookie($uid, $assertHash, $remoteIp, $lifetime); self::assertCookie($uid, $assertHash, $remoteIp, $lifetime);
} }
/** /**
@ -294,14 +296,14 @@ class CookieTest extends MockedTest
$this->config->shouldReceive('get')->with('system', 'auth_cookie_lifetime', Cookie::DEFAULT_EXPIRE)->andReturn(Cookie::DEFAULT_EXPIRE)->once(); $this->config->shouldReceive('get')->with('system', 'auth_cookie_lifetime', Cookie::DEFAULT_EXPIRE)->andReturn(Cookie::DEFAULT_EXPIRE)->once();
$cookie = new StaticCookie($this->config, $this->baseUrl, $serverArray); $cookie = new StaticCookie($this->config, $this->baseUrl, $serverArray);
$this->assertInstanceOf(Cookie::class, $cookie); self::assertInstanceOf(Cookie::class, $cookie);
// Invalid set, should get overwritten // Invalid set, should get overwritten
$cookie->set(-1, 'invalid', 'nothing', -234); $cookie->set(-1, 'invalid', 'nothing', -234);
$cookie->set($uid, $password, $privateKey, $lifetime); $cookie->set($uid, $password, $privateKey, $lifetime);
$this->assertCookie($uid, $assertHash, $remoteIp, $lifetime); self::assertCookie($uid, $assertHash, $remoteIp, $lifetime);
} }
/** /**
@ -318,14 +320,14 @@ class CookieTest extends MockedTest
$this->config->shouldReceive('get')->with('system', 'auth_cookie_lifetime', Cookie::DEFAULT_EXPIRE)->andReturn(Cookie::DEFAULT_EXPIRE)->once(); $this->config->shouldReceive('get')->with('system', 'auth_cookie_lifetime', Cookie::DEFAULT_EXPIRE)->andReturn(Cookie::DEFAULT_EXPIRE)->once();
$cookie = new StaticCookie($this->config, $this->baseUrl); $cookie = new StaticCookie($this->config, $this->baseUrl);
$this->assertInstanceOf(Cookie::class, $cookie); self::assertInstanceOf(Cookie::class, $cookie);
$this->assertEquals('test', StaticCookie::$_COOKIE[Cookie::NAME]); self::assertEquals('test', StaticCookie::$_COOKIE[Cookie::NAME]);
$this->assertEquals(null, StaticCookie::$_EXPIRE); self::assertEquals(null, StaticCookie::$_EXPIRE);
$cookie->clear(); $cookie->clear();
$this->assertEmpty(StaticCookie::$_COOKIE[Cookie::NAME]); self::assertEmpty(StaticCookie::$_COOKIE[Cookie::NAME]);
$this->assertEquals(-3600, StaticCookie::$_EXPIRE); self::assertEquals(-3600, StaticCookie::$_EXPIRE);
} }
} }

View file

@ -72,7 +72,7 @@ class UserTest extends MockedTest
$record = User::identities($this->parent['uid']); $record = User::identities($this->parent['uid']);
$this->assertEquals([], $record); self::assertEquals([], $record);
} }
public function testIdentitiesAsParent() public function testIdentitiesAsParent()
@ -109,7 +109,7 @@ class UserTest extends MockedTest
$record = User::identities($this->parent['uid']); $record = User::identities($this->parent['uid']);
$this->assertEquals([ self::assertEquals([
$this->parent, $this->parent,
$this->child, $this->child,
$this->manage $this->manage
@ -162,7 +162,7 @@ class UserTest extends MockedTest
$record = User::identities($this->child['uid']); $record = User::identities($this->child['uid']);
$this->assertEquals([ self::assertEquals([
$this->parent, $this->parent,
$this->child, $this->child,
$this->manage $this->manage

View file

@ -2,6 +2,8 @@
namespace Friendica\Test\src\Module\Api\Twitter; namespace Friendica\Test\src\Module\Api\Twitter;
use Friendica\Module\Api\Twitter\ContactEndpoint;
/** /**
* Class ContactEndpointMock * Class ContactEndpointMock
* *
@ -13,7 +15,7 @@ namespace Friendica\Test\src\Module\Api\Twitter;
* *
* @package Friendica\Test\Mock\Module\Api\Twitter * @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) public static function __callStatic($name, $arguments)
{ {

View file

@ -4,6 +4,7 @@ namespace Friendica\Test\src\Module\Api\Twitter;
use Friendica\Model\Contact; use Friendica\Model\Contact;
use Friendica\Module\Api\Twitter\ContactEndpoint; use Friendica\Module\Api\Twitter\ContactEndpoint;
use Friendica\Network\HTTPException\InternalServerErrorException;
use Friendica\Network\HTTPException\NotFoundException; use Friendica\Network\HTTPException\NotFoundException;
use Friendica\Object\Api\Twitter\User; use Friendica\Object\Api\Twitter\User;
use Friendica\Test\FixtureTest; use Friendica\Test\FixtureTest;
@ -12,9 +13,9 @@ class ContactEndpointTest extends FixtureTest
{ {
public function testGetUid() public function testGetUid()
{ {
$this->assertSame(42, ContactEndpointMock::getUid(42)); self::assertSame(42, ContactEndpointMock::getUid(42));
$this->assertSame(42, ContactEndpointMock::getUid(null, 'selfcontact')); self::assertSame(42, ContactEndpointMock::getUid(null, 'selfcontact'));
$this->assertSame(42, ContactEndpointMock::getUid(84, 'selfcontact')); self::assertSame(42, ContactEndpointMock::getUid(84, 'selfcontact'));
} }
public function testGetUidContactIdNotFound() public function testGetUidContactIdNotFound()
@ -52,7 +53,7 @@ class ContactEndpointTest extends FixtureTest
'total_count' => 0, 'total_count' => 0,
]; ];
$this->assertSame($expectedEmpty, ContactEndpointMock::ids(Contact::FOLLOWER, 42)); self::assertSame($expectedEmpty, ContactEndpointMock::ids(Contact::FOLLOWER, 42));
$expectedFriend = [ $expectedFriend = [
'ids' => [47], 'ids' => [47],
@ -63,20 +64,20 @@ class ContactEndpointTest extends FixtureTest
'total_count' => 1, 'total_count' => 1,
]; ];
$this->assertSame($expectedFriend, ContactEndpointMock::ids(Contact::FRIEND, 42)); self::assertSame($expectedFriend, ContactEndpointMock::ids(Contact::FRIEND, 42));
$this->assertSame($expectedFriend, ContactEndpointMock::ids([Contact::FOLLOWER, Contact::FRIEND], 42)); self::assertSame($expectedFriend, ContactEndpointMock::ids([Contact::FOLLOWER, Contact::FRIEND], 42));
$result = ContactEndpointMock::ids(Contact::SHARING, 42); $result = ContactEndpointMock::ids(Contact::SHARING, 42);
$this->assertArrayHasKey('ids', $result); self::assertArrayHasKey('ids', $result);
$this->assertContainsOnly('int', $result['ids']); self::assertContainsOnly('int', $result['ids']);
$this->assertSame(45, $result['ids'][0]); self::assertSame(45, $result['ids'][0]);
$result = ContactEndpointMock::ids([Contact::SHARING, Contact::FRIEND], 42); $result = ContactEndpointMock::ids([Contact::SHARING, Contact::FRIEND], 42);
$this->assertArrayHasKey('ids', $result); self::assertArrayHasKey('ids', $result);
$this->assertContainsOnly('int', $result['ids']); self::assertContainsOnly('int', $result['ids']);
$this->assertSame(45, $result['ids'][0]); self::assertSame(45, $result['ids'][0]);
} }
/** /**
@ -88,9 +89,9 @@ class ContactEndpointTest extends FixtureTest
{ {
$result = ContactEndpointMock::ids(Contact::SHARING, 42, -1, ContactEndpoint::DEFAULT_COUNT, true); $result = ContactEndpointMock::ids(Contact::SHARING, 42, -1, ContactEndpoint::DEFAULT_COUNT, true);
$this->assertArrayHasKey('ids', $result); self::assertArrayHasKey('ids', $result);
$this->assertContainsOnly('string', $result['ids']); self::assertContainsOnly('string', $result['ids']);
$this->assertSame('45', $result['ids'][0]); self::assertSame('45', $result['ids'][0]);
} }
public function testIdsPagination() public function testIdsPagination()
@ -106,7 +107,7 @@ class ContactEndpointTest extends FixtureTest
$result = ContactEndpointMock::ids([Contact::SHARING, Contact::FRIEND], 42, -1, 1); $result = ContactEndpointMock::ids([Contact::SHARING, Contact::FRIEND], 42, -1, 1);
$this->assertSame($expectedDefaultPageResult, $result); self::assertSame($expectedDefaultPageResult, $result);
$nextPageCursor = $result['next_cursor']; $nextPageCursor = $result['next_cursor'];
@ -121,7 +122,7 @@ class ContactEndpointTest extends FixtureTest
$result = ContactEndpointMock::ids([Contact::SHARING, Contact::FRIEND], 42, $nextPageCursor, 1); $result = ContactEndpointMock::ids([Contact::SHARING, Contact::FRIEND], 42, $nextPageCursor, 1);
$this->assertSame($expectedSecondPageResult, $result); self::assertSame($expectedSecondPageResult, $result);
$firstPageCursor = $result['previous_cursor']; $firstPageCursor = $result['previous_cursor'];
$emptyNextPageCursor = $result['next_cursor']; $emptyNextPageCursor = $result['next_cursor'];
@ -137,7 +138,7 @@ class ContactEndpointTest extends FixtureTest
$result = ContactEndpointMock::ids([Contact::SHARING, Contact::FRIEND], 42, $firstPageCursor, 1); $result = ContactEndpointMock::ids([Contact::SHARING, Contact::FRIEND], 42, $firstPageCursor, 1);
$this->assertSame($expectedFirstPageResult, $result); self::assertSame($expectedFirstPageResult, $result);
$emptyPrevPageCursor = $result['previous_cursor']; $emptyPrevPageCursor = $result['previous_cursor'];
@ -152,7 +153,7 @@ class ContactEndpointTest extends FixtureTest
$result = ContactEndpointMock::ids([Contact::SHARING, Contact::FRIEND], 42, $emptyPrevPageCursor, 1); $result = ContactEndpointMock::ids([Contact::SHARING, Contact::FRIEND], 42, $emptyPrevPageCursor, 1);
$this->assertSame($expectedEmptyPrevPageResult, $result); self::assertSame($expectedEmptyPrevPageResult, $result);
$expectedEmptyNextPageResult = [ $expectedEmptyNextPageResult = [
'ids' => [], 'ids' => [],
@ -165,14 +166,14 @@ class ContactEndpointTest extends FixtureTest
$result = ContactEndpointMock::ids([Contact::SHARING, Contact::FRIEND], 42, $emptyNextPageCursor, 1); $result = ContactEndpointMock::ids([Contact::SHARING, Contact::FRIEND], 42, $emptyNextPageCursor, 1);
$this->assertSame($expectedEmptyNextPageResult, $result); self::assertSame($expectedEmptyNextPageResult, $result);
} }
/** /**
* @depends testIds * @depends testIds
* *
* @throws NotFoundException * @throws NotFoundException
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
*/ */
public function testList() public function testList()
@ -186,7 +187,7 @@ class ContactEndpointTest extends FixtureTest
'total_count' => 0, 'total_count' => 0,
]; ];
$this->assertSame($expectedEmpty, ContactEndpointMock::list(Contact::FOLLOWER, 42)); self::assertSame($expectedEmpty, ContactEndpointMock::list(Contact::FOLLOWER, 42));
$expectedFriendContactUser = [ $expectedFriendContactUser = [
'id' => 45, 'id' => 45,
@ -241,14 +242,14 @@ class ContactEndpointTest extends FixtureTest
$result = ContactEndpointMock::list(Contact::SHARING, 42); $result = ContactEndpointMock::list(Contact::SHARING, 42);
$this->assertArrayHasKey('users', $result); self::assertArrayHasKey('users', $result);
$this->assertContainsOnlyInstancesOf(User::class, $result['users']); self::assertContainsOnlyInstancesOf(User::class, $result['users']);
$this->assertSame($expectedFriendContactUser, $result['users'][0]->toArray()); self::assertSame($expectedFriendContactUser, $result['users'][0]->toArray());
$result = ContactEndpointMock::list([Contact::SHARING, Contact::FRIEND], 42); $result = ContactEndpointMock::list([Contact::SHARING, Contact::FRIEND], 42);
$this->assertArrayHasKey('users', $result); self::assertArrayHasKey('users', $result);
$this->assertContainsOnlyInstancesOf(User::class, $result['users']); self::assertContainsOnlyInstancesOf(User::class, $result['users']);
$this->assertSame($expectedFriendContactUser, $result['users'][0]->toArray()); self::assertSame($expectedFriendContactUser, $result['users'][0]->toArray());
} }
} }

View file

@ -62,14 +62,14 @@ class CurlResultTest extends TestCase
'url' => 'https://test.local' 'url' => 'https://test.local'
]); ]);
$this->assertTrue($curlResult->isSuccess()); self::assertTrue($curlResult->isSuccess());
$this->assertFalse($curlResult->isTimeout()); self::assertFalse($curlResult->isTimeout());
$this->assertFalse($curlResult->isRedirectUrl()); self::assertFalse($curlResult->isRedirectUrl());
$this->assertSame($header, $curlResult->getHeader()); self::assertSame($header, $curlResult->getHeader());
$this->assertSame($body, $curlResult->getBody()); self::assertSame($body, $curlResult->getBody());
$this->assertSame('text/html; charset=utf-8', $curlResult->getContentType()); self::assertSame('text/html; charset=utf-8', $curlResult->getContentType());
$this->assertSame('https://test.local', $curlResult->getUrl()); self::assertSame('https://test.local', $curlResult->getUrl());
$this->assertSame('https://test.local', $curlResult->getRedirectUrl()); self::assertSame('https://test.local', $curlResult->getRedirectUrl());
} }
/** /**
@ -90,14 +90,14 @@ class CurlResultTest extends TestCase
'redirect_url' => 'https://test.other' 'redirect_url' => 'https://test.other'
]); ]);
$this->assertTrue($curlResult->isSuccess()); self::assertTrue($curlResult->isSuccess());
$this->assertFalse($curlResult->isTimeout()); self::assertFalse($curlResult->isTimeout());
$this->assertTrue($curlResult->isRedirectUrl()); self::assertTrue($curlResult->isRedirectUrl());
$this->assertSame($header, $curlResult->getHeader()); self::assertSame($header, $curlResult->getHeader());
$this->assertSame($body, $curlResult->getBody()); self::assertSame($body, $curlResult->getBody());
$this->assertSame('text/html; charset=utf-8', $curlResult->getContentType()); self::assertSame('text/html; charset=utf-8', $curlResult->getContentType());
$this->assertSame('https://test.local/test/it', $curlResult->getUrl()); self::assertSame('https://test.local/test/it', $curlResult->getUrl());
$this->assertSame('https://test.other/test/it', $curlResult->getRedirectUrl()); self::assertSame('https://test.other/test/it', $curlResult->getRedirectUrl());
} }
/** /**
@ -116,14 +116,14 @@ class CurlResultTest extends TestCase
'redirect_url' => 'https://test.other' 'redirect_url' => 'https://test.other'
], CURLE_OPERATION_TIMEDOUT, 'Tested error'); ], CURLE_OPERATION_TIMEDOUT, 'Tested error');
$this->assertFalse($curlResult->isSuccess()); self::assertFalse($curlResult->isSuccess());
$this->assertTrue($curlResult->isTimeout()); self::assertTrue($curlResult->isTimeout());
$this->assertFalse($curlResult->isRedirectUrl()); self::assertFalse($curlResult->isRedirectUrl());
$this->assertSame($header, $curlResult->getHeader()); self::assertSame($header, $curlResult->getHeader());
$this->assertSame($body, $curlResult->getBody()); self::assertSame($body, $curlResult->getBody());
$this->assertSame('text/html; charset=utf-8', $curlResult->getContentType()); self::assertSame('text/html; charset=utf-8', $curlResult->getContentType());
$this->assertSame('https://test.local/test/it', $curlResult->getRedirectUrl()); self::assertSame('https://test.local/test/it', $curlResult->getRedirectUrl());
$this->assertSame('Tested error', $curlResult->getError()); self::assertSame('Tested error', $curlResult->getError());
} }
/** /**
@ -143,14 +143,14 @@ class CurlResultTest extends TestCase
'url' => 'https://test.local/test/it?key=value', 'url' => 'https://test.local/test/it?key=value',
]); ]);
$this->assertTrue($curlResult->isSuccess()); self::assertTrue($curlResult->isSuccess());
$this->assertFalse($curlResult->isTimeout()); self::assertFalse($curlResult->isTimeout());
$this->assertTrue($curlResult->isRedirectUrl()); self::assertTrue($curlResult->isRedirectUrl());
$this->assertSame($header, $curlResult->getHeader()); self::assertSame($header, $curlResult->getHeader());
$this->assertSame($body, $curlResult->getBody()); self::assertSame($body, $curlResult->getBody());
$this->assertSame('text/html; charset=utf-8', $curlResult->getContentType()); self::assertSame('text/html; charset=utf-8', $curlResult->getContentType());
$this->assertSame('https://test.local/test/it?key=value', $curlResult->getUrl()); self::assertSame('https://test.local/test/it?key=value', $curlResult->getUrl());
$this->assertSame('https://test.other/some/?key=value', $curlResult->getRedirectUrl()); self::assertSame('https://test.other/some/?key=value', $curlResult->getRedirectUrl());
} }
/** /**
@ -166,8 +166,8 @@ class CurlResultTest extends TestCase
'content_type' => 'text/html; charset=utf-8', 'content_type' => 'text/html; charset=utf-8',
'url' => 'https://test.local' 'url' => 'https://test.local'
]); ]);
$this->assertTrue($curlResult->inHeader('vary')); self::assertTrue($curlResult->inHeader('vary'));
$this->assertFalse($curlResult->inHeader('wrongHeader')); self::assertFalse($curlResult->inHeader('wrongHeader'));
} }
/** /**
@ -186,8 +186,8 @@ class CurlResultTest extends TestCase
$headers = $curlResult->getHeaderArray(); $headers = $curlResult->getHeaderArray();
$this->assertNotEmpty($headers); self::assertNotEmpty($headers);
$this->assertArrayHasKey('vary', $headers); self::assertArrayHasKey('vary', $headers);
} }
/** /**
@ -204,7 +204,7 @@ class CurlResultTest extends TestCase
'url' => 'https://test.local' 'url' => 'https://test.local'
]); ]);
$this->assertNotEmpty($curlResult->getHeader()); self::assertNotEmpty($curlResult->getHeader());
$this->assertEmpty($curlResult->getHeader('wrongHeader')); self::assertEmpty($curlResult->getHeader('wrongHeader'));
} }
} }

View file

@ -85,7 +85,7 @@ class ProbeTest extends TestCase
$feedLink = Probe::getFeedLink($url, $body); $feedLink = Probe::getFeedLink($url, $body);
$this->assertEquals($expected, $feedLink, 'base url = ' . $url . ' | href = ' . $href); self::assertEquals($expected, $feedLink, 'base url = ' . $url . ' | href = ' . $href);
} }
} }
} }
@ -101,7 +101,7 @@ class ProbeTest extends TestCase
$feedLink = Probe::getFeedLink('http://example.com', $body); $feedLink = Probe::getFeedLink('http://example.com', $body);
$this->assertEquals($expected, $feedLink, 'base url = ' . $url . ' | href = ' . $href); self::assertEquals($expected, $feedLink, 'base url = ' . $url . ' | href = ' . $href);
} }
} }
} }

View file

@ -72,14 +72,14 @@ class ActivityTest extends MockedTest
{ {
$activity = new Activity(); $activity = new Activity();
$this->assertEquals($assert, $activity->match($haystack, $needle)); self::assertEquals($assert, $activity->match($haystack, $needle));
} }
public function testIsHidden() public function testIsHidden()
{ {
$activity = new Activity(); $activity = new Activity();
$this->assertTrue($activity->isHidden(Activity::LIKE)); self::assertTrue($activity->isHidden(Activity::LIKE));
$this->assertFalse($activity->isHidden(Activity\ObjectType::BOOKMARK)); self::assertFalse($activity->isHidden(Activity\ObjectType::BOOKMARK));
} }
} }

View file

@ -21,7 +21,6 @@
namespace Friendica\Test\src\Util; namespace Friendica\Test\src\Util;
use Error;
use Friendica\Model\Group; use Friendica\Model\Group;
use Friendica\Util\ACLFormatter; use Friendica\Util\ACLFormatter;
use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCase;
@ -37,18 +36,18 @@ class ACLFormaterTest extends TestCase
$acl = $aclFormatter->expand($text); $acl = $aclFormatter->expand($text);
$this->assertEquals($assert, $acl); self::assertEquals($assert, $acl);
$this->assertMergable($acl); self::assertMergable($acl);
} }
public function assertMergable(array $aclOne, array $aclTwo = []) public function assertMergable(array $aclOne, array $aclTwo = [])
{ {
$this->assertTrue(is_array($aclOne)); self::assertTrue(is_array($aclOne));
$this->assertTrue(is_array($aclTwo)); self::assertTrue(is_array($aclTwo));
$aclMerged = array_unique(array_merge($aclOne, $aclTwo)); $aclMerged = array_unique(array_merge($aclOne, $aclTwo));
$this->assertTrue(is_array($aclMerged)); self::assertTrue(is_array($aclMerged));
return $aclMerged; return $aclMerged;
} }
@ -118,7 +117,7 @@ class ACLFormaterTest extends TestCase
*/ */
public function testExpand($input, array $assert) public function testExpand($input, array $assert)
{ {
$this->assertAcl($input, $assert); self::assertAcl($input, $assert);
} }
/** /**
@ -131,11 +130,11 @@ class ACLFormaterTest extends TestCase
$allow_people = $aclFormatter->expand(); $allow_people = $aclFormatter->expand();
$allow_groups = $aclFormatter->expand(); $allow_groups = $aclFormatter->expand();
$this->assertEmpty($aclFormatter->expand(null)); self::assertEmpty($aclFormatter->expand(null));
$this->assertEmpty($aclFormatter->expand()); self::assertEmpty($aclFormatter->expand());
$recipients = array_unique(array_merge($allow_people, $allow_groups)); $recipients = array_unique(array_merge($allow_people, $allow_groups));
$this->assertEmpty($recipients); self::assertEmpty($recipients);
} }
public function dataAclToString() public function dataAclToString()
@ -188,6 +187,6 @@ class ACLFormaterTest extends TestCase
{ {
$aclFormatter = new ACLFormatter(); $aclFormatter = new ACLFormatter();
$this->assertEquals($assert, $aclFormatter->toString($input)); self::assertEquals($assert, $aclFormatter->toString($input));
} }
} }

View file

@ -35,7 +35,7 @@ class ArraysTest extends TestCase
public function testEmptyArrayEmptyDelimiter() public function testEmptyArrayEmptyDelimiter()
{ {
$str = Arrays::recursiveImplode([], ''); $str = Arrays::recursiveImplode([], '');
$this->assertEmpty($str); self::assertEmpty($str);
} }
/** /**
@ -44,7 +44,7 @@ class ArraysTest extends TestCase
public function testEmptyArrayNonEmptyDelimiter() public function testEmptyArrayNonEmptyDelimiter()
{ {
$str = Arrays::recursiveImplode([], ','); $str = Arrays::recursiveImplode([], ',');
$this->assertEmpty($str); self::assertEmpty($str);
} }
/** /**
@ -53,7 +53,7 @@ class ArraysTest extends TestCase
public function testNonEmptyArrayEmptyDelimiter() public function testNonEmptyArrayEmptyDelimiter()
{ {
$str = Arrays::recursiveImplode([1], ''); $str = Arrays::recursiveImplode([1], '');
$this->assertSame($str, '1'); self::assertSame($str, '1');
} }
/** /**
@ -62,7 +62,7 @@ class ArraysTest extends TestCase
public function testNonEmptyArray2EmptyDelimiter() public function testNonEmptyArray2EmptyDelimiter()
{ {
$str = Arrays::recursiveImplode([1, 2], ''); $str = Arrays::recursiveImplode([1, 2], '');
$this->assertSame($str, '12'); self::assertSame($str, '12');
} }
/** /**
@ -71,7 +71,7 @@ class ArraysTest extends TestCase
public function testNonEmptyArrayNonEmptyDelimiter() public function testNonEmptyArrayNonEmptyDelimiter()
{ {
$str = Arrays::recursiveImplode([1], ','); $str = Arrays::recursiveImplode([1], ',');
$this->assertSame($str, '1'); self::assertSame($str, '1');
} }
/** /**
@ -80,7 +80,7 @@ class ArraysTest extends TestCase
public function testNonEmptyArray2NonEmptyDelimiter() public function testNonEmptyArray2NonEmptyDelimiter()
{ {
$str = Arrays::recursiveImplode([1, 2], ','); $str = Arrays::recursiveImplode([1, 2], ',');
$this->assertSame($str, '1,2'); self::assertSame($str, '1,2');
} }
/** /**
@ -89,7 +89,7 @@ class ArraysTest extends TestCase
public function testEmptyMultiArray2EmptyDelimiter() public function testEmptyMultiArray2EmptyDelimiter()
{ {
$str = Arrays::recursiveImplode([[1], []], ''); $str = Arrays::recursiveImplode([[1], []], '');
$this->assertSame($str, '{1}{}'); self::assertSame($str, '{1}{}');
} }
/** /**
@ -98,7 +98,7 @@ class ArraysTest extends TestCase
public function testEmptyMulti2Array2EmptyDelimiter() public function testEmptyMulti2Array2EmptyDelimiter()
{ {
$str = Arrays::recursiveImplode([[1], [2]], ''); $str = Arrays::recursiveImplode([[1], [2]], '');
$this->assertSame($str, '{1}{2}'); self::assertSame($str, '{1}{2}');
} }
/** /**
@ -107,7 +107,7 @@ class ArraysTest extends TestCase
public function testEmptyMultiArray2NonEmptyDelimiter() public function testEmptyMultiArray2NonEmptyDelimiter()
{ {
$str = Arrays::recursiveImplode([[1], []], ','); $str = Arrays::recursiveImplode([[1], []], ',');
$this->assertSame($str, '{1},{}'); self::assertSame($str, '{1},{}');
} }
/** /**
@ -116,7 +116,7 @@ class ArraysTest extends TestCase
public function testEmptyMulti2Array2NonEmptyDelimiter() public function testEmptyMulti2Array2NonEmptyDelimiter()
{ {
$str = Arrays::recursiveImplode([[1], [2]], ','); $str = Arrays::recursiveImplode([[1], [2]], ',');
$this->assertSame($str, '{1},{2}'); self::assertSame($str, '{1},{2}');
} }
/** /**
@ -125,6 +125,6 @@ class ArraysTest extends TestCase
public function testEmptyMulti3Array2NonEmptyDelimiter() public function testEmptyMulti3Array2NonEmptyDelimiter()
{ {
$str = Arrays::recursiveImplode([[1], [2, [3]]], ','); $str = Arrays::recursiveImplode([[1], [2, [3]]], ',');
$this->assertSame($str, '{1},{2,{3}}'); self::assertSame($str, '{1},{2,{3}}');
} }
} }

View file

@ -59,16 +59,17 @@ class BasePathTest extends MockedTest
public function testDetermineBasePath(array $server, $input, $output) public function testDetermineBasePath(array $server, $input, $output)
{ {
$basepath = new BasePath($input, $server); $basepath = new BasePath($input, $server);
$this->assertEquals($output, $basepath->getPath()); self::assertEquals($output, $basepath->getPath());
} }
/** /**
* Test the basepath determination with a complete wrong path * Test the basepath determination with a complete wrong path
* @expectedException \Exception
* @expectedExceptionMessageRegExp /(.*) is not a valid basepath/
*/ */
public function testFailedBasePath() public function testFailedBasePath()
{ {
$this->expectException(\Exception::class);
$this->expectExceptionMessageRegExp("/(.*) is not a valid basepath/");
$basepath = new BasePath('/now23452sgfgas', []); $basepath = new BasePath('/now23452sgfgas', []);
$basepath->getPath(); $basepath->getPath();
} }

View file

@ -201,11 +201,11 @@ class BaseURLTest extends MockedTest
$baseUrl = new BaseURL($configMock, $server); $baseUrl = new BaseURL($configMock, $server);
$this->assertEquals($assert['hostname'], $baseUrl->getHostname()); self::assertEquals($assert['hostname'], $baseUrl->getHostname());
$this->assertEquals($assert['urlPath'], $baseUrl->getUrlPath()); self::assertEquals($assert['urlPath'], $baseUrl->getUrlPath());
$this->assertEquals($assert['sslPolicy'], $baseUrl->getSSLPolicy()); self::assertEquals($assert['sslPolicy'], $baseUrl->getSSLPolicy());
$this->assertEquals($assert['scheme'], $baseUrl->getScheme()); self::assertEquals($assert['scheme'], $baseUrl->getScheme());
$this->assertEquals($assert['url'], $baseUrl->get()); self::assertEquals($assert['url'], $baseUrl->get());
} }
public function dataSave() public function dataSave()
@ -320,7 +320,7 @@ class BaseURLTest extends MockedTest
$baseUrl->save($save['hostname'], $save['sslPolicy'], $save['urlPath']); $baseUrl->save($save['hostname'], $save['sslPolicy'], $save['urlPath']);
$this->assertEquals($url, $baseUrl->get()); self::assertEquals($url, $baseUrl->get());
} }
/** /**
@ -358,7 +358,7 @@ class BaseURLTest extends MockedTest
$baseUrl->saveByURL($url); $baseUrl->saveByURL($url);
$this->assertEquals($url, $baseUrl->get()); self::assertEquals($url, $baseUrl->get());
} }
public function dataGetBaseUrl() public function dataGetBaseUrl()
@ -417,7 +417,7 @@ class BaseURLTest extends MockedTest
$baseUrl = new BaseURL($configMock, []); $baseUrl = new BaseURL($configMock, []);
$this->assertEquals($assert, $baseUrl->get($ssl)); self::assertEquals($assert, $baseUrl->get($ssl));
} }
public function dataCheckRedirectHTTPS() public function dataCheckRedirectHTTPS()
@ -476,7 +476,7 @@ class BaseURLTest extends MockedTest
$baseUrl = new BaseURL($configMock, $server); $baseUrl = new BaseURL($configMock, $server);
$this->assertEquals($redirect, $baseUrl->checkRedirectHttps()); self::assertEquals($redirect, $baseUrl->checkRedirectHttps());
} }
public function dataWrongSave() public function dataWrongSave()
@ -531,12 +531,12 @@ class BaseURLTest extends MockedTest
} }
$baseUrl = new BaseURL($configMock, []); $baseUrl = new BaseURL($configMock, []);
$this->assertFalse($baseUrl->save('test', 10, 'nope')); self::assertFalse($baseUrl->save('test', 10, 'nope'));
// nothing should have changed because we never successfully saved anything // nothing should have changed because we never successfully saved anything
$this->assertEquals($baseUrl->getHostname(), 'friendica.local'); self::assertEquals('friendica.local', $baseUrl->getHostname());
$this->assertEquals($baseUrl->getUrlPath(), 'new/test'); self::assertEquals('new/test', $baseUrl->getUrlPath());
$this->assertEquals($baseUrl->getSSLPolicy(), BaseURL::DEFAULT_SSL_SCHEME); self::assertEquals(BaseURL::DEFAULT_SSL_SCHEME, $baseUrl->getSSLPolicy());
$this->assertEquals($baseUrl->get(), 'http://friendica.local/new/test'); self::assertEquals('http://friendica.local/new/test', $baseUrl->get());
} }
} }

View file

@ -50,16 +50,17 @@ class ConfigFileLoaderTest extends MockedTest
$configFileLoader->setupCache($configCache); $configFileLoader->setupCache($configCache);
$this->assertEquals($this->root->url(), $configCache->get('system', 'basepath')); self::assertEquals($this->root->url(), $configCache->get('system', 'basepath'));
} }
/** /**
* Test the loadConfigFiles() method with a wrong local.config.php * Test the loadConfigFiles() method with a wrong local.config.php
* @expectedException \Exception *
* @expectedExceptionMessageRegExp /Error loading config file \w+/
*/ */
public function testLoadConfigWrong() public function testLoadConfigWrong()
{ {
$this->expectExceptionMessageRegExp("/Error loading config file \w+/");
$this->expectException(\Exception::class);
$this->delConfigFile('local.config.php'); $this->delConfigFile('local.config.php');
vfsStream::newFile('local.config.php') vfsStream::newFile('local.config.php')
@ -95,13 +96,13 @@ class ConfigFileLoaderTest extends MockedTest
$configFileLoader->setupCache($configCache); $configFileLoader->setupCache($configCache);
$this->assertEquals('testhost', $configCache->get('database', 'hostname')); self::assertEquals('testhost', $configCache->get('database', 'hostname'));
$this->assertEquals('testuser', $configCache->get('database', 'username')); self::assertEquals('testuser', $configCache->get('database', 'username'));
$this->assertEquals('testpw', $configCache->get('database', 'password')); self::assertEquals('testpw', $configCache->get('database', 'password'));
$this->assertEquals('testdb', $configCache->get('database', 'database')); self::assertEquals('testdb', $configCache->get('database', 'database'));
$this->assertEquals('admin@test.it', $configCache->get('config', 'admin_email')); self::assertEquals('admin@test.it', $configCache->get('config', 'admin_email'));
$this->assertEquals('Friendica Social Network', $configCache->get('config', 'sitename')); self::assertEquals('Friendica Social Network', $configCache->get('config', 'sitename'));
} }
/** /**
@ -127,12 +128,12 @@ class ConfigFileLoaderTest extends MockedTest
$configFileLoader->setupCache($configCache); $configFileLoader->setupCache($configCache);
$this->assertEquals('testhost', $configCache->get('database', 'hostname')); self::assertEquals('testhost', $configCache->get('database', 'hostname'));
$this->assertEquals('testuser', $configCache->get('database', 'username')); self::assertEquals('testuser', $configCache->get('database', 'username'));
$this->assertEquals('testpw', $configCache->get('database', 'password')); self::assertEquals('testpw', $configCache->get('database', 'password'));
$this->assertEquals('testdb', $configCache->get('database', 'database')); self::assertEquals('testdb', $configCache->get('database', 'database'));
$this->assertEquals('admin@test.it', $configCache->get('config', 'admin_email')); self::assertEquals('admin@test.it', $configCache->get('config', 'admin_email'));
} }
/** /**
@ -158,25 +159,25 @@ class ConfigFileLoaderTest extends MockedTest
$configFileLoader->setupCache($configCache); $configFileLoader->setupCache($configCache);
$this->assertEquals('testhost', $configCache->get('database', 'hostname')); self::assertEquals('testhost', $configCache->get('database', 'hostname'));
$this->assertEquals('testuser', $configCache->get('database', 'username')); self::assertEquals('testuser', $configCache->get('database', 'username'));
$this->assertEquals('testpw', $configCache->get('database', 'password')); self::assertEquals('testpw', $configCache->get('database', 'password'));
$this->assertEquals('testdb', $configCache->get('database', 'database')); self::assertEquals('testdb', $configCache->get('database', 'database'));
$this->assertEquals('anotherCharset', $configCache->get('database', 'charset')); self::assertEquals('anotherCharset', $configCache->get('database', 'charset'));
$this->assertEquals('/var/run/friendica.pid', $configCache->get('system', 'pidfile')); self::assertEquals('/var/run/friendica.pid', $configCache->get('system', 'pidfile'));
$this->assertEquals('Europe/Berlin', $configCache->get('system', 'default_timezone')); self::assertEquals('Europe/Berlin', $configCache->get('system', 'default_timezone'));
$this->assertEquals('fr', $configCache->get('system', 'language')); self::assertEquals('fr', $configCache->get('system', 'language'));
$this->assertEquals('admin@test.it', $configCache->get('config', 'admin_email')); self::assertEquals('admin@test.it', $configCache->get('config', 'admin_email'));
$this->assertEquals('Friendly admin', $configCache->get('config', 'admin_nickname')); self::assertEquals('Friendly admin', $configCache->get('config', 'admin_nickname'));
$this->assertEquals('/another/php', $configCache->get('config', 'php_path')); self::assertEquals('/another/php', $configCache->get('config', 'php_path'));
$this->assertEquals('999', $configCache->get('config', 'max_import_size')); self::assertEquals('999', $configCache->get('config', 'max_import_size'));
$this->assertEquals('666', $configCache->get('system', 'maximagesize')); self::assertEquals('666', $configCache->get('system', 'maximagesize'));
$this->assertEquals('quattro,vier,duepuntozero', $configCache->get('system', 'allowed_themes')); self::assertEquals('quattro,vier,duepuntozero', $configCache->get('system', 'allowed_themes'));
$this->assertEquals('1', $configCache->get('system', 'no_regfullname')); self::assertEquals('1', $configCache->get('system', 'no_regfullname'));
} }
public function testLoadAddonConfig() public function testLoadAddonConfig()
@ -206,12 +207,12 @@ class ConfigFileLoaderTest extends MockedTest
$conf = $configFileLoader->loadAddonConfig('test'); $conf = $configFileLoader->loadAddonConfig('test');
$this->assertEquals('testhost', $conf['database']['hostname']); self::assertEquals('testhost', $conf['database']['hostname']);
$this->assertEquals('testuser', $conf['database']['username']); self::assertEquals('testuser', $conf['database']['username']);
$this->assertEquals('testpw', $conf['database']['password']); self::assertEquals('testpw', $conf['database']['password']);
$this->assertEquals('testdb', $conf['database']['database']); self::assertEquals('testdb', $conf['database']['database']);
$this->assertEquals('admin@test.it', $conf['config']['admin_email']); self::assertEquals('admin@test.it', $conf['config']['admin_email']);
} }
/** /**
@ -239,8 +240,8 @@ class ConfigFileLoaderTest extends MockedTest
$configFileLoader->setupCache($configCache); $configFileLoader->setupCache($configCache);
$this->assertEquals('admin@overwritten.local', $configCache->get('config', 'admin_email')); self::assertEquals('admin@overwritten.local', $configCache->get('config', 'admin_email'));
$this->assertEquals('newValue', $configCache->get('system', 'newKey')); self::assertEquals('newValue', $configCache->get('system', 'newKey'));
} }
/** /**
@ -268,8 +269,8 @@ class ConfigFileLoaderTest extends MockedTest
$configFileLoader->setupCache($configCache); $configFileLoader->setupCache($configCache);
$this->assertEquals('admin@overwritten.local', $configCache->get('config', 'admin_email')); self::assertEquals('admin@overwritten.local', $configCache->get('config', 'admin_email'));
$this->assertEquals('newValue', $configCache->get('system', 'newKey')); self::assertEquals('newValue', $configCache->get('system', 'newKey'));
} }
/** /**
@ -297,7 +298,7 @@ class ConfigFileLoaderTest extends MockedTest
$configFileLoader->setupCache($configCache); $configFileLoader->setupCache($configCache);
$this->assertEquals('admin@test.it', $configCache->get('config', 'admin_email')); self::assertEquals('admin@test.it', $configCache->get('config', 'admin_email'));
$this->assertEmpty($configCache->get('system', 'NewKey')); self::assertEmpty($configCache->get('system', 'NewKey'));
} }
} }

View file

@ -19,6 +19,8 @@
* *
* This is in the same namespace as Crypto for mocking 'rand' and 'random_init' * 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; namespace Friendica\Util;
use phpseclib\Crypt\RSA; use phpseclib\Crypt\RSA;
@ -35,23 +37,23 @@ class CryptoTest extends TestCase
{ {
global $phpMock; global $phpMock;
$phpMock['random_int'] = function ($mMin, $mMax) use ($min, $max) { $phpMock['random_int'] = function ($mMin, $mMax) use ($min, $max) {
$this->assertEquals($min, $mMin); self::assertEquals($min, $mMin);
$this->assertEquals($max, $mMax); self::assertEquals($max, $mMax);
return 1; return 1;
}; };
} }
public function testRandomDigitsRandomInt() public function testRandomDigitsRandomInt()
{ {
$this->assertRandomInt(0, 9); self::assertRandomInt(0, 9);
$test = Crypto::randomDigits(1); $test = Crypto::randomDigits(1);
$this->assertEquals(1, strlen($test)); self::assertEquals(1, strlen($test));
$this->assertEquals(1, $test); self::assertEquals(1, $test);
$test = Crypto::randomDigits(8); $test = Crypto::randomDigits(8);
$this->assertEquals(8, strlen($test)); self::assertEquals(8, strlen($test));
$this->assertEquals(11111111, $test); self::assertEquals(11111111, $test);
} }
public function dataRsa() public function dataRsa()
@ -69,7 +71,7 @@ class CryptoTest extends TestCase
*/ */
public function testPubRsaToMe(string $key, string $expected) public function testPubRsaToMe(string $key, string $expected)
{ {
$this->assertEquals($expected, Crypto::rsaToPem(base64_decode($key))); self::assertEquals($expected, Crypto::rsaToPem(base64_decode($key)));
} }
@ -95,7 +97,7 @@ class CryptoTest extends TestCase
'n' => new BigInteger($m, 256) 'n' => new BigInteger($m, 256)
]); ]);
$this->assertEquals($expectedRSA->getPublicKey(), $key); self::assertEquals($expectedRSA->getPublicKey(), $key);
} }
/** /**
@ -107,7 +109,7 @@ class CryptoTest extends TestCase
$checkKey = Crypto::meToPem($m, $e); $checkKey = Crypto::meToPem($m, $e);
$this->assertEquals($key, $checkKey); self::assertEquals($key, $checkKey);
} }
} }
@ -120,7 +122,6 @@ function random_int($min, $max)
{ {
global $phpMock; global $phpMock;
if (isset($phpMock['random_int'])) { if (isset($phpMock['random_int'])) {
$result = call_user_func_array($phpMock['random_int'], func_get_args()); return call_user_func_array($phpMock['random_int'], func_get_args());
return $result;
} }
} }

View file

@ -75,6 +75,6 @@ class DateTimeFormatTest extends MockedTest
{ {
$dtFormat = new DateTimeFormat(); $dtFormat = new DateTimeFormat();
$this->assertEquals($assert, $dtFormat->isYearMonth($input)); self::assertEquals($assert, $dtFormat->isYearMonth($input));
} }
} }

View file

@ -35,9 +35,6 @@ class EMailerTest extends MockedTest
/** @var BaseURL|MockInterface */ /** @var BaseURL|MockInterface */
private $baseUrl; private $baseUrl;
/** @var string */
private $defaultHeaders;
protected function setUp() protected function setUp()
{ {
parent::setUp(); parent::setUp();
@ -54,8 +51,6 @@ class EMailerTest extends MockedTest
$this->baseUrl = \Mockery::mock(BaseURL::class); $this->baseUrl = \Mockery::mock(BaseURL::class);
$this->baseUrl->shouldReceive('getHostname')->andReturn('friendica.local'); $this->baseUrl->shouldReceive('getHostname')->andReturn('friendica.local');
$this->baseUrl->shouldReceive('get')->andReturn('http://friendica.local'); $this->baseUrl->shouldReceive('get')->andReturn('http://friendica.local');
$this->defaultHeaders = [];
} }
protected function tearDown() protected function tearDown()
@ -81,21 +76,21 @@ class EMailerTest extends MockedTest
$emailer = new EmailerSpy($this->config, $this->pConfig, $this->baseUrl, new NullLogger(), $this->l10n); $emailer = new EmailerSpy($this->config, $this->pConfig, $this->baseUrl, new NullLogger(), $this->l10n);
$this->assertTrue($emailer->send($testEmail)); self::assertTrue($emailer->send($testEmail));
$this->assertContains("X-Friendica-Host: friendica.local", EmailerSpy::$MAIL_DATA['headers']); self::assertContains("X-Friendica-Host: friendica.local", EmailerSpy::$MAIL_DATA['headers']);
$this->assertContains("X-Friendica-Platform: Friendica", EmailerSpy::$MAIL_DATA['headers']); self::assertContains("X-Friendica-Platform: Friendica", EmailerSpy::$MAIL_DATA['headers']);
$this->assertContains("List-ID: <notification.friendica.local>", EmailerSpy::$MAIL_DATA['headers']); self::assertContains("List-ID: <notification.friendica.local>", EmailerSpy::$MAIL_DATA['headers']);
$this->assertContains("List-Archive: <http://friendica.local/notifications/system>", EmailerSpy::$MAIL_DATA['headers']); self::assertContains("List-Archive: <http://friendica.local/notifications/system>", EmailerSpy::$MAIL_DATA['headers']);
$this->assertContains("Reply-To: Sender <sender@friendica.local>", EmailerSpy::$MAIL_DATA['headers']); self::assertContains("Reply-To: Sender <sender@friendica.local>", EmailerSpy::$MAIL_DATA['headers']);
$this->assertContains("MIME-Version: 1.0", EmailerSpy::$MAIL_DATA['headers']); self::assertContains("MIME-Version: 1.0", EmailerSpy::$MAIL_DATA['headers']);
// Base64 "Test Text" // Base64 "Test Text"
$this->assertContains(chunk_split(base64_encode('Test Text')), EmailerSpy::$MAIL_DATA['body']); self::assertContains(chunk_split(base64_encode('Test Text')), EmailerSpy::$MAIL_DATA['body']);
// Base64 "Test Message<b>Bold</b>" // Base64 "Test Message<b>Bold</b>"
$this->assertContains(chunk_split(base64_encode("Test Message<b>Bold</b>")), EmailerSpy::$MAIL_DATA['body']); self::assertContains(chunk_split(base64_encode("Test Message<b>Bold</b>")), EmailerSpy::$MAIL_DATA['body']);
$this->assertEquals("Test Subject", EmailerSpy::$MAIL_DATA['subject']); self::assertEquals("Test Subject", EmailerSpy::$MAIL_DATA['subject']);
$this->assertEquals("recipient@friendica.local", EmailerSpy::$MAIL_DATA['to']); self::assertEquals("recipient@friendica.local", EmailerSpy::$MAIL_DATA['to']);
$this->assertEquals("-f sender@friendica.local", EmailerSpy::$MAIL_DATA['parameters']); self::assertEquals("-f sender@friendica.local", EmailerSpy::$MAIL_DATA['parameters']);
} }
public function testTwoMessageIds() public function testTwoMessageIds()
@ -124,10 +119,10 @@ class EMailerTest extends MockedTest
$emailer = new EmailerSpy($this->config, $this->pConfig, $this->baseUrl, new NullLogger(), $this->l10n); $emailer = new EmailerSpy($this->config, $this->pConfig, $this->baseUrl, new NullLogger(), $this->l10n);
// even in case there are two message ids, send the mail anyway // even in case there are two message ids, send the mail anyway
$this->assertTrue($emailer->send($testEmail)); self::assertTrue($emailer->send($testEmail));
// check case sensitive key problem // check case sensitive key problem
$this->assertArrayHasKey('Message-ID', $testEmail->getAdditionalMailHeader()); self::assertArrayHasKey('Message-ID', $testEmail->getAdditionalMailHeader());
$this->assertArrayHasKey('Message-Id', $testEmail->getAdditionalMailHeader()); self::assertArrayHasKey('Message-Id', $testEmail->getAdditionalMailHeader());
} }
} }

View file

@ -24,6 +24,7 @@ namespace Friendica\Test\src\Util\Emailer;
use Friendica\App\BaseURL; use Friendica\App\BaseURL;
use Friendica\Core\Config\IConfig; use Friendica\Core\Config\IConfig;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Network\HTTPException\InternalServerErrorException;
use Friendica\Object\EMail\IEmail; use Friendica\Object\EMail\IEmail;
use Friendica\Test\MockedTest; use Friendica\Test\MockedTest;
use Friendica\Test\Util\SampleMailBuilder; use Friendica\Test\Util\SampleMailBuilder;
@ -50,7 +51,7 @@ class MailBuilderTest extends MockedTest
/** @var string */ /** @var string */
private $defaultHeaders; private $defaultHeaders;
public function setUp() protected function setUp()
{ {
parent::setUp(); parent::setUp();
@ -67,15 +68,15 @@ class MailBuilderTest extends MockedTest
public function assertEmail(IEmail $email, array $asserts) public function assertEmail(IEmail $email, array $asserts)
{ {
$this->assertEquals($asserts['subject'] ?? $email->getSubject(), $email->getSubject()); self::assertEquals($asserts['subject'] ?? $email->getSubject(), $email->getSubject());
$this->assertEquals($asserts['html'] ?? $email->getMessage(), $email->getMessage()); self::assertEquals($asserts['html'] ?? $email->getMessage(), $email->getMessage());
$this->assertEquals($asserts['text'] ?? $email->getMessage(true), $email->getMessage(true)); self::assertEquals($asserts['text'] ?? $email->getMessage(true), $email->getMessage(true));
$this->assertEquals($asserts['toAddress'] ?? $email->getToAddress(), $email->getToAddress()); self::assertEquals($asserts['toAddress'] ?? $email->getToAddress(), $email->getToAddress());
$this->assertEquals($asserts['fromAddress'] ?? $email->getFromAddress(), $email->getFromAddress()); self::assertEquals($asserts['fromAddress'] ?? $email->getFromAddress(), $email->getFromAddress());
$this->assertEquals($asserts['fromName'] ?? $email->getFromName(), $email->getFromName()); self::assertEquals($asserts['fromName'] ?? $email->getFromName(), $email->getFromName());
$this->assertEquals($asserts['replyTo'] ?? $email->getReplyTo(), $email->getReplyTo()); self::assertEquals($asserts['replyTo'] ?? $email->getReplyTo(), $email->getReplyTo());
$this->assertEquals($asserts['uid'] ?? $email->getRecipientUid(), $email->getRecipientUid()); self::assertEquals($asserts['uid'] ?? $email->getRecipientUid(), $email->getRecipientUid());
$this->assertEquals($asserts['header'] ?? $email->getAdditionalMailHeader(), $email->getAdditionalMailHeader()); self::assertEquals($asserts['header'] ?? $email->getAdditionalMailHeader(), $email->getAdditionalMailHeader());
} }
/** /**
@ -85,7 +86,7 @@ class MailBuilderTest extends MockedTest
{ {
$builder = new SampleMailBuilder($this->l10n, $this->baseUrl, $this->config, new NullLogger()); $builder = new SampleMailBuilder($this->l10n, $this->baseUrl, $this->config, new NullLogger());
$this->assertInstanceOf(MailBuilder::class, $builder); self::assertInstanceOf(MailBuilder::class, $builder);
} }
/** /**
@ -95,7 +96,7 @@ class MailBuilderTest extends MockedTest
*/ */
public function testBuilderWithNonRawEmail() 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');
} }
/** /**
@ -112,7 +113,7 @@ class MailBuilderTest extends MockedTest
->forUser(['uid' => 100]) ->forUser(['uid' => 100])
->build(true); ->build(true);
$this->assertEmail($testEmail, [ self::assertEmail($testEmail, [
'subject' => 'Subject', 'subject' => 'Subject',
'html' => 'Html', 'html' => 'Html',
'text' => 'text', 'text' => 'text',
@ -128,11 +129,12 @@ class MailBuilderTest extends MockedTest
/** /**
* Test if the builder throws an exception in case no recipient * Test if the builder throws an exception in case no recipient
* *
* @expectedException \Friendica\Network\HTTPException\InternalServerErrorException
* @expectedExceptionMessage Recipient address is missing.
*/ */
public function testBuilderWithEmptyMail() 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 = new SampleMailBuilder($this->l10n, $this->baseUrl, $this->config, new NullLogger());
$builder->build(true); $builder->build(true);
@ -140,12 +142,12 @@ class MailBuilderTest extends MockedTest
/** /**
* Test if the builder throws an exception in case no sender * 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() 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 = new SampleMailBuilder($this->l10n, $this->baseUrl, $this->config, new NullLogger());
$builder $builder
@ -165,7 +167,7 @@ class MailBuilderTest extends MockedTest
->withSender('Sender', 'sender@friendica.local') ->withSender('Sender', 'sender@friendica.local')
->build(true); ->build(true);
$this->assertEmail($testEmail, [ self::assertEmail($testEmail, [
'toAddress' => 'recipient@friendica.local', 'toAddress' => 'recipient@friendica.local',
'fromName' => 'Sender', 'fromName' => 'Sender',
'fromAddress' => 'sender@friendica.local', 'fromAddress' => 'sender@friendica.local',
@ -186,7 +188,7 @@ class MailBuilderTest extends MockedTest
->withSender('Sender', 'sender@friendica.local') ->withSender('Sender', 'sender@friendica.local')
->build(true); ->build(true);
$this->assertEmail($testEmail, [ self::assertEmail($testEmail, [
'toAddress' => 'recipient@friendica.local', 'toAddress' => 'recipient@friendica.local',
'fromName' => 'Sender', 'fromName' => 'Sender',
'fromAddress' => 'sender@friendica.local', 'fromAddress' => 'sender@friendica.local',

View file

@ -41,10 +41,7 @@ class SystemMailBuilderTest extends MockedTest
/** @var BaseURL */ /** @var BaseURL */
private $baseUrl; private $baseUrl;
/** @var string[] */ protected function setUp()
private $defaultHeaders;
public function setUp()
{ {
parent::setUp(); parent::setUp();
@ -59,8 +56,6 @@ class SystemMailBuilderTest extends MockedTest
$this->baseUrl = \Mockery::mock(BaseURL::class); $this->baseUrl = \Mockery::mock(BaseURL::class);
$this->baseUrl->shouldReceive('getHostname')->andReturn('friendica.local'); $this->baseUrl->shouldReceive('getHostname')->andReturn('friendica.local');
$this->baseUrl->shouldReceive('get')->andReturn('http://friendica.local'); $this->baseUrl->shouldReceive('get')->andReturn('http://friendica.local');
$this->defaultHeaders = [];
} }
/** /**
@ -70,7 +65,7 @@ class SystemMailBuilderTest extends MockedTest
{ {
$builder = new SystemMailBuilder($this->l10n, $this->baseUrl, $this->config, new NullLogger(), 'moreply@friendica.local', 'FriendicaSite'); $builder = new SystemMailBuilder($this->l10n, $this->baseUrl, $this->config, new NullLogger(), 'moreply@friendica.local', 'FriendicaSite');
$this->assertInstanceOf(MailBuilder::class, $builder); self::assertInstanceOf(MailBuilder::class, $builder);
$this->assertInstanceOf(SystemMailBuilder::class, $builder); self::assertInstanceOf(SystemMailBuilder::class, $builder);
} }
} }

View file

@ -43,7 +43,7 @@ class HTTPSignatureTest extends TestCase
YWuxyvBa0Z6NdOb0di70cdrSDEsL5Gz7LBY5J2N9KdGg=="'; YWuxyvBa0Z6NdOb0di70cdrSDEsL5Gz7LBY5J2N9KdGg=="';
$headers = HTTPSignature::parseSigheader($header); $headers = HTTPSignature::parseSigheader($header);
$this->assertSame([ self::assertSame([
'keyId' => 'test-key-a', 'keyId' => 'test-key-a',
'algorithm' => 'hs2019', 'algorithm' => 'hs2019',
'created' => '1402170695', 'created' => '1402170695',

View file

@ -34,7 +34,7 @@ class JsonLDTest extends TestCase
$object = []; $object = [];
$data = JsonLD::fetchElementArray($object, 'field'); $data = JsonLD::fetchElementArray($object, 'field');
$this->assertNull($data); self::assertNull($data);
} }
public function testFetchElementArrayFoundEmptyArray() public function testFetchElementArrayFoundEmptyArray()
@ -42,7 +42,7 @@ class JsonLDTest extends TestCase
$object = ['field' => []]; $object = ['field' => []];
$data = JsonLD::fetchElementArray($object, 'field'); $data = JsonLD::fetchElementArray($object, 'field');
$this->assertSame([[]], $data); self::assertSame([[]], $data);
} }
public function testFetchElementArrayFoundID() public function testFetchElementArrayFoundID()
@ -50,7 +50,7 @@ class JsonLDTest extends TestCase
$object = ['field' => ['value1', ['@id' => 'value2'], ['@id' => 'value3']]]; $object = ['field' => ['value1', ['@id' => 'value2'], ['@id' => 'value3']]];
$data = JsonLD::fetchElementArray($object, 'field', '@id'); $data = JsonLD::fetchElementArray($object, 'field', '@id');
$this->assertSame(['value1', 'value2', 'value3'], $data); self::assertSame(['value1', 'value2', 'value3'], $data);
} }
public function testFetchElementArrayFoundID2() public function testFetchElementArrayFoundID2()
@ -60,7 +60,7 @@ class JsonLDTest extends TestCase
'value3', ['@id' => 'value4', 'subfield42' => 'value42']]]; 'value3', ['@id' => 'value4', 'subfield42' => 'value42']]];
$data = JsonLD::fetchElementArray($object, 'field', '@id'); $data = JsonLD::fetchElementArray($object, 'field', '@id');
$this->assertSame(['value3', 'value4'], $data); self::assertSame(['value3', 'value4'], $data);
} }
public function testFetchElementArrayFoundArrays() public function testFetchElementArrayFoundArrays()
{ {
@ -71,7 +71,7 @@ class JsonLDTest extends TestCase
['subfield21' => 'value21', 'subfield22' => 'value22']]; ['subfield21' => 'value21', 'subfield22' => 'value22']];
$data = JsonLD::fetchElementArray($object, 'field'); $data = JsonLD::fetchElementArray($object, 'field');
$this->assertSame($expect, $data); self::assertSame($expect, $data);
} }
public function testFetchElementNotFound() public function testFetchElementNotFound()
@ -79,7 +79,7 @@ class JsonLDTest extends TestCase
$object = []; $object = [];
$data = JsonLD::fetchElement($object, 'field'); $data = JsonLD::fetchElement($object, 'field');
$this->assertNull($data); self::assertNull($data);
} }
public function testFetchElementFound() public function testFetchElementFound()
@ -87,7 +87,7 @@ class JsonLDTest extends TestCase
$object = ['field' => 'value']; $object = ['field' => 'value'];
$data = JsonLD::fetchElement($object, 'field'); $data = JsonLD::fetchElement($object, 'field');
$this->assertSame('value', $data); self::assertSame('value', $data);
} }
public function testFetchElementFoundEmptyString() public function testFetchElementFoundEmptyString()
@ -95,7 +95,7 @@ class JsonLDTest extends TestCase
$object = ['field' => '']; $object = ['field' => ''];
$data = JsonLD::fetchElement($object, 'field'); $data = JsonLD::fetchElement($object, 'field');
$this->assertSame('', $data); self::assertSame('', $data);
} }
public function testFetchElementKeyFoundEmptyArray() public function testFetchElementKeyFoundEmptyArray()
@ -103,7 +103,7 @@ class JsonLDTest extends TestCase
$object = ['field' => ['content' => []]]; $object = ['field' => ['content' => []]];
$data = JsonLD::fetchElement($object, 'field', 'content'); $data = JsonLD::fetchElement($object, 'field', 'content');
$this->assertSame([], $data); self::assertSame([], $data);
} }
public function testFetchElementFoundID() public function testFetchElementFoundID()
@ -111,7 +111,7 @@ class JsonLDTest extends TestCase
$object = ['field' => ['field2' => 'value2', '@id' => 'value', 'field3' => 'value3']]; $object = ['field' => ['field2' => 'value2', '@id' => 'value', 'field3' => 'value3']];
$data = JsonLD::fetchElement($object, 'field'); $data = JsonLD::fetchElement($object, 'field');
$this->assertSame('value', $data); self::assertSame('value', $data);
} }
public function testFetchElementType() public function testFetchElementType()
@ -119,7 +119,7 @@ class JsonLDTest extends TestCase
$object = ['source' => ['content' => 'body', 'mediaType' => 'text/bbcode']]; $object = ['source' => ['content' => 'body', 'mediaType' => 'text/bbcode']];
$data = JsonLD::fetchElement($object, 'source', 'content', 'mediaType', 'text/bbcode'); $data = JsonLD::fetchElement($object, 'source', 'content', 'mediaType', 'text/bbcode');
$this->assertSame('body', $data); self::assertSame('body', $data);
} }
public function testFetchElementTypeValueNotFound() public function testFetchElementTypeValueNotFound()
@ -127,7 +127,7 @@ class JsonLDTest extends TestCase
$object = ['source' => ['content' => 'body', 'mediaType' => 'text/html']]; $object = ['source' => ['content' => 'body', 'mediaType' => 'text/html']];
$data = JsonLD::fetchElement($object, 'source', 'content', 'mediaType', 'text/bbcode'); $data = JsonLD::fetchElement($object, 'source', 'content', 'mediaType', 'text/bbcode');
$this->assertNull($data); self::assertNull($data);
} }
public function testFetchElementTypeNotFound() public function testFetchElementTypeNotFound()
@ -135,7 +135,7 @@ class JsonLDTest extends TestCase
$object = ['source' => ['content' => 'body', 'mediaType' => 'text/html']]; $object = ['source' => ['content' => 'body', 'mediaType' => 'text/html']];
$data = JsonLD::fetchElement($object, 'source', 'content', 'mediaType2', 'text/html'); $data = JsonLD::fetchElement($object, 'source', 'content', 'mediaType2', 'text/html');
$this->assertNull($data); self::assertNull($data);
} }
public function testFetchElementKeyWithoutType() public function testFetchElementKeyWithoutType()
@ -143,7 +143,7 @@ class JsonLDTest extends TestCase
$object = ['source' => ['content' => 'body', 'mediaType' => 'text/bbcode']]; $object = ['source' => ['content' => 'body', 'mediaType' => 'text/bbcode']];
$data = JsonLD::fetchElement($object, 'source', 'content'); $data = JsonLD::fetchElement($object, 'source', 'content');
$this->assertSame('body', $data); self::assertSame('body', $data);
} }
public function testFetchElementTypeArray() public function testFetchElementTypeArray()
@ -152,7 +152,7 @@ class JsonLDTest extends TestCase
['content' => 'body', 'mediaType' => 'text/bbcode']]]; ['content' => 'body', 'mediaType' => 'text/bbcode']]];
$data = JsonLD::fetchElement($object, 'source', 'content', 'mediaType', 'text/bbcode'); $data = JsonLD::fetchElement($object, 'source', 'content', 'mediaType', 'text/bbcode');
$this->assertSame('body', $data); self::assertSame('body', $data);
} }
public function testFetchElementTypeValueArrayNotFound() public function testFetchElementTypeValueArrayNotFound()
@ -161,7 +161,7 @@ class JsonLDTest extends TestCase
['content' => 'body', 'mediaType' => 'text/bbcode']]]; ['content' => 'body', 'mediaType' => 'text/bbcode']]];
$data = JsonLD::fetchElement($object, 'source', 'content', 'mediaType', 'text/markdown'); $data = JsonLD::fetchElement($object, 'source', 'content', 'mediaType', 'text/markdown');
$this->assertNull($data); self::assertNull($data);
} }
public function testFetchElementTypeArrayNotFound() public function testFetchElementTypeArrayNotFound()
@ -170,6 +170,6 @@ class JsonLDTest extends TestCase
['content' => 'body', 'mediaType' => 'text/bbcode']]]; ['content' => 'body', 'mediaType' => 'text/bbcode']]];
$data = JsonLD::fetchElement($object, 'source', 'content', 'mediaType2', 'text/bbcode'); $data = JsonLD::fetchElement($object, 'source', 'content', 'mediaType2', 'text/bbcode');
$this->assertNull($data); self::assertNull($data);
} }
} }

View file

@ -72,12 +72,12 @@ abstract class AbstractLoggerTest extends MockedTest
public function assertLogline($string) public function assertLogline($string)
{ {
$this->assertRegExp(self::LOGLINE, $string); self::assertRegExp(self::LOGLINE, $string);
} }
public function assertLoglineNums($assertNum, $string) public function assertLoglineNums($assertNum, $string)
{ {
$this->assertEquals($assertNum, preg_match_all(self::LOGLINE, $string)); self::assertEquals($assertNum, preg_match_all(self::LOGLINE, $string));
} }
/** /**
@ -92,8 +92,8 @@ abstract class AbstractLoggerTest extends MockedTest
$logger->notice('message', ['an' => 'context']); $logger->notice('message', ['an' => 'context']);
$text = $this->getContent(); $text = $this->getContent();
$this->assertLogline($text); self::assertLogline($text);
$this->assertLoglineNums(4, $text); self::assertLoglineNums(4, $text);
} }
/** /**
@ -106,8 +106,8 @@ abstract class AbstractLoggerTest extends MockedTest
$logger->emergency('A {psr} test', ['psr' => 'working']); $logger->emergency('A {psr} test', ['psr' => 'working']);
$logger->alert('An {array} test', ['array' => ['it', 'is', 'working']]); $logger->alert('An {array} test', ['array' => ['it', 'is', 'working']]);
$text = $this->getContent(); $text = $this->getContent();
$this->assertContains('A working test', $text); self::assertContains('A working test', $text);
$this->assertContains('An ["it","is","working"] test', $text); self::assertContains('An ["it","is","working"] test', $text);
} }
/** /**
@ -119,9 +119,9 @@ abstract class AbstractLoggerTest extends MockedTest
$logger->emergency('A test'); $logger->emergency('A test');
$text = $this->getContent(); $text = $this->getContent();
$this->assertContains('"file":"' . self::FILE . '"', $text); self::assertContains('"file":"' . self::FILE . '"', $text);
$this->assertContains('"line":' . self::LINE, $text); self::assertContains('"line":' . self::LINE, $text);
$this->assertContains('"function":"' . self::FUNC . '"', $text); self::assertContains('"function":"' . self::FUNC . '"', $text);
} }
/** /**
@ -141,7 +141,7 @@ abstract class AbstractLoggerTest extends MockedTest
$text = $this->getContent(); $text = $this->getContent();
$this->assertLoglineNums(5, $text); self::assertLoglineNums(5, $text);
} }
/** /**
@ -155,8 +155,8 @@ abstract class AbstractLoggerTest extends MockedTest
$text = $this->getContent(); $text = $this->getContent();
$this->assertLogline($text); self::assertLogline($text);
$this->assertContains(@json_encode($context), $text); self::assertContains(@json_encode($context), $text);
} }
} }

View file

@ -32,11 +32,6 @@ class StreamLoggerTest extends AbstractLoggerTest
{ {
use VFSTrait; use VFSTrait;
/**
* @var StreamLogger
*/
private $logger;
/** /**
* @var vfsStreamFile * @var vfsStreamFile
*/ */
@ -53,7 +48,7 @@ class StreamLoggerTest extends AbstractLoggerTest
$this->setUpVfsDir(); $this->setUpVfsDir();
$this->fileSystem = new Filesystem(); $this->fileSystem = new FileSystem();
} }
/** /**
@ -64,9 +59,9 @@ class StreamLoggerTest extends AbstractLoggerTest
$this->logfile = vfsStream::newFile('friendica.log') $this->logfile = vfsStream::newFile('friendica.log')
->at($this->root); ->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;
} }
/** /**
@ -92,7 +87,7 @@ class StreamLoggerTest extends AbstractLoggerTest
$text = $logfile->getContent(); $text = $logfile->getContent();
$this->assertLogline($text); self::assertLogline($text);
} }
/** /**
@ -111,16 +106,17 @@ class StreamLoggerTest extends AbstractLoggerTest
$text = $logfile->getContent(); $text = $logfile->getContent();
$this->assertLoglineNums(2, $text); self::assertLoglineNums(2, $text);
} }
/** /**
* Test when a file isn't set * Test when a file isn't set
* @expectedException \LogicException
* @expectedExceptionMessage Missing stream URL.
*/ */
public function testNoUrl() public function testNoUrl()
{ {
$this->expectException(\LogicException::class);
$this->expectExceptionMessage("Missing stream URL.");
$logger = new StreamLogger('test', '', $this->introspection, $this->fileSystem); $logger = new StreamLogger('test', '', $this->introspection, $this->fileSystem);
$logger->emergency('not working'); $logger->emergency('not working');
@ -128,11 +124,12 @@ class StreamLoggerTest extends AbstractLoggerTest
/** /**
* Test when a file cannot be opened * Test when a file cannot be opened
* @expectedException \UnexpectedValueException
* @expectedExceptionMessageRegExp /The stream or file .* could not be opened: .* /
*/ */
public function testWrongUrl() public function testWrongUrl()
{ {
$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessageRegExp("/The stream or file .* could not be opened: .* /");
$logfile = vfsStream::newFile('friendica.log') $logfile = vfsStream::newFile('friendica.log')
->at($this->root)->chmod(0); ->at($this->root)->chmod(0);
@ -143,12 +140,13 @@ class StreamLoggerTest extends AbstractLoggerTest
/** /**
* Test when the directory cannot get created * Test when the directory cannot get created
* @expectedException \UnexpectedValueException
* @expectedExceptionMessageRegExp /Directory .* cannot get created: .* /
*/ */
public function testWrongDir() 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); $logger = new StreamLogger('test', '/$%/wrong/directory/file.txt', $this->introspection, $this->fileSystem);
@ -157,21 +155,23 @@ class StreamLoggerTest extends AbstractLoggerTest
/** /**
* Test when the minimum level is not valid * Test when the minimum level is not valid
* @expectedException \InvalidArgumentException
* @expectedExceptionMessageRegExp /The level ".*" is not valid./
*/ */
public function testWrongMinimumLevel() 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'); $logger = new StreamLogger('test', 'file.text', $this->introspection, $this->fileSystem, 'NOPE');
} }
/** /**
* Test when the minimum level is not valid * Test when the minimum level is not valid
* @expectedException \InvalidArgumentException
* @expectedExceptionMessageRegExp /The level ".*" is not valid./
*/ */
public function testWrongLogLevel() public function testWrongLogLevel()
{ {
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessageRegExp("/The level \".*\" is not valid./");
$logfile = vfsStream::newFile('friendica.log') $logfile = vfsStream::newFile('friendica.log')
->at($this->root); ->at($this->root);
@ -182,11 +182,12 @@ class StreamLoggerTest extends AbstractLoggerTest
/** /**
* Test when the file is null * Test when the file is null
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage A stream must either be a resource or a string.
*/ */
public function testWrongFile() 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); $logger = new StreamLogger('test', null, $this->introspection, $this->fileSystem);
} }
@ -195,7 +196,7 @@ class StreamLoggerTest extends AbstractLoggerTest
*/ */
public function testRealPath() 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') $logfile = vfsStream::newFile('friendica.log')
->at($this->root); ->at($this->root);

View file

@ -59,21 +59,23 @@ class SyslogLoggerTest extends AbstractLoggerTest
/** /**
* Test when the minimum level is not valid * Test when the minimum level is not valid
* @expectedException \InvalidArgumentException
* @expectedExceptionMessageRegExp /The level ".*" is not valid./
*/ */
public function testWrongMinimumLevel() public function testWrongMinimumLevel()
{ {
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessageRegExp("/The level \".*\" is not valid./");
$logger = new SyslogLoggerWrapper('test', $this->introspection, 'NOPE'); $logger = new SyslogLoggerWrapper('test', $this->introspection, 'NOPE');
} }
/** /**
* Test when the minimum level is not valid * Test when the minimum level is not valid
* @expectedException \InvalidArgumentException
* @expectedExceptionMessageRegExp /The level ".*" is not valid./
*/ */
public function testWrongLogLevel() public function testWrongLogLevel()
{ {
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessageRegExp("/The level \".*\" is not valid./");
$logger = new SyslogLoggerWrapper('test', $this->introspection); $logger = new SyslogLoggerWrapper('test', $this->introspection);
$logger->log('NOPE', 'a test'); $logger->log('NOPE', 'a test');
@ -81,11 +83,12 @@ class SyslogLoggerTest extends AbstractLoggerTest
/** /**
* Test when the logfacility is wrong (string) * Test when the logfacility is wrong (string)
* @expectedException \UnexpectedValueException
* @expectedExceptionMessageRegExp /Can\'t open syslog for ident ".*" and facility ".*": .* /
*/ */
public function testServerException() 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 = new SyslogLoggerWrapper('test', $this->introspection, LogLevel::DEBUG, null, 'a string');
$logger->emergency('not working'); $logger->emergency('not working');
} }

View file

@ -51,6 +51,7 @@ class SyslogLoggerWrapper extends SyslogLogger
/** /**
* {@inheritdoc} * {@inheritdoc}
* @noinspection PhpMissingParentCallCommonInspection
*/ */
protected function syslogWrapper($level, $entry) protected function syslogWrapper($level, $entry)
{ {

View file

@ -29,15 +29,17 @@ class WorkerLoggerTest extends MockedTest
{ {
private function assertUid($uid, $length = 7) private function assertUid($uid, $length = 7)
{ {
$this->assertRegExp('/^[a-zA-Z0-9]{' . $length . '}+$/', $uid); self::assertRegExp('/^[a-zA-Z0-9]{' . $length . '}+$/', $uid);
} }
/** /**
* Test the a id with length zero * Test the a id with length zero
* @expectedException \Error *
*/ */
public function testGetWorkerIdZero() public function testGetWorkerIdZero()
{ {
$this->expectException(\Error::class);
$logger = \Mockery::mock(LoggerInterface::class); $logger = \Mockery::mock(LoggerInterface::class);
new WorkerLogger($logger, 'test', 0); new WorkerLogger($logger, 'test', 0);
} }
@ -51,7 +53,7 @@ class WorkerLoggerTest extends MockedTest
for ($i = 1; $i < 14; $i++) { for ($i = 1; $i < 14; $i++) {
$workLogger = new WorkerLogger($logger, 'test', $i); $workLogger = new WorkerLogger($logger, 'test', $i);
$uid = $workLogger->getWorkerId(); $uid = $workLogger->getWorkerId();
$this->assertUid($uid, $i); self::assertUid($uid, $i);
} }
} }
@ -107,7 +109,7 @@ class WorkerLoggerTest extends MockedTest
$testContext = $context; $testContext = $context;
$testContext['worker_id'] = $workLogger->getWorkerId(); $testContext['worker_id'] = $workLogger->getWorkerId();
$testContext['worker_cmd'] = 'test'; $testContext['worker_cmd'] = 'test';
$this->assertUid($testContext['worker_id']); self::assertUid($testContext['worker_id']);
$logger $logger
->shouldReceive($func) ->shouldReceive($func)
->with($msg, $testContext) ->with($msg, $testContext)
@ -125,7 +127,7 @@ class WorkerLoggerTest extends MockedTest
$context = $testContext = ['test' => 'it']; $context = $testContext = ['test' => 'it'];
$testContext['worker_id'] = $workLogger->getWorkerId(); $testContext['worker_id'] = $workLogger->getWorkerId();
$testContext['worker_cmd'] = 'test'; $testContext['worker_cmd'] = 'test';
$this->assertUid($testContext['worker_id']); self::assertUid($testContext['worker_id']);
$logger $logger
->shouldReceive('log') ->shouldReceive('log')
->with('debug', 'a test', $testContext) ->with('debug', 'a test', $testContext)

View file

@ -53,6 +53,8 @@ class ProfilerTest extends MockedTest
->andReturn(true) ->andReturn(true)
->twice(); ->twice();
$profiler = new Profiler($configCache); $profiler = new Profiler($configCache);
self::assertInstanceOf(Profiler::class, $profiler);
} }
/** /**
@ -134,14 +136,14 @@ class ProfilerTest extends MockedTest
$profiler->saveTimestamp($timestamp, $name, $function); $profiler->saveTimestamp($timestamp, $name, $function);
} }
$this->assertGreaterThanOrEqual(0, $profiler->get($name)); self::assertGreaterThanOrEqual(0, $profiler->get($name));
} }
/** /**
* Test the Profiler reset * Test the Profiler reset
* @dataProvider dataPerformance * @dataProvider dataPerformance
*/ */
public function testReset($timestamp, $name, array $functions) public function testReset($timestamp, $name)
{ {
$configCache = \Mockery::mock(Cache::class); $configCache = \Mockery::mock(Cache::class);
$configCache->shouldReceive('get') $configCache->shouldReceive('get')
@ -154,7 +156,7 @@ class ProfilerTest extends MockedTest
$profiler->saveTimestamp($timestamp, $name); $profiler->saveTimestamp($timestamp, $name);
$profiler->reset(); $profiler->reset();
$this->assertEquals(0, $profiler->get($name)); self::assertEquals(0, $profiler->get($name));
} }
public function dataBig() public function dataBig()
@ -227,7 +229,7 @@ class ProfilerTest extends MockedTest
foreach ($data as $perf => $items) { foreach ($data as $perf => $items) {
foreach ($items['functions'] as $function) { foreach ($items['functions'] as $function) {
// assert that the output contains the functions // assert that the output contains the functions
$this->assertRegExp('/' . $function . ': \d+/', $output); self::assertRegExp('/' . $function . ': \d+/', $output);
} }
} }
} }
@ -249,8 +251,8 @@ class ProfilerTest extends MockedTest
$profiler = new Profiler($configCache); $profiler = new Profiler($configCache);
$this->assertFalse($profiler->isRendertime()); self::assertFalse($profiler->isRendertime());
$this->assertEmpty($profiler->getRendertimeString()); self::assertEmpty($profiler->getRendertimeString());
$profiler->saveTimestamp(time(), 'network', 'test1'); $profiler->saveTimestamp(time(), 'network', 'test1');
@ -266,8 +268,8 @@ class ProfilerTest extends MockedTest
$profiler->update($config); $profiler->update($config);
$this->assertFalse($profiler->isRendertime()); self::assertFalse($profiler->isRendertime());
$this->assertEmpty($profiler->getRendertimeString()); self::assertEmpty($profiler->getRendertimeString());
$config->shouldReceive('get') $config->shouldReceive('get')
->with('system', 'profiler') ->with('system', 'profiler')
@ -282,9 +284,9 @@ class ProfilerTest extends MockedTest
$profiler->saveTimestamp(time(), 'database', 'test2'); $profiler->saveTimestamp(time(), 'database', 'test2');
$this->assertTrue($profiler->isRendertime()); self::assertTrue($profiler->isRendertime());
$output = $profiler->getRendertimeString(); $output = $profiler->getRendertimeString();
$this->assertRegExp('/test1: \d+/', $output); self::assertRegExp('/test1: \d+/', $output);
$this->assertRegExp('/test2: \d+/', $output); self::assertRegExp('/test2: \d+/', $output);
} }
} }

View file

@ -37,7 +37,7 @@ class StringsTest extends TestCase
$randomname1 = Strings::getRandomName(10); $randomname1 = Strings::getRandomName(10);
$randomname2 = Strings::getRandomName(10); $randomname2 = Strings::getRandomName(10);
$this->assertNotEquals($randomname1, $randomname2); self::assertNotEquals($randomname1, $randomname2);
} }
/** /**
@ -48,7 +48,7 @@ class StringsTest extends TestCase
$randomname1 = Strings::getRandomName(9); $randomname1 = Strings::getRandomName(9);
$randomname2 = Strings::getRandomName(9); $randomname2 = Strings::getRandomName(9);
$this->assertNotEquals($randomname1, $randomname2); self::assertNotEquals($randomname1, $randomname2);
} }
/** /**
@ -57,7 +57,7 @@ class StringsTest extends TestCase
public function testRandomNameNoLength() public function testRandomNameNoLength()
{ {
$randomname1 = Strings::getRandomName(0); $randomname1 = Strings::getRandomName(0);
$this->assertEquals(0, strlen($randomname1)); self::assertEquals(0, strlen($randomname1));
} }
/** /**
@ -68,7 +68,7 @@ class StringsTest extends TestCase
public function testRandomNameNegativeLength() public function testRandomNameNegativeLength()
{ {
$randomname1 = Strings::getRandomName(-23); $randomname1 = Strings::getRandomName(-23);
$this->assertEquals(0, strlen($randomname1)); self::assertEquals(0, strlen($randomname1));
} }
/** /**
@ -77,10 +77,10 @@ class StringsTest extends TestCase
public function testRandomNameLength1() public function testRandomNameLength1()
{ {
$randomname1 = Strings::getRandomName(1); $randomname1 = Strings::getRandomName(1);
$this->assertEquals(1, strlen($randomname1)); self::assertEquals(1, strlen($randomname1));
$randomname2 = Strings::getRandomName(1); $randomname2 = Strings::getRandomName(1);
$this->assertEquals(1, strlen($randomname2)); self::assertEquals(1, strlen($randomname2));
} }
/** /**
@ -93,8 +93,8 @@ class StringsTest extends TestCase
$validstring = Strings::escapeTags($invalidstring); $validstring = Strings::escapeTags($invalidstring);
$escapedString = Strings::escapeHtml($invalidstring); $escapedString = Strings::escapeHtml($invalidstring);
$this->assertEquals('[submit type="button" onclick="alert(\'failed!\');" /]', $validstring); self::assertEquals('[submit type="button" onclick="alert(\'failed!\');" /]', $validstring);
$this->assertEquals( self::assertEquals(
"&lt;submit type=&quot;button&quot; onclick=&quot;alert('failed!');&quot; /&gt;", "&lt;submit type=&quot;button&quot; onclick=&quot;alert('failed!');&quot; /&gt;",
$escapedString $escapedString
); );
@ -125,14 +125,14 @@ class StringsTest extends TestCase
/** /**
* Tests if the string is a valid hexadecimal value * Tests if the string is a valid hexadecimal value
* *
* @param string $input * @param string|null $input
* @param bool $valid * @param bool $valid
* *
* @dataProvider dataIsHex * @dataProvider dataIsHex
*/ */
public function testIsHex($input, $valid) public function testIsHex(string $input = null, bool $valid = false)
{ {
$this->assertEquals($valid, Strings::isHex($input)); self::assertEquals($valid, Strings::isHex($input));
} }
/** /**
@ -142,13 +142,13 @@ class StringsTest extends TestCase
public function testSubstringReplaceASCII() public function testSubstringReplaceASCII()
{ {
for ($start = -10; $start <= 10; $start += 5) { for ($start = -10; $start <= 10; $start += 5) {
$this->assertEquals( self::assertEquals(
substr_replace('string', 'replacement', $start), substr_replace('string', 'replacement', $start),
Strings::substringReplace('string', 'replacement', $start) Strings::substringReplace('string', 'replacement', $start)
); );
for ($length = -10; $length <= 10; $length += 5) { for ($length = -10; $length <= 10; $length += 5) {
$this->assertEquals( self::assertEquals(
substr_replace('string', 'replacement', $start, $length), substr_replace('string', 'replacement', $start, $length),
Strings::substringReplace('string', 'replacement', $start, $length) Strings::substringReplace('string', 'replacement', $start, $length)
); );
@ -184,7 +184,7 @@ class StringsTest extends TestCase
*/ */
public function testSubstringReplaceMultiByte(string $expected, string $string, string $replacement, int $start, int $length = null) public function testSubstringReplaceMultiByte(string $expected, string $string, string $replacement, int $start, int $length = null)
{ {
$this->assertEquals( self::assertEquals(
$expected, $expected,
Strings::substringReplace( Strings::substringReplace(
$string, $string,
@ -203,7 +203,7 @@ class StringsTest extends TestCase
return $text; return $text;
}); });
$this->assertEquals($originalText, $text); self::assertEquals($originalText, $text);
} }
public function testPerformWithEscapedBlocksNested() public function testPerformWithEscapedBlocksNested()
@ -218,6 +218,6 @@ class StringsTest extends TestCase
return $text; return $text;
}); });
$this->assertEquals($originalText, $text); self::assertEquals($originalText, $text);
} }
} }

View file

@ -29,36 +29,36 @@ use PHPUnit\Framework\TestCase;
*/ */
class XmlTest extends TestCase class XmlTest extends TestCase
{ {
/** /**
* escape and unescape * escape and unescape
*/ */
public function testEscapeUnescape() public function testEscapeUnescape()
{ {
$text="<tag>I want to break\n this!11!<?hard?></tag>"; $text = "<tag>I want to break\n this!11!<?hard?></tag>";
$xml=XML::escape($text); $xml = XML::escape($text);
$retext=XML::unescape($text); $retext = XML::unescape($text);
$this->assertEquals($text, $retext); self::assertEquals($text, $retext);
} }
/** /**
* escape and put in a document * escape and put in a document
*/ */
public function testEscapeDocument() public function testEscapeDocument()
{ {
$tag="<tag>I want to break</tag>"; $tag = "<tag>I want to break</tag>";
$xml=XML::escape($tag); $xml = XML::escape($tag);
$text='<text>'.$xml.'</text>'; $text = '<text>' . $xml . '</text>';
$xml_parser=xml_parser_create(); $xml_parser = xml_parser_create();
//should be possible to parse it //should be possible to parse it
$values=array(); $values = [];
$index=array(); $index = [];
$this->assertEquals(1, xml_parse_into_struct($xml_parser, $text, $values, $index)); self::assertEquals(1, xml_parse_into_struct($xml_parser, $text, $values, $index));
$this->assertEquals( self::assertEquals(
array('TEXT'=>array(0)), ['TEXT' => [0]],
$index $index
); );
$this->assertEquals( self::assertEquals(
array(array('tag'=>'TEXT', 'type'=>'complete', 'level'=>1, 'value'=>$tag)), [['tag' => 'TEXT', 'type' => 'complete', 'level' => 1, 'value' => $tag]],
$values $values
); );
xml_parser_free($xml_parser); xml_parser_free($xml_parser);