From aeb94e4dcc20a5a920d5e88ac6eed7c0099e4e61 Mon Sep 17 00:00:00 2001 From: Sven Reichel Date: Mon, 16 Dec 2024 02:42:26 +0100 Subject: [PATCH] reset tests --- .../Magento/Application/ConfigFileTest.php | 41 ++-- tests/N98/Magento/Application/ConfigTest.php | 111 +++++---- .../Application/ConfigurationLoaderTest.php | 14 +- tests/N98/Magento/ApplicationTest.php | 44 ++-- .../Admin/User/ChangePasswordCommandTest.php | 30 +-- .../Admin/User/ChangeStatusCommandTest.php | 79 +++---- .../Admin/User/CreateUserCommandTest.php | 90 ++++---- .../Admin/User/DeleteUserCommandTest.php | 98 ++++---- .../Command/Admin/User/ListCommandTest.php | 13 +- .../Command/Cache/CleanCommandTest.php | 18 +- .../Command/Cache/Dir/FlushCommandTest.php | 12 +- .../Command/Cache/DisableCommandTest.php | 12 +- .../Command/Cache/EnableCommandTest.php | 13 +- .../Command/Cache/FlushCommandTest.php | 7 +- .../Magento/Command/Cache/ListCommandTest.php | 9 +- .../Command/Cache/ReportCommandTest.php | 15 +- .../Magento/Command/Cache/ViewCommandTest.php | 14 +- .../Category/Create/DummyCommandTest.php | 56 ++--- .../Command/Cms/Block/ToggleCommandTest.php | 13 +- .../Command/Config/DeleteCommandTest.php | 19 +- .../Command/Config/DumpCommandTest.php | 9 +- .../Magento/Command/Config/GetCommandTest.php | 57 +++-- .../Command/Config/SearchCommandTest.php | 13 +- .../Command/Customer/CreateCommandTest.php | 24 +- .../Command/Customer/DeleteCommandTest.php | 210 ++++++++--------- .../Command/Customer/ListCommandTest.php | 7 +- .../Command/Database/DumpCommandTest.php | 99 ++++---- .../Command/Database/InfoCommandTest.php | 14 +- .../Maintain/CheckTablesCommandTest.php | 23 +- .../Command/Database/QueryCommandTest.php | 13 +- .../Command/Database/StatusCommandTest.php | 34 +-- .../Command/Database/VariablesCommandTest.php | 40 ++-- .../Command/Design/DemoNoticeCommandTest.php | 13 +- .../Developer/ClassLookupCommandTest.php | 20 +- .../Ide/PhpStorm/MetaCommandTest.php | 22 +- .../Command/Developer/Log/LogCommand.php | 7 +- .../Command/Developer/MergeCssCommandTest.php | 13 +- .../Command/Developer/MergeJsCommandTest.php | 13 +- .../Developer/Module/CreateCommandTest.php | 25 +- .../Module/Dependencies/FromCommandTest.php | 25 +- .../Module/Dependencies/OnCommandTest.php | 34 +-- .../Developer/Module/ListCommandTest.php | 9 +- .../Module/Observer/ListCommandTest.php | 9 +- .../Module/Rewrite/ClassExistsCheckerTest.php | 116 +++++----- .../Module/Rewrite/ConflictsCommandTest.php | 38 ++-- .../Module/Rewrite/fixture/Le_Foo_Le_Bar.php | 8 +- .../Rewrite/fixture/Le_Foo_Le_Bar_Fine.php | 8 +- .../Rewrite/fixture/Le_Foo_Le_Bar_R1.php | 12 +- .../Rewrite/fixture/Le_Foo_Le_Bar_R2.php | 7 +- .../Developer/Module/UpdateCommandTest.php | 119 +++++----- .../Command/Developer/ProfilerCommandTest.php | 13 +- .../Setup/Script/AttributeCommandTest.php | 14 +- .../Command/Developer/SymlinksCommandTest.php | 13 +- .../TemplateHintsBlocksCommandTest.php | 13 +- .../Developer/TemplateHintsCommandTest.php | 13 +- .../Developer/Theme/DuplicatesCommandTest.php | 16 +- .../Developer/Theme/InfoCommandTest.php | 11 +- .../Developer/Theme/ListCommandTest.php | 9 +- .../Translate/InlineAdminCommandTest.php | 13 +- .../Translate/InlineShopCommandTest.php | 13 +- .../Developer/Translate/SetCommandTest.php | 9 +- .../Eav/Attribute/Create/DummyCommandTest.php | 34 ++- .../Command/Eav/Attribute/ListCommandTest.php | 13 +- .../Eav/Attribute/RemoveCommandTest.php | 86 +++---- .../Command/Eav/Attribute/ViewCommandTest.php | 15 +- tests/N98/Magento/Command/HelpCommandTest.php | 8 +- .../Command/Indexer/ListCommandTest.php | 7 +- .../Command/Indexer/ReindexAllCommandTest.php | 25 +- .../Command/Indexer/ReindexCommandTest.php | 9 +- .../InstallCommandPackageVersionTest.php | 75 +++--- .../Command/Installer/InstallCommandTest.php | 23 +- .../Installer/InstallCommandTester.php | 13 +- .../Installer/UninstallCommandTest.php | 25 +- tests/N98/Magento/Command/ListCommandTest.php | 11 +- .../LocalConfig/GenerateCommandTest.php | 214 +++++++++--------- .../ListExtensionsCommandTest.php | 13 +- .../ValidateExtensionCommandTest.php | 8 +- .../N98/Magento/Command/Media/DumpCommand.php | 7 +- .../Script/Repository/ListCommandTest.php | 13 +- .../Script/Repository/RunCommandTest.php | 14 +- .../N98/Magento/Command/ScriptCommandTest.php | 31 ++- .../CookieDomainCheckAbstractTest.php | 73 +++--- .../Command/System/CheckCommandTest.php | 15 +- .../System/Cron/HistoryCommandTest.php | 9 +- .../Command/System/Cron/ListCommandTest.php | 7 +- .../Command/System/Cron/RunCommandTest.php | 19 +- .../System/Cron/ServerEnvironmentTest.php | 34 +-- .../Command/System/InfoCommandTest.php | 15 +- .../Command/System/MaintenanceCommandTest.php | 17 +- .../System/Setup/ChangeVersionCommandTest.php | 57 ++--- .../Setup/CompareVersionsCommandTest.php | 22 +- .../System/Setup/IncrementalCommandStub.php | 20 +- .../System/Setup/IncrementalCommandTest.php | 17 +- .../System/Setup/RemoveCommandTest.php | 92 ++++---- .../Command/System/Setup/RunCommandTest.php | 9 +- .../Store/Config/BaseUrlListCommandTest.php | 11 +- .../Command/System/Store/ListCommandTest.php | 9 +- .../Command/System/Url/ListCommandTest.php | 13 +- .../System/Website/ListCommandTest.php | 11 +- tests/N98/Magento/Command/TestCase.php | 24 +- tests/N98/Magento/DbSettingsTest.php | 50 ++-- tests/N98/Magento/MagerunCommandTester.php | 12 +- tests/N98/Magento/ModulesTest.php | 49 ++-- tests/N98/Magento/TestApplication.php | 84 ++++--- tests/N98/Magento/TestApplicationTest.php | 41 ++-- .../_ApplicationTestComposer/FooCommand.php | 7 +- .../src/TestModule/FooCommand.php | 15 +- .../N98MagerunTest/AlternativeConfigModel.php | 7 +- .../N98MagerunTest/TestDummyCommand.php | 9 +- tests/N98/Util/ArrayFunctionsTest.php | 81 +++---- tests/N98/Util/AutoloadHandlerTest.php | 104 +++++---- tests/N98/Util/AutoloadRestorerTest.php | 31 +-- tests/N98/Util/BinaryStringTest.php | 16 +- .../Console/Helper/DatabaseHelperTest.php | 139 +++++++----- .../N98/Util/Console/Helper/IoHelperTest.php | 18 +- .../N98/Util/Console/Helper/MagentoHelper.php | 60 +++-- .../Table/Renderer/RenderFactoryTest.php | 13 +- .../Helper/Table/Renderer/TestCase.php | 3 - .../Table/Renderer/TextRendererTest.php | 21 +- .../Helper/Table/Renderer/XmlRendererTest.php | 56 ++--- tests/N98/Util/DateTimeTest.php | 22 +- tests/N98/Util/ExecTest.php | 26 ++- tests/N98/Util/FilesystemTest.php | 92 ++++---- tests/N98/Util/OperatingSystemTest.php | 59 ++--- tests/N98/Util/StringTypedTest.php | 20 +- tests/N98/Util/Unicode/CharsetTest.php | 9 +- tests/N98/Util/VerifyOrDieTest.php | 60 +++-- tests/N98/Util/WindowsSystemTest.php | 33 ++- 128 files changed, 2011 insertions(+), 2130 deletions(-) diff --git a/tests/N98/Magento/Application/ConfigFileTest.php b/tests/N98/Magento/Application/ConfigFileTest.php index d381d8b3c..f4108f001 100644 --- a/tests/N98/Magento/Application/ConfigFileTest.php +++ b/tests/N98/Magento/Application/ConfigFileTest.php @@ -1,7 +1,4 @@ assertInstanceOf(ConfigFile::class, $configFile); + self::assertInstanceOf(ConfigFile::class, $configFile); $configFile = ConfigFile::createFromFile(__FILE__); - $this->assertInstanceOf(ConfigFile::class, $configFile); + self::assertInstanceOf(ConfigFile::class, $configFile); } - public function testApplyVariables() + /** + * @test + */ + public function applyVariables() { $configFile = new ConfigFile(); $configFile->loadFile('data://,- %root%'); $configFile->applyVariables('root-folder'); - $this->assertSame(['root-folder'], $configFile->toArray()); + self::assertSame(['root-folder'], $configFile->toArray()); } - public function testMergeArray() + /** + * @test + */ + public function mergeArray() { $configFile = new ConfigFile(); $configFile->loadFile('data://,- bar'); - $result = $configFile->mergeArray(['foo']); - $this->assertSame(['foo', 'bar'], $result); + self::assertSame(['foo', 'bar'], $result); } - public function testParseEmptyFile() + /** + * @test + */ + public function parseEmptyFile() { $this->expectException(RuntimeException::class); - $this->expectExceptionMessage("Failed to parse config-file 'data://,'"); + $this->expectExceptionMessage('Failed to parse config-file \'data://,\''); $configFile = new ConfigFile(); $configFile->loadFile('data://,'); $this->addToAssertionCount(1); @@ -61,7 +69,10 @@ public function testParseEmptyFile() self::fail('An expected exception has not been thrown.'); } - public function testInvalidFileThrowsException() + /** + * @test + */ + public function invalidFileThrowsException() { $this->expectException(InvalidArgumentException::class); @ConfigFile::createFromFile(':'); diff --git a/tests/N98/Magento/Application/ConfigTest.php b/tests/N98/Magento/Application/ConfigTest.php index 5f7ce909d..4598d8b24 100644 --- a/tests/N98/Magento/Application/ConfigTest.php +++ b/tests/N98/Magento/Application/ConfigTest.php @@ -1,7 +1,4 @@ */ @@ -27,72 +24,82 @@ * @covers N98\Magento\Application\Config * @package N98\Magento\Application */ -final class ConfigTest extends TestCase +class ConfigTest extends TestCase { - public function testCreation() + /** + * @test + */ + public function creation() { $config = new Config(); - $this->assertInstanceOf(__NAMESPACE__ . '\\Config', $config); + self::assertInstanceOf(__NAMESPACE__ . '\\Config', $config); } - public function testLoader() + /** + * @test + */ + public function loader() { $config = new Config(); try { $config->load(); self::fail('An expected exception was not thrown'); - } catch (ErrorException $errorException) { - $this->assertSame('Configuration not yet fully loaded', $errorException->getMessage()); + } catch (ErrorException $e) { + self::assertEquals('Configuration not yet fully loaded', $e->getMessage()); } - $this->assertSame([], $config->getConfig()); + self::assertEquals([], $config->getConfig()); - $configurationLoader = $config->getLoader(); - $this->assertInstanceOf(__NAMESPACE__ . '\\ConfigurationLoader', $configurationLoader); - $this->assertSame($configurationLoader, $config->getLoader()); + $loader = $config->getLoader(); + self::assertInstanceOf(__NAMESPACE__ . '\\ConfigurationLoader', $loader); + self::assertSame($loader, $config->getLoader()); - $configurationLoader->loadStageTwo(''); + $loader->loadStageTwo(''); $config->load(); - $this->assertIsArray($config->getConfig()); - $this->assertGreaterThan(4, count($config->getConfig())); + self::assertIsArray($config->getConfig()); + self::assertGreaterThan(4, count($config->getConfig())); - $config->setLoader($configurationLoader); + $config->setLoader($loader); } /** * config array setter is used in some tests on @see \N98\Magento\Application::setConfig() + * + * @test */ - public function testSetConfig() + public function setConfig() { $config = new Config(); $config->setConfig([0, 1, 2]); - $actual = $config->getConfig(); - $this->assertSame(1, $actual[1]); + self::assertSame($actual[1], 1); } - public function testConfigCommandAlias() + /** + * @test + */ + public function configCommandAlias() { $config = new Config(); $input = new ArgvInput(); $actual = $config->checkConfigCommandAlias($input); - $this->assertInstanceOf(InputInterface::class, $actual); + self::assertInstanceOf(InputInterface::class, $actual); $saved = $_SERVER['argv']; { $config->setConfig(['commands' => ['aliases' => [['list-help' => 'list --help']]]]); - $inputDefinition = new InputDefinition(); - $inputDefinition->addArgument(new InputArgument('command')); + $definition = new InputDefinition(); + $definition->addArgument(new InputArgument('command')); $argv = ['/path/to/command', 'list-help']; $_SERVER['argv'] = $argv; - $input = new ArgvInput($argv, $inputDefinition); - $this->assertSame('list-help', (string) $input); + $input = new ArgvInput($argv, $definition); + self::assertSame('list-help', (string) $input); $actual = $config->checkConfigCommandAlias($input); - $this->assertSame('list-help', $actual->getFirstArgument()); - $this->assertSame('list-help --help', (string) $actual); + self::assertSame('list-help', $actual->getFirstArgument()); + self::assertSame('list-help --help', (string) $actual); } $_SERVER['argv'] = $saved; @@ -100,10 +107,13 @@ public function testConfigCommandAlias() $config->registerConfigCommandAlias($command); - $this->assertSame(['list-help'], $command->getAliases()); + self::assertSame(['list-help'], $command->getAliases()); } - public function testCustomCommands() + /** + * @test + */ + public function customCommands() { $configArray = [ 'commands' => [ @@ -114,10 +124,10 @@ public function testCustomCommands() ], ]; - $bufferedOutput = new BufferedOutput(); - $bufferedOutput->setVerbosity($bufferedOutput::VERBOSITY_DEBUG); + $output = new BufferedOutput(); + $output->setVerbosity($output::VERBOSITY_DEBUG); - $config = new Config([], false, $bufferedOutput); + $config = new Config([], false, $output); $config->setConfig($configArray); /** @var Application|MockObject $application */ @@ -127,38 +137,41 @@ public function testCustomCommands() $config->registerCustomCommands($application); } - public function testRegisterCustomAutoloaders() + /** + * @test + */ + public function registerCustomAutoloaders() { - $array = [ - 'autoloaders' => ['$prefix' => '$path'], - 'autoloaders_psr4' => ['$prefix\\' => '$path'], - ]; + $array = ['autoloaders' => ['$prefix' => '$path'], 'autoloaders_psr4' => ['$prefix\\' => '$path']]; $expected = 'Registered PSR-0 autoloader $prefix -> $path' . "\n" . 'Registered PSR-4 autoloader $prefix\\ -> $path' . "\n"; - $bufferedOutput = new BufferedOutput(); + $output = new BufferedOutput(); - $config = new Config([], false, $bufferedOutput); + $config = new Config([], false, $output); $config->setConfig($array); - $classLoader = new ClassLoader(); - $config->registerCustomAutoloaders($classLoader); + $autloader = new ClassLoader(); + $config->registerCustomAutoloaders($autloader); - $bufferedOutput->setVerbosity($bufferedOutput::VERBOSITY_DEBUG); - $config->registerCustomAutoloaders($classLoader); + $output->setVerbosity($output::VERBOSITY_DEBUG); + $config->registerCustomAutoloaders($autloader); - $this->assertSame($expected, $bufferedOutput->fetch()); + self::assertSame($expected, $output->fetch()); } - public function testLoadPartialConfig() + /** + * @test + */ + public function loadPartialConfig() { $config = new Config(); - $this->assertSame([], $config->getDetectSubFolders()); + self::assertEquals([], $config->getDetectSubFolders()); $config->loadPartialConfig(false); $actual = $config->getDetectSubFolders(); - $this->assertIsArray($actual); - $this->assertNotSame([], $actual); + self::assertIsArray($actual); + self::assertNotEquals([], $actual); } } diff --git a/tests/N98/Magento/Application/ConfigurationLoaderTest.php b/tests/N98/Magento/Application/ConfigurationLoaderTest.php index 52a03237c..0ac645e14 100644 --- a/tests/N98/Magento/Application/ConfigurationLoaderTest.php +++ b/tests/N98/Magento/Application/ConfigurationLoaderTest.php @@ -1,7 +1,4 @@ assertInstanceOf(__NAMESPACE__ . '\\ConfigurationLoader', $configurationLoader); + $loader = new ConfigurationLoader([], false, new NullOutput()); + self::assertInstanceOf(__NAMESPACE__ . '\\ConfigurationLoader', $loader); } } diff --git a/tests/N98/Magento/ApplicationTest.php b/tests/N98/Magento/ApplicationTest.php index cea0e4f80..5eba4c184 100644 --- a/tests/N98/Magento/ApplicationTest.php +++ b/tests/N98/Magento/ApplicationTest.php @@ -1,7 +1,5 @@ setMagentoRootFolder($this->getTestMagentoRoot()); - $this->assertInstanceOf(Application::class, $application); + self::assertInstanceOf(Application::class, $application); $loader = $application->getAutoloader(); - $this->assertInstanceOf(ClassLoader::class, $loader); + self::assertInstanceOf(ClassLoader::class, $loader); /** * Check version */ - $this->assertSame(Application::APP_VERSION, trim(file_get_contents(__DIR__ . '/../../../version.txt'))); + self::assertEquals(Application::APP_VERSION, trim(file_get_contents(__DIR__ . '/../../../version.txt'))); /* @var $loader \Composer\Autoload\ClassLoader */ $prefixes = $loader->getPrefixesPsr4(); - $this->assertArrayHasKey('N98\\', $prefixes); + self::assertArrayHasKey('N98\\', $prefixes); $distConfigArray = Yaml::parse(file_get_contents(__DIR__ . '/../../../config.yaml')); - $configArray = ['autoloaders' => ['N98MagerunTest' => __DIR__ . '/_ApplicationTestSrc'], 'commands' => ['customCommands' => [0 => \N98MagerunTest\TestDummyCommand::class], 'aliases' => [['cl' => 'cache:list']]], 'init' => ['options' => ['config_model' => \N98MagerunTest\AlternativeConfigModel::class]]]; + $configArray = ['autoloaders' => ['N98MagerunTest' => __DIR__ . '/_ApplicationTestSrc'], 'commands' => ['customCommands' => [0 => 'N98MagerunTest\TestDummyCommand'], 'aliases' => [['cl' => 'cache:list']]], 'init' => ['options' => ['config_model' => 'N98MagerunTest\AlternativeConfigModel']]]; $application->setAutoExit(false); $application->init(ArrayFunctions::mergeArrays($distConfigArray, $configArray)); $application->run(new StringInput('list'), new NullOutput()); - // Check if autoloader, commands and aliases are registered + // Check if autoloaders, commands and aliases are registered $prefixes = $loader->getPrefixes(); - $this->assertArrayHasKey('N98MagerunTest', $prefixes); + self::assertArrayHasKey('N98MagerunTest', $prefixes); $testDummyCommand = $application->find('n98mageruntest:test:dummy'); - $this->assertInstanceOf(\N98MagerunTest\TestDummyCommand::class, $testDummyCommand); + self::assertInstanceOf('\N98MagerunTest\TestDummyCommand', $testDummyCommand); $commandTester = new CommandTester($testDummyCommand); $commandTester->execute( - ['command' => $testDummyCommand->getName()], + ['command' => $testDummyCommand->getName()] ); - $this->assertStringContainsString('dummy', $commandTester->getDisplay()); - $this->assertTrue($application->getDefinition()->hasOption('root-dir')); + self::assertStringContainsString('dummy', $commandTester->getDisplay()); + self::assertTrue($application->getDefinition()->hasOption('root-dir')); // Test alternative config model $application->initMagento(); if (version_compare(Mage::getVersion(), '1.7.0.2', '>=')) { // config_model option is only available in Magento CE >1.6 - $this->assertInstanceOf(\N98MagerunTest\AlternativeConfigModel::class, Mage::getConfig()); + self::assertInstanceOf('\N98MagerunTest\AlternativeConfigModel', Mage::getConfig()); } // check alias - $this->assertInstanceOf(ListCommand::class, $application->find('cl')); + self::assertInstanceOf(ListCommand::class, $application->find('cl')); } public function testPlugins() @@ -90,33 +88,33 @@ public function testPlugins() $application->init($injectConfig); // Check for module command - $this->assertInstanceOf(\TestModule\FooCommand::class, $application->find('testmodule:foo')); + self::assertInstanceOf('TestModule\FooCommand', $application->find('testmodule:foo')); } public function testComposer() { vfsStream::setup('root'); vfsStream::create( - ['htdocs' => ['app' => ['Mage.php' => '']], 'vendor' => ['acme' => ['magerun-test-module' => ['n98-magerun.yaml' => file_get_contents(__DIR__ . '/_ApplicationTestComposer/n98-magerun.yaml'), 'src' => ['Acme' => ['FooCommand.php' => file_get_contents(__DIR__ . '/_ApplicationTestComposer/FooCommand.php')]]]], 'n98' => ['magerun' => ['src' => ['N98' => ['Magento' => ['Command' => ['ConfigurationLoader.php' => '']]]]]]]], + ['htdocs' => ['app' => ['Mage.php' => '']], 'vendor' => ['acme' => ['magerun-test-module' => ['n98-magerun.yaml' => file_get_contents(__DIR__ . '/_ApplicationTestComposer/n98-magerun.yaml'), 'src' => ['Acme' => ['FooCommand.php' => file_get_contents(__DIR__ . '/_ApplicationTestComposer/FooCommand.php')]]]], 'n98' => ['magerun' => ['src' => ['N98' => ['Magento' => ['Command' => ['ConfigurationLoader.php' => '']]]]]]]] ); - /** @var ConfigurationLoader|MockObject $mock */ - $mock = $this->getMockBuilder(ConfigurationLoader::class) + /** @var ConfigurationLoader|MockObject $configurationLoader */ + $configurationLoader = $this->getMockBuilder(ConfigurationLoader::class) ->setMethods(['getConfigurationLoaderDir']) ->setConstructorArgs([[], false, new NullOutput()]) ->getMock(); - $mock + $configurationLoader ->method('getConfigurationLoaderDir') ->willReturn(vfsStream::url('root/vendor/n98/magerun/src/N98/Magento/Command')); /* @var $application Application */ $application = require __DIR__ . '/../../../src/bootstrap.php'; $application->setMagentoRootFolder(vfsStream::url('root/htdocs')); - $application->setConfigurationLoader($mock); + $application->setConfigurationLoader($configurationLoader); $application->init(); // Check for module command - $this->assertInstanceOf(\Acme\FooCommand::class, $application->find('acme:foo')); + self::assertInstanceOf('Acme\FooCommand', $application->find('acme:foo')); } } diff --git a/tests/N98/Magento/Command/Admin/User/ChangePasswordCommandTest.php b/tests/N98/Magento/Command/Admin/User/ChangePasswordCommandTest.php index 8d6533122..b3fbb8fe4 100644 --- a/tests/N98/Magento/Command/Admin/User/ChangePasswordCommandTest.php +++ b/tests/N98/Magento/Command/Admin/User/ChangePasswordCommandTest.php @@ -1,7 +1,5 @@ command = $this->getMockBuilder(ChangePasswordCommand::class) ->setMethods(['getUserModel']) @@ -37,7 +33,7 @@ protected function setUp(): void public function testCanChangePassword() { $this->userModel - ->expects($this->once()) + ->expects(self::once()) ->method('loadByUsername') ->with('aydin') ->willReturn($this->userModel); @@ -48,30 +44,29 @@ public function testCanChangePassword() ->willReturn(2); $this->userModel - ->expects($this->once()) + ->expects(self::once()) ->method('validate'); $this->userModel - ->expects($this->once()) + ->expects(self::once()) ->method('save'); $application = $this->getApplication(); $application->add($this->command); - $command = $this->getApplication()->find($this->commandName); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), 'username' => 'aydin', 'password' => 'password'], + ['command' => $command->getName(), 'username' => 'aydin', 'password' => 'password'] ); - $this->assertStringContainsString('Password successfully changed', $commandTester->getDisplay()); + self::assertStringContainsString('Password successfully changed', $commandTester->getDisplay()); } public function testReturnEarlyIfUserNotFound() { $this->userModel - ->expects($this->once()) + ->expects(self::once()) ->method('loadByUsername') ->with('notauser') ->willReturn($this->userModel); @@ -83,12 +78,11 @@ public function testReturnEarlyIfUserNotFound() $application = $this->getApplication(); $application->add($this->command); - $command = $this->getApplication()->find($this->commandName); $commandTester = new CommandTester($command); $commandTester->execute(['command' => $command->getName(), 'username' => 'notauser']); - $this->assertStringContainsString('User was not found', $commandTester->getDisplay()); + self::assertStringContainsString('User was not found', $commandTester->getDisplay()); } } diff --git a/tests/N98/Magento/Command/Admin/User/ChangeStatusCommandTest.php b/tests/N98/Magento/Command/Admin/User/ChangeStatusCommandTest.php index 95186a120..9157adeba 100644 --- a/tests/N98/Magento/Command/Admin/User/ChangeStatusCommandTest.php +++ b/tests/N98/Magento/Command/Admin/User/ChangeStatusCommandTest.php @@ -1,7 +1,5 @@ command = $this->getMockBuilder(ChangeStatusCommand::class) ->setMethods(['getUserModel']) @@ -39,7 +35,7 @@ public function testCanEnableByUser() { $username = 'aydin'; $this->userModel - ->expects($this->once()) + ->expects(self::once()) ->method('loadByUsername') ->with($username) ->willReturn($this->userModel); @@ -55,7 +51,7 @@ public function testCanEnableByUser() ->willReturn(2); $this->userModel - ->expects($this->once()) + ->expects(self::once()) ->method('validate'); $this->userModel @@ -64,12 +60,12 @@ public function testCanEnableByUser() ->willReturn(0); $this->userModel - ->expects($this->once()) + ->expects(self::once()) ->method('setIsActive') ->with(1); $this->userModel - ->expects($this->once()) + ->expects(self::once()) ->method('save'); $this->userModel @@ -78,28 +74,27 @@ public function testCanEnableByUser() ->willReturn(1); $this->userModel - ->expects($this->once()) + ->expects(self::once()) ->method('getUsername') ->willReturn($username); $application = $this->getApplication(); $application->add($this->command); - $command = $this->getApplication()->find($this->commandName); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), 'id' => $username], + ['command' => $command->getName(), 'id' => $username] ); - $this->assertStringContainsString(sprintf('User %s is now active', $username), $commandTester->getDisplay()); + self::assertStringContainsString("User $username is now active", $commandTester->getDisplay()); } public function testCanDisableUser() { $username = 'aydin'; $this->userModel - ->expects($this->once()) + ->expects(self::once()) ->method('loadByUsername') ->with($username) ->willReturn($this->userModel); @@ -115,7 +110,7 @@ public function testCanDisableUser() ->willReturn(2); $this->userModel - ->expects($this->once()) + ->expects(self::once()) ->method('validate'); $this->userModel @@ -124,12 +119,12 @@ public function testCanDisableUser() ->willReturn(1); $this->userModel - ->expects($this->once()) + ->expects(self::once()) ->method('setIsActive') ->with(0); $this->userModel - ->expects($this->once()) + ->expects(self::once()) ->method('save'); $this->userModel @@ -138,28 +133,27 @@ public function testCanDisableUser() ->willReturn(2); $this->userModel - ->expects($this->once()) + ->expects(self::once()) ->method('getUsername') ->willReturn($username); $application = $this->getApplication(); $application->add($this->command); - $command = $this->getApplication()->find($this->commandName); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), 'id' => $username], + ['command' => $command->getName(), 'id' => $username] ); - $this->assertStringContainsString(sprintf('User %s is now inactive', $username), $commandTester->getDisplay()); + self::assertStringContainsString("User $username is now inactive", $commandTester->getDisplay()); } public function testCanToggleUserByEmail() { $username = 'aydin'; $this->userModel - ->expects($this->once()) + ->expects(self::once()) ->method('loadByUsername') ->with($username) ->willReturn($this->userModel); @@ -170,7 +164,7 @@ public function testCanToggleUserByEmail() ->willReturn(0); $this->userModel - ->expects($this->once()) + ->expects(self::once()) ->method('load') ->willReturn($this->userModel); @@ -180,7 +174,7 @@ public function testCanToggleUserByEmail() ->willReturn(2); $this->userModel - ->expects($this->once()) + ->expects(self::once()) ->method('validate'); $this->userModel @@ -189,12 +183,12 @@ public function testCanToggleUserByEmail() ->willReturn(0); $this->userModel - ->expects($this->once()) + ->expects(self::once()) ->method('setIsActive') ->with(1); $this->userModel - ->expects($this->once()) + ->expects(self::once()) ->method('save'); $this->userModel @@ -203,27 +197,26 @@ public function testCanToggleUserByEmail() ->willReturn(1); $this->userModel - ->expects($this->once()) + ->expects(self::once()) ->method('getUsername') ->willReturn($username); $application = $this->getApplication(); $application->add($this->command); - $command = $this->getApplication()->find($this->commandName); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), 'id' => $username], + ['command' => $command->getName(), 'id' => $username] ); - $this->assertStringContainsString(sprintf('User %s is now active', $username), $commandTester->getDisplay()); + self::assertStringContainsString("User $username is now active", $commandTester->getDisplay()); } public function testReturnEarlyIfUserNotFound() { $this->userModel - ->expects($this->once()) + ->expects(self::once()) ->method('loadByUsername') ->with('notauser') ->willReturn($this->userModel); @@ -234,7 +227,7 @@ public function testReturnEarlyIfUserNotFound() ->willReturn(null); $this->userModel - ->expects($this->once()) + ->expects(self::once()) ->method('load') ->with('notauser', 'email') ->willReturn($this->userModel); @@ -246,29 +239,28 @@ public function testReturnEarlyIfUserNotFound() $application = $this->getApplication(); $application->add($this->command); - $command = $this->getApplication()->find($this->commandName); $commandTester = new CommandTester($command); $commandTester->execute(['command' => $command->getName(), 'id' => 'notauser']); - $this->assertStringContainsString('User was not found', $commandTester->getDisplay()); + self::assertStringContainsString('User was not found', $commandTester->getDisplay()); } public function testIfNoIdIsPresentItIsPromptedFor() { $userEmail = 'aydin@hotmail.co.uk'; - $mock = $this->getMockBuilder(QuestionHelper::class) + $dialog = $this->getMockBuilder(QuestionHelper::class) ->disableOriginalConstructor() ->setMethods(['ask']) ->getMock(); - $mock->expects($this->once()) + $dialog->expects(self::once()) ->method('ask') ->willReturn($userEmail); $this->userModel - ->expects($this->once()) + ->expects(self::once()) ->method('loadByUsername') ->with($userEmail) ->willReturn($this->userModel); @@ -283,15 +275,14 @@ public function testIfNoIdIsPresentItIsPromptedFor() $application = $this->getApplication(); $application->add($this->command); - $command = $this->getApplication()->find($this->commandName); // We override the standard helper with our mock - $command->getHelperSet()->set($mock, 'dialog'); + $command->getHelperSet()->set($dialog, 'dialog'); $commandTester = new CommandTester($command); $commandTester->execute(['command' => $command->getName()]); - $this->assertStringContainsString('User aydin is now inactive', $commandTester->getDisplay()); + self::assertStringContainsString('User aydin is now inactive', $commandTester->getDisplay()); } } diff --git a/tests/N98/Magento/Command/Admin/User/CreateUserCommandTest.php b/tests/N98/Magento/Command/Admin/User/CreateUserCommandTest.php index 8cf448f8c..0749e2391 100644 --- a/tests/N98/Magento/Command/Admin/User/CreateUserCommandTest.php +++ b/tests/N98/Magento/Command/Admin/User/CreateUserCommandTest.php @@ -1,12 +1,7 @@ command = $this->getMockBuilder(CreateUserCommand::class) ->setMethods(['getUserModel', 'getRoleModel', 'getRulesModel']) ->getMock(); - $this->userModel = $this->getMockBuilder(Mage_Admin_Model_User::class) + $this->userModel = $this->getMockBuilder('Mage_Admin_Model_User') ->setMethods(['setData', 'save', 'setRoleIds', 'getUserId', 'setRoleUserId', 'saveRelations']) ->disableOriginalConstructor() ->getMock(); @@ -41,7 +32,7 @@ protected function setUp(): void ->method('getUserModel') ->willReturn($this->userModel); - $this->roleModel = $this->getMockBuilder(Mage_Admin_Model_Roles::class) + $this->roleModel = $this->getMockBuilder('Mage_Admin_Model_Role') ->setMethods(['load', 'getId', 'setName', 'setRoleType', 'save']) ->disableOriginalConstructor() ->getMock(); @@ -50,7 +41,7 @@ protected function setUp(): void ->method('getRoleModel') ->willReturn($this->roleModel); - $this->rulesModel = $this->getMockBuilder(Mage_Admin_Model_Rules::class) + $this->rulesModel = $this->getMockBuilder('Mage_Admin_Model_Rules') ->setMethods(['setRoleId', 'setResources', 'saveRel']) ->disableOriginalConstructor() ->getMock(); @@ -62,33 +53,33 @@ protected function setUp(): void public function testArgumentPromptsWhenNotPresent() { - $mock = $this->getMockBuilder(QuestionHelper::class) + $questionHelper = $this->getMockBuilder(QuestionHelper::class) ->disableOriginalConstructor() ->onlyMethods(['ask']) ->getMock(); - $mock->expects(self::at(0)) + $questionHelper->expects(self::at(0)) ->method('ask') ->willReturn('aydin'); - $mock->expects(self::at(1)) + $questionHelper->expects(self::at(1)) ->method('ask') ->willReturn('aydin@hotmail.co.uk'); - $mock->expects(self::at(2)) + $questionHelper->expects(self::at(2)) ->method('ask') ->willReturn('p4ssw0rd'); - $mock->expects(self::at(3)) + $questionHelper->expects(self::at(3)) ->method('ask') ->willReturn('Aydin'); - $mock->expects(self::at(4)) + $questionHelper->expects(self::at(4)) ->method('ask') ->willReturn('Hassan'); $this->roleModel - ->expects($this->once()) + ->expects(self::once()) ->method('load') ->with('Administrators', 'role_name') ->willReturn($this->roleModel); @@ -111,12 +102,12 @@ public function testArgumentPromptsWhenNotPresent() ->willReturn($this->userModel); $this->userModel - ->expects($this->once()) + ->expects(self::once()) ->method('save') ->willReturn($this->userModel); $this->userModel - ->expects($this->once()) + ->expects(self::once()) ->method('setRoleIds') ->with([9]) ->willReturn($this->userModel); @@ -127,62 +118,59 @@ public function testArgumentPromptsWhenNotPresent() ->willReturn(2); $this->userModel - ->expects($this->once()) + ->expects(self::once()) ->method('setRoleUserId') ->with(2) ->willReturn($this->userModel); $this->userModel - ->expects($this->once()) + ->expects(self::once()) ->method('saveRelations'); $application = $this->getApplication(); $application->add($this->command); - $command = $this->getApplication()->find($this->commandName); // We override the standard helper with our mock - $command->getHelperSet()->set($mock, 'question'); + $command->getHelperSet()->set($questionHelper, 'question'); $commandTester = new CommandTester($command); $commandTester->execute(['command' => $command->getName(), 'role' => 'Administrators']); - $this->assertStringContainsString('User aydin successfully created', $commandTester->getDisplay()); + self::assertStringContainsString('User aydin successfully created', $commandTester->getDisplay()); } public function testInvalidRole() { $application = $this->getApplication(); $application->add($this->command); - $command = $this->getApplication()->find($this->commandName); $this->roleModel - ->expects($this->once()) + ->expects(self::once()) ->method('load') ->with('invalid role', 'role_name') ->willReturn($this->roleModel); $this->roleModel - ->expects($this->once()) + ->expects(self::once()) ->method('getId') ->willReturn(null); $commandTester = new CommandTester($command); $commandTester->execute(['command' => $command->getName(), 'username' => 'aydin', 'firstname' => 'Aydin', 'lastname' => 'Hassan', 'email' => 'aydin@hotmail.co.uk', 'password' => 'p4ssw0rd', 'role' => 'invalid role']); - $this->assertStringContainsString('Role was not found', $commandTester->getDisplay()); + self::assertStringContainsString('Role was not found', $commandTester->getDisplay()); } public function testCreatingDevelopmentRole() { $application = $this->getApplication(); $application->add($this->command); - $command = $this->getApplication()->find($this->commandName); $this->roleModel - ->expects($this->once()) + ->expects(self::once()) ->method('load') ->with('Development', 'role_name') ->willReturn($this->roleModel); @@ -193,19 +181,19 @@ public function testCreatingDevelopmentRole() ->willReturn(null); $this->roleModel - ->expects($this->once()) + ->expects(self::once()) ->method('setName') ->with('Development') ->willReturn($this->roleModel); $this->roleModel - ->expects($this->once()) + ->expects(self::once()) ->method('setRoleType') ->with('G') ->willReturn($this->roleModel); $this->roleModel - ->expects($this->once()) + ->expects(self::once()) ->method('save'); $this->roleModel @@ -214,19 +202,19 @@ public function testCreatingDevelopmentRole() ->willReturn(5); $this->rulesModel - ->expects($this->once()) + ->expects(self::once()) ->method('setRoleId') ->with(5) ->willReturn($this->rulesModel); $this->rulesModel - ->expects($this->once()) + ->expects(self::once()) ->method('setResources') ->with(['all']) ->willReturn($this->rulesModel); $this->rulesModel - ->expects($this->once()) + ->expects(self::once()) ->method('saveRel'); $this->userModel @@ -243,7 +231,7 @@ public function testCreatingDevelopmentRole() ->willReturn($this->userModel); $this->userModel - ->expects($this->once()) + ->expects(self::once()) ->method('save') ->willReturn($this->userModel); @@ -253,7 +241,7 @@ public function testCreatingDevelopmentRole() ->willReturn(5); $this->userModel - ->expects($this->once()) + ->expects(self::once()) ->method('setRoleIds') ->with([5]) ->willReturn($this->userModel); @@ -264,13 +252,13 @@ public function testCreatingDevelopmentRole() ->willReturn(2); $this->userModel - ->expects($this->once()) + ->expects(self::once()) ->method('setRoleUserId') ->with(2) ->willReturn($this->userModel); $this->userModel - ->expects($this->once()) + ->expects(self::once()) ->method('saveRelations'); $commandTester = new CommandTester($command); @@ -283,7 +271,7 @@ public function testCreatingDevelopmentRole() 'password' => 'p4ssw0rd', ]); - $this->assertStringContainsString('The role Development was automatically created', $commandTester->getDisplay()); - $this->assertStringContainsString('User aydin successfully created', $commandTester->getDisplay()); + self::assertStringContainsString('The role Development was automatically created', $commandTester->getDisplay()); + self::assertStringContainsString('User aydin successfully created', $commandTester->getDisplay()); } } diff --git a/tests/N98/Magento/Command/Admin/User/DeleteUserCommandTest.php b/tests/N98/Magento/Command/Admin/User/DeleteUserCommandTest.php index 657208295..0c8059685 100644 --- a/tests/N98/Magento/Command/Admin/User/DeleteUserCommandTest.php +++ b/tests/N98/Magento/Command/Admin/User/DeleteUserCommandTest.php @@ -1,7 +1,5 @@ command = $this->getMockBuilder(DeleteUserCommand::class) ->setMethods(['getUserModel']) @@ -37,7 +34,7 @@ protected function setUp(): void public function testCanDeleteByUserName() { $this->userModel - ->expects($this->once()) + ->expects(self::once()) ->method('loadByUsername') ->with('aydin') ->willReturn($this->userModel); @@ -53,30 +50,29 @@ public function testCanDeleteByUserName() ->willReturn(2); $this->userModel - ->expects($this->never()) + ->expects(self::never()) ->method('load'); $this->userModel - ->expects($this->once()) + ->expects(self::once()) ->method('delete'); $application = $this->getApplication(); $application->add($this->command); - $command = $this->getApplication()->find('admin:user:delete'); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), 'id' => 'aydin', '--force' => true], + ['command' => $command->getName(), 'id' => 'aydin', '--force' => true] ); - $this->assertStringContainsString('User was successfully deleted', $commandTester->getDisplay()); + self::assertStringContainsString('User was successfully deleted', $commandTester->getDisplay()); } public function testCanDeleteByEmail() { $this->userModel - ->expects($this->once()) + ->expects(self::once()) ->method('loadByUsername') ->with('aydin@hotmail.co.uk') ->willReturn($this->userModel); @@ -87,7 +83,7 @@ public function testCanDeleteByEmail() ->willReturn(null); $this->userModel - ->expects($this->once()) + ->expects(self::once()) ->method('load') ->with('aydin@hotmail.co.uk', 'email') ->willReturn($this->userModel); @@ -98,26 +94,25 @@ public function testCanDeleteByEmail() ->willReturn(2); $this->userModel - ->expects($this->once()) + ->expects(self::once()) ->method('delete'); $application = $this->getApplication(); $application->add($this->command); - $command = $this->getApplication()->find('admin:user:delete'); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), 'id' => 'aydin@hotmail.co.uk', '--force' => true], + ['command' => $command->getName(), 'id' => 'aydin@hotmail.co.uk', '--force' => true] ); - $this->assertStringContainsString('User was successfully deleted', $commandTester->getDisplay()); + self::assertStringContainsString('User was successfully deleted', $commandTester->getDisplay()); } public function testReturnEarlyIfUserNotFound() { $this->userModel - ->expects($this->once()) + ->expects(self::once()) ->method('loadByUsername') ->with('notauser') ->willReturn($this->userModel); @@ -128,7 +123,7 @@ public function testReturnEarlyIfUserNotFound() ->willReturn(null); $this->userModel - ->expects($this->once()) + ->expects(self::once()) ->method('load') ->with('notauser', 'email') ->willReturn($this->userModel); @@ -140,19 +135,18 @@ public function testReturnEarlyIfUserNotFound() $application = $this->getApplication(); $application->add($this->command); - $command = $this->getApplication()->find('admin:user:delete'); $commandTester = new CommandTester($command); $commandTester->execute(['command' => $command->getName(), 'id' => 'notauser']); - $this->assertStringContainsString('User was not found', $commandTester->getDisplay()); + self::assertStringContainsString('User was not found', $commandTester->getDisplay()); } public function testMessageIsPrintedIfErrorDeleting() { $this->userModel - ->expects($this->once()) + ->expects(self::once()) ->method('loadByUsername') ->with('aydin@hotmail.co.uk') ->willReturn($this->userModel); @@ -163,7 +157,7 @@ public function testMessageIsPrintedIfErrorDeleting() ->willReturn(null); $this->userModel - ->expects($this->once()) + ->expects(self::once()) ->method('load') ->with('aydin@hotmail.co.uk', 'email') ->willReturn($this->userModel); @@ -175,27 +169,26 @@ public function testMessageIsPrintedIfErrorDeleting() $exception = new Exception('Error!'); $this->userModel - ->expects($this->once()) + ->expects(self::once()) ->method('delete') - ->willThrowException($exception); + ->will(self::throwException($exception)); $application = $this->getApplication(); $application->add($this->command); - $command = $this->getApplication()->find('admin:user:delete'); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), 'id' => 'aydin@hotmail.co.uk', '--force' => true], + ['command' => $command->getName(), 'id' => 'aydin@hotmail.co.uk', '--force' => true] ); - $this->assertStringContainsString('Error!', $commandTester->getDisplay()); + self::assertStringContainsString('Error!', $commandTester->getDisplay()); } public function testConfirmationTrueReplyDeletesUser() { $this->userModel - ->expects($this->once()) + ->expects(self::once()) ->method('loadByUsername') ->with('notauser') ->willReturn($this->userModel); @@ -206,7 +199,7 @@ public function testConfirmationTrueReplyDeletesUser() ->willReturn(null); $this->userModel - ->expects($this->once()) + ->expects(self::once()) ->method('load') ->with('notauser', 'email') ->willReturn($this->userModel); @@ -217,35 +210,34 @@ public function testConfirmationTrueReplyDeletesUser() ->willReturn(2); $this->userModel - ->expects($this->once()) + ->expects(self::once()) ->method('delete'); $application = $this->getApplication(); $application->add($this->command); - $command = $this->getApplication()->find('admin:user:delete'); - $mock = $this->getMockBuilder(QuestionHelper::class) + $questionHelper = $this->getMockBuilder(QuestionHelper::class) ->onlyMethods(['ask']) ->getMock(); - $mock->expects($this->once()) + $questionHelper->expects(self::once()) ->method('ask') ->willReturn(true); // We override the standard helper with our mock - $command->getHelperSet()->set($mock, 'question'); + $command->getHelperSet()->set($questionHelper, 'question'); $commandTester = new CommandTester($command); $commandTester->execute(['command' => $command->getName(), 'id' => 'notauser']); - $this->assertStringContainsString('User was successfully deleted', $commandTester->getDisplay()); + self::assertStringContainsString('User was successfully deleted', $commandTester->getDisplay()); } public function testConfirmationFalseReplyDoesNotDeleteUser() { $this->userModel - ->expects($this->once()) + ->expects(self::once()) ->method('loadByUsername') ->with('notauser') ->willReturn($this->userModel); @@ -256,7 +248,7 @@ public function testConfirmationFalseReplyDoesNotDeleteUser() ->willReturn(null); $this->userModel - ->expects($this->once()) + ->expects(self::once()) ->method('load') ->with('notauser', 'email') ->willReturn($this->userModel); @@ -267,24 +259,23 @@ public function testConfirmationFalseReplyDoesNotDeleteUser() ->willReturn(2); $this->userModel - ->expects($this->never()) + ->expects(self::never()) ->method('delete'); $application = $this->getApplication(); $application->add($this->command); - $command = $this->getApplication()->find('admin:user:delete'); - $mock = $this->getMockBuilder(QuestionHelper::class) + $questionHelper = $this->getMockBuilder(QuestionHelper::class) ->onlyMethods(['ask']) ->getMock(); - $mock->expects($this->once()) + $questionHelper->expects(self::once()) ->method('ask') ->willReturn(false); // We override the standard helper with our mock - $command->getHelperSet()->set($mock, 'question'); + $command->getHelperSet()->set($questionHelper, 'question'); $commandTester = new CommandTester($command); $commandTester->execute([ @@ -292,21 +283,21 @@ public function testConfirmationFalseReplyDoesNotDeleteUser() 'id' => 'notauser', ]); - $this->assertStringContainsString('Aborting delete', $commandTester->getDisplay()); + self::assertStringContainsString('Aborting delete', $commandTester->getDisplay()); } public function testIfNoIdIsPresentItIsPromptedFor() { - $mock = $this->getMockBuilder(QuestionHelper::class) + $questionHelper = $this->getMockBuilder(QuestionHelper::class) ->onlyMethods(['ask']) ->getMock(); - $mock->expects($this->once()) + $questionHelper->expects(self::once()) ->method('ask') ->willReturn('aydin@hotmail.co.uk'); $this->userModel - ->expects($this->once()) + ->expects(self::once()) ->method('loadByUsername') ->with('aydin@hotmail.co.uk') ->willReturn($this->userModel); @@ -317,7 +308,7 @@ public function testIfNoIdIsPresentItIsPromptedFor() ->willReturn(null); $this->userModel - ->expects($this->once()) + ->expects(self::once()) ->method('load') ->with('aydin@hotmail.co.uk', 'email') ->willReturn($this->userModel); @@ -328,20 +319,19 @@ public function testIfNoIdIsPresentItIsPromptedFor() ->willReturn(2); $this->userModel - ->expects($this->once()) + ->expects(self::once()) ->method('delete'); $application = $this->getApplication(); $application->add($this->command); - $command = $this->getApplication()->find('admin:user:delete'); // We override the standard helper with our mock - $command->getHelperSet()->set($mock, 'dialog'); + $command->getHelperSet()->set($questionHelper, 'dialog'); $commandTester = new CommandTester($command); $commandTester->execute(['command' => $command->getName(), '--force' => true]); - $this->assertStringContainsString('User was successfully deleted', $commandTester->getDisplay()); + self::assertStringContainsString('User was successfully deleted', $commandTester->getDisplay()); } } diff --git a/tests/N98/Magento/Command/Admin/User/ListCommandTest.php b/tests/N98/Magento/Command/Admin/User/ListCommandTest.php index 22e2bd482..79562cb00 100644 --- a/tests/N98/Magento/Command/Admin/User/ListCommandTest.php +++ b/tests/N98/Magento/Command/Admin/User/ListCommandTest.php @@ -1,27 +1,24 @@ getApplication(); $application->add(new ListCommand()); - $command = $this->getApplication()->find('admin:user:list'); $commandTester = new CommandTester($command); $commandTester->execute(['command' => $command->getName()]); - $this->assertStringContainsString('id', $commandTester->getDisplay()); - $this->assertStringContainsString('user', $commandTester->getDisplay()); - $this->assertStringContainsString('email', $commandTester->getDisplay()); - $this->assertStringContainsString('status', $commandTester->getDisplay()); + self::assertStringContainsString('id', $commandTester->getDisplay()); + self::assertStringContainsString('user', $commandTester->getDisplay()); + self::assertStringContainsString('email', $commandTester->getDisplay()); + self::assertStringContainsString('status', $commandTester->getDisplay()); } } diff --git a/tests/N98/Magento/Command/Cache/CleanCommandTest.php b/tests/N98/Magento/Command/Cache/CleanCommandTest.php index 9b2a31dc6..92c1945c0 100644 --- a/tests/N98/Magento/Command/Cache/CleanCommandTest.php +++ b/tests/N98/Magento/Command/Cache/CleanCommandTest.php @@ -1,7 +1,5 @@ isMagentoEnterprise()) { $against = '1.14.0.0'; } - if (-1 != version_compare($version, $against)) { self::markTestSkipped( sprintf( 'Test skipped because it fails after new install of a Magento 1.9+ version (Magento version is: ' . - '%s) which is the case on travis where we always have a new install.', - $version, - ), + '%s) which is the case on travis where we always have a new install.', $version + ) ); } @@ -45,20 +41,18 @@ public function testExecute() { $application = $this->getApplication(); $application->add(new CleanCommand()); - $command = $this->getApplication()->find('cache:clean'); $commandTester = new CommandTester($command); $commandTester->execute(['command' => $command->getName()]); - $this->assertStringContainsString('Cache config cleaned', $commandTester->getDisplay()); + self::assertStringContainsString('Cache config cleaned', $commandTester->getDisplay()); } public function testItCanCleanMultipleCaches() { $application = $this->getApplication(); $application->add(new CleanCommand()); - $command = $this->getApplication()->find('cache:clean'); $commandTester = new CommandTester($command); @@ -66,7 +60,7 @@ public function testItCanCleanMultipleCaches() $display = $commandTester->getDisplay(); - $this->assertStringContainsString('Cache config cleaned', $display); - $this->assertStringContainsString('Cache layout cleaned', $display); + self::assertStringContainsString('Cache config cleaned', $display); + self::assertStringContainsString('Cache layout cleaned', $display); } } diff --git a/tests/N98/Magento/Command/Cache/Dir/FlushCommandTest.php b/tests/N98/Magento/Command/Cache/Dir/FlushCommandTest.php index 0c49de88e..ad1be00f4 100644 --- a/tests/N98/Magento/Command/Cache/Dir/FlushCommandTest.php +++ b/tests/N98/Magento/Command/Cache/Dir/FlushCommandTest.php @@ -1,7 +1,4 @@ execute(['command' => $command->getName()]); $display = $commandTester->getDisplay(); - $this->assertStringContainsString('Flushing cache directory ', $display); - $this->assertStringContainsString('Cache directory flushed', $display); + self::assertStringContainsString('Flushing cache directory ', $display); + self::assertStringContainsString('Cache directory flushed', $display); } /** @@ -41,7 +38,8 @@ private function prepareCommand($object) { $application = $this->getApplication(); $application->add($object); + $command = $application->find($object::NAME); - return $application->find($object::NAME); + return $command; } } diff --git a/tests/N98/Magento/Command/Cache/DisableCommandTest.php b/tests/N98/Magento/Command/Cache/DisableCommandTest.php index fb683a745..e5cdca618 100644 --- a/tests/N98/Magento/Command/Cache/DisableCommandTest.php +++ b/tests/N98/Magento/Command/Cache/DisableCommandTest.php @@ -1,14 +1,12 @@ execute(['command' => $command->getName()]); - $this->assertMatchesRegularExpression('/Caches disabled/', $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/Caches disabled/', $commandTester->getDisplay()); } public function testExecuteMultipleCaches() @@ -30,10 +28,10 @@ public function testExecuteMultipleCaches() $command = $this->getApplication()->find('cache:disable'); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), 'code' => 'eav,config'], + ['command' => $command->getName(), 'code' => 'eav,config'] ); - $this->assertMatchesRegularExpression('/Cache config disabled/', $commandTester->getDisplay()); - $this->assertMatchesRegularExpression('/Cache eav disabled/', $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/Cache config disabled/', $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/Cache eav disabled/', $commandTester->getDisplay()); } } diff --git a/tests/N98/Magento/Command/Cache/EnableCommandTest.php b/tests/N98/Magento/Command/Cache/EnableCommandTest.php index 23e40f51a..0cb85aa45 100644 --- a/tests/N98/Magento/Command/Cache/EnableCommandTest.php +++ b/tests/N98/Magento/Command/Cache/EnableCommandTest.php @@ -1,26 +1,23 @@ getApplication(); $application->add(new EnableCommand()); - $command = $this->getApplication()->find('cache:enable'); $commandTester = new CommandTester($command); $commandTester->execute(['command' => $command->getName()]); - $this->assertMatchesRegularExpression('/Caches enabled/', $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/Caches enabled/', $commandTester->getDisplay()); } public function testExecuteMultipleCaches() @@ -31,10 +28,10 @@ public function testExecuteMultipleCaches() $command = $this->getApplication()->find('cache:enable'); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), 'code' => 'eav,config'], + ['command' => $command->getName(), 'code' => 'eav,config'] ); - $this->assertMatchesRegularExpression('/Cache config enabled/', $commandTester->getDisplay()); - $this->assertMatchesRegularExpression('/Cache eav enabled/', $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/Cache config enabled/', $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/Cache eav enabled/', $commandTester->getDisplay()); } } diff --git a/tests/N98/Magento/Command/Cache/FlushCommandTest.php b/tests/N98/Magento/Command/Cache/FlushCommandTest.php index 6264fd509..236c518c1 100644 --- a/tests/N98/Magento/Command/Cache/FlushCommandTest.php +++ b/tests/N98/Magento/Command/Cache/FlushCommandTest.php @@ -1,25 +1,22 @@ getApplication(); $application->add(new FlushCommand()); - $command = $this->getApplication()->find('cache:flush'); $commandTester = new CommandTester($command); $commandTester->execute(['command' => $command->getName()]); - $this->assertMatchesRegularExpression('/Cache cleared/', $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/Cache cleared/', $commandTester->getDisplay()); } } diff --git a/tests/N98/Magento/Command/Cache/ListCommandTest.php b/tests/N98/Magento/Command/Cache/ListCommandTest.php index e3f4c0052..f636a6f27 100644 --- a/tests/N98/Magento/Command/Cache/ListCommandTest.php +++ b/tests/N98/Magento/Command/Cache/ListCommandTest.php @@ -1,25 +1,22 @@ getApplication(); $application->add(new ListCommand()); - $command = $this->getApplication()->find('cache:list'); $commandTester = new CommandTester($command); $commandTester->execute(['command' => $command->getName()]); - $this->assertMatchesRegularExpression('/config/', $commandTester->getDisplay()); - $this->assertMatchesRegularExpression('/collections/', $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/config/', $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/collections/', $commandTester->getDisplay()); } } diff --git a/tests/N98/Magento/Command/Cache/ReportCommandTest.php b/tests/N98/Magento/Command/Cache/ReportCommandTest.php index 1c0630f95..6634eed32 100644 --- a/tests/N98/Magento/Command/Cache/ReportCommandTest.php +++ b/tests/N98/Magento/Command/Cache/ReportCommandTest.php @@ -1,29 +1,26 @@ getApplication(); $application->add(new ListCommand()); - $command = $this->getApplication()->find('cache:report'); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), '--tags' => true, '--mtime' => true], + ['command' => $command->getName(), '--tags' => true, '--mtime' => true] ); - $this->assertMatchesRegularExpression('/ID/', $commandTester->getDisplay()); - $this->assertMatchesRegularExpression('/EXPIRE/', $commandTester->getDisplay()); - $this->assertMatchesRegularExpression('/MTIME/', $commandTester->getDisplay()); - $this->assertMatchesRegularExpression('/TAGS/', $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/ID/', $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/EXPIRE/', $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/MTIME/', $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/TAGS/', $commandTester->getDisplay()); } } diff --git a/tests/N98/Magento/Command/Cache/ViewCommandTest.php b/tests/N98/Magento/Command/Cache/ViewCommandTest.php index 9e5df04b9..72dcb5130 100644 --- a/tests/N98/Magento/Command/Cache/ViewCommandTest.php +++ b/tests/N98/Magento/Command/Cache/ViewCommandTest.php @@ -1,37 +1,33 @@ getApplication(); $application->add(new ListCommand()); - $command = $this->getApplication()->find('cache:view'); Mage::app()->getCache()->save('TEST n98-magerun', 'n98-magerun-unittest'); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), 'id' => 'n98-magerun-unittest'], + ['command' => $command->getName(), 'id' => 'n98-magerun-unittest'] ); - $this->assertMatchesRegularExpression('/TEST n98-magerun/', $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/TEST n98-magerun/', $commandTester->getDisplay()); } public function testExecuteUnserialize() { $application = $this->getApplication(); $application->add(new ListCommand()); - $command = $this->getApplication()->find('cache:view'); $cacheData = [1, 2, 3, 'foo' => ['bar']]; @@ -39,9 +35,9 @@ public function testExecuteUnserialize() $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), 'id' => 'n98-magerun-unittest', '--unserialize' => true], + ['command' => $command->getName(), 'id' => 'n98-magerun-unittest', '--unserialize' => true] ); - $this->assertSame(print_r($cacheData, true) . "\n", $commandTester->getDisplay(true)); + self::assertEquals(print_r($cacheData, true) . "\n", $commandTester->getDisplay(true)); } } diff --git a/tests/N98/Magento/Command/Category/Create/DummyCommandTest.php b/tests/N98/Magento/Command/Category/Create/DummyCommandTest.php index 8686798bc..478065312 100644 --- a/tests/N98/Magento/Command/Category/Create/DummyCommandTest.php +++ b/tests/N98/Magento/Command/Category/Create/DummyCommandTest.php @@ -1,7 +1,5 @@ getApplication(); $application->add(new DummyCommand()); - $command = $application->find('category:create:dummy'); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), 'store-id' => 1, 'children-categories-number' => 1, 'category-name-prefix' => 'My Awesome Category', 'category-number' => 1], + ['command' => $command->getName(), 'store-id' => 1, 'children-categories-number' => 1, 'category-name-prefix' => 'My Awesome Category', 'category-number' => 1] ); - $this->assertMatchesRegularExpression("/CATEGORY: 'My Awesome Category (.+)' WITH ID: '(.+)' CREATED!/", $commandTester->getDisplay()); - $this->assertMatchesRegularExpression("/CATEGORY CHILD: 'My Awesome Category (.+)' WITH ID: '(.+)' CREATED!/", $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/CATEGORY: \'My Awesome Category (.+)\' WITH ID: \'(.+)\' CREATED!/', $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/CATEGORY CHILD: \'My Awesome Category (.+)\' WITH ID: \'(.+)\' CREATED!/', $commandTester->getDisplay()); // Check if the category is created correctly $match_parent = ''; $match_child = ''; - preg_match("/CATEGORY: 'My Awesome Category (.+)' WITH ID: '(.+)' CREATED!/", $commandTester->getDisplay(), $match_parent); - $this->assertTrue($this->checkifCategoryExist($match_parent[2])); - preg_match("/CATEGORY CHILD: 'My Awesome Category (.+)' WITH ID: '(.+)' CREATED!/", $commandTester->getDisplay(), $match_child); - $this->assertTrue($this->checkifCategoryExist($match_child[2])); + preg_match('/CATEGORY: \'My Awesome Category (.+)\' WITH ID: \'(.+)\' CREATED!/', $commandTester->getDisplay(), $match_parent); + self::assertTrue($this->checkifCategoryExist($match_parent[2])); + preg_match('/CATEGORY CHILD: \'My Awesome Category (.+)\' WITH ID: \'(.+)\' CREATED!/', $commandTester->getDisplay(), $match_child); + self::assertTrue($this->checkifCategoryExist($match_child[2])); // Delete category created $this->deleteMagentoCategory($match_parent[2]); $this->deleteMagentoCategory($match_child[2]); } - private function checkifCategoryExist($_category_id) + protected function checkifCategoryExist($_category_id) { if (!is_null(Mage::getModel('catalog/category')->load($_category_id)->getName())) { return true; } - - return null; } - private function deleteMagentoCategory($_category_id) + protected function deleteMagentoCategory($_category_id) { Mage::getModel('catalog/category')->load($_category_id)->delete(); } @@ -60,69 +55,68 @@ public function testmanageArguments() { $application = $this->getApplication(); $application->add(new DummyCommand()); - $command = $application->find('category:create:dummy'); - $mock = $this->getMockBuilder(QuestionHelper::class) + $dialog = $this->getMockBuilder(QuestionHelper::class) ->disableOriginalConstructor() ->setMethods(['ask']) ->getMock(); // ASK - store-id - $mock + $dialog ->method('ask') ->with( self::isInstanceOf(InputInterface::class), self::isInstanceOf(OutputInterface::class), - self::isInstanceOf(Question::class), + self::isInstanceOf(Question::class) ) ->willReturn(1); // ASK - children-categories-number - $mock + $dialog ->method('ask') ->with( self::isInstanceOf(InputInterface::class), self::isInstanceOf(OutputInterface::class), - self::isInstanceOf(Question::class), + self::isInstanceOf(Question::class) ) ->willReturn(0); // ASK - category-name-prefix - $mock + $dialog ->method('ask') ->with( self::isInstanceOf(InputInterface::class), self::isInstanceOf(OutputInterface::class), - self::isInstanceOf(Question::class), + self::isInstanceOf(Question::class) ) ->willReturn('My Awesome Category '); // ASK - category-number - $mock + $dialog ->method('ask') ->with( self::isInstanceOf(InputInterface::class), self::isInstanceOf(OutputInterface::class), - self::isInstanceOf(Question::class), + self::isInstanceOf(Question::class) ) ->willReturn(0); // We override the standard helper with our mock - $command->getHelperSet()->set($mock, 'dialog'); + $command->getHelperSet()->set($dialog, 'dialog'); $commandTester = new CommandTester($command); $commandTester->execute( [ 'command' => $command->getName(), - ], + ] ); $arguments = $commandTester->getInput()->getArguments(); - $this->assertArrayHasKey('store-id', $arguments); - $this->assertArrayHasKey('children-categories-number', $arguments); - $this->assertArrayHasKey('category-name-prefix', $arguments); - $this->assertArrayHasKey('category-number', $arguments); + self::assertArrayHasKey('store-id', $arguments); + self::assertArrayHasKey('children-categories-number', $arguments); + self::assertArrayHasKey('category-name-prefix', $arguments); + self::assertArrayHasKey('category-number', $arguments); } } diff --git a/tests/N98/Magento/Command/Cms/Block/ToggleCommandTest.php b/tests/N98/Magento/Command/Cms/Block/ToggleCommandTest.php index 508e7ffc6..61c9c6a4a 100644 --- a/tests/N98/Magento/Command/Cms/Block/ToggleCommandTest.php +++ b/tests/N98/Magento/Command/Cms/Block/ToggleCommandTest.php @@ -1,7 +1,5 @@ getApplication(); $application->add(new ToggleCommand()); - $command = $this->getApplication()->find('cms:block:toggle'); $commandTester = new CommandTester($command); $victim = Mage::getModel('cms/block')->getCollection()->getFirstItem(); @@ -28,16 +25,16 @@ public function testExecute() 'command' => $command->getName(), // id should work 'block_id' => $victim->getId(), - ], + ] ); - $this->assertStringContainsString('disabled', $commandTester->getDisplay()); + self::assertStringContainsString('disabled', $commandTester->getDisplay()); $commandTester->execute( [ 'command' => $command->getName(), // identifier should work 'block_id' => $victim->getIdentifier(), - ], + ] ); - $this->assertStringContainsString('enabled', $commandTester->getDisplay()); + self::assertStringContainsString('enabled', $commandTester->getDisplay()); } } diff --git a/tests/N98/Magento/Command/Config/DeleteCommandTest.php b/tests/N98/Magento/Command/Config/DeleteCommandTest.php index 6b8060938..0a666184f 100644 --- a/tests/N98/Magento/Command/Config/DeleteCommandTest.php +++ b/tests/N98/Magento/Command/Config/DeleteCommandTest.php @@ -1,20 +1,17 @@ getApplication(); $application->add(new DumpCommand()); - $setCommand = $this->getApplication()->find('config:set'); $deleteCommand = $this->getApplication()->find('config:delete'); @@ -23,15 +20,15 @@ public function testExecute() */ $commandTester = new CommandTester($setCommand); $commandTester->execute( - ['command' => $setCommand->getName(), 'path' => 'n98_magerun/foo/bar', 'value' => '1234'], + ['command' => $setCommand->getName(), 'path' => 'n98_magerun/foo/bar', 'value' => '1234'] ); - $this->assertStringContainsString('n98_magerun/foo/bar => 1234', $commandTester->getDisplay()); + self::assertStringContainsString('n98_magerun/foo/bar => 1234', $commandTester->getDisplay()); $commandTester = new CommandTester($deleteCommand); $commandTester->execute( - ['command' => $deleteCommand->getName(), 'path' => 'n98_magerun/foo/bar'], + ['command' => $deleteCommand->getName(), 'path' => 'n98_magerun/foo/bar'] ); - $this->assertStringContainsString('| n98_magerun/foo/bar | default | 0 |', $commandTester->getDisplay()); + self::assertStringContainsString('| n98_magerun/foo/bar | default | 0 |', $commandTester->getDisplay()); /** * Delete all @@ -46,17 +43,17 @@ public function testExecute() 'path' => 'n98_magerun/foo/bar', '--scope' => 'stores', '--scope-id' => $store->getId(), - 'value' => 'store-' . $store->getId()], + 'value' => 'store-' . $store->getId()] ); } $commandTester = new CommandTester($deleteCommand); $commandTester->execute( - ['command' => $deleteCommand->getName(), 'path' => 'n98_magerun/foo/bar', '--all' => true], + ['command' => $deleteCommand->getName(), 'path' => 'n98_magerun/foo/bar', '--all' => true] ); foreach (Mage::app()->getStores() as $store) { - $this->assertStringContainsString('| n98_magerun/foo/bar | stores | ' . $store->getId() . ' |', $commandTester->getDisplay()); + self::assertStringContainsString('| n98_magerun/foo/bar | stores | ' . $store->getId() . ' |', $commandTester->getDisplay()); } } } diff --git a/tests/N98/Magento/Command/Config/DumpCommandTest.php b/tests/N98/Magento/Command/Config/DumpCommandTest.php index 4c9726b5e..b2c738c37 100644 --- a/tests/N98/Magento/Command/Config/DumpCommandTest.php +++ b/tests/N98/Magento/Command/Config/DumpCommandTest.php @@ -1,25 +1,22 @@ getApplication(); $application->add(new DumpCommand()); - $command = $this->getApplication()->find('config:dump'); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), 'xpath' => 'global/install'], + ['command' => $command->getName(), 'xpath' => 'global/install'] ); - $this->assertStringContainsString('date', $commandTester->getDisplay()); + self::assertStringContainsString('date', $commandTester->getDisplay()); } } diff --git a/tests/N98/Magento/Command/Config/GetCommandTest.php b/tests/N98/Magento/Command/Config/GetCommandTest.php index e05d2920e..26b088f38 100644 --- a/tests/N98/Magento/Command/Config/GetCommandTest.php +++ b/tests/N98/Magento/Command/Config/GetCommandTest.php @@ -1,37 +1,38 @@ skipMagentoMinimumVersion('1.6.2.0', '1.11.2.0'); $this->assertDisplayRegExp( ['command' => 'config:set', '--no-null' => null, 'path' => 'n98_magerun/foo/bar', 'value' => 'NULL'], - '~^n98_magerun/foo/bar => NULL$~', + '~^n98_magerun/foo/bar => NULL$~' ); $this->assertDisplayContains( ['command' => 'config:get', '--magerun-script' => null, 'path' => 'n98_magerun/foo/bar'], - 'config:set --no-null --scope-id=0 --scope=default', + 'config:set --no-null --scope-id=0 --scope=default' ); $this->assertDisplayContains( ['command' => 'config:set', 'path' => 'n98_magerun/foo/bar', 'value' => 'NULL'], - 'n98_magerun/foo/bar => NULL (NULL/"unknown" value)', + 'n98_magerun/foo/bar => NULL (NULL/"unknown" value)' ); $this->assertDisplayContains( ['command' => 'config:get', 'path' => 'n98_magerun/foo/bar'], - '| n98_magerun/foo/bar | default | 0 | NULL (NULL/"unknown" value) |', + '| n98_magerun/foo/bar | default | 0 | NULL (NULL/"unknown" value) |' ); $this->assertDisplayContains( @@ -41,34 +42,32 @@ public function testNullValues() # needed to not use the previous output cache 'path' => 'n98_magerun/foo/bar', ], - "config:set --scope-id=0 --scope=default -- 'n98_magerun/foo/bar' NULL", + 'config:set --scope-id=0 --scope=default -- \'n98_magerun/foo/bar\' NULL' ); } - public function provideFormatsWithNull(): \Iterator + public function provideFormatsWithNull() { - yield [null, '~\\Q| n98_magerun/foo/bar | default | 0 | NULL (NULL/"unknown" value) |\\E~']; - yield ['csv', '~\\Qn98_magerun/foo/bar,default,0,NULL\\E~']; - yield ['json', '~"Value": *null~']; - yield ['xml', '~\\QNULL\\E~']; + return [[null, '~\\Q| n98_magerun/foo/bar | default | 0 | NULL (NULL/"unknown" value) |\\E~'], ['csv', '~\\Qn98_magerun/foo/bar,default,0,NULL\\E~'], ['json', '~"Value": *null~'], ['xml', '~\\QNULL\\E~']]; } /** + * @test * @dataProvider provideFormatsWithNull */ - public function testNullWithFormat($format, $expected) + public function nullWithFormat($format, $expected) { # Very old Magento versions do not support NULL values in configuration values $this->skipMagentoMinimumVersion('1.6.2.0', '1.11.2.0'); $this->assertDisplayContains( ['command' => 'config:set', 'path' => 'n98_magerun/foo/bar', 'value' => 'NULL'], - 'n98_magerun/foo/bar => NULL (NULL/"unknown" value)', + 'n98_magerun/foo/bar => NULL (NULL/"unknown" value)' ); $this->assertDisplayRegExp( ['command' => 'config:get', '--format' => $format, 'path' => 'n98_magerun/foo/bar'], - $expected, + $expected ); } @@ -79,22 +78,22 @@ public function testExecute() */ $this->assertDisplayContains( ['command' => 'config:set', 'path' => 'n98_magerun/foo/bar', 'value' => '1234'], - 'n98_magerun/foo/bar => 1234', + 'n98_magerun/foo/bar => 1234' ); $this->assertDisplayContains( ['command' => 'config:get', 'path' => 'n98_magerun/foo/bar'], - '| n98_magerun/foo/bar | default | 0 | 1234 |', + '| n98_magerun/foo/bar | default | 0 | 1234 |' ); $this->assertDisplayContains( ['command' => 'config:get', 'path' => 'n98_magerun/foo/bar', '--update-script' => true], - "\$installer->setConfigData('n98_magerun/foo/bar', '1234');", + "\$installer->setConfigData('n98_magerun/foo/bar', '1234');" ); $this->assertDisplayContains( ['command' => 'config:get', 'path' => 'n98_magerun/foo/bar', '--magerun-script' => true], - "config:set --scope-id=0 --scope=default -- 'n98_magerun/foo/bar' '1234'", + "config:set --scope-id=0 --scope=default -- 'n98_magerun/foo/bar' '1234'" ); /** @@ -116,7 +115,7 @@ public function testExecute() */ $this->assertDisplayRegExp( ['command' => 'config:get', 'path' => 'n98_magerun/foo/bar', '--format' => 'json'], - '/"Value":\s*"1234"/', + '/"Value":\s*"1234"/' ); } @@ -147,11 +146,10 @@ private function skipMagentoMinimumVersion($community, $enterprise) sprintf( 'Test requires minimum Magento version of "%s", version "%s" is in use', $community, - $magentoVersion, - ), + $magentoVersion + ) ); } - break; case 'Enterprise': if (version_compare($magentoVersion, $enterprise, '<')) { @@ -159,18 +157,17 @@ private function skipMagentoMinimumVersion($community, $enterprise) sprintf( 'Test requires minimum Magento version of "%s", version "%s" is in use', $enterprise, - $magentoVersion, - ), + $magentoVersion + ) ); } - break; default: self::markTestSkipped( sprintf( 'Test requires community or enterprise edition, Magento edition "%s" given', - $magentoEdition, - ), + $magentoEdition + ) ); } } diff --git a/tests/N98/Magento/Command/Config/SearchCommandTest.php b/tests/N98/Magento/Command/Config/SearchCommandTest.php index e4d8cc393..27bac88a0 100644 --- a/tests/N98/Magento/Command/Config/SearchCommandTest.php +++ b/tests/N98/Magento/Command/Config/SearchCommandTest.php @@ -1,31 +1,28 @@ getApplication(); $application->add(new DumpCommand()); - $command = $this->getApplication()->find('config:search'); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), 'text' => 'This message will be shown'], + ['command' => $command->getName(), 'text' => 'This message will be shown'] ); - $this->assertStringContainsString('Found a field with a match', $commandTester->getDisplay()); + self::assertStringContainsString('Found a field with a match', $commandTester->getDisplay()); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), 'text' => 'xyz1234567890'], + ['command' => $command->getName(), 'text' => 'xyz1234567890'] ); - $this->assertStringContainsString('No matches for xyz1234567890', $commandTester->getDisplay()); + self::assertStringContainsString('No matches for xyz1234567890', $commandTester->getDisplay()); } } diff --git a/tests/N98/Magento/Command/Customer/CreateCommandTest.php b/tests/N98/Magento/Command/Customer/CreateCommandTest.php index aa4fa0682..3d92bd3ae 100644 --- a/tests/N98/Magento/Command/Customer/CreateCommandTest.php +++ b/tests/N98/Magento/Command/Customer/CreateCommandTest.php @@ -1,7 +1,5 @@ _getCommand(); + $command = $this->_getCommand(); $generatedEmail = uniqid('', true) . '@example.com'; $this->getApplication()->initMagento(); $website = Mage::app()->getWebsite(); - $commandTester = new CommandTester($createCommand); - $options = ['command' => $createCommand->getName(), 'email' => $generatedEmail, 'password' => 'password123', 'firstname' => 'John', 'lastname' => 'Doe', 'website' => $website->getCode()]; + $commandTester = new CommandTester($command); + $options = ['command' => $command->getName(), 'email' => $generatedEmail, 'password' => 'password123', 'firstname' => 'John', 'lastname' => 'Doe', 'website' => $website->getCode()]; $commandTester->execute($options); - $this->assertMatchesRegularExpression('/Customer ' . $generatedEmail . ' successfully created/', $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/Customer ' . $generatedEmail . ' successfully created/', $commandTester->getDisplay()); // Format option - $commandTester = new CommandTester($createCommand); + $commandTester = new CommandTester($command); $generatedEmail = uniqid('', true) . '@example.com'; $options['email'] = $generatedEmail; $options['--format'] = 'csv'; - $this->assertSame(0, $commandTester->execute($options)); - $this->assertStringContainsString('email,password,firstname,lastname', $commandTester->getDisplay()); - $this->assertStringContainsString($generatedEmail . ',password123,John,Doe', $commandTester->getDisplay()); + self::assertEquals(0, $commandTester->execute($options)); + self::assertStringContainsString('email,password,firstname,lastname', $commandTester->getDisplay()); + self::assertStringContainsString($generatedEmail . ',password123,John,Doe', $commandTester->getDisplay()); } public function testWithWrongPassword() @@ -62,13 +60,13 @@ public function testWithWrongPassword() $options = ['command' => $command->getName(), 'email' => $generatedEmail, 'password' => 'pass', 'firstname' => 'John', 'lastname' => 'Doe']; $commandTester = new CommandTester($command); $commandTester->execute($options); - $this->assertMatchesRegularExpression('/The password must have at least 6 characters. Leading or trailing spaces will be ignored./', $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/The password must have at least 6 characters. Leading or trailing spaces will be ignored./', $commandTester->getDisplay()); } /** * @return CreateCommand */ - private function _getCommand() + protected function _getCommand() { $application = $this->getApplication(); $application->add(new CreateCommand()); diff --git a/tests/N98/Magento/Command/Customer/DeleteCommandTest.php b/tests/N98/Magento/Command/Customer/DeleteCommandTest.php index ee5d56bb5..41e921e4e 100644 --- a/tests/N98/Magento/Command/Customer/DeleteCommandTest.php +++ b/tests/N98/Magento/Command/Customer/DeleteCommandTest.php @@ -1,7 +1,5 @@ getModelClassName('customer/customer'); return $this->getMockBuilder($className) @@ -47,7 +41,7 @@ private function getCustomerModel(array $methods) ->getMock(); } - private function getCustomerCollection(array $methods) + protected function getCustomerCollection(array $methods) { $className = $this->getResourceClassName('customer/customer_collection'); return $this->getMockBuilder($className) @@ -59,8 +53,8 @@ private function getCustomerCollection(array $methods) protected function setUp(): void { $this->markTestIncomplete('This tests are not compatible with PHPUnit 9. Refactring is needed.'); - $application = $this->getApplication(); - $application->initMagento(); + $this->application = $this->getApplication(); + $this->application->initMagento(); $this->customerModel = $this->getCustomerModel(['loadByEmail', 'load', 'getId', 'delete', 'setWebsiteId']); $this->customerCollection = $this->getCustomerCollection(['addAttributeToSelect', 'addAttributeToFilter']); @@ -77,7 +71,7 @@ protected function setUp(): void ->onlyMethods(['askWebsite']) ->getMock(); - $mock = $this->getMockBuilder('Mage_Core_Model_Website') + $this->website = $this->getMockBuilder('Mage_Core_Model_Website') ->setMethods(['getId']) ->getMock(); @@ -95,9 +89,9 @@ protected function setUp(): void $this->parameterHelper ->method('askWebsite') - ->willReturn($mock); + ->willReturn($this->website); - $mock + $this->website ->method('getId') ->willReturn(1); } @@ -105,7 +99,7 @@ protected function setUp(): void public function testCanDeleteById() { $this->customerModel - ->expects($this->once()) + ->expects(self::once()) ->method('load') ->with('1') ->willReturn($this->customerModel); @@ -121,31 +115,30 @@ public function testCanDeleteById() ->willReturn(1); $this->customerModel - ->expects($this->never()) + ->expects(self::never()) ->method('loadByEmail'); $this->customerModel - ->expects($this->once()) + ->expects(self::once()) ->method('delete'); $application = $this->getApplication(); $application->add($this->command); - $command = $this->getApplication()->find('customer:delete'); $command->getHelperSet()->set($this->questionHelper, 'question'); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), 'id' => '1', '--force' => true], + ['command' => $command->getName(), 'id' => '1', '--force' => true] ); - $this->assertStringContainsString('successfully deleted', $commandTester->getDisplay()); + self::assertStringContainsString('successfully deleted', $commandTester->getDisplay()); } public function testCanDeleteByEmail() { $this->customerModel - ->expects($this->once()) + ->expects(self::once()) ->method('load') ->with('mike@testing.com') ->willReturn($this->customerModel); @@ -156,13 +149,13 @@ public function testCanDeleteByEmail() ->willReturn(null); $this->customerModel - ->expects($this->once()) + ->expects(self::once()) ->method('setWebsiteId') ->with(1) ->willReturn($this->customerModel); $this->customerModel - ->expects($this->once()) + ->expects(self::once()) ->method('loadByEmail') ->with('mike@testing.com') ->willReturn($this->customerModel); @@ -173,27 +166,26 @@ public function testCanDeleteByEmail() ->willReturn(1); $this->customerModel - ->expects($this->once()) + ->expects(self::once()) ->method('delete'); $application = $this->getApplication(); $application->add($this->command); - $command = $this->getApplication()->find('customer:delete'); $command->getHelperSet()->set($this->questionHelper, 'question'); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), 'id' => 'mike@testing.com', '--force' => true], + ['command' => $command->getName(), 'id' => 'mike@testing.com', '--force' => true] ); - $this->assertStringContainsString('successfully deleted', $commandTester->getDisplay()); + self::assertStringContainsString('successfully deleted', $commandTester->getDisplay()); } public function testCustomerNotFound() { $this->customerModel - ->expects($this->once()) + ->expects(self::once()) ->method('load') ->with('mike@testing.com') ->willReturn($this->customerModel); @@ -204,35 +196,34 @@ public function testCustomerNotFound() ->willReturn(null); $this->customerModel - ->expects($this->once()) + ->expects(self::once()) ->method('setWebsiteId') ->with(1) ->willReturn($this->customerModel); $this->customerModel - ->expects($this->once()) + ->expects(self::once()) ->method('loadByEmail') ->with('mike@testing.com') ->willReturn($this->customerModel); $application = $this->getApplication(); $application->add($this->command); - $command = $this->getApplication()->find('customer:delete'); $command->getHelperSet()->set($this->questionHelper, 'question'); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), 'id' => 'mike@testing.com', '--force' => true], + ['command' => $command->getName(), 'id' => 'mike@testing.com', '--force' => true] ); - $this->assertStringContainsString('No customer found!', $commandTester->getDisplay()); + self::assertStringContainsString('No customer found!', $commandTester->getDisplay()); } public function testDeleteFailed() { $this->customerModel - ->expects($this->once()) + ->expects(self::once()) ->method('load') ->with('1') ->willReturn($this->customerModel); @@ -248,27 +239,26 @@ public function testDeleteFailed() ->willReturn(1); $this->customerModel - ->expects($this->never()) + ->expects(self::never()) ->method('loadByEmail'); $this->customerModel - ->expects($this->once()) + ->expects(self::once()) ->method('delete') - ->willThrowException(new Exception('Failed to save')); + ->will(self::throwException(new Exception('Failed to save'))); $application = $this->getApplication(); $application->add($this->command); - $command = $this->getApplication()->find('customer:delete'); $commandTester = new CommandTester($command); $command->getHelperSet()->set($this->questionHelper, 'question'); $commandTester->execute( - ['command' => $command->getName(), 'id' => '1', '--force' => true], + ['command' => $command->getName(), 'id' => '1', '--force' => true] ); - $this->assertStringContainsString('Failed to save', $commandTester->getDisplay()); + self::assertStringContainsString('Failed to save', $commandTester->getDisplay()); } public function testPromptForCustomerIdAndDelete() @@ -284,7 +274,7 @@ public function testPromptForCustomerIdAndDelete() ->willReturn('1'); $this->customerModel - ->expects($this->once()) + ->expects(self::once()) ->method('load') ->with('1') ->willReturn($this->customerModel); @@ -300,16 +290,15 @@ public function testPromptForCustomerIdAndDelete() ->willReturn(1); $this->customerModel - ->expects($this->never()) + ->expects(self::never()) ->method('loadByEmail'); $this->customerModel - ->expects($this->once()) + ->expects(self::once()) ->method('delete'); $application = $this->getApplication(); $application->add($this->command); - $command = $this->getApplication()->find('customer:delete'); $command->getHelperSet()->set($this->questionHelper, 'question'); $command->getHelperSet()->set($this->parameterHelper, 'parameter'); @@ -317,43 +306,42 @@ public function testPromptForCustomerIdAndDelete() $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), '--force' => true], + ['command' => $command->getName(), '--force' => true] ); - $this->assertStringContainsString('successfully deleted', $commandTester->getDisplay()); + self::assertStringContainsString('successfully deleted', $commandTester->getDisplay()); } public function testBatchDeleteGetsCustomerCollection() { $this->customerCollection - ->expects($this->atLeastOnce()) + ->expects(self::atLeastOnce()) ->method('addAttributeToSelect') ->willReturnMap([['firstname', false, $this->customerCollection], ['lastname', false, $this->customerCollection], ['email', false, $this->customerCollection]]); $this->questionHelper - ->expects($this->once()) + ->expects(self::once()) ->method('ask') ->willReturn(false); $application = $this->getApplication(); $application->add($this->command); - $command = $this->getApplication()->find('customer:delete'); $commandTester = new CommandTester($command); $command->getHelperSet()->set($this->questionHelper, 'question'); $commandTester->execute( - ['command' => $command->getName(), '--all' => true], + ['command' => $command->getName(), '--all' => true] ); - $this->assertStringContainsString('Aborting delete', $commandTester->getDisplay()); + self::assertStringContainsString('Aborting delete', $commandTester->getDisplay()); } public function testRangeDeleteGetsCustomerCollection() { $this->customerCollection - ->expects($this->atLeastOnce()) + ->expects(self::atLeastOnce()) ->method('addAttributeToSelect') ->willReturnMap([['firstname', false, $this->customerCollection], ['lastname', false, $this->customerCollection], ['email', false, $this->customerCollection]]); @@ -372,7 +360,7 @@ public function testRangeDeleteGetsCustomerCollection() ->willReturn('10'); $this->customerCollection - ->expects($this->once()) + ->expects(self::once()) ->method('addAttributeToFilter') ->willReturn($this->customerCollection); @@ -383,23 +371,22 @@ public function testRangeDeleteGetsCustomerCollection() $application = $this->getApplication(); $application->add($this->command); - $command = $this->getApplication()->find('customer:delete'); $commandTester = new CommandTester($command); $command->getHelperSet()->set($this->questionHelper, 'question'); $commandTester->execute( - ['command' => $command->getName(), '--range' => true], + ['command' => $command->getName(), '--range' => true] ); - $this->assertStringContainsString('Aborting delete', $commandTester->getDisplay()); + self::assertStringContainsString('Aborting delete', $commandTester->getDisplay()); } public function testShouldRemoveStopsDeletion() { $this->customerModel - ->expects($this->once()) + ->expects(self::once()) ->method('load') ->with('1') ->willReturn($this->customerModel); @@ -415,37 +402,36 @@ public function testShouldRemoveStopsDeletion() ->willReturn(1); $this->customerModel - ->expects($this->never()) + ->expects(self::never()) ->method('loadByEmail'); $this->questionHelper - ->expects($this->once()) + ->expects(self::once()) ->method('askConfirmation') ->willReturn(false); $this->customerModel - ->expects($this->never()) + ->expects(self::never()) ->method('delete'); $application = $this->getApplication(); $application->add($this->command); - $command = $this->getApplication()->find('customer:delete'); $commandTester = new CommandTester($command); $command->getHelperSet()->set($this->questionHelper, 'question'); $commandTester->execute( - ['command' => $command->getName(), 'id' => '1'], + ['command' => $command->getName(), 'id' => '1'] ); - $this->assertStringContainsString('Aborting delete', $commandTester->getDisplay()); + self::assertStringContainsString('Aborting delete', $commandTester->getDisplay()); } public function testShouldRemovePromptAllowsDeletion() { $this->customerModel - ->expects($this->once()) + ->expects(self::once()) ->method('load') ->with('1') ->willReturn($this->customerModel); @@ -461,52 +447,51 @@ public function testShouldRemovePromptAllowsDeletion() ->willReturn(1); $this->customerModel - ->expects($this->never()) + ->expects(self::never()) ->method('loadByEmail'); $this->questionHelper - ->expects($this->once()) + ->expects(self::once()) ->method('askConfirmation') ->willReturn(true); $this->customerModel - ->expects($this->once()) + ->expects(self::once()) ->method('delete'); $application = $this->getApplication(); $application->add($this->command); - $command = $this->getApplication()->find('customer:delete'); $commandTester = new CommandTester($command); $command->getHelperSet()->set($this->questionHelper, 'question'); $commandTester->execute( - ['command' => $command->getName(), 'id' => '1'], + ['command' => $command->getName(), 'id' => '1'] ); - $this->assertStringContainsString('successfully deleted', $commandTester->getDisplay()); + self::assertStringContainsString('successfully deleted', $commandTester->getDisplay()); } public function testPromptDeleteAllAndDeleteRangeAndAbort() { $this->questionHelper ->expects(self::exactly(3)) - ->method('askConfirmation')->willReturnOnConsecutiveCalls(true, false, false); + ->method('askConfirmation') + ->will(self::onConsecutiveCalls(true, false, false)); $application = $this->getApplication(); $application->add($this->command); - $command = $this->getApplication()->find('customer:delete'); $commandTester = new CommandTester($command); $command->getHelperSet()->set($this->questionHelper, 'question'); $commandTester->execute( - ['command' => $command->getName()], + ['command' => $command->getName()] ); - $this->assertStringContainsString('nothing to do', $commandTester->getDisplay()); + self::assertStringContainsString('nothing to do', $commandTester->getDisplay()); } public function testPromptAllCanDeleteAll() @@ -514,7 +499,7 @@ public function testPromptAllCanDeleteAll() $this->questionHelper ->expects(self::exactly(2)) ->method('askConfirmation') - ->willReturn(true); + ->will(self::onConsecutiveCalls(true, true)); $this->customerCollection ->expects(self::exactly(3)) @@ -522,33 +507,33 @@ public function testPromptAllCanDeleteAll() ->willReturnMap([['firstname', false, $this->customerCollection], ['lastname', false, $this->customerCollection], ['email', false, $this->customerCollection]]); $this->command - ->expects($this->once()) + ->expects(self::once()) ->method('batchDelete') ->with($this->customerCollection) ->willReturn(3); $application = $this->getApplication(); $application->add($this->command); - $command = $this->getApplication()->find('customer:delete'); $command->getHelperSet()->set($this->questionHelper, 'question'); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), '--force' => true], + ['command' => $command->getName(), '--force' => true] ); - $this->assertStringContainsString('Successfully deleted 3 customer/s', $commandTester->getDisplay()); + self::assertStringContainsString('Successfully deleted 3 customer/s', $commandTester->getDisplay()); } public function testPromptRangeCanDeleteRange() { $this->questionHelper ->expects(self::exactly(3)) - ->method('askConfirmation')->willReturnOnConsecutiveCalls(true, false, true); + ->method('askConfirmation') + ->will(self::onConsecutiveCalls(true, false, true)); $this->customerCollection - ->expects($this->atLeastOnce()) + ->expects(self::atLeastOnce()) ->method('addAttributeToSelect') ->willReturnMap([['firstname', false, $this->customerCollection], ['lastname', false, $this->customerCollection], ['email', false, $this->customerCollection]]); @@ -567,67 +552,68 @@ public function testPromptRangeCanDeleteRange() ->willReturn('10'); $this->customerCollection - ->expects($this->once()) - ->method('addAttributeToFilter')->willReturnSelf(); + ->expects(self::once()) + ->method('addAttributeToFilter') + ->will(self::returnSelf()); $this->command - ->expects($this->once()) + ->expects(self::once()) ->method('batchDelete') ->with($this->customerCollection) ->willReturn(3); $application = $this->getApplication(); $application->add($this->command); - $command = $this->getApplication()->find('customer:delete'); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), '--force' => true], + ['command' => $command->getName(), '--force' => true] ); - $this->assertStringContainsString('Successfully deleted 3 customer/s', $commandTester->getDisplay()); + self::assertStringContainsString('Successfully deleted 3 customer/s', $commandTester->getDisplay()); } public function testBatchDelete() { - $mock = $this->getMockBuilder(DeleteCommand::class) + $command = $this->getMockBuilder(DeleteCommand::class) ->setMethods(['deleteCustomer']) ->disableOriginalConstructor() ->getMock(); - $mock + $command ->expects(self::exactly(2)) - ->method('deleteCustomer')->willReturnOnConsecutiveCalls(true, new Exception('Failed to delete')); + ->method('deleteCustomer') + ->will(self::onConsecutiveCalls(true, new Exception('Failed to delete'))); - $reflectionObject = new ReflectionObject($mock); - $reflectionMethod = $reflectionObject->getMethod('batchDelete'); - $reflectionMethod->setAccessible(true); + $refObject = new ReflectionObject($command); + $method = $refObject->getMethod('batchDelete'); + $method->setAccessible(true); $data = new ArrayIterator([$this->customerModel, $this->customerModel]); $collection = $this->getCustomerCollection(['getIterator']); $collection - ->expects($this->once()) + ->expects(self::once()) ->method('getIterator') ->willReturn($data); - $result = $reflectionMethod->invokeArgs($mock, [$collection]); + $result = $method->invokeArgs($command, [$collection]); - $this->assertSame(1, $result); + self::assertEquals(1, $result); } public function testValidateInt() { $this->expectException(RuntimeException::class); $this->expectExceptionMessage('The range should be numeric and above 0 e.g. 1'); - $reflectionObject = new ReflectionObject($this->command); - $reflectionMethod = $reflectionObject->getMethod('validateInt'); - $reflectionMethod->setAccessible(true); + $refObject = new ReflectionObject($this->command); + $method = $refObject->getMethod('validateInt'); + $method->setAccessible(true); - $resultValid = $reflectionMethod->invokeArgs($this->command, ['5']); - $this->assertSame(5, $resultValid); - $reflectionMethod->invokeArgs($this->command, ['bad input']); // Exception! + $resultValid = $method->invokeArgs($this->command, ['5']); + self::assertEquals(5, $resultValid); + $method->invokeArgs($this->command, ['bad input']); // Exception! } } diff --git a/tests/N98/Magento/Command/Customer/ListCommandTest.php b/tests/N98/Magento/Command/Customer/ListCommandTest.php index a2593703a..a6f995944 100644 --- a/tests/N98/Magento/Command/Customer/ListCommandTest.php +++ b/tests/N98/Magento/Command/Customer/ListCommandTest.php @@ -1,24 +1,21 @@ getApplication(); $application->add(new ListCommand()); - $command = $this->getApplication()->find('customer:list'); $commandTester = new CommandTester($command); $commandTester->execute(['command' => $command->getName()]); - $this->assertMatchesRegularExpression('/email/', $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/email/', $commandTester->getDisplay()); } } diff --git a/tests/N98/Magento/Command/Database/DumpCommandTest.php b/tests/N98/Magento/Command/Database/DumpCommandTest.php index 1fe9e3271..b30d6c7fc 100644 --- a/tests/N98/Magento/Command/Database/DumpCommandTest.php +++ b/tests/N98/Magento/Command/Database/DumpCommandTest.php @@ -1,7 +1,5 @@ isEnabled()) { @@ -27,8 +25,9 @@ private function getCommand() $application = $this->getApplication(); $application->add($dumpCommand); + $command = $this->getApplication()->find('db:dump'); - return $this->getApplication()->find('db:dump'); + return $command; } public function testExecute() @@ -37,42 +36,46 @@ public function testExecute() $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), '--add-time' => true, '--only-command' => true, '--force' => true, '--compression' => 'gz'], + ['command' => $command->getName(), '--add-time' => true, '--only-command' => true, '--force' => true, '--compression' => 'gz'] ); - $this->assertMatchesRegularExpression('/mysqldump/', $commandTester->getDisplay()); - $this->assertMatchesRegularExpression('/\.sql/', $commandTester->getDisplay()); - $this->assertStringContainsString('.sql.gz', $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/mysqldump/', $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/\.sql/', $commandTester->getDisplay()); + self::assertStringContainsString('.sql.gz', $commandTester->getDisplay()); } /** * @see filenamePatterns */ - public function provideFilenamePatternsAndOptions(): \Iterator + public function provideFilenamePatternsAndOptions() { - # testAddTimeAutogenerated - yield ['/^.*\d{4}-\d{2}-\d{2}_\d{6}\.sql$/', []]; - # testAddTimePrefixAutogenerated - yield ['/^\d{4}-\d{2}-\d{2}_\d{6}.*\.sql$/', ['--add-time' => 'prefix']]; - # testAddTimeFilenameSpecified - yield ['/^.*\d{4}-\d{2}-\d{2}_\d{6}\.sql.gz$/', ['--compression' => 'gzip']]; - # testAddTimeFilenameSpecified - yield ['/^foo_\d{4}-\d{2}-\d{2}_\d{6}\.sql$/', ['filename' => 'foo.sql']]; - # testAddTimePrefixFilenameSpecified - yield ['/^\d{4}-\d{2}-\d{2}_\d{6}_foo\.sql$/', ['filename' => 'foo.sql', '--add-time' => 'prefix']]; - # testAddTimeOffFilenameSpecified - yield ['/^foo.sql$/', ['filename' => 'foo.sql', '--add-time' => 'no']]; - # testAddTimeFilenameSpecifiedRelative - yield ['/^..\/foo_\d{4}-\d{2}-\d{2}_\d{6}\.sql$/', ['filename' => '../foo.sql']]; + return [ + # testAddTimeAutogenerated + ['/^.*[0-9]{4}-[0-9]{2}-[0-9]{2}_[0-9]{6}\.sql$/', []], + # testAddTimePrefixAutogenerated + ['/^[0-9]{4}-[0-9]{2}-[0-9]{2}_[0-9]{6}.*\.sql$/', ['--add-time' => 'prefix']], + # testAddTimeFilenameSpecified + ['/^.*[0-9]{4}-[0-9]{2}-[0-9]{2}_[0-9]{6}\.sql.gz$/', ['--compression' => 'gzip']], + # testAddTimeFilenameSpecified + ['/^foo_[0-9]{4}-[0-9]{2}-[0-9]{2}_[0-9]{6}\.sql$/', ['filename' => 'foo.sql']], + # testAddTimePrefixFilenameSpecified + ['/^[0-9]{4}-[0-9]{2}-[0-9]{2}_[0-9]{6}_foo\.sql$/', ['filename' => 'foo.sql', '--add-time' => 'prefix']], + # testAddTimeOffFilenameSpecified + ['/^foo.sql$/', ['filename' => 'foo.sql', '--add-time' => 'no']], + # testAddTimeFilenameSpecifiedRelative + ['/^..\/foo_[0-9]{4}-[0-9]{2}-[0-9]{2}_[0-9]{6}\.sql$/', ['filename' => '../foo.sql']], + ]; } /** + * @test * @dataProvider provideFilenamePatternsAndOptions * * @param string $regex + * @param array $options * @return void */ - public function testFilenamePatterns($regex, array $options) + public function filenamePatterns($regex, array $options) { $command = $this->getCommand(); @@ -91,28 +94,28 @@ public function testWithStripOption() $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), '--add-time' => true, '--only-command' => true, '--force' => true, '--strip' => '@development not_existing_table_1', '--compression' => 'gzip'], + ['command' => $command->getName(), '--add-time' => true, '--only-command' => true, '--force' => true, '--strip' => '@development not_existing_table_1', '--compression' => 'gzip'] ); $dbConfig = $this->getDatabaseConnection()->getConfig(); $db = $dbConfig['dbname']; - $this->assertMatchesRegularExpression(sprintf('/--ignore-table=%s.customer_entity/', $db), $commandTester->getDisplay()); - $this->assertMatchesRegularExpression(sprintf('/--ignore-table=%s.customer_address_entity/', $db), $commandTester->getDisplay()); - $this->assertMatchesRegularExpression(sprintf('/--ignore-table=%s.sales_flat_order/', $db), $commandTester->getDisplay()); - $this->assertMatchesRegularExpression(sprintf('/--ignore-table=%s.sales_flat_order_item/', $db), $commandTester->getDisplay()); - $this->assertMatchesRegularExpression(sprintf('/--ignore-table=%s.sales_flat_order_item/', $db), $commandTester->getDisplay()); - $this->assertStringNotContainsString('not_existing_table_1', $commandTester->getDisplay()); - $this->assertStringContainsString('.sql.gz', $commandTester->getDisplay()); + self::assertMatchesRegularExpression("/--ignore-table=$db.customer_entity/", $commandTester->getDisplay()); + self::assertMatchesRegularExpression("/--ignore-table=$db.customer_address_entity/", $commandTester->getDisplay()); + self::assertMatchesRegularExpression("/--ignore-table=$db.sales_flat_order/", $commandTester->getDisplay()); + self::assertMatchesRegularExpression("/--ignore-table=$db.sales_flat_order_item/", $commandTester->getDisplay()); + self::assertMatchesRegularExpression("/--ignore-table=$db.sales_flat_order_item/", $commandTester->getDisplay()); + self::assertStringNotContainsString('not_existing_table_1', $commandTester->getDisplay()); + self::assertStringContainsString('.sql.gz', $commandTester->getDisplay()); /** * Uncompressed */ $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), '--add-time' => true, '--only-command' => true, '--force' => true, '--strip' => '@development'], + ['command' => $command->getName(), '--add-time' => true, '--only-command' => true, '--force' => true, '--strip' => '@development'] ); - $this->assertStringNotContainsString('.sql.gz', $commandTester->getDisplay()); + self::assertStringNotContainsString('.sql.gz', $commandTester->getDisplay()); } public function testWithIncludeExcludeOptions() @@ -127,19 +130,19 @@ public function testWithIncludeExcludeOptions() */ $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), '--add-time' => true, '--only-command' => true, '--force' => true, '--exclude' => 'core_config_data', '--compression' => 'gzip'], + ['command' => $command->getName(), '--add-time' => true, '--only-command' => true, '--force' => true, '--exclude' => 'core_config_data', '--compression' => 'gzip'] ); - $this->assertMatchesRegularExpression(sprintf('/--ignore-table=%s\.core_config_data/', $db), $commandTester->getDisplay()); + self::assertMatchesRegularExpression("/--ignore-table=$db\.core_config_data/", $commandTester->getDisplay()); /** * Include */ $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), '--add-time' => true, '--only-command' => true, '--force' => true, '--include' => 'core_config_data', '--compression' => 'gzip'], + ['command' => $command->getName(), '--add-time' => true, '--only-command' => true, '--force' => true, '--include' => 'core_config_data', '--compression' => 'gzip'] ); - $this->assertDoesNotMatchRegularExpression(sprintf('/--ignore-table=%s\.core_config_data/', $db), $commandTester->getDisplay()); - $this->assertMatchesRegularExpression(sprintf('/--ignore-table=%s\.catalog_product_entity/', $db), $commandTester->getDisplay()); + self::assertDoesNotMatchRegularExpression("/--ignore-table=$db\.core_config_data/", $commandTester->getDisplay()); + self::assertMatchesRegularExpression("/--ignore-table=$db\.catalog_product_entity/", $commandTester->getDisplay()); } public function testIncludeExcludeMutualExclusivity() @@ -153,30 +156,30 @@ public function testIncludeExcludeMutualExclusivity() $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), '--add-time' => true, '--only-command' => true, '--force' => true, '--include' => 'core_config_data', '--exclude' => 'catalog_product_entity', '--compression' => 'gzip'], + ['command' => $command->getName(), '--add-time' => true, '--only-command' => true, '--force' => true, '--include' => 'core_config_data', '--exclude' => 'catalog_product_entity', '--compression' => 'gzip'] ); } /** + * @test * @link https://github.com/netz98/n98-magerun2/issues/200 */ - public function testRealDump() + public function realDump() { $dumpFile = new SplFileInfo($this->getTestMagentoRoot() . '/test-dump.sql'); if ($dumpFile->isReadable()) { - $this->assertTrue(unlink($dumpFile), 'Precondition to unlink that the file does not exists'); + self::assertTrue(unlink($dumpFile), 'Precondition to unlink that the file does not exists'); } - - $this->assertIsNotReadable((string) $dumpFile, 'Precondition that the file does not exists'); + self::assertIsNotReadable((string)$dumpFile, 'Precondition that the file does not exists'); $command = $this->getCommand(); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), '--strip' => '@stripped', 'filename' => $dumpFile], + ['command' => $command->getName(), '--strip' => '@stripped', 'filename' => $dumpFile] ); - $this->assertTrue($dumpFile->isReadable(), 'File was created'); + self::assertTrue($dumpFile->isReadable(), 'File was created'); // dump should be larger than quarter a megabyte - $this->assertGreaterThan(250000, $dumpFile->getSize()); + self::assertGreaterThan(250000, $dumpFile->getSize()); } } diff --git a/tests/N98/Magento/Command/Database/InfoCommandTest.php b/tests/N98/Magento/Command/Database/InfoCommandTest.php index cf6945742..8e9aeb45a 100644 --- a/tests/N98/Magento/Command/Database/InfoCommandTest.php +++ b/tests/N98/Magento/Command/Database/InfoCommandTest.php @@ -1,40 +1,36 @@ getApplication(); $application->add(new InfoCommand()); - $command = $this->getApplication()->find('db:info'); $commandTester = new CommandTester($command); $commandTester->execute(['command' => $command->getName()]); - $this->assertMatchesRegularExpression('/PDO-Connection-String/', $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/PDO-Connection-String/', $commandTester->getDisplay()); } public function testExecuteWithSettingArgument() { $application = $this->getApplication(); $application->add(new InfoCommand()); - $command = $this->getApplication()->find('db:info'); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), 'setting' => 'MySQL-Cli-String'], + ['command' => $command->getName(), 'setting' => 'MySQL-Cli-String'] ); - $this->assertDoesNotMatchRegularExpression('/MySQL-Cli-String/', $commandTester->getDisplay()); - $this->assertStringContainsString('mysql -h', $commandTester->getDisplay()); + self::assertDoesNotMatchRegularExpression('/MySQL-Cli-String/', $commandTester->getDisplay()); + self::assertStringContainsString('mysql -h', $commandTester->getDisplay()); } } diff --git a/tests/N98/Magento/Command/Database/Maintain/CheckTablesCommandTest.php b/tests/N98/Magento/Command/Database/Maintain/CheckTablesCommandTest.php index 7d3261eef..25e9ced50 100644 --- a/tests/N98/Magento/Command/Database/Maintain/CheckTablesCommandTest.php +++ b/tests/N98/Magento/Command/Database/Maintain/CheckTablesCommandTest.php @@ -1,7 +1,5 @@ execute( - ['command' => $command->getName(), '--format' => 'csv', '--type' => 'quick', '--table' => 'catalogsearch_*'], + ['command' => $command->getName(), '--format' => 'csv', '--type' => 'quick', '--table' => 'catalogsearch_*'] ); - $this->assertStringContainsString('catalogsearch_fulltext,check,quick,OK', $commandTester->getDisplay()); + self::assertStringContainsString('catalogsearch_fulltext,check,quick,OK', $commandTester->getDisplay()); $timeRegex = '"\s+[0-9]+\srows","[0-9\.]+\ssecs"'; - $this->assertMatchesRegularExpression('~catalogsearch_query,"ENGINE InnoDB",' . $timeRegex . '~', $commandTester->getDisplay()); - $this->assertMatchesRegularExpression('~catalogsearch_result,"ENGINE InnoDB",' . $timeRegex . '~', $commandTester->getDisplay()); + self::assertMatchesRegularExpression( + '~catalogsearch_query,"ENGINE InnoDB",' . $timeRegex . '~', + $commandTester->getDisplay() + ); + self::assertMatchesRegularExpression( + '~catalogsearch_result,"ENGINE InnoDB",' . $timeRegex . '~', + $commandTester->getDisplay() + ); } /** * @return Command */ - private function getCommand() + protected function getCommand() { $application = $this->getApplication(); $application->add(new CheckTablesCommand()); + $command = $this->getApplication()->find('db:maintain:check-tables'); - return $this->getApplication()->find('db:maintain:check-tables'); + return $command; } } diff --git a/tests/N98/Magento/Command/Database/QueryCommandTest.php b/tests/N98/Magento/Command/Database/QueryCommandTest.php index 42cb19517..5260fd219 100644 --- a/tests/N98/Magento/Command/Database/QueryCommandTest.php +++ b/tests/N98/Magento/Command/Database/QueryCommandTest.php @@ -1,28 +1,25 @@ getApplication(); $application->add(new QueryCommand()); - $command = $this->getApplication()->find('db:query'); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), 'query' => 'SHOW TABLES;'], + ['command' => $command->getName(), 'query' => 'SHOW TABLES;'] ); - $this->assertStringContainsString('admin_user', $commandTester->getDisplay()); - $this->assertStringContainsString('catalog_product_entity', $commandTester->getDisplay()); - $this->assertStringContainsString('wishlist', $commandTester->getDisplay()); + self::assertStringContainsString('admin_user', $commandTester->getDisplay()); + self::assertStringContainsString('catalog_product_entity', $commandTester->getDisplay()); + self::assertStringContainsString('wishlist', $commandTester->getDisplay()); } } diff --git a/tests/N98/Magento/Command/Database/StatusCommandTest.php b/tests/N98/Magento/Command/Database/StatusCommandTest.php index 488780902..4204c1a1d 100644 --- a/tests/N98/Magento/Command/Database/StatusCommandTest.php +++ b/tests/N98/Magento/Command/Database/StatusCommandTest.php @@ -1,27 +1,26 @@ getApplication(); $application->add(new StatusCommand()); - $command = $this->getApplication()->find('db:status'); $commandTester = new CommandTester($command); $commandTester->execute( - array_merge(['command' => $command->getName()], $options), + array_merge(['command' => $command->getName()], $options) ); return $commandTester; } @@ -31,10 +30,10 @@ public function testExecute() $commandTester = $this->getCommand(['--format' => 'csv']); $display = $commandTester->getDisplay(); - $this->assertStringContainsString('Threads_connected', $display); - $this->assertStringContainsString('Innodb_buffer_pool_wait_free', $display); - $this->assertStringContainsString('InnoDB Buffer Pool hit', $display); - $this->assertStringContainsString('Full table scans', $display); + self::assertStringContainsString('Threads_connected', $display); + self::assertStringContainsString('Innodb_buffer_pool_wait_free', $display); + self::assertStringContainsString('InnoDB Buffer Pool hit', $display); + self::assertStringContainsString('Full table scans', $display); } public function testSearch() @@ -43,16 +42,19 @@ public function testSearch() $display = $commandTester->getDisplay(); - $this->assertStringContainsString('Innodb_buffer_pool_read_ahead_rnd', $display); - $this->assertStringContainsString('Innodb_buffer_pool_wait_free', $display); - $this->assertStringContainsString('InnoDB Buffer Pool hit', $display); - $this->assertStringContainsString('Innodb_dblwr_pages_written', $display); - $this->assertStringContainsString('Innodb_os_log_written', $display); + self::assertStringContainsString('Innodb_buffer_pool_read_ahead_rnd', $display); + self::assertStringContainsString('Innodb_buffer_pool_wait_free', $display); + self::assertStringContainsString('InnoDB Buffer Pool hit', $display); + self::assertStringContainsString('Innodb_dblwr_pages_written', $display); + self::assertStringContainsString('Innodb_os_log_written', $display); } public function testRounding() { $commandTester = $this->getCommand(['--format' => 'csv', '--rounding' => '2', 'search' => '%size%']); - $this->assertMatchesRegularExpression('~Innodb_page_size,[0-9\.]+K,~', $commandTester->getDisplay()); + self::assertMatchesRegularExpression( + '~Innodb_page_size,[0-9\.]+K,~', + $commandTester->getDisplay() + ); } } diff --git a/tests/N98/Magento/Command/Database/VariablesCommandTest.php b/tests/N98/Magento/Command/Database/VariablesCommandTest.php index 83d6878bb..65caba25d 100644 --- a/tests/N98/Magento/Command/Database/VariablesCommandTest.php +++ b/tests/N98/Magento/Command/Database/VariablesCommandTest.php @@ -1,14 +1,12 @@ statusCommand = new StatusCommand(); $application = $this->getApplication(); $application->add($this->statusCommand); - $command = $this->getApplication()->find('db:variables'); $commandTester = new CommandTester($command); $commandTester->execute( - array_merge(['command' => $command->getName()], $options), + array_merge(['command' => $command->getName()], $options) ); return $commandTester; @@ -48,10 +47,10 @@ public function testExecute() $commandTester = $this->getCommand(['--format' => 'csv']); $display = $commandTester->getDisplay(); - $this->assertStringContainsString('have_query_cache', $display); - $this->assertStringContainsString('innodb_log_buffer_size', $display); - $this->assertStringContainsString('max_connections', $display); - $this->assertStringContainsString('thread_cache_size', $display); + self::assertStringContainsString('have_query_cache', $display); + self::assertStringContainsString('innodb_log_buffer_size', $display); + self::assertStringContainsString('max_connections', $display); + self::assertStringContainsString('thread_cache_size', $display); } /** @@ -61,18 +60,17 @@ public function testSearch() { $commandTester = $this->getCommand(['--format' => 'csv', 'search' => 'Innodb%']); - $databaseHelper = $this->getDatabaseHelper(); + $dbHelper = $this->getDatabaseHelper(); $display = $commandTester->getDisplay(); - $this->assertStringContainsString('innodb_concurrency_tickets', $display); + self::assertStringContainsString('innodb_concurrency_tickets', $display); // innodb_force_load_corrupted Introduced in 5.6.3 - if (-1 < version_compare($databaseHelper->getMysqlVariable('version'), '5.6.3')) { - $this->assertStringContainsString('innodb_force_load_corrupted', $display); + if (-1 < version_compare($dbHelper->getMysqlVariable('version'), '5.6.3')) { + self::assertStringContainsString('innodb_force_load_corrupted', $display); } - - $this->assertStringContainsString('innodb_log_file_size', $display); - $this->assertMatchesRegularExpression('~innodb_(?:file|read)_io_threads~', $display); + self::assertStringContainsString('innodb_log_file_size', $display); + self::assertMatchesRegularExpression('~innodb_(?:file|read)_io_threads~', $display); } /** @@ -82,15 +80,15 @@ public function testRounding() { $commandTester = $this->getCommand(['--format' => 'csv', '--rounding' => '2', 'search' => '%size%']); - $databaseHelper = $this->getDatabaseHelper(); + $dbHelper = $this->getDatabaseHelper(); $display = $commandTester->getDisplay(); - $this->assertMatchesRegularExpression('~myisam_max_sort_file_size,[0-9\.]+[A-Z]~', $commandTester->getDisplay()); + self::assertMatchesRegularExpression('~myisam_max_sort_file_size,[0-9\.]+[A-Z]~', $commandTester->getDisplay()); // max_binlog_stmt_cache_size Introduced in 5.5.9 - if (-1 < version_compare($databaseHelper->getMysqlVariable('version'), '5.5.9')) { - $this->assertMatchesRegularExpression('~max_binlog_stmt_cache_size,[0-9\.]+[A-Z]~', $display); + if (-1 < version_compare($dbHelper->getMysqlVariable('version'), '5.5.9')) { + self::assertMatchesRegularExpression('~max_binlog_stmt_cache_size,[0-9\.]+[A-Z]~', $display); } } } diff --git a/tests/N98/Magento/Command/Design/DemoNoticeCommandTest.php b/tests/N98/Magento/Command/Design/DemoNoticeCommandTest.php index 629e04fa9..a43a362d4 100644 --- a/tests/N98/Magento/Command/Design/DemoNoticeCommandTest.php +++ b/tests/N98/Magento/Command/Design/DemoNoticeCommandTest.php @@ -1,33 +1,30 @@ getApplication(); $application->add(new DemoNoticeCommand()); $application->setAutoExit(false); - $command = $this->getApplication()->find('design:demo-notice'); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), 'store' => 'admin', '--on' => true], + ['command' => $command->getName(), 'store' => 'admin', '--on' => true] ); - $this->assertMatchesRegularExpression('/Demo Notice enabled/', $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/Demo Notice enabled/', $commandTester->getDisplay()); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), 'store' => 'admin', '--off' => true], + ['command' => $command->getName(), 'store' => 'admin', '--off' => true] ); - $this->assertMatchesRegularExpression('/Demo Notice disabled/', $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/Demo Notice disabled/', $commandTester->getDisplay()); } } diff --git a/tests/N98/Magento/Command/Developer/ClassLookupCommandTest.php b/tests/N98/Magento/Command/Developer/ClassLookupCommandTest.php index 736cea5c3..25e936fd6 100644 --- a/tests/N98/Magento/Command/Developer/ClassLookupCommandTest.php +++ b/tests/N98/Magento/Command/Developer/ClassLookupCommandTest.php @@ -1,13 +1,11 @@ getApplication(); $application->add(new ClassLookupCommand()); - $command = $this->getApplication()->find('dev:class:lookup'); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), 'type' => $type, 'name' => $name], + ['command' => $command->getName(), 'type' => $type, 'name' => $name] ); $output = $commandTester->getDisplay(); - $this->assertMatchesRegularExpression(sprintf('/%s/', $expected), $output); + self::assertMatchesRegularExpression(sprintf('/%s/', $expected), $output); - $existsAssertion = ($exists) ? 'assertDoesNotMatchRegularExpression' : 'assertMatchesRegularExpression'; + $existsAssertion = (!$exists) ? 'assertMatchesRegularExpression' : 'assertDoesNotMatchRegularExpression'; $this->{$existsAssertion}(sprintf('/%s/', 'does not exist'), $output); } @@ -42,13 +39,8 @@ public function testExecute($type, $name, $expected, $exists) * Provide data for the class lookup testExecute() * @return array */ - public function classLookupProvider(): \Iterator + public function classLookupProvider() { - yield ['type' => 'model', 'name' => 'catalog/product', 'expected' => 'Mage_Catalog_Model_Product', 'exists' => true]; - yield ['type' => 'model', 'name' => 'catalog/nothing_to_see_here', 'expected' => 'Mage_Catalog_Model_Nothing_To_See_Here', 'exists' => false]; - yield ['type' => 'helper', 'name' => 'checkout/cart', 'expected' => 'Mage_Checkout_Helper_Cart', 'exists' => true]; - yield ['type' => 'helper', 'name' => 'checkout/stolen_creditcards', 'expected' => 'Mage_Checkout_Helper_Stolen_Creditcards', 'exists' => false]; - yield ['type' => 'block', 'name' => 'customer/account_dashboard', 'expected' => 'Mage_Customer_Block_Account_Dashboard', 'exists' => true]; - yield ['type' => 'block', 'name' => 'customer/my_code_snippets', 'expected' => 'Mage_Customer_Block_My_Code_Snippets', 'exists' => false]; + return [['type' => 'model', 'name' => 'catalog/product', 'expected' => 'Mage_Catalog_Model_Product', 'exists' => true], ['type' => 'model', 'name' => 'catalog/nothing_to_see_here', 'expected' => 'Mage_Catalog_Model_Nothing_To_See_Here', 'exists' => false], ['type' => 'helper', 'name' => 'checkout/cart', 'expected' => 'Mage_Checkout_Helper_Cart', 'exists' => true], ['type' => 'helper', 'name' => 'checkout/stolen_creditcards', 'expected' => 'Mage_Checkout_Helper_Stolen_Creditcards', 'exists' => false], ['type' => 'block', 'name' => 'customer/account_dashboard', 'expected' => 'Mage_Customer_Block_Account_Dashboard', 'exists' => true], ['type' => 'block', 'name' => 'customer/my_code_snippets', 'expected' => 'Mage_Customer_Block_My_Code_Snippets', 'exists' => false]]; } } diff --git a/tests/N98/Magento/Command/Developer/Ide/PhpStorm/MetaCommandTest.php b/tests/N98/Magento/Command/Developer/Ide/PhpStorm/MetaCommandTest.php index 8a0fc404d..e2dc21dd1 100644 --- a/tests/N98/Magento/Command/Developer/Ide/PhpStorm/MetaCommandTest.php +++ b/tests/N98/Magento/Command/Developer/Ide/PhpStorm/MetaCommandTest.php @@ -1,41 +1,41 @@ getApplication(); $application->add(new MetaCommand()); - $command = $this->getApplication()->find('dev:ide:phpstorm:meta'); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), '--stdout' => true], + ['command' => $command->getName(), '--stdout' => true] ); $fileContent = $commandTester->getDisplay(true); - $this->assertStringContainsString('\'catalog\' => \Mage_Catalog_Helper_Data', $fileContent); - $this->assertStringContainsString('\'core/config\' => \Mage_Core_Model_Config', $fileContent); + self::assertStringContainsString('\'catalog\' => \Mage_Catalog_Helper_Data', $fileContent); + self::assertStringContainsString('\'core/config\' => \Mage_Core_Model_Config', $fileContent); if (class_exists('\Mage_Core_Model_Resource_Config')) { // since magento 1.7 - $this->assertStringContainsString('\'core/config\' => \Mage_Core_Model_Resource_Config', $fileContent); + self::assertStringContainsString('\'core/config\' => \Mage_Core_Model_Resource_Config', $fileContent); } - $this->assertStringContainsString('\'wishlist\' => \Mage_Wishlist_Helper_Data', $fileContent); + self::assertStringContainsString('\'wishlist\' => \Mage_Wishlist_Helper_Data', $fileContent); if (class_exists('\Mage_Core_Model_Resource_Helper_Mysql4')) { - $this->assertStringContainsString('\'core\' => \Mage_Core_Model_Resource_Helper_Mysql4', $fileContent); + self::assertStringContainsString('\'core\' => \Mage_Core_Model_Resource_Helper_Mysql4', $fileContent); } - $this->assertStringNotContainsString('\'payment/paygate_request\' => \Mage_Payment_Model_Paygate_Request', $fileContent); + self::assertStringNotContainsString( + '\'payment/paygate_request\' => \Mage_Payment_Model_Paygate_Request', + $fileContent + ); } } diff --git a/tests/N98/Magento/Command/Developer/Log/LogCommand.php b/tests/N98/Magento/Command/Developer/Log/LogCommand.php index 2d96d114d..c46cd7e74 100644 --- a/tests/N98/Magento/Command/Developer/Log/LogCommand.php +++ b/tests/N98/Magento/Command/Developer/Log/LogCommand.php @@ -1,7 +1,5 @@ getApplication(); $application->add(new LogCommand()); $application->setAutoExit(false); - $command = $this->getApplication()->find('dev:log'); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), '--global' => true, '--on' => true], + ['command' => $command->getName(), '--global' => true, '--on' => true] ); self::assertMatchesRegularExpression('/Development Log/', $commandTester->getDisplay()); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), '--global' => true, '--off' => true], + ['command' => $command->getName(), '--global' => true, '--off' => true] ); self::assertMatchesRegularExpression('/Development Log/', $commandTester->getDisplay()); diff --git a/tests/N98/Magento/Command/Developer/MergeCssCommandTest.php b/tests/N98/Magento/Command/Developer/MergeCssCommandTest.php index 9db57a0fa..fd8842e28 100644 --- a/tests/N98/Magento/Command/Developer/MergeCssCommandTest.php +++ b/tests/N98/Magento/Command/Developer/MergeCssCommandTest.php @@ -1,33 +1,30 @@ getApplication(); $application->add(new MergeCssCommand()); $application->setAutoExit(false); - $command = $this->getApplication()->find('dev:merge-css'); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), '--on' => true, 'store' => 'admin'], + ['command' => $command->getName(), '--on' => true, 'store' => 'admin'] ); - $this->assertMatchesRegularExpression('/CSS Merging enabled/', $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/CSS Merging enabled/', $commandTester->getDisplay()); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), '--off' => true, 'store' => 'admin'], + ['command' => $command->getName(), '--off' => true, 'store' => 'admin'] ); - $this->assertMatchesRegularExpression('/CSS Merging disabled/', $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/CSS Merging disabled/', $commandTester->getDisplay()); } } diff --git a/tests/N98/Magento/Command/Developer/MergeJsCommandTest.php b/tests/N98/Magento/Command/Developer/MergeJsCommandTest.php index 87add7a47..a7ab4d160 100644 --- a/tests/N98/Magento/Command/Developer/MergeJsCommandTest.php +++ b/tests/N98/Magento/Command/Developer/MergeJsCommandTest.php @@ -1,33 +1,30 @@ getApplication(); $application->add(new MergeJsCommand()); $application->setAutoExit(false); - $command = $this->getApplication()->find('dev:merge-js'); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), '--on' => true, 'store' => 'admin'], + ['command' => $command->getName(), '--on' => true, 'store' => 'admin'] ); - $this->assertMatchesRegularExpression('/JS Merging enabled/', $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/JS Merging enabled/', $commandTester->getDisplay()); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), '--off' => true, 'store' => 'admin'], + ['command' => $command->getName(), '--off' => true, 'store' => 'admin'] ); - $this->assertMatchesRegularExpression('/JS Merging disabled/', $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/JS Merging disabled/', $commandTester->getDisplay()); } } diff --git a/tests/N98/Magento/Command/Developer/Module/CreateCommandTest.php b/tests/N98/Magento/Command/Developer/Module/CreateCommandTest.php index 3eb6d2170..f9199ffcb 100644 --- a/tests/N98/Magento/Command/Developer/Module/CreateCommandTest.php +++ b/tests/N98/Magento/Command/Developer/Module/CreateCommandTest.php @@ -1,20 +1,17 @@ getApplication(); $application->add(new ListCommand()); - $command = $this->getApplication()->find('dev:module:create'); $root = getcwd(); @@ -28,19 +25,19 @@ public function testExecute() $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), '--add-all' => true, '--add-setup' => true, '--add-readme' => true, '--add-composer' => true, '--modman' => true, '--description' => 'Unit Test Description', '--author-name' => 'Unit Test', '--author-email' => 'n98-magerun@example.com', 'vendorNamespace' => 'N98Magerun', 'moduleName' => 'UnitTest'], + ['command' => $command->getName(), '--add-all' => true, '--add-setup' => true, '--add-readme' => true, '--add-composer' => true, '--modman' => true, '--description' => 'Unit Test Description', '--author-name' => 'Unit Test', '--author-email' => 'n98-magerun@example.com', 'vendorNamespace' => 'N98Magerun', 'moduleName' => 'UnitTest'] ); - $this->assertFileExists($root . '/N98Magerun_UnitTest/composer.json'); - $this->assertFileExists($root . '/N98Magerun_UnitTest/readme.md'); + self::assertFileExists($root . '/N98Magerun_UnitTest/composer.json'); + self::assertFileExists($root . '/N98Magerun_UnitTest/readme.md'); $moduleBaseFolder = $root . '/N98Magerun_UnitTest/src/app/code/local/N98Magerun/UnitTest/'; - $this->assertFileExists($moduleBaseFolder . 'etc/config.xml'); - $this->assertFileExists($moduleBaseFolder . 'controllers'); - $this->assertFileExists($moduleBaseFolder . 'Block'); - $this->assertFileExists($moduleBaseFolder . 'Model'); - $this->assertFileExists($moduleBaseFolder . 'Helper'); - $this->assertFileExists($moduleBaseFolder . 'data/n98magerun_unittest_setup'); - $this->assertFileExists($moduleBaseFolder . 'sql/n98magerun_unittest_setup'); + self::assertFileExists($moduleBaseFolder . 'etc/config.xml'); + self::assertFileExists($moduleBaseFolder . 'controllers'); + self::assertFileExists($moduleBaseFolder . 'Block'); + self::assertFileExists($moduleBaseFolder . 'Model'); + self::assertFileExists($moduleBaseFolder . 'Helper'); + self::assertFileExists($moduleBaseFolder . 'data/n98magerun_unittest_setup'); + self::assertFileExists($moduleBaseFolder . 'sql/n98magerun_unittest_setup'); // delete old module if (is_dir($root . '/N98Magerun_UnitTest')) { diff --git a/tests/N98/Magento/Command/Developer/Module/Dependencies/FromCommandTest.php b/tests/N98/Magento/Command/Developer/Module/Dependencies/FromCommandTest.php index 92bb3b4db..36788a55e 100644 --- a/tests/N98/Magento/Command/Developer/Module/Dependencies/FromCommandTest.php +++ b/tests/N98/Magento/Command/Developer/Module/Dependencies/FromCommandTest.php @@ -1,7 +1,5 @@ ['$moduleName' => 'NotExistentModule', '$all' => 0, '$expectations' => ['Module NotExistentModule was not found'], '$notContains' => []]; - yield 'Not existing module, with --all' => ['$moduleName' => 'NotExistentModule', '$all' => 1, '$expectations' => ['Module NotExistentModule was not found'], '$notContains' => []]; - yield 'Not existing module, with -a' => ['$moduleName' => 'NotExistentModule', '$all' => 2, '$expectations' => ['Module NotExistentModule was not found'], '$notContains' => []]; - yield 'Mage_Admin module, no --all' => ['$moduleName' => 'Mage_Admin', '$all' => 0, '$expectations' => ['Mage_Adminhtml'], '$notContains' => ['Mage_AdminNotification']]; - yield 'Mage_Admin module, with --all' => ['$moduleName' => 'Mage_Admin', '$all' => 1, '$expectations' => ['Mage_AdminNotification', 'Mage_Adminhtml'], '$notContains' => ['Mage_Compiler', 'Mage_Customer']]; - yield 'Mage_Admin module, with -a' => ['$moduleName' => 'Mage_Admin', '$all' => 2, '$expectations' => ['Mage_AdminNotification', 'Mage_Adminhtml'], '$notContains' => ['Mage_Compiler', 'Mage_Customer']]; + return ['Not existing module, no --all' => ['$moduleName' => 'NotExistentModule', '$all' => 0, '$expectations' => ['Module NotExistentModule was not found'], '$notContains' => []], 'Not existing module, with --all' => ['$moduleName' => 'NotExistentModule', '$all' => 1, '$expectations' => ['Module NotExistentModule was not found'], '$notContains' => []], 'Not existing module, with -a' => ['$moduleName' => 'NotExistentModule', '$all' => 2, '$expectations' => ['Module NotExistentModule was not found'], '$notContains' => []], 'Mage_Admin module, no --all' => ['$moduleName' => 'Mage_Admin', '$all' => 0, '$expectations' => ['Mage_Adminhtml'], '$notContains' => ['Mage_AdminNotification']], 'Mage_Admin module, with --all' => ['$moduleName' => 'Mage_Admin', '$all' => 1, '$expectations' => ['Mage_AdminNotification', 'Mage_Adminhtml'], '$notContains' => ['Mage_Compiler', 'Mage_Customer']], 'Mage_Admin module, with -a' => ['$moduleName' => 'Mage_Admin', '$all' => 2, '$expectations' => ['Mage_AdminNotification', 'Mage_Adminhtml'], '$notContains' => ['Mage_Compiler', 'Mage_Customer']]]; } /** * @dataProvider dataProviderTestExecute * @param string $moduleName * @param int $all + * @param array $contains + * @param array $notContains */ public function testExecute($moduleName, $all, array $contains, array $notContains) { $application = $this->getApplication(); $application->add(new FromCommand()); - $command = $this->getApplication()->find('dev:module:dependencies:from'); $commandTester = new CommandTester($command); @@ -51,12 +45,11 @@ public function testExecute($moduleName, $all, array $contains, array $notContai } $commandTester->execute($input); - foreach ($contains as $contain) { - $this->assertStringContainsString($contain, $commandTester->getDisplay()); + foreach ($contains as $expectation) { + self::assertStringContainsString($expectation, $commandTester->getDisplay()); } - - foreach ($notContains as $notContain) { - $this->assertStringNotContainsString($notContain, $commandTester->getDisplay()); + foreach ($notContains as $expectation) { + self::assertStringNotContainsString($expectation, $commandTester->getDisplay()); } } } diff --git a/tests/N98/Magento/Command/Developer/Module/Dependencies/OnCommandTest.php b/tests/N98/Magento/Command/Developer/Module/Dependencies/OnCommandTest.php index 4491e59b9..953360d8c 100644 --- a/tests/N98/Magento/Command/Developer/Module/Dependencies/OnCommandTest.php +++ b/tests/N98/Magento/Command/Developer/Module/Dependencies/OnCommandTest.php @@ -1,7 +1,5 @@ ['$moduleName' => 'NotExistentModule', '$all' => 0, '$expectations' => ['Module NotExistentModule was not found'], '$notContains' => []]; - yield 'Not existing module, with --all' => ['$moduleName' => 'NotExistentModule', '$all' => 1, '$expectations' => ['Module NotExistentModule was not found'], '$notContains' => []]; - yield 'Not existing module, with -a' => ['$moduleName' => 'NotExistentModule', '$all' => 2, '$expectations' => ['Module NotExistentModule was not found'], '$notContains' => []]; - yield 'Mage_Core module, no --all' => ['$moduleName' => 'Mage_Core', '$all' => 0, '$expectations' => ["Module Mage_Core doesn't have dependencies"], '$notContains' => []]; - yield 'Mage_Core module, with --all' => ['$moduleName' => 'Mage_Core', '$all' => 1, '$expectations' => ["Module Mage_Core doesn't have dependencies"], '$notContains' => []]; - yield 'Mage_Core module, with -a' => ['$moduleName' => 'Mage_Core', '$all' => 2, '$expectations' => ["Module Mage_Core doesn't have dependencies"], '$notContains' => []]; - yield 'Mage_Customer module, no --all' => ['$moduleName' => 'Mage_Customer', '$all' => 0, '$expectations' => [ + return ['Not existing module, no --all' => ['$moduleName' => 'NotExistentModule', '$all' => 0, '$expectations' => ['Module NotExistentModule was not found'], '$notContains' => []], 'Not existing module, with --all' => ['$moduleName' => 'NotExistentModule', '$all' => 1, '$expectations' => ['Module NotExistentModule was not found'], '$notContains' => []], 'Not existing module, with -a' => ['$moduleName' => 'NotExistentModule', '$all' => 2, '$expectations' => ['Module NotExistentModule was not found'], '$notContains' => []], 'Mage_Core module, no --all' => ['$moduleName' => 'Mage_Core', '$all' => 0, '$expectations' => ["Module Mage_Core doesn't have dependencies"], '$notContains' => []], 'Mage_Core module, with --all' => ['$moduleName' => 'Mage_Core', '$all' => 1, '$expectations' => ["Module Mage_Core doesn't have dependencies"], '$notContains' => []], 'Mage_Core module, with -a' => ['$moduleName' => 'Mage_Core', '$all' => 2, '$expectations' => ["Module Mage_Core doesn't have dependencies"], '$notContains' => []], 'Mage_Customer module, no --all' => ['$moduleName' => 'Mage_Customer', '$all' => 0, '$expectations' => [ 'Mage_Dataflow', /*'Mage_Directory',*/ 'Mage_Eav', - ], '$notContains' => ['Mage_Core']]; - yield 'Mage_Customer module, with --all' => ['$moduleName' => 'Mage_Customer', '$all' => 1, '$expectations' => [ + ], '$notContains' => ['Mage_Core']], 'Mage_Customer module, with --all' => ['$moduleName' => 'Mage_Customer', '$all' => 1, '$expectations' => [ 'Mage_Core', 'Mage_Dataflow', /*'Mage_Directory',*/ 'Mage_Eav', - ], '$notContains' => []]; - yield 'Mage_Customer module, with -a' => ['$moduleName' => 'Mage_Customer', '$all' => 2, '$expectations' => [ + ], '$notContains' => []], 'Mage_Customer module, with -a' => ['$moduleName' => 'Mage_Customer', '$all' => 2, '$expectations' => [ 'Mage_Core', 'Mage_Dataflow', /*'Mage_Directory',*/ 'Mage_Eav', - ], '$notContains' => []]; + ], '$notContains' => []]]; } /** * @dataProvider dataProviderTestExecute * @param string $moduleName * @param int $all + * @param array $contains + * @param array $notContains */ public function testExecute($moduleName, $all, array $contains, array $notContains) { $application = $this->getApplication(); $application->add(new OnCommand()); - $command = $this->getApplication()->find('dev:module:dependencies:on'); $commandTester = new CommandTester($command); @@ -68,12 +59,11 @@ public function testExecute($moduleName, $all, array $contains, array $notContai } $commandTester->execute($input); - foreach ($contains as $contain) { - $this->assertStringContainsString($contain, $commandTester->getDisplay()); + foreach ($contains as $expectation) { + self::assertStringContainsString($expectation, $commandTester->getDisplay()); } - - foreach ($notContains as $notContain) { - $this->assertStringNotContainsString($notContain, $commandTester->getDisplay()); + foreach ($notContains as $expectation) { + self::assertStringNotContainsString($expectation, $commandTester->getDisplay()); } } } diff --git a/tests/N98/Magento/Command/Developer/Module/ListCommandTest.php b/tests/N98/Magento/Command/Developer/Module/ListCommandTest.php index 04f5e7f3d..2607c0b7e 100644 --- a/tests/N98/Magento/Command/Developer/Module/ListCommandTest.php +++ b/tests/N98/Magento/Command/Developer/Module/ListCommandTest.php @@ -1,26 +1,23 @@ getApplication(); $application->add(new ListCommand()); - $command = $this->getApplication()->find('dev:module:list'); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName()], + ['command' => $command->getName()] ); - $this->assertMatchesRegularExpression('/Mage_Core/', $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/Mage_Core/', $commandTester->getDisplay()); } } diff --git a/tests/N98/Magento/Command/Developer/Module/Observer/ListCommandTest.php b/tests/N98/Magento/Command/Developer/Module/Observer/ListCommandTest.php index 7ed8c01e1..1bdf40b05 100644 --- a/tests/N98/Magento/Command/Developer/Module/Observer/ListCommandTest.php +++ b/tests/N98/Magento/Command/Developer/Module/Observer/ListCommandTest.php @@ -1,26 +1,23 @@ getApplication(); $application->add(new ListCommand()); - $command = $this->getApplication()->find('dev:module:observer:list'); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), 'type' => 'global'], + ['command' => $command->getName(), 'type' => 'global'] ); - $this->assertStringContainsString('controller_front_init_routers', $commandTester->getDisplay()); + self::assertStringContainsString('controller_front_init_routers', $commandTester->getDisplay()); } } diff --git a/tests/N98/Magento/Command/Developer/Module/Rewrite/ClassExistsCheckerTest.php b/tests/N98/Magento/Command/Developer/Module/Rewrite/ClassExistsCheckerTest.php index 8f0edf79c..ab68e64ee 100644 --- a/tests/N98/Magento/Command/Developer/Module/Rewrite/ClassExistsCheckerTest.php +++ b/tests/N98/Magento/Command/Developer/Module/Rewrite/ClassExistsCheckerTest.php @@ -1,7 +1,4 @@ assertInstanceOf(__NAMESPACE__ . '\ClassExistsChecker', $checker); + self::assertInstanceOf(__NAMESPACE__ . '\ClassExistsChecker', $checker); $checker = ClassExistsChecker::create('Le_Foo_Le_Bar_Nexiste_Pas'); - $this->assertInstanceOf(__NAMESPACE__ . '\ClassExistsChecker', $checker); + self::assertInstanceOf(__NAMESPACE__ . '\ClassExistsChecker', $checker); } - public function testExistingClass() + /** + * @test + */ + public function existingClass() { - $this->assertTrue(ClassExistsChecker::create(IteratorIterator::class)->existsExtendsSafe()); + self::assertTrue(ClassExistsChecker::create(IteratorIterator::class)->existsExtendsSafe()); } - public function testNonExistingClass() + /** + * @test + */ + public function nonExistingClass() { - $this->assertFalse(ClassExistsChecker::create('asdfu8jq23nklr08asASDF0oaosdufhoanl')->existsExtendsSafe()); + self::assertFalse(ClassExistsChecker::create('asdfu8jq23nklr08asASDF0oaosdufhoanl')->existsExtendsSafe()); } - public function testThrowingAnExceptionWhileIncluding() + /** + * @test + */ + public function throwingAnExceptionWhileIncluding() { // similar to Varien_Autoload $innerException = null; - $autoloadHandler = $this->create(function ($className) use (&$innerException): void { + $autoload = $this->create(function ($className) use (&$innerException) { $innerException = new BadMethodCallException('exception in include simulation for ' . $className); throw $innerException; }); @@ -67,16 +76,13 @@ public function testThrowingAnExceptionWhileIncluding() try { $className = 'Le_Foo_Le_Bar_Nexiste_Pas'; ClassExistsChecker::create($className)->existsExtendsSafe(); - $autoloadHandler->reset(); + $autoload->reset(); self::fail('An expected Exception has not been thrown'); - } catch (Exception $exception) { - $autoloadHandler->reset(); - $this->assertInstanceOf(__NAMESPACE__ . '\ClassExistsThrownException', $exception); - if (isset($innerException)) { - $this->assertInstanceOf(get_class($innerException), $exception->getPrevious()); - } - - $this->assertSame($innerException, $exception->getPrevious()); + } catch (Exception $ex) { + $autoload->reset(); + self::assertInstanceOf(__NAMESPACE__ . '\ClassExistsThrownException', $ex); + isset($innerException) && self::assertInstanceOf(get_class($innerException), $ex->getPrevious()); + self::assertSame($innerException, $ex->getPrevious()); } } @@ -84,34 +90,40 @@ public function testThrowingAnExceptionWhileIncluding() * @return array * @see preventingFatalOnNonExistingBaseClass */ - public function provideClassNames(): \Iterator + public function provideClassNames() { - yield ['Le_Foo_Le_Bar']; - # extends from a non-existing file of that base-class - yield ['Le_Foo_Le_Bar_R1']; + return [ + ['Le_Foo_Le_Bar'], + # extends from a non-existing file of that base-class + ['Le_Foo_Le_Bar_R1'], + ]; } /** + * @test * @dataProvider provideClassNames * @param string $className */ - public function testPreventingFatalOnNonExistingBaseClass($className) + public function preventingFatalOnNonExistingBaseClass($className) { - $autoloadHandler = $this->create($this->getAutoloader()); + $autoload = $this->create($this->getAutoloader()); $restore = $this->noErrorExceptions(); try { $actual = ClassExistsChecker::create($className)->existsExtendsSafe(); $restore(); - $autoloadHandler->reset(); - $this->assertFalse($actual); - } catch (Exception $exception) { + $autoload->reset(); + self::assertFalse($actual); + } catch (Exception $ex) { $restore(); - $autoloadHandler->reset(); + $autoload->reset(); self::fail('An exception has been thrown'); } } - public function testWarningTriggeringExpectedBehaviour() + /** + * @test + */ + public function warningTriggeringExpectedBehaviour() { $this->markTestSkipped('Maybe not compatible with PHP 8.1 anymore. Has to be checked again.'); $undef_var = null; @@ -123,43 +135,43 @@ public function testWarningTriggeringExpectedBehaviour() $canary = error_get_last(); // precondition is that there was no error yet - $this->assertNotNull($canary, 'precondition not met'); + self::assertNotNull($canary, 'precondition not met'); // precondition of the error reporting level $reporting = error_reporting(); // 22527 - E_ALL & ~E_DEPRECATED & ~E_STRICT (PHP 5.6) // 32767 - E_ALL (Travis PHP 5.3, PHP 5.4) $knownErrorLevels = ['E_ALL & ~E_DEPRECATED & ~E_STRICT (Deb Sury 5.6)' => 22527, 'E_ALL (Travis PHP 5.3, 5.4, 5.5)' => 32767]; - $this->assertContains($reporting, $knownErrorLevels, 'error reporting as of ' . $reporting); + self::assertContains($reporting, $knownErrorLevels, "error reporting as of $reporting"); // by default the class must be loaded with a different autoloader - $this->assertFalse(class_exists('Le_Foo_Le_Bar_Fine')); + self::assertFalse(class_exists('Le_Foo_Le_Bar_Fine')); // post-condition is that there was no error yet - $this->assertSame($canary, error_get_last()); + self::assertSame($canary, error_get_last()); // should not trigger an error if the class exists - $this->create($this->getAutoloader()); - $this->assertTrue(class_exists('Le_Foo_Le_Bar_Fine')); - $this->assertSame($canary, error_get_last()); + $autoload = $this->create($this->getAutoloader()); + self::assertTrue(class_exists('Le_Foo_Le_Bar_Fine')); + self::assertSame($canary, error_get_last()); // should trigger a warning if the class does not exists as file on disk per auto-loading $restore = $this->noErrorExceptions(); $actual = class_exists('Le_Foo_Le_Bar_Nexiste_Pas'); $restore(); - $this->assertFalse($actual); + self::assertFalse($actual); $lastError = error_get_last(); if ($canary === $lastError) { self::markTestIncomplete('System does not triggers the expected warning on include'); } - $this->assertNotSame($canary, $lastError); - $this->assertArrayHasKey('type', $lastError); - $this->assertSame(2, $lastError['type']); - $this->assertArrayHasKey('message', $lastError); + self::assertNotSame($canary, $lastError); + self::assertArrayHasKey('type', $lastError); + self::assertSame(2, $lastError['type']); + self::assertArrayHasKey('message', $lastError); $pattern = '~include\(\): Failed opening \'.*Rewrite/fixture/Le_Foo_Le_Bar_Nexiste_Pas\.php\' for inclusion ~'; - $this->assertMatchesRegularExpression($pattern, $lastError['message']); + self::assertMatchesRegularExpression($pattern, $lastError['message']); } /** @@ -170,10 +182,9 @@ public function testWarningTriggeringExpectedBehaviour() private function getAutoloader() { return function ($className) { - if (in_array(preg_match('~^(Le_Foo_Le_Bar)~', $className), [0, false], true)) { + if (!preg_match('~^(Le_Foo_Le_Bar)~', $className)) { return false; } - $file = __DIR__ . '/fixture/' . $className . '.php'; return include $file; @@ -195,7 +206,7 @@ private function noErrorExceptions($includeIni = true) $logErrorsOrig = ini_get('log_errors'); $includeIni && ini_set('log_errors', false); - $restore = function () use ($displayErrorsOrig, $logErrorsOrig): void { + $restore = function () use ($displayErrorsOrig, $logErrorsOrig) { ini_set('display_errors', $displayErrorsOrig); ini_set('log_errors', $logErrorsOrig); }; @@ -210,13 +221,14 @@ private function noErrorExceptions($includeIni = true) * after test is over * * @param $callback + * @param null $flags * @return AutoloadHandler */ private function create($callback, $flags = null) { - $autoloadHandler = AutoloadHandler::create($callback, $flags); - $this->cleanup[] = $autoloadHandler->getCleanupCallback(); - return $autoloadHandler; + $handler = AutoloadHandler::create($callback, $flags); + $this->cleanup[] = $handler->getCleanupCallback(); + return $handler; } private function cleanup() diff --git a/tests/N98/Magento/Command/Developer/Module/Rewrite/ConflictsCommandTest.php b/tests/N98/Magento/Command/Developer/Module/Rewrite/ConflictsCommandTest.php index 311a5a802..1278ef1bd 100644 --- a/tests/N98/Magento/Command/Developer/Module/Rewrite/ConflictsCommandTest.php +++ b/tests/N98/Magento/Command/Developer/Module/Rewrite/ConflictsCommandTest.php @@ -1,7 +1,5 @@ getApplication(); $application->add(new ConflictsCommand()); - $command = $this->getApplication()->find('dev:module:rewrite:conflicts'); /** @@ -27,20 +24,20 @@ public function testExecute() */ $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName()], + ['command' => $command->getName()] ); - $this->assertStringContainsString('No rewrite conflicts were found', $commandTester->getDisplay()); + self::assertStringContainsString('No rewrite conflicts were found', $commandTester->getDisplay()); /** * Junit Log without any output */ $commandTester = new CommandTester($command); $result = $commandTester->execute( - ['command' => $command->getName(), '--log-junit' => '_output.xml'], + ['command' => $command->getName(), '--log-junit' => '_output.xml'] ); - $this->assertSame(0, $result); - $this->assertSame('', $commandTester->getDisplay()); - $this->assertFileExists('_output.xml'); + self::assertEquals(0, $result); + self::assertEquals('', $commandTester->getDisplay()); + self::assertFileExists('_output.xml'); @unlink('_output.xml'); } @@ -50,11 +47,11 @@ public function testExecute() public function testExecuteConflict() { $rewrites = ['blocks' => ['n98/mock_conflict' => ['Mage_Customer_Block_Account', 'Mage_Tag_Block_All']]]; - $conflictsCommand = $this->getCommandWithMockLoadRewrites($rewrites); - $commandTester = new CommandTester($conflictsCommand); - $result = $commandTester->execute(['command' => $conflictsCommand->getName()]); - $this->assertNotSame(0, $result); - $this->assertStringContainsString('1 conflict was found', $commandTester->getDisplay()); + $command = $this->getCommandWithMockLoadRewrites($rewrites); + $commandTester = new CommandTester($command); + $result = $commandTester->execute(['command' => $command->getName()]); + self::assertNotEquals(0, $result); + self::assertStringContainsString('1 conflict was found', $commandTester->getDisplay()); } /** @@ -65,17 +62,18 @@ public function testExecuteConflict() public function testExecuteConflictFalsePositive() { $rewrites = ['blocks' => ['n98/mock_conflict' => ['Mage_Catalog_Block_Product_Price', 'Mage_Bundle_Block_Catalog_Product_Price']]]; - $conflictsCommand = $this->getCommandWithMockLoadRewrites($rewrites); - $commandTester = new CommandTester($conflictsCommand); - $result = $commandTester->execute(['command' => $conflictsCommand->getName()]); - $this->assertSame(0, $result); - $this->assertStringContainsString('No rewrite conflicts were found', $commandTester->getDisplay()); + $command = $this->getCommandWithMockLoadRewrites($rewrites); + $commandTester = new CommandTester($command); + $result = $commandTester->execute(['command' => $command->getName()]); + self::assertEquals(0, $result); + self::assertStringContainsString('No rewrite conflicts were found', $commandTester->getDisplay()); } /** * Mock the ConflictsCommand and change the return value of loadRewrites() * to the given argument * + * @param array $return * @return ConflictsCommand */ private function getCommandWithMockLoadRewrites(array $return) diff --git a/tests/N98/Magento/Command/Developer/Module/Rewrite/fixture/Le_Foo_Le_Bar.php b/tests/N98/Magento/Command/Developer/Module/Rewrite/fixture/Le_Foo_Le_Bar.php index d8ddc95d2..eb64c09c1 100644 --- a/tests/N98/Magento/Command/Developer/Module/Rewrite/fixture/Le_Foo_Le_Bar.php +++ b/tests/N98/Magento/Command/Developer/Module/Rewrite/fixture/Le_Foo_Le_Bar.php @@ -1,7 +1,4 @@ markTestIncomplete('Find a replacement for missing setInputStream of question helper'); $application = $this->getApplication(); $application->add(new ListCommand()); - $createCommand = $this->getApplication()->find('dev:module:create'); $updateCommand = $this->getApplication()->find('dev:module:update'); $updateCommand->setTestMode(true); - $root = getcwd(); $this->_deleteOldModule($root); $commandTester = new CommandTester($createCommand); $commandTester->execute( - ['command' => $createCommand->getName(), '--add-all' => true, '--modman' => true, '--description' => 'Unit Test Description', '--author-name' => 'Unit Test', '--author-email' => 'n98-magerun@example.com', 'vendorNamespace' => 'N98Magerun', 'moduleName' => 'UnitTest'], + ['command' => $createCommand->getName(), '--add-all' => true, '--modman' => true, '--description' => 'Unit Test Description', '--author-name' => 'Unit Test', '--author-email' => 'n98-magerun@example.com', 'vendorNamespace' => 'N98Magerun', 'moduleName' => 'UnitTest'] ); $commandTester = new CommandTester($updateCommand); @@ -52,7 +48,7 @@ public function testExecute() * @param $root * @return bool|Filesystem */ - private function _deleteOldModule($root) + protected function _deleteOldModule($root) { // delete old module $filesystem = false; @@ -62,14 +58,13 @@ private function _deleteOldModule($root) $filesystem->recursiveRemoveDirectory($root . '/N98Magerun_UnitTest'); clearstatcache(); } - return $filesystem; } - private function getInputStream($input) + protected function getInputStream($input) { $stream = fopen('php://memory', 'rb+', false); - fwrite($stream, $input); + fputs($stream, $input); rewind($stream); return $stream; @@ -79,7 +74,7 @@ private function getInputStream($input) * @param $moduleBaseFolder * @return string */ - private function _getConfigXmlContents($moduleBaseFolder) + protected function _getConfigXmlContents($moduleBaseFolder) { return file_get_contents($moduleBaseFolder . 'etc/config.xml'); } @@ -89,16 +84,16 @@ private function _getConfigXmlContents($moduleBaseFolder) * @param $updateCommand * @param $moduleBaseFolder */ - private function _setVersionOptionTest($commandTester, $updateCommand, $moduleBaseFolder) + protected function _setVersionOptionTest($commandTester, $updateCommand, $moduleBaseFolder) { $commandTester->execute( - ['command' => $updateCommand->getName(), '--set-version' => true, 'vendorNamespace' => 'N98Magerun', 'moduleName' => 'UnitTest'], + ['command' => $updateCommand->getName(), '--set-version' => true, 'vendorNamespace' => 'N98Magerun', 'moduleName' => 'UnitTest'] ); - $this->assertFileExists($moduleBaseFolder . 'etc/config.xml'); + self::assertFileExists($moduleBaseFolder . 'etc/config.xml'); $configXmlContent = $this->_getConfigXmlContents($moduleBaseFolder); - $this->assertStringContainsString('2.0.0', $configXmlContent); + self::assertStringContainsString('2.0.0', $configXmlContent); } /** @@ -108,22 +103,22 @@ private function _setVersionOptionTest($commandTester, $updateCommand, $moduleBa * @param $moduleBaseFolder * @return string */ - private function _addResourceModelOptionTest($dialog, $commandTester, $updateCommand, $moduleBaseFolder) + protected function _addResourceModelOptionTest($dialog, $commandTester, $updateCommand, $moduleBaseFolder) { $dialog->setInputStream($this->getInputStream("y\nentity1\nentity1table\nentity2\nentity2table\n\n")); $commandTester->execute( - ['command' => $updateCommand->getName(), '--add-resource-model' => true, 'vendorNamespace' => 'N98Magerun', 'moduleName' => 'UnitTest'], + ['command' => $updateCommand->getName(), '--add-resource-model' => true, 'vendorNamespace' => 'N98Magerun', 'moduleName' => 'UnitTest'] ); $configXmlContent = $this->_getConfigXmlContents($moduleBaseFolder); - $this->assertStringContainsString('', $configXmlContent); - $this->assertStringContainsString('n98magerun_unittest_resource_eav_mysql4', $configXmlContent); - $this->assertStringContainsString('N98Magerun_UnitTest_Model_Resource', $configXmlContent); - $this->assertStringContainsString('', $configXmlContent); - $this->assertStringContainsString('', $configXmlContent); - $this->assertStringContainsString('entity1table
', $configXmlContent); - $this->assertStringContainsString('', $configXmlContent); - $this->assertStringContainsString('entity2table
', $configXmlContent); + self::assertStringContainsString('', $configXmlContent); + self::assertStringContainsString('n98magerun_unittest_resource_eav_mysql4', $configXmlContent); + self::assertStringContainsString('N98Magerun_UnitTest_Model_Resource', $configXmlContent); + self::assertStringContainsString('', $configXmlContent); + self::assertStringContainsString('', $configXmlContent); + self::assertStringContainsString('entity1table
', $configXmlContent); + self::assertStringContainsString('', $configXmlContent); + self::assertStringContainsString('entity2table
', $configXmlContent); } /** @@ -132,21 +127,21 @@ private function _addResourceModelOptionTest($dialog, $commandTester, $updateCom * @param $updateCommand * @param $moduleBaseFolder */ - private function _addRoutersOptionTest($dialog, $commandTester, $updateCommand, $moduleBaseFolder) + protected function _addRoutersOptionTest($dialog, $commandTester, $updateCommand, $moduleBaseFolder) { $dialog->setInputStream($this->getInputStream("admin\nstandard\nn98magerun\n")); $commandTester->execute( - ['command' => $updateCommand->getName(), '--add-routers' => true, 'vendorNamespace' => 'N98Magerun', 'moduleName' => 'UnitTest'], + ['command' => $updateCommand->getName(), '--add-routers' => true, 'vendorNamespace' => 'N98Magerun', 'moduleName' => 'UnitTest'] ); $configXmlContent = $this->_getConfigXmlContents($moduleBaseFolder); - $this->assertStringContainsString('', $configXmlContent); - $this->assertStringContainsString('', $configXmlContent); - $this->assertStringContainsString('', $configXmlContent); - $this->assertStringContainsString('', $configXmlContent); - $this->assertStringContainsString('standard', $configXmlContent); - $this->assertStringContainsString('n98magerun_unittest', $configXmlContent); - $this->assertStringContainsString('n98magerun', $configXmlContent); + self::assertStringContainsString('', $configXmlContent); + self::assertStringContainsString('', $configXmlContent); + self::assertStringContainsString('', $configXmlContent); + self::assertStringContainsString('', $configXmlContent); + self::assertStringContainsString('standard', $configXmlContent); + self::assertStringContainsString('n98magerun_unittest', $configXmlContent); + self::assertStringContainsString('n98magerun', $configXmlContent); } /** @@ -155,18 +150,18 @@ private function _addRoutersOptionTest($dialog, $commandTester, $updateCommand, * @param $updateCommand * @param $moduleBaseFolder */ - private function _addEventsOptionTest($dialog, $commandTester, $updateCommand, $moduleBaseFolder) + protected function _addEventsOptionTest($dialog, $commandTester, $updateCommand, $moduleBaseFolder) { $dialog->setInputStream($this->getInputStream("frontend\ncontroller_action_postdispatch\nn98mageruntest_observer\nn98magerun_unittest/observer\ncontrollerActionPostdispatch")); $commandTester->execute( - ['command' => $updateCommand->getName(), '--add-events' => true, 'vendorNamespace' => 'N98Magerun', 'moduleName' => 'UnitTest'], + ['command' => $updateCommand->getName(), '--add-events' => true, 'vendorNamespace' => 'N98Magerun', 'moduleName' => 'UnitTest'] ); $configXmlContent = $this->_getConfigXmlContents($moduleBaseFolder); - $this->assertStringContainsString('', $configXmlContent); - $this->assertStringContainsString('', $configXmlContent); - $this->assertStringContainsString('', $configXmlContent); - $this->assertStringContainsString('n98magerun_unittest/observer', $configXmlContent); - $this->assertStringContainsString('controllerActionPostdispatch', $configXmlContent); + self::assertStringContainsString('', $configXmlContent); + self::assertStringContainsString('', $configXmlContent); + self::assertStringContainsString('', $configXmlContent); + self::assertStringContainsString('n98magerun_unittest/observer', $configXmlContent); + self::assertStringContainsString('controllerActionPostdispatch', $configXmlContent); } /** @@ -175,18 +170,18 @@ private function _addEventsOptionTest($dialog, $commandTester, $updateCommand, $ * @param $updateCommand * @param $moduleBaseFolder */ - private function _addLayoutUpdatesOptionTest($dialog, $commandTester, $updateCommand, $moduleBaseFolder) + protected function _addLayoutUpdatesOptionTest($dialog, $commandTester, $updateCommand, $moduleBaseFolder) { $dialog->setInputStream($this->getInputStream("adminhtml\nn98magerun_unittest\nn98magerun_unittest.xml")); $commandTester->execute( - ['command' => $updateCommand->getName(), '--add-layout-updates' => true, 'vendorNamespace' => 'N98Magerun', 'moduleName' => 'UnitTest'], + ['command' => $updateCommand->getName(), '--add-layout-updates' => true, 'vendorNamespace' => 'N98Magerun', 'moduleName' => 'UnitTest'] ); $configXmlContent = $this->_getConfigXmlContents($moduleBaseFolder); - $this->assertStringContainsString('', $configXmlContent); - $this->assertStringContainsString('', $configXmlContent); - $this->assertStringContainsString('', $configXmlContent); - $this->assertStringContainsString('', $configXmlContent); - $this->assertStringContainsString('n98magerun_unittest.xml', $configXmlContent); + self::assertStringContainsString('', $configXmlContent); + self::assertStringContainsString('', $configXmlContent); + self::assertStringContainsString('', $configXmlContent); + self::assertStringContainsString('', $configXmlContent); + self::assertStringContainsString('n98magerun_unittest.xml', $configXmlContent); } /** @@ -195,19 +190,19 @@ private function _addLayoutUpdatesOptionTest($dialog, $commandTester, $updateCom * @param $updateCommand * @param $moduleBaseFolder */ - private function _addTranslateOptionTest($dialog, $commandTester, $updateCommand, $moduleBaseFolder) + protected function _addTranslateOptionTest($dialog, $commandTester, $updateCommand, $moduleBaseFolder) { $dialog->setInputStream($this->getInputStream("adminhtml\nN98magerun_UnitTest.csv")); $commandTester->execute( - ['command' => $updateCommand->getName(), '--add-translate' => true, 'vendorNamespace' => 'N98Magerun', 'moduleName' => 'UnitTest'], + ['command' => $updateCommand->getName(), '--add-translate' => true, 'vendorNamespace' => 'N98Magerun', 'moduleName' => 'UnitTest'] ); $configXmlContent = $this->_getConfigXmlContents($moduleBaseFolder); - $this->assertStringContainsString('', $configXmlContent); - $this->assertStringContainsString('', $configXmlContent); - $this->assertStringContainsString('', $configXmlContent); - $this->assertStringContainsString('', $configXmlContent); - $this->assertStringContainsString('', $configXmlContent); - $this->assertStringContainsString('N98magerun_UnitTest.csv', $configXmlContent); + self::assertStringContainsString('', $configXmlContent); + self::assertStringContainsString('', $configXmlContent); + self::assertStringContainsString('', $configXmlContent); + self::assertStringContainsString('', $configXmlContent); + self::assertStringContainsString('', $configXmlContent); + self::assertStringContainsString('N98magerun_UnitTest.csv', $configXmlContent); } /** @@ -216,16 +211,16 @@ private function _addTranslateOptionTest($dialog, $commandTester, $updateCommand * @param $updateCommand * @param $moduleBaseFolder */ - private function _addDefaultOptionTest($dialog, $commandTester, $updateCommand, $moduleBaseFolder) + protected function _addDefaultOptionTest($dialog, $commandTester, $updateCommand, $moduleBaseFolder) { $dialog->setInputStream($this->getInputStream("sectiontest\ngrouptest\nfieldname\nfieldvalue")); $commandTester->execute( - ['command' => $updateCommand->getName(), '--add-default' => true, 'vendorNamespace' => 'N98Magerun', 'moduleName' => 'UnitTest'], + ['command' => $updateCommand->getName(), '--add-default' => true, 'vendorNamespace' => 'N98Magerun', 'moduleName' => 'UnitTest'] ); $configXmlContent = $this->_getConfigXmlContents($moduleBaseFolder); - $this->assertStringContainsString('', $configXmlContent); - $this->assertStringContainsString('', $configXmlContent); - $this->assertStringContainsString('', $configXmlContent); - $this->assertStringContainsString('fieldvalue', $configXmlContent); + self::assertStringContainsString('', $configXmlContent); + self::assertStringContainsString('', $configXmlContent); + self::assertStringContainsString('', $configXmlContent); + self::assertStringContainsString('fieldvalue', $configXmlContent); } } diff --git a/tests/N98/Magento/Command/Developer/ProfilerCommandTest.php b/tests/N98/Magento/Command/Developer/ProfilerCommandTest.php index d8edad711..d2500d9eb 100644 --- a/tests/N98/Magento/Command/Developer/ProfilerCommandTest.php +++ b/tests/N98/Magento/Command/Developer/ProfilerCommandTest.php @@ -1,33 +1,30 @@ getApplication(); $application->add(new ProfilerCommand()); $application->setAutoExit(false); - $command = $this->getApplication()->find('dev:profiler'); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), '--global' => true, '--on' => true], + ['command' => $command->getName(), '--global' => true, '--on' => true] ); - $this->assertMatchesRegularExpression('/Profiler enabled/', $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/Profiler enabled/', $commandTester->getDisplay()); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), '--global' => true, '--off' => true], + ['command' => $command->getName(), '--global' => true, '--off' => true] ); - $this->assertMatchesRegularExpression('/Profiler disabled/', $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/Profiler disabled/', $commandTester->getDisplay()); } } diff --git a/tests/N98/Magento/Command/Developer/Setup/Script/AttributeCommandTest.php b/tests/N98/Magento/Command/Developer/Setup/Script/AttributeCommandTest.php index 735b75639..d360d75b2 100644 --- a/tests/N98/Magento/Command/Developer/Setup/Script/AttributeCommandTest.php +++ b/tests/N98/Magento/Command/Developer/Setup/Script/AttributeCommandTest.php @@ -1,27 +1,27 @@ getApplication(); $application->add(new AttributeCommand()); $application->setAutoExit(false); - $command = $this->getApplication()->find('dev:setup:script:attribute'); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), 'entityType' => 'catalog_product', 'attributeCode' => 'sku'], + ['command' => $command->getName(), 'entityType' => 'catalog_product', 'attributeCode' => 'sku'] + ); + self::assertStringContainsString("'type' => 'static',", $commandTester->getDisplay()); + self::assertStringContainsString( + "Mage::getModel('eav/entity_attribute')->loadByCode('catalog_product', 'sku');", + $commandTester->getDisplay() ); - $this->assertStringContainsString("'type' => 'static',", $commandTester->getDisplay()); - $this->assertStringContainsString("Mage::getModel('eav/entity_attribute')->loadByCode('catalog_product', 'sku');", $commandTester->getDisplay()); } } diff --git a/tests/N98/Magento/Command/Developer/SymlinksCommandTest.php b/tests/N98/Magento/Command/Developer/SymlinksCommandTest.php index 30e5b94a8..a31d818f1 100644 --- a/tests/N98/Magento/Command/Developer/SymlinksCommandTest.php +++ b/tests/N98/Magento/Command/Developer/SymlinksCommandTest.php @@ -1,33 +1,30 @@ getApplication(); $application->add(new SymlinksCommand()); $application->setAutoExit(false); - $command = $this->getApplication()->find('dev:symlinks'); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), '--global' => true, '--on' => true], + ['command' => $command->getName(), '--global' => true, '--on' => true] ); - $this->assertMatchesRegularExpression('/Symlinks allowed/', $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/Symlinks allowed/', $commandTester->getDisplay()); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), '--global' => true, '--off' => true], + ['command' => $command->getName(), '--global' => true, '--off' => true] ); - $this->assertMatchesRegularExpression('/Symlinks denied/', $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/Symlinks denied/', $commandTester->getDisplay()); } } diff --git a/tests/N98/Magento/Command/Developer/TemplateHintsBlocksCommandTest.php b/tests/N98/Magento/Command/Developer/TemplateHintsBlocksCommandTest.php index 8748fbdd6..0593bbd78 100644 --- a/tests/N98/Magento/Command/Developer/TemplateHintsBlocksCommandTest.php +++ b/tests/N98/Magento/Command/Developer/TemplateHintsBlocksCommandTest.php @@ -1,33 +1,30 @@ getApplication(); $application->add(new TemplateHintsBlocksCommand()); $application->setAutoExit(false); - $command = $this->getApplication()->find('dev:template-hints-blocks'); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), '--on' => true, 'store' => 'admin'], + ['command' => $command->getName(), '--on' => true, 'store' => 'admin'] ); - $this->assertMatchesRegularExpression('/Template Hints Blocks enabled/', $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/Template Hints Blocks enabled/', $commandTester->getDisplay()); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), '--off' => true, 'store' => 'admin'], + ['command' => $command->getName(), '--off' => true, 'store' => 'admin'] ); - $this->assertMatchesRegularExpression('/Template Hints Blocks disabled/', $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/Template Hints Blocks disabled/', $commandTester->getDisplay()); } } diff --git a/tests/N98/Magento/Command/Developer/TemplateHintsCommandTest.php b/tests/N98/Magento/Command/Developer/TemplateHintsCommandTest.php index 666e9e69e..6dbb1e358 100644 --- a/tests/N98/Magento/Command/Developer/TemplateHintsCommandTest.php +++ b/tests/N98/Magento/Command/Developer/TemplateHintsCommandTest.php @@ -1,33 +1,30 @@ getApplication(); $application->add(new TemplateHintsCommand()); $application->setAutoExit(false); - $command = $this->getApplication()->find('dev:template-hints'); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), '--on' => true, 'store' => 'admin'], + ['command' => $command->getName(), '--on' => true, 'store' => 'admin'] ); - $this->assertMatchesRegularExpression('/Template Hints enabled/', $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/Template Hints enabled/', $commandTester->getDisplay()); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), '--off' => true, 'store' => 'admin'], + ['command' => $command->getName(), '--off' => true, 'store' => 'admin'] ); - $this->assertMatchesRegularExpression('/Template Hints disabled/', $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/Template Hints disabled/', $commandTester->getDisplay()); } } diff --git a/tests/N98/Magento/Command/Developer/Theme/DuplicatesCommandTest.php b/tests/N98/Magento/Command/Developer/Theme/DuplicatesCommandTest.php index 6932f5a38..c2d2cdb71 100644 --- a/tests/N98/Magento/Command/Developer/Theme/DuplicatesCommandTest.php +++ b/tests/N98/Magento/Command/Developer/Theme/DuplicatesCommandTest.php @@ -1,31 +1,28 @@ getApplication(); $application->add(new DuplicatesCommand()); - $command = $this->getApplication()->find('dev:theme:duplicates'); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), 'theme' => 'base/default', 'originalTheme' => 'base/default'], + ['command' => $command->getName(), 'theme' => 'base/default', 'originalTheme' => 'base/default'] ); $display = $commandTester->getDisplay(); $this->assertContainsPath('template/catalog/product/price.phtml', $display); $this->assertContainsPath('layout/catalog.xml', $display); - $this->assertStringNotContainsString('No duplicates was found', $display); + self::assertStringNotContainsString('No duplicates was found', $display); } /** @@ -43,13 +40,12 @@ private function assertContainsPath($path, $haystack) $pattern = '~'; while ($segment = array_shift($segments)) { $pattern .= preg_quote($segment, '~'); - if ($segments !== []) { - $pattern .= $segmentCount++ !== 0 ? '\\1' : $separator; + if ($segments) { + $pattern .= $segmentCount++ ? '\\1' : $separator; } } - $pattern .= '~'; - $this->assertMatchesRegularExpression($pattern, $haystack); + self::assertMatchesRegularExpression($pattern, $haystack); } } diff --git a/tests/N98/Magento/Command/Developer/Theme/InfoCommandTest.php b/tests/N98/Magento/Command/Developer/Theme/InfoCommandTest.php index a44a8ec5a..551293ab6 100644 --- a/tests/N98/Magento/Command/Developer/Theme/InfoCommandTest.php +++ b/tests/N98/Magento/Command/Developer/Theme/InfoCommandTest.php @@ -1,27 +1,24 @@ getApplication(); $application->add(new ListCommand()); - $command = $this->getApplication()->find('dev:theme:info'); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName()], + ['command' => $command->getName()] ); - $this->assertStringContainsString('base/default', $commandTester->getDisplay()); - $this->assertStringContainsString('Design Package Name', $commandTester->getDisplay()); + self::assertStringContainsString('base/default', $commandTester->getDisplay()); + self::assertStringContainsString('Design Package Name', $commandTester->getDisplay()); } } diff --git a/tests/N98/Magento/Command/Developer/Theme/ListCommandTest.php b/tests/N98/Magento/Command/Developer/Theme/ListCommandTest.php index dc08839b9..1c6a620ff 100644 --- a/tests/N98/Magento/Command/Developer/Theme/ListCommandTest.php +++ b/tests/N98/Magento/Command/Developer/Theme/ListCommandTest.php @@ -1,26 +1,23 @@ getApplication(); $application->add(new ListCommand()); - $command = $this->getApplication()->find('dev:theme:list'); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName()], + ['command' => $command->getName()] ); - $this->assertStringContainsString('base/default', $commandTester->getDisplay()); + self::assertStringContainsString('base/default', $commandTester->getDisplay()); } } diff --git a/tests/N98/Magento/Command/Developer/Translate/InlineAdminCommandTest.php b/tests/N98/Magento/Command/Developer/Translate/InlineAdminCommandTest.php index edfeedf7e..893589925 100644 --- a/tests/N98/Magento/Command/Developer/Translate/InlineAdminCommandTest.php +++ b/tests/N98/Magento/Command/Developer/Translate/InlineAdminCommandTest.php @@ -1,33 +1,30 @@ getApplication(); $application->add(new InlineAdminCommand()); $application->setAutoExit(false); - $command = $this->getApplication()->find('dev:translate:admin'); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), '--on' => true], + ['command' => $command->getName(), '--on' => true] ); - $this->assertStringContainsString('Inline Translation (Admin) enabled', $commandTester->getDisplay()); + self::assertStringContainsString('Inline Translation (Admin) enabled', $commandTester->getDisplay()); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), '--off' => true], + ['command' => $command->getName(), '--off' => true] ); - $this->assertStringContainsString('Inline Translation (Admin) disabled', $commandTester->getDisplay()); + self::assertStringContainsString('Inline Translation (Admin) disabled', $commandTester->getDisplay()); } } diff --git a/tests/N98/Magento/Command/Developer/Translate/InlineShopCommandTest.php b/tests/N98/Magento/Command/Developer/Translate/InlineShopCommandTest.php index 39d6932d0..ff71874a3 100644 --- a/tests/N98/Magento/Command/Developer/Translate/InlineShopCommandTest.php +++ b/tests/N98/Magento/Command/Developer/Translate/InlineShopCommandTest.php @@ -1,33 +1,30 @@ getApplication(); $application->add(new InlineAdminCommand()); $application->setAutoExit(false); - $command = $this->getApplication()->find('dev:translate:shop'); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), 'store' => 'admin', '--on' => true], + ['command' => $command->getName(), 'store' => 'admin', '--on' => true] ); - $this->assertStringContainsString('Inline Translation enabled', $commandTester->getDisplay()); + self::assertStringContainsString('Inline Translation enabled', $commandTester->getDisplay()); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), 'store' => 'admin', '--off' => true], + ['command' => $command->getName(), 'store' => 'admin', '--off' => true] ); - $this->assertStringContainsString('Inline Translation disabled', $commandTester->getDisplay()); + self::assertStringContainsString('Inline Translation disabled', $commandTester->getDisplay()); } } diff --git a/tests/N98/Magento/Command/Developer/Translate/SetCommandTest.php b/tests/N98/Magento/Command/Developer/Translate/SetCommandTest.php index 63de0940a..fbafd6ae1 100644 --- a/tests/N98/Magento/Command/Developer/Translate/SetCommandTest.php +++ b/tests/N98/Magento/Command/Developer/Translate/SetCommandTest.php @@ -1,26 +1,23 @@ getApplication(); $application->add(new InlineAdminCommand()); $application->setAutoExit(false); - $command = $this->getApplication()->find('dev:translate:set'); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), 'string' => 'foo', 'translate' => 'bar', 'store' => 'admin'], + ['command' => $command->getName(), 'string' => 'foo', 'translate' => 'bar', 'store' => 'admin'] ); - $this->assertStringContainsString('foo => bar', $commandTester->getDisplay()); + self::assertStringContainsString('foo => bar', $commandTester->getDisplay()); } } diff --git a/tests/N98/Magento/Command/Eav/Attribute/Create/DummyCommandTest.php b/tests/N98/Magento/Command/Eav/Attribute/Create/DummyCommandTest.php index 1db745b71..715cdd909 100644 --- a/tests/N98/Magento/Command/Eav/Attribute/Create/DummyCommandTest.php +++ b/tests/N98/Magento/Command/Eav/Attribute/Create/DummyCommandTest.php @@ -1,7 +1,5 @@ getApplication(); $application->add(new DummyCommand()); - $command = $application->find('eav:attribute:create-dummy-values'); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), 'locale' => 'en_US', 'attribute-id' => 92, 'values-type' => 'int', 'values-number' => 1], + ['command' => $command->getName(), 'locale' => 'en_US', 'attribute-id' => 92, 'values-type' => 'int', 'values-number' => 1] ); - $this->assertMatchesRegularExpression("/ATTRIBUTE VALUE: '(.+)' ADDED!/", $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/ATTRIBUTE VALUE: \'(.+)\' ADDED!/', $commandTester->getDisplay()); } public function testmanageArguments() { $application = $this->getApplication(); $application->add(new DummyCommand()); - $command = $application->find('eav:attribute:create-dummy-values'); - $mock = $this->getMockBuilder(QuestionHelper::class) + $dialog = $this->getMockBuilder(QuestionHelper::class) ->disableOriginalConstructor() ->setMethods(['ask']) ->getMock(); // ASK - attribute-id - $mock + $dialog ->method('ask') ->with( self::isInstanceOf(InputInterface::class), self::isInstanceOf(OutputInterface::class), - self::isInstanceOf(Question::class), + self::isInstanceOf(Question::class) ) ->willReturn(92); // ASK - values-type - $mock + $dialog ->method('ask') ->with( self::isInstanceOf(InputInterface::class), self::isInstanceOf(OutputInterface::class), - self::isInstanceOf(Question::class), + self::isInstanceOf(Question::class) ) ->willReturn('int'); // ASK - values-number - $mock + $dialog ->method('ask') ->with( self::isInstanceOf(InputInterface::class), self::isInstanceOf(OutputInterface::class), - self::isInstanceOf(Question::class), + self::isInstanceOf(Question::class) ) ->willReturn(1); // We override the standard helper with our mock - $command->getHelperSet()->set($mock, 'dialog'); + $command->getHelperSet()->set($dialog, 'dialog'); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName()], + ['command' => $command->getName()] ); $arguments = $commandTester->getInput()->getArguments(); - $this->assertArrayHasKey('attribute-id', $arguments); - $this->assertArrayHasKey('values-type', $arguments); - $this->assertArrayHasKey('values-number', $arguments); + self::assertArrayHasKey('attribute-id', $arguments); + self::assertArrayHasKey('values-type', $arguments); + self::assertArrayHasKey('values-number', $arguments); } } diff --git a/tests/N98/Magento/Command/Eav/Attribute/ListCommandTest.php b/tests/N98/Magento/Command/Eav/Attribute/ListCommandTest.php index 966228d4a..ffad51ba0 100644 --- a/tests/N98/Magento/Command/Eav/Attribute/ListCommandTest.php +++ b/tests/N98/Magento/Command/Eav/Attribute/ListCommandTest.php @@ -1,28 +1,25 @@ getApplication(); $application->add(new ListCommand()); - $command = $this->getApplication()->find('eav:attribute:list'); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), '--filter-type' => 'catalog_product', '--add-source' => true], + ['command' => $command->getName(), '--filter-type' => 'catalog_product', '--add-source' => true] ); - $this->assertStringContainsString('eav/entity_attribute_source_boolean', $commandTester->getDisplay()); - $this->assertStringContainsString('sku', $commandTester->getDisplay()); - $this->assertStringContainsString('catalog_product', $commandTester->getDisplay()); + self::assertStringContainsString('eav/entity_attribute_source_boolean', $commandTester->getDisplay()); + self::assertStringContainsString('sku', $commandTester->getDisplay()); + self::assertStringContainsString('catalog_product', $commandTester->getDisplay()); } } diff --git a/tests/N98/Magento/Command/Eav/Attribute/RemoveCommandTest.php b/tests/N98/Magento/Command/Eav/Attribute/RemoveCommandTest.php index a6107308a..80d9c43f5 100644 --- a/tests/N98/Magento/Command/Eav/Attribute/RemoveCommandTest.php +++ b/tests/N98/Magento/Command/Eav/Attribute/RemoveCommandTest.php @@ -1,7 +1,5 @@ */ -final class RemoveCommandTest extends TestCase +class RemoveCommandTest extends TestCase { public function testCommandThrowsExceptionIfInvalidEntityType() { $application = $this->getApplication(); $application->add(new RemoveCommand()); $application->setAutoExit(false); - $command = $this->getApplication()->find('eav:attribute:remove'); $this->expectException(InvalidArgumentException::class); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), 'entityType' => 'not_a_valid_type', 'attributeCode' => ['someAttribute']], + ['command' => $command->getName(), 'entityType' => 'not_a_valid_type', 'attributeCode' => ['someAttribute']] ); } @@ -37,15 +34,17 @@ public function testCommandPrintsErrorIfAttributeNotExists() $application = $this->getApplication(); $application->add(new RemoveCommand()); $application->setAutoExit(false); - $command = $this->getApplication()->find('eav:attribute:remove'); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), 'entityType' => 'catalog_product', 'attributeCode' => ['not_an_attribute']], + ['command' => $command->getName(), 'entityType' => 'catalog_product', 'attributeCode' => ['not_an_attribute']] ); - $this->assertStringContainsString('Attribute: "not_an_attribute" does not exist for entity type: "catalog_product"', $commandTester->getDisplay()); + self::assertStringContainsString( + 'Attribute: "not_an_attribute" does not exist for entity type: "catalog_product"', + $commandTester->getDisplay() + ); } public function testAttributeIsSuccessfullyRemoved() @@ -53,20 +52,19 @@ public function testAttributeIsSuccessfullyRemoved() $application = $this->getApplication(); $application->add(new RemoveCommand()); $application->setAutoExit(false); - $command = $this->getApplication()->find('eav:attribute:remove'); $entityType = 'catalog_product'; $attributeCode = 'crazyCoolAttribute'; $this->createAttribute($entityType, $attributeCode, ['type' => 'text', 'input' => 'text', 'label' => 'Test Attribute']); - $this->assertTrue($this->attributeExists($entityType, $attributeCode)); + self::assertTrue($this->attributeExists($entityType, $attributeCode)); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), 'entityType' => $entityType, 'attributeCode' => [$attributeCode]], + ['command' => $command->getName(), 'entityType' => $entityType, 'attributeCode' => [$attributeCode]] ); - $this->assertFalse($this->attributeExists($entityType, $attributeCode)); + self::assertFalse($this->attributeExists($entityType, $attributeCode)); } /** @@ -78,19 +76,18 @@ public function testOrderAttributeIsSuccessfullyRemoved($entityTypeCode) $application = $this->getApplication(); $application->add(new RemoveCommand()); $application->setAutoExit(false); - $command = $this->getApplication()->find('eav:attribute:remove'); $attributeCode = 'crazyCoolAttribute'; $this->createAttribute($entityTypeCode, $attributeCode, ['type' => 'text', 'input' => 'text', 'label' => 'Test Attribute']); - $this->assertTrue($this->attributeExists($entityTypeCode, $attributeCode)); + self::assertTrue($this->attributeExists($entityTypeCode, $attributeCode)); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), 'entityType' => $entityTypeCode, 'attributeCode' => [$attributeCode]], + ['command' => $command->getName(), 'entityType' => $entityTypeCode, 'attributeCode' => [$attributeCode]] ); - $this->assertFalse($this->attributeExists($entityTypeCode, $attributeCode)); + self::assertFalse($this->attributeExists($entityTypeCode, $attributeCode)); } public function testCanRemoveMultipleAttributes() @@ -98,7 +95,6 @@ public function testCanRemoveMultipleAttributes() $application = $this->getApplication(); $application->add(new RemoveCommand()); $application->setAutoExit(false); - $command = $this->getApplication()->find('eav:attribute:remove'); $attributeCode1 = 'crazyCoolAttribute1'; @@ -107,19 +103,25 @@ public function testCanRemoveMultipleAttributes() $this->createAttribute('catalog_product', $attributeCode2, ['type' => 'text', 'input' => 'text', 'label' => 'Test Attribute 2']); - $this->assertTrue($this->attributeExists('catalog_product', $attributeCode1)); - $this->assertTrue($this->attributeExists('catalog_product', $attributeCode2)); + self::assertTrue($this->attributeExists('catalog_product', $attributeCode1)); + self::assertTrue($this->attributeExists('catalog_product', $attributeCode2)); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), 'entityType' => 'catalog_product', 'attributeCode' => [$attributeCode1, $attributeCode2]], + ['command' => $command->getName(), 'entityType' => 'catalog_product', 'attributeCode' => [$attributeCode1, $attributeCode2]] ); - $this->assertFalse($this->attributeExists('catalog_product', $attributeCode1)); - $this->assertFalse($this->attributeExists('catalog_product', $attributeCode2)); + self::assertFalse($this->attributeExists('catalog_product', $attributeCode1)); + self::assertFalse($this->attributeExists('catalog_product', $attributeCode2)); - $this->assertStringContainsString('Successfully removed attribute: "crazyCoolAttribute1" from entity type: "catalog_product"', $commandTester->getDisplay()); + self::assertStringContainsString( + 'Successfully removed attribute: "crazyCoolAttribute1" from entity type: "catalog_product"', + $commandTester->getDisplay() + ); - $this->assertStringContainsString('Successfully removed attribute: "crazyCoolAttribute2" from entity type: "catalog_product"', $commandTester->getDisplay()); + self::assertStringContainsString( + 'Successfully removed attribute: "crazyCoolAttribute2" from entity type: "catalog_product"', + $commandTester->getDisplay() + ); } public function testCanRemoveMultipleAttributesIfSomeNotExist() @@ -127,41 +129,39 @@ public function testCanRemoveMultipleAttributesIfSomeNotExist() $application = $this->getApplication(); $application->add(new RemoveCommand()); $application->setAutoExit(false); - $command = $this->getApplication()->find('eav:attribute:remove'); $attributeCode1 = 'crazyCoolAttribute1'; $attributeCode2 = 'crazyCoolAttribute2'; $this->createAttribute('catalog_product', $attributeCode1, ['type' => 'text', 'input' => 'text', 'label' => 'Test Attribute 1']); - $this->assertTrue($this->attributeExists('catalog_product', $attributeCode1)); - $this->assertFalse($this->attributeExists('catalog_product', $attributeCode2)); + self::assertTrue($this->attributeExists('catalog_product', $attributeCode1)); + self::assertFalse($this->attributeExists('catalog_product', $attributeCode2)); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), 'entityType' => 'catalog_product', 'attributeCode' => [$attributeCode1, $attributeCode2]], + ['command' => $command->getName(), 'entityType' => 'catalog_product', 'attributeCode' => [$attributeCode1, $attributeCode2]] ); - $this->assertFalse($this->attributeExists('catalog_product', $attributeCode1)); - $this->assertFalse($this->attributeExists('catalog_product', $attributeCode2)); + self::assertFalse($this->attributeExists('catalog_product', $attributeCode1)); + self::assertFalse($this->attributeExists('catalog_product', $attributeCode2)); - $this->assertStringContainsString('Attribute: "crazyCoolAttribute2" does not exist for entity type: "catalog_product"', $commandTester->getDisplay()); + self::assertStringContainsString( + 'Attribute: "crazyCoolAttribute2" does not exist for entity type: "catalog_product"', + $commandTester->getDisplay() + ); - $this->assertStringContainsString('Successfully removed attribute: "crazyCoolAttribute1" from entity type: "catalog_product"', $commandTester->getDisplay()); + self::assertStringContainsString( + 'Successfully removed attribute: "crazyCoolAttribute1" from entity type: "catalog_product"', + $commandTester->getDisplay() + ); } /** * @return array */ - public static function entityTypeProvider(): \Iterator + public static function entityTypeProvider() { - yield ['catalog_category']; - yield ['catalog_product']; - yield ['creditmemo']; - yield ['customer']; - yield ['customer_address']; - yield ['invoice']; - yield ['order']; - yield ['shipment']; + return [['catalog_category'], ['catalog_product'], ['creditmemo'], ['customer'], ['customer_address'], ['invoice'], ['order'], ['shipment']]; } /** @@ -169,7 +169,7 @@ public static function entityTypeProvider(): \Iterator * @param string $attributeCode * @param array $data */ - private function createAttribute($entityType, $attributeCode, $data) + protected function createAttribute($entityType, $attributeCode, $data) { $setup = Mage::getModel('eav/entity_setup', 'core_setup'); $setup->addAttribute($entityType, $attributeCode, $data); @@ -187,7 +187,7 @@ private function createAttribute($entityType, $attributeCode, $data) * @param string $attributeCode * @return bool */ - private function attributeExists($entityType, $attributeCode) + protected function attributeExists($entityType, $attributeCode) { $codes = Mage::getModel('eav/config')->getEntityAttributeCodes($entityType); return in_array($attributeCode, $codes); diff --git a/tests/N98/Magento/Command/Eav/Attribute/ViewCommandTest.php b/tests/N98/Magento/Command/Eav/Attribute/ViewCommandTest.php index c7320a339..f4979e177 100644 --- a/tests/N98/Magento/Command/Eav/Attribute/ViewCommandTest.php +++ b/tests/N98/Magento/Command/Eav/Attribute/ViewCommandTest.php @@ -1,29 +1,26 @@ getApplication(); $application->add(new ListCommand()); - $command = $this->getApplication()->find('eav:attribute:view'); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), 'entityType' => 'catalog_product', 'attributeCode' => 'sku'], + ['command' => $command->getName(), 'entityType' => 'catalog_product', 'attributeCode' => 'sku'] ); - $this->assertStringContainsString('sku', $commandTester->getDisplay()); - $this->assertStringContainsString('catalog_product_entity', $commandTester->getDisplay()); - $this->assertStringContainsString('Backend-Type', $commandTester->getDisplay()); - $this->assertStringContainsString('static', $commandTester->getDisplay()); + self::assertStringContainsString('sku', $commandTester->getDisplay()); + self::assertStringContainsString('catalog_product_entity', $commandTester->getDisplay()); + self::assertStringContainsString('Backend-Type', $commandTester->getDisplay()); + self::assertStringContainsString('static', $commandTester->getDisplay()); } } diff --git a/tests/N98/Magento/Command/HelpCommandTest.php b/tests/N98/Magento/Command/HelpCommandTest.php index 092520151..e977e453f 100644 --- a/tests/N98/Magento/Command/HelpCommandTest.php +++ b/tests/N98/Magento/Command/HelpCommandTest.php @@ -1,12 +1,10 @@ execute( - ['command' => 'help'], + ['command' => 'help'] ); - $this->assertStringContainsString('The help command displays help for a given command', $commandTester->getDisplay()); + self::assertStringContainsString('The help command displays help for a given command', $commandTester->getDisplay()); } } diff --git a/tests/N98/Magento/Command/Indexer/ListCommandTest.php b/tests/N98/Magento/Command/Indexer/ListCommandTest.php index 3808cf0f0..65ef34076 100644 --- a/tests/N98/Magento/Command/Indexer/ListCommandTest.php +++ b/tests/N98/Magento/Command/Indexer/ListCommandTest.php @@ -1,25 +1,22 @@ getApplication(); $application->add(new ListCommand()); - $command = $this->getApplication()->find('index:list'); $commandTester = new CommandTester($command); $commandTester->execute(['command' => $command->getName()]); // check if i.e. at least one index is listed - $this->assertMatchesRegularExpression('/catalog_product_flat/', $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/catalog_product_flat/', $commandTester->getDisplay()); } } diff --git a/tests/N98/Magento/Command/Indexer/ReindexAllCommandTest.php b/tests/N98/Magento/Command/Indexer/ReindexAllCommandTest.php index cef9ca947..ede929457 100644 --- a/tests/N98/Magento/Command/Indexer/ReindexAllCommandTest.php +++ b/tests/N98/Magento/Command/Indexer/ReindexAllCommandTest.php @@ -1,36 +1,33 @@ getApplication(); $application->add(new ReindexAllCommand()); - $command = $this->getApplication()->find('index:reindex:all'); $application->initMagento(); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName()], + ['command' => $command->getName()] ); - $this->assertStringContainsString('Successfully reindexed catalog_product_attribute', $commandTester->getDisplay()); - $this->assertStringContainsString('Successfully reindexed catalog_product_price', $commandTester->getDisplay()); - $this->assertStringContainsString('Successfully reindexed catalog_url', $commandTester->getDisplay()); - $this->assertStringContainsString('Successfully reindexed catalog_product_flat', $commandTester->getDisplay()); - $this->assertStringContainsString('Successfully reindexed catalog_category_flat', $commandTester->getDisplay()); - $this->assertStringContainsString('Successfully reindexed catalog_category_product', $commandTester->getDisplay()); - $this->assertStringContainsString('Successfully reindexed catalogsearch_fulltext', $commandTester->getDisplay()); - $this->assertStringContainsString('Successfully reindexed cataloginventory_stock', $commandTester->getDisplay()); - $this->assertStringContainsString('Successfully reindexed tag_summary', $commandTester->getDisplay()); + self::assertStringContainsString('Successfully reindexed catalog_product_attribute', $commandTester->getDisplay()); + self::assertStringContainsString('Successfully reindexed catalog_product_price', $commandTester->getDisplay()); + self::assertStringContainsString('Successfully reindexed catalog_url', $commandTester->getDisplay()); + self::assertStringContainsString('Successfully reindexed catalog_product_flat', $commandTester->getDisplay()); + self::assertStringContainsString('Successfully reindexed catalog_category_flat', $commandTester->getDisplay()); + self::assertStringContainsString('Successfully reindexed catalog_category_product', $commandTester->getDisplay()); + self::assertStringContainsString('Successfully reindexed catalogsearch_fulltext', $commandTester->getDisplay()); + self::assertStringContainsString('Successfully reindexed cataloginventory_stock', $commandTester->getDisplay()); + self::assertStringContainsString('Successfully reindexed tag_summary', $commandTester->getDisplay()); } } diff --git a/tests/N98/Magento/Command/Indexer/ReindexCommandTest.php b/tests/N98/Magento/Command/Indexer/ReindexCommandTest.php index ade192a23..9fddd8076 100644 --- a/tests/N98/Magento/Command/Indexer/ReindexCommandTest.php +++ b/tests/N98/Magento/Command/Indexer/ReindexCommandTest.php @@ -1,26 +1,23 @@ getApplication(); $application->add(new ReindexCommand()); - $command = $this->getApplication()->find('index:reindex'); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), 'index_code' => 'tag_summary,tag_summary'], + ['command' => $command->getName(), 'index_code' => 'tag_summary,tag_summary'] ); - $this->assertStringContainsString('Successfully reindexed tag_summary', $commandTester->getDisplay()); + self::assertStringContainsString('Successfully reindexed tag_summary', $commandTester->getDisplay()); } } diff --git a/tests/N98/Magento/Command/Installer/InstallCommandPackageVersionTest.php b/tests/N98/Magento/Command/Installer/InstallCommandPackageVersionTest.php index 07d7b184c..aaad373e2 100644 --- a/tests/N98/Magento/Command/Installer/InstallCommandPackageVersionTest.php +++ b/tests/N98/Magento/Command/Installer/InstallCommandPackageVersionTest.php @@ -1,7 +1,4 @@ getApplication(); $application->add(new InstallCommand()); /** @var InstallCommand $command */ $command = $this->getApplication()->find('install'); - $installCommandTester = new InstallCommandTester(); - $packages = $installCommandTester->getMagentoPackages($command); + $tester = new InstallCommandTester(); + $packages = $tester->getMagentoPackages($command); $this->assertOngoingPackageVersions($packages, 2, 5); } @@ -36,6 +36,7 @@ public function testVersionListing() * helper assertion to verify that all packages with multiple versions are listet with the latest and greatest * version first. * + * @param array $packages * @param int $namespacesMinimum minimum number of package namespace (e.g. CE and mirror), normally 2 * @param int $nonVersionsMaximum maximum number of packages that will trigger an assertion */ @@ -47,58 +48,63 @@ private function assertOngoingPackageVersions(array $packages, $namespacesMinimu $nameConstraint = []; foreach ($packages as $package) { - $this->assertArrayHasKey('name', $package); - $this->assertArrayHasKey('version', $package); + self::assertArrayHasKey('name', $package); + self::assertArrayHasKey('version', $package); $name = $package['name']; $version = $package['version']; - $nameAndVersion = sprintf('%s %s', $name, $version); + $nameAndVersion = "$name $version"; - $this->assertArrayNotHasKey($name, $nameConstraint, sprintf('duplicate package "%s"', $name)); + self::assertArrayNotHasKey( + $name, + $nameConstraint, + sprintf('duplicate package "%s"', $name) + ); $nameConstraint[$name] = 1; if (!$this->isVersionNumber($version)) { $nonVersionsList[] = $nameAndVersion; - ++$nonVersions; + $nonVersions++; continue; } [$namespace, $nameVersion] = $this->splitName($name); if ($nameVersion === null || $nameVersion !== $version) { $nonVersionsList[] = $name; - ++$nonVersions; + $nonVersions++; continue; } - - $this->assertSame($version, $nameVersion); + self::assertSame($version, $nameVersion); if (isset($nameStack[$namespace])) { $comparison = version_compare($nameStack[$namespace], $version); $message = sprintf( - sprintf('Check order of versions for package "%s", higher comes first, but got %%s before %%s', $namespace), + "Check order of versions for package \"$namespace\", higher comes first, but got %s before %s", $nameStack[$namespace], - $version, + $version ); - $this->assertGreaterThan(0, $comparison, $message); + self::assertGreaterThan(0, $comparison, $message); } - $nameStack[$namespace] = $nameVersion; } - $this->assertGreaterThanOrEqual($namespacesMinimum, count($nameStack)); + self::assertGreaterThanOrEqual($namespacesMinimum, count($nameStack)); $message = sprintf('Too many non-versions (%s)', implode(', ', $nonVersionsList)); - $this->assertLessThan($nonVersionsMaximum, $nonVersions, $message); + self::assertLessThan($nonVersionsMaximum, $nonVersions, $message); } - public function testDemoDataPackages() + /** + * @test that demo-data-packages actually exist + */ + public function demoDataPackages() { $application = $this->getApplication(); $application->add(new InstallCommand()); /** @var InstallCommand $command */ $command = $this->getApplication()->find('install'); - $installCommandTester = new InstallCommandTester(); - $packages = $installCommandTester->getMagentoPackages($command); - $demoDataPackages = $installCommandTester->getSampleDataPackages($command); + $tester = new InstallCommandTester(); + $packages = $tester->getMagentoPackages($command); + $demoDataPackages = $tester->getSampleDataPackages($command); $this->assertSampleDataPackagesExist($packages, $demoDataPackages); } @@ -110,14 +116,13 @@ private function assertSampleDataPackagesExist(array $packages, array $demoDataP $map[$package['name']] = $index; } - foreach ($packages as $package) { + foreach ($packages as $index => $package) { if (!isset($package['extra']['sample-data'])) { continue; } - $name = $package['extra']['sample-data']; $message = sprintf('Invalid sample-data "%s" (undefined) in package "%s"', $name, $package['name']); - $this->assertArrayHasKey($name, $map, $message); + self::assertArrayHasKey($name, $map, $message); } } @@ -138,11 +143,8 @@ private function splitName($name) */ private function isVersionNumber($buffer) { - if ($this->isQuadripartiteVersionNumber($buffer)) { - return true; - } - - return $this->isTripartiteOpenMageVersionNumber($buffer); + return $this->isQuadripartiteVersionNumber($buffer) + || $this->isTripartiteOpenMageVersionNumber($buffer); } /** @@ -152,9 +154,8 @@ private function isVersionNumber($buffer) * @param string $buffer * @return bool */ - private function isTripartiteOpenMageVersionNumber($buffer) - { - if (in_array(preg_match('~^(?:19|2\d)\.\d+\.\d+$~', $buffer), [0, false], true)) { + private function isTripartiteOpenMageVersionNumber($buffer) { + if (!preg_match('~^(?:19|2\d)\.\d+\.\d+$~', $buffer)) { return false; } @@ -173,7 +174,7 @@ private function isTripartiteOpenMageVersionNumber($buffer) */ private function isQuadripartiteVersionNumber($buffer) { - if (in_array(preg_match('~^\d+\.\d+\.\d+\.\d+$~', $buffer), [0, false], true)) { + if (!preg_match('~^\d+\.\d+\.\d+\.\d+$~', $buffer)) { return false; } diff --git a/tests/N98/Magento/Command/Installer/InstallCommandTest.php b/tests/N98/Magento/Command/Installer/InstallCommandTest.php index ecdc6fe8a..05be3c506 100644 --- a/tests/N98/Magento/Command/Installer/InstallCommandTest.php +++ b/tests/N98/Magento/Command/Installer/InstallCommandTest.php @@ -1,7 +1,5 @@ markTestIncomplete('With PHPUnit 10 the test is waiting forever. This has to be fixed.'); $application = $this->getApplication(); $application->add(new InstallCommand()); - $command = $this->getApplication()->find('install'); $commandTester = new CommandTester($command); @@ -58,13 +55,13 @@ public function testInstallFailsWithInvalidDbConfigWhenAllOptionsArePassedIn() '--dbHost' => 'hostWhichDoesNotExists', '--dbUser' => 'user', '--dbPass' => 'pa$$w0rd', - '--dbName' => 'magento', - ], + '--dbName' => 'magento' + ] ); - } catch (InvalidArgumentException $invalidArgumentException) { - $this->assertSame('Database configuration is invalid', $invalidArgumentException->getMessage()); + } catch (InvalidArgumentException $e) { + self::assertEquals('Database configuration is invalid', $e->getMessage()); $display = $commandTester->getDisplay(true); - $this->assertStringContainsString('SQLSTATE', $display); + self::assertStringContainsString('SQLSTATE', $display); return; } @@ -75,7 +72,7 @@ public function testInstallFailsWithInvalidDbConfigWhenAllOptionsArePassedIn() /** * Remove directory made by installer */ - protected function tearDown(): void + public function tearDown(): void { if (is_readable($this->installDir)) { @rmdir($this->installDir); diff --git a/tests/N98/Magento/Command/Installer/InstallCommandTester.php b/tests/N98/Magento/Command/Installer/InstallCommandTester.php index c0154fd80..29989f0b9 100644 --- a/tests/N98/Magento/Command/Installer/InstallCommandTester.php +++ b/tests/N98/Magento/Command/Installer/InstallCommandTester.php @@ -1,7 +1,4 @@ getCommandConfig($commandClass); + $commandConfig = $command->getCommandConfig($commandClass); return $commandConfig['magento-packages']; } /** + * @param InstallCommand $command * @return array */ - public function getSampleDataPackages(InstallCommand $installCommand) + public function getSampleDataPackages(InstallCommand $command) { $commandClass = self::COMMAND_CLASS; - $commandConfig = $installCommand->getCommandConfig($commandClass); + $commandConfig = $command->getCommandConfig($commandClass); return $commandConfig['demo-data-packages']; } } diff --git a/tests/N98/Magento/Command/Installer/UninstallCommandTest.php b/tests/N98/Magento/Command/Installer/UninstallCommandTest.php index 53d63176e..e88dc5fc5 100644 --- a/tests/N98/Magento/Command/Installer/UninstallCommandTest.php +++ b/tests/N98/Magento/Command/Installer/UninstallCommandTest.php @@ -1,7 +1,5 @@ */ -final class UninstallCommandTest extends TestCase +class UninstallCommandTest extends TestCase { /** * Check that Magento is not removed if confirmation is denied @@ -24,21 +22,19 @@ public function testUninstallDoesNotUninstallIfConfirmationDenied() $this->markTestIncomplete('Find a replacement for setInputStream() of old DialogHelper'); $application = $this->getApplication(); $application->add(new UninstallCommand()); - $command = $this->getApplication()->find('uninstall'); $commandTester = new CommandTester($command); $dialog = new QuestionHelper(); $dialog->setInputStream($this->getInputStream('no\n')); - $command->setHelperSet(new HelperSet([$dialog])); $commandTester->execute(['command' => $command->getName(), '--installationFolder' => $this->getTestMagentoRoot()]); - $this->assertSame('Really uninstall ? [n]: ', $commandTester->getDisplay()); + self::assertEquals('Really uninstall ? [n]: ', $commandTester->getDisplay()); //check magento still installed - $this->assertFileExists($this->getTestMagentoRoot() . '/app/etc/local.xml'); + self::assertFileExists($this->getTestMagentoRoot() . '/app/etc/local.xml'); } /** @@ -49,29 +45,28 @@ public function testUninstallForceActuallyRemoves() $this->markTestIncomplete('Find a replacement for setInputStream() of old DialogHelper'); $application = $this->getApplication(); $application->add(new UninstallCommand()); - $command = $this->getApplication()->find('uninstall'); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), '--force' => true, '--installationFolder' => $this->getTestMagentoRoot()], + ['command' => $command->getName(), '--force' => true, '--installationFolder' => $this->getTestMagentoRoot()] ); - $this->assertStringContainsString('Dropped database', $commandTester->getDisplay()); - $this->assertStringContainsString('Remove directory ' . $this->getTestMagentoRoot(), $commandTester->getDisplay()); - $this->assertStringContainsString('Done', $commandTester->getDisplay()); - $this->assertFileDoesNotExist($this->getTestMagentoRoot() . '/app/etc/local.xml'); + self::assertStringContainsString('Dropped database', $commandTester->getDisplay()); + self::assertStringContainsString('Remove directory ' . $this->getTestMagentoRoot(), $commandTester->getDisplay()); + self::assertStringContainsString('Done', $commandTester->getDisplay()); + self::assertFileDoesNotExist($this->getTestMagentoRoot() . '/app/etc/local.xml'); } /** * @param $input * @return resource */ - private function getInputStream($input) + protected function getInputStream($input) { $stream = fopen('php://memory', 'rb+', false); - fwrite($stream, $input); + fputs($stream, $input); rewind($stream); return $stream; } diff --git a/tests/N98/Magento/Command/ListCommandTest.php b/tests/N98/Magento/Command/ListCommandTest.php index d32e7b6fa..afea0d266 100644 --- a/tests/N98/Magento/Command/ListCommandTest.php +++ b/tests/N98/Magento/Command/ListCommandTest.php @@ -1,12 +1,10 @@ execute( - ['command' => 'list'], + ['command' => 'list'] ); - $this->assertStringContainsString(sprintf('n98-magerun %s by valantic CEC', $this->getApplication()->getVersion()), $commandTester->getDisplay()); + self::assertStringContainsString( + sprintf('n98-magerun %s by valantic CEC', $this->getApplication()->getVersion()), + $commandTester->getDisplay() + ); } } diff --git a/tests/N98/Magento/Command/LocalConfig/GenerateCommandTest.php b/tests/N98/Magento/Command/LocalConfig/GenerateCommandTest.php index 5e9105460..90949612c 100644 --- a/tests/N98/Magento/Command/LocalConfig/GenerateCommandTest.php +++ b/tests/N98/Magento/Command/LocalConfig/GenerateCommandTest.php @@ -1,7 +1,5 @@ configFile = sprintf('%s/%s/local.xml', sys_get_temp_dir(), $this->getName()); mkdir(dirname($this->configFile), 0777, true); @@ -38,7 +36,7 @@ protected function setUp(): void copy( sprintf('%s/app/etc/local.xml.template', $this->getTestMagentoRoot()), - sprintf('%s/local.xml.template', dirname($this->configFile)), + sprintf('%s/local.xml.template', dirname($this->configFile)) ); parent::setUp(); @@ -60,11 +58,14 @@ public function testErrorIsPrintedIfConfigFileExists() 'session-save' => 'my_session_save', 'admin-frontname' => 'my_admin_frontname', 'encryption-key' => 'key123456789', - ], + ] ); - $this->assertFileExists($this->configFile); - $this->assertStringContainsString(sprintf('local.xml file already exists in folder "%s/app/etc"', dirname($this->configFile)), $commandTester->getDisplay()); + self::assertFileExists($this->configFile); + self::assertStringContainsString( + sprintf('local.xml file already exists in folder "%s/app/etc"', dirname($this->configFile)), + $commandTester->getDisplay() + ); } public function testErrorIsPrintedIfConfigTemplateNotExists() @@ -82,10 +83,13 @@ public function testErrorIsPrintedIfConfigTemplateNotExists() 'session-save' => 'my_session_save', 'admin-frontname' => 'my_admin_frontname', 'encryption-key' => 'key123456789', - ], + ] ); - $this->assertStringContainsString(sprintf('File %s/local.xml.template does not exist', dirname($this->configFile)), $commandTester->getDisplay()); + self::assertStringContainsString( + sprintf('File %s/local.xml.template does not exist', dirname($this->configFile)), + $commandTester->getDisplay() + ); } public function testErrorIsPrintedIfAppEtcDirNotWriteable() @@ -106,10 +110,13 @@ public function testErrorIsPrintedIfAppEtcDirNotWriteable() 'session-save' => 'my_session_save', 'admin-frontname' => 'my_admin_frontname', 'encryption-key' => 'key123456789', - ], + ] ); - $this->assertStringContainsString(sprintf('Folder %s is not writeable', dirname($this->configFile)), $commandTester->getDisplay()); + self::assertStringContainsString( + sprintf('Folder %s is not writeable', dirname($this->configFile)), + $commandTester->getDisplay() + ); chmod(dirname($this->configFile), $originalMode); } @@ -128,21 +135,21 @@ public function testRandomMd5IsUsedIfNoEncryptionKeyParamPassed() 'db-name' => 'my_db_name', 'session-save' => 'my_session_save', 'admin-frontname' => 'my_admin_frontname', - ], + ] ); - $this->assertFileExists($this->configFile); + self::assertFileExists($this->configFile); $fileContent = \file_get_contents($this->configFile); - $this->assertStringContainsString('', $fileContent); - $this->assertStringContainsString('', $fileContent); - $this->assertStringContainsString('', $fileContent); - $this->assertStringContainsString('', $fileContent); - $this->assertStringContainsString('', $fileContent); - $this->assertStringContainsString('', $fileContent); - $this->assertMatchesRegularExpression('/<\/key>/', $fileContent); + self::assertStringContainsString('', $fileContent); + self::assertStringContainsString('', $fileContent); + self::assertStringContainsString('', $fileContent); + self::assertStringContainsString('', $fileContent); + self::assertStringContainsString('', $fileContent); + self::assertStringContainsString('', $fileContent); + self::assertMatchesRegularExpression('/<\/key>/', $fileContent); $xml = \simplexml_load_file($this->configFile); - $this->assertIsNotBool($xml); + self::assertIsNotBool($xml); } public function testExecuteWithCliParameters() @@ -160,21 +167,21 @@ public function testExecuteWithCliParameters() 'session-save' => 'my_session_save', 'admin-frontname' => 'my_admin_frontname', 'encryption-key' => 'key123456789', - ], + ] ); - $this->assertFileExists($this->configFile); + self::assertFileExists($this->configFile); $fileContent = \file_get_contents($this->configFile); - $this->assertStringContainsString('', $fileContent); - $this->assertStringContainsString('', $fileContent); - $this->assertStringContainsString('', $fileContent); - $this->assertStringContainsString('', $fileContent); - $this->assertStringContainsString('', $fileContent); - $this->assertStringContainsString('', $fileContent); - $this->assertStringContainsString('', $fileContent); + self::assertStringContainsString('', $fileContent); + self::assertStringContainsString('', $fileContent); + self::assertStringContainsString('', $fileContent); + self::assertStringContainsString('', $fileContent); + self::assertStringContainsString('', $fileContent); + self::assertStringContainsString('', $fileContent); + self::assertStringContainsString('', $fileContent); $xml = \simplexml_load_file($this->configFile); - $this->assertIsNotBool($xml); + self::assertIsNotBool($xml); } public function testInteractiveInputUsesDefaultValuesIfNoValueEntered() @@ -193,21 +200,21 @@ public function testInteractiveInputUsesDefaultValuesIfNoValueEntered() ], [ 'interactive' => false, - ], + ] ); - $this->assertFileExists($this->configFile); + self::assertFileExists($this->configFile); $fileContent = \file_get_contents($this->configFile); - $this->assertStringContainsString('', $fileContent); - $this->assertStringContainsString('', $fileContent); - $this->assertStringContainsString('', $fileContent); - $this->assertStringContainsString('', $fileContent); - $this->assertStringContainsString('', $fileContent); - $this->assertStringContainsString('', $fileContent); - $this->assertStringContainsString('', $fileContent); + self::assertStringContainsString('', $fileContent); + self::assertStringContainsString('', $fileContent); + self::assertStringContainsString('', $fileContent); + self::assertStringContainsString('', $fileContent); + self::assertStringContainsString('', $fileContent); + self::assertStringContainsString('', $fileContent); + self::assertStringContainsString('', $fileContent); $xml = \simplexml_load_file($this->configFile); - $this->assertIsNotBool($xml); + self::assertIsNotBool($xml); } /** @@ -238,15 +245,15 @@ public function testRequiredOptionsThrowExceptionIfNotSet($param, $prompt, $defa ->onlyMethods(['ask']) ->getMock(); - $questionHelperMock->expects($this->once()) + $questionHelperMock->expects(self::once()) ->method('ask') ->with( self::isInstanceOf(InputInterface::class), self::isInstanceOf(StreamOutput::class), new Question( sprintf('Please enter the %s: ', $prompt), - $default, - ), + $default + ) ) ->willReturn(null); @@ -261,13 +268,15 @@ public function testRequiredOptionsThrowExceptionIfNotSet($param, $prompt, $defa /** * @return array */ - public function requiredFieldsProvider(): \Iterator + public function requiredFieldsProvider() { - yield ['db-host', 'database host', '']; - yield ['db-user', 'database username', '']; - yield ['db-name', 'database name', '']; - yield ['session-save', 'session save', 'files']; - yield ['admin-frontname', 'admin frontname', 'admin']; + return [ + ['db-host', 'database host', ''], + ['db-user', 'database username', ''], + ['db-name', 'database name', ''], + ['session-save', 'session save', 'files'], + ['admin-frontname', 'admin frontname', 'admin'], + ]; } public function testExecuteInteractively() @@ -296,8 +305,8 @@ public function testExecuteInteractively() self::isInstanceOf(StreamOutput::class), new Question( sprintf('Please enter the %s: ', $prompt), - $default, - ), + $default + ) ) ->willReturn($returnValue); } @@ -307,17 +316,17 @@ public function testExecuteInteractively() $commandTester = new CommandTester($command); $commandTester->execute(['command' => $command->getName()]); - $this->assertFileExists($this->configFile); + self::assertFileExists($this->configFile); $fileContent = \file_get_contents($this->configFile); - $this->assertStringContainsString('', $fileContent); - $this->assertStringContainsString('', $fileContent); - $this->assertStringContainsString('', $fileContent); - $this->assertStringContainsString('', $fileContent); - $this->assertStringContainsString('', $fileContent); - $this->assertStringContainsString('', $fileContent); + self::assertStringContainsString('', $fileContent); + self::assertStringContainsString('', $fileContent); + self::assertStringContainsString('', $fileContent); + self::assertStringContainsString('', $fileContent); + self::assertStringContainsString('', $fileContent); + self::assertStringContainsString('', $fileContent); $xml = \simplexml_load_file($this->configFile); - $this->assertIsNotBool($xml); + self::assertIsNotBool($xml); } public function testIfPasswordOmittedItIsWrittenBlank() @@ -328,12 +337,12 @@ public function testIfPasswordOmittedItIsWrittenBlank() ->onlyMethods(['ask']) ->getMock(); - $questionHelperMock->expects($this->once()) + $questionHelperMock->expects(self::once()) ->method('ask') ->with( self::isInstanceOf(InputInterface::class), self::isInstanceOf(StreamOutput::class), - new Question('Please enter the database password: '), + new Question('Please enter the database password: ') ) ->willReturn(null); @@ -349,21 +358,21 @@ public function testIfPasswordOmittedItIsWrittenBlank() 'session-save' => 'my_session_save', 'admin-frontname' => 'my_admin_frontname', 'encryption-key' => 'key123456789', - ], + ] ); - $this->assertFileExists($this->configFile); + self::assertFileExists($this->configFile); $fileContent = \file_get_contents($this->configFile); - $this->assertStringContainsString('', $fileContent); - $this->assertStringContainsString('', $fileContent); - $this->assertStringContainsString('', $fileContent); - $this->assertStringContainsString('', $fileContent); - $this->assertStringContainsString('', $fileContent); - $this->assertStringContainsString('', $fileContent); - $this->assertStringContainsString('', $fileContent); + self::assertStringContainsString('', $fileContent); + self::assertStringContainsString('', $fileContent); + self::assertStringContainsString('', $fileContent); + self::assertStringContainsString('', $fileContent); + self::assertStringContainsString('', $fileContent); + self::assertStringContainsString('', $fileContent); + self::assertStringContainsString('', $fileContent); $xml = \simplexml_load_file($this->configFile); - $this->assertIsNotBool($xml); + self::assertIsNotBool($xml); } public function testCdataTagIsNotAddedIfPresentInInput() @@ -374,14 +383,14 @@ public function testCdataTagIsNotAddedIfPresentInInput() ->onlyMethods(['ask']) ->getMock(); - $questionHelperMock->expects($this->once()) + $questionHelperMock->expects(self::once()) ->method('ask') ->with( self::isInstanceOf(InputInterface::class), self::isInstanceOf(StreamOutput::class), new Question( - 'Please enter the database host: ', - ), + 'Please enter the database host: ' + ) ) ->willReturn('CDATAdatabasehost'); @@ -397,42 +406,44 @@ public function testCdataTagIsNotAddedIfPresentInInput() 'session-save' => 'my_session_save', 'admin-frontname' => 'my_admin_frontname', 'encryption-key' => 'key123456789', - ], + ] ); - $this->assertFileExists($this->configFile); + self::assertFileExists($this->configFile); $fileContent = \file_get_contents($this->configFile); - $this->assertStringContainsString('', $fileContent); - $this->assertStringContainsString('', $fileContent); - $this->assertStringContainsString('', $fileContent); - $this->assertStringContainsString('', $fileContent); - $this->assertStringContainsString('', $fileContent); - $this->assertStringContainsString('', $fileContent); - $this->assertStringContainsString('', $fileContent); + self::assertStringContainsString('', $fileContent); + self::assertStringContainsString('', $fileContent); + self::assertStringContainsString('', $fileContent); + self::assertStringContainsString('', $fileContent); + self::assertStringContainsString('', $fileContent); + self::assertStringContainsString('', $fileContent); + self::assertStringContainsString('', $fileContent); $xml = \simplexml_load_file($this->configFile); - $this->assertIsNotBool($xml); + self::assertIsNotBool($xml); } - public function testWrapCdata() + /** + * @test unit utility method _wrapCdata + */ + public function wrapCdata() { - $generateCommand = new GenerateCommand(); - $reflectionClass = new ReflectionClass($generateCommand); - $reflectionMethod = $reflectionClass->getMethod('_wrapCData'); - $reflectionMethod->setAccessible(true); - - $sujet = function ($string) use ($reflectionMethod, $generateCommand) { - return $reflectionMethod->invoke($generateCommand, $string); + $command = new GenerateCommand(); + $refl = new ReflectionClass($command); + $method = $refl->getMethod('_wrapCData'); + $method->setAccessible(true); + $sujet = function ($string) use ($method, $command) { + return $method->invoke($command, $string); }; - $this->assertSame('', $sujet(null)); - $this->assertSame('', $sujet('CDATA')); - $this->assertSame('', $sujet(']]')); - $this->assertSame(']]>', $sujet(' with terminator "]]>" inside ')); - $this->assertSame(']]>', $sujet(']]> at the start ')); - $this->assertSame(']]>', $sujet(' at the end ]]>')); + self::assertSame('', $sujet(null)); + self::assertSame('', $sujet('CDATA')); + self::assertSame('', $sujet(']]')); + self::assertSame(']]>', $sujet(' with terminator "]]>" inside ')); + self::assertSame(']]>', $sujet(']]> at the start ')); + self::assertSame(']]>', $sujet(' at the end ]]>')); } - protected function tearDown(): void + public function tearDown(): void { if (file_exists($this->configFile)) { unlink($this->configFile); @@ -441,7 +452,6 @@ protected function tearDown(): void if (file_exists(sprintf('%s/local.xml.template', dirname($this->configFile)))) { unlink(sprintf('%s/local.xml.template', dirname($this->configFile))); } - rmdir(dirname($this->configFile)); } } diff --git a/tests/N98/Magento/Command/MagentoConnect/ListExtensionsCommandTest.php b/tests/N98/Magento/Command/MagentoConnect/ListExtensionsCommandTest.php index 5c7beb7d4..78d53c46e 100644 --- a/tests/N98/Magento/Command/MagentoConnect/ListExtensionsCommandTest.php +++ b/tests/N98/Magento/Command/MagentoConnect/ListExtensionsCommandTest.php @@ -1,14 +1,12 @@ getApplication(); $application->add(new ListExtensionsCommand()); - $command = $this->getApplication()->find('extension:list'); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), 'search' => 'Mage_All_Latest'], + ['command' => $command->getName(), 'search' => 'Mage_All_Latest'] ); - $this->assertContains('Package', $commandTester->getDisplay()); - $this->assertContains('Version', $commandTester->getDisplay()); - $this->assertContains('Mage_All_Latest', $commandTester->getDisplay()); + self::assertContains('Package', $commandTester->getDisplay()); + self::assertContains('Version', $commandTester->getDisplay()); + self::assertContains('Mage_All_Latest', $commandTester->getDisplay()); } } diff --git a/tests/N98/Magento/Command/MagentoConnect/ValidateExtensionCommandTest.php b/tests/N98/Magento/Command/MagentoConnect/ValidateExtensionCommandTest.php index 4174767c7..8b7091a44 100644 --- a/tests/N98/Magento/Command/MagentoConnect/ValidateExtensionCommandTest.php +++ b/tests/N98/Magento/Command/MagentoConnect/ValidateExtensionCommandTest.php @@ -1,14 +1,12 @@ execute( - ['command' => $commandMock->getName(), 'package' => 'Mage_All_Latest', '--include-default' => true], + ['command' => $commandMock->getName(), 'package' => 'Mage_All_Latest', '--include-default' => true] ); $output = $commandTester->getDisplay(); - $this->assertContains('Mage_All_Latest', $output); + self::assertContains('Mage_All_Latest', $output); } } diff --git a/tests/N98/Magento/Command/Media/DumpCommand.php b/tests/N98/Magento/Command/Media/DumpCommand.php index cf321d5be..30b7f37ec 100644 --- a/tests/N98/Magento/Command/Media/DumpCommand.php +++ b/tests/N98/Magento/Command/Media/DumpCommand.php @@ -1,7 +1,5 @@ getApplication(); $application->add(new DumpCommand()); - $command = $this->getApplication()->find('media:dump'); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), 'filename' => tempnam('media_'), '--strip' => true], + ['command' => $command->getName(), 'filename' => tempnam('media_'), '--strip' => true] ); - self::assertStringContainsString('Compress directory', $commandTester->getDisplay()); + self::assertContains('Compress directory', $commandTester->getDisplay()); } } diff --git a/tests/N98/Magento/Command/Script/Repository/ListCommandTest.php b/tests/N98/Magento/Command/Script/Repository/ListCommandTest.php index ae2944b41..ab4bbcf7f 100644 --- a/tests/N98/Magento/Command/Script/Repository/ListCommandTest.php +++ b/tests/N98/Magento/Command/Script/Repository/ListCommandTest.php @@ -1,13 +1,11 @@ setConfig($config); $application->add(new RunCommand()); - $command = $this->getApplication()->find('script:repo:list'); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName()], + ['command' => $command->getName()] ); - $this->assertStringContainsString('Cache Flush Command Test (Hello World)', $commandTester->getDisplay()); - $this->assertStringContainsString('Foo command', $commandTester->getDisplay()); - $this->assertStringContainsString('Bar command', $commandTester->getDisplay()); + self::assertStringContainsString('Cache Flush Command Test (Hello World)', $commandTester->getDisplay()); + self::assertStringContainsString('Foo command', $commandTester->getDisplay()); + self::assertStringContainsString('Bar command', $commandTester->getDisplay()); } } diff --git a/tests/N98/Magento/Command/Script/Repository/RunCommandTest.php b/tests/N98/Magento/Command/Script/Repository/RunCommandTest.php index cf48c7251..e70133a4a 100644 --- a/tests/N98/Magento/Command/Script/Repository/RunCommandTest.php +++ b/tests/N98/Magento/Command/Script/Repository/RunCommandTest.php @@ -1,13 +1,11 @@ setConfig($config); $application->add(new RunCommand()); - $command = $this->getApplication()->find('script:repo:run'); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), 'script' => 'hello-world'], + ['command' => $command->getName(), 'script' => 'hello-world'] ); // Runs sys:info -> Check for any output - $this->assertStringContainsString('Vendors (core)', $commandTester->getDisplay()); + self::assertStringContainsString('Vendors (core)', $commandTester->getDisplay()); - $this->assertStringContainsString($testDir . '/hello-world.magerun', $this->normalizePathSeparators($commandTester->getDisplay())); + self::assertStringContainsString( + $testDir . '/hello-world.magerun', + $this->normalizePathSeparators($commandTester->getDisplay()) + ); } /** diff --git a/tests/N98/Magento/Command/ScriptCommandTest.php b/tests/N98/Magento/Command/ScriptCommandTest.php index 34859f059..d98f992e9 100644 --- a/tests/N98/Magento/Command/ScriptCommandTest.php +++ b/tests/N98/Magento/Command/ScriptCommandTest.php @@ -1,40 +1,37 @@ getApplication(); $application->add(new ScriptCommand()); $application->setAutoExit(false); - $command = $this->getApplication()->find('script'); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), 'filename' => __DIR__ . '/_files/test.mr'], + ['command' => $command->getName(), 'filename' => __DIR__ . '/_files/test.mr'] ); // Check pre defined vars $edition = is_callable(['\Mage', 'getEdition']) ? Mage::getEdition() : 'Community'; - $this->assertStringContainsString('magento.edition: ' . $edition, $commandTester->getDisplay()); - - $this->assertStringContainsString('magento.root: ' . $this->getApplication()->getMagentoRootFolder(), $commandTester->getDisplay()); - $this->assertStringContainsString('magento.version: ' . Mage::getVersion(), $commandTester->getDisplay()); - $this->assertStringContainsString('magerun.version: ' . $this->getApplication()->getVersion(), $commandTester->getDisplay()); - - $this->assertStringContainsString('code', $commandTester->getDisplay()); - $this->assertStringContainsString('foo.sql', $commandTester->getDisplay()); - $this->assertStringContainsString('BAR: foo.sql.gz', $commandTester->getDisplay()); - $this->assertStringContainsString('Magento Websites', $commandTester->getDisplay()); - $this->assertStringContainsString('web/secure/base_url', $commandTester->getDisplay()); - $this->assertStringContainsString('web/seo/use_rewrites => 1', $commandTester->getDisplay()); + self::assertStringContainsString('magento.edition: ' . $edition, $commandTester->getDisplay()); + + self::assertStringContainsString('magento.root: ' . $this->getApplication()->getMagentoRootFolder(), $commandTester->getDisplay()); + self::assertStringContainsString('magento.version: ' . Mage::getVersion(), $commandTester->getDisplay()); + self::assertStringContainsString('magerun.version: ' . $this->getApplication()->getVersion(), $commandTester->getDisplay()); + + self::assertStringContainsString('code', $commandTester->getDisplay()); + self::assertStringContainsString('foo.sql', $commandTester->getDisplay()); + self::assertStringContainsString('BAR: foo.sql.gz', $commandTester->getDisplay()); + self::assertStringContainsString('Magento Websites', $commandTester->getDisplay()); + self::assertStringContainsString('web/secure/base_url', $commandTester->getDisplay()); + self::assertStringContainsString('web/seo/use_rewrites => 1', $commandTester->getDisplay()); } } diff --git a/tests/N98/Magento/Command/System/Check/Settings/CookieDomainCheckAbstractTest.php b/tests/N98/Magento/Command/System/Check/Settings/CookieDomainCheckAbstractTest.php index ecc4d174d..c1f71ffca 100644 --- a/tests/N98/Magento/Command/System/Check/Settings/CookieDomainCheckAbstractTest.php +++ b/tests/N98/Magento/Command/System/Check/Settings/CookieDomainCheckAbstractTest.php @@ -1,7 +1,4 @@ - yield ['http://go/', 'go', false]; - yield ['http://go/', '.go', false]; - yield ['http://go.go/', 'go', false]; - yield ['http://go.go/', '.go', false]; - # ... some edge-cases left out - yield ['http://www.good.go/', '.good.go', true]; - yield ['http://www.good.go/', 'www.good.go', true]; - yield ['http://good.go/', 'www.good.go', false]; - yield ['http://also.good.go/', 'www.good.go', false]; + return [ + ['', '', false], + ['https://www.example.com/', '', false], + ['', '.example.com', false], + ['https://www.example.com/', '.example.com', true], + ['https://www.example.com/', 'www.example.com', true], + ['https://images.example.com/', 'www.example.com', false], + ['https://images.example.com/', 'example.com', true], + ['https://images.example.com/', '.example.com', true], + ['https://example.com/', '.example.com', false], + ['https://www.example.com/', '.www.example.com', false], + ['https://www.example.com/', 'wwww.example.com', false], + ['https://www.example.com/', 'ww.example.com', false], + ['https://www.example.com/', '.ww.example.com', false], + ['https://www.example.com/', '.w.example.com', false], + ['https://www.example.com/', '..example.com', false], + // false-positives we know about, there is no check against public suffix list (the co.uk check) + ['https://www.example.com/', '.com', false], + ['https://www.example.co.uk/', '.co.uk', true], + ['https://www.example.co.uk/', 'co.uk', true], + // go cases + ['http://go/', 'go', false], + ['http://go/', '.go', false], + ['http://go.go/', 'go', false], + ['http://go.go/', '.go', false], + # ... some edge-cases left out + ['http://www.good.go/', '.good.go', true], + ['http://www.good.go/', 'www.good.go', true], + ['http://good.go/', 'www.good.go', false], + ['http://also.good.go/', 'www.good.go', false], + ]; } /** + * @test * @dataProvider provideCookieDomainsAndBaseUrls */ - public function testValidateCookieDomainAgainstUrl($baseUrl, $cookieDomain, $expected) + public function validateCookieDomainAgainstUrl($baseUrl, $cookieDomain, $expected) { /** @var CookieDomainCheckAbstract $stub */ $stub = $this->getMockForAbstractClass(__NAMESPACE__ . '\CookieDomainCheckAbstract'); @@ -67,6 +66,6 @@ public function testValidateCookieDomainAgainstUrl($baseUrl, $cookieDomain, $exp $message = sprintf('%s for %s', $cookieDomain, $baseUrl); - $this->assertSame($expected, $actual, $message); + self::assertSame($expected, $actual, $message); } } diff --git a/tests/N98/Magento/Command/System/CheckCommandTest.php b/tests/N98/Magento/Command/System/CheckCommandTest.php index 7ec36142c..614cc360d 100644 --- a/tests/N98/Magento/Command/System/CheckCommandTest.php +++ b/tests/N98/Magento/Command/System/CheckCommandTest.php @@ -1,28 +1,25 @@ getApplication(); $application->add(new InfoCommand()); - $command = $this->getApplication()->find('sys:check'); $commandTester = new CommandTester($command); $commandTester->execute(['command' => $command->getName()]); - $this->assertMatchesRegularExpression('/SETTINGS/', $commandTester->getDisplay()); - $this->assertMatchesRegularExpression('/FILESYSTEM/', $commandTester->getDisplay()); - $this->assertMatchesRegularExpression('/PHP/', $commandTester->getDisplay()); - $this->assertMatchesRegularExpression('/SECURITY/', $commandTester->getDisplay()); - $this->assertMatchesRegularExpression('/MYSQL/', $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/SETTINGS/', $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/FILESYSTEM/', $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/PHP/', $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/SECURITY/', $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/MYSQL/', $commandTester->getDisplay()); } } diff --git a/tests/N98/Magento/Command/System/Cron/HistoryCommandTest.php b/tests/N98/Magento/Command/System/Cron/HistoryCommandTest.php index ddc2d9eea..26033ff80 100644 --- a/tests/N98/Magento/Command/System/Cron/HistoryCommandTest.php +++ b/tests/N98/Magento/Command/System/Cron/HistoryCommandTest.php @@ -1,26 +1,23 @@ getApplication(); $application->add(new ListCommand()); - $command = $this->getApplication()->find('sys:cron:history'); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName()], + ['command' => $command->getName()] ); - $this->assertMatchesRegularExpression('/Last executed jobs/', $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/Last executed jobs/', $commandTester->getDisplay()); } } diff --git a/tests/N98/Magento/Command/System/Cron/ListCommandTest.php b/tests/N98/Magento/Command/System/Cron/ListCommandTest.php index d0f7f47f4..82f80c1d2 100644 --- a/tests/N98/Magento/Command/System/Cron/ListCommandTest.php +++ b/tests/N98/Magento/Command/System/Cron/ListCommandTest.php @@ -1,24 +1,21 @@ getApplication(); $application->add(new ListCommand()); - $command = $this->getApplication()->find('sys:cron:list'); $commandTester = new CommandTester($command); $commandTester->execute(['command' => $command->getName()]); - $this->assertMatchesRegularExpression('/Cronjob List/', $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/Cronjob List/', $commandTester->getDisplay()); } } diff --git a/tests/N98/Magento/Command/System/Cron/RunCommandTest.php b/tests/N98/Magento/Command/System/Cron/RunCommandTest.php index 1d7efbbf5..158b822c7 100644 --- a/tests/N98/Magento/Command/System/Cron/RunCommandTest.php +++ b/tests/N98/Magento/Command/System/Cron/RunCommandTest.php @@ -1,41 +1,40 @@ getApplication(); $application->add(new ListCommand()); - $command = $this->getApplication()->find('sys:cron:run'); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), 'job' => 'log_clean'], + ['command' => $command->getName(), 'job' => 'log_clean'] ); - $this->assertMatchesRegularExpression('/Run Mage_Log_Model_Cron::logClean done/', $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/Run Mage_Log_Model_Cron::logClean done/', $commandTester->getDisplay()); } - public function testUrlBuildingWhileCron() + /** + * @test + */ + public function urlBuildingWhileCron() { $application = $this->getApplication(); $application->add(new RunCommand()); - $command = $this->getApplication()->find('sys:cron:run'); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), 'job' => 'log_clean'], + ['command' => $command->getName(), 'job' => 'log_clean'] ); - $this->assertMatchesRegularExpression('/Run Mage_Log_Model_Cron::logClean done/', $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/Run Mage_Log_Model_Cron::logClean done/', $commandTester->getDisplay()); } } diff --git a/tests/N98/Magento/Command/System/Cron/ServerEnvironmentTest.php b/tests/N98/Magento/Command/System/Cron/ServerEnvironmentTest.php index 01bc2a9ec..ff7cb3a96 100644 --- a/tests/N98/Magento/Command/System/Cron/ServerEnvironmentTest.php +++ b/tests/N98/Magento/Command/System/Cron/ServerEnvironmentTest.php @@ -1,7 +1,5 @@ getApplication(); - $this->assertInstanceOf(Application::class, $application); + self::assertInstanceOf(Application::class, $application); } - public function testRegression() + /** + * @test that getBaseUrl contains the script-name (here: Phpunit runner) + */ + public function regression() { $store = Mage::app()->getStore(null); $actual = $store->getBaseUrl(Mage_Core_Model_Store::URL_TYPE_LINK); - $this->assertIsString($actual); - $this->assertMatchesRegularExpression('~/(ide-phpunit.php|phpunit)/$~', $actual); + self::assertIsString($actual); + self::assertMatchesRegularExpression('~/(ide-phpunit.php|phpunit)/$~', $actual); } - public function testEnvironmentFix() + /** + * @test + */ + public function environmentFix() { $store = Mage::app()->getStore(null); $store->resetConfig(); - $serverEnvironment = new ServerEnvironment(); - $serverEnvironment->initalize(); + $environment = new ServerEnvironment(); + $environment->initalize(); $actual = $store->getBaseUrl(Mage_Core_Model_Store::URL_TYPE_LINK); - $this->assertIsString($actual); - $this->assertStringEndsWith('/index.php/', $actual); + self::assertIsString($actual); + self::assertStringEndsWith('/index.php/', $actual); $store->resetConfig(); - $serverEnvironment->reset(); + $environment->reset(); $actual = Mage::app()->getStore(null)->getBaseUrl(Mage_Core_Model_Store::URL_TYPE_LINK); - $this->assertIsString($actual); - $this->assertMatchesRegularExpression('~/(ide-phpunit.php|phpunit)/$~', $actual); + self::assertIsString($actual); + self::assertMatchesRegularExpression('~/(ide-phpunit.php|phpunit)/$~', $actual); } } diff --git a/tests/N98/Magento/Command/System/InfoCommandTest.php b/tests/N98/Magento/Command/System/InfoCommandTest.php index 17807476e..e0515f9f4 100644 --- a/tests/N98/Magento/Command/System/InfoCommandTest.php +++ b/tests/N98/Magento/Command/System/InfoCommandTest.php @@ -1,34 +1,31 @@ getApplication(); $application->add(new InfoCommand()); - $command = $this->getApplication()->find('sys:info'); $commandTester = new CommandTester($command); $commandTester->execute(['command' => $command->getName()]); - $this->assertMatchesRegularExpression('/Magento System Information/', $commandTester->getDisplay()); - $this->assertMatchesRegularExpression('/Install Date/', $commandTester->getDisplay()); - $this->assertMatchesRegularExpression('/Crypt Key/', $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/Magento System Information/', $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/Install Date/', $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/Crypt Key/', $commandTester->getDisplay()); // Settings argument $commandTester->execute( - ['command' => $command->getName(), 'key' => 'version'], + ['command' => $command->getName(), 'key' => 'version'] ); $commandResult = $commandTester->getDisplay(); - $this->assertMatchesRegularExpression('/\d+\.\d+\.\d+/', $commandResult); + self::assertMatchesRegularExpression('/\d+\.\d+\.\d+/', $commandResult); } } diff --git a/tests/N98/Magento/Command/System/MaintenanceCommandTest.php b/tests/N98/Magento/Command/System/MaintenanceCommandTest.php index 10047f40d..903249799 100644 --- a/tests/N98/Magento/Command/System/MaintenanceCommandTest.php +++ b/tests/N98/Magento/Command/System/MaintenanceCommandTest.php @@ -1,19 +1,16 @@ getApplication(); $application->add(new MaintenanceCommand()); - $command = $application->find('sys:maintenance'); $magentoRootFolder = $application->getMagentoRootFolder(); @@ -23,15 +20,15 @@ public function testExecute() $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), '--on' => ''], + ['command' => $command->getName(), '--on' => ''] ); - $this->assertMatchesRegularExpression('/Maintenance mode on/', $commandTester->getDisplay()); - $this->assertFileExists($magentoRootFolder . '/maintenance.flag'); + self::assertMatchesRegularExpression('/Maintenance mode on/', $commandTester->getDisplay()); + self::assertFileExists($magentoRootFolder . '/maintenance.flag'); $commandTester->execute( - ['command' => $command->getName(), '--off' => ''], + ['command' => $command->getName(), '--off' => ''] ); - $this->assertMatchesRegularExpression('/Maintenance mode off/', $commandTester->getDisplay()); - $this->assertFileDoesNotExist($magentoRootFolder . '/maintenance.flag'); + self::assertMatchesRegularExpression('/Maintenance mode off/', $commandTester->getDisplay()); + self::assertFileDoesNotExist($magentoRootFolder . '/maintenance.flag'); } } diff --git a/tests/N98/Magento/Command/System/Setup/ChangeVersionCommandTest.php b/tests/N98/Magento/Command/System/Setup/ChangeVersionCommandTest.php index cdc6512f7..a52f7b7ba 100644 --- a/tests/N98/Magento/Command/System/Setup/ChangeVersionCommandTest.php +++ b/tests/N98/Magento/Command/System/Setup/ChangeVersionCommandTest.php @@ -1,15 +1,12 @@ setMethods(['_getResourceSingleton']) ->getMock(); - $mock = $this->getMockBuilder(Mage_Core_Model_Resource_Db_Collection_Abstract::class) + $resourceModel = $this->getMockBuilder('\Mage_Core_Model_Resource_Resource') ->disableOriginalConstructor() ->setMethods(['setDbVersion', 'setDataVersion']) ->getMock(); $command - ->expects($this->once()) + ->expects(self::once()) ->method('_getResourceSingleton') - ->willReturn($mock); + ->willReturn($resourceModel); - $mock - ->expects($this->once()) + $resourceModel + ->expects(self::once()) ->method('setDbVersion') ->with('weee_setup', '1.6.0.0'); - $mock - ->expects($this->once()) + $resourceModel + ->expects(self::once()) ->method('setDataVersion') ->with('weee_setup', '1.6.0.0'); $application = $this->getApplication(); $application->add($command); - $command = $this->getApplication()->find('sys:setup:change-version'); $commandTester = new CommandTester($command); $commandTester->execute(['command' => $command->getName(), 'module' => 'Mage_Weee', 'version' => '1.6.0.0']); - $this->assertStringContainsString('Successfully updated: "Mage_Weee" - "weee_setup" to version: "1.6.0.0"', $commandTester->getDisplay()); + self::assertStringContainsString( + 'Successfully updated: "Mage_Weee" - "weee_setup" to version: "1.6.0.0"', + $commandTester->getDisplay() + ); } public function testUpdateBySetupName() @@ -54,48 +53,49 @@ public function testUpdateBySetupName() ->setMethods(['_getResourceSingleton']) ->getMock(); - $mock = $this->getMockBuilder(Mage_Core_Model_Resource_Db_Collection_Abstract::class) + $resourceModel = $this->getMockBuilder('\Mage_Core_Model_Resource_Resource') ->disableOriginalConstructor() ->setMethods(['setDbVersion', 'setDataVersion']) ->getMock(); $command - ->expects($this->once()) + ->expects(self::once()) ->method('_getResourceSingleton') - ->willReturn($mock); + ->willReturn($resourceModel); - $mock - ->expects($this->once()) + $resourceModel + ->expects(self::once()) ->method('setDbVersion') ->with('weee_setup', '1.6.0.0'); - $mock - ->expects($this->once()) + $resourceModel + ->expects(self::once()) ->method('setDataVersion') ->with('weee_setup', '1.6.0.0'); $application = $this->getApplication(); $application->add($command); - $command = $this->getApplication()->find('sys:setup:change-version'); $commandTester = new CommandTester($command); $commandTester->execute(['command' => $command->getName(), 'module' => 'Mage_Weee', 'version' => '1.6.0.0', 'setup' => 'weee_setup']); - $this->assertStringContainsString('Successfully updated: "Mage_Weee" - "weee_setup" to version: "1.6.0.0"', $commandTester->getDisplay()); + self::assertStringContainsString( + 'Successfully updated: "Mage_Weee" - "weee_setup" to version: "1.6.0.0"', + $commandTester->getDisplay() + ); } public function testSetupNameNotFound() { $application = $this->getApplication(); $application->add(new ChangeVersionCommand()); - $command = $this->getApplication()->find('sys:setup:change-version'); $commandTester = new CommandTester($command); $this->expectException( - InvalidArgumentException::class, + InvalidArgumentException::class ); $commandTester->execute(['command' => $command->getName(), 'module' => 'Mage_Weee', 'version' => '1.6.0.0', 'setup' => 'no_setup_exists']); @@ -105,7 +105,6 @@ public function testModuleDoesNotExist() { $application = $this->getApplication(); $application->add(new ChangeVersionCommand()); - $command = $this->getApplication()->find('sys:setup:change-version'); $commandTester = new CommandTester($command); @@ -120,19 +119,21 @@ public function testCommandReturnsEarlyIfNoSetupResourcesForModule() ->setMethods(['getModuleSetupResources']) ->getMock(); - $command->expects($this->once()) + $command->expects(self::once()) ->method('getModuleSetupResources') ->with('Mage_Weee') ->willReturn([]); $application = $this->getApplication(); $application->add($command); - $command = $this->getApplication()->find('sys:setup:change-version'); $commandTester = new CommandTester($command); $commandTester->execute(['command' => $command->getName(), 'module' => 'Mage_Weee', 'version' => '1.0.0.0', 'setup' => 'weee_setup']); - $this->assertStringContainsString('No setup resources found for module: "Mage_Weee"', $commandTester->getDisplay()); + self::assertStringContainsString( + 'No setup resources found for module: "Mage_Weee"', + $commandTester->getDisplay() + ); } } diff --git a/tests/N98/Magento/Command/System/Setup/CompareVersionsCommandTest.php b/tests/N98/Magento/Command/System/Setup/CompareVersionsCommandTest.php index bf03d64e9..b1c63f21c 100644 --- a/tests/N98/Magento/Command/System/Setup/CompareVersionsCommandTest.php +++ b/tests/N98/Magento/Command/System/Setup/CompareVersionsCommandTest.php @@ -1,32 +1,29 @@ getApplication(); $application->add(new CompareVersionsCommand()); - $command = $this->getApplication()->find('sys:setup:compare-versions'); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName()], + ['command' => $command->getName()] ); - $this->assertMatchesRegularExpression('/Setup/', $commandTester->getDisplay()); - $this->assertMatchesRegularExpression('/Module/', $commandTester->getDisplay()); - $this->assertMatchesRegularExpression('/DB/', $commandTester->getDisplay()); - $this->assertMatchesRegularExpression('/Data/', $commandTester->getDisplay()); - $this->assertMatchesRegularExpression('/Status/', $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/Setup/', $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/Module/', $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/DB/', $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/Data/', $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/Status/', $commandTester->getDisplay()); } public function testJunit() @@ -34,14 +31,13 @@ public function testJunit() vfsStream::setup(); $application = $this->getApplication(); $application->add(new CompareVersionsCommand()); - $command = $this->getApplication()->find('sys:setup:compare-versions'); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName(), '--log-junit' => vfsStream::url('root/junit.xml')], + ['command' => $command->getName(), '--log-junit' => vfsStream::url('root/junit.xml')] ); - $this->assertFileExists(vfsStream::url('root/junit.xml')); + self::assertFileExists(vfsStream::url('root/junit.xml')); } } diff --git a/tests/N98/Magento/Command/System/Setup/IncrementalCommandStub.php b/tests/N98/Magento/Command/System/Setup/IncrementalCommandStub.php index 43df42d59..a6bf48c89 100644 --- a/tests/N98/Magento/Command/System/Setup/IncrementalCommandStub.php +++ b/tests/N98/Magento/Command/System/Setup/IncrementalCommandStub.php @@ -1,30 +1,30 @@ + */ namespace N98\Magento\Command\System\Setup; -use ReflectionException; - /** * Class IncrementalCommandStub - * - * @author Tom Klingenberg */ class IncrementalCommandStub extends IncrementalCommand { /** @noinspection MagicMethodsValidityInspection */ - public function __construct() + public function __construct($name = null) { // missing parent constructor call by intention } /** + * @param string $method * @param object|string $object - * @return array|string - * @throws ReflectionException + * @param array $args + * @return mixed */ - public function callProtectedMethodFromObject(string $method, $object, array $args = []) + public function callProtectedMethodFromObject($method, $object, $args = []) { return $this->_callProtectedMethodFromObject($method, $object, $args); } diff --git a/tests/N98/Magento/Command/System/Setup/IncrementalCommandTest.php b/tests/N98/Magento/Command/System/Setup/IncrementalCommandTest.php index 45207a623..f547589ef 100644 --- a/tests/N98/Magento/Command/System/Setup/IncrementalCommandTest.php +++ b/tests/N98/Magento/Command/System/Setup/IncrementalCommandTest.php @@ -1,7 +1,5 @@ callProtectedMethodFromObject('protectedMethod', $this, ['fooBar']); - $this->assertSame('barBaz', $actual); + $actual = $stub->callProtectedMethodFromObject('protectedMethod', $this, ['fooBar']); + self::assertSame('barBaz', $actual); } - public function protectedMethod($arg): string + protected function protectedMethod($arg) { - $this->assertSame('fooBar', $arg); + self::assertSame('fooBar', $arg); $this->addToAssertionCount(1); return 'barBaz'; diff --git a/tests/N98/Magento/Command/System/Setup/RemoveCommandTest.php b/tests/N98/Magento/Command/System/Setup/RemoveCommandTest.php index f8bcce466..3951ad62e 100644 --- a/tests/N98/Magento/Command/System/Setup/RemoveCommandTest.php +++ b/tests/N98/Magento/Command/System/Setup/RemoveCommandTest.php @@ -1,90 +1,83 @@ */ -final class RemoveCommandTest extends TestCase +class RemoveCommandTest extends TestCase { public function testRemoveModule() { - $mockAdapter = $this->getMockBuilder(Varien_Db_Adapter_Pdo_Mysql::class) + $mockAdapter = $this->getMockBuilder('\Varien_Db_Adapter_Pdo_Mysql') ->disableOriginalConstructor() ->setMethods(['delete']) ->getMock(); - $mockAdapter->expects($this->once()) + $mockAdapter->expects(self::once()) ->method('delete') ->willReturn(1); - $coreResource = $this->getMockBuilder(Mage_Core_Model_Resource::class) - ->setMethods(['getConnection']) - ->getMock(); - - $coreResource->expects($this->once()) + $coreResource = $this->createMock(\Mage_Core_Model_Resource::class); + $coreResource->expects(self::once()) ->method('getConnection') ->willReturn($mockAdapter); $command = $this->getMockBuilder(RemoveCommand::class) - ->setMethods(['getMageCoreResource']) + ->setMethods(['_getModel']) ->getMock(); - $command->expects($this->once()) - ->method('getMageCoreResource') + $command->expects(self::once()) + ->method('_getModel') + ->with('core/resource') ->willReturn($coreResource); $application = $this->getApplication(); $application->add($command); - $command = $this->getApplication()->find('sys:setup:remove'); $commandTester = new CommandTester($command); $commandTester->execute(['command' => $command->getName(), 'module' => 'Mage_Weee']); - $this->assertStringContainsString('Successfully removed setup resource: "weee_setup" from module: "Mage_Weee"', $commandTester->getDisplay()); + self::assertStringContainsString( + 'Successfully removed setup resource: "weee_setup" from module: "Mage_Weee"', + $commandTester->getDisplay() + ); } public function testRemoveBySetupName() { - $mockAdapter = $this->getMockBuilder(Varien_Db_Adapter_Pdo_Mysql::class) + $mockAdapter = $this->getMockBuilder('\Varien_Db_Adapter_Pdo_Mysql') ->disableOriginalConstructor() ->setMethods(['delete']) ->getMock(); - $mockAdapter->expects($this->once()) + $mockAdapter->expects(self::once()) ->method('delete') ->willReturn(1); - $coreResource = $this->getMockBuilder(Mage_Core_Model_Resource::class) - ->setMethods(['getConnection']) - ->getMock(); - - $coreResource->expects($this->once()) + $coreResource = $this->createMock('\Mage_Core_Model_Resource'); + $coreResource->expects(self::once()) ->method('getConnection') ->willReturn($mockAdapter); $command = $this->getMockBuilder(RemoveCommand::class) - ->setMethods(['getMageCoreResource']) + ->setMethods(['_getModel']) ->getMock(); - $command->expects($this->once()) - ->method('getMageCoreResource') + $command->expects(self::once()) + ->method('_getModel') + ->with('core/resource') ->willReturn($coreResource); $application = $this->getApplication(); $application->add($command); - $command = $this->getApplication()->find('sys:setup:remove'); $commandTester = new CommandTester($command); @@ -94,63 +87,65 @@ public function testRemoveBySetupName() 'setup' => 'weee_setup', ]); - $this->assertStringContainsString('Successfully removed setup resource: "weee_setup" from module: "Mage_Weee"', $commandTester->getDisplay()); + self::assertStringContainsString( + 'Successfully removed setup resource: "weee_setup" from module: "Mage_Weee"', + $commandTester->getDisplay() + ); } public function testRemoveBySetupNameFailure() { - $mockAdapter = $this->getMockBuilder(Varien_Db_Adapter_Pdo_Mysql::class) + $mockAdapter = $this->getMockBuilder('\Varien_Db_Adapter_Pdo_Mysql') ->disableOriginalConstructor() ->setMethods(['delete']) ->getMock(); - $mockAdapter->expects($this->once()) + $mockAdapter->expects(self::once()) ->method('delete') ->willReturn(0); - $coreResource = $this->getMockBuilder(Mage_Core_Model_Resource::class) - ->setMethods(['getConnection', 'getTableName']) - ->getMock(); - - $coreResource->expects($this->once()) + $coreResource = $this->createMock('\Mage_Core_Model_Resource'); + $coreResource->expects(self::once()) ->method('getConnection') ->willReturn($mockAdapter); - $coreResource->expects($this->once()) + $coreResource->expects(self::once()) ->method('getTableName') ->with('core_resource') ->willReturn('core_resource'); $command = $this->getMockBuilder(RemoveCommand::class) - ->setMethods(['getMageCoreResource']) + ->setMethods(['_getModel']) ->getMock(); - $command->expects($this->once()) - ->method('getMageCoreResource') + $command->expects(self::once()) + ->method('_getModel') + ->with('core/resource') ->willReturn($coreResource); $application = $this->getApplication(); $application->add($command); - $command = $this->getApplication()->find('sys:setup:remove'); $commandTester = new CommandTester($command); $commandTester->execute(['command' => $command->getName(), 'module' => 'Mage_Weee', 'setup' => 'weee_setup']); - $this->assertStringContainsString('No entry was found for setup resource: "weee_setup" in module: "Mage_Weee"', $commandTester->getDisplay()); + self::assertStringContainsString( + 'No entry was found for setup resource: "weee_setup" in module: "Mage_Weee"', + $commandTester->getDisplay() + ); } public function testSetupNameNotFound() { $application = $this->getApplication(); $application->add(new RemoveCommand()); - $command = $this->getApplication()->find('sys:setup:remove'); $commandTester = new CommandTester($command); $this->expectException( - InvalidArgumentException::class, + InvalidArgumentException::class ); $commandTester->execute(['command' => $command->getName(), 'module' => 'Mage_Weee', 'setup' => 'no_setup_exists']); @@ -160,7 +155,6 @@ public function testModuleDoesNotExist() { $application = $this->getApplication(); $application->add(new RemoveCommand()); - $command = $this->getApplication()->find('sys:setup:remove'); $commandTester = new CommandTester($command); @@ -175,14 +169,13 @@ public function testCommandReturnsEarlyIfNoSetupResourcesForModule() ->setMethods(['getModuleSetupResources']) ->getMock(); - $command->expects($this->once()) + $command->expects(self::once()) ->method('getModuleSetupResources') ->with('Mage_Weee') ->willReturn([]); $application = $this->getApplication(); $application->add($command); - $command = $this->getApplication()->find('sys:setup:remove'); $commandTester = new CommandTester($command); @@ -192,6 +185,9 @@ public function testCommandReturnsEarlyIfNoSetupResourcesForModule() 'setup' => 'weee_setup', ]); - $this->assertStringContainsString('No setup resources found for module: "Mage_Weee"', $commandTester->getDisplay()); + self::assertStringContainsString( + 'No setup resources found for module: "Mage_Weee"', + $commandTester->getDisplay() + ); } } diff --git a/tests/N98/Magento/Command/System/Setup/RunCommandTest.php b/tests/N98/Magento/Command/System/Setup/RunCommandTest.php index 8fc711047..2219388cb 100644 --- a/tests/N98/Magento/Command/System/Setup/RunCommandTest.php +++ b/tests/N98/Magento/Command/System/Setup/RunCommandTest.php @@ -1,26 +1,23 @@ getApplication(); $application->add(new CompareVersionsCommand()); - $command = $this->getApplication()->find('sys:setup:run'); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName()], + ['command' => $command->getName()] ); - $this->assertMatchesRegularExpression('/done/', $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/done/', $commandTester->getDisplay()); } } diff --git a/tests/N98/Magento/Command/System/Store/Config/BaseUrlListCommandTest.php b/tests/N98/Magento/Command/System/Store/Config/BaseUrlListCommandTest.php index bbf95a68d..4d5434f87 100644 --- a/tests/N98/Magento/Command/System/Store/Config/BaseUrlListCommandTest.php +++ b/tests/N98/Magento/Command/System/Store/Config/BaseUrlListCommandTest.php @@ -1,27 +1,24 @@ getApplication(); $application->add(new BaseUrlListCommand()); - $command = $this->getApplication()->find('sys:store:config:base-url:list'); $commandTester = new CommandTester($command); $commandTester->execute( - ['command' => $command->getName()], + ['command' => $command->getName()] ); - $this->assertMatchesRegularExpression('/secure_baseurl/', $commandTester->getDisplay()); - $this->assertMatchesRegularExpression('/unsecure_baseurl/', $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/secure_baseurl/', $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/unsecure_baseurl/', $commandTester->getDisplay()); } } diff --git a/tests/N98/Magento/Command/System/Store/ListCommandTest.php b/tests/N98/Magento/Command/System/Store/ListCommandTest.php index baee7938b..baf953137 100644 --- a/tests/N98/Magento/Command/System/Store/ListCommandTest.php +++ b/tests/N98/Magento/Command/System/Store/ListCommandTest.php @@ -1,25 +1,22 @@ getApplication(); $application->add(new ListCommand()); - $command = $this->getApplication()->find('sys:store:list'); $commandTester = new CommandTester($command); $commandTester->execute(['command' => $command->getName()]); - $this->assertMatchesRegularExpression('/id/', $commandTester->getDisplay()); - $this->assertMatchesRegularExpression('/code/', $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/id/', $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/code/', $commandTester->getDisplay()); } } diff --git a/tests/N98/Magento/Command/System/Url/ListCommandTest.php b/tests/N98/Magento/Command/System/Url/ListCommandTest.php index a05f6b44d..b6166ee7e 100644 --- a/tests/N98/Magento/Command/System/Url/ListCommandTest.php +++ b/tests/N98/Magento/Command/System/Url/ListCommandTest.php @@ -1,19 +1,16 @@ getApplication(); $application->add(new ListCommand()); - $command = $this->getApplication()->find('sys:url:list'); $commandTester = new CommandTester($command); @@ -26,11 +23,11 @@ public function testExecute() '--add-categories' => true, '--add-products' => true, '--add-cmspages' => true, - ], + ] ); - $this->assertMatchesRegularExpression('/prefix/', $commandTester->getDisplay()); - $this->assertMatchesRegularExpression('/http/', $commandTester->getDisplay()); - $this->assertMatchesRegularExpression('/suffix/', $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/prefix/', $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/http/', $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/suffix/', $commandTester->getDisplay()); } } diff --git a/tests/N98/Magento/Command/System/Website/ListCommandTest.php b/tests/N98/Magento/Command/System/Website/ListCommandTest.php index 9ad2c5a86..3027e9341 100644 --- a/tests/N98/Magento/Command/System/Website/ListCommandTest.php +++ b/tests/N98/Magento/Command/System/Website/ListCommandTest.php @@ -1,26 +1,23 @@ getApplication(); $application->add(new ListCommand()); - $command = $this->getApplication()->find('sys:website:list'); $commandTester = new CommandTester($command); $commandTester->execute(['command' => $command->getName()]); - $this->assertMatchesRegularExpression('/Magento Websites/', $commandTester->getDisplay()); - $this->assertMatchesRegularExpression('/id/', $commandTester->getDisplay()); - $this->assertMatchesRegularExpression('/code/', $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/Magento Websites/', $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/id/', $commandTester->getDisplay()); + self::assertMatchesRegularExpression('/code/', $commandTester->getDisplay()); } } diff --git a/tests/N98/Magento/Command/TestCase.php b/tests/N98/Magento/Command/TestCase.php index a04cd171b..7bed51752 100644 --- a/tests/N98/Magento/Command/TestCase.php +++ b/tests/N98/Magento/Command/TestCase.php @@ -1,7 +1,5 @@ $command] : $command; + if (is_string($command)) { + $input = ['command' => $command]; + } else { + $input = $command; + } $hash = md5(json_encode($input, JSON_THROW_ON_ERROR)); if (!isset($this->testers[$hash])) { @@ -95,7 +97,7 @@ protected function assertDisplayContains($command, $needle, $message = '') { $display = $this->getMagerunTester($command)->getDisplay(); - $this->assertStringContainsString($needle, $display, $message); + self::assertStringContainsString($needle, $display, $message); } /** @@ -107,7 +109,7 @@ protected function assertDisplayNotContains($command, $needle, $message = '') { $display = $this->getMagerunTester($command)->getDisplay(); - $this->assertStringNotContainsString($needle, $display, $message); + self::assertStringNotContainsString($needle, $display, $message); } /** @@ -119,7 +121,7 @@ protected function assertDisplayRegExp($command, $pattern, $message = '') { $display = $this->getMagerunTester($command)->getDisplay(); - $this->assertMatchesRegularExpression($pattern, $display, $message); + self::assertMatchesRegularExpression($pattern, $display, $message); } /** @@ -131,17 +133,17 @@ protected function assertDisplayRegExp($command, $pattern, $message = '') */ protected function assertExecute($command, $message = '') { - $magerunCommandTester = $this->getMagerunTester($command); - $status = $magerunCommandTester->getStatus(); + $tester = $this->getMagerunTester($command); + $status = $tester->getStatus(); - if (strlen($message) !== 0) { + if (strlen($message)) { $message .= "\n"; } $message .= 'Command executes with a status code of zero'; - $this->assertSame(0, $status, $message); + self::assertSame(0, $status, $message); - return $magerunCommandTester; + return $tester; } } diff --git a/tests/N98/Magento/DbSettingsTest.php b/tests/N98/Magento/DbSettingsTest.php index 5c8819f75..e238066a3 100644 --- a/tests/N98/Magento/DbSettingsTest.php +++ b/tests/N98/Magento/DbSettingsTest.php @@ -1,7 +1,4 @@ getTestMagentoRoot() . '/app/etc/local.xml'; - $dbSettings = new DbSettings($file); - $this->assertInstanceOf(__NAMESPACE__ . '\\DbSettings', $dbSettings); + $settings = new DbSettings($file); + self::assertInstanceOf(__NAMESPACE__ . '\\DbSettings', $settings); } - public function testSettings() + /** + * @test + */ + public function settings() { $file = __DIR__ . '/local.xml'; - $dbSettings = new DbSettings($file); + $settings = new DbSettings($file); - $this->assertSame('', $dbSettings->getTablePrefix()); + self::assertSame('', $settings->getTablePrefix()); - $this->assertSame('localhost', $dbSettings->getHost()); - $this->assertNull($dbSettings->getPort()); + self::assertSame('localhost', $settings->getHost()); + self::assertNull($settings->getPort()); - $this->assertNull($dbSettings->getUnixSocket()); + self::assertNull($settings->getUnixSocket()); - $this->assertSame('user', $dbSettings->getUsername()); - $this->assertSame('pass', $dbSettings->getPassword()); + self::assertSame('user', $settings->getUsername()); + self::assertSame('pass', $settings->getPassword()); // DbSettings is more strict here, only using known DSN settings, see @link http://php.net/ref.pdo-mysql.connection // minus those settings that are black-listed: dbname, charset // "mysql:host=localhost;initStatements=SET NAMES utf8;model=mysql4;type=pdo_mysql;pdoType=;active=1;prefix=" - $this->assertSame('mysql:host=localhost', $dbSettings->getDsn()); + self::assertEquals('mysql:host=localhost', $settings->getDsn()); } - public function testArrayAccess() + /** + * @test + */ + public function arrayAccess() { $file = __DIR__ . '/local.xml'; - $dbSettings = new DbSettings($file); + $settings = new DbSettings($file); - $this->assertSame('user', $dbSettings['username']); - $this->assertSame('pass', $dbSettings['password']); + self::assertSame('user', $settings['username']); + self::assertSame('pass', $settings['password']); // unix_socket should be NULL - $this->assertNull($dbSettings['unix_socket']); + self::assertNull($settings['unix_socket']); // it's still leaky: - $this->assertInstanceOf(SimpleXMLElement::class, $dbSettings['pdoType']); + self::assertInstanceOf(SimpleXMLElement::class, $settings['pdoType']); } } diff --git a/tests/N98/Magento/MagerunCommandTester.php b/tests/N98/Magento/MagerunCommandTester.php index 4717d3065..efac9c199 100644 --- a/tests/N98/Magento/MagerunCommandTester.php +++ b/tests/N98/Magento/MagerunCommandTester.php @@ -1,7 +1,5 @@ assertArrayHasKey('command', $input); $testCase->assertIsString($input['command']); - $this->commandName = $input['command']; $this->input = $input; } @@ -88,7 +86,7 @@ public function getStatus() private function getExecutedCommandTester() { $commandTester = $this->getCommandTester(); - if ($this->status === null) { + if (!isset($this->status)) { $this->status = $commandTester->execute($this->input); } @@ -101,7 +99,7 @@ private function getExecutedCommandTester() private function getCommandTester() { $command = null; - if ($this->commandTester !== null) { + if (isset($this->commandTester)) { return $this->commandTester; } @@ -124,12 +122,12 @@ private function getCommandInternal() $test->assertSame( $command->getName(), $this->commandName, - 'Verifying that test is done against main command name', + 'Verifying that test is done against main command name' ); if (!$command instanceof Command) { throw new InvalidArgumentException( - sprintf('Command "%s" is not a console command', $this->commandName), + sprintf('Command "%s" is not a console command', $this->commandName) ); } diff --git a/tests/N98/Magento/ModulesTest.php b/tests/N98/Magento/ModulesTest.php index 9ebba0fb4..60072186d 100644 --- a/tests/N98/Magento/ModulesTest.php +++ b/tests/N98/Magento/ModulesTest.php @@ -1,7 +1,4 @@ assertInstanceOf(__NAMESPACE__ . '\Modules', $modules); + self::assertInstanceOf(__NAMESPACE__ . '\Modules', $modules); } - public function testFilteringCountAndIterating() + /** + * @test + */ + public function filteringCountAndIterating() { $modules = new Modules(); $result = $modules->filterModules( - $this->filter(), + $this->filter() ); - $this->assertInstanceOf(__NAMESPACE__ . '\Modules', $result); - $this->assertCount(0, $result); - $this->assertCount(0, iterator_to_array($result)); + self::assertInstanceOf(__NAMESPACE__ . '\Modules', $result); + self::assertCount(0, $result); + self::assertCount(0, iterator_to_array($result)); } - public function testFindInstalledModulesAndFilterThem() + /** + * @test + */ + public function findInstalledModulesAndFilterThem() { $this->getApplication()->initMagento(); $modules = new Modules(); - $this->assertCount(0, $modules); + self::assertCount(0, $modules); $total = count($modules->findInstalledModules()); - $this->assertGreaterThan(10, $total); + self::assertGreaterThan(10, $total); $filtered = $modules->filterModules($this->filter('codepool', 'core')); - $this->assertLessThan($total, count($filtered)); + self::assertLessThan($total, count($filtered)); $filtered = $modules->filterModules($this->filter('status', 'active')); - $this->assertLessThan($total, count($filtered)); + self::assertLessThan($total, count($filtered)); $filtered = $modules->filterModules($this->filter('vendor', 'Mage_')); - $this->assertLessThan($total, count($filtered)); + self::assertLessThan($total, count($filtered)); } /** @@ -76,19 +82,18 @@ private function filter($option = null, $value = null) if (!array_key_exists($option, $defaultOptions)) { throw new InvalidArgumentException(sprintf('Invalid option "%s"', $option)); } - $options[$option] = $value; } /** @var $input PHPUnit_Framework_MockObject_MockObject|ArrayInput */ - $mock = $this->getMockBuilder(ArrayInput::class) + $input = $this->getMockBuilder(ArrayInput::class) ->disableOriginalConstructor() ->setMethods(['getOption']) ->getMock(); $i = 0; foreach ($options as $opt => $val) { - $mock + $input ->expects(self::at($i++)) ->method('getOption') ->with($opt) @@ -98,12 +103,12 @@ private function filter($option = null, $value = null) continue; } - $mock->expects(self::at($i++)) + $input->expects(self::at($i++)) ->method('getOption') ->with($opt) ->willReturn($val); } - return $mock; + return $input; } } diff --git a/tests/N98/Magento/TestApplication.php b/tests/N98/Magento/TestApplication.php index 33f9b7f4f..4387b86ad 100644 --- a/tests/N98/Magento/TestApplication.php +++ b/tests/N98/Magento/TestApplication.php @@ -1,6 +1,9 @@ + */ namespace N98\Magento; @@ -14,43 +17,57 @@ * Magento test-application, the one used in unit and integration testing. * * @package N98\Magento - * - * @author Tom Klingenberg */ class TestApplication { - private ?Application $application = null; + /** + * @var Application + */ + private $application; - private ?string $root = null; + /** + * @var string|null + */ + private $root; - private ?string $varName; + /** + * @var string + */ + private $varname; - private ?string $baseName; + /** + * @var string + */ + private $basename; - private TestCase $testCase; + /** + * @var TestCase + */ + private $testCase; /** - * @param string $varName name of the environment variable containing the test-root - * @param string $baseName name of the stop file containing the test-root + * @param string $varname name of the environment variable containing the test-root + * @param string $basename name of the stopfile containing the test-root + * + * @return string|null */ - public static function getTestMagentoRootFromEnvironment(string $varName, string $baseName): ?string + public static function getTestMagentoRootFromEnvironment($varname, $basename) { - $root = getenv($varName); - if (empty($root) && strlen($baseName)) { - $stopFile = getcwd() . '/' . $baseName; - if (is_readable($stopFile) && $buffer = rtrim(file_get_contents($stopFile))) { + $root = getenv($varname); + if (empty($root) && strlen($basename)) { + $stopfile = getcwd() . '/' . $basename; + if (is_readable($stopfile) && $buffer = rtrim(file_get_contents($stopfile))) { $root = $buffer; } } - if (empty($root)) { - return null; + return; } # directory test if (!is_dir($root)) { throw new RuntimeException( - sprintf("%s path '%s' is not a directory (cwd: '%s', stopfile: '%s')", $varName, $root, getcwd(), $stopFile ?? ''), + sprintf("%s path '%s' is not a directory (cwd: '%s', stopfile: '%s')", $varname, $root, getcwd(), $stopfile ?? '') ); } @@ -58,22 +75,28 @@ public static function getTestMagentoRootFromEnvironment(string $varName, string $rootRealpath = realpath($root); if (false === $rootRealpath) { throw new RuntimeException( - sprintf("Failed to resolve %s path '%s' with realpath()", $varName, $root), + sprintf("Failed to resolve %s path '%s' with realpath()", $varname, $root) ); } return $rootRealpath; } - public static function getConfig(TestCase $testCase): array + /** + * @param TestCase $testCase + * @return array + */ + public static function getConfig(TestCase $testCase) { $testApplication = new TestApplication($testCase); + return $testApplication->getApplication()->getConfig(); } /** * TestApplication constructor. * + * @param TestCase $testCase * @param null $varname [optional] name of the environment variable containing the path to magento-root, "N98_MAGERUN_TEST_MAGENTO_ROOT" by default * @param null $basename [optional] of the stop-file, ".n98-magerun" by default */ @@ -82,14 +105,12 @@ public function __construct(TestCase $testCase, $varname = null, $basename = nul if (null === $varname) { $varname = 'N98_MAGERUN_TEST_MAGENTO_ROOT'; } - if (null === $basename) { $basename = '.n98-magerun'; } - $this->testCase = $testCase; - $this->varName = $varname; - $this->baseName = $basename; + $this->varname = $varname; + $this->basename = $basename; } /** @@ -99,18 +120,19 @@ public function __construct(TestCase $testCase, $varname = null, $basename = nul * * @return string */ - public function getTestMagentoRoot(): ?string + public function getTestMagentoRoot() { - if ($this->root !== null && $this->root !== '' && $this->root !== '0') { + if ($this->root) { return $this->root; } - $varName = $this->varName; - $root = self::getTestMagentoRootFromEnvironment($varName, $this->baseName); + $varname = $this->varname; + + $root = self::getTestMagentoRootFromEnvironment($varname, $this->basename); if (null === $root) { throw new SkippedTestError( - sprintf('Please specify environment variable %s with path to your test magento installation!', $varName), + "Please specify environment variable $varname with path to your test magento installation!" ); } @@ -122,7 +144,7 @@ public function getTestMagentoRoot(): ?string */ public function getApplication() { - if (!$this->application instanceof \N98\Magento\Application) { + if ($this->application === null) { $root = $this->getTestMagentoRoot(); /** @var Application|MockObject $application */ diff --git a/tests/N98/Magento/TestApplicationTest.php b/tests/N98/Magento/TestApplicationTest.php index 1539dbb3e..9c9c9b940 100644 --- a/tests/N98/Magento/TestApplicationTest.php +++ b/tests/N98/Magento/TestApplicationTest.php @@ -1,7 +1,4 @@ assertInstanceOf(__NAMESPACE__ . '\TestApplication', $testApplication); + $application = new TestApplication($this); + self::assertInstanceOf(__NAMESPACE__ . '\TestApplication', $application); } - public function testMagentoTestRoot() + /** + * @test + */ + public function magentoTestRoot() { - $testApplication = new TestApplication($this); - $actual = $testApplication->getTestMagentoRoot(); - $this->assertIsString($actual); - $this->assertGreaterThan(10, strlen($actual)); - $this->assertDirectoryExists($actual); + $application = new TestApplication($this); + $actual = $application->getTestMagentoRoot(); + self::assertIsString($actual); + self::assertGreaterThan(10, strlen($actual)); + self::assertDirectoryExists($actual); } - public function testGetApplication() + /** + * @test + */ + public function getApplication() { - $testApplication = new TestApplication($this); - $application = $testApplication->getApplication(); - $this->assertInstanceOf(__NAMESPACE__ . '\Application', $application); + $application = new TestApplication($this); + $actual = $application->getApplication(); + self::assertInstanceOf(__NAMESPACE__ . '\Application', $actual); } } diff --git a/tests/N98/Magento/_ApplicationTestComposer/FooCommand.php b/tests/N98/Magento/_ApplicationTestComposer/FooCommand.php index 5a6118b9e..d75e794ba 100644 --- a/tests/N98/Magento/_ApplicationTestComposer/FooCommand.php +++ b/tests/N98/Magento/_ApplicationTestComposer/FooCommand.php @@ -1,23 +1,20 @@ setName('acme:foo'); } protected function execute(InputInterface $input, OutputInterface $output): int { - return Command::SUCCESS; + return 0; } } diff --git a/tests/N98/Magento/_ApplicationTestModules/test_dummy_module/src/TestModule/FooCommand.php b/tests/N98/Magento/_ApplicationTestModules/test_dummy_module/src/TestModule/FooCommand.php index d7ba862a2..46b7d5b47 100644 --- a/tests/N98/Magento/_ApplicationTestModules/test_dummy_module/src/TestModule/FooCommand.php +++ b/tests/N98/Magento/_ApplicationTestModules/test_dummy_module/src/TestModule/FooCommand.php @@ -1,30 +1,31 @@ setName('testmodule:foo') ->setDescription('Test command registered in a module'); } + /** + * @param InputInterface $input + * @param OutputInterface $output + * @return int|void + */ protected function execute(InputInterface $input, OutputInterface $output): int { $this->detectMagento($output); if (!$this->initMagento()) { - return Command::INVALID; + return 0; } - - return Command::SUCCESS; + return 0; } } diff --git a/tests/N98/Magento/_ApplicationTestSrc/N98MagerunTest/AlternativeConfigModel.php b/tests/N98/Magento/_ApplicationTestSrc/N98MagerunTest/AlternativeConfigModel.php index f86e20360..d158c2608 100644 --- a/tests/N98/Magento/_ApplicationTestSrc/N98MagerunTest/AlternativeConfigModel.php +++ b/tests/N98/Magento/_ApplicationTestSrc/N98MagerunTest/AlternativeConfigModel.php @@ -1,9 +1,8 @@ setName('n98mageruntest:test:dummy') @@ -22,10 +19,10 @@ protected function execute(InputInterface $input, OutputInterface $output): int { $this->detectMagento($output); if (!$this->initMagento()) { - return Command::INVALID; + return 0; } $output->writeln('dummy'); - return Command::SUCCESS; + return 0; } } diff --git a/tests/N98/Util/ArrayFunctionsTest.php b/tests/N98/Util/ArrayFunctionsTest.php index 9312973da..de3d92a95 100644 --- a/tests/N98/Util/ArrayFunctionsTest.php +++ b/tests/N98/Util/ArrayFunctionsTest.php @@ -1,77 +1,76 @@ assertEquals($expected, ArrayFunctions::mergeArrays($a, $b)); + self::assertEquals($expected, ArrayFunctions::mergeArrays($a, $b)); } /** * @return array */ - public function mergeArraysProvider(): \Iterator + public function mergeArraysProvider() { - yield [[], ['Foo', 'Bar'], ['Foo', 'Bar']]; - yield [['Foo', 'Bar'], [], ['Foo', 'Bar']]; - yield [['Foo'], ['Bar'], ['Foo', 'Bar']]; - yield [['Foo', ['Bar']], ['Bar'], ['Foo', ['Bar'], 'Bar']]; - /** - * Override Bar->Bar - */ - yield [['Foo', 'Bar' => ['Bar' => 1]], ['Bar' => ['Bar' => 2]], ['Foo', 'Bar' => ['Bar' => 2]]]; + return [ + [[], ['Foo', 'Bar'], ['Foo', 'Bar']], + [['Foo', 'Bar'], [], ['Foo', 'Bar']], + [['Foo'], ['Bar'], ['Foo', 'Bar']], + [['Foo', ['Bar']], ['Bar'], ['Foo', ['Bar'], 'Bar']], + /** + * Override Bar->Bar + */ + [['Foo', 'Bar' => ['Bar' => 1]], ['Bar' => ['Bar' => 2]], ['Foo', 'Bar' => ['Bar' => 2]]], + ]; } - public function testColumnOrderArrayTable() + /** + * @test + */ + public function columnOrderArrayTable() { $headers = ['foo', 'bar', 'baz']; $table = [['foo' => 'A1', 'baz' => 'C1', 'B1', 'D1'], ['A2', 'B2', 'C2', 'D2'], [null, null, null, 'foo' => 'A3']]; $actual = ArrayFunctions::columnOrderArrayTable($headers, $table); - $this->assertIsArray($actual); - $this->assertCount(count($table), $actual); + self::assertIsArray($actual); + self::assertCount(count($table), $actual); $expected = [['foo' => 'A1', 'bar' => 'B1', 'baz' => 'C1', 'D1'], ['foo' => 'A2', 'bar' => 'B2', 'baz' => 'C2', 'D2'], ['foo' => 'A3', 'bar' => null, 'baz' => null, null]]; - $this->assertEquals($expected, $actual); - $this->assertSame($expected, $actual); + self::assertEquals($expected, $actual); + self::assertSame($expected, $actual); } /** + * @test * @dataProvider provideColumnOrderings */ - public function testColumnOrder($columns, $array, $expected) + public function columnOrder($columns, $array, $expected) { $actual = ArrayFunctions::columnOrder($columns, $array); - $this->assertIsArray($actual); - $this->assertEquals($expected, $actual); - $this->assertSame($expected, $actual); + self::assertIsArray($actual); + self::assertEquals($expected, $actual); + self::assertSame($expected, $actual); } /** * @see columnOrder * @return array */ - public function provideColumnOrderings(): \Iterator + public function provideColumnOrderings() { - yield [['foo', 'bar', 'baz'], ['A', 'B', 'C'], ['foo' => 'A', 'bar' => 'B', 'baz' => 'C']]; - yield [['foo', 'bar', 'baz'], ['A', 'B', 'C', 'D'], ['foo' => 'A', 'bar' => 'B', 'baz' => 'C', 'D']]; - yield [['foo', 'bar', 'baz'], ['A', 'B', 'C'], ['foo' => 'A', 'bar' => 'B', 'baz' => 'C']]; - yield [['foo', 'bar', 'baz'], ['buz' => 'D', 'A', 'B', 'C'], ['foo' => 'A', 'bar' => 'B', 'baz' => 'C', 'buz' => 'D']]; - yield [['foo', 'bar', 'baz'], ['foo' => 'A', 'baz' => 'C', 'B', 'D'], ['foo' => 'A', 'bar' => 'B', 'baz' => 'C', 'D']]; - yield [['foo', 'bar', 'baz'], ['foo' => 'A', 'baz' => 'C'], ['foo' => 'A', 'bar' => null, 'baz' => 'C']]; + return [[['foo', 'bar', 'baz'], ['A', 'B', 'C'], ['foo' => 'A', 'bar' => 'B', 'baz' => 'C']], [['foo', 'bar', 'baz'], ['A', 'B', 'C', 'D'], ['foo' => 'A', 'bar' => 'B', 'baz' => 'C', 'D']], [['foo', 'bar', 'baz'], ['A', 'B', 'C'], ['foo' => 'A', 'bar' => 'B', 'baz' => 'C']], [['foo', 'bar', 'baz'], ['buz' => 'D', 'A', 'B', 'C'], ['foo' => 'A', 'bar' => 'B', 'baz' => 'C', 'buz' => 'D']], [['foo', 'bar', 'baz'], ['foo' => 'A', 'baz' => 'C', 'B', 'D'], ['foo' => 'A', 'bar' => 'B', 'baz' => 'C', 'D']], [['foo', 'bar', 'baz'], ['foo' => 'A', 'baz' => 'C'], ['foo' => 'A', 'bar' => null, 'baz' => 'C']]]; } /** @@ -79,28 +78,30 @@ public function provideColumnOrderings(): \Iterator * @see matrixFilterStartsWith * @return array */ - public function provideMatrix(): \Iterator + public function provideMatrix() { - yield [[['foo' => 'bar'], ['foo' => 'baz'], ['foo' => 'zaz']]]; + return [[[['foo' => 'bar'], ['foo' => 'baz'], ['foo' => 'zaz']]]]; } /** + * @test * @dataProvider provideMatrix */ - public function testMatrixFilterByValue(array $matrix) + public function matrixFilterByValue(array $matrix) { - $this->assertCount(3, $matrix); + self::assertCount(3, $matrix); $filtered = ArrayFunctions::matrixFilterByValue($matrix, 'foo', 'bar'); - $this->assertCount(1, $filtered); + self::assertCount(1, $filtered); } /** + * @test * @dataProvider provideMatrix */ - public function testMatrixFilterStartsWith(array $matrix) + public function matrixFilterStartsWith(array $matrix) { - $this->assertCount(3, $matrix); - $filtered = ArrayFunctions::matrixFilterStartsWith($matrix, 'foo', 'ba'); - $this->assertCount(2, $filtered); + self::assertCount(3, $matrix); + $filtered = ArrayFunctions::matrixFilterStartswith($matrix, 'foo', 'ba'); + self::assertCount(2, $filtered); } } diff --git a/tests/N98/Util/AutoloadHandlerTest.php b/tests/N98/Util/AutoloadHandlerTest.php index 2950ac49e..2564958cc 100644 --- a/tests/N98/Util/AutoloadHandlerTest.php +++ b/tests/N98/Util/AutoloadHandlerTest.php @@ -1,22 +1,21 @@ + */ namespace N98\Util; -use Error; use PHPUnit\Framework\TestCase; use BadMethodCallException; - /** * Class AutoloadHandlerTest * - * @covers AutoloadHandler + * @covers \N98\Util\AutoloadHandler * @package N98\Util - * - * @author Tom Klingenberg */ -final class AutoloadHandlerTest extends TestCase +class AutoloadHandlerTest extends TestCase { private array $cleanup = []; @@ -30,26 +29,32 @@ protected function tearDown(): void parent::tearDown(); } - public function testCreation() + /** + * @test + */ + public function creation() { $handler = $this->create(null); - $this->assertInstanceOf(__NAMESPACE__ . '\AutoloadHandler', $handler); - $this->assertIsCallable($handler); + self::assertInstanceOf(__NAMESPACE__ . '\AutoloadHandler', $handler); + self::assertIsCallable($handler); } - public function testNoRegistrationOnCreation() + /** + * @test + */ + public function noRegistrationOnCreation(): never { - $this->expectException(Error::class); - $this->expectExceptionMessage('Typed property ' . AutoloadHandler::class . '::$splRegistered must not be accessed before initialization'); + $this->expectException(BadMethodCallException::class); + $this->expectExceptionMessage('Autoload callback is not callable'); $handler = $this->create(null, AutoloadHandler::NO_AUTO_REGISTER); $handler->disable(); // assertions require a disabled handler b/c of exceptions - $this->assertNotContains($handler, spl_autoload_functions()); - $this->assertFalse($handler->__invoke('test')); + self::assertNotContains($handler, spl_autoload_functions()); + self::assertFalse($handler->__invoke('test')); $handler->register(); $actual = in_array($handler, spl_autoload_functions()); - $this->assertTrue($actual); + self::assertTrue($actual); $handler->enable(); $handler->__invoke('test'); @@ -64,7 +69,10 @@ private function create($implementation, $flags = null) return $autoloadHandler; } - public function testRegistrationAndDeregistration() + /** + * @test + */ + public function registrationAndDeregistration() { $calls = (object) ['retval' => true]; $assertAble = function ($className) use (&$calls) { @@ -75,15 +83,18 @@ public function testRegistrationAndDeregistration() }; $handler = $this->create($assertAble); - $this->assertTrue($handler->isEnabled()); - $this->assertTrue($handler->__invoke('Fake')); + self::assertTrue($handler->isEnabled()); + self::assertTrue($handler->__invoke('Fake')); $handler->unregister(); - $this->assertFalse($handler->__invoke('Fake')); - $this->assertSame(1, $calls->count['Fake']); + self::assertFalse($handler->__invoke('Fake')); + self::assertEquals(1, $calls->count['Fake']); } - public function testChangingCallback() + /** + * @test + */ + public function changingCallback() { $calls = (object) ['retval' => true]; $assertAble = function ($className) use (&$calls) { @@ -94,46 +105,55 @@ public function testChangingCallback() }; $handler = $this->create(null, AutoloadHandler::NO_EXCEPTION); - $this->assertFalse($handler->__invoke('Test')); - $this->assertObjectNotHasProperty('count', $calls); + self::assertFalse($handler->__invoke('Test')); + self::assertObjectNotHasAttribute('count', $calls); $handler->setCallback($assertAble); - $this->assertTrue($handler->__invoke('Test')); - $this->assertSame(1, $calls->count['Test']); + self::assertTrue($handler->__invoke('Test')); + self::assertEquals(1, $calls->count['Test']); $handler->setCallback(null); - $this->assertFalse($handler->__invoke('Test')); - $this->assertSame(1, $calls->count['Test']); + self::assertFalse($handler->__invoke('Test')); + self::assertEquals(1, $calls->count['Test']); } - public function testDisablingAndEnabling() + /** + * @test + */ + public function disablingAndEnabling(): never { $handler = $this->create(null); $handler->setEnabled(false); - $this->assertFalse($handler->__invoke('Test')); + self::assertFalse($handler->__invoke('Test')); $handler->setEnabled(true); $this->expectException(BadMethodCallException::class); - $this->assertFalse($handler->__invoke('Test')); + self::assertFalse($handler->__invoke('Test')); self::fail('An expected exception has not been thrown'); } - public function testCallbackSelfReference() + /** + * @test + */ + public function callbackSelfReference() { $testClass = 'MyOf' . random_int(1000, 9999) . 'Fake' . random_int(1000, 9999) . 'Class'; $test = $this; - $handler = $this->create(function ($className) use (&$handler, $test, $testClass): void { + $handler = $this->create(function ($className) use (&$handler, $test, $testClass) { /** @var $handler AutoloadHandler */ - $test->assertSame($testClass, $className); + $test->assertEquals($testClass, $className); $handler->disable(); }); $actual = class_exists($testClass); $isEnabled = $handler->isEnabled(); - $this->assertSame(1, self::getCount()); - $this->assertFalse($isEnabled); - $this->assertFalse($actual); + self::assertEquals(1, self::getCount()); + self::assertFalse($isEnabled); + self::assertFalse($actual); } - public function testCleanupCallback() + /** + * @test + */ + public function cleanupCallback() { $calls = (object) ['retval' => true]; $assertAble = function ($className) use (&$calls) { @@ -146,10 +166,10 @@ public function testCleanupCallback() $handler = $this->create($assertAble, AutoloadHandler::NO_EXCEPTION); $cleanup = $handler->getCleanupCallback(); $actual = class_exists('Test'); - $this->assertFalse($actual); - $this->assertContains($handler, spl_autoload_functions(), 'before cleanup'); + self::assertFalse($actual); + self::assertContains($handler, spl_autoload_functions(), 'before cleanup'); $cleanup(); - $this->assertNotContains($handler, spl_autoload_functions(), 'after cleanup'); + self::assertNotContains($handler, spl_autoload_functions(), 'after cleanup'); // calling cleanup again must not do any warnings etc. $cleanup(); } diff --git a/tests/N98/Util/AutoloadRestorerTest.php b/tests/N98/Util/AutoloadRestorerTest.php index 3227f866f..26488c69c 100644 --- a/tests/N98/Util/AutoloadRestorerTest.php +++ b/tests/N98/Util/AutoloadRestorerTest.php @@ -1,7 +1,4 @@ assertInstanceOf(AutoloadRestorer::class, $autoloadRestorer); + self::assertInstanceOf(AutoloadRestorer::class, $autoloadRestorer); } - public function testRestoration() + /** + * @test + */ + public function restoration() { - $callbackStub = function (): void {}; + $callbackStub = function () { + }; - $this->assertTrue(spl_autoload_register($callbackStub)); + self::assertTrue(spl_autoload_register($callbackStub)); $autoloadRestorer = new AutoloadRestorer(); - $this->assertContains($callbackStub, spl_autoload_functions()); + self::assertContains($callbackStub, spl_autoload_functions()); - $this->assertTrue(spl_autoload_unregister($callbackStub)); + self::assertTrue(spl_autoload_unregister($callbackStub)); - $this->assertNotContains($callbackStub, spl_autoload_functions()); + self::assertNotContains($callbackStub, spl_autoload_functions()); $autoloadRestorer->restore(); - $this->assertContains($callbackStub, spl_autoload_functions()); + self::assertContains($callbackStub, spl_autoload_functions()); } } diff --git a/tests/N98/Util/BinaryStringTest.php b/tests/N98/Util/BinaryStringTest.php index f0e6b6947..1660c21d4 100644 --- a/tests/N98/Util/BinaryStringTest.php +++ b/tests/N98/Util/BinaryStringTest.php @@ -1,36 +1,32 @@ assertEqualsCanonicalizing($expected, BinaryString::trimExplodeEmpty($delimiter, $string)); + self::assertEqualsCanonicalizing($expected, BinaryString::trimExplodeEmpty($delimiter, $string)); } /** * @return array */ - public function trimExplodeEmptyProvider(): \Iterator + public function trimExplodeEmptyProvider() { - yield [',', 'Foo,Bar', ['Foo', 'Bar']]; - yield ['#', ' Foo# Bar', ['Foo', 'Bar']]; - yield [',', ',,Foo, Bar,,', ['Foo', 'Bar']]; + return [[',', 'Foo,Bar', ['Foo', 'Bar']], ['#', ' Foo# Bar', ['Foo', 'Bar']], [',', ',,Foo, Bar,,', ['Foo', 'Bar']]]; } } diff --git a/tests/N98/Util/Console/Helper/DatabaseHelperTest.php b/tests/N98/Util/Console/Helper/DatabaseHelperTest.php index bba9623e9..467d5258e 100644 --- a/tests/N98/Util/Console/Helper/DatabaseHelperTest.php +++ b/tests/N98/Util/Console/Helper/DatabaseHelperTest.php @@ -1,7 +1,5 @@ getApplication()->find('db:info'); $command->getHelperSet()->setCommand($command); @@ -36,44 +34,56 @@ private function getHelper() public function testHelperInstance() { - $this->assertInstanceOf(DatabaseHelper::class, $this->getHelper()); + self::assertInstanceOf(DatabaseHelper::class, $this->getHelper()); } - public function testGetConnection() + /** + * @test + */ + public function getConnection() { - $this->assertInstanceOf(PDO::class, $this->getHelper()->getConnection()); + self::assertInstanceOf(PDO::class, $this->getHelper()->getConnection()); } - public function testDsn() + /** + * @test + */ + public function dsn() { - $this->assertStringStartsWith('mysql:', $this->getHelper()->dsn()); + self::assertStringStartsWith('mysql:', $this->getHelper()->dsn()); } - public function testMysqlUserHasPrivilege() + /** + * @test + */ + public function mysqlUserHasPrivilege() { - $this->assertTrue($this->getHelper()->mysqlUserHasPrivilege('SELECT')); + self::assertTrue($this->getHelper()->mysqlUserHasPrivilege('SELECT')); } - public function testGetMysqlVariableValue() + /** + * @test + */ + public function getMysqlVariableValue() { - $databaseHelper = $this->getHelper(); + $helper = $this->getHelper(); // verify (complex) return value with existing global variable - $actual = $databaseHelper->getMysqlVariableValue('version'); + $actual = $helper->getMysqlVariableValue('version'); - $this->assertIsArray($actual); - $this->assertCount(1, $actual); + self::assertIsArray($actual); + self::assertCount(1, $actual); $key = '@@version'; - $this->assertArrayHasKey($key, $actual); - $this->assertIsString($actual[$key]); + self::assertArrayHasKey($key, $actual); + self::assertIsString($actual[$key]); // quoted - $actual = $databaseHelper->getMysqlVariableValue('`version`'); - $this->assertSame('@@`version`', key($actual)); + $actual = $helper->getMysqlVariableValue('`version`'); + self::assertEquals('@@`version`', key($actual)); // non-existent global variable try { - $databaseHelper->getMysqlVariableValue('nonexistent'); + $helper->getMysqlVariableValue('nonexistent'); self::fail('An expected exception has not been thrown'); } catch (RuntimeException $runtimeException) { // do nothing -> We need to check different strings for old MySQL and MariaDB servers @@ -81,22 +91,25 @@ public function testGetMysqlVariableValue() } } - public function testGetMysqlVariable() + /** + * @test + */ + public function getMysqlVariable() { - $databaseHelper = $this->getHelper(); + $helper = $this->getHelper(); // behaviour with existing global variable - $actual = $databaseHelper->getMysqlVariable('version'); - $this->assertIsString($actual); + $actual = $helper->getMysqlVariable('version'); + self::assertIsString($actual); // behavior with existent session variable (INTEGER) - $databaseHelper->getConnection()->query('SET @existent = 14;'); - $actual = $databaseHelper->getMysqlVariable('existent', '@'); - $this->assertSame(14, $actual); + $helper->getConnection()->query('SET @existent = 14;'); + $actual = $helper->getMysqlVariable('existent', '@'); + self::assertEquals(14, $actual); // behavior with non-existent session variable - $actual = $databaseHelper->getMysqlVariable('nonexistent', '@'); - $this->assertNull($actual); + $actual = $helper->getMysqlVariable('nonexistent', '@'); + self::assertNull($actual); // behavior with non-existent global variable /* @@ -114,23 +127,29 @@ public function testGetMysqlVariable() // invalid variable type try { - $databaseHelper->getMysqlVariable('nonexistent', '@@@'); + $helper->getMysqlVariable('nonexistent', '@@@'); self::fail('An expected Exception has not been thrown'); } catch (InvalidArgumentException $invalidArgumentException) { // test against the mysql error message - $this->assertSame('Invalid mysql variable type "@@@", must be "@@" (system) or "@" (session)', $invalidArgumentException->getMessage()); + self::assertEquals( + 'Invalid mysql variable type "@@@", must be "@@" (system) or "@" (session)', + $invalidArgumentException->getMessage() + ); } } - public function testGetTables() + /** + * @test + */ + public function getTables() { - $databaseHelper = $this->getHelper(); + $helper = $this->getHelper(); - $tables = $databaseHelper->getTables(); - $this->assertIsArray($tables); - $this->assertContains('admin_user', $tables); + $tables = $helper->getTables(); + self::assertIsArray($tables); + self::assertContains('admin_user', $tables); - $dbSettings = $databaseHelper->getDbSettings(); + $dbSettings = $helper->getDbSettings(); $reflectionObject = new ReflectionObject($dbSettings); $reflectionProperty = $reflectionObject->getProperty('config'); $reflectionProperty->setAccessible(true); @@ -138,7 +157,7 @@ public function testGetTables() $config = $reflectionProperty->getValue($dbSettings); $previous = $config['prefix']; - $this->tearDownRestore[] = function () use ($reflectionProperty, $dbSettings, $previous): void { + $this->tearDownRestore[] = function () use ($reflectionProperty, $dbSettings, $previous) { $config = []; $config['prefix'] = $previous; $reflectionProperty->setValue($dbSettings, $config); @@ -147,35 +166,38 @@ public function testGetTables() $config['prefix'] = $previous . 'core_'; $reflectionProperty->setValue($dbSettings, $config); - $tables = $databaseHelper->getTables(null); // default value should be null-able and is false - $this->assertIsArray($tables); - $this->assertNotContains('admin_user', $tables); - $this->assertContains('core_store', $tables); - $this->assertContains('core_website', $tables); - - $tables = $databaseHelper->getTables(true); - $this->assertIsArray($tables); - $this->assertNotContains('admin_user', $tables); - $this->assertContains('store', $tables); - $this->assertContains('website', $tables); + $tables = $helper->getTables(null); // default value should be null-able and is false + self::assertIsArray($tables); + self::assertNotContains('admin_user', $tables); + self::assertContains('core_store', $tables); + self::assertContains('core_website', $tables); + + $tables = $helper->getTables(true); + self::assertIsArray($tables); + self::assertNotContains('admin_user', $tables); + self::assertContains('store', $tables); + self::assertContains('website', $tables); } - public function testResolveTables() + /** + * @test + */ + public function resolveTables() { $tables = $this->getHelper()->resolveTables(['catalog_*']); - $this->assertContains('catalog_product_entity', $tables); - $this->assertNotContains('catalogrule', $tables); + self::assertContains('catalog_product_entity', $tables); + self::assertNotContains('catalogrule', $tables); $definitions = ['wild_1' => ['tables' => ['catalog_*']], 'wild_2' => ['tables' => ['core_config_dat?']], 'dataflow' => ['tables' => ['dataflow_batch_import', 'dataflow_batch_export']]]; $tables = $this->getHelper()->resolveTables( ['@wild_1', '@wild_2', '@dataflow'], - $definitions, + $definitions ); - $this->assertContains('catalog_product_entity', $tables); - $this->assertContains('core_config_data', $tables); - $this->assertContains('dataflow_batch_import', $tables); - $this->assertNotContains('catalogrule', $tables); + self::assertContains('catalog_product_entity', $tables); + self::assertContains('core_config_data', $tables); + self::assertContains('dataflow_batch_import', $tables); + self::assertNotContains('catalogrule', $tables); } /** @@ -187,7 +209,6 @@ protected function tearDown(): void foreach ($this->tearDownRestore as $singleTearDownRestore) { $singleTearDownRestore(); } - $this->tearDownRestore = null; parent::tearDown(); diff --git a/tests/N98/Util/Console/Helper/IoHelperTest.php b/tests/N98/Util/Console/Helper/IoHelperTest.php index 3b20fe118..4363b90e1 100644 --- a/tests/N98/Util/Console/Helper/IoHelperTest.php +++ b/tests/N98/Util/Console/Helper/IoHelperTest.php @@ -1,7 +1,4 @@ assertInstanceOf(IoHelper::class, $ioHelper); - $this->assertInstanceOf(HelperInterface::class, $ioHelper); - $this->assertNull($ioHelper->getOutput()); + self::assertInstanceOf(IoHelper::class, $ioHelper); + self::assertInstanceOf(HelperInterface::class, $ioHelper); + self::assertNull($ioHelper->getOutput()); - $this->assertSame('io', $ioHelper->getName()); + self::assertSame('io', $ioHelper->getName()); } } diff --git a/tests/N98/Util/Console/Helper/MagentoHelper.php b/tests/N98/Util/Console/Helper/MagentoHelper.php index 3c425d072..b90bcef44 100644 --- a/tests/N98/Util/Console/Helper/MagentoHelper.php +++ b/tests/N98/Util/Console/Helper/MagentoHelper.php @@ -1,7 +1,5 @@ getHelper()); } - public function testDetectMagentoInStandardFolder() + /** + * @test + */ + public function detectMagentoInStandardFolder() { vfsStream::setup('root'); vfsStream::create( - ['app' => ['Mage.php' => '']], + ['app' => ['Mage.php' => '']] ); - $magentoHelper = $this->getHelper(); - $magentoHelper->detect(vfsStream::url('root'), []); + $helper = $this->getHelper(); + $helper->detect(vfsStream::url('root'), []); - self::assertSame(vfsStream::url('root'), $magentoHelper->getRootFolder()); + self::assertEquals(vfsStream::url('root'), $helper->getRootFolder()); } - public function testDetectMagentoInHtdocsSubfolder() + /** + * @test + */ + public function detectMagentoInHtdocsSubfolder() { vfsStream::setup('root'); vfsStream::create( - ['htdocs' => ['app' => ['Mage.php' => '']]], + ['htdocs' => ['app' => ['Mage.php' => '']]] ); - $magentoHelper = $this->getHelper(); + $helper = $this->getHelper(); // vfs cannot resolve relative path so we do 'root/htdocs' etc. - $magentoHelper->detect( + $helper->detect( vfsStream::url('root'), - [vfsStream::url('root/www'), vfsStream::url('root/public'), vfsStream::url('root/htdocs')], + [vfsStream::url('root/www'), vfsStream::url('root/public'), vfsStream::url('root/htdocs')] ); - self::assertSame(vfsStream::url('root/htdocs'), $magentoHelper->getRootFolder()); + self::assertEquals(vfsStream::url('root/htdocs'), $helper->getRootFolder()); } - public function testDetectMagentoFailed() + /** + * @test + */ + public function detectMagentoFailed() { vfsStream::setup('root'); vfsStream::create( - ['htdocs' => []], + ['htdocs' => []] ); - $magentoHelper = $this->getHelper(); + $helper = $this->getHelper(); // vfs cannot resolve relative path so we do 'root/htdocs' etc. - $magentoHelper->detect( - vfsStream::url('root'), + $helper->detect( + vfsStream::url('root') ); - self::assertNull($magentoHelper->getRootFolder()); + self::assertNull($helper->getRootFolder()); } - public function testDetectMagentoInModmanInfrastructure() + /** + * @test + */ + public function detectMagentoInModmanInfrastructure() { vfsStream::setup('root'); vfsStream::create( - ['.basedir' => 'root/htdocs/magento_root', 'htdocs' => ['magento_root' => ['app' => ['Mage.php' => '']]]], + ['.basedir' => 'root/htdocs/magento_root', 'htdocs' => ['magento_root' => ['app' => ['Mage.php' => '']]]] ); - $magentoHelper = $this->getHelper(); + $helper = $this->getHelper(); // vfs cannot resolve relative path so we do 'root/htdocs' etc. - $magentoHelper->detect( - vfsStream::url('root'), + $helper->detect( + vfsStream::url('root') ); // Verify if this could be checked with more elegance - self::assertSame(vfsStream::url('root/../root/htdocs/magento_root'), $magentoHelper->getRootFolder()); + self::assertEquals(vfsStream::url('root/../root/htdocs/magento_root'), $helper->getRootFolder()); } } diff --git a/tests/N98/Util/Console/Helper/Table/Renderer/RenderFactoryTest.php b/tests/N98/Util/Console/Helper/Table/Renderer/RenderFactoryTest.php index 1a69abced..c31821cb3 100644 --- a/tests/N98/Util/Console/Helper/Table/Renderer/RenderFactoryTest.php +++ b/tests/N98/Util/Console/Helper/Table/Renderer/RenderFactoryTest.php @@ -1,12 +1,9 @@ create('csv'); - $this->assertInstanceOf(CsvRenderer::class, $csv); + self::assertInstanceOf(CsvRenderer::class, $csv); $json = $rendererFactory->create('json'); - $this->assertInstanceOf(JsonRenderer::class, $json); + self::assertInstanceOf(JsonRenderer::class, $json); $xml = $rendererFactory->create('xml'); - $this->assertInstanceOf(XmlRenderer::class, $xml); + self::assertInstanceOf(XmlRenderer::class, $xml); $invalidFormat = $rendererFactory->create('invalid_format'); - $this->assertNull($invalidFormat); + self::assertFalse($invalidFormat); } } diff --git a/tests/N98/Util/Console/Helper/Table/Renderer/TestCase.php b/tests/N98/Util/Console/Helper/Table/Renderer/TestCase.php index 0b1667638..e32515e5b 100644 --- a/tests/N98/Util/Console/Helper/Table/Renderer/TestCase.php +++ b/tests/N98/Util/Console/Helper/Table/Renderer/TestCase.php @@ -1,7 +1,4 @@ assertInstanceOf(__NAMESPACE__ . '\\TextRenderer', $renderer); + self::assertInstanceOf(__NAMESPACE__ . '\\TextRenderer', $renderer); $rendererFactory = new RendererFactory(); $renderer = $rendererFactory->create('text'); - $this->assertInstanceOf(__NAMESPACE__ . '\\TextRenderer', $renderer); + self::assertInstanceOf(__NAMESPACE__ . '\\TextRenderer', $renderer); } - public function testRendering() + /** + * @test + */ + public function rendering() { $textRenderer = new TextRenderer(); $streamOutput = new StreamOutput(fopen('php://memory', 'wb', false)); @@ -51,6 +54,6 @@ public function testRendering() $textRenderer->render($streamOutput, $rows); - $this->assertSame($expected, $this->getOutputBuffer($streamOutput)); + self::assertEquals($expected, $this->getOutputBuffer($streamOutput)); } } diff --git a/tests/N98/Util/Console/Helper/Table/Renderer/XmlRendererTest.php b/tests/N98/Util/Console/Helper/Table/Renderer/XmlRendererTest.php index 1ea283f15..ff2a46e83 100644 --- a/tests/N98/Util/Console/Helper/Table/Renderer/XmlRendererTest.php +++ b/tests/N98/Util/Console/Helper/Table/Renderer/XmlRendererTest.php @@ -1,7 +1,4 @@ assertInstanceOf(__NAMESPACE__ . '\\XmlRenderer', $renderer); + self::assertInstanceOf(__NAMESPACE__ . '\\XmlRenderer', $renderer); $rendererFactory = new RendererFactory(); $renderer = $rendererFactory->create('xml'); - $this->assertInstanceOf(__NAMESPACE__ . '\\XmlRenderer', $renderer); + self::assertInstanceOf(__NAMESPACE__ . '\\XmlRenderer', $renderer); } /** + * @return array * @see tableRendering */ - public function provideTables(): \Iterator + public function provideTables() { - yield [[['column' => 'Doors wide > open'], ['column' => "null \0 bytes FTW"]], ' + return [[[['column' => 'Doors wide > open'], ['column' => "null \0 bytes FTW"]], '
column
@@ -51,12 +52,10 @@ public function provideTables(): \Iterator bnVsbCAAIGJ5dGVzIEZUVw== -
']; - yield [[], ' +'], [[], ' -
']; - yield [[['Column1' => 'Value A1', 'Column2' => 'A2 is another value that there is'], [1, "multi\nline\nftw"], ['C1 cell here!', new SimpleXMLElement('PHP Magic->toString() test')]], ' +'], [[['Column1' => 'Value A1', 'Column2' => 'A2 is another value that there is'], [1, "multi\nline\nftw"], ['C1 cell here!', new SimpleXMLElement('PHP Magic->toString() test')]], '
Column1
@@ -76,8 +75,7 @@ public function provideTables(): \Iterator C1 cell here! PHP Magic->toString() test -
']; - yield [[["\x00" => 'foo']], ' +'], [[["\x00" => 'foo']], '
@@ -85,8 +83,7 @@ public function provideTables(): \Iterator <_>foo -
']; - yield [[['foo' => 'bar'], ['baz', 'buz' => 'here']], ' +'], [[['foo' => 'bar'], ['baz', 'buz' => 'here']], '
foo
@@ -98,19 +95,25 @@ public function provideTables(): \Iterator baz here -
']; +']]; } - public function testInvalidName() + /** + * @test + */ + public function invalidName() { - $this->expectException(TypeError::class); - $this->expectExceptionMessage('DOMDocument::createElement(): Argument #2 ($value) must be of type string, int given'); + $this->expectException(DOMException::class); + $this->expectExceptionMessage("Invalid name '0'"); $xmlRenderer = new XmlRenderer(); $nullOutput = new NullOutput(); $xmlRenderer->render($nullOutput, [['foo']]); } - public function testInvalidEncoding() + /** + * @test + */ + public function invalidEncoding() { $this->expectException(RuntimeException::class); $this->expectExceptionMessage("Encoding error, only US-ASCII and UTF-8 supported, can not process '"); @@ -120,15 +123,16 @@ public function testInvalidEncoding() } /** + * @test * @dataProvider provideTables */ - public function testTableRendering($rows, $expected) + public function tableRendering($rows, $expected) { $xmlRenderer = new XmlRenderer(); $streamOutput = new StreamOutput(fopen('php://memory', 'wb', false)); $xmlRenderer->render($streamOutput, $rows); - $this->assertSame($expected . "\n", $this->getOutputBuffer($streamOutput)); + self::assertEquals($expected . "\n", $this->getOutputBuffer($streamOutput)); } } diff --git a/tests/N98/Util/DateTimeTest.php b/tests/N98/Util/DateTimeTest.php index b0a84a697..22613d2b5 100644 --- a/tests/N98/Util/DateTimeTest.php +++ b/tests/N98/Util/DateTimeTest.php @@ -1,36 +1,30 @@ assertSame($expected, $dateTime->getDifferenceAsString($time1, $time2)); + self::assertEquals($expected, $dateTime->getDifferenceAsString($time1, $time2)); } /** * @return array */ - public static function getDifferenceAsStringProvider(): \Iterator + public static function getDifferenceAsStringProvider() { - yield [new DateTime('2013-12-01', new DateTimeZone('UTC')), new DateTime('2013-12-01', new DateTimeZone('UTC')), '0']; - yield [new DateTime('2013-12-01 00:00:00', new DateTimeZone('UTC')), new DateTime('2013-12-01 00:00:01', new DateTimeZone('UTC')), '1s']; - yield [new DateTime('2013-12-01 00:00:00', new DateTimeZone('UTC')), new DateTime('2013-12-01 00:01:01', new DateTimeZone('UTC')), '1m 1s']; - yield [new DateTime('2013-12-01 00:00:00', new DateTimeZone('UTC')), new DateTime('2013-12-01 01:01:01', new DateTimeZone('UTC')), '1h 1m 1s']; - yield [new DateTime('2013-12-01 00:00:00', new DateTimeZone('UTC')), new DateTime('2013-12-02 01:01:01', new DateTimeZone('UTC')), '1d 1h 1m 1s']; - yield [new DateTime('2013-12-01 00:00:00', new DateTimeZone('UTC')), new DateTime('2014-01-02 01:01:01', new DateTimeZone('UTC')), '1M 1d 1h 1m 1s']; - yield [new DateTime('2013-12-01 00:00:00', new DateTimeZone('UTC')), new DateTime('2015-01-02 01:01:01', new DateTimeZone('UTC')), '1Y 1M 1d 1h 1m 1s']; + return [[new DateTime('2013-12-01', new DateTimeZone('UTC')), new DateTime('2013-12-01', new DateTimeZone('UTC')), '0'], [new DateTime('2013-12-01 00:00:00', new DateTimeZone('UTC')), new DateTime('2013-12-01 00:00:01', new DateTimeZone('UTC')), '1s'], [new DateTime('2013-12-01 00:00:00', new DateTimeZone('UTC')), new DateTime('2013-12-01 00:01:01', new DateTimeZone('UTC')), '1m 1s'], [new DateTime('2013-12-01 00:00:00', new DateTimeZone('UTC')), new DateTime('2013-12-01 01:01:01', new DateTimeZone('UTC')), '1h 1m 1s'], [new DateTime('2013-12-01 00:00:00', new DateTimeZone('UTC')), new DateTime('2013-12-02 01:01:01', new DateTimeZone('UTC')), '1d 1h 1m 1s'], [new DateTime('2013-12-01 00:00:00', new DateTimeZone('UTC')), new DateTime('2014-01-02 01:01:01', new DateTimeZone('UTC')), '1M 1d 1h 1m 1s'], [new DateTime('2013-12-01 00:00:00', new DateTimeZone('UTC')), new DateTime('2015-01-02 01:01:01', new DateTimeZone('UTC')), '1Y 1M 1d 1h 1m 1s']]; } } diff --git a/tests/N98/Util/ExecTest.php b/tests/N98/Util/ExecTest.php index c31de2d62..de8e7b7d8 100644 --- a/tests/N98/Util/ExecTest.php +++ b/tests/N98/Util/ExecTest.php @@ -1,35 +1,41 @@ assertSame(0, $actual); + self::assertSame(0, $actual); } - public function testFullParameters() + /** + * @test + */ + public function fullParameters() { Exec::run('echo test', $commandOutput, $returnCode); - $this->assertSame(Exec::CODE_CLEAN_EXIT, $returnCode); - $this->assertStringStartsWith('test', $commandOutput); + self::assertEquals(Exec::CODE_CLEAN_EXIT, $returnCode); + self::assertStringStartsWith('test', $commandOutput); } - public function testException() + /** + * @test + */ + public function exception() { $this->expectException(RuntimeException::class); Exec::run('foobar'); diff --git a/tests/N98/Util/FilesystemTest.php b/tests/N98/Util/FilesystemTest.php index d534c4ede..2faa25133 100644 --- a/tests/N98/Util/FilesystemTest.php +++ b/tests/N98/Util/FilesystemTest.php @@ -1,29 +1,30 @@ + */ namespace N98\Util; -use Generator; use PHPUnit\Framework\TestCase; use RuntimeException; - /** * Class FilesystemTest * @package N98\Util - * * @author Aydin Hassan - * @author Tom Klingenberg - * - * @covers \N98\Util\Filesystem + * @covers N98\Util\Filesystem */ -final class FilesystemTest extends TestCase +class FilesystemTest extends TestCase { - private Filesystem $filesystem; + /** + * @var Filesystem + */ + protected $fileSystem; protected function setUp(): void { - $this->filesystem = new Filesystem(); + $this->fileSystem = new Filesystem(); } public function testRecursiveCopy() @@ -42,9 +43,9 @@ public function testRecursiveCopy() touch($file1); touch($file2); - $this->filesystem->recursiveCopy($basePath, $dest); - $this->assertFileExists($dest . '/folder1/file1.txt'); - $this->assertFileExists($dest . '/folder2/file2.txt'); + $this->fileSystem->recursiveCopy($basePath, $dest); + self::assertFileExists($dest . '/folder1/file1.txt'); + self::assertFileExists($dest . '/folder2/file2.txt'); //cleanup unlink($file1); @@ -59,15 +60,14 @@ public function testRecursiveCopy() rmdir($dest . '/folder2'); rmdir($dest); - $this->assertFileDoesNotExist($dest . '/folder1/file1.txt'); - $this->assertFileDoesNotExist($dest); + self::assertFileDoesNotExist($dest . '/folder1/file1.txt'); + self::assertFileDoesNotExist($dest); if (!is_dir($tmp . '/a')) { mkdir($tmp . '/a'); } - touch($tmp . '/file1.txt'); - $this->filesystem->recursiveCopy($tmp . '/a', $tmp . '/file1.txt'); + $this->fileSystem->recursiveCopy($tmp . '/a', $tmp . '/file1.txt'); unlink($tmp . '/file1.txt'); rmdir($tmp . '/a'); } @@ -82,7 +82,7 @@ public function testRecursiveCopyWithBlacklist() $ignoreMe = $folder1 . '/ignore.me'; $file2 = $folder2 . '/file2.txt'; $dest = sys_get_temp_dir() . '/n98_copy_dest'; - $this->filesystem->recursiveRemoveDirectory($dest, true); + $this->fileSystem->recursiveRemoveDirectory($dest, true); @mkdir($folder1, 0777, true); @mkdir($folder2, 0777, true); @@ -90,10 +90,10 @@ public function testRecursiveCopyWithBlacklist() touch($ignoreMe); touch($file2); - $this->filesystem->recursiveCopy($basePath, $dest, ['ignore.me']); - $this->assertFileExists($dest . '/folder1/file1.txt'); - $this->assertFileDoesNotExist($dest . '/folder1/ignore.me'); - $this->assertFileExists($dest . '/folder2/file2.txt'); + $this->fileSystem->recursiveCopy($basePath, $dest, ['ignore.me']); + self::assertFileExists($dest . '/folder1/file1.txt'); + self::assertFileDoesNotExist($dest . '/folder1/ignore.me'); + self::assertFileExists($dest . '/folder2/file2.txt'); //cleanup unlink($file1); @@ -126,12 +126,12 @@ public function testRecursiveDirectoryRemoveUnLinksSymLinks() touch($symLinkedFile); $result = @symlink($symLinked, $basePath . '/symlink'); - $this->assertTrue($result); + self::assertTrue($result); - $this->filesystem->recursiveRemoveDirectory($basePath); + $this->fileSystem->recursiveRemoveDirectory($basePath); - $this->assertFileExists($symLinkedFile); - $this->assertFileDoesNotExist($basePath); + self::assertFileExists($symLinkedFile); + self::assertFileDoesNotExist($basePath); } public function testRecursiveRemove() @@ -148,8 +148,8 @@ public function testRecursiveRemove() touch($file1); touch($file2); - $this->filesystem->recursiveRemoveDirectory($basePath); - $this->assertFileDoesNotExist($basePath); + $this->fileSystem->recursiveRemoveDirectory($basePath); + self::assertFileDoesNotExist($basePath); } public function testRecursiveRemoveWithTrailingSlash() @@ -166,13 +166,13 @@ public function testRecursiveRemoveWithTrailingSlash() touch($file1); touch($file2); - $this->filesystem->recursiveRemoveDirectory($basePath . '/'); - $this->assertFileDoesNotExist($basePath); + $this->fileSystem->recursiveRemoveDirectory($basePath . '/'); + self::assertFileDoesNotExist($basePath); } public function testFalseIsReturnedIfDirectoryNotExist() { - $this->assertFalse($this->filesystem->recursiveRemoveDirectory('not-a-folder')); + self::assertFalse($this->fileSystem->recursiveRemoveDirectory('not-a-folder')); } public function testFalseIsReturnedIfDirectoryNotReadable() @@ -180,7 +180,7 @@ public function testFalseIsReturnedIfDirectoryNotReadable() $tmp = sys_get_temp_dir(); $basePath = $tmp . '/n98_testdir-never-existed'; - $this->assertFalse($this->filesystem->recursiveRemoveDirectory($basePath)); + self::assertFalse($this->fileSystem->recursiveRemoveDirectory($basePath)); } public function testParentIsNotRemovedIfEmptyIsTrue() @@ -197,27 +197,29 @@ public function testParentIsNotRemovedIfEmptyIsTrue() touch($file1); touch($file2); - $this->filesystem->recursiveRemoveDirectory($basePath, true); - $this->assertFileExists($basePath); - $this->assertFileDoesNotExist($folder1); - $this->assertFileDoesNotExist($folder2); + $this->fileSystem->recursiveRemoveDirectory($basePath, true); + self::assertFileExists($basePath); + self::assertFileDoesNotExist($folder1); + self::assertFileDoesNotExist($folder2); } /** + * @param int $bytes + * @param int $decimalPlaces + * @param string $expected * @dataProvider convertedBytesProvider */ - public function testConvertBytesToHumanReadable(int $bytes, int $decimalPlaces, string $expected) + public function testConvertBytesToHumanReadable($bytes, $decimalPlaces, $expected) { $res = Filesystem::humanFileSize($bytes, $decimalPlaces); - $this->assertSame($expected, $res); + self::assertSame($expected, $res); } - public static function convertedBytesProvider(): Generator + /** + * @return array + */ + public static function convertedBytesProvider() { - yield [20_000_000, 2, '19.07M']; - yield [20_000_000, 3, '19.073M']; - yield [2_000_000_000, 2, '1.86G']; - yield [2, 2, '2.00B']; - yield [2048, 2, '2.00K']; + return [[20_000_000, 2, '19.07M'], [20_000_000, 3, '19.073M'], [2_000_000_000, 2, '1.86G'], [2, 2, '2.00B'], [2048, 2, '2.00K']]; } } diff --git a/tests/N98/Util/OperatingSystemTest.php b/tests/N98/Util/OperatingSystemTest.php index 9e60cf46f..f57f61759 100644 --- a/tests/N98/Util/OperatingSystemTest.php +++ b/tests/N98/Util/OperatingSystemTest.php @@ -1,7 +1,4 @@ assertCount(4, $matrix, 'Number of OSes to check for'); - $this->assertCount(1, array_filter($matrix), 'One OS must be detected'); + self::assertCount(4, $matrix, 'Number of OSes to check for'); + self::assertCount(1, array_filter($matrix), 'One OS must be detected'); } /** @@ -33,10 +32,10 @@ public function testOsDetection() */ public function testIsLinux() { - $this->assertTrue(OperatingSystem::isLinux()); - $this->assertFalse(OperatingSystem::isWindows()); - $this->assertFalse(OperatingSystem::isMacOs()); - $this->assertFalse(OperatingSystem::isNetware()); + self::assertTrue(OperatingSystem::isLinux()); + self::assertFalse(OperatingSystem::isWindows()); + self::assertFalse(OperatingSystem::isMacOs()); + self::assertFalse(OperatingSystem::isNetware()); } /** @@ -44,10 +43,10 @@ public function testIsLinux() */ public function testIsWindows() { - $this->assertTrue(OperatingSystem::isWindows()); - $this->assertFalse(OperatingSystem::isLinux()); - $this->assertFalse(OperatingSystem::isMacOs()); - $this->assertFalse(OperatingSystem::isNetware()); + self::assertTrue(OperatingSystem::isWindows()); + self::assertFalse(OperatingSystem::isLinux()); + self::assertFalse(OperatingSystem::isMacOs()); + self::assertFalse(OperatingSystem::isNetware()); } /** @@ -55,10 +54,10 @@ public function testIsWindows() */ public function testIsMacOs() { - $this->assertTrue(OperatingSystem::isMacOs()); - $this->assertFalse(OperatingSystem::isLinux()); - $this->assertFalse(OperatingSystem::isWindows()); - $this->assertFalse(OperatingSystem::isNetware()); + self::assertTrue(OperatingSystem::isMacOs()); + self::assertFalse(OperatingSystem::isLinux()); + self::assertFalse(OperatingSystem::isWindows()); + self::assertFalse(OperatingSystem::isNetware()); } /** @@ -66,23 +65,27 @@ public function testIsMacOs() */ public function testIsNetware() { - $this->assertTrue(OperatingSystem::isNetware()); - $this->assertFalse(OperatingSystem::isLinux()); - $this->assertFalse(OperatingSystem::isWindows()); - $this->assertFalse(OperatingSystem::isMacOs()); + self::assertTrue(OperatingSystem::isNetware()); + self::assertFalse(OperatingSystem::isLinux()); + self::assertFalse(OperatingSystem::isWindows()); + self::assertFalse(OperatingSystem::isMacOs()); } - public function testGetCwd() + /** + * @test + */ + public function getCwd() { $expected = getcwd(); - $this->assertEquals($expected, OperatingSystem::getCwd()); + self::assertEquals($expected, OperatingSystem::getCwd()); } /** + * @test * @requires PHP 5.4 */ - public function testPhpBinary() + public function phpBinary() { - $this->assertSame(PHP_BINARY, OperatingSystem::getPhpBinary()); + self::assertEquals(PHP_BINARY, OperatingSystem::getPhpBinary()); } } diff --git a/tests/N98/Util/StringTypedTest.php b/tests/N98/Util/StringTypedTest.php index 5caefdae9..8045c94cc 100644 --- a/tests/N98/Util/StringTypedTest.php +++ b/tests/N98/Util/StringTypedTest.php @@ -1,7 +1,4 @@ assertTrue(StringTyped::parseBoolOption('true')); + self::assertTrue(StringTyped::parseBoolOption('true')); - $this->assertSame('inactive', StringTyped::formatActive(null)); - $this->assertSame('active', StringTyped::formatActive('1')); + self::assertSame('inactive', StringTyped::formatActive(null)); + self::assertSame('active', StringTyped::formatActive('1')); } } diff --git a/tests/N98/Util/Unicode/CharsetTest.php b/tests/N98/Util/Unicode/CharsetTest.php index cc888bbf8..90e140c3c 100644 --- a/tests/N98/Util/Unicode/CharsetTest.php +++ b/tests/N98/Util/Unicode/CharsetTest.php @@ -1,16 +1,13 @@ assertSame('✖', Charset::convertInteger(Charset::UNICODE_CROSS_CHAR)); - $this->assertSame('✔', Charset::convertInteger(Charset::UNICODE_CHECKMARK_CHAR)); + self::assertEquals('✖', Charset::convertInteger(Charset::UNICODE_CROSS_CHAR)); + self::assertEquals('✔', Charset::convertInteger(Charset::UNICODE_CHECKMARK_CHAR)); } } diff --git a/tests/N98/Util/VerifyOrDieTest.php b/tests/N98/Util/VerifyOrDieTest.php index f25e5b526..7a609cdac 100644 --- a/tests/N98/Util/VerifyOrDieTest.php +++ b/tests/N98/Util/VerifyOrDieTest.php @@ -1,48 +1,71 @@ + */ namespace N98\Util; use InvalidArgumentException; -use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\TestCase as TestCase; use RuntimeException; -use TypeError; /** * Class VerifyOrDieTest * * @package N98\Util - * - * @author Tom Klingenberg */ -final class VerifyOrDieTest extends TestCase +class VerifyOrDieTest extends TestCase { - public function testPortableFilename() + /** + * @test a portable filename passes + */ + public function portableFilename() { - $this->assertSame('example.txt', VerifyOrDie::filename('example.txt')); - $this->assertSame('.hidden', VerifyOrDie::filename('.hidden')); + self::assertSame('example.txt', VerifyOrDie::filename('example.txt')); + + self::assertSame('.hidden', VerifyOrDie::filename('.hidden')); } - public function testUserMessage() + /** + * @test user-message for verification + */ + public function userMessage() { $message = sprintf('Database name %s is not portable', var_export('-fail', true)); try { VerifyOrDie::filename('-fail', $message); self::fail('An expected exception has not been thrown.'); } catch (RuntimeException $runtimeException) { - $this->assertSame($message, $runtimeException->getMessage()); + self::assertSame($message, $runtimeException->getMessage()); } } - public function testZeroLengthFilename() + /** + * @test a filename must have at least one byte + */ + public function zeroLengthFilename() { $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('Filename is zero-length string'); VerifyOrDie::filename(''); } - public function testStartWithDashFilename() + /** + * @test + */ + public function invalidArugment() + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Parameter basename must be of type string, NULL given'); + VerifyOrDie::filename(null); + } + + /** + * @test a filename must not start with a dash + */ + public function startWithDashFilename() { $this->expectException(\RuntimeException::class); $this->expectExceptionMessage("Filename '-rf' starts with a dash"); @@ -50,9 +73,10 @@ public function testStartWithDashFilename() } /** + * @test * @dataProvider provideNonPortableFilenames */ - public function testNonPortableFilenameThrowsException($filename) + public function nonPortableFilenameThrowsException($filename) { $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('is not portable'); @@ -62,10 +86,8 @@ public function testNonPortableFilenameThrowsException($filename) /** * @see nonPortableFilenameThrowsException */ - public function provideNonPortableFilenames(): \Iterator + public function provideNonPortableFilenames() { - yield ['no-slash-/-in.there']; - yield ['windoze-limits-<>:"/\\|?*']; - yield ['lets-keep-spaces out']; + return [['no-slash-/-in.there'], ['windoze-limits-<>:"/\\|?*'], ['lets-keep-spaces out']]; } } diff --git a/tests/N98/Util/WindowsSystemTest.php b/tests/N98/Util/WindowsSystemTest.php index 5797092aa..841c3c78a 100644 --- a/tests/N98/Util/WindowsSystemTest.php +++ b/tests/N98/Util/WindowsSystemTest.php @@ -1,7 +1,4 @@ assertTrue(WindowsSystem::isProgramInstalled('notepad')); + self::assertTrue(WindowsSystem::isProgramInstalled('notepad')); - $this->assertFalse(WindowsSystem::isProgramInstalled('notepad-that-never-made-it-into-windows-kernel')); + self::assertFalse(WindowsSystem::isProgramInstalled('notepad-that-never-made-it-into-windows-kernel')); - $this->assertFalse(WindowsSystem::isProgramInstalled('invalid\\command*name|thisis')); + self::assertFalse(WindowsSystem::isProgramInstalled('invalid\\command*name|thisis')); } /** * @see isExecutableName * @return array */ - public function provideExecutableNames(): \Iterator + public function provideExecutableNames() { - yield ['notepad', false]; - yield ['notepad.com', true]; - yield ['notepad.exe', true]; - yield ['notepad.exe.exe', true]; - yield ['notepad.eXe', true]; - yield ['notepad.EXE', true]; - yield ['notepad.bat', true]; - yield ['notepad.txt', false]; + return [['notepad', false], ['notepad.com', true], ['notepad.exe', true], ['notepad.exe.exe', true], ['notepad.eXe', true], ['notepad.EXE', true], ['notepad.bat', true], ['notepad.txt', false]]; } /** + * @test * * @param string $name * @param bool $expected * @dataProvider provideExecutableNames */ - public function testIsExecutableName($name, $expected) + public function isExecutableName($name, $expected) { - $this->assertSame($expected, WindowsSystem::isExecutableName($name), $name); + self::assertSame($expected, WindowsSystem::isExecutableName($name), $name); } }