This commit is contained in:
2020-02-01 16:47:12 +07:00
commit 4c619ad6e6
16739 changed files with 3329179 additions and 0 deletions

View File

@@ -0,0 +1,92 @@
<?php
use Codeception\Configuration;
class C3Test extends \PHPUnit\Framework\TestCase
{
/**
* @var string
*/
public $c3 = null;
/**
* @var string
*/
public $c3_dir = null;
protected function setUp()
{
if (!extension_loaded('xdebug')) {
$this->markTestSkipped('xdebug extension required for c3test.');
}
$this->c3 = Configuration::dataDir() . 'claypit/c3.php';
$this->c3_dir = Codeception\Configuration::outputDir() . 'c3tmp/';
@mkdir($this->c3_dir, 0777, true);
$_SERVER['HTTP_X_CODECEPTION_CODECOVERAGE'] = 'test';
$_SERVER['HTTP_X_CODECEPTION_CODECOVERAGE_DEBUG'] = 'debug';
}
protected function tearDown()
{
unset($_SERVER['HTTP_X_CODECEPTION_CODECOVERAGE_DEBUG']);
unset($_SERVER['HTTP_X_CODECEPTION_CODECOVERAGE']);
\Codeception\Util\FileSystem::deleteDir($this->c3_dir);
}
public function testC3CodeCoverageStarted()
{
if (defined('HHVM_VERSION')) {
$this->markTestSkipped('This test fails on HHVM');
}
$_SERVER['REQUEST_URI'] = '/';
include $this->c3;
$this->assertInstanceOf('PHP_CodeCoverage', $codeCoverage);
}
public function testCodeCoverageRestrictedAccess()
{
unset($_SERVER['HTTP_X_CODECEPTION_CODECOVERAGE']);
include $this->c3;
$this->assertFalse(isset($config_file));
$this->assertFalse(isset($requested_c3_report));
}
public function testCodeCoverageCleanup()
{
$_SERVER['REQUEST_URI'] = '/c3/report/clear';
$cc_file = $this->c3_dir . 'dummy.txt';
file_put_contents($cc_file, 'nothing');
include $this->c3;
$this->assertEquals('clear', $route);
$this->assertFileNotExists($cc_file);
}
public function testCodeCoverageHtmlReport()
{
if (defined('HHVM_VERSION')) {
$this->markTestSkipped('Remote coverage HTML report does not work on HHVM');
}
$_SERVER['REQUEST_URI'] = '/c3/report/html';
include $this->c3;
$this->assertEquals('html', $route);
$this->assertFileExists($this->c3_dir . 'codecoverage.tar');
}
public function testCodeCoverageXmlReport()
{
$_SERVER['REQUEST_URI'] = '/c3/report/clover';
include $this->c3;
$this->assertEquals('clover', $route);
$this->assertFileExists($this->c3_dir . 'codecoverage.clover.xml');
}
public function testCodeCoverageSerializedReport()
{
$_SERVER['REQUEST_URI'] = '/c3/report/serialized';
include $this->c3;
$this->assertEquals('serialized', $route);
$this->assertInstanceOf('PHP_CodeCoverage', $codeCoverage);
}
}

View File

@@ -0,0 +1,28 @@
<?php
namespace Codeception;
class ApplicationTest extends \PHPUnit\Framework\TestCase
{
public static function setUpBeforeClass()
{
require_once \Codeception\Configuration::dataDir() . 'register_command/examples/MyCustomCommand.php';
}
public function testRegisterCustomCommand()
{
\Codeception\Configuration::append(array('extensions' => array(
'commands' => array(
'Project\Command\MyCustomCommand'))));
$application = new Application();
$application->registerCustomCommands();
try {
$application->find('myProject:myCommand');
} catch (\Exception $e) {
$this->fail($e->getMessage());
}
}
}

View File

@@ -0,0 +1,97 @@
<?php
use Codeception\Util\Stub;
use Codeception\Application;
use Symfony\Component\Console\Tester\CommandTester;
class BaseCommandRunner extends \PHPUnit\Framework\TestCase
{
/**
* @var \Codeception\Command\Base
*/
protected $command;
public $filename = "";
public $content = "";
public $output = "";
public $config = [];
public $saved = [];
protected $commandName = 'do:stuff';
protected function execute($args = [], $isSuite = true)
{
$app = new Application();
$app->add($this->command);
$default = \Codeception\Configuration::$defaultConfig;
$default['paths']['tests'] = __DIR__;
$conf = $isSuite
? \Codeception\Configuration::suiteSettings('unit', $default)
: $default;
$this->config = array_merge($conf, $this->config);
$commandTester = new CommandTester($app->find($this->commandName));
$args['command'] = $this->commandName;
$commandTester->execute($args, ['interactive' => false]);
$this->output = $commandTester->getDisplay();
}
protected function makeCommand($className, $saved = true, $extraMethods = [])
{
if (!$this->config) {
$this->config = [];
}
$self = $this;
$mockedMethods = [
'createFile' => function ($file, $output) use ($self, $saved) {
if (!$saved) {
return false;
}
$self->filename = $file;
$self->content = $output;
$self->log[] = ['filename' => $file, 'content' => $output];
$self->saved[$file] = $output;
return true;
},
'getGlobalConfig' => function () use ($self) {
return $self->config;
},
'getSuiteConfig' => function () use ($self) {
return $self->config;
},
'createDirectoryFor' => function ($path, $testName) {
$path = rtrim($path, DIRECTORY_SEPARATOR);
$testName = str_replace(['/', '\\'], [DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR], $testName);
return pathinfo($path . DIRECTORY_SEPARATOR . $testName, PATHINFO_DIRNAME) . DIRECTORY_SEPARATOR;
},
'getSuites' => function () {
return ['shire'];
},
'getApplication' => function () {
return new \Codeception\Util\Maybe;
}
];
$mockedMethods = array_merge($mockedMethods, $extraMethods);
$this->command = Stub::construct(
$className,
[$this->commandName],
$mockedMethods
);
}
protected function assertIsValidPhp($php)
{
$temp_file = tempnam(sys_get_temp_dir(), 'CodeceptionUnitTest');
file_put_contents($temp_file, $php);
exec('php -l ' . $temp_file, $output, $code);
unlink($temp_file);
$this->assertEquals(0, $code, $php);
}
}

View File

@@ -0,0 +1,49 @@
<?php
require_once __DIR__ . DIRECTORY_SEPARATOR . 'BaseCommandRunner.php';
class BuildTest extends BaseCommandRunner
{
protected function setUp()
{
$this->makeCommand('\Codeception\Command\Build');
$this->config = array(
'actor' => 'HobbitGuy',
'path' => 'tests/shire/',
'modules' => array('enabled' => array('Filesystem', 'EmulateModuleHelper')),
'include' => []
);
}
public function testBuild()
{
$this->execute();
$this->assertContains('class HobbitGuy extends \Codeception\Actor', $this->content);
// inherited methods from Actor
$this->assertContains('@method void wantTo($text)', $this->content);
$this->assertContains('@method void expectTo($prediction)', $this->content);
$this->content = $this->log[0]['content'];
// methods from Filesystem module
$this->assertContains('public function amInPath($path)', $this->content);
$this->assertContains('public function copyDir($src, $dst)', $this->content);
$this->assertContains('public function seeInThisFile($text)', $this->content);
// methods from EmulateHelper
$this->assertContains('public function seeEquals($expected, $actual)', $this->content);
$this->assertContains('HobbitGuyActions.php generated successfully.', $this->output);
$this->assertIsValidPhp($this->content);
}
public function testBuildNamespacedActor()
{
$this->config['namespace'] = 'Shire';
$this->execute();
$this->assertContains('namespace Shire;', $this->content);
$this->assertContains('class HobbitGuy extends \Codeception\Actor', $this->content);
$this->assertContains('use _generated\HobbitGuyActions;', $this->content);
$this->assertIsValidPhp($this->content);
}
}

View File

@@ -0,0 +1,54 @@
<?php
require_once __DIR__ . DIRECTORY_SEPARATOR . 'BaseCommandRunner.php';
class GenerateCeptTest extends BaseCommandRunner
{
protected function setUp()
{
$this->makeCommand('\Codeception\Command\GenerateCept');
$this->config = array(
'actor' => 'HobbitGuy',
'path' => 'tests/shire',
);
}
public function testGenerateBasic()
{
$this->execute(array('suite' => 'shire', 'test' => 'HomeCanInclude12Dwarfs'));
$this->assertEquals($this->filename, 'tests/shire/HomeCanInclude12DwarfsCept.php');
$this->assertContains('$I = new HobbitGuy($scenario);', $this->content);
$this->assertContains('Test was created in tests/shire/HomeCanInclude12DwarfsCept.php', $this->output);
$this->assertIsValidPhp($this->content);
}
public function testGenerateWithSuffix()
{
$this->execute(array('suite' => 'shire', 'test' => 'HomeCanInclude12DwarfsCept'));
$this->assertEquals($this->filename, 'tests/shire/HomeCanInclude12DwarfsCept.php');
$this->assertIsValidPhp($this->content);
}
/**
* @group command
*/
public function testGenerateWithFullName()
{
$this->execute(array('suite' => 'shire', 'test' => 'HomeCanInclude12DwarfsCept.php'));
$this->assertEquals($this->filename, 'tests/shire/HomeCanInclude12DwarfsCept.php');
$this->assertIsValidPhp($this->content);
}
/**
* @group command
*/
public function testGenerateWithGuyNamespaced()
{
$this->config['namespace'] = 'MiddleEarth';
$this->execute(array('suite' => 'shire', 'test' => 'HomeCanInclude12Dwarfs'));
$this->assertEquals($this->filename, 'tests/shire/HomeCanInclude12DwarfsCept.php');
$this->assertContains('use MiddleEarth\HobbitGuy;', $this->content);
$this->assertContains('$I = new HobbitGuy($scenario);', $this->content);
$this->assertIsValidPhp($this->content);
}
}

View File

@@ -0,0 +1,94 @@
<?php
require_once __DIR__ . DIRECTORY_SEPARATOR . 'BaseCommandRunner.php';
class GenerateCestTest extends BaseCommandRunner
{
protected function setUp()
{
$this->makeCommand('\Codeception\Command\GenerateCest');
$this->config = array(
'actor' => 'HobbitGuy',
'path' => 'tests/shire',
);
}
/**
* @group command
*/
public function testBasic()
{
$this->execute(array('suite' => 'shire', 'class' => 'HallUnderTheHill'));
$this->assertEquals('tests/shire/HallUnderTheHillCest.php', $this->filename);
$this->assertContains('class HallUnderTheHillCest', $this->content);
$this->assertContains('public function _before(HobbitGuy $I)', $this->content);
$this->assertContains('public function _after(HobbitGuy $I)', $this->content);
$this->assertContains('public function tryToTest(HobbitGuy $I)', $this->content);
$this->assertContains('Test was created in tests/shire/HallUnderTheHillCest.php', $this->output);
}
/**
* @group command
*/
public function testNamespaced()
{
$this->config['namespace'] = 'Shire';
$this->execute(array('suite' => 'shire', 'class' => 'HallUnderTheHill'));
$this->assertContains('namespace Shire;', $this->content);
$this->assertContains('use Shire\HobbitGuy;', $this->content);
$this->assertContains('class HallUnderTheHillCest', $this->content);
}
/**
* @group command
*/
public function testGenerateWithFullName()
{
$this->execute(array('suite' => 'shire', 'class' => 'HomeCanInclude12DwarfsCest.php'));
$this->assertEquals('tests/shire/HomeCanInclude12DwarfsCest.php', $this->filename);
}
/**
* @group command
*/
public function testGenerateWithSuffix()
{
$this->execute(array('suite' => 'shire', 'class' => 'HomeCanInclude12DwarfsCest'));
$this->assertEquals($this->filename, 'tests/shire/HomeCanInclude12DwarfsCest.php');
$this->assertIsValidPhp($this->content);
}
public function testGenerateWithGuyNamespaced()
{
$this->config['namespace'] = 'MiddleEarth';
$this->execute(array('suite' => 'shire', 'class' => 'HallUnderTheHillCest'));
$this->assertEquals($this->filename, 'tests/shire/HallUnderTheHillCest.php');
$this->assertContains('namespace MiddleEarth;', $this->content);
$this->assertContains('use MiddleEarth\\HobbitGuy;', $this->content);
$this->assertContains('public function tryToTest(HobbitGuy $I)', $this->content);
$this->assertIsValidPhp($this->content);
}
public function testCreateWithNamespace()
{
$this->execute(array('suite' => 'shire', 'class' => 'MiddleEarth\HallUnderTheHillCest'));
$this->assertEquals('tests/shire/MiddleEarth/HallUnderTheHillCest.php', $this->filename);
$this->assertContains('namespace MiddleEarth;', $this->content);
$this->assertContains('class HallUnderTheHillCest', $this->content);
$this->assertContains('Test was created in tests/shire/MiddleEarth/HallUnderTheHillCest.php', $this->output);
}
public function testGenerateWithSuiteNamespace()
{
$this->config['suite_namespace'] = 'MiddleEarth\\Bosses\\';
$this->config['namespace'] = 'MiddleEarth';
$this->config['actor'] = 'HobbitGuy';
$this->execute(array('suite' => 'shire', 'class' => 'HallUnderTheHillCest'));
$this->assertEquals($this->filename, 'tests/shire/HallUnderTheHillCest.php');
$this->assertContains('namespace MiddleEarth\\Bosses;', $this->content);
$this->assertContains('use MiddleEarth\\HobbitGuy', $this->content);
$this->assertContains('public function tryToTest(HobbitGuy $I)', $this->content);
$this->assertIsValidPhp($this->content);
}
}

View File

@@ -0,0 +1,30 @@
<?php
require_once __DIR__ . DIRECTORY_SEPARATOR . 'BaseCommandRunner.php';
class GenerateEnvironmentTest extends BaseCommandRunner
{
protected function setUp()
{
$this->makeCommand('\Codeception\Command\GenerateEnvironment');
$this->config = [
'class_name' => 'HobbitGuy',
'path' => 'tests/shire',
'paths' => ['envs' => 'tests/_envs','tests' => 'tests'],
];
}
public function testCreated()
{
$this->execute(['env' => 'firefox']);
$this->assertContains('firefox config was created in tests/_envs/firefox.yml', $this->output);
$this->assertEquals('tests/_envs/firefox.yml', $this->filename);
}
public function testFailed()
{
$this->makeCommand('\Codeception\Command\GenerateEnvironment', false);
$this->execute(['env' => 'firefox']);
$this->assertContains('File tests/_envs/firefox.yml already exists', $this->output);
}
}

View File

@@ -0,0 +1,42 @@
<?php
require_once __DIR__ . DIRECTORY_SEPARATOR . 'BaseCommandRunner.php';
class GenerateGroupTest extends BaseCommandRunner
{
protected function setUp()
{
$this->makeCommand('\Codeception\Command\GenerateGroup');
$this->config = array(
'class_name' => 'HobbitGuy',
'path' => 'tests/shire',
'paths' => array('support' => 'tests/_support','tests' => 'tests'),
'settings' => array('bootstrap' => '_bootstrap.php')
);
}
public function testBasic()
{
$this->execute(array('group' => 'Core'));
$generated = $this->log[0];
$this->assertEquals(\Codeception\Configuration::supportDir().'Group/Core.php', $generated['filename']);
$this->assertContains('namespace Group;', $generated['content']);
$this->assertContains('class Core', $generated['content']);
$this->assertContains('public function _before', $generated['content']);
$this->assertContains('public function _after', $generated['content']);
$this->assertContains('static $group = \'core\'', $generated['content']);
$this->assertIsValidPhp($generated['content']);
}
public function testNamespace()
{
$this->config['namespace'] = 'Shire';
$this->execute(array('group' => 'Core'));
$generated = $this->log[0];
$this->assertEquals(\Codeception\Configuration::supportDir().'Group/Core.php', $generated['filename']);
$this->assertContains('namespace Shire\Group;', $generated['content']);
$this->assertIsValidPhp($generated['content']);
}
}

View File

@@ -0,0 +1,70 @@
<?php
require_once __DIR__ . DIRECTORY_SEPARATOR . 'BaseCommandRunner.php';
class GeneratePageObjectTest extends BaseCommandRunner
{
protected function setUp()
{
$this->makeCommand('\Codeception\Command\GeneratePageObject');
$this->config = array(
'actor' => 'HobbitGuy',
'path' => 'tests/shire',
'paths' => array('tests' => 'tests'),
'settings' => array('bootstrap' => '_bootstrap.php')
);
}
public function testBasic()
{
unset($this->config['actor']);
$this->execute(array('suite' => 'Login'), false);
$this->assertEquals(\Codeception\Configuration::supportDir().'Page/Login.php', $this->filename);
$this->assertContains('class Login', $this->content);
$this->assertContains('public static', $this->content);
$this->assertNotContains('public function __construct', $this->content);
$this->assertIsValidPhp($this->content);
}
public function testNamespace()
{
unset($this->config['actor']);
$this->config['namespace'] = 'MiddleEarth';
$this->execute(array('suite' => 'Login'), false);
$this->assertEquals(\Codeception\Configuration::supportDir().'Page/Login.php', $this->filename);
$this->assertContains('namespace MiddleEarth\Page;', $this->content);
$this->assertContains('class Login', $this->content);
$this->assertContains('public static', $this->content);
$this->assertIsValidPhp($this->content);
}
public function testCreateForSuite()
{
$this->execute(array('suite' => 'shire', 'page' => 'Login'));
$this->assertEquals(\Codeception\Configuration::supportDir().'Page/Shire/Login.php', $this->filename);
$this->assertContains('namespace Page\Shire;', $this->content);
$this->assertContains('class Login', $this->content);
$this->assertContains('protected $hobbitGuy;', $this->content);
$this->assertContains('public function __construct(\HobbitGuy $I)', $this->content);
$this->assertIsValidPhp($this->content);
}
public function testCreateForSuiteWithNamespace()
{
$this->config['namespace'] = 'MiddleEarth';
$this->execute(array('suite' => 'shire', 'page' => 'Login'));
$this->assertEquals(\Codeception\Configuration::supportDir().'Page/Shire/Login.php', $this->filename);
$this->assertContains('namespace MiddleEarth\Page\Shire;', $this->content);
$this->assertContains('class Login', $this->content);
$this->assertContains('protected $hobbitGuy;', $this->content);
$this->assertContains('public function __construct(\MiddleEarth\HobbitGuy $I)', $this->content);
$this->assertIsValidPhp($this->content);
}
public function testCreateInSubpath()
{
$this->execute(array('suite' => 'User/View'));
$this->assertEquals(\Codeception\Configuration::supportDir().'Page/User/View.php', $this->filename);
$this->assertIsValidPhp($this->content);
}
}

View File

@@ -0,0 +1,107 @@
<?php
use Codeception\Lib\ModuleContainer;
use Codeception\Util\Stub;
require_once __DIR__ . DIRECTORY_SEPARATOR . 'BaseCommandRunner.php';
class GenerateScenarioTest extends BaseCommandRunner
{
/**
* @var ModuleContainer
*/
protected $moduleContainer;
protected function setUp()
{
$this->moduleContainer = new ModuleContainer(Stub::make('Codeception\Lib\Di'), []);
$this->moduleContainer->create('EmulateModuleHelper');
$this->modules = $this->moduleContainer->all();
$this->actions = $this->moduleContainer->getActions();
$this->filename = null;
$this->makeCommand('\Codeception\Command\GenerateScenarios');
$this->config = array(
'paths' => array(
'tests' => 'tests/data/claypit/tests/',
'data' => '_data',
),
'class_name' => 'DumbGuy',
'path' => 'tests/data/claypit/tests/dummy/'
);
}
public function testBasic()
{
$this->execute(array('suite' => 'dummy'));
$file = codecept_root_dir().'tests/data/scenarios/dummy/File_Exists.txt';
$this->assertArrayHasKey($file, $this->saved);
$content = $this->saved[$file];
$this->assertContains('I WANT TO CHECK CONFIG EXISTS', $content);
$this->assertContains('I see file found "$codeception"', $content);
$this->assertContains('* File_Exists generated', $this->output);
}
public function testMultipleTestsGeneration()
{
$this->execute(['suite' => 'dummy']);
$this->assertArrayHasKey(codecept_root_dir().'tests/data/scenarios/dummy/Another.optimistic.txt', $this->saved);
$this->assertArrayHasKey(codecept_root_dir().'tests/data/scenarios/dummy/Another.pessimistic.txt', $this->saved);
$file = codecept_root_dir().'tests/data/scenarios/dummy/File_Exists.txt';
$this->assertArrayHasKey($file, $this->saved);
$content = $this->saved[$file];
$this->assertContains('I WANT TO CHECK CONFIG EXISTS', $content);
$this->assertContains('I see file found "$codeception"', $content);
$this->assertContains('* File_Exists generated', $this->output);
}
public function testHtml()
{
$this->execute(array('suite' => 'dummy', '--format' => 'html'));
$file = codecept_root_dir().'tests/data/scenarios/dummy/File_Exists.html';
$this->assertArrayHasKey($file, $this->saved);
$content = $this->saved[$file];
$this->assertContains('<html><body><h3>I WANT TO CHECK CONFIG EXISTS</h3>', $content);
$this->assertContains('I see file found &quot;$codeception&quot;', strip_tags($content));
$this->assertContains('* File_Exists generated', $this->output);
}
public function testOneFile()
{
$this->config['path'] = 'tests/data/claypit/tests/skipped/';
$this->config['class_name'] = 'SkipGuy';
$this->execute(array('suite' => 'skipped', '--single-file' => true));
$this->assertEquals(codecept_root_dir().'tests/data/scenarios/skipped.txt', $this->filename);
$this->assertContains('I WANT TO SKIP IT', $this->content);
$this->assertContains('I WANT TO MAKE IT INCOMPLETE', $this->content);
$this->assertContains('* Skip_Me rendered', $this->output);
$this->assertContains('* Incomplete_Me rendered', $this->output);
}
public function testOneFileWithHtml()
{
$this->config['path'] = 'tests/data/claypit/tests/skipped/';
$this->config['class_name'] = 'SkipGuy';
$this->execute(array('suite' => 'skipped', '--single-file' => true, '--format' => 'html'));
$this->assertEquals(codecept_root_dir().'tests/data/scenarios/skipped.html', $this->filename);
$this->assertContains('<h3>I WANT TO MAKE IT INCOMPLETE</h3>', $this->content);
$this->assertContains('<h3>I WANT TO SKIP IT</h3>', $this->content);
$this->assertContains('<body><h3>', $this->content);
$this->assertContains('</body></html>', $this->content);
$this->assertContains('* Skip_Me rendered', $this->output);
$this->assertContains('* Incomplete_Me rendered', $this->output);
}
public function testDifferentPath()
{
$this->execute(array('suite' => 'dummy', '--single-file' => true, '--path' => 'docs'));
$this->assertEquals('docs/dummy.txt', $this->filename);
$this->assertContains('I WANT TO CHECK CONFIG EXISTS', $this->content);
$this->assertContains('* File_Exists rendered', $this->output);
}
}

View File

@@ -0,0 +1,52 @@
<?php
require_once __DIR__ . DIRECTORY_SEPARATOR . 'BaseCommandRunner.php';
class GenerateStepObjectTest extends BaseCommandRunner
{
protected function setUp()
{
$this->makeCommand('\Codeception\Command\GenerateStepObject');
$this->config = array(
'actor' => 'HobbitGuy',
'path' => 'tests/shire',
);
}
public function testBasic()
{
$this->execute(array('suite' => 'shire', 'step' => 'Login', '--silent' => true));
$generated = $this->log[0];
$this->assertEquals(\Codeception\Configuration::supportDir().'Step/Shire/Login.php', $generated['filename']);
$this->assertContains('class Login extends \HobbitGuy', $generated['content']);
$this->assertContains('namespace Step\\Shire;', $generated['content']);
$this->assertIsValidPhp($generated['content']);
$this->assertIsValidPhp($this->content);
}
public function testNamespace()
{
$this->config['namespace'] = 'MiddleEarth';
$this->execute(array('suite' => 'shire', 'step' => 'Login', '--silent' => true));
$generated = $this->log[0];
$this->assertEquals(\Codeception\Configuration::supportDir().'Step/Shire/Login.php', $generated['filename']);
$this->assertContains('namespace MiddleEarth\Step\Shire;', $generated['content']);
$this->assertContains('class Login extends \MiddleEarth\HobbitGuy', $generated['content']);
$this->assertIsValidPhp($generated['content']);
$this->assertIsValidPhp($this->content);
}
public function testCreateInSubpath()
{
$this->execute(array('suite' => 'shire', 'step' => 'User/Login', '--silent' => true));
$generated = $this->log[0];
$this->assertEquals(
\Codeception\Configuration::supportDir().'Step/Shire/User/Login.php',
$generated['filename']
);
$this->assertIsValidPhp($this->content);
}
}

View File

@@ -0,0 +1,49 @@
<?php
require_once __DIR__ . DIRECTORY_SEPARATOR . 'BaseCommandRunner.php';
class GenerateSuiteTest extends BaseCommandRunner
{
public $config = ['actor_suffix' => 'Guy'];
protected function setUp()
{
$this->makeCommand('\Codeception\Command\GenerateSuite');
}
public function testBasic()
{
$this->execute(array('suite' => 'shire', 'actor' => 'Hobbit'), false);
$configFile = $this->log[1];
$this->assertEquals(\Codeception\Configuration::projectDir().'tests/shire.suite.yml', $configFile['filename']);
$conf = \Symfony\Component\Yaml\Yaml::parse($configFile['content']);
$this->assertEquals('Hobbit', $conf['actor']);
$this->assertContains('\Helper\Shire', $conf['modules']['enabled']);
$this->assertContains('Suite shire generated', $this->output);
$actor = $this->log[2];
$this->assertEquals(\Codeception\Configuration::supportDir().'Hobbit.php', $actor['filename']);
$this->assertContains('class Hobbit extends \Codeception\Actor', $actor['content']);
$helper = $this->log[0];
$this->assertEquals(\Codeception\Configuration::supportDir().'Helper/Shire.php', $helper['filename']);
$this->assertContains('namespace Helper;', $helper['content']);
$this->assertContains('class Shire extends \Codeception\Module', $helper['content']);
}
public function testGuyWithSuffix()
{
$this->execute(array('suite' => 'shire', 'actor' => 'HobbitTester'), false);
$configFile = $this->log[1];
$conf = \Symfony\Component\Yaml\Yaml::parse($configFile['content']);
$this->assertEquals('HobbitTester', $conf['actor']);
$this->assertContains('\Helper\Shire', $conf['modules']['enabled']);
$helper = $this->log[0];
$this->assertEquals(\Codeception\Configuration::supportDir().'Helper/Shire.php', $helper['filename']);
$this->assertContains('class Shire extends \Codeception\Module', $helper['content']);
}
}

View File

@@ -0,0 +1,57 @@
<?php
require_once __DIR__ . DIRECTORY_SEPARATOR . 'BaseCommandRunner.php';
class GenerateTestTest extends BaseCommandRunner
{
protected function setUp()
{
$this->makeCommand('\Codeception\Command\GenerateTest');
$this->config = array(
'actor' => 'HobbitGuy',
'path' => 'tests/shire',
);
}
public function testBasic()
{
$this->execute(array('suite' => 'shire', 'class' => 'HallUnderTheHill'));
$this->assertEquals('tests/shire/HallUnderTheHillTest.php', $this->filename);
$this->assertContains('class HallUnderTheHillTest extends \Codeception\Test\Unit', $this->content);
$this->assertContains('Test was created in tests/shire/HallUnderTheHillTest.php', $this->output);
$this->assertContains('protected function _before()', $this->content);
$this->assertContains('protected function _after()', $this->content);
}
public function testCreateWithSuffix()
{
$this->execute(array('suite' => 'shire', 'class' => 'HallUnderTheHillTest'));
$this->assertEquals('tests/shire/HallUnderTheHillTest.php', $this->filename);
$this->assertContains('Test was created in tests/shire/HallUnderTheHillTest.php', $this->output);
}
public function testCreateWithNamespace()
{
$this->execute(array('suite' => 'shire', 'class' => 'MiddleEarth\HallUnderTheHillTest'));
$this->assertEquals('tests/shire/MiddleEarth/HallUnderTheHillTest.php', $this->filename);
$this->assertContains('namespace MiddleEarth;', $this->content);
$this->assertContains('class HallUnderTheHillTest extends \Codeception\Test\Unit', $this->content);
$this->assertContains('Test was created in tests/shire/MiddleEarth/HallUnderTheHillTest.php', $this->output);
}
public function testCreateWithExtension()
{
$this->execute(array('suite' => 'shire', 'class' => 'HallUnderTheHillTest.php'));
$this->assertEquals('tests/shire/HallUnderTheHillTest.php', $this->filename);
$this->assertContains('class HallUnderTheHillTest extends \Codeception\Test\Unit', $this->content);
$this->assertContains('protected $tester;', $this->content);
$this->assertContains('@var \HobbitGuy', $this->content);
$this->assertContains('Test was created in tests/shire/HallUnderTheHillTest.php', $this->output);
}
public function testValidPHP()
{
$this->execute(array('suite' => 'shire', 'class' => 'HallUnderTheHill'));
$this->assertIsValidPhp($this->content);
}
}

View File

@@ -0,0 +1,22 @@
<?php
namespace Project\Command;
class MyCustomCommandTest extends \PHPUnit\Framework\TestCase
{
public static function setUpBeforeClass()
{
require_once \Codeception\Configuration::dataDir() . 'register_command/examples/MyCustomCommand.php';
}
public function testHasCodeceptionCustomCommandInterface()
{
$command = new MyCustomCommand('commandName');
$this->assertInstanceOf('Codeception\CustomCommandInterface', $command);
}
public function testHasCommandName()
{
$commandName = MyCustomCommand::getCommandName();
$this->assertEquals('myProject:myCommand', $commandName);
}
}

View File

@@ -0,0 +1,46 @@
<?php
require_once __DIR__ . DIRECTORY_SEPARATOR . 'BaseCommandRunner.php';
class SelfUpdateTest extends BaseCommandRunner
{
const COMMAND_CLASS = '\Codeception\Command\SelfUpdate';
public function testHasUpdate()
{
$this->setUpCommand('2.1.2', ['2.1.0-beta', '2.1.2', '2.1.3', '2.2.0-RC2']);
$this->execute();
$this->assertContains('Codeception version 2.1.2', $this->output);
$this->assertContains('A newer version is available: 2.1.3', $this->output);
}
public function testAlreadyLatest()
{
$this->setUpCommand('2.1.8', ['2.1.0-beta', '2.1.7', '2.1.8', '2.2.0-RC2']);
$this->execute();
$this->assertContains('Codeception version 2.1.8', $this->output);
$this->assertContains('You are already using the latest version.', $this->output);
}
/**
* @param string $version
* @param array $tags
*/
protected function setUpCommand($version, $tags)
{
$this->makeCommand(
self::COMMAND_CLASS,
false,
[
'getCurrentVersion' => function () use ($version) {
return $version;
},
'getGithubTags' => function () use ($tags) {
return $tags;
}
]
);
$this->config = [];
}
}

View File

@@ -0,0 +1,72 @@
<?php
class ConfigurationTest extends \PHPUnit\Framework\TestCase
{
public function setUp()
{
$this->config = \Codeception\Configuration::config();
}
protected function tearDown()
{
\Codeception\Module\UniversalFramework::$includeInheritedActions = true;
\Codeception\Module\UniversalFramework::$onlyActions = [];
\Codeception\Module\UniversalFramework::$excludeActions = [];
}
/**
* @group core
*/
public function testSuites()
{
$suites = \Codeception\Configuration::suites();
$this->assertContains('unit', $suites);
$this->assertContains('cli', $suites);
}
/**
* @group core
*/
public function testFunctionForStrippingClassNames()
{
$matches = array();
$this->assertEquals(1, preg_match('~\\\\?(\\w*?Helper)$~', '\\Codeception\\Module\\UserHelper', $matches));
$this->assertEquals('UserHelper', $matches[1]);
$this->assertEquals(1, preg_match('~\\\\?(\\w*?Helper)$~', 'UserHelper', $matches));
$this->assertEquals('UserHelper', $matches[1]);
}
/**
* @group core
*/
public function testModules()
{
$settings = array('modules' => array('enabled' => array('EmulateModuleHelper')));
$modules = \Codeception\Configuration::modules($settings);
$this->assertContains('EmulateModuleHelper', $modules);
$settings = array('modules' => array(
'enabled' => array('EmulateModuleHelper'),
'disabled' => array('EmulateModuleHelper'),
));
$modules = \Codeception\Configuration::modules($settings);
$this->assertNotContains('EmulateModuleHelper', $modules);
}
/**
* @group core
*/
public function testDefaultCustomCommandConfig()
{
$defaultConfig = \Codeception\Configuration::$defaultConfig;
$this->assertArrayHasKey('extensions', $defaultConfig);
$commandsConfig = $defaultConfig['extensions'];
$this->assertArrayHasKey('commands', $commandsConfig);
$this->assertArrayHasKey('extends', $defaultConfig);
$this->assertNull($defaultConfig['extends']);
}
}

View File

@@ -0,0 +1,73 @@
<?php
class CrawlerConstraintTest extends \PHPUnit\Framework\TestCase
{
/**
* @var Codeception\PHPUnit\Constraint\Crawler
*/
protected $constraint;
public function setUp()
{
$this->constraint = new Codeception\PHPUnit\Constraint\Crawler('hello', '/user');
}
public function testEvaluation()
{
$nodes = new Symfony\Component\DomCrawler\Crawler("<p>Bye world</p><p>Hello world</p>");
$this->constraint->evaluate($nodes);
}
public function testFailMessageResponse()
{
$nodes = new Symfony\Component\DomCrawler\Crawler('<p>Bye world</p><p>Bye warcraft</p>');
try {
$this->constraint->evaluate($nodes->filter('p'), 'selector');
} catch (\PHPUnit\Framework\AssertionFailedError $fail) {
$this->assertContains(
"Failed asserting that any element by 'selector' on page /user",
$fail->getMessage()
);
$this->assertContains('+ <p>Bye world</p>', $fail->getMessage());
$this->assertContains('+ <p>Bye warcraft</p>', $fail->getMessage());
return;
}
$this->fail("should have failed, but not");
}
public function testFailMessageResponseWhenMoreNodes()
{
$html = '';
for ($i = 0; $i < 15; $i++) {
$html .= "<p>item $i</p>";
}
$nodes = new Symfony\Component\DomCrawler\Crawler($html);
try {
$this->constraint->evaluate($nodes->filter('p'), 'selector');
} catch (\PHPUnit\Framework\AssertionFailedError $fail) {
$this->assertContains(
"Failed asserting that any element by 'selector' on page /user",
$fail->getMessage()
);
$this->assertNotContains('+ <p>item 0</p>', $fail->getMessage());
$this->assertNotContains('+ <p>item 14</p>', $fail->getMessage());
$this->assertContains('[total 15 elements]', $fail->getMessage());
return;
}
$this->fail("should have failed, but not");
}
public function testFailMessageResponseWithoutUrl()
{
$this->constraint = new Codeception\PHPUnit\Constraint\Crawler('hello');
$nodes = new Symfony\Component\DomCrawler\Crawler('<p>Bye world</p><p>Bye warcraft</p>');
try {
$this->constraint->evaluate($nodes->filter('p'), 'selector');
} catch (\PHPUnit\Framework\AssertionFailedError $fail) {
$this->assertContains("Failed asserting that any element by 'selector'", $fail->getMessage());
$this->assertNotContains("Failed asserting that any element by 'selector' on page", $fail->getMessage());
return;
}
$this->fail("should have failed, but not");
}
}

View File

@@ -0,0 +1,66 @@
<?php
class CrawlerNotConstraintTest extends \PHPUnit\Framework\TestCase
{
/**
* @var Codeception\PHPUnit\Constraint\Crawler
*/
protected $constraint;
public function setUp()
{
$this->constraint = new Codeception\PHPUnit\Constraint\CrawlerNot('warcraft', '/user');
}
public function testEvaluation()
{
$nodes = new Symfony\Component\DomCrawler\Crawler("<p>Bye world</p><p>Hello world</p>");
$this->constraint->evaluate($nodes);
}
public function testFailMessageResponse()
{
$nodes = new Symfony\Component\DomCrawler\Crawler('<p>Bye world</p><p>Bye warcraft</p>');
try {
$this->constraint->evaluate($nodes->filter('p'), 'selector');
} catch (\PHPUnit\Framework\AssertionFailedError $fail) {
$this->assertContains("There was 'selector' element on page /user", $fail->getMessage());
$this->assertNotContains('+ <p>Bye world</p>', $fail->getMessage());
$this->assertContains('+ <p>Bye warcraft</p>', $fail->getMessage());
return;
}
$this->fail("should have failed, but not");
}
public function testFailMessageResponseWhenMoreNodes()
{
$html = '';
for ($i = 0; $i < 15; $i++) {
$html .= "<p>warcraft $i</p>";
}
$nodes = new Symfony\Component\DomCrawler\Crawler($html);
try {
$this->constraint->evaluate($nodes->filter('p'), 'selector');
} catch (\PHPUnit\Framework\AssertionFailedError $fail) {
$this->assertContains("There was 'selector' element on page /user", $fail->getMessage());
$this->assertContains('+ <p>warcraft 0</p>', $fail->getMessage());
$this->assertContains('+ <p>warcraft 14</p>', $fail->getMessage());
return;
}
$this->fail("should have failed, but not");
}
public function testFailMessageResponseWithoutUrl()
{
$this->constraint = new Codeception\PHPUnit\Constraint\CrawlerNot('warcraft');
$nodes = new Symfony\Component\DomCrawler\Crawler('<p>Bye world</p><p>Bye warcraft</p>');
try {
$this->constraint->evaluate($nodes->filter('p'), 'selector');
} catch (\PHPUnit\Framework\AssertionFailedError $fail) {
$this->assertContains("There was 'selector' element", $fail->getMessage());
$this->assertNotContains("There was 'selector' element on page /user", $fail->getMessage());
return;
}
$this->fail("should have failed, but not");
}
}

View File

@@ -0,0 +1,90 @@
<?php
require_once __DIR__.'/mocked_webelement.php';
class WebDriverConstraintTest extends \PHPUnit\Framework\TestCase
{
/**
* @var Codeception\PHPUnit\Constraint\WebDriver
*/
protected $constraint;
public function setUp()
{
$this->constraint = new Codeception\PHPUnit\Constraint\WebDriver('hello', '/user');
}
public function testEvaluation()
{
$nodes = array(new TestedWebElement('Hello world'), new TestedWebElement('Bye world'));
$this->constraint->evaluate($nodes);
}
public function testFailMessageResponseWithStringSelector()
{
$nodes = array(new TestedWebElement('Bye warcraft'), new TestedWebElement('Bye world'));
try {
$this->constraint->evaluate($nodes, 'selector');
} catch (\PHPUnit\Framework\AssertionFailedError $fail) {
$this->assertContains(
"Failed asserting that any element by 'selector' on page /user",
$fail->getMessage()
);
$this->assertContains('+ <p> Bye world', $fail->getMessage());
$this->assertContains('+ <p> Bye warcraft', $fail->getMessage());
return;
}
$this->fail("should have failed, but not");
}
public function testFailMessageResponseWithArraySelector()
{
$nodes = array(new TestedWebElement('Bye warcraft'));
try {
$this->constraint->evaluate($nodes, ['css' => 'p.mocked']);
} catch (\PHPUnit\Framework\AssertionFailedError $fail) {
$this->assertContains(
"Failed asserting that any element by css 'p.mocked' on page /user",
$fail->getMessage()
);
$this->assertContains('+ <p> Bye warcraft', $fail->getMessage());
return;
}
$this->fail("should have failed, but not");
}
public function testFailMessageResponseWhenMoreNodes()
{
$nodes = array();
for ($i = 0; $i < 15; $i++) {
$nodes[] = new TestedWebElement("item $i");
}
try {
$this->constraint->evaluate($nodes, 'selector');
} catch (\PHPUnit\Framework\AssertionFailedError $fail) {
$this->assertContains(
"Failed asserting that any element by 'selector' on page /user",
$fail->getMessage()
);
$this->assertNotContains('+ <p> item 0', $fail->getMessage());
$this->assertNotContains('+ <p> item 14', $fail->getMessage());
$this->assertContains('[total 15 elements]', $fail->getMessage());
return;
}
$this->fail("should have failed, but not");
}
public function testFailMessageResponseWithoutUrl()
{
$this->constraint = new Codeception\PHPUnit\Constraint\WebDriver('hello');
$nodes = array(new TestedWebElement('Bye warcraft'), new TestedWebElement('Bye world'));
try {
$this->constraint->evaluate($nodes, 'selector');
} catch (\PHPUnit\Framework\AssertionFailedError $fail) {
$this->assertContains("Failed asserting that any element by 'selector'", $fail->getMessage());
$this->assertNotContains("Failed asserting that any element by 'selector' on page", $fail->getMessage());
return;
}
$this->fail("should have failed, but not");
}
}

View File

@@ -0,0 +1,80 @@
<?php
require_once __DIR__.'/mocked_webelement.php';
class WebDriverConstraintNotTest extends \PHPUnit\Framework\TestCase
{
/**
* @var Codeception\PHPUnit\Constraint\WebDriver
*/
protected $constraint;
public function setUp()
{
$this->constraint = new Codeception\PHPUnit\Constraint\WebDriverNot('warcraft', '/user');
}
public function testEvaluation()
{
$nodes = array(new TestedWebElement('Hello world'), new TestedWebElement('Bye world'));
$this->constraint->evaluate($nodes);
}
public function testFailMessageResponseWithStringSelector()
{
$nodes = array(new TestedWebElement('Bye warcraft'), new TestedWebElement('Bye world'));
try {
$this->constraint->evaluate($nodes, 'selector');
} catch (\PHPUnit\Framework\AssertionFailedError $fail) {
$this->assertContains("There was 'selector' element on page /user", $fail->getMessage());
$this->assertNotContains('+ <p> Bye world', $fail->getMessage());
$this->assertContains('+ <p> Bye warcraft', $fail->getMessage());
return;
}
$this->fail("should have failed, but not");
}
public function testFailMessageResponseWithArraySelector()
{
$nodes = array(new TestedWebElement('Bye warcraft'));
try {
$this->constraint->evaluate($nodes, ['css' => 'p.mocked']);
} catch (\PHPUnit\Framework\AssertionFailedError $fail) {
$this->assertContains("There was css 'p.mocked' element on page /user", $fail->getMessage());
$this->assertContains('+ <p> Bye warcraft', $fail->getMessage());
return;
}
$this->fail("should have failed, but not");
}
public function testFailMessageResponseWhenMoreNodes()
{
$nodes = array();
for ($i = 0; $i < 15; $i++) {
$nodes[] = new TestedWebElement("warcraft $i");
}
try {
$this->constraint->evaluate($nodes, 'selector');
} catch (\PHPUnit\Framework\AssertionFailedError $fail) {
$this->assertContains("There was 'selector' element on page /user", $fail->getMessage());
$this->assertContains('+ <p> warcraft 0', $fail->getMessage());
$this->assertContains('+ <p> warcraft 14', $fail->getMessage());
return;
}
$this->fail("should have failed, but not");
}
public function testFailMessageResponseWithoutUrl()
{
$this->constraint = new Codeception\PHPUnit\Constraint\WebDriverNot('warcraft');
$nodes = array(new TestedWebElement('Bye warcraft'), new TestedWebElement('Bye world'));
try {
$this->constraint->evaluate($nodes, 'selector');
} catch (\PHPUnit\Framework\AssertionFailedError $fail) {
$this->assertContains("There was 'selector' element", $fail->getMessage());
$this->assertNotContains("There was 'selector' element on page", $fail->getMessage());
return;
}
$this->fail("should have failed, but not");
}
}

View File

@@ -0,0 +1,25 @@
<?php
class TestedWebElement extends RemoteWebElement
{
protected $value;
public function __construct($value)
{
$this->value = $value;
}
public function getTagName()
{
return 'p';
}
public function getText()
{
return $this->value;
}
public function isDisplayed()
{
return true;
}
}

View File

@@ -0,0 +1,56 @@
<?php
namespace Codeception\Coverage;
use Codeception\Stub;
use SebastianBergmann\CodeCoverage\CodeCoverage;
use SebastianBergmann\CodeCoverage\Driver\Driver;
class FilterTest extends \Codeception\Test\Unit
{
/**
* @var Filter
*/
protected $filter;
protected function _before()
{
$driver = Stub::makeEmpty('SebastianBergmann\CodeCoverage\Driver\Driver');
$this->filter = new Filter(new CodeCoverage($driver));
}
public function testWhitelistFilterApplied()
{
$config = [
'coverage' => [
'whitelist' => [
'include' => [
'tests/*',
'vendor/*/*Test.php',
'src/Codeception/Codecept.php'
],
'exclude' => [
'tests/unit/CodeGuy.php'
]
]
]
];
$this->filter->whiteList($config);
$fileFilter = $this->filter->getFilter();
$this->assertFalse($fileFilter->isFiltered(codecept_root_dir('tests/unit/C3Test.php')));
$this->assertFalse($fileFilter->isFiltered(codecept_root_dir('src/Codeception/Codecept.php')));
$this->assertTrue($fileFilter->isFiltered(codecept_root_dir('vendor/guzzlehttp/guzzle/src/Client.php')));
$this->assertTrue($fileFilter->isFiltered(codecept_root_dir('tests/unit/CodeGuy.php')));
}
public function testShortcutFilter()
{
$config = ['coverage' => [
'include' => ['tests/*'],
'exclude' => ['tests/unit/CodeGuy.php']
]];
$this->filter->whiteList($config);
$fileFilter = $this->filter->getFilter();
$this->assertFalse($fileFilter->isFiltered(codecept_root_dir('tests/unit/C3Test.php')));
$this->assertTrue($fileFilter->isFiltered(codecept_root_dir('tests/unit/CodeGuy.php')));
}
}

View File

@@ -0,0 +1,20 @@
<?php
class ModuleConfigTest extends \PHPUnit\Framework\TestCase
{
// tests
public function testCanBeCreatedForModuleName()
{
$exception = new \Codeception\Exception\ModuleConfigException('Codeception\Module\WebDriver', "Hello world");
$this->assertEquals("WebDriver module is not configured!\n \nHello world", $exception->getMessage());
}
public function testCanBeCreatedForModuleObject()
{
$exception = new \Codeception\Exception\ModuleConfigException(
new \Codeception\Module\CodeHelper(make_container()),
"Hello world"
);
$this->assertEquals("CodeHelper module is not configured!\n \nHello world", $exception->getMessage());
}
}

View File

@@ -0,0 +1,48 @@
<?php
namespace Codeception\Lib\Console;
use Codeception\Test\Unit;
/**
* ColorizerTest
**/
class ColorizerTest extends Unit
{
/**
* @var Colorizer
*/
protected $colorizer;
/**
*
*/
protected function setUp()
{
parent::setUp();
$this->colorizer = new Colorizer();
}
public function testItAddFormatToDiffMessage()
{
$toColorizeInput = <<<PLAIN
foo
bar
+ actual line
- expected line
bar
PLAIN;
$expectedColorized = <<<COLORED
foo
bar
<info>+ actual line</info>
<comment>- expected line</comment>
bar
COLORED;
$actual = $this->colorizer->colorize($toColorizeInput);
$this->assertEquals($expectedColorized, $actual, 'it should add the format tags');
}
}

View File

@@ -0,0 +1,54 @@
<?php
namespace Codeception\Lib\Console;
use SebastianBergmann\Comparator\ComparisonFailure;
/**
* DiffFactoryTest
**/
class DiffFactoryTest extends \Codeception\Test\Unit
{
/**
* @var DiffFactory
*/
protected $diffFactory;
protected function setUp()
{
$this->diffFactory = new DiffFactory();
}
public function testItCreatesMessageForComparisonFailure()
{
$expectedDiff = $this->getExpectedDiff();
$failure = $this->createFailure();
$message = $this->diffFactory->createDiff($failure);
$this->assertEquals($expectedDiff, (string) $message, 'The diff should be generated.');
}
/**
* @return ComparisonFailure
*/
protected function createFailure()
{
$expected = "a\nb";
$actual = "a\nc";
return new ComparisonFailure($expected, $actual, $expected, $actual);
}
/**
* @return string
*/
protected function getExpectedDiff()
{
$expectedDiff = <<<TXT
@@ @@
a
-b
+c
TXT;
return $expectedDiff . "\n";
}
}

View File

@@ -0,0 +1,33 @@
<?php
namespace Codeception\Lib\Console;
class MessageTest extends \Codeception\Test\Unit
{
// tests
public function testCut()
{
$message = new Message('very long text');
$this->assertEquals('very long ', $message->cut(10)->getMessage());
$message = new Message('очень длинный текст');
$this->assertEquals('очень длин', $message->cut(10)->getMessage());
}
//test message cutting
// @codingStandardsIgnoreStart
public function testVeryLongTestNameVeryLongTestNameVeryLongTestNameVeryLongTestNameVeryLongTestNameVeryLongTestNameVeryLongTestName()
{
// @codingStandardsIgnoreEnd
}
// test multibyte message width
public function testWidth()
{
$message = new Message('message example');
$this->assertEquals('message example ', $message->width(30)->getMessage());
$message = new Message('пример текста');
$this->assertEquals('пример текста ', $message->width(30)->getMessage());
}
}

View File

@@ -0,0 +1,50 @@
<?php
namespace Codeception\Lib;
class DiTest extends \Codeception\Test\Unit
{
/**
* @var Di
*/
protected $di;
protected function setUp()
{
$this->di = new Di();
}
protected function injectionShouldFail($msg = '')
{
$this->setExpectedException('Codeception\Exception\InjectionException', $msg);
}
public function testFailDependenciesCyclic()
{
require_once codecept_data_dir().'FailDependenciesCyclic.php';
$this->injectionShouldFail(
'Failed to resolve cyclic dependencies for class \'FailDependenciesCyclic\IncorrectDependenciesClass\''
);
$this->di->instantiate('FailDependenciesCyclic\IncorrectDependenciesClass');
}
public function testFailDependenciesInChain()
{
require_once codecept_data_dir().'FailDependenciesInChain.php';
$this->injectionShouldFail('Failed to resolve dependency \'FailDependenciesInChain\AnotherClass\'');
$this->di->instantiate('FailDependenciesInChain\IncorrectDependenciesClass');
}
public function testFailDependenciesNonExistent()
{
require_once codecept_data_dir().'FailDependenciesNonExistent.php';
$this->injectionShouldFail('Class FailDependenciesNonExistent\NonExistentClass does not exist');
$this->di->instantiate('FailDependenciesNonExistent\IncorrectDependenciesClass');
}
public function testFailDependenciesPrimitiveParam()
{
require_once codecept_data_dir().'FailDependenciesPrimitiveParam.php';
$this->injectionShouldFail('Parameter \'required\' must have default value');
$this->di->instantiate('FailDependenciesPrimitiveParam\IncorrectDependenciesClass');
}
}

View File

@@ -0,0 +1,34 @@
<?php
use \Codeception\Lib\Driver\Db;
use \Codeception\Test\Unit;
use \Codeception\Util\ReflectionHelper;
/**
* @group appveyor
* @group db
*/
class DbTest extends Unit
{
/**
* @dataProvider getWhereCriteria
*/
public function testGenerateWhereClause($criteria, $expectedResult)
{
$db = new Db('sqlite:tests/data/sqlite.db','root','');
$result = ReflectionHelper::invokePrivateMethod($db, 'generateWhereClause', [&$criteria]);
$this->assertEquals($expectedResult, $result);
}
public function getWhereCriteria()
{
return [
'like' => [['email like' => 'mail.ua'], 'WHERE "email" LIKE ? '],
'<=' => [['id <=' => '5'], 'WHERE "id" <= ? '],
'<' => [['id <' => '5'], 'WHERE "id" < ? '],
'>=' => [['id >=' => '5'], 'WHERE "id" >= ? '],
'>' => [['id >' => '5'], 'WHERE "id" > ? '],
'!=' => [['id !=' => '5'], 'WHERE "id" != ? '],
];
}
}

View File

@@ -0,0 +1,151 @@
<?php
use \Codeception\Lib\Driver\Db;
use \Codeception\Test\Unit;
/**
* @group appveyor
* @group db
*/
class MysqlTest extends Unit
{
protected static $config = [
'dsn' => 'mysql:host=localhost;dbname=codeception_test',
'user' => 'root',
'password' => ''
];
protected static $sql;
/**
* @var \Codeception\Lib\Driver\MySql
*/
protected $mysql;
public static function setUpBeforeClass()
{
if (getenv('APPVEYOR')) {
self::$config['password'] = 'Password12!';
}
$sql = file_get_contents(\Codeception\Configuration::dataDir() . '/dumps/mysql.sql');
$sql = preg_replace('%/\*(?:(?!\*/).)*\*/%s', "", $sql);
self::$sql = explode("\n", $sql);
try {
$mysql = Db::create(self::$config['dsn'], self::$config['user'], self::$config['password']);
$mysql->cleanup();
} catch (\Exception $e) {
}
}
public function setUp()
{
try {
$this->mysql = Db::create(self::$config['dsn'], self::$config['user'], self::$config['password']);
} catch (\Exception $e) {
$this->markTestSkipped('Couldn\'t establish connection to database: ' . $e->getMessage());
}
$this->mysql->cleanup();
$this->mysql->load(self::$sql);
}
public function tearDown()
{
if (isset($this->mysql)) {
$this->mysql->cleanup();
}
}
public function testCleanupDatabase()
{
$this->assertNotEmpty($this->mysql->getDbh()->query("SHOW TABLES")->fetchAll());
$this->mysql->cleanup();
$this->assertEmpty($this->mysql->getDbh()->query("SHOW TABLES")->fetchAll());
}
/**
* @group appveyor
*/
public function testLoadDump()
{
$res = $this->mysql->getDbh()->query("select * from users where name = 'davert'");
$this->assertNotEquals(false, $res);
$this->assertGreaterThan(0, $res->rowCount());
$res = $this->mysql->getDbh()->query("select * from groups where name = 'coders'");
$this->assertNotEquals(false, $res);
$this->assertGreaterThan(0, $res->rowCount());
}
public function testGetSingleColumnPrimaryKey()
{
$this->assertEquals(['id'], $this->mysql->getPrimaryKey('order'));
}
public function testGetCompositePrimaryKey()
{
$this->assertEquals(['group_id', 'id'], $this->mysql->getPrimaryKey('composite_pk'));
}
public function testGetEmptyArrayIfTableHasNoPrimaryKey()
{
$this->assertEquals([], $this->mysql->getPrimaryKey('no_pk'));
}
public function testGetPrimaryColumnOfTableUsingReservedWordAsTableName()
{
$this->assertEquals('id', $this->mysql->getPrimaryColumn('order'));
}
public function testGetPrimaryColumnThrowsExceptionIfTableHasCompositePrimaryKey()
{
$this->setExpectedException(
'\Exception',
'getPrimaryColumn method does not support composite primary keys, use getPrimaryKey instead'
);
$this->mysql->getPrimaryColumn('composite_pk');
}
public function testDeleteFromTableUsingReservedWordAsTableName()
{
$this->mysql->deleteQuery('order', 1);
$res = $this->mysql->getDbh()->query("select id from `order` where id = 1");
$this->assertEquals(0, $res->rowCount());
}
public function testDeleteFromTableUsingReservedWordAsPrimaryKey()
{
$this->mysql->deleteQuery('table_with_reserved_primary_key', 1, 'unique');
$res = $this->mysql->getDbh()->query("select name from `table_with_reserved_primary_key` where `unique` = 1");
$this->assertEquals(0, $res->rowCount());
}
public function testSelectWithBooleanParam()
{
$res = $this->mysql->executeQuery("select `id` from `users` where `is_active` = ?", [false]);
$this->assertEquals(1, $res->rowCount());
}
public function testInsertIntoBitField()
{
if (getenv('WERCKER_ROOT')) {
$this->markTestSkipped('Disabled on Wercker CI');
}
$res = $this->mysql->executeQuery(
"insert into `users`(`id`,`name`,`email`,`is_active`,`created_at`) values (?,?,?,?,?)",
[5,'insert.test','insert.test@mail.ua',false,'2012-02-01 21:17:47']
);
$this->assertEquals(1, $res->rowCount());
}
/**
* THis will fail if MariaDb is used
*/
public function testLoadThrowsExceptionWhenDumpFileContainsSyntaxError()
{
$sql = "INSERT INTO `users` (`name`) VALS('')";
$expectedMessage = 'You have an error in your SQL syntax; ' .
'check the manual that corresponds to your MySQL server version for the right syntax to use near ' .
"'VALS('')' at line 1\nSQL query being executed: \n" . $sql;
$this->setExpectedException('Codeception\Exception\ModuleException', $expectedMessage);
$this->mysql->load([$sql]);
}
}

View File

@@ -0,0 +1,160 @@
<?php
use \Codeception\Lib\Driver\Db;
use \Codeception\Test\Unit;
/**
* @group appveyor
* @group db
*/
class PostgresTest extends Unit
{
protected static $config = [
'dsn' => 'pgsql:host=localhost;dbname=codeception_test',
'user' => 'postgres',
'password' => null,
];
protected static $sql;
protected $postgres;
public static function setUpBeforeClass()
{
if (!function_exists('pg_connect')) {
return;
}
if (getenv('APPVEYOR')) {
self::$config['password'] = 'Password12!';
}
$dumpFile = 'dumps/postgres.sql';
if (defined('HHVM_VERSION')) {
$dumpFile = 'dumps/postgres-hhvm.sql';
}
$sql = file_get_contents(codecept_data_dir($dumpFile));
$sql = preg_replace('%/\*(?:(?!\*/).)*\*/%s', '', $sql);
self::$sql = explode("\n", $sql);
}
public function setUp()
{
try {
$this->postgres = Db::create(self::$config['dsn'], self::$config['user'], self::$config['password']);
$this->postgres->cleanup();
} catch (\Exception $e) {
$this->markTestSkipped('Coudn\'t establish connection to database: ' . $e->getMessage());
}
$this->postgres->load(self::$sql);
}
public function tearDown()
{
if (isset($this->postgres)) {
$this->postgres->cleanup();
}
}
public function testCleanupDatabase()
{
$this->assertNotEmpty(
$this->postgres->getDbh()->query("SELECT * FROM pg_tables where schemaname = 'public'")->fetchAll()
);
$this->postgres->cleanup();
$this->assertEmpty(
$this->postgres->getDbh()->query("SELECT * FROM pg_tables where schemaname = 'public'")->fetchAll()
);
}
public function testCleanupDatabaseDeletesTypes()
{
$customTypes = ['composite_type', 'enum_type', 'range_type', 'base_type'];
foreach ($customTypes as $customType) {
$this->assertNotEmpty(
$this->postgres->getDbh()
->query("SELECT 1 FROM pg_type WHERE typname = '" . $customType . "';")
->fetchAll()
);
}
$this->postgres->cleanup();
foreach ($customTypes as $customType) {
$this->assertEmpty(
$this->postgres->getDbh()
->query("SELECT 1 FROM pg_type WHERE typname = '" . $customType . "';")
->fetchAll()
);
}
}
public function testLoadDump()
{
$res = $this->postgres->getDbh()->query("select * from users where name = 'davert'");
$this->assertNotEquals(false, $res);
$this->assertGreaterThan(0, $res->rowCount());
$res = $this->postgres->getDbh()->query("select * from groups where name = 'coders'");
$this->assertNotEquals(false, $res);
$this->assertGreaterThan(0, $res->rowCount());
$res = $this->postgres->getDbh()->query("select * from users where email = 'user2@example.org'");
$this->assertNotEquals(false, $res);
$this->assertGreaterThan(0, $res->rowCount());
$res = $this->postgres->getDbh()
->query("select * from anotherschema.users where email = 'schemauser@example.org'");
$this->assertEquals(1, $res->rowCount());
}
public function testSelectWithEmptyCriteria()
{
$emptyCriteria = [];
$generatedSql = $this->postgres->select('test_column', 'test_table', $emptyCriteria);
$this->assertNotContains('where', $generatedSql);
}
public function testGetSingleColumnPrimaryKey()
{
$this->assertEquals(['id'], $this->postgres->getPrimaryKey('order'));
}
public function testGetCompositePrimaryKey()
{
$this->assertEquals(['group_id', 'id'], $this->postgres->getPrimaryKey('composite_pk'));
}
public function testGetEmptyArrayIfTableHasNoPrimaryKey()
{
$this->assertEquals([], $this->postgres->getPrimaryKey('no_pk'));
}
public function testLastInsertIdReturnsSequenceValueWhenNonStandardSequenceNameIsUsed()
{
$this->postgres->executeQuery('INSERT INTO seqnames(name) VALUES(?)',['test']);
$this->assertEquals(1, $this->postgres->lastInsertId('seqnames'));
}
public function testGetPrimaryColumnOfTableUsingReservedWordAsTableName()
{
$this->assertEquals('id', $this->postgres->getPrimaryColumn('order'));
}
public function testGetPrimaryColumnThrowsExceptionIfTableHasCompositePrimaryKey()
{
$this->setExpectedException(
'\Exception',
'getPrimaryColumn method does not support composite primary keys, use getPrimaryKey instead'
);
$this->postgres->getPrimaryColumn('composite_pk');
}
/**
* @issue https://github.com/Codeception/Codeception/issues/4059
*/
public function testLoadDumpEndingWithoutDelimiter()
{
$newDriver = new \Codeception\Lib\Driver\PostgreSql(self::$config['dsn'], self::$config['user'], self::$config['password']);
$newDriver->load(['INSERT INTO empty_table VALUES(1, \'test\')']);
$res = $newDriver->getDbh()->query("select * from empty_table where field = 'test'");
$this->assertNotEquals(false, $res);
$this->assertNotEmpty($res->fetchAll());
}
}

View File

@@ -0,0 +1,129 @@
<?php
use \Codeception\Lib\Driver\Db;
use \Codeception\Test\Unit;
/**
* @group db
* Class SqliteTest
*/
class SqliteTest extends Unit
{
protected static $config = array(
'dsn' => 'sqlite:tests/data/sqlite.db',
'user' => 'root',
'password' => ''
);
/**
* @var \Codeception\Lib\Driver\Sqlite
*/
protected static $sqlite;
protected static $sql;
public static function setUpBeforeClass()
{
if (version_compare(PHP_VERSION, '5.5.0', '<')) {
$dumpFile = '/dumps/sqlite-54.sql';
} else {
$dumpFile = '/dumps/sqlite.sql';
}
$sql = file_get_contents(\Codeception\Configuration::dataDir() . $dumpFile);
$sql = preg_replace('%/\*(?:(?!\*/).)*\*/%s', "", $sql);
self::$sql = explode("\n", $sql);
}
public function setUp()
{
self::$sqlite = Db::create(self::$config['dsn'], self::$config['user'], self::$config['password']);
self::$sqlite->cleanup();
self::$sqlite->load(self::$sql);
}
public function tearDown()
{
if (isset(self::$sqlite)) {
self::$sqlite->cleanup();
}
}
public function testLoadDump()
{
$res = self::$sqlite->getDbh()->query("select * from users where name = 'davert'");
$this->assertNotEquals(false, $res);
$this->assertNotEmpty($res->fetchAll());
$res = self::$sqlite->getDbh()->query("select * from groups where name = 'coders'");
$this->assertNotEquals(false, $res);
$this->assertNotEmpty($res->fetchAll());
}
public function testGetPrimaryKeyReturnsRowIdIfTableHasIt()
{
$this->assertEquals(['_ROWID_'], self::$sqlite->getPrimaryKey('groups'));
}
public function testGetPrimaryKeyReturnsRowIdIfTableHasNoPrimaryKey()
{
$this->assertEquals(['_ROWID_'], self::$sqlite->getPrimaryKey('no_pk'));
}
public function testGetSingleColumnPrimaryKeyWhenTableHasNoRowId()
{
if (version_compare(PHP_VERSION, '5.5.0', '<')) {
$this->markTestSkipped('Sqlite does not support WITHOUT ROWID on travis');
}
$this->assertEquals(['id'], self::$sqlite->getPrimaryKey('order'));
}
public function testGetCompositePrimaryKeyWhenTableHasNoRowId()
{
if (version_compare(PHP_VERSION, '5.5.0', '<')) {
$this->markTestSkipped('Sqlite does not support WITHOUT ROWID on travis');
}
$this->assertEquals(['group_id', 'id'], self::$sqlite->getPrimaryKey('composite_pk'));
}
public function testGetPrimaryColumnOfTableUsingReservedWordAsTableNameWhenTableHasNoRowId()
{
if (version_compare(PHP_VERSION, '5.5.0', '<')) {
$this->markTestSkipped('Sqlite does not support WITHOUT ROWID on travis');
}
$this->assertEquals('id', self::$sqlite->getPrimaryColumn('order'));
}
public function testGetPrimaryColumnThrowsExceptionIfTableHasCompositePrimaryKey()
{
if (version_compare(PHP_VERSION, '5.5.0', '<')) {
$this->markTestSkipped('Sqlite does not support WITHOUT ROWID on travis');
}
$this->setExpectedException(
'\Exception',
'getPrimaryColumn method does not support composite primary keys, use getPrimaryKey instead'
);
self::$sqlite->getPrimaryColumn('composite_pk');
}
public function testThrowsExceptionIfInMemoryDatabaseIsUsed()
{
$this->setExpectedException(
'\Codeception\Exception\ModuleException',
':memory: database is not supported'
);
Db::create('sqlite::memory:', '', '');
}
/**
* @issue https://github.com/Codeception/Codeception/issues/4059
*/
public function testLoadDumpEndingWithoutDelimiter()
{
$newDriver = new \Codeception\Lib\Driver\Sqlite(self::$config['dsn'], '', '');
$newDriver->load(['INSERT INTO empty_table VALUES(1, "test")']);
$res = $newDriver->getDbh()->query("select * from empty_table where field = 'test'");
$this->assertNotEquals(false, $res);
$this->assertNotEmpty($res->fetchAll());
}
}

View File

@@ -0,0 +1,93 @@
<?php
namespace Codeception\Lib;
use Codeception\Util\Stub;
class GroupManagerTest extends \Codeception\Test\Unit
{
/**
* @var \Codeception\Lib\GroupManager
*/
protected $manager;
// tests
public function testGroupsFromArray()
{
$this->manager = new GroupManager(['important' => ['UserTest.php:testName', 'PostTest.php']]);
$test1 = $this->makeTestCase('UserTest.php', 'testName');
$test2 = $this->makeTestCase('PostTest.php');
$test3 = $this->makeTestCase('UserTest.php', 'testNot');
$this->assertContains('important', $this->manager->groupsForTest($test1));
$this->assertContains('important', $this->manager->groupsForTest($test2));
$this->assertNotContains('important', $this->manager->groupsForTest($test3));
}
public function testGroupsFromFile()
{
$this->manager = new GroupManager(['important' => 'tests/data/test_groups']);
$test1 = $this->makeTestCase('tests/UserTest.php', 'testName');
$test2 = $this->makeTestCase('tests/PostTest.php');
$test3 = $this->makeTestCase('tests/UserTest.php', 'testNot');
$this->assertContains('important', $this->manager->groupsForTest($test1));
$this->assertContains('important', $this->manager->groupsForTest($test2));
$this->assertNotContains('important', $this->manager->groupsForTest($test3));
}
public function testGroupsFromFileOnWindows()
{
$this->manager = new GroupManager(['important' => 'tests/data/group_3']);
$test = $this->makeTestCase('tests/WinTest.php');
$this->assertContains('important', $this->manager->groupsForTest($test));
}
public function testGroupsFromArrayOnWindows()
{
$this->manager = new GroupManager(['important' => ['tests\WinTest.php']]);
$test = $this->makeTestCase('tests/WinTest.php');
$this->assertContains('important', $this->manager->groupsForTest($test));
}
public function testGroupsByPattern()
{
$this->manager = new GroupManager(['group_*' => 'tests/data/group_*']);
$test1 = $this->makeTestCase('tests/UserTest.php');
$test2 = $this->makeTestCase('tests/PostTest.php');
$this->assertContains('group_1', $this->manager->groupsForTest($test1));
$this->assertContains('group_2', $this->manager->groupsForTest($test2));
}
public function testGroupsByDifferentPattern()
{
$this->manager = new GroupManager(['g_*' => 'tests/data/group_*']);
$test1 = $this->makeTestCase('tests/UserTest.php');
$test2 = $this->makeTestCase('tests/PostTest.php');
$this->assertContains('g_1', $this->manager->groupsForTest($test1));
$this->assertContains('g_2', $this->manager->groupsForTest($test2));
}
public function testGroupsFileHandlesWhitespace()
{
$this->manager = new GroupManager(['whitespace_group_test' => 'tests/data/whitespace_group_test']);
$goodTest = $this->makeTestCase('tests/WhitespaceTest.php');
$badTest = $this->makeTestCase('');
$this->assertContains('whitespace_group_test', $this->manager->groupsForTest($goodTest));
$this->assertEmpty($this->manager->groupsForTest($badTest));
}
protected function makeTestCase($file, $name = '')
{
return Stub::make(
'\Codeception\Lib\DescriptiveTestCase',
[
'getReportFields' => ['file' => codecept_root_dir() . $file],
'getName' => $name
]
);
}
}
class DescriptiveTestCase extends \Codeception\Test\Unit
{
}

View File

@@ -0,0 +1,457 @@
<?php
namespace Codeception\Lib;
use Codeception\Lib\Interfaces\ConflictsWithModule;
use Codeception\Lib\Interfaces\DependsOnModule;
use Codeception\Test\Unit;
use Codeception\Util\Stub;
// @codingStandardsIgnoreFile
class ModuleContainerTest extends Unit
{
use \Codeception\Specify;
/**
* @var ModuleContainer
*/
protected $moduleContainer;
protected function setUp()
{
$this->moduleContainer = new ModuleContainer(Stub::make('Codeception\Lib\Di'), []);
}
protected function tearDown()
{
\Codeception\Module\UniversalFramework::$includeInheritedActions = true;
\Codeception\Module\UniversalFramework::$onlyActions = [];
\Codeception\Module\UniversalFramework::$excludeActions = [];
\Codeception\Module\UniversalFramework::$aliases = [];
}
/**
* @group core
* @throws \Codeception\Exception\ConfigurationException
*/
public function testCreateModule()
{
$module = $this->moduleContainer->create('EmulateModuleHelper');
$this->assertInstanceOf('Codeception\Module\EmulateModuleHelper', $module);
$module = $this->moduleContainer->create('Codeception\Module\EmulateModuleHelper');
$this->assertInstanceOf('Codeception\Module\EmulateModuleHelper', $module);
$this->assertTrue($this->moduleContainer->hasModule('EmulateModuleHelper'));
$this->assertInstanceOf(
'Codeception\Module\EmulateModuleHelper',
$this->moduleContainer->getModule('EmulateModuleHelper')
);
}
/**
* @group core
*/
public function testActions()
{
$this->moduleContainer->create('EmulateModuleHelper');
$actions = $this->moduleContainer->getActions();
$this->assertArrayHasKey('seeEquals', $actions);
$this->assertEquals('EmulateModuleHelper', $actions['seeEquals']);
}
/**
* @group core
*/
public function testActionsInExtendedModule()
{
$this->moduleContainer->create('\Codeception\Module\UniversalFramework');
$actions = $this->moduleContainer->getActions();
$this->assertArrayHasKey('amOnPage', $actions);
$this->assertArrayHasKey('see', $actions);
$this->assertArrayHasKey('click', $actions);
}
/**
* @group core
*/
public function testActionsInExtendedButNotInheritedModule()
{
\Codeception\Module\UniversalFramework::$includeInheritedActions = false;
$this->moduleContainer->create('\Codeception\Module\UniversalFramework');
$actions = $this->moduleContainer->getActions();
$this->assertArrayNotHasKey('amOnPage', $actions);
$this->assertArrayNotHasKey('see', $actions);
$this->assertArrayNotHasKey('click', $actions);
$this->assertArrayHasKey('useUniversalFramework', $actions);
}
/**
* @group core
*/
public function testExplicitlySetActionsOnNotInherited()
{
\Codeception\Module\UniversalFramework::$includeInheritedActions = false;
\Codeception\Module\UniversalFramework::$onlyActions = ['see'];
$this->moduleContainer->create('\Codeception\Module\UniversalFramework');
$actions = $this->moduleContainer->getActions();
$this->assertArrayNotHasKey('amOnPage', $actions);
$this->assertArrayHasKey('see', $actions);
$this->assertArrayNotHasKey('click', $actions);
}
/**
* @group core
*/
public function testActionsExplicitlySetForNotInheritedModule()
{
\Codeception\Module\UniversalFramework::$onlyActions = ['see'];
$this->moduleContainer->create('\Codeception\Module\UniversalFramework');
$actions = $this->moduleContainer->getActions();
$this->assertArrayNotHasKey('amOnPage', $actions);
$this->assertArrayHasKey('see', $actions);
}
/**
* @group core
*/
public function testCreateModuleWithoutRequiredFields()
{
$this->setExpectedException('\Codeception\Exception\ModuleConfigException');
$this->moduleContainer->create('Codeception\Lib\StubModule');
}
/**
* @group core
*/
public function testCreateModuleWithCorrectConfig()
{
$config = [
'modules' => [
'config' => [
'Codeception\Lib\StubModule' => [
'firstField' => 'firstValue',
'secondField' => 'secondValue',
]
]
]
];
$this->moduleContainer = new ModuleContainer(Stub::make('Codeception\Lib\Di'), $config);
$module = $this->moduleContainer->create('Codeception\Lib\StubModule');
$this->assertEquals('firstValue', $module->_getFirstField());
$this->assertEquals('secondValue', $module->_getSecondField());
}
/**
* @group core
*/
public function testReconfigureModule()
{
$config = [
'modules' => [
'config' => [
'Codeception\Lib\StubModule' => [
'firstField' => 'firstValue',
'secondField' => 'secondValue',
]
]
]
];
$this->moduleContainer = new ModuleContainer(Stub::make('Codeception\Lib\Di'), $config);
$module = $this->moduleContainer->create('Codeception\Lib\StubModule');
$module->_reconfigure(['firstField' => '1st', 'secondField' => '2nd']);
$this->assertEquals('1st', $module->_getFirstField());
$this->assertEquals('2nd', $module->_getSecondField());
$module->_resetConfig();
$this->assertEquals('firstValue', $module->_getFirstField());
$this->assertEquals('secondValue', $module->_getSecondField());
}
public function testConflictsByModuleName()
{
$this->setExpectedException('Codeception\Exception\ModuleConflictException');
$this->moduleContainer->create('Codeception\Lib\ConflictedModule');
$this->moduleContainer->create('Cli');
$this->moduleContainer->validateConflicts();
}
public function testConflictsByClass()
{
$this->setExpectedException('Codeception\Exception\ModuleConflictException');
$this->moduleContainer->create('Codeception\Lib\ConflictedModule2');
$this->moduleContainer->create('Cli');
$this->moduleContainer->validateConflicts();
}
public function testConflictsByInterface()
{
$this->setExpectedException('Codeception\Exception\ModuleConflictException');
$this->moduleContainer->create('Codeception\Lib\ConflictedModule3');
$this->moduleContainer->create('Symfony2');
$this->moduleContainer->validateConflicts();
}
public function testConflictsByWebInterface()
{
$this->setExpectedException('Codeception\Exception\ModuleConflictException');
$this->moduleContainer->create('Laravel5');
$this->moduleContainer->create('Symfony2');
$this->moduleContainer->validateConflicts();
}
public function testConflictsForREST()
{
$config = ['modules' =>
['config' => [
'REST' => [
'depends' => 'ZF1',
]
]
]
];
$this->moduleContainer = new ModuleContainer(Stub::make('Codeception\Lib\Di'), $config);
$this->moduleContainer->create('ZF1');
$this->moduleContainer->create('REST');
$this->moduleContainer->validateConflicts();
}
public function testConflictsOnDependentModules()
{
$config = ['modules' =>
['config' => [
'WebDriver' => ['url' => 'localhost', 'browser' => 'firefox'],
'REST' => [
'depends' => 'PhpBrowser',
]
]
]
];
$this->moduleContainer = new ModuleContainer(Stub::make('Codeception\Lib\Di'), $config);
$this->moduleContainer->create('WebDriver');
$this->moduleContainer->create('REST');
$this->moduleContainer->validateConflicts();
}
public function testNoConflictsForPartedModules()
{
$config = ['modules' =>
['config' => [
'Laravel5' => [
'part' => 'ORM',
]
]
]
];
$this->moduleContainer = new ModuleContainer(Stub::make('Codeception\Lib\Di'), $config);
$this->moduleContainer->create('Laravel5');
$this->moduleContainer->create('Symfony2');
$this->moduleContainer->validateConflicts();
}
public function testModuleDependenciesFail()
{
$this->setExpectedException('Codeception\Exception\ModuleRequireException');
$this->moduleContainer->create('Codeception\Lib\DependencyModule');
}
public function testModuleDependencies()
{
$config = ['modules' => [
'enabled' => ['Codeception\Lib\DependencyModule'],
'config' => [
'Codeception\Lib\DependencyModule' => [
'depends' => 'Codeception\Lib\ConflictedModule'
]
]
]];
$this->moduleContainer = new ModuleContainer(Stub::make('Codeception\Lib\Di'), $config);
$this->moduleContainer->create('Codeception\Lib\DependencyModule');
$this->moduleContainer->hasModule('\Codeception\Lib\DependencyModule');
}
public function testModuleParts1()
{
$config = ['modules' => [
'enabled' => ['\Codeception\Lib\PartedModule'],
'config' => [
'\Codeception\Lib\PartedModule' => [
'part' => 'one'
]
]
]
];
$this->moduleContainer = new ModuleContainer(Stub::make('Codeception\Lib\Di'), $config);
$this->moduleContainer->create('\Codeception\Lib\PartedModule');
$actions = $this->moduleContainer->getActions();
$this->assertArrayHasKey('partOne', $actions);
$this->assertArrayNotHasKey('partTwo', $actions);
}
public function testModuleParts2()
{
$config = ['modules' => [
'enabled' => ['\Codeception\Lib\PartedModule'],
'config' => ['\Codeception\Lib\PartedModule' => [
'part' => ['Two']
]
]
]
];
$this->moduleContainer = new ModuleContainer(Stub::make('Codeception\Lib\Di'), $config);
$this->moduleContainer->create('\Codeception\Lib\PartedModule');
$actions = $this->moduleContainer->getActions();
$this->assertArrayHasKey('partTwo', $actions);
$this->assertArrayNotHasKey('partOne', $actions);
}
public function testShortConfigParts()
{
$config = [
'modules' => [
'enabled' => [
['\Codeception\Lib\PartedModule' => [
'part' => 'one'
]
]
],
]
];
$this->moduleContainer = new ModuleContainer(Stub::make('Codeception\Lib\Di'), $config);
$this->moduleContainer->create('\Codeception\Lib\PartedModule');
$actions = $this->moduleContainer->getActions();
$this->assertArrayHasKey('partOne', $actions);
$this->assertArrayNotHasKey('partTwo', $actions);
}
public function testShortConfigFormat()
{
$config = [
'modules' =>
['enabled' => [
['Codeception\Lib\StubModule' => [
'firstField' => 'firstValue',
'secondField' => 'secondValue',
]
]
]
]
];
$this->moduleContainer = new ModuleContainer(Stub::make('Codeception\Lib\Di'), $config);
$module = $this->moduleContainer->create('Codeception\Lib\StubModule');
$this->assertEquals('firstValue', $module->_getFirstField());
$this->assertEquals('secondValue', $module->_getSecondField());
}
public function testShortConfigDependencies()
{
$config = ['modules' => [
'enabled' => [['Codeception\Lib\DependencyModule' => [
'depends' => 'Codeception\Lib\ConflictedModule'
]]],
]];
$this->moduleContainer = new ModuleContainer(Stub::make('Codeception\Lib\Di'), $config);
$this->moduleContainer->create('Codeception\Lib\DependencyModule');
$this->moduleContainer->hasModule('\Codeception\Lib\DependencyModule');
}
public function testInjectModuleIntoHelper()
{
$config = ['modules' => [
'enabled' => ['Codeception\Lib\HelperModule'],
]];
$this->moduleContainer = new ModuleContainer(Stub::make('Codeception\Lib\Di'), $config);
$this->moduleContainer->create('Codeception\Lib\HelperModule');
$this->moduleContainer->hasModule('Codeception\Lib\HelperModule');
}
}
class StubModule extends \Codeception\Module
{
protected $requiredFields = [
'firstField',
'secondField',
];
public function _getFirstField()
{
return $this->config['firstField'];
}
public function _getSecondField()
{
return $this->config['secondField'];
}
}
class HelperModule extends \Codeception\Module
{
public function _inject(ConflictedModule $module)
{
$this->module = $module;
}
}
class ConflictedModule extends \Codeception\Module implements ConflictsWithModule
{
public function _conflicts()
{
return 'Cli';
}
}
class ConflictedModule2 extends \Codeception\Module implements ConflictsWithModule
{
public function _conflicts()
{
return '\Codeception\Module\Cli';
}
}
class ConflictedModule3 extends \Codeception\Module implements ConflictsWithModule
{
public function _conflicts()
{
return 'Codeception\Lib\Interfaces\Web';
}
}
class DependencyModule extends \Codeception\Module implements DependsOnModule
{
public function _depends()
{
return ['Codeception\Lib\ConflictedModule' => 'Error message'];
}
public function _inject()
{
}
}
class PartedModule extends \Codeception\Module implements \Codeception\Lib\Interfaces\PartedModule
{
public function _parts()
{
return ['one'];
}
/**
* @part one
*/
public function partOne()
{
}
/**
* @part two
*/
public function partTwo()
{
}
}

View File

@@ -0,0 +1,178 @@
<?php
use Codeception\Lib\Parser;
/**
* @group core
* Class ParserTest
*/
class ParserTest extends \Codeception\Test\Unit
{
/**
* @var Parser
*/
protected $parser;
/**
* @var \Codeception\Scenario
*/
protected $scenario;
protected $testMetadata;
protected function _before()
{
$cept = new \Codeception\Test\Cept('demo', 'DemoCept.php');
$this->testMetadata = $cept->getMetadata();
$this->scenario = new Codeception\Scenario($cept);
$this->parser = new Parser($this->scenario, $this->testMetadata);
}
public function testParsingFeature()
{
$code = "<?php\n \\\$I->wantTo('run this test'); ";
$this->parser->parseFeature($code);
$this->assertEquals('run this test', $this->scenario->getFeature());
$code = "<?php\n \\\$I->wantToTest('this run'); ";
$this->parser->parseFeature($code);
$this->assertEquals('test this run', $this->scenario->getFeature());
}
public function testParsingWithWhitespace()
{
$code = "<?php\n \\\$I->wantTo( 'run this test' ); ";
$this->parser->parseFeature($code);
$this->assertEquals('run this test', $this->scenario->getFeature());
}
public function testScenarioOptions()
{
$code = <<<EOF
<?php
// @group davert
// @env windows
\$I = new AcceptanceTeser(\$scenario);
EOF;
$this->parser->parseScenarioOptions($code);
$this->assertContains('davert', $this->testMetadata->getGroups());
$this->assertContains('windows', $this->testMetadata->getEnv());
}
public function testCommentedInBlockScenarioOptions()
{
$code = <<<EOF
<?php
/**
* @skip
*/
EOF;
$this->parser->parseScenarioOptions($code);
$this->assertTrue($this->testMetadata->isBlocked());
}
public function testFeatureCommented()
{
$code = "<?php\n //\\\$I->wantTo('run this test'); ";
$this->parser->parseFeature($code);
$this->assertNull($this->scenario->getFeature());
$code = "<?php\n /*\n \\\$I->wantTo('run this test'); \n */";
$this->parser->parseFeature($code);
$this->assertNull($this->scenario->getFeature());
}
public function testScenarioSkipOptionsHandled()
{
$code = "<?php\n // @skip pass along";
$this->parser->parseScenarioOptions($code);
$this->assertTrue($this->testMetadata->isBlocked());
}
public function testScenarioIncompleteOptionHandled()
{
$code = "<?php\n // @incomplete not ready yet";
$this->parser->parseScenarioOptions($code);
$this->assertTrue($this->testMetadata->isBlocked());
}
public function testSteps()
{
$code = file_get_contents(\Codeception\Configuration::projectDir().'tests/cli/UnitCept.php');
$this->assertContains('$I->seeInThisFile', $code);
$this->parser->parseSteps($code);
$text = $this->scenario->getText();
$this->assertContains("I see in this file", $text);
}
public function testStepsWithFriends()
{
$code = file_get_contents(\Codeception\Configuration::projectDir().'tests/web/FriendsCept.php');
$this->assertContains('$I->haveFriend', $code);
$this->parser->parseSteps($code);
$text = $this->scenario->getText();
$this->assertContains("jon does", $text);
$this->assertContains("I have friend", $text);
$this->assertContains("back to me", $text);
}
public function testParseFile()
{
$classes = Parser::getClassesFromFile(codecept_data_dir('SimpleTest.php'));
$this->assertEquals(['SampleTest'], $classes);
}
public function testParseFileWithClass()
{
if (version_compare(PHP_VERSION, '5.5.0', '<')) {
$this->markTestSkipped('only for php 5.5');
}
$classes = Parser::getClassesFromFile(codecept_data_dir('php55Test'));
$this->assertEquals(['php55Test'], $classes);
}
public function testParseFileWithAnonymousClass()
{
if (version_compare(PHP_VERSION, '7.0.0', '<')) {
$this->markTestSkipped('only for php 7');
}
$classes = Parser::getClassesFromFile(codecept_data_dir('php70Test'));
$this->assertEquals(['php70Test'], $classes);
}
/*
* https://github.com/Codeception/Codeception/issues/1779
*/
public function testParseFileWhichUnsetsFileVariable()
{
$classes = Parser::getClassesFromFile(codecept_data_dir('unsetFile.php'));
$this->assertEquals([], $classes);
}
/**
* @group core
* @throws \Codeception\Exception\TestParseException
*/
public function testModernValidation()
{
if (PHP_MAJOR_VERSION < 7) {
$this->markTestSkipped();
}
$this->setExpectedException('Codeception\Exception\TestParseException');
Parser::load(codecept_data_dir('Invalid.php'));
}
/**
* @group core
*/
public function testClassesFromFile()
{
$classes = Parser::getClassesFromFile(codecept_data_dir('DummyClass.php'));
$this->assertContains('DummyClass', $classes);
$classes = Parser::getClassesFromFile(codecept_data_dir('SimpleWithDependencyInjectionCest.php'));
$this->assertContains('simpleDI\\LoadedTestWithDependencyInjectionCest', $classes);
$this->assertContains('simpleDI\\AnotherCest', $classes);
}
}

View File

@@ -0,0 +1,55 @@
<?php
class AMQPTest extends \PHPUnit\Framework\TestCase
{
protected $config = array(
'host' => 'localhost',
'username' => 'guest',
'password' => 'guest',
'port' => '5672',
'vhost' => '/',
'cleanup' => false,
'queues' => array('queue1')
);
/**
* @var \Codeception\Module\AMQP
*/
protected $module = null;
public function setUp()
{
$this->module = new \Codeception\Module\AMQP(make_container());
$this->module->_setConfig($this->config);
$res = @stream_socket_client('tcp://localhost:5672');
if ($res === false) {
$this->markTestSkipped('AMQP is not running');
}
$this->module->_initialize();
$connection = $this->module->connection;
$connection->channel()->queue_declare('queue1');
}
public function testPushToQueue()
{
$this->module->pushToQueue('queue1', 'hello');
$this->module->seeMessageInQueueContainsText('queue1', 'hello');
}
public function testPushToExchange()
{
$queue = 'test-queue';
$exchange = 'test-exchange';
$topic = 'test.3';
$message = 'test-message';
$this->module->declareExchange($exchange, 'topic', false, true, false);
$this->module->declareQueue($queue, false, true, false, false);
$this->module->bindQueueToExchange($queue, $exchange, 'test.#');
$this->module->pushToExchange($exchange, $message, $topic);
$this->module->seeMessageInQueueContainsText($queue , $message);
}
}

View File

@@ -0,0 +1,73 @@
<?php
class AssertsTest extends \PHPUnit\Framework\TestCase
{
public function testAsserts()
{
$module = new \Codeception\Module\Asserts(make_container());
$module->assertEquals(1, 1);
$module->assertContains(1, [1, 2]);
$module->assertSame(1, 1);
$module->assertNotSame(1, '1');
$module->assertRegExp('/^[\d]$/', '1');
$module->assertNotRegExp('/^[a-z]$/', '1');
$module->assertStringStartsWith('fo', 'foo');
$module->assertStringStartsNotWith('ba', 'foo');
$module->assertEmpty([]);
$module->assertNotEmpty([1]);
$module->assertNull(null);
$module->assertNotNull('');
$module->assertNotNull(false);
$module->assertNotNull(0);
$module->assertTrue(true);
$module->assertNotTrue(false);
$module->assertNotTrue(null);
$module->assertNotTrue('foo');
$module->assertFalse(false);
$module->assertNotFalse(true);
$module->assertNotFalse(null);
$module->assertNotFalse('foo');
$module->assertFileExists(__FILE__);
$module->assertFileNotExists(__FILE__ . '.notExist');
$module->assertInstanceOf('Exception', new Exception());
$module->assertInternalType('integer', 5);
$module->assertArrayHasKey('one', ['one' => 1, 'two' => 2]);
$module->assertArraySubset(['foo' => [1]], ['foo' => [1, 2]]);
$module->assertCount(3, [1, 2, 3]);
}
public function testExceptions()
{
$module = new \Codeception\Module\Asserts(make_container());
$module->expectException('Exception', function () {
throw new Exception;
});
$module->expectException(new Exception('here'), function () {
throw new Exception('here');
});
$module->expectException(new Exception('here', 200), function () {
throw new Exception('here', 200);
});
}
/**
* @expectedException PHPUnit\Framework\AssertionFailedError
*/
public function testExceptionFails()
{
$module = new \Codeception\Module\Asserts(make_container());
$module->expectException(new Exception('here', 200), function () {
throw new Exception('here', 2);
});
}
/**
* @expectedException PHPUnit\Framework\AssertionFailedError
* @expectedExceptionMessageRegExp /RuntimeException/
*/
public function testOutputExceptionTimeWhenNothingCaught()
{
$module = new \Codeception\Module\Asserts(make_container());
$module->expectException(RuntimeException::class, function () {
});
}
}

View File

@@ -0,0 +1,50 @@
<?php
use Codeception\Util\Stub;
use Pheanstalk\Exception\ConnectionException;
class BeanstalkdTest extends \PHPUnit\Framework\TestCase
{
protected $config = array(
'type' => 'beanstalkq',
'host' => 'localhost'
);
/**
* @var \Codeception\Module\Queue
*/
protected $module = null;
public function setUp()
{
$this->module = new \Codeception\Module\Queue(make_container());
$this->module->_setConfig($this->config);
$this->module->_before(Stub::makeEmpty('\Codeception\TestInterface'));
try {
$this->module->clearQueue('default');
} catch (ConnectionException $e) {
$this->markTestSkipped("Beanstalk is not running");
}
}
/** @test */
public function flow()
{
$this->module->addMessageToQueue('hello world - ' . date('d-m-y'), 'default');
$this->module->clearQueue('default');
$this->module->seeQueueExists('default');
$this->module->dontSeeQueueExists('fake_queue');
$this->module->seeEmptyQueue('default');
$this->module->addMessageToQueue('hello world - ' . date('d-m-y'), 'default');
$this->module->dontSeeEmptyQueue('default');
$this->module->seeQueueHasTotalCount('default', 2);
$this->module->seeQueueHasCurrentCount('default', 1);
$this->module->dontSeeQueueHasCurrentCount('default', 9999);
$this->module->grabQueues();
}
}

View File

@@ -0,0 +1,84 @@
<?php
require_once \Codeception\Configuration::testsDir().'unit/Codeception/Module/Db/TestsForDb.php';
/**
* @group appveyor
* @group db
*/
class MySqlDbTest extends TestsForDb
{
public function getPopulator()
{
if (getenv('APPVEYOR')) {
$this->markTestSkipped('Disabled on Appveyor');
}
if (getenv('WERCKER_ROOT')) {
$this->markTestSkipped('Disabled on Wercker CI');
}
$config = $this->getConfig();
$password = $config['password'] ? '-p'.$config['password'] : '';
return "mysql -u \$user $password \$dbname < {$config['dump']}";
}
public function getConfig()
{
return [
'dsn' => 'mysql:host=localhost;dbname=codeception_test',
'user' => 'root',
'password' => getenv('APPVEYOR') ? 'Password12!' : '',
'dump' => 'tests/data/dumps/mysql.sql',
'reconnect' => true,
'cleanup' => true,
'populate' => true
];
}
/**
* Overriden, Using MYSQL CONNECTION_ID to get current connection
*/
public function testConnectionIsResetOnEveryTestWhenReconnectIsTrue()
{
$testCase1 = \Codeception\Util\Stub::makeEmpty('\Codeception\TestInterface');
$testCase2 = \Codeception\Util\Stub::makeEmpty('\Codeception\TestInterface');
$testCase3 = \Codeception\Util\Stub::makeEmpty('\Codeception\TestInterface');
$this->module->_setConfig(['reconnect' => false]);
$this->module->_beforeSuite();
// Simulate a test that runs
$this->module->_before($testCase1);
$connection1 = $this->module->dbh->query('SELECT CONNECTION_ID()')->fetch(PDO::FETCH_COLUMN);
$this->module->_after($testCase1);
// Simulate a second test that runs
$this->module->_before($testCase2);
$connection2 = $this->module->dbh->query('SELECT CONNECTION_ID()')->fetch(PDO::FETCH_COLUMN);
$this->module->_after($testCase2);
$this->module->_afterSuite();
$this->module->_setConfig(['reconnect' => true]);
$this->module->_before($testCase3);
$connection3 = $this->module->dbh->query('SELECT CONNECTION_ID()')->fetch(PDO::FETCH_COLUMN);
$this->module->_after($testCase3);
$this->assertEquals($connection1, $connection2);
$this->assertNotEquals($connection3, $connection2);
}
public function testGrabColumnFromDatabase()
{
$emails = $this->module->grabColumnFromDatabase('users', 'email');
$this->assertEquals(
[
'davert@mail.ua',
'nick@mail.ua',
'miles@davis.com',
'charlie@parker.com',
],
$emails);
}
}

View File

@@ -0,0 +1,43 @@
<?php
use Codeception\Lib\DbPopulator;
/**
* @group db
* Class DbPopulatorTest
*/
class DbPopulatorTest extends \Codeception\Test\Unit
{
public function testCommandBuilderInterpolatesVariables()
{
$populator = new DbPopulator(
[
'populate' => true,
'dsn' => 'mysql:host=127.0.0.1;dbname=my_db',
'dump' => 'tests/data/dumps/sqlite.sql',
'user' => 'root',
'populator' => 'mysql -u $user -h $host -D $dbname < $dump'
]
);
$this->assertEquals(
'mysql -u root -h 127.0.0.1 -D my_db < tests/data/dumps/sqlite.sql',
$populator->getBuiltCommand()
);
}
public function testCommandBuilderWontTouchVariablesNotFound()
{
$populator = new DbPopulator([
'populator' => 'noop_tool -u $user -h $host -D $dbname < $dump',
'user' => 'root',
]);
$this->assertEquals(
'noop_tool -u root -h $host -D $dbname < $dump',
$populator->getBuiltCommand()
);
}
}

View File

@@ -0,0 +1,38 @@
<?php
require_once \Codeception\Configuration::testsDir().'unit/Codeception/Module/Db/TestsForDb.php';
/**
* @group appveyor
* @group db
*/
class PostgreSqlDbTest extends TestsForDb
{
public function getPopulator()
{
if (getenv('APPVEYOR')) {
$this->markTestSkipped('Disabled on Appveyor');
}
if (getenv('WERCKER_ROOT')) {
$this->markTestSkipped('Disabled on Wercker CI');
}
return "psql -d codeception_test -U postgres < tests/data/dumps/postgres.sql";
}
public function getConfig()
{
if (!function_exists('pg_connect')) {
$this->markTestSkipped();
}
return [
'dsn' => 'pgsql:host=localhost;dbname=codeception_test',
'user' => 'postgres',
'password' => getenv('APPVEYOR') ? 'Password12!' : null,
'dump' => defined('HHVM_VERSION') ? 'tests/data/dumps/postgres-hhvm.sql' : 'tests/data/dumps/postgres.sql',
'reconnect' => true,
'cleanup' => true,
'populate' => true
];
}
}

View File

@@ -0,0 +1,77 @@
<?php
require_once \Codeception\Configuration::testsDir().'unit/Codeception/Module/Db/TestsForDb.php';
/**
* @group appveyor
* @group db
* Class SqliteDbTest
*/
class SqliteDbTest extends TestsForDb
{
public function getPopulator()
{
if (getenv('APPVEYOR')) {
$this->markTestSkipped('Disabled on Appveyor');
}
if (getenv('WERCKER_ROOT')) {
$this->markTestSkipped('Disabled on Wercker CI');
}
$this->markTestSkipped('Currently Travis CI uses old SQLite :(');
$config = $this->getConfig();
@chmod('tests/data/sqlite.db', 0777);
return 'cat '. $config['dump'] .' | sqlite3 tests/data/sqlite.db';
}
public function getConfig()
{
if (version_compare(PHP_VERSION, '5.5.0', '<')) {
$dumpFile = 'dumps/sqlite-54.sql';
} else {
$dumpFile = 'dumps/sqlite.sql';
}
return [
'dsn' => 'sqlite:tests/data/sqlite.db',
'user' => 'root',
'password' => '',
'dump' => 'tests/data/' . $dumpFile,
'reconnect' => true,
'cleanup' => true,
'populate' => true
];
}
public function testConnectionIsResetOnEveryTestWhenReconnectIsTrue()
{
$testCase1 = \Codeception\Util\Stub::makeEmpty('\Codeception\TestInterface');
$testCase2 = \Codeception\Util\Stub::makeEmpty('\Codeception\TestInterface');
$testCase3 = \Codeception\Util\Stub::makeEmpty('\Codeception\TestInterface');
$this->module->_setConfig(['reconnect' => false]);
$this->module->_beforeSuite();
// Simulate a test that runs
$this->module->_before($testCase1);
$connection1 = spl_object_hash($this->module->dbh);
$this->module->_after($testCase1);
// Simulate a second test that runs
$this->module->_before($testCase2);
$connection2 = spl_object_hash($this->module->dbh);
$this->module->_after($testCase2);
$this->module->_afterSuite();
$this->module->_setConfig(['reconnect' => true]);
$this->module->_before($testCase3);
$connection3 = spl_object_hash($this->module->dbh);
$this->module->_after($testCase3);
$this->assertEquals($connection1, $connection2);
$this->assertNotEquals($connection3, $connection2);
}
}

View File

@@ -0,0 +1,206 @@
<?php
use Codeception\Lib\Driver\Db;
abstract class TestsForDb extends \Codeception\Test\Unit
{
/**
* @var \Codeception\Module\Db
*/
protected $module;
abstract public function getConfig();
abstract public function getPopulator();
protected function setUp()
{
$config = $this->getConfig();
Db::create($config['dsn'], $config['user'], $config['password'])->cleanup();
$this->module = new \Codeception\Module\Db(make_container(), $config);
$this->module->_beforeSuite();
$this->module->_before(\Codeception\Util\Stub::makeEmpty('\Codeception\TestInterface'));
$this->assertTrue($this->module->isPopulated());
}
protected function tearDown()
{
$this->module->_resetConfig();
$this->module->_after(\Codeception\Util\Stub::makeEmpty('\Codeception\TestInterface'));
}
public function testConnectionIsKeptForTheWholeSuite()
{
$testCase1 = \Codeception\Util\Stub::makeEmpty('\Codeception\TestInterface');
$testCase2 = \Codeception\Util\Stub::makeEmpty('\Codeception\TestInterface');
$this->module->_reconfigure(['reconnect' => false]);
$this->module->_beforeSuite();
// Simulate a test that runs
$this->module->_before($testCase1);
// Save these object instances IDs
$driverAndConn1 = [
$this->module->driver,
$this->module->dbh
];
$this->module->_after($testCase1);
// Simulate a second test that runs
$this->module->_before($testCase2);
$driverAndConn2 = [
$this->module->driver,
$this->module->dbh
];
$this->module->_after($testCase2);
$this->assertEquals($driverAndConn2, $driverAndConn1);
$this->module->_afterSuite();
}
public function testSeeInDatabase()
{
$this->module->seeInDatabase('users', ['name' => 'davert']);
}
public function testCountInDatabase()
{
$this->module->seeNumRecords(1, 'users', ['name' => 'davert']);
$this->module->seeNumRecords(0, 'users', ['name' => 'davert', 'email' => 'xxx@yyy.zz']);
$this->module->seeNumRecords(0, 'users', ['name' => 'user1']);
}
public function testDontSeeInDatabase()
{
$this->module->dontSeeInDatabase('users', ['name' => 'user1']);
}
public function testDontSeeInDatabaseWithEmptyTable()
{
$this->module->dontSeeInDatabase('empty_table');
}
public function testCleanupDatabase()
{
$this->module->seeInDatabase('users', ['name' => 'davert']);
$this->module->_cleanup();
// Since table does not exist it should fail
// TODO: Catch this exception at the driver level and re-throw a general one
// just for "table not found" across all the drivers
$this->setExpectedException('PDOException');
$this->module->dontSeeInDatabase('users', ['name' => 'davert']);
}
public function testHaveAndSeeInDatabase()
{
$userId = $this->module->haveInDatabase('users', ['name' => 'john', 'email' => 'john@jon.com']);
$this->module->haveInDatabase('groups', ['name' => 'john', 'enabled' => false]);
$this->assertInternalType('integer', $userId);
$this->module->seeInDatabase('users', ['name' => 'john', 'email' => 'john@jon.com']);
$this->module->dontSeeInDatabase('users', ['name' => 'john', 'email' => null]);
$this->module->_after(\Codeception\Util\Stub::makeEmpty('\Codeception\TestInterface'));
$this->module->_before(\Codeception\Util\Stub::makeEmpty('\Codeception\TestInterface'));
$this->module->dontSeeInDatabase('users', ['name' => 'john']);
}
public function testHaveInDatabaseWithCompositePrimaryKey()
{
if (version_compare(PHP_VERSION, '5.5.0', '<')) {
$this->markTestSkipped('Does not support WITHOUT ROWID on travis');
}
$insertQuery = 'INSERT INTO composite_pk (group_id, id, status) VALUES (?, ?, ?)';
//this test checks that module does not delete columns by partial primary key
$this->module->driver->executeQuery($insertQuery, [1, 2, 'test']);
$this->module->driver->executeQuery($insertQuery, [2, 1, 'test2']);
$testData = ['id' => 2, 'group_id' => 2, 'status' => 'test3'];
$this->module->haveInDatabase('composite_pk', $testData);
$this->module->seeInDatabase('composite_pk', $testData);
$this->module->_reconfigure(['cleanup' => false]);
$this->module->_after(\Codeception\Util\Stub::makeEmpty('\Codeception\TestInterface'));
$this->module->_before(\Codeception\Util\Stub::makeEmpty('\Codeception\TestInterface'));
$this->module->dontSeeInDatabase('composite_pk', $testData);
$this->module->seeInDatabase('composite_pk', ['group_id' => 1, 'id' => 2, 'status' => 'test']);
$this->module->seeInDatabase('composite_pk', ['group_id' => 2, 'id' => 1, 'status' => 'test2']);
}
public function testHaveInDatabaseWithoutPrimaryKey()
{
$testData = ['status' => 'test'];
$this->module->haveInDatabase('no_pk', $testData);
$this->module->seeInDatabase('no_pk', $testData);
$this->module->_after(\Codeception\Util\Stub::makeEmpty('\Codeception\TestInterface'));
$this->module->_before(\Codeception\Util\Stub::makeEmpty('\Codeception\TestInterface'));
$this->module->dontSeeInDatabase('no_pk', $testData);
}
public function testGrabFromDatabase()
{
$email = $this->module->grabFromDatabase('users', 'email', ['name' => 'davert']);
$this->assertEquals('davert@mail.ua', $email);
}
public function testGrabNumRecords()
{
$num = $this->module->grabNumRecords('users', ['name' => 'davert']);
$this->assertEquals($num, 1);
$num = $this->module->grabNumRecords('users', ['name' => 'davert', 'email' => 'xxx@yyy.zz']);
$this->assertEquals($num, 0);
$num = $this->module->grabNumRecords('users', ['name' => 'user1']);
$this->assertEquals($num, 0);
}
public function testLoadWithPopulator()
{
$this->module->_cleanup();
$this->assertFalse($this->module->isPopulated());
try {
$this->module->seeInDatabase('users', ['name' => 'davert']);
} catch (\PDOException $noTable) {
$noTable;
// No table was found...
}
$this->module->_reconfigure(
[
'populate' => true,
'populator' => $this->getPopulator(),
'cleanup' => true,
]
);
$this->module->_loadDump();
$this->assertTrue($this->module->isPopulated());
$this->module->seeInDatabase('users', ['name' => 'davert']);
}
public function testUpdateInDatabase()
{
$this->module->seeInDatabase('users', ['name' => 'davert']);
$this->module->dontSeeInDatabase('users', ['name' => 'user1']);
$this->module->updateInDatabase('users', ['name' => 'user1'], ['name' => 'davert']);
$this->module->dontSeeInDatabase('users', ['name' => 'davert']);
$this->module->seeInDatabase('users', ['name' => 'user1']);
$this->module->updateInDatabase('users', ['name' => 'davert'], ['name' => 'user1']);
}
public function testInsertInDatabase()
{
$testData = ['status' => 'test'];
$this->module->_insertInDatabase('no_pk', $testData);
$this->module->seeInDatabase('no_pk', $testData);
$this->module->_reconfigure(['cleanup' => false]);
$this->module->_after(\Codeception\Util\Stub::makeEmpty('\Codeception\TestInterface'));
$this->module->_before(\Codeception\Util\Stub::makeEmpty('\Codeception\TestInterface'));
$this->module->seeInDatabase('no_pk', $testData);
}
}

View File

@@ -0,0 +1,124 @@
<?php
use Codeception\Util\Stub;
/**
* Module for testing remote ftp systems.
*
* ## Status
*
* Maintainer: **nathanmac**
* Stability: **stable**
* Contact: nathan.macnamara@outlook.com
*
*/
class FTPTest extends \PHPUnit\Framework\TestCase
{
protected $config = array(
'host' => '127.0.0.1',
'tmp' => 'temp',
'user' => 'user',
'password' => 'password'
);
/**
* @var \Codeception\Module\FTP
*/
protected $module = null;
public function setUp()
{
$this->module = new \Codeception\Module\FTP(make_container());
$this->module->_setConfig($this->config);
$this->module->_before(Stub::makeEmpty('\Codeception\Test\Test'));
}
/**
* Disabled Test - for travis testing, requires testing server
*/
public function flow()
{
// Check root directory
$this->assertEquals('/', $this->module->grabDirectory());
// Create directory
$this->module->makeDir('TESTING');
// Move to new directory
$this->module->amInPath('TESTING');
// Verify current directory
$this->assertEquals('/TESTING', $this->module->grabDirectory());
$files = $this->module->grabFileList();
// Create files on server
$this->module->writeToFile('test_ftp_123.txt', 'some data added here');
$this->module->writeToFile('test_ftp_567.txt', 'some data added here');
$this->module->writeToFile('test_ftp_678.txt', 'some data added here');
// Grab file list
$files = $this->module->grabFileList();
// Verify files are listed
$this->assertContains('test_ftp_123.txt', $files);
$this->assertContains('test_ftp_567.txt', $files);
$this->assertContains('test_ftp_678.txt', $files);
$this->module->seeFileFound('test_ftp_123.txt');
$this->module->dontSeeFileFound('test_ftp_321.txt');
$this->module->seeFileFoundMatches('/^test_ftp_([0-9]{3}).txt$/');
$this->module->dontSeeFileFoundMatches('/^test_([0-9]{3})_ftp.txt$/');
$this->assertGreaterThan(0, $this->module->grabFileCount());
$this->assertGreaterThan(0, $this->module->grabFileSize('test_ftp_678.txt'));
$this->assertGreaterThan(0, $this->module->grabFileModified('test_ftp_678.txt'));
$this->module->openFile('test_ftp_567.txt');
$this->module->deleteThisFile();
$this->module->dontSeeFileFound('test_ftp_567.txt');
// Open file (download local copy)
$this->module->openFile('test_ftp_123.txt');
$this->module->seeInThisFile('data');
$this->module->dontSeeInThisFile('banana');
$this->module->seeFileContentsEqual('some data added here');
$this->module->renameFile('test_ftp_678.txt', 'test_ftp_987.txt');
$files = $this->module->grabFileList();
// Verify old file is not listed
$this->assertNotContains('test_ftp_678.txt', $files);
// Verify renamed file is listed
$this->assertContains('test_ftp_987.txt', $files);
$this->module->deleteFile('test_ftp_123.txt');
$files = $this->module->grabFileList();
// Verify deleted file is not listed
$this->assertNotContains('test_ftp_123.txt', $files);
// Move to root directory
$this->module->amInPath('/');
$this->assertEquals('/', $this->module->grabDirectory());
$this->module->renameDir('TESTING', 'TESTING_NEW');
// Remove directory (with contents)
$this->module->deleteDir('TESTING_NEW');
// Test Clearing the Directory
$this->module->makeDir('TESTING');
$this->module->amInPath('TESTING');
$this->module->writeToFile('test_ftp_123.txt', 'some data added here');
$this->module->amInPath('/');
$this->assertGreaterThan(0, $this->module->grabFileCount('TESTING'));
$this->module->cleanDir('TESTING');
$this->assertEquals(0, $this->module->grabFileCount('TESTING'));
$this->module->deleteDir('TESTING');
}
public function tearDown()
{
$this->module->_after(Stub::makeEmpty('\Codeception\Test\Test'));
}
}

View File

@@ -0,0 +1,90 @@
<?php
use Codeception\Module\Filesystem;
use Codeception\Util\Stub;
class FilesystemTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Codeception\Module\Filesystem
*/
protected $module;
public function setUp()
{
$this->module = new Filesystem(make_container());
$this->module->_before(Stub::makeEmpty('\Codeception\Test\Test'));
}
public function tearDown()
{
$this->module->_after(Stub::makeEmpty('\Codeception\Test\Test'));
}
public function testSeeFileFoundPassesWhenFileExists()
{
$this->module->seeFileFound('tests/data/dumps/mysql.sql');
}
public function testSeeFileFoundPassesWhenFileExistsInSubdirectoryOfPath()
{
$this->module->seeFileFound('mysql.sql', 'tests/data/');
}
/**
* @expectedException PHPUnit\Framework\AssertionFailedError
* @expectedExceptionMessage File "does-not-exist" not found at
*/
public function testSeeFileFoundFailsWhenFileDoesNotExist()
{
$this->module->seeFileFound('does-not-exist');
}
/**
* @expectedException PHPUnit\Framework\AssertionFailedError
* @expectedExceptionMessageRegExp /Directory does not exist: .*does-not-exist/
*/
public function testSeeFileFoundFailsWhenPathDoesNotExist()
{
$this->module->seeFileFound('mysql.sql', 'does-not-exist');
}
public function testDontSeeFileFoundPassesWhenFileDoesNotExists()
{
$this->module->dontSeeFileFound('does-not-exist');
}
public function testDontSeeFileFoundPassesWhenFileDoesNotExistsInPath()
{
$this->module->dontSeeFileFound('does-not-exist', 'tests/data/');
}
/**
* @expectedException PHPUnit\Framework\AssertionFailedError
* @expectedExceptionMessage Failed asserting that file "tests/data/dumps/mysql.sql" does not exist.
*/
public function testDontSeeFileFoundFailsWhenFileExists()
{
$this->module->dontSeeFileFound('tests/data/dumps/mysql.sql');
}
/**
* @expectedException PHPUnit\Framework\AssertionFailedError
* @expectedExceptionMessageRegExp /Directory does not exist: .*does-not-exist/
*/
public function testDontSeeFileFoundFailsWhenPathDoesNotExist()
{
$this->module->dontSeeFileFound('mysql.sql', 'does-not-exist');
}
/**
* @expectedException PHPUnit\Framework\AssertionFailedError
* @expectedExceptionMessageRegExp /Failed asserting that file ".*tests\/data\/dumps\/mysql.sql" does not exist/
*/
public function testDontSeeFileFoundFailsWhenFileExistsInSubdirectoryOfPath()
{
$this->module->dontSeeFileFound('mysql.sql', 'tests/data/');
}
}

View File

@@ -0,0 +1,95 @@
<?php
use Codeception\Util\Stub;
require_once __DIR__ . '/TestsForWeb.php';
/**
* @group appveyor
*/
class FrameworksTest extends TestsForWeb
{
/**
* @var \Codeception\Lib\Framework
*/
protected $module;
public function setUp()
{
$this->module = new \Codeception\Module\UniversalFramework(make_container());
}
public function testHttpAuth()
{
$this->module->amOnPage('/auth');
$this->module->see('Unauthorized');
$this->module->amHttpAuthenticated('davert', 'password');
$this->module->amOnPage('/auth');
$this->module->dontSee('Unauthorized');
$this->module->see("Welcome, davert");
$this->module->amHttpAuthenticated('davert', '123456');
$this->module->amOnPage('/auth');
$this->module->see('Forbidden');
}
public function testExceptionIsThrownOnRedirectToExternalUrl()
{
$this->setExpectedException('\Codeception\Exception\ExternalUrlException');
$this->module->amOnPage('/external_url');
$this->module->click('Next');
}
public function testMoveBackOneStep()
{
$this->module->amOnPage('/iframe');
$this->module->switchToIframe('content');
$this->module->seeCurrentUrlEquals('/info');
$this->module->click('Ссылочка');
$this->module->seeCurrentUrlEquals('/');
$this->module->moveBack();
$this->module->seeCurrentUrlEquals('/info');
$this->module->click('Sign in!');
$this->module->seeCurrentUrlEquals('/login');
}
public function testMoveBackTwoSteps()
{
$this->module->amOnPage('/iframe');
$this->module->switchToIframe('content');
$this->module->seeCurrentUrlEquals('/info');
$this->module->click('Ссылочка');
$this->module->seeCurrentUrlEquals('/');
$this->module->moveBack(2);
$this->module->seeCurrentUrlEquals('/iframe');
}
public function testMoveBackThrowsExceptionIfNumberOfStepsIsInvalid()
{
$this->module->amOnPage('/iframe');
$this->module->switchToIframe('content');
$this->module->seeCurrentUrlEquals('/info');
$this->module->click('Ссылочка');
$this->module->seeCurrentUrlEquals('/');
$invalidValues = [0, -5, 1.5, 'a', 3];
foreach ($invalidValues as $invalidValue) {
try {
$this->module->moveBack($invalidValue);
$this->fail('Expected to get exception here');
} catch (\InvalidArgumentException $e) {
codecept_debug('Exception: ' . $e->getMessage());
}
}
}
public function testCreateSnapshotOnFail()
{
$module = Stub::construct(get_class($this->module), [make_container()], [
'_savePageSource' => \Codeception\Stub\Expected::once(function ($filename) {
$this->assertEquals(codecept_log_dir('Codeception.Module.UniversalFramework.looks.like..test.fail.html'), $filename);
}),
]);
$module->amOnPage('/');
$cest = new \Codeception\Test\Cest($this->module, 'looks:like::test', 'demo1Cest.php');
$module->_failed($cest, new \PHPUnit\Framework\AssertionFailedError());
}
}

View File

@@ -0,0 +1,148 @@
<?php
use Codeception\Module\MongoDb;
class MongoDbLegacyTest extends \PHPUnit\Framework\TestCase
{
/**
* @var array
*/
private $mongoConfig = array(
'dsn' => 'mongodb://localhost:27017/test'
);
/**
* @var MongoDb
*/
protected $module;
/**
* @var \MongoDb
*/
protected $db;
/**
* @var \MongoCollection
*/
private $userCollection;
protected function setUp()
{
if (!class_exists('Mongo')) {
$this->markTestSkipped('Mongo is not installed');
}
if (!class_exists('MongoDB\Client')) {
$this->markTestSkipped('MongoDb\Client is not installed');
}
$mongo = new \MongoClient();
$this->module = new MongoDb(make_container());
$this->module->_setConfig($this->mongoConfig);
$this->module->_initialize();
$this->db = $mongo->selectDB('test');
$this->userCollection = $this->db->createCollection('users');
$this->userCollection->insert(array('id' => 1, 'email' => 'miles@davis.com'));
}
protected function tearDown()
{
if (!is_null($this->userCollection)) {
$this->userCollection->drop();
}
}
public function testSeeInCollection()
{
$this->module->seeInCollection('users', array('email' => 'miles@davis.com'));
}
public function testDontSeeInCollection()
{
$this->module->dontSeeInCollection('users', array('email' => 'davert@davert.com'));
}
public function testHaveAndSeeInCollection()
{
$this->module->haveInCollection('users', array('name' => 'John', 'email' => 'john@coltrane.com'));
$this->module->seeInCollection('users', array('name' => 'John', 'email' => 'john@coltrane.com'));
}
public function testGrabFromCollection()
{
$user = $this->module->grabFromCollection('users', array('id' => 1));
$this->assertArrayHasKey('email', $user);
$this->assertEquals('miles@davis.com', $user['email']);
}
public function testSeeNumElementsInCollection()
{
$this->module->seeNumElementsInCollection('users', 1);
$this->module->seeNumElementsInCollection('users', 1, array('email' => 'miles@davis.com'));
$this->module->seeNumElementsInCollection('users', 0, array('name' => 'Doe'));
}
public function testGrabCollectionCount()
{
$this->userCollection->insert(array('id' => 2, 'email' => 'louis@armstrong.com'));
$this->userCollection->insert(array('id' => 3, 'email' => 'dizzy@gillespie.com'));
$this->assertEquals(1, $this->module->grabCollectionCount('users', array('id' => 3)));
$this->assertEquals(3, $this->module->grabCollectionCount('users'));
}
public function testSeeElementIsArray()
{
$this->userCollection->insert(array('id' => 4, 'trumpets' => array('piccolo', 'bass', 'slide')));
$this->module->seeElementIsArray('users', array('id' => 4), 'trumpets');
}
public function testSeeElementIsArrayThrowsError()
{
$this->setExpectedException('PHPUnit\Framework\ExpectationFailedException');
$this->userCollection->insert(array('id' => 5, 'trumpets' => array('piccolo', 'bass', 'slide')));
$this->userCollection->insert(array('id' => 6, 'trumpets' => array('piccolo', 'bass', 'slide')));
$this->module->seeElementIsArray('users', array(), 'trumpets');
}
public function testSeeElementIsObject()
{
$trumpet = new \StdClass;
$trumpet->name = 'Trumpet 1';
$trumpet->pitch = 'B♭';
$trumpet->price = array('min' => 458, 'max' => 891);
$this->userCollection->insert(array('id' => 6, 'trumpet' => $trumpet));
$this->module->seeElementIsObject('users', array('id' => 6), 'trumpet');
}
public function testSeeElementIsObjectThrowsError()
{
$trumpet = new \StdClass;
$trumpet->name = 'Trumpet 1';
$trumpet->pitch = 'B♭';
$trumpet->price = array('min' => 458, 'max' => 891);
$this->setExpectedException('PHPUnit\Framework\ExpectationFailedException');
$this->userCollection->insert(array('id' => 5, 'trumpet' => $trumpet));
$this->userCollection->insert(array('id' => 6, 'trumpet' => $trumpet));
$this->module->seeElementIsObject('users', array(), 'trumpet');
}
public function testUseDatabase()
{
$this->module->useDatabase('example');
$this->module->haveInCollection('stuff', array('name' => 'Ashley', 'email' => 'me@ashleyclarke.me'));
$this->module->seeInCollection('stuff', array('name' => 'Ashley', 'email' => 'me@ashleyclarke.me'));
$this->module->dontSeeInCollection('users', array('email' => 'miles@davis.com'));
}
}

View File

@@ -0,0 +1,170 @@
<?php
use Codeception\Module\MongoDb;
use Codeception\Exception\ModuleException;
use Codeception\Test\Unit;
class MongoDbTest extends Unit
{
/**
* @var array
*/
private $mongoConfig = array(
'dsn' => 'mongodb://localhost:27017/test?connectTimeoutMS=300',
'dump' => 'tests/data/dumps/mongo.js',
'populate' => true
);
/**
* @var MongoDb
*/
protected $module;
/**
* @var \MongoDB\Database
*/
protected $db;
/**
* @var \MongoDB\Collection
*/
private $userCollection;
protected function setUp()
{
if (!class_exists('\MongoDB\Client')) {
$this->markTestSkipped('MongoDB is not installed');
}
$mongo = new \MongoDB\Client();
$this->module = new MongoDb(make_container());
$this->module->_setConfig($this->mongoConfig);
try {
$this->module->_initialize();
} catch (ModuleException $e) {
$this->markTestSkipped($e->getMessage());
}
$this->db = $mongo->selectDatabase('test');
$this->userCollection = $this->db->users;
$this->userCollection->insertOne(array('id' => 1, 'email' => 'miles@davis.com'));
}
protected function tearDown()
{
if (!is_null($this->userCollection)) {
$this->userCollection->drop();
}
}
public function testSeeInCollection()
{
$this->module->seeInCollection('users', array('email' => 'miles@davis.com'));
}
public function testDontSeeInCollection()
{
$this->module->dontSeeInCollection('users', array('email' => 'davert@davert.com'));
}
public function testHaveAndSeeInCollection()
{
$this->module->haveInCollection('users', array('name' => 'John', 'email' => 'john@coltrane.com'));
$this->module->seeInCollection('users', array('name' => 'John', 'email' => 'john@coltrane.com'));
}
public function testGrabFromCollection()
{
$user = $this->module->grabFromCollection('users', array('id' => 1));
$this->assertArrayHasKey('email', $user);
$this->assertEquals('miles@davis.com', $user['email']);
}
public function testSeeNumElementsInCollection()
{
$this->module->seeNumElementsInCollection('users', 1);
$this->module->seeNumElementsInCollection('users', 1, array('email' => 'miles@davis.com'));
$this->module->seeNumElementsInCollection('users', 0, array('name' => 'Doe'));
}
public function testGrabCollectionCount()
{
$this->userCollection->insertOne(array('id' => 2, 'email' => 'louis@armstrong.com'));
$this->userCollection->insertOne(array('id' => 3, 'email' => 'dizzy@gillespie.com'));
$this->assertEquals(1, $this->module->grabCollectionCount('users', array('id' => 3)));
$this->assertEquals(3, $this->module->grabCollectionCount('users'));
}
public function testSeeElementIsArray()
{
$this->userCollection->insertOne(array('id' => 4, 'trumpets' => array('piccolo', 'bass', 'slide')));
$this->module->seeElementIsArray('users', array('id' => 4), 'trumpets');
}
public function testSeeElementIsArrayThrowsError()
{
$this->setExpectedException('PHPUnit\Framework\ExpectationFailedException');
$this->userCollection->insertOne(array('id' => 5, 'trumpets' => array('piccolo', 'bass', 'slide')));
$this->userCollection->insertOne(array('id' => 6, 'trumpets' => array('piccolo', 'bass', 'slide')));
$this->module->seeElementIsArray('users', array(), 'trumpets');
}
public function testSeeElementIsObject()
{
$trumpet = new \StdClass;
$trumpet->name = 'Trumpet 1';
$trumpet->pitch = 'B♭';
$trumpet->price = array('min' => 458, 'max' => 891);
$this->userCollection->insertOne(array('id' => 6, 'trumpet' => $trumpet));
$this->module->seeElementIsObject('users', array('id' => 6), 'trumpet');
}
public function testSeeElementIsObjectThrowsError()
{
$trumpet = new \StdClass;
$trumpet->name = 'Trumpet 1';
$trumpet->pitch = 'B♭';
$trumpet->price = array('min' => 458, 'max' => 891);
$this->setExpectedException('PHPUnit\Framework\ExpectationFailedException');
$this->userCollection->insertOne(array('id' => 5, 'trumpet' => $trumpet));
$this->userCollection->insertOne(array('id' => 6, 'trumpet' => $trumpet));
$this->module->seeElementIsObject('users', array(), 'trumpet');
}
public function testUseDatabase()
{
$this->module->useDatabase('example');
$this->module->haveInCollection('stuff', array('name' => 'Ashley', 'email' => 'me@ashleyclarke.me'));
$this->module->seeInCollection('stuff', array('name' => 'Ashley', 'email' => 'me@ashleyclarke.me'));
$this->module->dontSeeInCollection('users', array('email' => 'miles@davis.com'));
}
public function testLoadDump()
{
$testRecords = [
['name' => 'Michael Jordan', 'position' => 'sg'],
['name' => 'Ron Harper','position' => 'pg'],
['name' => 'Steve Kerr','position' => 'pg'],
['name' => 'Toni Kukoc','position' => 'sf'],
['name' => 'Luc Longley','position' => 'c'],
['name' => 'Scottie Pippen','position' => 'sf'],
['name' => 'Dennis Rodman','position' => 'pf']
];
foreach ($testRecords as $testRecord) {
$this->module->haveInCollection('96_bulls', $testRecord);
}
}
}

View File

@@ -0,0 +1,326 @@
<?php
use Codeception\Test\Unit;
use Codeception\Util\Stub as Stub;
class PhpBrowserRestTest extends Unit
{
/**
* @var \Codeception\Module\REST
*/
protected $module;
/**
* @var \Codeception\Module\PhpBrowser
*/
protected $phpBrowser;
public function setUp()
{
$this->phpBrowser = new \Codeception\Module\PhpBrowser(make_container());
$url = 'http://localhost:8010';
$this->phpBrowser->_setConfig(['url' => $url]);
$this->phpBrowser->_initialize();
$this->module = Stub::make('\Codeception\Module\REST');
$this->module->_inject($this->phpBrowser);
$this->module->_initialize();
$this->module->_before(Stub::makeEmpty('\Codeception\Test\Cest'));
$this->phpBrowser->_before(Stub::makeEmpty('\Codeception\Test\Cest'));
}
private function setStubResponse($response)
{
$this->phpBrowser = Stub::make('\Codeception\Module\PhpBrowser', ['_getResponseContent' => $response]);
$this->module->_inject($this->phpBrowser);
$this->module->_initialize();
$this->module->_before(Stub::makeEmpty('\Codeception\Test\Cest'));
}
public function testGet()
{
$this->module->sendGET('/rest/user/');
$this->module->seeResponseIsJson();
$this->module->seeResponseContains('davert');
$this->module->seeResponseContainsJson(['name' => 'davert']);
$this->module->seeResponseCodeIs(200);
$this->module->dontSeeResponseCodeIs(404);
}
public function testSendAbsoluteUrlGet()
{
$this->module->sendGET('http://127.0.0.1:8010/rest/user/');
$this->module->seeResponseCodeIs(200);
}
public function testPost()
{
$this->module->sendPOST('/rest/user/', ['name' => 'john']);
$this->module->seeResponseContains('john');
$this->module->seeResponseContainsJson(['name' => 'john']);
}
public function testValidJson()
{
$this->setStubResponse('{"xxx": "yyy"}');
$this->module->seeResponseIsJson();
$this->setStubResponse('{"xxx": "yyy", "zzz": ["a","b"]}');
$this->module->seeResponseIsJson();
$this->module->seeResponseEquals('{"xxx": "yyy", "zzz": ["a","b"]}');
}
public function testInvalidJson()
{
$this->setExpectedException('PHPUnit\Framework\ExpectationFailedException');
$this->setStubResponse('{xxx = yyy}');
$this->module->seeResponseIsJson();
}
public function testValidXml()
{
$this->setStubResponse('<xml></xml>');
$this->module->seeResponseIsXml();
$this->setStubResponse('<xml><name>John</name></xml>');
$this->module->seeResponseIsXml();
$this->module->seeResponseEquals('<xml><name>John</name></xml>');
}
public function testInvalidXml()
{
$this->setExpectedException('PHPUnit\Framework\ExpectationFailedException');
$this->setStubResponse('<xml><name>John</surname></xml>');
$this->module->seeResponseIsXml();
}
public function testSeeInJson()
{
$this->setStubResponse(
'{"ticket": {"title": "Bug should be fixed", "user": {"name": "Davert"}, "labels": null}}'
);
$this->module->seeResponseIsJson();
$this->module->seeResponseContainsJson(['name' => 'Davert']);
$this->module->seeResponseContainsJson(['user' => ['name' => 'Davert']]);
$this->module->seeResponseContainsJson(['ticket' => ['title' => 'Bug should be fixed']]);
$this->module->seeResponseContainsJson(['ticket' => ['user' => ['name' => 'Davert']]]);
$this->module->seeResponseContainsJson(array('ticket' => array('labels' => null)));
}
public function testSeeInJsonCollection()
{
$this->setStubResponse(
'[{"user":"Blacknoir","age":27,"tags":["wed-dev","php"]},'
. '{"user":"John Doe","age":27,"tags":["web-dev","java"]}]'
);
$this->module->seeResponseIsJson();
$this->module->seeResponseContainsJson(array('tags' => array('web-dev', 'java')));
$this->module->seeResponseContainsJson(array('user' => 'John Doe', 'age' => 27));
}
public function testArrayJson()
{
$this->setStubResponse(
'[{"id":1,"title": "Bug should be fixed"},{"title": "Feature should be implemented","id":2}]'
);
$this->module->seeResponseContainsJson(array('id' => 1));
}
/**
* @issue https://github.com/Codeception/Codeception/issues/4202
*/
public function testSeeResponseContainsJsonFailsGracefullyWhenJsonResultIsNotArray()
{
$this->shouldFail();
$this->setStubResponse(json_encode('no_status'));
$this->module->seeResponseContainsJson(array('id' => 1));
}
public function testDontSeeResponseJsonMatchesJsonPathPassesWhenJsonResultIsNotArray()
{
$this->setStubResponse(json_encode('no_status'));
$this->module->dontSeeResponseJsonMatchesJsonPath('$.error');
}
public function testDontSeeInJson()
{
$this->setStubResponse('{"ticket": {"title": "Bug should be fixed", "user": {"name": "Davert"}}}');
$this->module->seeResponseIsJson();
$this->module->dontSeeResponseContainsJson(array('name' => 'Davet'));
$this->module->dontSeeResponseContainsJson(array('user' => array('name' => 'Davet')));
$this->module->dontSeeResponseContainsJson(array('user' => array('title' => 'Bug should be fixed')));
}
public function testApplicationJsonIncludesJsonAsContent()
{
$this->module->haveHttpHeader('Content-Type', 'application/json');
$this->module->sendPOST('/', array('name' => 'john'));
/** @var $request \Symfony\Component\BrowserKit\Request **/
$request = $this->module->client->getRequest();
$this->assertContains('application/json', $request->getServer());
$server = $request->getServer();
$this->assertEquals('application/json', $server['HTTP_CONTENT_TYPE']);
$this->assertJson($request->getContent());
$this->assertEmpty($request->getParameters());
}
/**
* @issue https://github.com/Codeception/Codeception/issues/3516
*/
public function testApplicationJsonHeaderCheckIsCaseInsensitive()
{
$this->module->haveHttpHeader('content-type', 'application/json');
$this->module->sendPOST('/', array('name' => 'john'));
/** @var $request \Symfony\Component\BrowserKit\Request **/
$request = $this->module->client->getRequest();
$server = $request->getServer();
$this->assertEquals('application/json', $server['HTTP_CONTENT_TYPE']);
$this->assertJson($request->getContent());
$this->assertEmpty($request->getParameters());
}
public function testGetApplicationJsonNotIncludesJsonAsContent()
{
$this->module->haveHttpHeader('Content-Type', 'application/json');
$this->module->sendGET('/', array('name' => 'john'));
/** @var $request \Symfony\Component\BrowserKit\Request **/
$request = $this->module->client->getRequest();
$this->assertNull($request->getContent());
$this->assertContains('john', $request->getParameters());
}
/**
* @Issue https://github.com/Codeception/Codeception/issues/2075
* Client is undefined for the second test
*/
public function testTwoTests()
{
$cest1 = Stub::makeEmpty('\Codeception\Test\Cest');
$cest2 = Stub::makeEmpty('\Codeception\Test\Cest');
$this->module->sendGET('/rest/user/');
$this->module->seeResponseIsJson();
$this->module->seeResponseContains('davert');
$this->module->seeResponseContainsJson(array('name' => 'davert'));
$this->module->seeResponseCodeIs(200);
$this->module->dontSeeResponseCodeIs(404);
$this->phpBrowser->_after($cest1);
$this->module->_after($cest1);
$this->module->_before($cest2);
$this->phpBrowser->_before($cest2);
$this->module->sendGET('/rest/user/');
$this->module->seeResponseIsJson();
$this->module->seeResponseContains('davert');
$this->module->seeResponseContainsJson(array('name' => 'davert'));
$this->module->seeResponseCodeIs(200);
$this->module->dontSeeResponseCodeIs(404);
}
/**
* @Issue https://github.com/Codeception/Codeception/issues/2070
*/
public function testArrayOfZeroesInJsonResponse()
{
$this->module->haveHttpHeader('Content-Type', 'application/json');
$this->module->sendGET('/rest/zeroes');
$this->module->dontSeeResponseContainsJson([
'responseCode' => 0,
'data' => [
0,
0,
0,
]
]);
}
public function testFileUploadWithKeyValueArray()
{
$tmpFileName = tempnam('/tmp', 'test_');
file_put_contents($tmpFileName, 'test data');
$files = [
'file' => $tmpFileName,
];
$this->module->sendPOST('/rest/file-upload', [], $files);
$this->module->seeResponseContainsJson([
'uploaded' => true,
]);
}
public function testFileUploadWithFilesArray()
{
$tmpFileName = tempnam('/tmp', 'test_');
file_put_contents($tmpFileName, 'test data');
$files = [
'file' => [
'name' => 'file.txt',
'type' => 'text/plain',
'size' => 9,
'tmp_name' => $tmpFileName,
]
];
$this->module->sendPOST('/rest/file-upload', [], $files);
$this->module->seeResponseContainsJson([
'uploaded' => true,
]);
}
public function testCanInspectResultOfPhpBrowserRequest()
{
$this->phpBrowser->amOnPage('/rest/user/');
$this->module->seeResponseCodeIs(200);
$this->module->seeResponseIsJson();
}
/**
* @Issue https://github.com/Codeception/Codeception/issues/1650
*/
public function testHostHeader()
{
if (getenv('dependencies') === 'lowest') {
$this->markTestSkipped('This test can\'t pass with the lowest versions of dependencies');
}
$this->module->sendGET('/rest/http-host/');
$this->module->seeResponseContains('host: "localhost:8010"');
$this->module->haveHttpHeader('Host', 'www.example.com');
$this->module->sendGET('/rest/http-host/');
$this->module->seeResponseContains('host: "www.example.com"');
}
/**
* @Issue 4203 https://github.com/Codeception/Codeception/issues/4203
* @depends testHostHeader
*/
public function testSessionHeaderBackup()
{
if (getenv('dependencies') === 'lowest') {
$this->markTestSkipped('This test can\'t pass with the lowest versions of dependencies');
}
$this->module->haveHttpHeader('Host', 'www.example.com');
$this->module->sendGET('/rest/http-host/');
$this->module->seeResponseContains('host: "www.example.com"');
$session = $this->phpBrowser->_backupSession();
$this->module->haveHttpHeader('Host', 'www.localhost.com');
$this->module->sendGET('/rest/http-host/');
$this->module->seeResponseContains('host: "www.localhost.com"');
$this->phpBrowser->_loadSession($session);
$this->module->sendGET('/rest/http-host/');
$this->module->seeResponseContains('host: "www.example.com"');
}
protected function shouldFail()
{
$this->setExpectedException('PHPUnit\Framework\AssertionFailedError');
}
public function testGrabFromCurrentUrl()
{
$this->module->sendGET('/rest/http-host/');
$this->assertEquals('/rest/http-host/', $this->phpBrowser->grabFromCurrentUrl());
}
}

View File

@@ -0,0 +1,730 @@
<?php
use Codeception\Util\Stub;
require_once 'tests/data/app/data.php';
require_once __DIR__ . '/TestsForBrowsers.php';
use GuzzleHttp\Psr7\Response;
class PhpBrowserTest extends TestsForBrowsers
{
/**
* @var \Codeception\Module\PhpBrowser
*/
protected $module;
protected $history = [];
protected function setUp()
{
$this->module = new \Codeception\Module\PhpBrowser(make_container());
$url = 'http://localhost:8000';
$this->module->_setConfig(array('url' => $url));
$this->module->_initialize();
$this->module->_before($this->makeTest());
if (class_exists('GuzzleHttp\Url')) {
$this->history = new \GuzzleHttp\Subscriber\History();
$this->module->guzzle->getEmitter()->attach($this->history);
} else {
$this->module->guzzle->getConfig('handler')->push(\GuzzleHttp\Middleware::history($this->history));
}
}
private function getLastRequest()
{
if (is_array($this->history)) {
return end($this->history)['request'];
}
return $this->history->getLastRequest();
}
protected function tearDown()
{
if ($this->module) {
$this->module->_after($this->makeTest());
}
data::clean();
}
protected function makeTest()
{
return Stub::makeEmpty('\Codeception\Test\Cept');
}
public function testAjax()
{
$this->module->amOnPage('/');
$this->module->sendAjaxGetRequest('/info');
$this->assertNotNull(data::get('ajax'));
$this->module->sendAjaxPostRequest('/form/complex', array('show' => 'author'));
$this->assertNotNull(data::get('ajax'));
$post = data::get('form');
$this->assertEquals('author', $post['show']);
}
public function testLinksWithNonLatin()
{
$this->module->amOnPage('/info');
$this->module->seeLink('Ссылочка');
$this->module->click('Ссылочка');
}
/**
* @see https://github.com/Codeception/Codeception/issues/4509
*/
public function testSeeTextAfterJSComparisionOperator()
{
$this->module->amOnPage('/info');
$this->module->see('Text behind JS comparision');
}
public function testSetMultipleCookies()
{
$this->module->amOnPage('/');
$cookie_name_1 = 'test_cookie';
$cookie_value_1 = 'this is a test';
$this->module->setCookie($cookie_name_1, $cookie_value_1);
$cookie_name_2 = '2_test_cookie';
$cookie_value_2 = '2 this is a test';
$this->module->setCookie($cookie_name_2, $cookie_value_2);
$this->module->seeCookie($cookie_name_1);
$this->module->seeCookie($cookie_name_2);
$this->module->dontSeeCookie('evil_cookie');
$cookie1 = $this->module->grabCookie($cookie_name_1);
$this->assertEquals($cookie_value_1, $cookie1);
$cookie2 = $this->module->grabCookie($cookie_name_2);
$this->assertEquals($cookie_value_2, $cookie2);
$this->module->resetCookie($cookie_name_1);
$this->module->dontSeeCookie($cookie_name_1);
$this->module->seeCookie($cookie_name_2);
$this->module->resetCookie($cookie_name_2);
$this->module->dontSeeCookie($cookie_name_2);
}
public function testSessionsHaveIndependentCookies()
{
$this->module->amOnPage('/');
$cookie_name_1 = 'test_cookie';
$cookie_value_1 = 'this is a test';
$this->module->setCookie($cookie_name_1, $cookie_value_1);
$session = $this->module->_backupSession();
$this->module->_initializeSession();
$this->module->dontSeeCookie($cookie_name_1);
$cookie_name_2 = '2_test_cookie';
$cookie_value_2 = '2 this is a test';
$this->module->setCookie($cookie_name_2, $cookie_value_2);
$this->module->_loadSession($session);
$this->module->dontSeeCookie($cookie_name_2);
$this->module->seeCookie($cookie_name_1);
}
public function testSubmitFormGet()
{
$I = $this->module;
$I->amOnPage('/search');
$I->submitForm('form', array('searchQuery' => 'test'));
$I->see('Success');
}
public function testHtmlRedirect()
{
$this->module->amOnPage('/redirect2');
$this->module->seeResponseCodeIs(200);
$this->module->seeCurrentUrlEquals('/info');
$this->module->amOnPage('/redirect_interval');
$this->module->seeCurrentUrlEquals('/redirect_interval');
}
public function testHtmlRedirectWithParams()
{
$this->module->amOnPage('/redirect_params');
$this->module->seeResponseCodeIs(200);
$this->module->seeCurrentUrlEquals('/search?one=1&two=2');
}
public function testMetaRefresh()
{
$this->module->amOnPage('/redirect_meta_refresh');
$this->module->seeResponseCodeIs(200);
$this->module->seeCurrentUrlEquals('/info');
}
public function testMetaRefreshIsIgnoredIfIntervalIsLongerThanMaxInterval()
{
// prepare config
$config = $this->module->_getConfig();
$config['refresh_max_interval'] = 3; // less than 9
$this->module->_reconfigure($config);
$this->module->amOnPage('/redirect_meta_refresh');
$this->module->seeResponseCodeIs(200);
$this->module->seeCurrentUrlEquals('/redirect_meta_refresh');
}
public function testRefreshRedirect()
{
$this->module->amOnPage('/redirect3');
$this->module->seeResponseCodeIs(200);
$this->module->seeCurrentUrlEquals('/info');
$this->module->amOnPage('/redirect_header_interval');
$this->module->seeCurrentUrlEquals('/redirect_header_interval');
$this->module->see('Welcome to test app!');
}
public function testRedirectWithGetParams()
{
$this->module->amOnPage('/redirect4');
$this->module->seeInCurrentUrl('/search?ln=test@gmail.com&sn=testnumber');
$params = data::get('params');
$this->assertContains('test@gmail.com', $params);
}
public function testRedirectBaseUriHasPath()
{
// prepare config
$config = $this->module->_getConfig();
$config['url'] .= '/somepath'; // append path to the base url
$this->module->_reconfigure($config);
$this->module->amOnPage('/redirect_base_uri_has_path');
$this->module->seeResponseCodeIs(200);
$this->module->seeCurrentUrlEquals('/somepath/info');
$this->module->see('Lots of valuable data here');
}
public function testRedirectBaseUriHasPathAnd302Code()
{
// prepare config
$config = $this->module->_getConfig();
$config['url'] .= '/somepath'; // append path to the base url
$this->module->_reconfigure($config);
$this->module->amOnPage('/redirect_base_uri_has_path_302');
$this->module->seeResponseCodeIs(200);
$this->module->seeCurrentUrlEquals('/somepath/info');
$this->module->see('Lots of valuable data here');
}
public function testRelativeRedirect()
{
// test relative redirects where the effective request URI is in a
// subdirectory
$this->module->amOnPage('/relative/redirect');
$this->module->seeResponseCodeIs(200);
$this->module->seeCurrentUrlEquals('/relative/info');
// also, test relative redirects where the effective request URI is not
// in a subdirectory
$this->module->amOnPage('/relative_redirect');
$this->module->seeResponseCodeIs(200);
$this->module->seeCurrentUrlEquals('/info');
}
public function testChainedRedirects()
{
$this->module->amOnPage('/redirect_twice');
$this->module->seeResponseCodeIs(200);
$this->module->seeCurrentUrlEquals('/info');
}
public function testDisabledRedirects()
{
$this->module->client->followRedirects(false);
$this->module->amOnPage('/redirect_twice');
$this->module->seeResponseCodeIs(302);
$this->module->seeCurrentUrlEquals('/redirect_twice');
}
public function testRedirectLimitReached()
{
$this->module->client->setMaxRedirects(1);
try {
$this->module->amOnPage('/redirect_twice');
$this->assertTrue(false, 'redirect limit is not respected');
} catch (\LogicException $e) {
$this->assertEquals(
'The maximum number (1) of redirections was reached.',
$e->getMessage(),
'redirect limit is respected'
);
}
}
public function testRedirectLimitNotReached()
{
$this->module->client->setMaxRedirects(2);
$this->module->amOnPage('/redirect_twice');
$this->module->seeResponseCodeIs(200);
$this->module->seeCurrentUrlEquals('/info');
}
public function testLocationHeaderDoesNotRedirectWhenStatusCodeIs201()
{
$this->module->amOnPage('/location_201');
$this->module->seeResponseCodeIs(201);
$this->module->seeCurrentUrlEquals('/location_201');
}
public function testRedirectToAnotherDomainUsingSchemalessUrl()
{
$this->module->amOnUrl('http://httpbin.org/redirect-to?url=//example.org/');
$currentUrl = $this->module->client->getHistory()->current()->getUri();
$this->assertSame('http://example.org/', $currentUrl);
}
public function testSetCookieByHeader()
{
$this->module->amOnPage('/cookies2');
$this->module->seeResponseCodeIs(200);
$this->module->seeCookie('a');
$this->assertEquals('b', $this->module->grabCookie('a'));
$this->module->seeCookie('c');
}
public function testSettingContentTypeFromHtml()
{
$this->module->amOnPage('/content-iso');
$charset = $this->module->client->getResponse()->getHeader('Content-Type');
$this->assertEquals('text/html;charset=ISO-8859-1', $charset);
}
public function testSettingCharsetFromHtml()
{
$this->module->amOnPage('/content-cp1251');
$charset = $this->module->client->getResponse()->getHeader('Content-Type');
$this->assertEquals('text/html;charset=windows-1251', $charset);
}
/**
* @Issue https://github.com/Codeception/Codeception/issues/933
*/
public function testSubmitFormWithQueries()
{
$this->module->amOnPage('/form/example3');
$this->module->seeElement('form');
$this->module->submitForm('form', array(
'name' => 'jon',
));
$form = data::get('form');
$this->assertEquals('jon', $form['name']);
$this->module->seeCurrentUrlEquals('/form/example3?validate=yes');
}
public function testHeadersBySetHeader()
{
$this->module->setHeader('xxx', 'yyyy');
$this->module->amOnPage('/');
$this->assertTrue($this->getLastRequest()->hasHeader('xxx'));
}
public function testDeleteHeaders()
{
$this->module->setHeader('xxx', 'yyyy');
$this->module->deleteHeader('xxx');
$this->module->amOnPage('/');
$this->assertFalse($this->getLastRequest()->hasHeader('xxx'));
}
public function testDeleteHeadersByEmptyValue()
{
$this->module->setHeader('xxx', 'yyyy');
$this->module->setHeader('xxx', '');
$this->module->amOnPage('/');
$this->assertFalse($this->getLastRequest()->hasHeader('xxx'));
}
public function testCurlOptions()
{
$this->module->_setConfig(array('url' => 'http://google.com', 'curl' => array('CURLOPT_NOBODY' => true)));
$this->module->_initialize();
if (method_exists($this->module->guzzle, 'getConfig')) {
$config = $this->module->guzzle->getConfig();
} else {
$config = $this->module->guzzle->getDefaultOption('config');
}
$this->assertArrayHasKey('curl', $config);
$this->assertArrayHasKey(CURLOPT_NOBODY, $config['curl']);
}
public function testCurlSslOptions()
{
if (getenv('WERCKER_ROOT')) {
$this->markTestSkipped('Disabled on Wercker CI');
}
$this->module->_setConfig(array(
'url' => 'https://google.com',
'curl' => array(
'CURLOPT_NOBODY' => true,
'CURLOPT_SSL_CIPHER_LIST' => 'TLSv1',
)));
$this->module->_initialize();
if (method_exists($this->module->guzzle, 'getConfig')) {
$config = $this->module->guzzle->getConfig();
} else {
$config = $this->module->guzzle->getDefaultOption('config');
}
$this->assertArrayHasKey('curl', $config);
$this->assertArrayHasKey(CURLOPT_SSL_CIPHER_LIST, $config['curl']);
$this->module->amOnPage('/');
$this->assertSame('', $this->module->_getResponseContent(), 'CURLOPT_NOBODY setting is not respected');
}
public function testHttpAuth()
{
$this->module->amOnPage('/auth');
$this->module->seeResponseCodeIs(401);
$this->module->see('Unauthorized');
$this->module->amHttpAuthenticated('davert', 'password');
$this->module->amOnPage('/auth');
$this->module->seeResponseCodeIs(200);
$this->module->dontSee('Unauthorized');
$this->module->see("Welcome, davert");
$this->module->amHttpAuthenticated(null, null);
$this->module->amOnPage('/auth');
$this->module->seeResponseCodeIs(401);
$this->module->amHttpAuthenticated('davert', '123456');
$this->module->amOnPage('/auth');
$this->module->see('Forbidden');
}
public function testRawGuzzle()
{
$code = $this->module->executeInGuzzle(function (\GuzzleHttp\Client $client) {
$res = $client->get('/info');
return $res->getStatusCode();
});
$this->assertEquals(200, $code);
}
/**
* If we have a form with fields like
* ```
* <input type="file" name="foo" />
* <input type="file" name="foo[bar]" />
* ```
* then only array variable will be used while simple variable will be ignored in php $_FILES
* (eg $_FILES = [
* foo => [
* tmp_name => [
* 'bar' => 'asdf'
* ],
* //...
* ]
* ]
* )
* (notice there is no entry for file "foo", only for file "foo[bar]"
* this will check if current element contains inner arrays within it's keys
* so we can ignore element itself and only process inner files
*/
public function testFormWithFilesInOnlyArray()
{
$this->shouldFail();
$this->module->amOnPage('/form/example13');
$this->module->attachFile('foo', 'app/avatar.jpg');
$this->module->attachFile('foo[bar]', 'app/avatar.jpg');
$this->module->click('Submit');
}
public function testDoubleSlash()
{
$I = $this->module;
$I->amOnPage('/register');
$I->submitForm('form', array('test' => 'test'));
$formUrl = $this->module->client->getHistory()->current()->getUri();
$formPath = parse_url($formUrl)['path'];
$this->assertEquals($formPath, '/register');
}
public function testFillFieldWithoutPage()
{
$this->setExpectedException("\\Codeception\\Exception\\ModuleException");
$this->module->fillField('#name', 'Nothing special');
}
public function testArrayFieldSubmitForm()
{
$this->skipForOldGuzzle();
$this->module->amOnPage('/form/example17');
$this->module->submitForm(
'form',
[
'FooBar' => ['bar' => 'booze'],
'Food' => [
'beer' => [
'yum' => ['yeah' => 'crunked']
]
]
]
);
$data = data::get('form');
$this->assertEquals('booze', $data['FooBar']['bar']);
$this->assertEquals('crunked', $data['Food']['beer']['yum']['yeah']);
}
public function testCookiesForDomain()
{
$this->skipForOldGuzzle();
$mock = new \GuzzleHttp\Handler\MockHandler([
new Response(200, ['X-Foo' => 'Bar']),
]);
$handler = \GuzzleHttp\HandlerStack::create($mock);
$handler->push(\GuzzleHttp\Middleware::history($this->history));
$client = new \GuzzleHttp\Client(['handler' => $handler, 'base_uri' => 'http://codeception.com']);
$guzzleConnector = new \Codeception\Lib\Connector\Guzzle6();
$guzzleConnector->setClient($client);
$guzzleConnector->getCookieJar()->set(new \Symfony\Component\BrowserKit\Cookie('hello', 'world'));
$guzzleConnector->request('GET', 'http://codeception.com/');
$this->assertArrayHasKey('cookies', $this->history[0]['options']);
/** @var $cookie GuzzleHttp\Cookie\SetCookie **/
$cookies = $this->history[0]['options']['cookies']->toArray();
$cookie = reset($cookies);
$this->assertEquals('codeception.com', $cookie['Domain']);
}
/**
* @issue https://github.com/Codeception/Codeception/issues/2653
*/
public function testSetCookiesByOptions()
{
$config = $this->module->_getConfig();
$config['cookies'] = [
[
'Name' => 'foo',
'Value' => 'bar1',
],
[
'Name' => 'baz',
'Value' => 'bar2',
],
];
$this->module->_reconfigure($config);
// this url redirects if cookies are present
$this->module->amOnPage('/cookies');
$this->module->seeCurrentUrlEquals('/info');
}
private function skipForOldGuzzle()
{
if (class_exists('GuzzleHttp\Url')) {
$this->markTestSkipped("Not for Guzzle <6");
}
}
/**
* @issue https://github.com/Codeception/Codeception/issues/2234
*/
public function testEmptyValueOfCookie()
{
//set cookie
$this->module->amOnPage('/cookies2');
$this->module->amOnPage('/unset-cookie');
$this->module->seeResponseCodeIs(200);
$this->module->dontSeeCookie('a');
}
public function testRequestApi()
{
$this->setExpectedException('Codeception\Exception\ModuleException');
$response = $this->module->_request('POST', '/form/try', ['user' => 'davert']);
$data = data::get('form');
$this->assertEquals('davert', $data['user']);
$this->assertInternalType('string', $response);
$this->assertContains('Welcome to test app', $response);
$this->module->click('Welcome to test app'); // page not loaded
}
public function testLoadPageApi()
{
$this->module->_loadPage('POST', '/form/try', ['user' => 'davert']);
$data = data::get('form');
$this->assertEquals('davert', $data['user']);
$this->module->see('Welcome to test app');
$this->module->click('More info');
$this->module->seeInCurrentUrl('/info');
}
/**
* @issue https://github.com/Codeception/Codeception/issues/2408
*/
public function testClickFailure()
{
$this->module->amOnPage('/info');
$this->setExpectedException(
'Codeception\Exception\ElementNotFound',
"'Sign In!' is invalid CSS and XPath selector and Link or Button element with 'name=Sign In!' was not found"
);
$this->module->click('Sign In!');
}
/**
* @issue https://github.com/Codeception/Codeception/issues/2841
*/
public function testSubmitFormDoesNotKeepGetParameters()
{
$this->module->amOnPage('/form/bug2841?stuff=other');
$this->module->fillField('#texty', 'thingshjere');
$this->module->click('#submit-registration');
$this->assertEmpty(data::get('query'), 'Query string is not empty');
}
public function testClickLinkAndFillField()
{
$this->module->amOnPage('/info');
$this->module->click('Sign in!');
$this->module->seeCurrentUrlEquals('/login');
$this->module->fillField('email', 'email@example.org');
}
public function testClickSelectsClickableElementFromMatches()
{
$this->module->amOnPage('/form/multiple_matches');
$this->module->click('Press Me!');
$this->module->seeCurrentUrlEquals('/info');
}
public function testClickSelectsClickableElementFromMatchesUsingCssLocator()
{
$this->module->amOnPage('/form/multiple_matches');
$this->module->click(['css' => '.link']);
$this->module->seeCurrentUrlEquals('/info');
}
/**
* @expectedException PHPUnit\Framework\AssertionFailedError
*/
public function testClickingOnButtonOutsideFormDoesNotCauseFatalError()
{
$this->module->amOnPage('/form/button-not-in-form');
$this->module->click('The Button');
}
public function testSubmitFormWithoutEmptyOptionsInSelect()
{
$this->module->amOnPage('/form/bug3824');
$this->module->submitForm('form', []);
$this->module->dontSee('ERROR');
}
/**
* @issue https://github.com/Codeception/Codeception/issues/3953
*/
public function testFillFieldInGetFormWithoutId()
{
$this->module->amOnPage('/form/bug3953');
$this->module->selectOption('select_name', 'two');
$this->module->fillField('search_name', 'searchterm');
$this->module->click('Submit');
$params = data::get('query');
$this->assertEquals('two', $params['select_name']);
$this->assertEquals('searchterm', $params['search_name']);
}
public function testGrabPageSourceWhenNotOnPage()
{
$this->setExpectedException(
'\Codeception\Exception\ModuleException',
'Page not loaded. Use `$I->amOnPage` (or hidden API methods `_request` and `_loadPage`) to open it'
);
$this->module->grabPageSource();
}
public function testGrabPageSourceWhenOnPage()
{
$this->module->amOnPage('/minimal');
$sourceExpected =
<<<HTML
<!DOCTYPE html>
<html>
<head>
<title>
Minimal page
</title>
</head>
<body>
<h1>
Minimal page
</h1>
</body>
</html>
HTML
;
$sourceActual = $this->module->grabPageSource();
$this->assertXmlStringEqualsXmlString($sourceExpected, $sourceActual);
}
/**
* @issue https://github.com/Codeception/Codeception/issues/4383
*/
public function testSecondAmOnUrlWithEmptyPath()
{
$this->module->amOnUrl('http://localhost:8000/info');
$this->module->see('Lots of valuable data here');
$this->module->amOnUrl('http://localhost:8000');
$this->module->dontSee('Lots of valuable data here');
}
public function testSetUserAgentUsingConfig()
{
$this->module->_setConfig(['headers' => ['User-Agent' => 'Codeception User Agent Test 1.0']]);
$this->module->_initialize();
$this->module->amOnPage('/user-agent');
$response = $this->module->grabPageSource();
$this->assertEquals('Codeception User Agent Test 1.0', $response, 'Incorrect user agent');
}
public function testIfStatusCodeIsWithin2xxRange()
{
$this->module->amOnPage('https://httpstat.us/200');
$this->module->seeResponseCodeIsSuccessful();
$this->module->amOnPage('https://httpstat.us/299');
$this->module->seeResponseCodeIsSuccessful();
}
public function testIfStatusCodeIsWithin3xxRange()
{
$this->module->amOnPage('https://httpstat.us/300');
$this->module->seeResponseCodeIsRedirection();
$this->module->amOnPage('https://httpstat.us/399');
$this->module->seeResponseCodeIsRedirection();
}
public function testIfStatusCodeIsWithin4xxRange()
{
$this->module->amOnPage('https://httpstat.us/400');
$this->module->seeResponseCodeIsClientError();
$this->module->amOnPage('https://httpstat.us/499');
$this->module->seeResponseCodeIsClientError();
}
public function testIfStatusCodeIsWithin5xxRange()
{
$this->module->amOnPage('https://httpstat.us/500');
$this->module->seeResponseCodeIsServerError();
$this->module->amOnPage('https://httpstat.us/599');
$this->module->seeResponseCodeIsServerError();
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,456 @@
<?php
use Codeception\Test\Unit;
use Codeception\Util\Stub as Stub;
/**
* Class RestTest
* @group appveyor
*/
class RestTest extends Unit
{
/**
* @var \Codeception\Module\REST
*/
protected $module;
public function setUp()
{
$connector = new \Codeception\Lib\Connector\Universal();
$connector->setIndex(\Codeception\Configuration::dataDir() . '/rest/index.php');
$connectionModule = new \Codeception\Module\UniversalFramework(make_container());
$connectionModule->client = $connector;
$connectionModule->_initialize();
$this->module = Stub::make('\Codeception\Module\REST');
$this->module->_inject($connectionModule);
$this->module->_initialize();
$this->module->_before(Stub::makeEmpty('\Codeception\Test\Test'));
$this->module->client->setServerParameters([
'SCRIPT_FILENAME' => 'index.php',
'SCRIPT_NAME' => 'index',
'SERVER_NAME' => 'localhost',
'SERVER_PROTOCOL' => 'http'
]);
}
public function testConflictsWithAPI()
{
$this->assertInstanceOf('Codeception\Lib\Interfaces\ConflictsWithModule', $this->module);
$this->assertEquals('Codeception\Lib\Interfaces\API', $this->module->_conflicts());
}
private function setStubResponse($response)
{
$connectionModule = Stub::make('\Codeception\Module\UniversalFramework', ['_getResponseContent' => $response]);
$this->module->_inject($connectionModule);
$this->module->_initialize();
$this->module->_before(Stub::makeEmpty('\Codeception\Test\Test'));
}
public function testBeforeHookResetsVariables()
{
$this->module->haveHttpHeader('Origin', 'http://www.example.com');
$this->module->sendGET('/rest/user/');
$server = $this->module->client->getInternalRequest()->getServer();
$this->assertArrayHasKey('HTTP_ORIGIN', $server);
$this->module->_before(Stub::makeEmpty('\Codeception\Test\Test'));
$this->module->sendGET('/rest/user/');
$server = $this->module->client->getInternalRequest()->getServer();
$this->assertArrayNotHasKey('HTTP_ORIGIN', $server);
}
public function testGet()
{
$this->module->sendGET('/rest/user/');
$this->module->seeResponseIsJson();
$this->module->seeResponseContains('davert');
$this->module->seeResponseContainsJson(['name' => 'davert']);
$this->module->seeResponseCodeIs(200);
$this->module->dontSeeResponseCodeIs(404);
}
public function testPost()
{
$this->module->sendPOST('/rest/user/', ['name' => 'john']);
$this->module->seeResponseContains('john');
$this->module->seeResponseContainsJson(['name' => 'john']);
}
public function testPut()
{
$this->module->sendPUT('/rest/user/', ['name' => 'laura']);
$this->module->seeResponseContains('davert@mail.ua');
$this->module->seeResponseContainsJson(['name' => 'laura']);
$this->module->dontSeeResponseContainsJson(['name' => 'john']);
}
public function testGrabDataFromResponseByJsonPath()
{
$this->module->sendGET('/rest/user/');
// simple assoc array
$this->assertEquals(['davert@mail.ua'], $this->module->grabDataFromResponseByJsonPath('$.email'));
// nested assoc array
$this->assertEquals(['Kyiv'], $this->module->grabDataFromResponseByJsonPath('$.address.city'));
// nested index array
$this->assertEquals(['DavertMik'], $this->module->grabDataFromResponseByJsonPath('$.aliases[0]'));
// empty if data not found
$this->assertEquals([], $this->module->grabDataFromResponseByJsonPath('$.address.street'));
}
public function testValidJson()
{
$this->setStubResponse('{"xxx": "yyy"}');
$this->module->seeResponseIsJson();
$this->setStubResponse('{"xxx": "yyy", "zzz": ["a","b"]}');
$this->module->seeResponseIsJson();
$this->module->seeResponseEquals('{"xxx": "yyy", "zzz": ["a","b"]}');
}
public function testInvalidJson()
{
$this->setExpectedException('PHPUnit\Framework\ExpectationFailedException');
$this->setStubResponse('{xxx = yyy}');
$this->module->seeResponseIsJson();
}
public function testValidXml()
{
$this->setStubResponse('<xml></xml>');
$this->module->seeResponseIsXml();
$this->setStubResponse('<xml><name>John</name></xml>');
$this->module->seeResponseIsXml();
$this->module->seeResponseEquals('<xml><name>John</name></xml>');
}
public function testXmlResponseEquals()
{
$this->setStubResponse('<xml></xml>');
$this->module->seeResponseIsXml();
$this->module->seeXmlResponseEquals('<xml></xml>');
}
public function testInvalidXml()
{
$this->setExpectedException('PHPUnit\Framework\ExpectationFailedException');
$this->setStubResponse('<xml><name>John</surname></xml>');
$this->module->seeResponseIsXml();
}
public function testSeeInJsonResponse()
{
$this->setStubResponse(
'{"ticket": {"title": "Bug should be fixed", "user": {"name": "Davert"}, "labels": null}}'
);
$this->module->seeResponseIsJson();
$this->module->seeResponseContainsJson(['name' => 'Davert']);
$this->module->seeResponseContainsJson(['user' => ['name' => 'Davert']]);
$this->module->seeResponseContainsJson(['ticket' => ['title' => 'Bug should be fixed']]);
$this->module->seeResponseContainsJson(['ticket' => ['user' => ['name' => 'Davert']]]);
$this->module->seeResponseContainsJson(['ticket' => ['labels' => null]]);
}
public function testSeeInJsonCollection()
{
$this->setStubResponse(
'[{"user":"Blacknoir","age":"42","tags":["wed-dev","php"]},'
. '{"user":"John Doe","age":27,"tags":["web-dev","java"]}]'
);
$this->module->seeResponseIsJson();
$this->module->seeResponseContainsJson(['tags' => ['web-dev', 'java']]);
$this->module->seeResponseContainsJson(['user' => 'John Doe', 'age' => 27]);
$this->module->seeResponseContainsJson([['user' => 'John Doe', 'age' => 27]]);
$this->module->seeResponseContainsJson(
[['user' => 'Blacknoir', 'age' => 42], ['user' => 'John Doe', 'age' => "27"]]
);
}
public function testArrayJson()
{
$this->setStubResponse(
'[{"id":1,"title": "Bug should be fixed"},{"title": "Feature should be implemented","id":2}]'
);
$this->module->seeResponseContainsJson(['id' => 1]);
}
public function testDontSeeInJson()
{
$this->setStubResponse('{"ticket": {"title": "Bug should be fixed", "user": {"name": "Davert"}}}');
$this->module->seeResponseIsJson();
$this->module->dontSeeResponseContainsJson(['name' => 'Davet']);
$this->module->dontSeeResponseContainsJson(['user' => ['name' => 'Davet']]);
$this->module->dontSeeResponseContainsJson(['user' => ['title' => 'Bug should be fixed']]);
}
public function testApplicationJsonIncludesJsonAsContent()
{
$this->module->haveHttpHeader('Content-Type', 'application/json');
$this->module->sendPOST('/', ['name' => 'john']);
/** @var $request \Symfony\Component\BrowserKit\Request **/
$request = $this->module->client->getRequest();
$this->assertContains('application/json', $request->getServer());
$server = $request->getServer();
$this->assertEquals('application/json', $server['HTTP_CONTENT_TYPE']);
$this->assertJson($request->getContent());
$this->assertEmpty($request->getParameters());
}
public function testApplicationJsonIncludesObjectSerialized()
{
$this->module->haveHttpHeader('Content-Type', 'application/json');
$this->module->sendPOST('/', new JsonSerializedItem());
/** @var $request \Symfony\Component\BrowserKit\Request **/
$request = $this->module->client->getRequest();
$this->assertContains('application/json', $request->getServer());
$this->assertJson($request->getContent());
}
public function testGetApplicationJsonNotIncludesJsonAsContent()
{
$this->module->haveHttpHeader('Content-Type', 'application/json');
$this->module->sendGET('/', ['name' => 'john']);
/** @var $request \Symfony\Component\BrowserKit\Request **/
$request = $this->module->client->getRequest();
$this->assertNull($request->getContent());
$this->assertContains('john', $request->getParameters());
}
public function testUrlIsFull()
{
$this->module->sendGET('/api/v1/users');
/** @var $request \Symfony\Component\BrowserKit\Request **/
$request = $this->module->client->getRequest();
$this->assertEquals('http://localhost/api/v1/users', $request->getUri());
}
public function testSeeHeaders()
{
$response = new \Symfony\Component\BrowserKit\Response("", 200, [
'Cache-Control' => ['no-cache', 'no-store'],
'Content_Language' => 'en-US'
]);
$this->module->client->mockResponse($response);
$this->module->sendGET('/');
$this->module->seeHttpHeader('Cache-Control');
$this->module->seeHttpHeader('content_language', 'en-US');
$this->module->seeHttpHeader('Content-Language', 'en-US');
$this->module->dontSeeHttpHeader('Content-Language', 'en-RU');
$this->module->dontSeeHttpHeader('Content-Language1');
$this->module->seeHttpHeaderOnce('Content-Language');
$this->assertEquals('en-US', $this->module->grabHttpHeader('Content-Language'));
$this->assertEquals('no-cache', $this->module->grabHttpHeader('Cache-Control'));
$this->assertEquals(['no-cache', 'no-store'], $this->module->grabHttpHeader('Cache-Control', false));
}
public function testSeeHeadersOnce()
{
$this->shouldFail();
$response = new \Symfony\Component\BrowserKit\Response("", 200, [
'Cache-Control' => ['no-cache', 'no-store'],
]);
$this->module->client->mockResponse($response);
$this->module->sendGET('/');
$this->module->seeHttpHeaderOnce('Cache-Control');
}
public function testSeeResponseJsonMatchesXpath()
{
$this->setStubResponse(
'[{"user":"Blacknoir","age":27,"tags":["wed-dev","php"]},'
. '{"user":"John Doe","age":27,"tags":["web-dev","java"]}]'
);
$this->module->seeResponseIsJson();
$this->module->seeResponseJsonMatchesXpath('//user');
}
public function testSeeResponseJsonMatchesJsonPath()
{
$this->setStubResponse(
'[{"user":"Blacknoir","age":27,"tags":["wed-dev","php"]},'
. '{"user":"John Doe","age":27,"tags":["web-dev","java"]}]'
);
$this->module->seeResponseJsonMatchesJsonPath('$[*].user');
$this->module->seeResponseJsonMatchesJsonPath('$[1].tags');
}
public function testDontSeeResponseJsonMatchesJsonPath()
{
$this->setStubResponse(
'[{"user":"Blacknoir","age":27,"tags":["wed-dev","php"]},'
. '{"user":"John Doe","age":27,"tags":["web-dev","java"]}]'
);
$this->module->dontSeeResponseJsonMatchesJsonPath('$[*].profile');
}
public function testDontSeeResponseJsonMatchesXpath()
{
$this->setStubResponse(
'[{"user":"Blacknoir","age":27,"tags":["wed-dev","php"]},'
. '{"user":"John Doe","age":27,"tags":["web-dev","java"]}]'
);
$this->module->dontSeeResponseJsonMatchesXpath('//status');
}
public function testDontSeeResponseJsonMatchesXpathFails()
{
$this->shouldFail();
$this->setStubResponse(
'[{"user":"Blacknoir","age":27,"tags":["wed-dev","php"]},'
. '{"user":"John Doe","age":27,"tags":["web-dev","java"]}]'
);
$this->module->dontSeeResponseJsonMatchesXpath('//user');
}
/**
* @Issue https://github.com/Codeception/Codeception/issues/2775
*/
public function testSeeResponseJsonMatchesXPathWorksWithAmpersand()
{
$this->setStubResponse('{ "product":[ { "category":[ { "comment":"something & something" } ] } ] }');
$this->module->seeResponseIsJson();
$this->module->seeResponseJsonMatchesXpath('//comment');
}
public function testSeeResponseJsonMatchesJsonPathFails()
{
$this->shouldFail();
$this->setStubResponse(
'[{"user":"Blacknoir","age":27,"tags":["wed-dev","php"]},'
. '{"user":"John Doe","age":27,"tags":["web-dev","java"]}]'
);
$this->module->seeResponseIsJson();
$this->module->seeResponseJsonMatchesJsonPath('$[*].profile');
}
public function testStructuredJsonPathAndXPath()
{
$this->setStubResponse(
'{ "store": {"book": [{ "category": "reference", "author": "Nigel Rees", '
. '"title": "Sayings of the Century", "price": 8.95 }, { "category": "fiction", "author": "Evelyn Waugh", '
. '"title": "Sword of Honour", "price": 12.99 }, { "category": "fiction", "author": "Herman Melville", '
. '"title": "Moby Dick", "isbn": "0-553-21311-3", "price": 8.99 }, { "category": "fiction", '
. '"author": "J. R. R. Tolkien", "title": "The Lord of the Rings", "isbn": "0-395-19395-8", '
. '"price": 22.99 } ], "bicycle": {"color": "red", "price": 19.95 } } }'
);
$this->module->seeResponseIsJson();
$this->module->seeResponseJsonMatchesXpath('//book/category');
$this->module->seeResponseJsonMatchesJsonPath('$..book');
$this->module->seeResponseJsonMatchesJsonPath('$.store.book[2].author');
$this->module->dontSeeResponseJsonMatchesJsonPath('$.invalid');
$this->module->dontSeeResponseJsonMatchesJsonPath('$.store.book.*.invalidField');
}
public function testApplicationJsonSubtypeIncludesObjectSerialized()
{
$this->module->haveHttpHeader('Content-Type', 'application/resource+json');
$this->module->sendPOST('/', new JsonSerializedItem());
/** @var $request \Symfony\Component\BrowserKit\Request **/
$request = $this->module->client->getRequest();
$this->assertContains('application/resource+json', $request->getServer());
$this->assertJson($request->getContent());
}
public function testJsonTypeMatches()
{
$this->setStubResponse('{"xxx": "yyy", "user_id": 1}');
$this->module->seeResponseMatchesJsonType(['xxx' => 'string', 'user_id' => 'integer:<10']);
$this->module->dontSeeResponseMatchesJsonType(['xxx' => 'integer', 'user_id' => 'integer:<10']);
}
public function testJsonTypeMatchesWithJsonPath()
{
$this->setStubResponse('{"users": [{ "name": "davert"}, {"id": 1}]}');
$this->module->seeResponseMatchesJsonType(['name' => 'string'], '$.users[0]');
$this->module->seeResponseMatchesJsonType(['id' => 'integer'], '$.users[1]');
$this->module->dontSeeResponseMatchesJsonType(['id' => 'integer'], '$.users[0]');
}
public function testMatchJsonTypeFailsWithNiceMessage()
{
$this->setStubResponse('{"xxx": "yyy", "user_id": 1}');
try {
$this->module->seeResponseMatchesJsonType(['zzz' => 'string']);
$this->fail('it had to throw exception');
} catch (PHPUnit\Framework\AssertionFailedError $e) {
$this->assertEquals('Key `zzz` doesn\'t exist in {"xxx":"yyy","user_id":1}', $e->getMessage());
}
}
public function testDontMatchJsonTypeFailsWithNiceMessage()
{
$this->setStubResponse('{"xxx": "yyy", "user_id": 1}');
try {
$this->module->dontSeeResponseMatchesJsonType(['xxx' => 'string']);
$this->fail('it had to throw exception');
} catch (PHPUnit\Framework\AssertionFailedError $e) {
$this->assertEquals('Unexpectedly response matched: {"xxx":"yyy","user_id":1}', $e->getMessage());
}
}
public function testSeeResponseIsJsonFailsWhenResponseIsEmpty()
{
$this->shouldFail();
$this->setStubResponse('');
$this->module->seeResponseIsJson();
}
public function testSeeResponseIsJsonFailsWhenResponseIsInvalidJson()
{
$this->shouldFail();
$this->setStubResponse('{');
$this->module->seeResponseIsJson();
}
public function testSeeResponseJsonMatchesXpathCanHandleResponseWithOneElement()
{
$this->setStubResponse('{"success": 1}');
$this->module->seeResponseJsonMatchesXpath('//success');
}
public function testSeeResponseJsonMatchesXpathCanHandleResponseWithTwoElements()
{
$this->setStubResponse('{"success": 1, "info": "test"}');
$this->module->seeResponseJsonMatchesXpath('//success');
}
public function testSeeResponseJsonMatchesXpathCanHandleResponseWithOneSubArray()
{
$this->setStubResponse('{"array": {"success": 1}}');
$this->module->seeResponseJsonMatchesXpath('//array/success');
}
public function testSeeBinaryResponseEquals()
{
$data = base64_decode('/9j/2wBDAAMCAgICAgMCAgIDAwMDBAYEBAQEBAgGBgUGCQgKCgkICQkKDA8MCgsOCwkJDRENDg8QEBEQCgwSExIQEw8QEBD/yQALCAABAAEBAREA/8wABgAQEAX/2gAIAQEAAD8A0s8g/9k=');
$this->setStubResponse($data);
$this->module->seeBinaryResponseEquals(md5($data));
}
public function testDontSeeBinaryResponseEquals()
{
$data = base64_decode('/9j/2wBDAAMCAgICAgMCAgIDAwMDBAYEBAQEBAgGBgUGCQgKCgkICQkKDA8MCgsOCwkJDRENDg8QEBEQCgwSExIQEw8QEBD/yQALCAABAAEBAREA/8wABgAQEAX/2gAIAQEAAD8A0s8g/9k=');
$this->setStubResponse($data);
$this->module->dontSeeBinaryResponseEquals('024f615102cdb3c8c7cf75cdc5a83d15');
}
public function testAmDigestAuthenticatedThrowsExceptionWithFunctionalModules()
{
$this->setExpectedException('\Codeception\Exception\ModuleException', 'Not supported by functional modules');
$this->module->amDigestAuthenticated('username', 'password');
}
protected function shouldFail()
{
$this->setExpectedException('PHPUnit\Framework\AssertionFailedError');
}
}
class JsonSerializedItem implements JsonSerializable
{
public function jsonSerialize()
{
return array("hello" => "world");
}
}

View File

@@ -0,0 +1,113 @@
<?php
use Codeception\Util\Stub;
/**
* Module for testing remote ftp systems.
*
* ## Status
*
* Maintainer: **nathanmac**
* Stability: **stable**
* Contact: nathan.macnamara@outlook.com
*
*/
class SFTPTest extends \PHPUnit\Framework\TestCase
{
protected $config = array(
'host' => '127.0.0.1',
'port' => 22,
'tmp' => 'temp',
'user' => 'user',
'password' => 'password',
'type' => 'sftp'
);
/**
* @var \Codeception\Module\FTP
*/
protected $module = null;
public function setUp()
{
$this->module = new \Codeception\Module\FTP(make_container());
$this->module->_setConfig($this->config);
$this->module->_before(Stub::makeEmpty('\Codeception\Test\Test'));
}
/**
* Disabled Test - for travis testing, requires testing server
*/
public function flow()
{
$this->assertEquals('/', $this->module->grabDirectory());
$this->module->makeDir('TESTING');
$this->module->amInPath('TESTING');
$this->assertEquals('/TESTING', $this->module->grabDirectory());
$files = $this->module->grabFileList();
$this->module->writeToFile('test_ftp_123.txt', 'some data added here');
$this->module->writeToFile('test_ftp_567.txt', 'some data added here');
$this->module->writeToFile('test_ftp_678.txt', 'some data added here');
$files = $this->module->grabFileList();
$this->assertContains('test_ftp_123.txt', $files);
$this->assertContains('test_ftp_567.txt', $files);
$this->assertContains('test_ftp_678.txt', $files);
$this->module->seeFileFound('test_ftp_123.txt');
$this->module->dontSeeFileFound('test_ftp_321.txt');
$this->module->seeFileFoundMatches('/^test_ftp_([0-9]{3}).txt$/');
$this->module->dontSeeFileFoundMatches('/^test_([0-9]{3})_ftp.txt$/');
$this->assertGreaterThan(0, $this->module->grabFileCount());
$this->assertGreaterThan(0, $this->module->grabFileSize('test_ftp_678.txt'));
$this->assertGreaterThan(0, $this->module->grabFileModified('test_ftp_678.txt'));
$this->module->openFile('test_ftp_567.txt');
$this->module->deleteThisFile();
$this->module->dontSeeFileFound('test_ftp_567.txt');
$this->module->openFile('test_ftp_123.txt');
$this->module->seeInThisFile('data');
$this->module->dontSeeInThisFile('banana');
$this->module->seeFileContentsEqual('some data added here');
$this->module->renameFile('test_ftp_678.txt', 'test_ftp_987.txt');
$files = $this->module->grabFileList();
$this->assertNotContains('test_ftp_678.txt', $files);
$this->assertContains('test_ftp_987.txt', $files);
$this->module->deleteFile('test_ftp_123.txt');
$files = $this->module->grabFileList();
$this->assertNotContains('test_ftp_123.txt', $files);
$this->module->amInPath('/');
$this->assertEquals('/', $this->module->grabDirectory());
$this->module->renameDir('TESTING', 'TESTING_NEW');
$this->module->deleteDir('TESTING_NEW');
// Test Clearing the Directory
$this->module->makeDir('TESTING');
$this->module->amInPath('TESTING');
$this->module->writeToFile('test_ftp_123.txt', 'some data added here');
$this->module->amInPath('/');
$this->assertGreaterThan(0, $this->module->grabFileCount('TESTING'));
$this->module->cleanDir('TESTING');
$this->assertEquals(0, $this->module->grabFileCount('TESTING'));
$this->module->deleteDir('TESTING');
}
public function tearDown()
{
$this->module->_after(Stub::makeEmpty('\Codeception\Test\Test'));
}
}

View File

@@ -0,0 +1,29 @@
<?php
class SequenceTest extends \Codeception\Test\Unit
{
// tests
public function testSequences()
{
$module = new \Codeception\Module\Sequence(make_container());
$this->assertNotEquals(sq(), sq());
$this->assertNotEquals(sq(1), sq(2));
$this->assertEquals(sq(1), sq(1));
$old = sq(1);
$module->_after($this);
$this->assertNotEquals($old, sq(1));
}
public function testSuiteSequences()
{
$module = new \Codeception\Module\Sequence(make_container());
$this->assertNotEquals(sqs(), sqs());
$this->assertNotEquals(sqs(1), sqs(2));
$this->assertEquals(sqs(1), sqs(1));
$old = sqs(1);
$module->_after($this);
$this->assertEquals($old, sqs(1));
$module->_afterSuite();
$this->assertNotEquals($old, sqs(1));
}
}

View File

@@ -0,0 +1,143 @@
<?php
use Codeception\Util\Stub;
use Codeception\Util\Soap as SoapUtil;
/**
* Class SoapTest
* @group appveyor
*/
class SoapTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Codeception\Module\Soap
*/
protected $module = null;
protected $layout;
public function setUp()
{
$this->module = new \Codeception\Module\SOAP(make_container());
$this->module->_setConfig(array(
'schema' => 'http://www.w3.org/2001/xml.xsd',
'endpoint' => 'http://codeception.com/api/wsdl'
));
$this->layout = \Codeception\Configuration::dataDir().'/xml/layout.xml';
$this->module->isFunctional = true;
$this->module->_before(Stub::makeEmpty('\Codeception\Test\Test'));
$this->module->client = Stub::makeEmpty('\Codeception\Lib\Connector\Universal');
}
public function testXmlIsBuilt()
{
$dom = new \DOMDocument();
$dom->load($this->layout);
$this->assertEqualXMLStructure($this->module->xmlRequest->documentElement, $dom->documentElement);
$this->assertXmlStringEqualsXmlString($dom->saveXML(), $this->module->xmlRequest->saveXML());
}
public function testBuildHeaders()
{
$this->module->haveSoapHeader('AuthHeader', ['username' => 'davert', 'password' => '123456']);
$dom = new \DOMDocument();
$dom->load($this->layout);
$header = $dom->createElement('AuthHeader');
$header->appendChild($dom->createElement('username', 'davert'));
$header->appendChild($dom->createElement('password', '123456'));
$dom->documentElement->getElementsByTagName('Header')->item(0)->appendChild($header);
$this->assertEqualXMLStructure($this->module->xmlRequest->documentElement, $dom->documentElement);
}
public function testBuildRequest()
{
$this->module->sendSoapRequest('KillHumans', "<item><id>1</id><subitem>2</subitem></item>");
$this->assertNotNull($this->module->xmlRequest);
$dom = new \DOMDocument();
$dom->load($this->layout);
$body = $dom->createElement('item');
$body->appendChild($dom->createElement('id', 1));
$body->appendChild($dom->createElement('subitem', 2));
$request = $dom->createElement('ns:KillHumans');
$request->appendChild($body);
$dom->documentElement->getElementsByTagName('Body')->item(0)->appendChild($request);
$this->assertEqualXMLStructure($this->module->xmlRequest->documentElement, $dom->documentElement);
}
public function testBuildRequestWithDomNode()
{
$dom = new \DOMDocument();
$dom->load($this->layout);
$body = $dom->createElement('item');
$body->appendChild($dom->createElement('id', 1));
$body->appendChild($dom->createElement('subitem', 2));
$request = $dom->createElement('ns:KillHumans');
$request->appendChild($body);
$dom->documentElement->getElementsByTagName('Body')->item(0)->appendChild($request);
$this->module->sendSoapRequest('KillHumans', $body);
$this->assertEqualXMLStructure($this->module->xmlRequest->documentElement, $dom->documentElement);
}
public function testSeeXmlIncludes()
{
$dom = new DOMDocument();
$this->module->xmlResponse = $dom;
$dom->preserveWhiteSpace = false;
$dom->loadXML('<?xml version="1.0" encoding="UTF-8"?> <doc> <a a2="2" a1="1" >123</a> </doc>');
$this->module->seeSoapResponseIncludes('<a a2="2" a1="1" >123</a>');
}
public function testSeeXmlContainsXPath()
{
$dom = new DOMDocument();
$this->module->xmlResponse = $dom;
$dom->preserveWhiteSpace = false;
$dom->loadXML('<?xml version="1.0" encoding="UTF-8"?> <doc> <a a2="2" a1="1" >123</a> </doc>');
$this->module->seeSoapResponseContainsXPath('//doc/a[@a2=2 and @a1=1]');
}
public function testSeeXmlNotContainsXPath()
{
$dom = new DOMDocument();
$this->module->xmlResponse = $dom;
$dom->preserveWhiteSpace = false;
$dom->loadXML('<?xml version="1.0" encoding="UTF-8"?> <doc> <a a2="2" a1="1" >123</a> </doc>');
$this->module->dontSeeSoapResponseContainsXPath('//doc/a[@a2=2 and @a31]');
}
public function testSeeXmlEquals()
{
$dom = new DOMDocument();
$this->module->xmlResponse = $dom;
$xml = '<?xml version="1.0" encoding="UTF-8"?> <doc> <a a2="2" a1="1" >123</a> </doc>';
$dom->preserveWhiteSpace = false;
$dom->loadXML($xml);
$this->module->seeSoapResponseEquals($xml);
}
public function testSeeXmlIncludesWithBuilder()
{
$dom = new DOMDocument();
$this->module->xmlResponse = $dom;
$dom->loadXML('<?xml version="1.0" encoding="UTF-8"?>'."\n".' <doc><a a2="2" a1="1" >123</a></doc>');
$xml = SoapUtil::request()->doc->a
->attr('a2', '2')
->attr('a1', '1')
->val('123');
$this->module->seeSoapResponseIncludes($xml);
}
public function testGrabTextFrom()
{
$dom = new DOMDocument();
$this->module->xmlResponse = $dom;
$dom->loadXML('<?xml version="1.0" encoding="UTF-8"?><doc><node>123</node></doc>');
$res = $this->module->grabTextContentFrom('doc node');
$this->assertEquals('123', $res);
$res = $this->module->grabTextContentFrom('descendant-or-self::doc/descendant::node');
$this->assertEquals('123', $res);
}
}

View File

@@ -0,0 +1,65 @@
<?php
require_once 'TestsForWeb.php';
/**
* Author: davert
* Date: 13.01.12
*
* Class TestsForMink
* Description:
*
*/
abstract class TestsForBrowsers extends TestsForWeb
{
public function testAmOnSubdomain()
{
$this->module->_reconfigure(array('url' => 'http://google.com'));
$this->module->amOnSubdomain('user');
$this->assertEquals('http://user.google.com', $this->module->_getUrl());
$this->module->_reconfigure(array('url' => 'http://www.google.com'));
$this->module->amOnSubdomain('user');
$this->assertEquals('http://user.google.com', $this->module->_getUrl());
}
public function testOpenAbsoluteUrls()
{
$this->module->amOnUrl('http://localhost:8000/');
$this->module->see('Welcome to test app!', 'h1');
$this->module->amOnUrl('http://127.0.0.1:8000/info');
$this->module->see('Information', 'h1');
$this->module->amOnPage('/form/empty');
$this->module->seeCurrentUrlEquals('/form/empty');
$this->assertEquals('http://127.0.0.1:8000', $this->module->_getUrl(), 'Host has changed');
}
public function testHeadersRedirect()
{
$this->module->amOnPage('/redirect');
$this->module->seeInCurrentUrl('info');
}
/*
* https://github.com/Codeception/Codeception/issues/1510
*/
public function testSiteRootRelativePathsForBasePathWithSubdir()
{
$this->module->_reconfigure(array('url' => 'http://localhost:8000/form'));
$this->module->amOnPage('/relative_siteroot');
$this->module->seeInCurrentUrl('/form/relative_siteroot');
$this->module->submitForm('form', array(
'test' => 'value'
));
$this->module->dontSeeInCurrentUrl('form/form/');
$this->module->amOnPage('relative_siteroot');
$this->module->click('Click me');
$this->module->dontSeeInCurrentUrl('form/form/');
}
public function testOpenPageException()
{
$this->setExpectedException('Codeception\Exception\ModuleException');
$this->module->see('Hello');
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,29 @@
<?php
use Codeception\Util\Stub;
class ModuleTest extends \PHPUnit\Framework\TestCase
{
public function testRequirements()
{
$module = Stub::make('ModuleStub');
try {
$module->_setConfig([]);
} catch (\Exception $e) {
$this->assertContains('"error"', $e->getMessage());
$this->assertContains('no\such\class', $e->getMessage());
$this->assertContains('composer', $e->getMessage());
$this->assertNotContains('installed', $e->getMessage());
return;
}
$this->fail('no exception thrown');
}
}
class ModuleStub extends \Codeception\Module implements \Codeception\Lib\Interfaces\RequiresPackage
{
public function _requires()
{
return ['no\such\class' => '"error"', 'Codeception\Module' => '"installed"'];
}
}

View File

@@ -0,0 +1,35 @@
<?php
class ScenarioTest extends \PHPUnit\Framework\TestCase
{
public function testGetHtml()
{
$step1 = $this->getMockBuilder('\Codeception\Step')
->setConstructorArgs(['Do some testing', ['arg1', 'arg2']])
->setMethods(null)
->getMock();
$step2 = $this->getMockBuilder('\Codeception\Step')
->setConstructorArgs(['Do even more testing without args', []])
->setMethods(null)
->getMock();
$scenario = new \Codeception\Scenario(new \Codeception\Test\Cept('test', 'testCept.php'));
$scenario->addStep($step1);
$scenario->addStep($step2);
$scenario->setFeature('Do some testing');
$this->assertSame(
'<h3>I WANT TO DO SOME TESTING</h3>I do some testing <span style="color: #732E81">&quot;arg1&quot;,&quot;arg2&quot;</span>'
. '<br/>I do even more testing without args<br/>',
$scenario->getHtml()
);
}
public function testScenarioCurrentNameReturnsTestName()
{
$cept = new \Codeception\Test\Cept('successfulLogin', 'successfulLoginCept.php');
$scenario = new \Codeception\Scenario($cept);
$this->assertSame('successfulLogin', $scenario->current('name'));
}
}

View File

@@ -0,0 +1,12 @@
<?php
use \Codeception\Step\ConditionalAssertion;
class ConditionalAssertionTest extends \PHPUnit\Framework\TestCase
{
public function testCantSeeToString()
{
$assertion = new ConditionalAssertion('dontSee', ['text']);
$this->assertEquals('cant see "text"', $assertion->toString(200));
}
}

View File

@@ -0,0 +1,30 @@
<?php
class ExecutorTest extends \PHPUnit\Framework\TestCase
{
/**
* @dataProvider valuesProvider
*/
public function testRun($returnValue)
{
$expected = $returnValue;
$executor = new \Codeception\Step\Executor(function () use ($returnValue) {
return $returnValue;
});
$actual = $executor->run();
$this->assertEquals($expected, $actual);
}
/**
* @return array
*/
public function valuesProvider()
{
return array(
array(true),
array(false),
);
}
}

View File

@@ -0,0 +1,127 @@
<?php
use Facebook\WebDriver\WebDriverBy;
use Codeception\Util\Locator;
class StepTest extends \PHPUnit\Framework\TestCase
{
/**
* @param $args
* @return Codeception\Step
*/
protected function getStep($args)
{
return $this->getMockBuilder('\Codeception\Step')->setConstructorArgs($args)->setMethods(null)->getMock();
}
public function testGetArguments()
{
$by = WebDriverBy::cssSelector('.something');
$step = $this->getStep([null, [$by]]);
$this->assertEquals('"' . Locator::humanReadableString($by) . '"', $step->getArgumentsAsString());
$step = $this->getStep([null, [['just', 'array']]]);
$this->assertEquals('["just","array"]', $step->getArgumentsAsString());
$step = $this->getStep([null, [function () {
}]]);
$this->assertEquals('"Closure"', $step->getArgumentsAsString());
$step = $this->getStep([null, [[$this, 'testGetArguments']]]);
$this->assertEquals('["StepTest","testGetArguments"]', $step->getArgumentsAsString());
$step = $this->getStep([null, [['PDO', 'getAvailableDrivers']]]);
$this->assertEquals('["PDO","getAvailableDrivers"]', $step->getArgumentsAsString());
}
public function testGetHtml()
{
$step = $this->getStep(['Do some testing', ['arg1', 'arg2']]);
$this->assertSame('I do some testing <span style="color: #732E81">&quot;arg1&quot;,&quot;arg2&quot;</span>', $step->getHtml());
$step = $this->getStep(['Do some testing', []]);
$this->assertSame('I do some testing', $step->getHtml());
}
public function testLongArguments()
{
$step = $this->getStep(['have in database', [str_repeat('a', 2000)]]);
$output = $step->toString(200);
$this->assertLessThan(201, strlen($output), 'Output is too long: ' . $output);
$step = $this->getStep(['have in database', [str_repeat('a', 100), str_repeat('b', 100)]]);
$output = $step->toString(50);
$this->assertEquals(50, strlen($output), 'Incorrect length of output: ' . $output);
$this->assertEquals('have in database "aaaaaaaaaaa...","bbbbbbbbbbb..."', $output);
$step = $this->getStep(['have in database', [1, str_repeat('b', 100)]]);
$output = $step->toString(50);
$this->assertEquals('have in database 1,"bbbbbbbbbbbbbbbbbbbbbbbbbb..."', $output);
$step = $this->getStep(['have in database', [str_repeat('b', 100), 1]]);
$output = $step->toString(50);
$this->assertEquals('have in database "bbbbbbbbbbbbbbbbbbbbbbbbbb...",1', $output);
}
public function testArrayAsArgument()
{
$step = $this->getStep(['see array', [[1,2,3], 'two']]);
$output = $step->toString(200);
$this->assertEquals('see array [1,2,3],"two"', $output);
}
public function testSingleQuotedStringAsArgument()
{
$step = $this->getStep(['see array', [[1,2,3], "'two'"]]);
$output = $step->toString(200);
$this->assertEquals('see array [1,2,3],"\'two\'"', $output);
}
public function testSeeUppercaseText()
{
$step = $this->getStep(['see', ['UPPER CASE']]);
$output = $step->toString(200);
$this->assertEquals('see "UPPER CASE"', $output);
}
public function testMultiByteTextLengthIsMeasuredCorrectly()
{
$step = $this->getStep(['see', ['ŽŽŽŽŽŽŽŽŽŽ', 'AAAAAAAAAAA']]);
$output = $step->toString(30);
$this->assertEquals('see "ŽŽŽŽŽŽŽŽŽŽ","AAAAAAAAAAA"', $output);
}
public function testAmOnUrl()
{
$step = $this->getStep(['amOnUrl', ['http://www.example.org/test']]);
$output = $step->toString(200);
$this->assertEquals('am on url "http://www.example.org/test"', $output);
}
public function testNoArgs()
{
$step = $this->getStep(['acceptPopup', []]);
$output = $step->toString(200);
$this->assertEquals('accept popup ', $output);
$output = $step->toString(-5);
$this->assertEquals('accept popup ', $output);
}
public function testSeeMultiLineStringInSingleLine()
{
$step = $this->getStep(['see', ["aaaa\nbbbb\nc"]]);
$output = $step->toString(200);
$this->assertEquals('see "aaaa\nbbbb\nc"', $output);
}
public function testFormattedOutput()
{
$argument = Codeception\Util\Stub::makeEmpty('\Codeception\Step\Argument\FormattedOutput');
$argument->method('getOutput')->willReturn('some formatted output');
$step = $this->getStep(['argument', [$argument]]);
$output = $step->toString(200);
$this->assertEquals('argument "some formatted output"', $output);
}
}

View File

@@ -0,0 +1,26 @@
<?php
use Codeception\Event\SuiteEvent;
use Codeception\Lib\Notification;
use Codeception\Subscriber\ErrorHandler;
use Codeception\Suite;
class ErrorHandlerTest extends \PHPUnit\Framework\TestCase
{
public function testDeprecationMessagesRespectErrorLevelSetting()
{
$errorHandler = new ErrorHandler();
$suiteEvent = new SuiteEvent(new Suite(), null, ['error_level' => 'E_ERROR']);
$errorHandler->handle($suiteEvent);
//Satisfying The Premature Exit Handling
$errorHandler->onFinish($suiteEvent);
Notification::all(); //clear the messages
$errorHandler->errorHandler(E_USER_DEPRECATED, 'deprecated message', __FILE__, __LINE__, []);
$this->assertEquals([], Notification::all(), 'Deprecation message was added to notifications');
}
}

View File

@@ -0,0 +1,125 @@
<?php
if (!defined('PHPUNIT_TESTSUITE')) {
define('PHPUNIT_TESTSUITE', true);
}
/**
* @group core
* Class SuiteManagerTest
*/
class SuiteManagerTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Codeception\SuiteManager
*/
protected $suiteman;
/**
* @var \Symfony\Component\EventDispatcher\EventDispatcher
*/
protected $dispatcher;
/**
* @var \Codeception\PHPUnit\Runner
*/
protected $runner;
public function setUp()
{
$this->dispatcher = new Symfony\Component\EventDispatcher\EventDispatcher;
$settings = \Codeception\Configuration::$defaultSuiteSettings;
$settings['actor'] = 'CodeGuy';
$this->suiteman = new \Codeception\SuiteManager($this->dispatcher, 'suite', $settings);
$printer = \Codeception\Util\Stub::makeEmpty('PHPUnit\TextUI\ResultPrinter');
$this->runner = new \Codeception\PHPUnit\Runner;
$this->runner->setPrinter($printer);
}
/**
* @group core
*/
public function testRun()
{
$events = [];
$eventListener = function ($event, $eventName) use (&$events) {
$events[] = $eventName;
};
$this->dispatcher->addListener('suite.before', $eventListener);
$this->dispatcher->addListener('suite.after', $eventListener);
$this->suiteman->run(
$this->runner,
new \PHPUnit\Framework\TestResult,
['colors' => false, 'steps' => true, 'debug' => false, 'report_useless_tests' => false, 'disallow_test_output' => false]
);
$this->assertEquals($events, ['suite.before', 'suite.after']);
}
/**
* @group core
*/
public function testFewTests()
{
$file = \Codeception\Configuration::dataDir().'SimpleCest.php';
$this->suiteman->loadTests($file);
$this->assertEquals(2, $this->suiteman->getSuite()->count());
$file = \Codeception\Configuration::dataDir().'SimpleWithNoClassCest.php';
$this->suiteman->loadTests($file);
$this->assertEquals(3, $this->suiteman->getSuite()->count());
}
/**
* When running multiple environments, getClassesFromFile() method in SuiteManager is called once for each env.
* See \Codeception\Codecept::runSuite() - for each env new SuiteManager is created and tests loaded.
* Make sure that calling getClassesFromFile() multiple times will always return the same classes.
*
* @group core
*/
public function testAddCestWithEnv()
{
$file = \Codeception\Configuration::dataDir().'SimpleNamespacedTest.php';
$this->suiteman->loadTests($file);
$this->assertEquals(3, $this->suiteman->getSuite()->count());
$newSuiteMan = new \Codeception\SuiteManager(
$this->dispatcher,
'suite',
\Codeception\Configuration::$defaultSuiteSettings
);
$newSuiteMan->loadTests($file);
$this->assertEquals(3, $newSuiteMan->getSuite()->count());
}
public function testDependencyResolution()
{
$this->suiteman->loadTests(codecept_data_dir().'SimpleWithDependencyInjectionCest.php');
$this->assertEquals(3, $this->suiteman->getSuite()->count());
}
public function testGroupEventsAreFired()
{
$events = [];
$eventListener = function ($event, $eventName) use (&$events) {
$events[] = $eventName;
};
$this->dispatcher->addListener('test.before', $eventListener);
$this->dispatcher->addListener('test.before.admin', $eventListener);
$this->dispatcher->addListener('test.after', $eventListener);
$this->dispatcher->addListener('test.after.admin', $eventListener);
$this->suiteman->loadTests(codecept_data_dir().'SimpleAdminGroupCest.php');
$result = new \PHPUnit\Framework\TestResult;
$listener = new \Codeception\PHPUnit\Listener($this->dispatcher);
$result->addListener($listener);
$this->suiteman->run(
$this->runner,
$result,
['silent' => true, 'colors' => false, 'steps' => true, 'debug' => false, 'report_useless_tests' => false, 'disallow_test_output' => false]
);
$this->assertContains('test.before', $events);
$this->assertContains('test.before.admin', $events);
$this->assertContains('test.after', $events);
$this->assertContains('test.after.admin', $events);
}
}

View File

@@ -0,0 +1,27 @@
<?php
class CeptTest extends \Codeception\Test\Unit
{
/**
* @group core
*/
public function testCeptNamings()
{
$cept = new \Codeception\Test\Cept('Build', 'tests/cli/BuildCept.php');
$path = 'tests' . DIRECTORY_SEPARATOR . 'cli' . DIRECTORY_SEPARATOR;
$this->assertEquals(
$path . 'BuildCept.php',
\Codeception\Test\Descriptor::getTestFileName($cept)
);
$this->assertEquals(
$path . 'BuildCept.php',
\Codeception\Test\Descriptor::getTestFullName($cept)
);
$this->assertEquals(
'BuildCept',
\Codeception\Test\Descriptor::getTestSignature($cept)
);
}
}

View File

@@ -0,0 +1,34 @@
<?php
/**
* Class CestTest
*/
class CestTest extends \Codeception\Test\Unit
{
/**
* @group core
*/
public function testCestNamings()
{
$klass = new stdClass();
$cest = new \Codeception\Test\Cest($klass, 'user', 'tests/cli/BootstrapCest.php');
$path = 'tests' . DIRECTORY_SEPARATOR . 'cli' . DIRECTORY_SEPARATOR;
$this->assertEquals(
$path . 'BootstrapCest.php',
\Codeception\Test\Descriptor::getTestFileName($cest)
);
$this->assertEquals(
$path . 'BootstrapCest.php:user',
\Codeception\Test\Descriptor::getTestFullName($cest)
);
$this->assertEquals(
'stdClass:user',
\Codeception\Test\Descriptor::getTestSignature($cest)
);
}
}

View File

@@ -0,0 +1,252 @@
<?php
/**
* Class GherkinTest
* @group gherkin
*/
class GherkinTest extends \Codeception\Test\Unit
{
protected $feature;
public static $calls = '';
/**
* @var \Codeception\Test\Loader\Gherkin
*/
protected $loader;
protected function _before()
{
$this->loader = new \Codeception\Test\Loader\Gherkin(
[
'gherkin' => [
'contexts' => [
'default' => ['GherkinTestContext']
]
]
]
);
self::$calls = '';
}
protected function getServices()
{
return [
'di' => new \Codeception\Lib\Di(),
'dispatcher' => new \Codeception\Util\Maybe(),
'modules' => \Codeception\Util\Stub::makeEmpty('Codeception\Lib\ModuleContainer')
];
}
public function testLoadGherkin()
{
$this->loader->loadTests(codecept_data_dir('refund.feature'));
$tests = $this->loader->getTests();
$this->assertCount(1, $tests);
/** @var $test \Codeception\Test\Gherkin * */
$test = $tests[0];
$this->assertInstanceOf('\Codeception\Test\Gherkin', $test);
$this->assertEquals('Jeff returns a faulty microwave', $test->getFeature());
}
/**
* @depends testLoadGherkin
*/
public function testLoadWithContexts()
{
$this->loader->loadTests(codecept_data_dir('refund.feature'));
$test = $this->loader->getTests()[0];
/** @var $test \Codeception\Test\Gherkin * */
$test->getMetadata()->setServices($this->getServices());
$test->test();
$this->assertEquals('abc', self::$calls);
}
/**
* @depends testLoadGherkin
* @expectedException \Codeception\Exception\ParseException
*/
public function testBadRegex()
{
$this->loader = new \Codeception\Test\Loader\Gherkin(
[
'gherkin' => [
'contexts' => [
'default' => ['GherkinInvalidContext'],
]
]
]
);
$this->loader->loadTests(codecept_data_dir('refund.feature'));
$test = $this->loader->getTests()[0];
/** @var $test \Codeception\Test\Gherkin * */
$test->getMetadata()->setServices($this->getServices());
$test->test();
}
public function testTags()
{
$this->loader = new \Codeception\Test\Loader\Gherkin(
[
'gherkin' => [
'contexts' => [
'default' => ['GherkinTestContext'],
'tag' => [
'important' => ['TagGherkinContext']
]
]
]
]
);
$this->loader->loadTests(codecept_data_dir('refund.feature'));
$test = $this->loader->getTests()[0];
/** @var $test \Codeception\Test\Gherkin * */
$test->getMetadata()->setServices($this->getServices());
$test->test();
$this->assertEquals('aXc', self::$calls);
}
public function testRoles()
{
$this->loader = new \Codeception\Test\Loader\Gherkin(
[
'gherkin' => [
'contexts' => [
'default' => ['GherkinTestContext'],
'role' => [
'customer' => ['TagGherkinContext']
]
]
]
]
);
$this->loader->loadTests(codecept_data_dir('refund.feature'));
$test = $this->loader->getTests()[0];
/** @var $test \Codeception\Test\Gherkin * */
$test->getMetadata()->setServices($this->getServices());
$test->test();
$this->assertEquals('aXc', self::$calls);
}
public function testMatchingPatterns()
{
$pattern = 'hello :name, are you from :place?';
$regex = $this->loader->makePlaceholderPattern($pattern);
$this->assertRegExp($regex, 'hello "davert", are you from "kiev"?');
$this->assertNotRegExp($regex, 'hello davert, are you from "kiev"?');
$pattern = 'hello ":name", how are you';
$regex = $this->loader->makePlaceholderPattern($pattern);
$this->assertRegExp($regex, 'hello "davert", how are you');
$this->assertNotRegExp($regex, 'hello "davert", are you from "kiev"?');
$pattern = 'there should be :num cow(s)';
$regex = $this->loader->makePlaceholderPattern($pattern);
$this->assertRegExp($regex, 'there should be "1" cow');
$this->assertRegExp($regex, 'there should be "5" cows');
$this->assertRegExp($regex, 'there should be 1000 cows');
}
public function testGherkinCurrencySymbols()
{
$pattern = 'I have :money in my pocket';
$regex = $this->loader->makePlaceholderPattern($pattern);
$this->assertRegExp($regex, 'I have 3.5$ in my pocket');
$this->assertRegExp($regex, 'I have 3.5€ in my pocket');
$this->assertRegExp($regex, 'I have $3.5 in my pocket');
$this->assertRegExp($regex, 'I have £3.5 in my pocket');
$this->assertRegExp($regex, 'I have "35.10" in my pocket');
$this->assertRegExp($regex, 'I have 5 in my pocket');
$this->assertRegExp($regex, 'I have 5.1 in my pocket');
$this->assertNotRegExp($regex, 'I have 3.5 $ in my pocket');
$this->assertNotRegExp($regex, 'I have 3.5euro in my pocket');
// Issue #3156
$pattern = "there is a :arg1 product witch costs :arg2 €";
$regex = $this->loader->makePlaceholderPattern($pattern);
$this->assertRegExp($regex, 'there is a "football ball" product witch costs "1,5" €');
}
public function testMatchingEscapedPatterns()
{
$pattern = 'use password ":pass"';
$regex = $this->loader->makePlaceholderPattern($pattern);
$this->assertRegExp($regex, 'use password "fref\"fr"');
}
/**
* @Issue #3051
*/
public function testSimilarSteps()
{
$pattern = 'there is a User called :arg1';
$regex = $this->loader->makePlaceholderPattern($pattern);
$this->assertRegExp($regex, 'there is a User called "John"');
$this->assertNotRegExp($regex, 'there is a User called "John" and surname "Smith"');
}
public function testMultipleSteps()
{
$patterns = array_keys($this->loader->getSteps()['default']);
$this->assertContains('/^he returns the microwave$/u', $patterns);
$this->assertContains('/^microwave is brought back$/u', $patterns);
}
}
class GherkinTestContext
{
/**
* @Given Jeff has bought a microwave for :param
*/
public function hasBoughtMicrowave()
{
GherkinTest::$calls .= 'a';
}
/**
* @When he returns the microwave
* @Then microwave is brought back
*/
public function heReturns()
{
GherkinTest::$calls .= 'b';
}
/**
* @Then Jeff should be refunded $100
*/
public function beRefunded()
{
GherkinTest::$calls .= 'c';
}
}
class TagGherkinContext
{
/**
* @When he returns the microwave
*/
public function heReturns()
{
GherkinTest::$calls .= 'X';
}
}
class GherkinInvalidContext
{
/**
* @Given /I (?:use:am connected to) the database (?db:.+)/i
*/
public function notWorks()
{
}
}

View File

@@ -0,0 +1,14 @@
<?php
class TestTest extends \Codeception\Test\Unit
{
public function testReportedInterface()
{
$this->assertInstanceOf('\\Codeception\\Test\\Interfaces\\Reported', $this);
$this->assertEquals(array(
'file' => __FILE__,
'name' => 'testReportedInterface',
'class' => 'TestTest'
), $this->getReportFields());
}
}

View File

@@ -0,0 +1,92 @@
<?php
/**
* Class TestLoaderTest
* @group load
*/
class TestLoaderTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Codeception\Test\Loader
*/
protected $testLoader;
protected function setUp()
{
$this->testLoader = new \Codeception\Test\Loader(['path' => \Codeception\Configuration::dataDir()]);
}
/**
* @group core
*/
public function testAddCept()
{
$this->testLoader->loadTest('SimpleCept.php');
$this->assertCount(1, $this->testLoader->getTests());
}
public function testAddTest()
{
$this->testLoader->loadTest('SimpleTest.php');
$this->assertCount(1, $this->testLoader->getTests());
}
public function testAddCeptAbsolutePath()
{
$this->testLoader->loadTest(codecept_data_dir('SimpleCept.php'));
$this->assertCount(1, $this->testLoader->getTests());
}
public function testAddCeptWithoutExtension()
{
$this->testLoader->loadTest('SimpleCept');
$this->assertCount(1, $this->testLoader->getTests());
}
/**
* @group core
*/
public function testLoadFileWithFewCases()
{
$this->testLoader->loadTest('SimpleNamespacedTest.php');
$this->assertCount(3, $this->testLoader->getTests());
}
/**
* @group core
*/
public function testLoadAllTests()
{
// to autoload dependencies
Codeception\Util\Autoload::addNamespace(
'Math',
codecept_data_dir().'claypit/tests/_support/Math'
);
Codeception\Util\Autoload::addNamespace('Codeception\Module', codecept_data_dir().'claypit/tests/_support');
$this->testLoader = new \Codeception\Test\Loader(['path' => codecept_data_dir().'claypit/tests']);
$this->testLoader->loadTests();
$testNames = $this->getTestNames($this->testLoader->getTests());
$this->assertContainsTestName('AnotherCept', $testNames);
$this->assertContainsTestName('MageGuildCest:darkPower', $testNames);
$this->assertContainsTestName('FailingTest:testMe', $testNames);
$this->assertContainsTestName('MathCest:testAddition', $testNames);
$this->assertContainsTestName('MathTest:testAll', $testNames);
}
protected function getTestNames($tests)
{
$testNames = [];
foreach ($tests as $test) {
$testNames[] = \Codeception\Test\Descriptor::getTestSignature($test);
}
return $testNames;
}
protected function assertContainsTestName($name, $testNames)
{
$this->assertContains($name, $testNames, "$name not found in tests");
}
}

View File

@@ -0,0 +1,86 @@
<?php
use \Codeception\Util\Annotation;
/**
* Class AnnotationTest
*
* @author davert
* @tag codeception
* @tag tdd
*/
class AnnotationTest extends \PHPUnit\Framework\TestCase
{
public function testClassAnnotation()
{
$this->assertEquals('davert', Annotation::forClass(__CLASS__)->fetch('author'));
$this->assertEquals('codeception', Annotation::forClass(__CLASS__)->fetch('tag'));
}
/**
* @param $var1
* @param $var2
* @return null
*/
public function testMethodAnnotation()
{
$this->assertEquals('null', Annotation::forClass(__CLASS__)
->method('testMethodAnnotation')
->fetch('return'));
}
public function testMultipleClassAnnotations()
{
$this->assertEquals(array('codeception', 'tdd'), Annotation::forClass(__CLASS__)->fetchAll('tag'));
}
public function testMultipleMethodAnnotations()
{
$this->assertEquals(
array('$var1', '$var2'),
Annotation::forClass(__CLASS__)->method('testMethodAnnotation')->fetchAll('param')
);
}
public function testGetAnnotationsFromDocBlock()
{
$docblock = <<<EOF
@user davert
@param key1
@param key2
EOF;
$this->assertEquals(['davert'], Annotation::fetchAnnotationsFromDocblock('user', $docblock));
$this->assertEquals(['key1', 'key2'], Annotation::fetchAnnotationsFromDocblock('param', $docblock));
}
public function testGetAllAnnotationsFromDocBlock()
{
$docblock = <<<EOF
@user davert
@param key1
@param key2
EOF;
$all = Annotation::fetchAllAnnotationsFromDocblock($docblock);
codecept_debug($all);
$this->assertEquals([
'user' => ['davert'],
'param' => ['key1', 'key2']
], Annotation::fetchAllAnnotationsFromDocblock($docblock));
}
public function testValueToSupportJson()
{
$values = Annotation::arrayValue('{ "code": "200", "user": "davert", "email": "davert@gmail.com" }');
$this->assertEquals(['code' => '200', 'user' => 'davert', 'email' => 'davert@gmail.com'], $values);
}
public function testValueToSupportAnnotationStyle()
{
$values = Annotation::arrayValue('( code="200", user="davert", email = "davert@gmail.com")');
$this->assertEquals(['code' => '200', 'user' => 'davert', 'email' => 'davert@gmail.com'], $values);
}
}

View File

@@ -0,0 +1,267 @@
<?php
namespace Codeception\Util;
class ArrayContainsComparatorTest extends \Codeception\Test\Unit
{
/**
* @var ArrayContainsComparator
*/
protected $ary;
protected function _before()
{
$this->ary = new ArrayContainsComparator(
[
'ticket' => [
'title' => 'Bug should be fixed',
'user' => ['name' => 'Davert'],
'labels' => null
]
]
);
}
// tests
public function testInclusion()
{
$this->assertTrue($this->ary->containsArray(['name' => 'Davert']));
$this->assertTrue($this->ary->containsArray(['user' => ['name' => 'Davert']]));
$this->assertTrue($this->ary->containsArray(['ticket' => ['title' => 'Bug should be fixed']]));
$this->assertTrue($this->ary->containsArray(['ticket' => ['user' => ['name' => 'Davert']]]));
$this->assertTrue($this->ary->containsArray(['ticket' => ['labels' => null]]));
}
/**
* @Issue https://github.com/Codeception/Codeception/issues/2070
*/
public function testContainsArrayComparesArrayWithMultipleZeroesCorrectly()
{
$comparator = new ArrayContainsComparator([
'responseCode' => 0,
'message' => 'OK',
'data' => [9, 0, 0],
]);
$expectedArray = [
'responseCode' => 0,
'message' => 'OK',
'data' => [0, 0, 0],
];
$this->assertFalse($comparator->containsArray($expectedArray));
}
public function testContainsArrayComparesArrayWithMultipleIdenticalSubArraysCorrectly()
{
$comparator = new ArrayContainsComparator([
'responseCode' => 0,
'message' => 'OK',
'data' => [[9], [0], [0]],
]);
$expectedArray = [
'responseCode' => 0,
'message' => 'OK',
'data' => [[0], [0], [0]],
];
$this->assertFalse($comparator->containsArray($expectedArray));
}
public function testContainsArrayComparesArrayWithValueRepeatedMultipleTimesCorrectlyNegativeCase()
{
$comparator = new ArrayContainsComparator(['foo', 'foo', 'bar']);
$expectedArray = ['foo', 'foo', 'foo'];
$this->assertFalse($comparator->containsArray($expectedArray));
}
public function testContainsArrayComparesArrayWithValueRepeatedMultipleTimesCorrectlyPositiveCase()
{
$comparator = new ArrayContainsComparator(['foo', 'foo', 'bar']);
$expectedArray = ['foo', 'bar', 'foo'];
$this->assertTrue($comparator->containsArray($expectedArray));
}
/**
* @issue https://github.com/Codeception/Codeception/issues/2630
*/
public function testContainsArrayComparesNestedSequentialArraysCorrectlyWhenSecondValueIsTheSame()
{
$array = [
['2015-09-10', 'unknown-date-1'],
['2015-10-10', 'unknown-date-1'],
];
$comparator = new ArrayContainsComparator($array);
$this->assertTrue($comparator->containsArray($array));
}
/**
* @issue https://github.com/Codeception/Codeception/issues/2630
* @codingStandardsIgnoreStart
*/
public function testContainsArrayComparesNestedSequentialArraysCorrectlyWhenSecondValueIsTheSameButOrderOfItemsIsDifferent()
{
// @codingStandardsIgnoreEnd
$comparator = new ArrayContainsComparator([
[
"2015-09-10",
"unknown-date-1"
],
[
"2015-10-10",
"unknown-date-1"
]
]);
$expectedArray = [
["2015-10-10", "unknown-date-1"],
["2015-09-10", "unknown-date-1"],
];
$this->assertTrue($comparator->containsArray($expectedArray));
}
/**
* @issue https://github.com/Codeception/Codeception/issues/2630
*/
public function testContainsArrayComparesNestedSequentialArraysCorrectlyWhenSecondValueIsDifferent()
{
$comparator = new ArrayContainsComparator([
[
"2015-09-10",
"unknown-date-1"
],
[
"2015-10-10",
"unknown-date-2"
]
]);
$expectedArray = [
["2015-09-10", "unknown-date-1"],
["2015-10-10", "unknown-date-2"],
];
$this->assertTrue($comparator->containsArray($expectedArray));
}
/**
* @issue https://github.com/Codeception/Codeception/issues/2630
*/
public function testContainsArrayComparesNestedSequentialArraysCorrectlyWhenJsonHasMoreItemsThanExpectedArray()
{
$comparator = new ArrayContainsComparator([
[
"2015-09-10",
"unknown-date-1"
],
[
"2015-10-02",
"unknown-date-1"
],
[
"2015-10-10",
"unknown-date-2"
]
]);
$expectedArray = [
["2015-09-10", "unknown-date-1"],
["2015-10-10", "unknown-date-2"],
];
$this->assertTrue($comparator->containsArray($expectedArray));
}
/**
* @issue https://github.com/Codeception/Codeception/pull/2635
*/
public function testContainsMatchesSuperSetOfExpectedAssociativeArrayInsideSequentialArray()
{
$comparator = new ArrayContainsComparator([[
'id' => '1',
'title' => 'Game of Thrones',
'body' => 'You are so awesome',
'created_at' => '2015-12-16 10:42:20',
'updated_at' => '2015-12-16 10:42:20',
]]);
$expectedArray = [['id' => '1']];
$this->assertTrue($comparator->containsArray($expectedArray));
}
/**
* @issue https://github.com/Codeception/Codeception/issues/2630
*/
public function testContainsArrayWithUnexpectedLevel()
{
$comparator = new ArrayContainsComparator([
"level1" => [
"level2irrelevant" => [],
"level2" => [
[
"level3" => [
[
"level5irrelevant1" => "a1",
"level5irrelevant2" => "a2",
"level5irrelevant3" => "a3",
"level5irrelevant4" => "a4",
"level5irrelevant5" => "a5",
"level5irrelevant6" => "a6",
"level5irrelevant7" => "a7",
"level5irrelevant8" => "a8",
"int1" => 1
]
],
"level3irrelevant" => [
"level4irrelevant" => 1
]
],
[
"level3" => [
[
"level5irrelevant1" => "b1",
"level5irrelevant2" => "b2",
"level5irrelevant3" => "b3",
"level5irrelevant4" => "b4",
"level5irrelevant5" => "b5",
"level5irrelevant6" => "b6",
"level5irrelevant7" => "b7",
"level5irrelevant8" => "b8",
"int1" => 1
]
],
"level3irrelevant" => [
"level4irrelevant" => 2
]
]
]
]
]);
$expectedArray = [
'level1' => [
'level2' => [
[
'int1' => 1,
],
[
'int1' => 1,
],
]
]
];
$this->assertTrue(
$comparator->containsArray($expectedArray),
"- <info>" . var_export($expectedArray, true) . "</info>\n"
. "+ " . var_export($comparator->getHaystack(), true)
);
}
/**
* Simplified testcase for issue reproduced by testContainsArrayWithUnexpectedLevel
*/
public function testContainsArrayComparesSequentialArraysHavingDuplicateSubArraysCorrectly()
{
$comparator = new ArrayContainsComparator([[1],[1]]);
$expectedArray = [[1],[1]];
$this->assertTrue(
$comparator->containsArray($expectedArray),
"- <info>" . var_export($expectedArray, true) . "</info>\n"
. "+ " . var_export($comparator->getHaystack(), true)
);
}
}

View File

@@ -0,0 +1,81 @@
<?php
require_once 'MockAutoload.php';
use Codeception\Util\MockAutoload as Autoload;
class AutoloadTest extends \PHPUnit\Framework\TestCase
{
protected function setUp()
{
Autoload::setFiles([
'/vendor/foo.bar/src/ClassName.php',
'/vendor/foo.bar/src/DoomClassName.php',
'/vendor/foo.bar/tests/ClassNameTest.php',
'/vendor/foo.bardoom/src/ClassName.php',
'/vendor/foo.bar.baz.dib/src/ClassName.php',
'/vendor/foo.bar.baz.dib.zim.gir/src/ClassName.php',
'/vendor/src/ClassName.php',
'/vendor/src/Foo/Bar/AnotherClassName.php',
'/vendor/src/Bar/Baz/ClassName.php',
]);
Autoload::addNamespace('Foo\Bar', '/vendor/foo.bar/src');
Autoload::addNamespace('Foo\Bar', '/vendor/foo.bar/tests');
Autoload::addNamespace('Foo\BarDoom', '/vendor/foo.bardoom/src');
Autoload::addNamespace('Foo\Bar\Baz\Dib', '/vendor/foo.bar.baz.dib/src');
Autoload::addNamespace('Foo\Bar\Baz\Dib\Zim\Gir', '/vendor/foo.bar.baz.dib.zim.gir/src');
Autoload::addNamespace('', '/vendor/src');
}
public function testExistingFile()
{
$actual = Autoload::load('Foo\Bar\ClassName');
$expect = '/vendor/foo.bar/src/ClassName.php';
$this->assertSame($expect, $actual);
$actual = Autoload::load('Foo\Bar\ClassNameTest');
$expect = '/vendor/foo.bar/tests/ClassNameTest.php';
$this->assertSame($expect, $actual);
}
public function testMissingFile()
{
$actual = Autoload::load('No_Vendor\No_Package\NoClass');
$this->assertFalse($actual);
}
public function testDeepFile()
{
$actual = Autoload::load('Foo\Bar\Baz\Dib\Zim\Gir\ClassName');
$expect = '/vendor/foo.bar.baz.dib.zim.gir/src/ClassName.php';
$this->assertSame($expect, $actual);
}
public function testConfusion()
{
$actual = Autoload::load('Foo\Bar\DoomClassName');
$expect = '/vendor/foo.bar/src/DoomClassName.php';
$this->assertSame($expect, $actual);
$actual = Autoload::load('Foo\BarDoom\ClassName');
$expect = '/vendor/foo.bardoom/src/ClassName.php';
$this->assertSame($expect, $actual);
}
public function testEmptyPrefix()
{
$actual = Autoload::load('ClassName');
$expect = '/vendor/src/ClassName.php';
$this->assertSame($expect, $actual);
$actual = Autoload::load('Foo\Bar\AnotherClassName');
$expect = '/vendor/src/Foo/Bar/AnotherClassName.php';
$this->assertSame($expect, $actual);
$actual = Autoload::load('Bar\Baz\ClassName');
$expect = '/vendor/src/Bar/Baz/ClassName.php';
$this->assertSame($expect, $actual);
}
}

View File

@@ -0,0 +1,18 @@
<?php
namespace Codeception\Util;
class HttpCodeTest extends \Codeception\Test\Unit
{
public function testHttpCodeConstants()
{
$this->assertEquals(200, HttpCode::OK);
$this->assertEquals(404, HttpCode::NOT_FOUND);
}
public function testHttpCodeWithDescription()
{
$this->assertEquals('200 (OK)', HttpCode::getDescription(200));
$this->assertEquals('301 (Moved Permanently)', HttpCode::getDescription(301));
$this->assertEquals('401 (Unauthorized)', HttpCode::getDescription(401));
}
}

View File

@@ -0,0 +1,105 @@
<?php
namespace Codeception\Util;
class JsonArrayTest extends \Codeception\Test\Unit
{
/**
* @var JsonArray
*/
protected $jsonArray;
protected function _before()
{
$this->jsonArray = new JsonArray(
'{"ticket": {"title": "Bug should be fixed", "user": {"name": "Davert"}, "labels": null}}'
);
}
public function testXmlConversion()
{
$this->assertContains(
'<ticket><title>Bug should be fixed</title><user><name>Davert</name></user><labels></labels></ticket>',
$this->jsonArray->toXml()->saveXML()
);
}
public function testXmlArrayConversion2()
{
$jsonArray = new JsonArray(
'[{"user":"Blacknoir","age":27,"tags":["wed-dev","php"]},'
. '{"user":"John Doe","age":27,"tags":["web-dev","java"]}]'
);
$this->assertContains('<tags>wed-dev</tags>', $jsonArray->toXml()->saveXML());
$this->assertEquals(2, $jsonArray->filterByXPath('//user')->length);
}
public function testXPathLocation()
{
$this->assertGreaterThan(0, $this->jsonArray->filterByXPath('//ticket/title')->length);
$this->assertGreaterThan(0, $this->jsonArray->filterByXPath('//ticket/user/name')->length);
$this->assertGreaterThan(0, $this->jsonArray->filterByXPath('//user/name')->length);
}
public function testJsonPathLocation()
{
$this->assertNotEmpty($this->jsonArray->filterByJsonPath('$..user'));
$this->assertNotEmpty($this->jsonArray->filterByJsonPath('$.ticket.user.name'));
$this->assertNotEmpty($this->jsonArray->filterByJsonPath('$..user.name'));
$this->assertEquals(['Davert'], $this->jsonArray->filterByJsonPath('$.ticket.user.name'));
$this->assertEmpty($this->jsonArray->filterByJsonPath('$..invalid'));
}
/**
* @issue https://github.com/Codeception/Codeception/issues/2535
*/
public function testThrowsInvalidArgumentExceptionIfJsonIsInvalid()
{
$this->setExpectedException('InvalidArgumentException');
new JsonArray('{"test":');
}
/**
* @issue https://github.com/Codeception/Codeception/issues/4944
*/
public function testConvertsBareJson()
{
$jsonArray = new JsonArray('"I am a {string}."');
$this->assertEquals(['I am a {string}.'], $jsonArray->toArray());
}
/**
* @Issue https://github.com/Codeception/Codeception/issues/2899
*/
public function testInvalidXmlTag()
{
$jsonArray = new JsonArray('{"a":{"foo/bar":1,"":2},"b":{"foo/bar":1,"":2},"baz":2}');
$expectedXml = '<a><invalidTag1>1</invalidTag1><invalidTag2>2</invalidTag2></a>'
. '<b><invalidTag1>1</invalidTag1><invalidTag2>2</invalidTag2></b><baz>2</baz>';
$this->assertContains($expectedXml, $jsonArray->toXml()->saveXML());
}
public function testConvertsArrayHavingSingleElement()
{
$jsonArray = new JsonArray('{"success": 1}');
$expectedXml = '<?xml version="1.0" encoding="UTF-8"?>'
. "\n<root><success>1</success></root>\n";
$this->assertEquals($expectedXml, $jsonArray->toXml()->saveXML());
}
public function testConvertsArrayHavingTwoElements()
{
$jsonArray = new JsonArray('{"success": 1, "info": "test"}');
$expectedXml = '<?xml version="1.0" encoding="UTF-8"?>'
. "\n<root><success>1</success><info>test</info></root>\n";
$this->assertEquals($expectedXml, $jsonArray->toXml()->saveXML());
}
public function testConvertsArrayHavingSingleSubArray()
{
$jsonArray = new JsonArray('{"array": {"success": 1}}');
$expectedXml = '<?xml version="1.0" encoding="UTF-8"?>'
. "\n<array><success>1</success></array>\n";
$this->assertEquals($expectedXml, $jsonArray->toXml()->saveXML());
}
}

View File

@@ -0,0 +1,207 @@
<?php
namespace Codeception\Util;
class JsonTypeTest extends \Codeception\Test\Unit
{
protected $types = [
'id' => 'integer:>10',
'retweeted' => 'Boolean',
'in_reply_to_screen_name' => 'null|string',
'name' => 'string|null', // http://codeception.com/docs/modules/REST#seeResponseMatchesJsonType
'user' => [
'url' => 'String:url'
]
];
protected $data = [
'id' => 11,
'retweeted' => false,
'in_reply_to_screen_name' => null,
'name' => null,
'user' => ['url' => 'http://davert.com']
];
public function _after()
{
JsonType::cleanCustomFilters();
}
public function testMatchBasicTypes()
{
$jsonType = new JsonType($this->data);
$this->assertTrue($jsonType->matches($this->types));
}
public function testNotMatchesBasicType()
{
$this->data['in_reply_to_screen_name'] = true;
$jsonType = new JsonType($this->data);
$this->assertContains('`in_reply_to_screen_name: true` is of type', $jsonType->matches($this->types));
}
public function testIntegerFilter()
{
$jsonType = new JsonType($this->data);
$this->assertContains('`id: 11` is of type', $jsonType->matches(['id' => 'integer:<5']));
$this->assertContains('`id: 11` is of type', $jsonType->matches(['id' => 'integer:>15']));
$this->assertTrue($jsonType->matches(['id' => 'integer:=11']));
$this->assertTrue($jsonType->matches(['id' => 'integer:>5']));
$this->assertTrue($jsonType->matches(['id' => 'integer:>5:<12']));
$this->assertNotTrue($jsonType->matches(['id' => 'integer:>5:<10']));
}
public function testUrlFilter()
{
$this->data['user']['url'] = 'invalid_url';
$jsonType = new JsonType($this->data);
$this->assertNotTrue($jsonType->matches($this->types));
}
public function testRegexFilter()
{
$jsonType = new JsonType(['numbers' => '1-2-3']);
$this->assertTrue($jsonType->matches(['numbers' => 'string:regex(~1-2-3~)']));
$this->assertTrue($jsonType->matches(['numbers' => 'string:regex(~\d-\d-\d~)']));
$this->assertNotTrue($jsonType->matches(['numbers' => 'string:regex(~^\d-\d$~)']));
$jsonType = new JsonType(['published' => 1]);
$this->assertTrue($jsonType->matches(['published' => 'integer:regex(~1~)']));
$this->assertTrue($jsonType->matches(['published' => 'integer:regex(~1|2~)']));
$this->assertTrue($jsonType->matches(['published' => 'integer:regex(~2|1~)']));
$this->assertNotTrue($jsonType->matches(['published' => 'integer:regex(~2~)']));
$this->assertNotTrue($jsonType->matches(['published' => 'integer:regex(~2|3~)']));
$this->assertNotTrue($jsonType->matches(['published' => 'integer:regex(~3|2~)']));
$jsonType = new JsonType(['date' => '2011-11-30T04:06:44Z']);
$this->assertTrue($jsonType->matches(['date' => 'string:regex(~2011-11-30T04:06:44Z|2011-11-30T05:07:00Z~)']));
$this->assertNotTrue(
$jsonType->matches(['date' => 'string:regex(~2015-11-30T04:06:44Z|2016-11-30T05:07:00Z~)'])
);
}
public function testDateTimeFilter()
{
$jsonType = new JsonType(['date' => '2011-11-30T04:06:44Z']);
$this->assertTrue($jsonType->matches(['date' => 'string:date']));
$jsonType = new JsonType(['date' => '2012-04-30T04:06:00.123Z']);
$this->assertTrue($jsonType->matches(['date' => 'string:date']));
$jsonType = new JsonType(['date' => '1931-01-05T04:06:03.1+05:30']);
$this->assertTrue($jsonType->matches(['date' => 'string:date']));
}
public function testEmailFilter()
{
$jsonType = new JsonType(['email' => 'davert@codeception.com']);
$this->assertTrue($jsonType->matches(['email' => 'string:email']));
$jsonType = new JsonType(['email' => 'davert.codeception.com']);
$this->assertNotTrue($jsonType->matches(['email' => 'string:email']));
}
public function testNegativeFilters()
{
$jsonType = new JsonType(['name' => 'davert', 'id' => 1]);
$this->assertTrue($jsonType->matches([
'name' => 'string:!date|string:!empty',
'id' => 'integer:!=0',
]));
}
public function testCustomFilters()
{
JsonType::addCustomFilter('slug', function ($value) {
return strpos($value, ' ') === false;
});
$jsonType = new JsonType(['title' => 'have a test', 'slug' => 'have-a-test']);
$this->assertTrue($jsonType->matches([
'slug' => 'string:slug'
]));
$this->assertNotTrue($jsonType->matches([
'title' => 'string:slug'
]));
JsonType::addCustomFilter('/len\((.*?)\)/', function ($value, $len) {
return strlen($value) == $len;
});
$this->assertTrue($jsonType->matches([
'slug' => 'string:len(11)'
]));
$this->assertNotTrue($jsonType->matches([
'slug' => 'string:len(7)'
]));
}
public function testArray()
{
$this->types['user'] = 'array';
$jsonType = new JsonType($this->data);
$this->assertTrue($jsonType->matches($this->types));
}
public function testNull()
{
$jsonType = new JsonType(json_decode('{
"id": 123456,
"birthdate": null,
"firstname": "John",
"lastname": "Doe"
}', true));
$this->assertTrue($jsonType->matches([
'birthdate' => 'string|null'
]));
$this->assertTrue($jsonType->matches([
'birthdate' => 'null'
]));
}
public function testOR()
{
$jsonType = new JsonType(json_decode('{
"type": "DAY"
}', true));
$this->assertTrue($jsonType->matches([
'type' => 'string:=DAY|string:=WEEK'
]));
$jsonType = new JsonType(json_decode('{
"type": "WEEK"
}', true));
$this->assertTrue($jsonType->matches([
'type' => 'string:=DAY|string:=WEEK'
]));
}
public function testCollection()
{
$jsonType = new JsonType([
['id' => 1],
['id' => 3],
['id' => 5]
]);
$this->assertTrue($jsonType->matches([
'id' => 'integer'
]));
$this->assertNotTrue($res = $jsonType->matches([
'id' => 'integer:<3'
]));
$this->assertContains('3` is of type `integer:<3', $res);
$this->assertContains('5` is of type `integer:<3', $res);
}
/**
* @issue https://github.com/Codeception/Codeception/issues/4517
*/
public function testMatchesArrayReturnedByFetchBoth()
{
$jsonType = new JsonType([
'0' => 10,
'a' => 10,
'1' => 11,
'b' => 11,
]);
$this->assertTrue($jsonType->matches([
'a' => 'integer',
'b' => 'integer',
]));
}
}

View File

@@ -0,0 +1,110 @@
<?php
use Codeception\Util\Locator;
use Facebook\WebDriver\WebDriverBy;
class LocatorTest extends \PHPUnit\Framework\TestCase
{
public function testCombine()
{
$result = Locator::combine('//button[@value="Click Me"]', '//a[.="Click Me"]');
$this->assertEquals('//button[@value="Click Me"] | //a[.="Click Me"]', $result);
$result = Locator::combine('button[value="Click Me"]', '//a[.="Click Me"]');
$this->assertEquals('descendant-or-self::button[@value = \'Click Me\'] | //a[.="Click Me"]', $result);
$xml = new SimpleXMLElement("<root><button value='Click Me' /></root>");
$this->assertNotEmpty($xml->xpath($result));
$xml = new SimpleXMLElement("<root><a href='#'>Click Me</a></root>");
$this->assertNotEmpty($xml->xpath($result));
}
public function testHref()
{
$xml = new SimpleXMLElement("<root><a href='/logout'>Click Me</a></root>");
$this->assertNotEmpty($xml->xpath(Locator::href('/logout')));
}
public function testTabIndex()
{
$xml = new SimpleXMLElement("<root><a href='#' tabindex='2'>Click Me</a></root>");
$this->assertNotEmpty($xml->xpath(Locator::tabIndex(2)));
}
public function testFind()
{
$xml = new SimpleXMLElement("<root><a href='#' tabindex='2'>Click Me</a></root>");
$this->assertNotEmpty($xml->xpath(Locator::find('a', array('href' => '#'))));
$this->assertNotEmpty($xml->xpath(Locator::find('a', array('href', 'tabindex' => '2'))));
}
public function testIsXPath()
{
$this->assertTrue(Locator::isXPath("//hr[@class='edge' and position()=1]"));
$this->assertFalse(Locator::isXPath("and position()=1]"));
$this->assertTrue(Locator::isXPath('//table[parent::div[@class="pad"] and not(@id)]//a'));
}
public function testIsId()
{
$this->assertTrue(Locator::isID('#username'));
$this->assertTrue(Locator::isID('#user.name'));
$this->assertTrue(Locator::isID('#user-name'));
$this->assertFalse(Locator::isID('#user-name .field'));
$this->assertFalse(Locator::isID('.field'));
$this->assertFalse(Locator::isID('hello'));
}
public function testIsClass()
{
$this->assertTrue(Locator::isClass('.username'));
$this->assertTrue(Locator::isClass('.name'));
$this->assertTrue(Locator::isClass('.user-name'));
$this->assertFalse(Locator::isClass('.user-name .field'));
$this->assertFalse(Locator::isClass('#field'));
$this->assertFalse(Locator::isClass('hello'));
}
public function testContains()
{
$this->assertEquals(
'descendant-or-self::label[contains(., \'enter a name\')]',
Locator::contains('label', 'enter a name')
);
$this->assertEquals(
'descendant-or-self::label[@id = \'user\'][contains(., \'enter a name\')]',
Locator::contains('label#user', 'enter a name')
);
$this->assertEquals(
'//label[@for="name"][contains(., \'enter a name\')]',
Locator::contains('//label[@for="name"]', 'enter a name')
);
}
public function testHumanReadableString()
{
$this->assertEquals("'string selector'", Locator::humanReadableString("string selector"));
$this->assertEquals("css '.something'", Locator::humanReadableString(['css' => '.something']));
$this->assertEquals(
"css selector '.something'",
Locator::humanReadableString(WebDriverBy::cssSelector('.something'))
);
try {
Locator::humanReadableString(null);
$this->fail("Expected exception when calling humanReadableString() with invalid selector");
} catch (\InvalidArgumentException $e) {
}
}
public function testLocatingElementPosition()
{
$this->assertEquals('(descendant-or-self::p)[position()=1]', Locator::firstElement('p'));
$this->assertEquals('(descendant-or-self::p)[position()=last()]', Locator::lastElement('p'));
$this->assertEquals('(descendant-or-self::p)[position()=1]', Locator::elementAt('p', 1));
$this->assertEquals('(descendant-or-self::p)[position()=last()-0]', Locator::elementAt('p', -1));
$this->assertEquals('(descendant-or-self::p)[position()=last()-1]', Locator::elementAt('p', -2));
}
}

View File

@@ -0,0 +1,18 @@
<?php
namespace Codeception\Util;
class MockAutoload extends Autoload
{
protected static $files = [];
public static function setFiles(array $files)
{
self::$files = $files;
}
protected static function requireFile($file)
{
return in_array($file, self::$files);
}
}

View File

@@ -0,0 +1,84 @@
<?php
namespace Codeception\Util;
class PathResolverTest extends \Codeception\Test\Unit
{
/**
* @dataProvider getRelativeDirTestData
* @group core
*/
public function testGetRelativeDir($path, $projDir, $dirSep, $expectedOutput)
{
$relativeDir = PathResolver::getRelativeDir($path, $projDir, $dirSep);
$this->assertEquals($expectedOutput, $relativeDir);
}
/**
* data provider for testGetRelativeDir
*
* @return array(array(strings))
*/
public function getRelativeDirTestData()
{
return [
// Unix style paths:
// projectDir() with & without trailing directory seperator: actual subdir
['/my/proj/path/some/file/in/my/proj.txt', '/my/proj/path/', '/', 'some/file/in/my/proj.txt'],
['/my/proj/path/some/file/in/my/proj.txt', '/my/proj/path', '/', 'some/file/in/my/proj.txt'],
['/my/proj/pathsome/file/in/my/proj.txt', '/my/proj/path', '/', '../pathsome/file/in/my/proj.txt'],
// Case sensitive:
['/my/proj/Path/some/file/in/my/proj.txt', '/my/proj/path/', '/', '../Path/some/file/in/my/proj.txt'],
['/my/Proj/path/some/file/in/my/proj.txt', '/my/proj/path', '/', '../../Proj/path/some/file/in/my/proj.txt'],
['My/proj/path/some/file/in/my/proj.txt', 'my/proj/path/foo/bar', '/', '../../../../../My/proj/path/some/file/in/my/proj.txt'],
['/my/proj/path/some/file/in/my/proj.txt', '/my/proj/Path/foobar/', '/', '../../path/some/file/in/my/proj.txt'],
['/my/PROJ/path/some/dir/in/my/proj/', '/my/proj/path/foobar/', '/', '../../../PROJ/path/some/dir/in/my/proj/'],
// Absolute $path, Relative projectDir()
['/my/proj/path/some/file/in/my/proj.txt', 'my/proj/path/', '/', '/my/proj/path/some/file/in/my/proj.txt'],
['/My/proj/path/some/file/in/my/proj.txt', 'my/proj/path/', '/', '/My/proj/path/some/file/in/my/proj.txt'],
// Relative $path, Absolute projectDir()
['my/proj/path/some/file/in/my/proj.txt', '/my/proj/path/', '/', 'my/proj/path/some/file/in/my/proj.txt'],
// $path & projectDir() both relative
['my/proj/path/some/file/in/my/proj.txt', 'my/proj/path/foo/bar', '/', '../../some/file/in/my/proj.txt'],
// $path & projectDir() both absolute: not a subdir
['/my/proj/path/some/file/in/my/proj.txt', '/my/proj/path/foobar/', '/', '../some/file/in/my/proj.txt'],
// ensure trailing DIRECTORY_SEPERATOR maintained
['/my/proj/path/some/dir/in/my/proj/', '/my/proj/path/foobar', '/', '../some/dir/in/my/proj/'],
// Windows style paths:
// projectDir() with & without trailing directory seperator: actual subdir
['C:\\my\\proj\\path\\some\\file\\in\\my\\proj.txt', 'C:\\my\\proj\\path\\', '\\', 'some\\file\\in\\my\\proj.txt'],
['C:\\my\\proj\\path\\some\\file\\in\\my\\proj.txt', 'C:\\my\\proj\\path', '\\', 'some\\file\\in\\my\\proj.txt'],
['C:\\my\\proj\\pathsome\\file\\in\\my\\proj.txt', 'C:\\my\\proj\\path', '\\', '..\\pathsome\\file\\in\\my\\proj.txt'],
// No device letter... absoluteness mismatch
['\\my\\proj\\path\\some\\file\\in\\my\\proj.txt', 'my\\proj\\path\\', '\\', '\\my\\proj\\path\\some\\file\\in\\my\\proj.txt'],
['my\\proj\\path\\some\\file\\in\\my\\proj.txt', '\\my\\proj\\path\\', '\\', 'my\\proj\\path\\some\\file\\in\\my\\proj.txt'],
// No device letter... absoluteness match
['my\\proj\\path\\some\\file\\in\\my\\proj.txt', 'my\\proj\\path\\foo\\bar', '\\', '..\\..\\some\\file\\in\\my\\proj.txt'],
['\\my\\proj\\path\\some\\file\\in\\my\\proj.txt', '\\my\\proj\\path\\foobar\\', '\\', '..\\some\\file\\in\\my\\proj.txt'],
['\\my\\proj\\path\\some\\dir\\in\\my\\proj\\', '\\my\\proj\\path\\foobar\\', '\\', '..\\some\\dir\\in\\my\\proj\\'],
// Device letter (both)... path absoluteness mismatch
['C:\\my\\proj\\path\\some\\file\\in\\my\\proj.txt', 'C:my\\proj\\path\\', '\\', '\\my\\proj\\path\\some\\file\\in\\my\\proj.txt'],
['d:my\\proj\\path\\some\\file\\in\\my\\proj.txt', 'd:\\my\\proj\\path\\', '\\', 'my\\proj\\path\\some\\file\\in\\my\\proj.txt'],
// Device letter (both)... path absoluteness match... case-insensitivity
['E:my\\proj\\path\\some\\file\\in\\my\\proj.txt', 'E:my\\proj\\PATH\\foo\\bar', '\\', '..\\..\\some\\file\\in\\my\\proj.txt'],
['f:\\my\\Proj\\path\\some\\file\\in\\my\\proj.txt', 'F:\\my\\proj\\path\\foobar\\', '\\', '..\\some\\file\\in\\my\\proj.txt'],
['A:\\MY\\proj\\path\\some\\dir\\in\\my\\proj\\', 'a:\\my\\proj\\path\\foobar\\', '\\', '..\\some\\dir\\in\\my\\proj\\'],
// Absoluteness mismatch
['z:\\my\\proj\\path\\some\\file\\in\\my\\proj.txt', 'my\\proj\\path\\', '\\', 'z:\\my\\proj\\path\\some\\file\\in\\my\\proj.txt'],
['Y:my\\proj\\path\\some\\file\\in\\my\\proj.txt', '\\my\\proj\\path\\', '\\', 'Y:my\\proj\\path\\some\\file\\in\\my\\proj.txt'],
['x:my\\proj\\path\\some\\file\\in\\my\\proj.txt', 'my\\proj\\path\\foo\\bar', '\\', 'x:my\\proj\\path\\some\\file\\in\\my\\proj.txt'],
['P:\\my\\proj\\path\\some\\file\\in\\my\\proj.txt', '\\my\\proj\\path\\foobar\\', '\\', 'P:\\my\\proj\\path\\some\\file\\in\\my\\proj.txt'],
['Q:\\my\\proj\\path\\some\\dir\\in\\my\\proj\\', '\\my\\proj\\path\\foobar\\', '\\', 'Q:\\my\\proj\\path\\some\\dir\\in\\my\\proj\\'],
['\\my\\proj\\path\\some\\file\\in\\my\\proj.txt', 'm:my\\proj\\path\\', '\\', '\\my\\proj\\path\\some\\file\\in\\my\\proj.txt'],
['my\\proj\\path\\some\\file\\in\\my\\proj.txt', 'N:\\my\\proj\\path\\', '\\', 'my\\proj\\path\\some\\file\\in\\my\\proj.txt'],
['my\\proj\\path\\some\\file\\in\\my\\proj.txt', 'o:my\\proj\\path\\foo\\bar', '\\', 'my\\proj\\path\\some\\file\\in\\my\\proj.txt'],
['\\my\\proj\\path\\some\\file\\in\\my\\proj.txt', 'P:\\my\\proj\\path\\foobar\\', '\\', '\\my\\proj\\path\\some\\file\\in\\my\\proj.txt'],
['\\my\\proj\\path\\some\\dir\\in\\my\\proj\\', 'q:\\my\\proj\\path\\foobar\\', '\\', '\\my\\proj\\path\\some\\dir\\in\\my\\proj\\'],
// Device letter mismatch
['A:\\my\\proj\\path\\some\\file\\in\\my\\proj.txt', 'B:my\\proj\\path\\', '\\', 'A:\\my\\proj\\path\\some\\file\\in\\my\\proj.txt'],
['c:my\\proj\\path\\some\\file\\in\\my\\proj.json', 'd:\\my\\proj\\path\\', '\\', 'c:my\\proj\\path\\some\\file\\in\\my\\proj.json'],
['M:my\\proj\\path\\foo.txt', 'N:my\\proj\\path\\foo\\bar', '\\', 'M:my\\proj\\path\\foo.txt'],
['G:\\my\\proj\\path\\baz.exe', 'C:\\my\\proj\\path\\foobar\\', '\\', 'G:\\my\\proj\\path\\baz.exe'],
['C:\\my\\proj\\path\\bam\\', 'G:\\my\\proj\\path\\foobar\\', '\\', 'C:\\my\\proj\\path\\bam\\'] ];
}
}

View File

@@ -0,0 +1,447 @@
<?php
use \Codeception\Util\Stub as Stub;
class StubTest extends \PHPUnit\Framework\TestCase
{
/**
* @var DummyClass
*/
protected $dummy;
public function setUp()
{
$conf = \Codeception\Configuration::config();
require_once $file = \Codeception\Configuration::dataDir().'DummyClass.php';
$this->dummy = new DummyClass(true);
}
public function testMakeEmpty()
{
$dummy = Stub::makeEmpty('DummyClass');
$this->assertInstanceOf('DummyClass', $dummy);
$this->assertTrue(method_exists($dummy, 'helloWorld'));
$this->assertNull($dummy->helloWorld());
}
public function testMakeEmptyMethodReplaced()
{
$dummy = Stub::makeEmpty('DummyClass', array('helloWorld' => function () {
return 'good bye world';
}));
$this->assertMethodReplaced($dummy);
}
public function testMakeEmptyMethodSimplyReplaced()
{
$dummy = Stub::makeEmpty('DummyClass', array('helloWorld' => 'good bye world'));
$this->assertMethodReplaced($dummy);
}
public function testMakeEmptyExcept()
{
$dummy = Stub::makeEmptyExcept('DummyClass', 'helloWorld');
$this->assertEquals($this->dummy->helloWorld(), $dummy->helloWorld());
$this->assertNull($dummy->goodByeWorld());
}
public function testMakeEmptyExceptPropertyReplaced()
{
$dummy = Stub::makeEmptyExcept('DummyClass', 'getCheckMe', array('checkMe' => 'checked!'));
$this->assertEquals('checked!', $dummy->getCheckMe());
}
public function testMakeEmptyExceptMagicalPropertyReplaced()
{
$dummy = Stub::makeEmptyExcept('DummyClass', 'getCheckMeToo', array('checkMeToo' => 'checked!'));
$this->assertEquals('checked!', $dummy->getCheckMeToo());
}
public function testFactory()
{
$dummies = Stub::factory('DummyClass', 2);
$this->assertCount(2, $dummies);
$this->assertInstanceOf('DummyClass', $dummies[0]);
}
public function testMake()
{
$dummy = Stub::make('DummyClass', array('goodByeWorld' => function () {
return 'hello world';
}));
$this->assertEquals($this->dummy->helloWorld(), $dummy->helloWorld());
$this->assertEquals("hello world", $dummy->goodByeWorld());
}
public function testMakeMethodReplaced()
{
$dummy = Stub::make('DummyClass', array('helloWorld' => function () {
return 'good bye world';
}));
$this->assertMethodReplaced($dummy);
}
public function testMakeWithMagicalPropertiesReplaced()
{
$dummy = Stub::make('DummyClass', array('checkMeToo' => 'checked!'));
$this->assertEquals('checked!', $dummy->checkMeToo);
}
public function testMakeMethodSimplyReplaced()
{
$dummy = Stub::make('DummyClass', array('helloWorld' => 'good bye world'));
$this->assertMethodReplaced($dummy);
}
public function testCopy()
{
$dummy = Stub::copy($this->dummy, array('checkMe' => 'checked!'));
$this->assertEquals('checked!', $dummy->getCheckMe());
$dummy = Stub::copy($this->dummy, array('checkMeToo' => 'checked!'));
$this->assertEquals('checked!', $dummy->getCheckMeToo());
}
public function testConstruct()
{
$dummy = Stub::construct('DummyClass', array('checkMe' => 'checked!'));
$this->assertEquals('constructed: checked!', $dummy->getCheckMe());
$dummy = Stub::construct(
'DummyClass',
array('checkMe' => 'checked!'),
array('targetMethod' => function () {
return false;
})
);
$this->assertEquals('constructed: checked!', $dummy->getCheckMe());
$this->assertEquals(false, $dummy->targetMethod());
}
public function testConstructMethodReplaced()
{
$dummy = Stub::construct(
'DummyClass',
array(),
array('helloWorld' => function () {
return 'good bye world';
})
);
$this->assertMethodReplaced($dummy);
}
public function testConstructMethodSimplyReplaced()
{
$dummy = Stub::make('DummyClass', array('helloWorld' => 'good bye world'));
$this->assertMethodReplaced($dummy);
}
public function testConstructEmpty()
{
$dummy = Stub::constructEmpty('DummyClass', array('checkMe' => 'checked!'));
$this->assertNull($dummy->getCheckMe());
}
public function testConstructEmptyExcept()
{
$dummy = Stub::constructEmptyExcept('DummyClass', 'getCheckMe', array('checkMe' => 'checked!'));
$this->assertNull($dummy->targetMethod());
$this->assertEquals('constructed: checked!', $dummy->getCheckMe());
}
public function testUpdate()
{
$dummy = Stub::construct('DummyClass');
Stub::update($dummy, array('checkMe' => 'done'));
$this->assertEquals('done', $dummy->getCheckMe());
Stub::update($dummy, array('checkMeToo' => 'done'));
$this->assertEquals('done', $dummy->getCheckMeToo());
}
public function testStubsFromObject()
{
$dummy = Stub::make(new \DummyClass());
$this->assertInstanceOf(
'\PHPUnit_Framework_MockObject_MockObject',
$dummy
);
$dummy = Stub::make(new \DummyOverloadableClass());
$this->assertObjectHasAttribute('__mocked', $dummy);
$dummy = Stub::makeEmpty(new \DummyClass());
$this->assertInstanceOf(
'\PHPUnit_Framework_MockObject_MockObject',
$dummy
);
$dummy = Stub::makeEmpty(new \DummyOverloadableClass());
$this->assertObjectHasAttribute('__mocked', $dummy);
$dummy = Stub::makeEmptyExcept(new \DummyClass(), 'helloWorld');
$this->assertInstanceOf(
'\PHPUnit_Framework_MockObject_MockObject',
$dummy
);
$dummy = Stub::makeEmptyExcept(new \DummyOverloadableClass(), 'helloWorld');
$this->assertObjectHasAttribute('__mocked', $dummy);
$dummy = Stub::construct(new \DummyClass());
$this->assertInstanceOf(
'\PHPUnit_Framework_MockObject_MockObject',
$dummy
);
$dummy = Stub::construct(new \DummyOverloadableClass());
$this->assertObjectHasAttribute('__mocked', $dummy);
$dummy = Stub::constructEmpty(new \DummyClass());
$this->assertInstanceOf(
'\PHPUnit_Framework_MockObject_MockObject',
$dummy
);
$dummy = Stub::constructEmpty(new \DummyOverloadableClass());
$this->assertObjectHasAttribute('__mocked', $dummy);
$dummy = Stub::constructEmptyExcept(new \DummyClass(), 'helloWorld');
$this->assertInstanceOf(
'\PHPUnit_Framework_MockObject_MockObject',
$dummy
);
$dummy = Stub::constructEmptyExcept(new \DummyOverloadableClass(), 'helloWorld');
$this->assertObjectHasAttribute('__mocked', $dummy);
}
protected function assertMethodReplaced($dummy)
{
$this->assertTrue(method_exists($dummy, 'helloWorld'));
$this->assertNotEquals($this->dummy->helloWorld(), $dummy->helloWorld());
$this->assertEquals($dummy->helloWorld(), 'good bye world');
}
public static function matcherAndFailMessageProvider()
{
return array(
array(Stub::never(),
"DummyClass::targetMethod() was not expected to be called."
),
array(Stub::atLeastOnce(),
"Expectation failed for method name is equal to <string:targetMethod> when invoked at least once.\n"
. 'Expected invocation at least once but it never occured.'
),
array(Stub::once(),
"Expectation failed for method name is equal to <string:targetMethod> when invoked 1 time(s).\n"
. 'Method was expected to be called 1 times, actually called 0 times.'
),
array(Stub::exactly(1),
"Expectation failed for method name is equal to <string:targetMethod> when invoked 3 time(s).\n"
. 'Method was expected to be called 3 times, actually called 0 times.'
),
array(Stub::exactly(3),
"Expectation failed for method name is equal to <string:targetMethod> when invoked 3 time(s).\n"
. 'Method was expected to be called 3 times, actually called 0 times.'
),
);
}
/**
* @dataProvider matcherAndFailMessageProvider
*/
public function testMockedMethodIsCalledFail($stubMarshaler, $failMessage)
{
$mock = Stub::makeEmptyExcept('DummyClass', 'call', array('targetMethod' => $stubMarshaler), $this);
$mock->goodByeWorld();
try {
if ($this->thereAreNeverMatcher($stubMarshaler)) {
$this->thenWeMustCallMethodForException($mock);
} else {
$this->thenWeDontCallAnyMethodForExceptionJustVerify($mock);
}
} catch (PHPUnit\Framework\ExpectationFailedException $e) {
$this->assertSame($failMessage, $e->getMessage());
}
$this->resetMockObjects();
}
private function thenWeMustCallMethodForException($mock)
{
$mock->call();
}
private function thenWeDontCallAnyMethodForExceptionJustVerify($mock)
{
$mock->__phpunit_verify();
$this->fail('Expected exception');
}
private function thereAreNeverMatcher($stubMarshaler)
{
$matcher = $stubMarshaler->getMatcher();
return 0 == $matcher->getInvocationCount();
}
private function resetMockObjects()
{
$refl = new ReflectionObject($this);
$refl = $refl->getParentClass();
$prop = $refl->getProperty('mockObjects');
$prop->setAccessible(true);
$prop->setValue($this, array());
}
public static function matcherProvider()
{
return array(
array(0, Stub::never()),
array(1, Stub::once()),
array(2, Stub::atLeastOnce()),
array(3, Stub::exactly(3)),
array(1, Stub::once(function () {
return true;
}), true),
array(2, Stub::atLeastOnce(function () {
return array();
}), array()),
array(1, Stub::exactly(1, function () {
return null;
}), null),
array(1, Stub::exactly(1, function () {
return 'hello world!';
}), 'hello world!'),
);
}
/**
* @dataProvider matcherProvider
*/
public function testMethodMatcherWithMake($count, $matcher, $expected = false)
{
$dummy = Stub::make('DummyClass', array('goodByeWorld' => $matcher), $this);
$this->repeatCall($count, array($dummy, 'goodByeWorld'), $expected);
}
/**
* @dataProvider matcherProvider
*/
public function testMethodMatcherWithMakeEmpty($count, $matcher)
{
$dummy = Stub::makeEmpty('DummyClass', array('goodByeWorld' => $matcher), $this);
$this->repeatCall($count, array($dummy, 'goodByeWorld'));
}
/**
* @dataProvider matcherProvider
*/
public function testMethodMatcherWithMakeEmptyExcept($count, $matcher)
{
$dummy = Stub::makeEmptyExcept('DummyClass', 'getCheckMe', array('goodByeWorld' => $matcher), $this);
$this->repeatCall($count, array($dummy, 'goodByeWorld'));
}
/**
* @dataProvider matcherProvider
*/
public function testMethodMatcherWithConstruct($count, $matcher)
{
$dummy = Stub::construct('DummyClass', array(), array('goodByeWorld' => $matcher), $this);
$this->repeatCall($count, array($dummy, 'goodByeWorld'));
}
/**
* @dataProvider matcherProvider
*/
public function testMethodMatcherWithConstructEmpty($count, $matcher)
{
$dummy = Stub::constructEmpty('DummyClass', array(), array('goodByeWorld' => $matcher), $this);
$this->repeatCall($count, array($dummy, 'goodByeWorld'));
}
/**
* @dataProvider matcherProvider
*/
public function testMethodMatcherWithConstructEmptyExcept($count, $matcher)
{
$dummy = Stub::constructEmptyExcept(
'DummyClass',
'getCheckMe',
array(),
array('goodByeWorld' => $matcher),
$this
);
$this->repeatCall($count, array($dummy, 'goodByeWorld'));
}
private function repeatCall($count, $callable, $expected = false)
{
for ($i = 0; $i < $count; $i++) {
$actual = call_user_func($callable);
if ($expected) {
$this->assertEquals($expected, $actual);
}
}
}
public function testConsecutive()
{
$dummy = Stub::make('DummyClass', array('helloWorld' => Stub::consecutive('david', 'emma', 'sam', 'amy')));
$this->assertEquals('david', $dummy->helloWorld());
$this->assertEquals('emma', $dummy->helloWorld());
$this->assertEquals('sam', $dummy->helloWorld());
$this->assertEquals('amy', $dummy->helloWorld());
// Expected null value when no more values
$this->assertNull($dummy->helloWorld());
}
public function testStubPrivateProperties()
{
$tester = Stub::construct(
'MyClassWithPrivateProperties',
['name' => 'gamma'],
[
'randomName' => 'chicken',
't' => 'ticky2',
'getRandomName' => function () {
return "randomstuff";
}
]
);
$this->assertEquals('gamma', $tester->getName());
$this->assertEquals('randomstuff', $tester->getRandomName());
$this->assertEquals('ticky2', $tester->getT());
}
public function testStubMakeEmptyInterface()
{
$stub = Stub::makeEmpty('\Countable', ['count' => 5]);
$this->assertEquals(5, $stub->count());
}
}
class MyClassWithPrivateProperties
{
private $name;
private $randomName = "gaia";
private $t = "ticky";
public function __construct($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
public function getRandomName()
{
return $this->randomName;
}
public function getT()
{
return $this->t;
}
}

View File

@@ -0,0 +1,32 @@
<?php
namespace Codeception\Util;
class TemplateTest extends \PHPUnit\Framework\TestCase
{
public function testTemplateCanPassValues()
{
$template = new Template("hello, {{name}}");
$template->place('name', 'davert');
$this->assertEquals('hello, davert', $template->produce());
}
public function testTemplateCanHaveOtherPlaceholder()
{
$template = new Template("hello, %name%", '%', '%');
$template->place('name', 'davert');
$this->assertEquals('hello, davert', $template->produce());
}
public function testTemplateSupportsDotNotationForArrays()
{
$template = new Template("hello, {{user.data.name}}");
$template->place('user', ['data' => ['name' => 'davert']]);
$this->assertEquals('hello, davert', $template->produce());
}
public function testShouldSkipUnmatchedPlaceholder()
{
$template = new Template("hello, {{name}}");
$this->assertEquals('hello, {{name}}', $template->produce());
}
}

View File

@@ -0,0 +1,122 @@
<?php
namespace Codeception\Util;
class UriTest extends \Codeception\Test\Unit
{
// tests
public function testUrlMerge()
{
$this->assertEquals(
'http://codeception.com/quickstart',
Uri::mergeUrls('http://codeception.com/hello', '/quickstart'),
'merge paths'
);
$this->assertEquals(
'http://codeception.com/hello/davert',
Uri::mergeUrls('http://codeception.com/hello/world', 'davert'),
'merge relative urls'
);
$this->assertEquals(
'https://github.com/codeception/codeception',
Uri::mergeUrls('http://codeception.com/hello/world', 'https://github.com/codeception/codeception'),
'merge absolute urls'
);
}
/**
* @Issue https://github.com/Codeception/Codeception/pull/2141
*/
public function testMergingScheme()
{
$this->assertEquals(
'https://google.com/account/',
Uri::mergeUrls('http://google.com/', 'https://google.com/account/')
);
$this->assertEquals('https://facebook.com/', Uri::mergeUrls('https://google.com/test/', '//facebook.com/'));
$this->assertEquals(
'https://facebook.com/#anchor2',
Uri::mergeUrls('https://google.com/?param=1#anchor', '//facebook.com/#anchor2')
);
}
/**
* @Issue https://github.com/Codeception/Codeception/pull/2841
*/
public function testMergingPath()
{
$this->assertEquals('/form/?param=1#anchor', Uri::mergeUrls('/form/?param=1', '#anchor'));
$this->assertEquals('/form/?param=1#anchor2', Uri::mergeUrls('/form/?param=1#anchor1', '#anchor2'));
$this->assertEquals('/form/?param=2', Uri::mergeUrls('/form/?param=1#anchor', '?param=2'));
$this->assertEquals('/page/', Uri::mergeUrls('/form/?param=1#anchor', '/page/'));
}
/**
* @Issue https://github.com/Codeception/Codeception/pull/4847
*/
public function testMergingNonParsingPath()
{
$this->assertEquals('/3.0/en/index/page:5', Uri::mergeUrls('https://cakephp.org/', '/3.0/en/index/page:5'));
}
/**
* @Issue https://github.com/Codeception/Codeception/pull/2499
*/
public function testAppendAnchor()
{
$this->assertEquals(
'http://codeception.com/quickstart#anchor',
Uri::appendPath('http://codeception.com/quickstart', '#anchor')
);
$this->assertEquals(
'http://codeception.com/quickstart#anchor',
Uri::appendPath('http://codeception.com/quickstart#first', '#anchor')
);
}
public function testAppendPath()
{
$this->assertEquals(
'http://codeception.com/quickstart/path',
Uri::appendPath('http://codeception.com/quickstart', 'path')
);
$this->assertEquals(
'http://codeception.com/quickstart/path',
Uri::appendPath('http://codeception.com/quickstart', '/path')
);
}
public function testAppendEmptyPath()
{
$this->assertEquals(
'http://codeception.com/quickstart',
Uri::appendPath('http://codeception.com/quickstart', '')
);
}
public function testAppendPathRemovesQueryStringAndAnchor()
{
$this->assertEquals(
'http://codeception.com/quickstart',
Uri::appendPath('http://codeception.com/quickstart?a=b#c', '')
);
}
public function testMergeUrlsWhenBaseUriHasNoTrailingSlashAndUriPathHasNoLeadingSlash()
{
$this->assertEquals(
'http://codeception.com/test',
Uri::mergeUrls('http://codeception.com', 'test'));
}
public function testMergeUrlsWhenBaseUriEndsWithSlashButUriPathHasNoLeadingSlash()
{
$this->assertEquals(
'http://codeception.com/test',
Uri::mergeUrls('http://codeception.com/', 'test'));
}
}

View File

@@ -0,0 +1,10 @@
<?php
// Here you can initialize variables that will for your tests
\Codeception\Configuration::$lock = true;
function make_container()
{
return \Codeception\Util\Stub::make('Codeception\Lib\ModuleContainer');
}
require_once \Codeception\Configuration::dataDir().'DummyOverloadableClass.php';