Merge pull request #6051 from nupplaphil/friendica-6047

Test Mocking - Bugfixing & Enhancement
This commit is contained in:
Hypolite Petovan 2018-10-31 09:15:26 -04:00 committed by GitHub
commit c6ce9ddaa4
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
10 changed files with 581 additions and 169 deletions

View file

@ -0,0 +1,90 @@
<?php
namespace Friendica\Test\Util;
use Friendica\App;
use Friendica\BaseObject;
use Friendica\Render\FriendicaSmartyEngine;
use Mockery\MockInterface;
use org\bovigo\vfs\vfsStreamDirectory;
/**
* Trait to Mock the global App instance
*/
trait AppMockTrait
{
use ConfigMockTrait;
/**
* @var MockInterface|App The mocked Friendica\App
*/
protected $app;
/**
* Mock the App
*
* @param vfsStreamDirectory $root The root directory
*/
public function mockApp($root)
{
// simply returning the input when using L10n::t()
$l10nMock = \Mockery::mock('alias:Friendica\Core\L10n');
$l10nMock->shouldReceive('t')
->andReturnUsing(function ($arg) { return $arg; });
$this->mockConfigGet('system', 'theme', 'testtheme');
// Mocking App and most used functions
$this->app = \Mockery::mock(App::class);
$this->app
->shouldReceive('getBasePath')
->andReturn($root->url());
$this->app
->shouldReceive('getConfigValue')
->with('database', 'hostname')
->andReturn(getenv('MYSQL_HOST'));
$this->app
->shouldReceive('getConfigValue')
->with('database', 'username')
->andReturn(getenv('MYSQL_USERNAME'));
$this->app
->shouldReceive('getConfigValue')
->with('database', 'password')
->andReturn(getenv('MYSQL_PASSWORD'));
$this->app
->shouldReceive('getConfigValue')
->with('database', 'database')
->andReturn(getenv('MYSQL_DATABASE'));
$this->app
->shouldReceive('getTemplateEngine')
->andReturn(new FriendicaSmartyEngine());
$this->app
->shouldReceive('getCurrentTheme')
->andReturn('Smarty3');
$this->app
->shouldReceive('getTemplateLeftDelimiter')
->with('smarty3')
->andReturn('{{');
$this->app
->shouldReceive('getTemplateRightDelimiter')
->with('smarty3')
->andReturn('}}');
$this->app
->shouldReceive('saveTimestamp')
->andReturn(true);
$this->app
->shouldReceive('getBaseUrl')
->andReturn('http://friendica.local');
// Mocking the Theme
// Necessary for macro engine with template files
$themeMock = \Mockery::mock('alias:Friendica\Core\Theme');
$themeMock
->shouldReceive('install')
->with('testtheme')
->andReturn(true);
BaseObject::setApp($this->app);
}
}

View file

@ -0,0 +1,64 @@
<?php
namespace Friendica\Test\Util;
use Mockery\MockInterface;
/**
* Trait to Mock Config settings
*/
trait ConfigMockTrait
{
/**
* @var MockInterface The mocking interface of Friendica\Core\Config
*/
private $configMock;
/**
* Mocking a config setting
*
* @param string $family The family of the config double
* @param string $key The key of the config double
* @param mixed $value The value of the config double
* @param null|int $times How often the Config will get used
*/
public function mockConfigGet($family, $key, $value, $times = null)
{
if (!isset($this->configMock)) {
$this->configMock = \Mockery::mock('alias:Friendica\Core\Config');
}
$this->configMock
->shouldReceive('get')
->times($times)
->with($family, $key)
->andReturn($value);
}
/**
* Mocking setting a new config entry
*
* @param string $family The family of the config double
* @param string $key The key of the config double
* @param mixed $value The value of the config double
* @param null|int $times How often the Config will get used
* @param bool $return Return value of the set (default is true)
*/
public function mockConfigSet($family, $key, $value, $times = null, $return = true)
{
if (!isset($this->configMock)) {
$this->configMock = \Mockery::mock('alias:Friendica\Core\Config');
}
$this->mockConfigGet($family, $key, false, 1);
if ($return) {
$this->mockConfigGet($family, $key, $value, 1);
}
$this->configMock
->shouldReceive('set')
->times($times)
->with($family, $key, $value)
->andReturn($return);
}
}

View file

@ -0,0 +1,52 @@
<?php
namespace Friendica\Test\Util;
use Mockery\MockInterface;
/**
* Trait to mock the DBA connection status
*/
trait DBAMockTrait
{
/**
* @var MockInterface The mocking interface of Friendica\Database\DBA
*/
private $dbaMock;
/**
* Mocking DBA::connect()
*
* @param bool $return True, if the connect was successful, otherwise false
* @param null|int $times How often the method will get used
*/
public function mockConnect($return = true, $times = null)
{
if (!isset($this->dbaMock)) {
$this->dbaMock = \Mockery::mock('alias:Friendica\Database\DBA');
}
$this->dbaMock
->shouldReceive('connect')
->times($times)
->andReturn($return);
}
/**
* Mocking DBA::connected()
*
* @param bool $return True, if the DB is connected, otherwise false
* @param null|int $times How often the method will get used
*/
public function mockConnected($return = true, $times = null)
{
if (!isset($this->dbaMock)) {
$this->dbaMock = \Mockery::mock('alias:Friendica\Database\DBA');
}
$this->dbaMock
->shouldReceive('connected')
->times($times)
->andReturn($return);
}
}

View file

@ -0,0 +1,56 @@
<?php
namespace Friendica\Test\Util;
use Mockery\MockInterface;
/**
* Trait to mock the DBStructure connection status
*/
trait DBStructureMockTrait
{
/**
* @var MockInterface The mocking interface of Friendica\Database\DBStructure
*/
private $dbStructure;
/**
* Mocking DBStructure::update()
*
* @param array $args The arguments for the update call
* @param bool $return True, if the connect was successful, otherwise false
* @param null|int $times How often the method will get used
*/
public function mockUpdate($args = [], $return = true, $times = null)
{
if (!isset($this->dbStructure)) {
$this->dbStructure = \Mockery::mock('alias:Friendica\Database\DBStructure');
}
$this->dbStructure
->shouldReceive('update')
->withArgs($args)
->times($times)
->andReturn($return);
}
/**
* Mocking DBStructure::existsTable()
*
* @param string $tableName The name of the table to check
* @param bool $return True, if the connect was successful, otherwise false
* @param null|int $times How often the method will get used
*/
public function mockExistsTable($tableName, $return = true, $times = null)
{
if (!isset($this->dbStructure)) {
$this->dbStructure = \Mockery::mock('alias:Friendica\Database\DBStructure');
}
$this->dbStructure
->shouldReceive('existsTable')
->with($tableName)
->times($times)
->andReturn($return);
}
}

View file

@ -13,11 +13,15 @@ trait VFSTrait
*/ */
protected $root; protected $root;
/**
* Sets up the Virtual File System for Friendica with common files (config, dbstructure)
*/
protected function setUpVfsDir() { protected function setUpVfsDir() {
// the used directories inside the App class // the used directories inside the App class
$structure = [ $structure = [
'config' => [], 'config' => [],
'bin' => [] 'bin' => [],
'test' => []
]; ];
// create a virtual directory and copy all needed files and folders to it // create a virtual directory and copy all needed files and folders to it
@ -29,6 +33,11 @@ trait VFSTrait
$this->setConfigFile('dbstructure.php'); $this->setConfigFile('dbstructure.php');
} }
/**
* Copying a config file from the file system to the Virtual File System
*
* @param string $filename The filename of the config file
*/
protected function setConfigFile($filename) protected function setConfigFile($filename)
{ {
$file = dirname(__DIR__) . DIRECTORY_SEPARATOR . $file = dirname(__DIR__) . DIRECTORY_SEPARATOR .
@ -43,6 +52,11 @@ trait VFSTrait
} }
} }
/**
* Delets a config file from the Virtual File System
*
* @param string $filename The filename of the config file
*/
protected function delConfigFile($filename) protected function delConfigFile($filename)
{ {
if ($this->root->hasChild('config/' . $filename)) { if ($this->root->hasChild('config/' . $filename)) {

View file

@ -0,0 +1,56 @@
<?php return <<<INI
; If you're unsure about what any of the config keys below do, please check the config/defaults.ini.php for detailed
; documentation of their data type and behavior.
[database]
hostname = ""
username = ""
password = ""
database = ""
charset = utf8mb4
; ****************************************************************
; Some config values below can be overruled from the admin settings
; ****************************************************************
[config]
php_path = "/usr/bin/php"
admin_email = "admin@friendica.local"
sitename = Friendica Social Network
register_policy = REGISTER_OPEN
register_text =
max_import_size = 200000
[system]
urlpath = "/friendica"
default_timezone = "Europe/Berlin"
language = "de"
allowed_themes = vier,quattro,duepuntozero,smoothly,frio
theme = vier
allowed_link_protocols[0] = ftp
allowed_link_protocols[1] = ftps
allowed_link_protocols[2] = mailto
allowed_link_protocols[3] = cid
allowed_link_protocols[4] = gopher
maximagesize = 800000
no_regfullname = true
block_local_dir = false
directory = https://dir.friendica.social
auth_cookie_lifetime = 7
INI;
// Keep this line

View file

@ -2,7 +2,11 @@
namespace Friendica\Test\src\Core\Console; namespace Friendica\Test\src\Core\Console;
use Friendica\Core\Console\AutomaticInstallation;
use Friendica\Test\Util\DBAMockTrait;
use Friendica\Test\Util\DBStructureMockTrait;
use org\bovigo\vfs\vfsStream; use org\bovigo\vfs\vfsStream;
use org\bovigo\vfs\vfsStreamFile;
/** /**
* @runTestsInSeparateProcesses * @runTestsInSeparateProcesses
@ -11,12 +15,24 @@ use org\bovigo\vfs\vfsStream;
*/ */
class AutomaticInstallationConsoleTest extends ConsoleTest class AutomaticInstallationConsoleTest extends ConsoleTest
{ {
use DBAMockTrait;
use DBStructureMockTrait;
private $db_host; private $db_host;
private $db_port; private $db_port;
private $db_data; private $db_data;
private $db_user; private $db_user;
private $db_pass; private $db_pass;
/**
* @var vfsStreamFile Assert file without DB credentials
*/
private $assertFile;
/**
* @var vfsStreamFile Assert file with DB credentials
*/
private $assertFileDb;
public function setUp() public function setUp()
{ {
parent::setUp(); parent::setUp();
@ -32,19 +48,40 @@ class AutomaticInstallationConsoleTest extends ConsoleTest
$this->db_user = getenv('MYSQL_USERNAME') . getenv('MYSQL_USER'); $this->db_user = getenv('MYSQL_USERNAME') . getenv('MYSQL_USER');
$this->db_pass = getenv('MYSQL_PASSWORD'); $this->db_pass = getenv('MYSQL_PASSWORD');
// Mocking 'DBStructure::existsTable()' because with CI, we cannot create an empty database $this->mockConfigGet('config', 'php_path', false);
// therefore we temporary override the existing database
/// @todo Mocking the DB-Calls of ConsoleTest so we don't need this specific mock anymore $assertFile = dirname(__DIR__) . DIRECTORY_SEPARATOR .
$existsMock = \Mockery::mock('alias:Friendica\Database\DBStructure'); '..' . DIRECTORY_SEPARATOR .
$existsMock->shouldReceive('existsTable') '..' . DIRECTORY_SEPARATOR .
->with('user') 'datasets' . DIRECTORY_SEPARATOR .
->andReturn(false); 'ini' . DIRECTORY_SEPARATOR .
'assert.ini.php';
$this->assertFile = vfsStream::newFile('assert.ini.php')
->at($this->root->getChild('test'))
->setContent($this->replaceEnvironmentSettings($assertFile, false));
$this->assertFileDb = vfsStream::newFile('assert_db.ini.php')
->at($this->root->getChild('test'))
->setContent($this->replaceEnvironmentSettings($assertFile, true));
} }
private function assertConfig($family, $key, $value) /**
* Replacing environment specific variables in the assertion file
*
* @param string $file The file to compare in later tests
* @param bool $withDb If true, db settings are replaced too
* @return string The file content
*/
private function replaceEnvironmentSettings($file, $withDb)
{ {
$config = $this->execute(['config', $family, $key]); $fileContent = file_get_contents($file);
$this->assertEquals($family . "." . $key . " => " . $value . "\n", $config); $fileContent = str_replace("/usr/bin/php", trim(shell_exec('which php')), $fileContent);
if ($withDb) {
$fileContent = str_replace("hostname = \"\"", "hostname = \"" . $this->db_host . (!empty($this->db_port) ? ":" . $this->db_port : "") . "\"", $fileContent);
$fileContent = str_replace("username = \"\"", "username = \"" . $this->db_user . "\"", $fileContent);
$fileContent = str_replace("password = \"\"", "password = \"" . $this->db_pass . "\"", $fileContent);
$fileContent = str_replace("database = \"\"", "database = \"" . $this->db_data . "\"", $fileContent);
}
return $fileContent;
} }
private function assertFinished($txt, $withconfig = false, $copyfile = false) private function assertFinished($txt, $withconfig = false, $copyfile = false)
@ -113,14 +150,17 @@ FIN;
$finished = <<<FIN $finished = <<<FIN
Initializing setup... Initializing setup...
Creating config file... Complete!
Checking environment...
NOTICE: Not checking .htaccess/URL-Rewrite during CLI installation.
Complete! Complete!
Checking basic setup... Creating config file...
NOTICE: Not checking .htaccess/URL-Rewrite during CLI installation.
Complete! Complete!
@ -128,7 +168,7 @@ Checking basic setup...
Checking database... Checking database...
[Error] -------- [Error] --------
MySQL Connection: Failed, please check your MySQL settings and credentials. Could not connect to database.:
FIN; FIN;
@ -141,6 +181,11 @@ FIN;
*/ */
public function testWithConfig() public function testWithConfig()
{ {
$this->mockConnect(true, 1);
$this->mockConnected(true, 1);
$this->mockExistsTable('user', false, 1);
$this->mockUpdate([false, true, true], null, 1);
$config = <<<CONF $config = <<<CONF
<?php return <<<INI <?php return <<<INI
@ -179,7 +224,10 @@ CONF;
->at($this->root) ->at($this->root)
->setContent($config); ->setContent($config);
$txt = $this->execute(['autoinstall', '-f', 'prepared.ini.php']); $console = new AutomaticInstallation($this->consoleArgv);
$console->setOption('f', 'prepared.ini.php');
$txt = $this->dumpExecute($console);
$this->assertFinished($txt, false, true); $this->assertFinished($txt, false, true);
@ -191,23 +239,28 @@ CONF;
*/ */
public function testWithEnvironmentAndSave() public function testWithEnvironmentAndSave()
{ {
$this->mockConnect(true, 1);
$this->mockConnected(true, 1);
$this->mockExistsTable('user', false, 1);
$this->mockUpdate([false, true, true], null, 1);
$this->assertTrue(putenv('FRIENDICA_ADMIN_MAIL=admin@friendica.local')); $this->assertTrue(putenv('FRIENDICA_ADMIN_MAIL=admin@friendica.local'));
$this->assertTrue(putenv('FRIENDICA_TZ=Europe/Berlin')); $this->assertTrue(putenv('FRIENDICA_TZ=Europe/Berlin'));
$this->assertTrue(putenv('FRIENDICA_LANG=de')); $this->assertTrue(putenv('FRIENDICA_LANG=de'));
$this->assertTrue(putenv('FRIENDICA_URL_PATH=/friendica'));
$txt = $this->execute(['autoinstall', '--savedb']); $console = new AutomaticInstallation($this->consoleArgv);
$console->setOption('savedb', true);
$txt = $this->dumpExecute($console);
$this->assertFinished($txt, true); $this->assertFinished($txt, true);
$this->assertTrue($this->root->hasChild('config' . DIRECTORY_SEPARATOR . 'local.ini.php')); $this->assertTrue($this->root->hasChild('config' . DIRECTORY_SEPARATOR . 'local.ini.php'));
$this->assertConfig('database', 'hostname', $this->db_host . (!empty($this->db_port) ? ':' . $this->db_port : '')); $this->assertFileEquals(
$this->assertConfig('database', 'username', $this->db_user); $this->assertFileDb->url(),
$this->assertConfig('database', 'database', $this->db_data); $this->root->getChild('config' . DIRECTORY_SEPARATOR . 'local.ini.php')->url());
$this->assertConfig('config', 'admin_email', 'admin@friendica.local');
$this->assertConfig('system', 'default_timezone', 'Europe/Berlin');
// TODO language changes back to en
//$this->assertConfig('system', 'language', 'de');
} }
/** /**
@ -215,25 +268,27 @@ CONF;
*/ */
public function testWithEnvironmentWithoutSave() public function testWithEnvironmentWithoutSave()
{ {
$this->mockConnect(true, 1);
$this->mockConnected(true, 1);
$this->mockExistsTable('user', false, 1);
$this->mockUpdate([false, true, true], null, 1);
$this->assertTrue(putenv('FRIENDICA_ADMIN_MAIL=admin@friendica.local')); $this->assertTrue(putenv('FRIENDICA_ADMIN_MAIL=admin@friendica.local'));
$this->assertTrue(putenv('FRIENDICA_TZ=Europe/Berlin')); $this->assertTrue(putenv('FRIENDICA_TZ=Europe/Berlin'));
$this->assertTrue(putenv('FRIENDICA_LANG=de')); $this->assertTrue(putenv('FRIENDICA_LANG=de'));
$this->assertTrue(putenv('FRIENDICA_URL_PATH=/friendica')); $this->assertTrue(putenv('FRIENDICA_URL_PATH=/friendica'));
$txt = $this->execute(['autoinstall']); $console = new AutomaticInstallation($this->consoleArgv);
$txt = $this->dumpExecute($console);
$this->assertFinished($txt, true); $this->assertFinished($txt, true);
$this->assertTrue($this->root->hasChild('config' . DIRECTORY_SEPARATOR . 'local.ini.php')); $this->assertTrue($this->root->hasChild('config' . DIRECTORY_SEPARATOR . 'local.ini.php'));
$this->assertConfig('database', 'hostname', ''); $this->assertFileEquals(
$this->assertConfig('database', 'username', ''); $this->assertFile->url(),
$this->assertConfig('database', 'database', ''); $this->root->getChild('config' . DIRECTORY_SEPARATOR . 'local.ini.php')->url());
$this->assertConfig('config', 'admin_email', 'admin@friendica.local');
$this->assertConfig('system', 'default_timezone', 'Europe/Berlin');
$this->assertConfig('system', 'urlpath', '/friendica');
// TODO language changes back to en
//$this->assertConfig('system', 'language', 'de');
} }
/** /**
@ -241,46 +296,38 @@ CONF;
*/ */
public function testWithArguments() public function testWithArguments()
{ {
$args = ['autoinstall']; $this->mockConnect(true, 1);
array_push($args, '--dbhost'); $this->mockConnected(true, 1);
array_push($args, $this->db_host); $this->mockExistsTable('user', false, 1);
array_push($args, '--dbuser'); $this->mockUpdate([false, true, true], null, 1);
array_push($args, $this->db_user);
$console = new AutomaticInstallation($this->consoleArgv);
$console->setOption('dbhost', $this->db_host);
$console->setOption('dbuser', $this->db_user);
if (!empty($this->db_pass)) { if (!empty($this->db_pass)) {
array_push($args, '--dbpass'); $console->setOption('dbpass', $this->db_pass);
array_push($args, $this->db_pass);
} }
if (!empty($this->db_port)) { if (!empty($this->db_port)) {
array_push($args, '--dbport'); $console->setOption('dbport', $this->db_port);
array_push($args, $this->db_port);
} }
array_push($args, '--dbdata'); $console->setOption('dbdata', $this->db_data);
array_push($args, $this->db_data);
array_push($args, '--admin'); $console->setOption('admin', 'admin@friendica.local');
array_push($args, 'admin@friendica.local'); $console->setOption('tz', 'Europe/Berlin');
array_push($args, '--tz'); $console->setOption('lang', 'de');
array_push($args, 'Europe/Berlin');
array_push($args, '--lang');
array_push($args, 'de');
array_push($args, '--urlpath'); $console->setOption('urlpath', '/friendica');
array_push($args, '/friendica');
$txt = $this->execute($args); $txt = $this->dumpExecute($console);
$this->assertFinished($txt, true); $this->assertFinished($txt, true);
$this->assertTrue($this->root->hasChild('config' . DIRECTORY_SEPARATOR . 'local.ini.php')); $this->assertTrue($this->root->hasChild('config' . DIRECTORY_SEPARATOR . 'local.ini.php'));
$this->assertConfig('database', 'hostname', $this->db_host . (!empty($this->db_port) ? ':' . $this->db_port : '')); $this->assertFileEquals(
$this->assertConfig('database', 'username', $this->db_user); $this->assertFileDb->url(),
$this->assertConfig('database', 'database', $this->db_data); $this->root->getChild('config' . DIRECTORY_SEPARATOR . 'local.ini.php')->url());
$this->assertConfig('config', 'admin_email', 'admin@friendica.local');
$this->assertConfig('system', 'default_timezone', 'Europe/Berlin');
$this->assertConfig('system', 'urlpath', '/friendica');
// TODO language changes back to en
//$this->assertConfig('system', 'language', 'de');
} }
/** /**
@ -289,15 +336,11 @@ CONF;
*/ */
public function testNoDatabaseConnection() public function testNoDatabaseConnection()
{ {
// TODO DBA mocking for whole console tests make this test work again $this->mockConnect(false, 1);
$this->markTestSkipped('DBA is already loaded, we have to mock the whole App to make it work');
$dbaMock = \Mockery::mock('alias:Friendica\Database\DBA'); $console = new AutomaticInstallation($this->consoleArgv);
$dbaMock
->shouldReceive('connected')
->andReturn(false);
$txt = $this->execute(['autoinstall']); $txt = $this->dumpExecute($console);
$this->assertStuckDB($txt); $this->assertStuckDB($txt);
} }
@ -357,7 +400,10 @@ Examples
HELP; HELP;
$txt = $this->execute(['autoinstall', '-h']); $console = new AutomaticInstallation($this->consoleArgv);
$console->setOption('help', true);
$txt = $this->dumpExecute($console);
$this->assertEquals($txt, $theHelp); $this->assertEquals($txt, $theHelp);
} }

View file

@ -2,7 +2,7 @@
namespace Friendica\Test\src\Core\Console; namespace Friendica\Test\src\Core\Console;
use Friendica\Database\DBA; use Friendica\Core\Console\Config;
/** /**
* @runTestsInSeparateProcesses * @runTestsInSeparateProcesses
@ -11,76 +11,147 @@ use Friendica\Database\DBA;
*/ */
class ConfigConsoleTest extends ConsoleTest class ConfigConsoleTest extends ConsoleTest
{ {
public function tearDown() protected function setUp()
{ {
DBA::delete('config', ['k' => 'test']); parent::setUp();
parent::tearDown(); \Mockery::getConfiguration()->setConstantsMap([
} 'Friendica\App\Mode' => [
'DBCONFIGAVAILABLE' => 0
]
]);
private function assertGet($family, $key, $value) { $mode = \Mockery::mock('alias:Friendica\App\Mode');
$config = $this->execute(['config', $family, $key]); $mode
$this->assertEquals($family . "." . $key . " => " . $value . "\n", $config); ->shouldReceive('has')
} ->andReturn(true);
private function assertSet($family, $key, $value) { $this->app
$config = $this->execute(['config', $family, $key, $value]); ->shouldReceive('getMode')
$this->assertEquals($family . "." . $key . " <= " . $value . "\n", $config); ->andReturn($mode);
} }
function testSetGetKeyValue() { function testSetGetKeyValue() {
$this->assertSet( 'config', 'test', 'now'); $this->mockConfigSet('config', 'test', 'now', 1);
$this->assertGet('config', 'test', 'now'); $console = new Config($this->consoleArgv);
$this->assertSet('config', 'test', ''); $console->setArgument(0, 'config');
$this->assertGet('config', 'test', ''); $console->setArgument(1, 'test');
DBA::delete('config', ['k' => 'test']); $console->setArgument(2, 'now');
$this->assertGet('config', 'test', null); $txt = $this->dumpExecute($console);
$this->assertEquals("config.test <= now\n", $txt);
$this->mockConfigGet('config', 'test', 'now', 1);
$console = new Config($this->consoleArgv);
$console->setArgument(0, 'config');
$console->setArgument(1, 'test');
$txt = $this->dumpExecute($console);
$this->assertEquals("config.test => now\n", $txt);
$this->mockConfigGet('config', 'test', null, 1);
$console = new Config($this->consoleArgv);
$console->setArgument(0, 'config');
$console->setArgument(1, 'test');
$txt = $this->dumpExecute($console);
$this->assertEquals("config.test => \n", $txt);
} }
function testSetArrayValue() { function testSetArrayValue() {
$testArray = [1, 2, 3]; $testArray = [1, 2, 3];
DBA::insert('config', ['cat' => 'config', 'k' => 'test', 'v' => serialize($testArray)]); $this->mockConfigGet('config', 'test', $testArray, 1);
$txt = $this->execute(['config', 'config', 'test', 'now']); $console = new Config($this->consoleArgv);
$console->setArgument(0, 'config');
$console->setArgument(1, 'test');
$console->setArgument(2, 'now');
$txt = $this->dumpExecute($console);
$this->assertEquals("[Error] config.test is an array and can't be set using this command.\n", $txt); $this->assertEquals("[Error] config.test is an array and can't be set using this command.\n", $txt);
} }
function testTooManyArguments() { function testTooManyArguments() {
$txt = $this->execute(['config', 'config', 'test', 'it', 'now']); $console = new Config($this->consoleArgv);
$console->setArgument(0, 'config');
$console->setArgument(1, 'test');
$console->setArgument(2, 'it');
$console->setArgument(3, 'now');
$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); $this->assertEquals($assertion, $firstline);
} }
function testVerbose() { function testVerbose() {
$this->assertSet('test', 'it', 'now'); $this->mockConfigGet('test', 'it', 'now', 1);
$executable = $this->getExecutablePath(); $console = new Config($this->consoleArgv);
$console->setArgument(0, 'test');
$console->setArgument(1, 'it');
$console->setOption('v', 1);
$executable = $this->consoleArgv[0];
$assertion = <<<CONF $assertion = <<<CONF
Executable: {$executable} Executable: {$executable}
Arguments: array (
0 => 'config',
1 => 'test',
)
Options: array (
'v' => 1,
)
Command: config
Executable: {$executable}
Class: Friendica\Core\Console\Config Class: Friendica\Core\Console\Config
Arguments: array ( Arguments: array (
0 => 'test', 0 => 'test',
1 => 'it',
) )
Options: array ( Options: array (
'v' => 1, 'v' => 1,
) )
[test] test.it => now
it => now
CONF; CONF;
$txt = $this->execute(['config', 'test', '-v']); $txt = $this->dumpExecute($console);
$this->assertEquals($assertion, $txt); $this->assertEquals($assertion, $txt);
} }
function testUnableToSet() {
$this->mockConfigSet('test', 'it', 'now', 1, false);
$console = new Config();
$console->setArgument(0, 'test');
$console->setArgument(1, 'it');
$console->setArgument(2, 'now');
$txt = $this->dumpExecute($console);
$this->assertSame("Unable to set test.it\n", $txt);
}
public function testGetHelp()
{
// Usable to purposely fail if new commands are added without taking tests into account
$theHelp = <<<HELP
console config - Manage site configuration
Synopsis
bin/console config [-h|--help|-?] [-v]
bin/console config <category> [-h|--help|-?] [-v]
bin/console config <category> <key> [-h|--help|-?] [-v]
bin/console config <category> <key> <value> [-h|--help|-?] [-v]
Description
bin/console config
Lists all config values
bin/console config <category>
Lists all config values in the provided category
bin/console config <category> <key>
Shows the value of the provided key in the category
bin/console config <category> <key> <value>
Sets the value of the provided key in the category
Notes:
Setting config entries which are manually set in config/local.ini.php may result in
conflict between database settings and the manual startup settings.
Options
-h|--help|-? Show help information
-v Show more debug information.
HELP;
$console = new Config($this->consoleArgv);
$console->setOption('help', true);
$txt = $this->dumpExecute($console);
$this->assertEquals($txt, $theHelp);
}
} }

View file

@ -2,71 +2,57 @@
namespace Friendica\Test\src\Core\Console; namespace Friendica\Test\src\Core\Console;
use Friendica\App; use Asika\SimpleConsole\Console;
use Friendica\BaseObject; use Friendica\Test\Util\AppMockTrait;
use Friendica\Database\DBA;
use Friendica\Test\Util\Intercept; use Friendica\Test\Util\Intercept;
use Friendica\Test\Util\VFSTrait; use Friendica\Test\Util\VFSTrait;
use org\bovigo\vfs\vfsStream;
use org\bovigo\vfs\vfsStreamDirectory;
use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCase;
abstract class ConsoleTest extends TestCase abstract class ConsoleTest extends TestCase
{ {
use VFSTrait; use VFSTrait;
use AppMockTrait;
/** /**
* @var MultiUseConsole Extension of the basic Friendica Console for testing purpose * @var array The default argv for a Console Instance
*/ */
private $console; protected $consoleArgv = [ 'consoleTest.php' ];
/**
* @var App The Friendica App
*/
protected $app;
protected $stdout;
protected function setUp() protected function setUp()
{ {
parent::setUp(); parent::setUp();
Intercept::setUp();
if (!getenv('MYSQL_DATABASE')) { if (!getenv('MYSQL_DATABASE')) {
$this->markTestSkipped('Please set the MYSQL_* environment variables to your test database credentials.'); $this->markTestSkipped('Please set the MYSQL_* environment variables to your test database credentials.');
} }
Intercept::setUp();
$this->setUpVfsDir(); $this->setUpVfsDir();
$this->mockApp($this->root);
// fake console.php for setting an executable
vfsStream::newFile('console.php')
->at($this->root->getChild('bin'))
->setContent('<? php');
// Reusable App object
$this->app = new App($this->root->url());
BaseObject::setApp($this->app);
$this->console = new MultiUseConsole();
} }
public function execute($args) { protected function tearDown()
$this->app->reload(); {
\Mockery::close();
array_unshift($args, $this->getExecutablePath()); parent::tearDown();
Intercept::reset();
$this->console->reset();
$this->console->parseTestArgv($args);
$this->console->execute();
$returnStr = Intercept::$cache;
Intercept::reset();
return $returnStr;
} }
/** /**
* @return string returns the path to the console executable during tests * Dumps the execution of an console output to a string and returns it
*
* @param Console $console The current console instance
*
* @return string the output of the execution
*/ */
protected function getExecutablePath() { protected function dumpExecute($console)
return $this->root->getChild('bin' . DIRECTORY_SEPARATOR . 'console.php')->url(); {
Intercept::reset();
$console->execute();
$returnStr = Intercept::$cache;
Intercept::reset();
return $returnStr;
} }
} }

View file

@ -1,23 +0,0 @@
<?php
namespace Friendica\Test\src\Core\Console;
use Friendica\Core\Console;
/**
* Adds two methods to the Friendica\Core\Console so we can reuse it during tests
*
* @package Friendica\Test\src\Core\Console
*/
class MultiUseConsole extends Console
{
public function reset() {
$this->args = [];
$this->options = [];
}
public function parseTestArgv($argv)
{
$this->parseArgv($argv);
}
}