Move into nested docroot

This commit is contained in:
Rob Davies 2017-02-13 15:31:17 +00:00
parent 83a0d3a149
commit c8b70abde9
13405 changed files with 0 additions and 0 deletions

View file

@ -0,0 +1,43 @@
<?xml version="1.0" encoding="UTF-8"?>
<testsuites>
<testsuite name="Drupal Unit Test Suite" tests="1" assertions="0" failures="0" errors="1" time="0.002680">
<testsuite name="Drupal\Tests\Component\PhpStorage\FileStorageTest" file="/home/chx/www/system/core/tests/Drupal/Tests/Component/PhpStorage/FileStorageTest.php" namespace="Drupal\Tests\Component\PhpStorage" fullPackage="Drupal.Tests.Component.PhpStorage" tests="0" assertions="0" failures="0" errors="0" time="0.000000"/>
<testsuite name="Drupal\Tests\Component\PhpStorage\MTimeProtectedFastFileStorageTest" file="/home/chx/www/system/core/tests/Drupal/Tests/Component/PhpStorage/MTimeProtectedFastFileStorageTest.php" namespace="Drupal\Tests\Component\PhpStorage" fullPackage="Drupal.Tests.Component.PhpStorage" tests="0" assertions="0" failures="0" errors="0" time="0.000000"/>
<testsuite name="Drupal\Tests\Core\Cache\BackendChainImplementationUnitTest" file="/home/chx/www/system/core/tests/Drupal/Tests/Core/Cache/BackendChainImplementationUnitTest.php" namespace="Drupal\Tests\Core\Cache" fullPackage="Drupal.Tests.Core.Cache" tests="0" assertions="0" failures="0" errors="0" time="0.000000"/>
<testsuite name="Drupal\Tests\Core\Cache\NullBackendTest" file="/home/chx/www/system/core/tests/Drupal/Tests/Core/Cache/NullBackendTest.php" namespace="Drupal\Tests\Core\Cache" fullPackage="Drupal.Tests.Core.Cache" tests="0" assertions="0" failures="0" errors="0" time="0.000000"/>
<testsuite name="Drupal\Tests\Core\Extension\ModuleHandlerUnitTest" file="/home/chx/www/system/core/tests/Drupal/Tests/Core/Extension/ModuleHandlerUnitTest.php" namespace="Drupal\Tests\Core\Extension" fullPackage="Drupal.Tests.Core.Extension" tests="1" assertions="0" failures="0" errors="1" time="0.002680">
<testcase name="testloadInclude" class="Drupal\Tests\Core\Extension\ModuleHandlerUnitTest" file="/home/chx/www/system/core/tests/Drupal/Tests/Core/Extension/ModuleHandlerUnitTest.php" line="37" assertions="0" time="0.002680">
<error type="PHPUnit_Framework_Error_Notice">Drupal\Tests\Core\Extension\ModuleHandlerUnitTest::testloadInclude
Undefined index: foo
/home/chx/www/system/core/lib/Drupal/Core/Extension/ModuleHandler.php:219
/home/chx/www/system/core/tests/Drupal/Tests/Core/Extension/ModuleHandlerUnitTest.php:40
</error>
</testcase>
</testsuite>
<testsuite name="Drupal\Tests\Core\NestedArrayUnitTest" file="/home/chx/www/system/core/tests/Drupal/Tests/Core/NestedArrayUnitTest.php" namespace="Drupal\Tests\Core" fullPackage="Drupal.Tests.Core" tests="0" assertions="0" failures="0" errors="0" time="0.000000"/>
<testsuite name="Drupal\breakpoint\Tests\BreakpointMediaQueryTest" file="/home/chx/www/system/core/modules/breakpoint/tests/Drupal/breakpoint/Tests/BreakpointMediaQueryTest.php" namespace="Drupal\breakpoint\Tests" fullPackage="Drupal.breakpoint.Tests" tests="0" assertions="0" failures="0" errors="0" time="0.000000"/>
<testsuite name="Drupal\Tests\Core\Route\RoleAccessCheckTest" file="/var/www/d8/core/tests/Drupal/Tests/Core/Route/RoleAccessCheckTestkTest.php" namespace="Drupal\Tests\Core\Route" fullPackage="Drupal.Tests.Core.Route" tests="3" assertions="3" failures="3" errors="0" time="0.009176">
<testsuite name="Drupal\Tests\Core\Route\RoleAccessCheckTest::testRoleAccess" tests="3" assertions="3" failures="3" errors="0" time="0.009176">
<testcase name="testRoleAccess with data set #0" assertions="1" time="0.004519">
<failure type="PHPUnit_Framework_ExpectationFailedException">Drupal\Tests\Core\Route\RoleAccessCheckTest::testRoleAccess with data set #0 ('role_test_1', array(Drupal\user\Entity\User, Drupal\user\Entity\User))
Access granted for user with the roles role_test_1 on path: role_test_1
Failed asserting that false is true.
</failure>
</testcase>
<testcase name="testRoleAccess with data set #1" assertions="1" time="0.002354">
<failure type="PHPUnit_Framework_ExpectationFailedException">Drupal\Tests\Core\Route\RoleAccessCheckTest::testRoleAccess with data set #1 ('role_test_2', array(Drupal\user\Entity\User, Drupal\user\Entity\User))
Access granted for user with the roles role_test_2 on path: role_test_2
Failed asserting that false is true.
</failure>
</testcase>
<testcase name="testRoleAccess with data set #2" assertions="1" time="0.002303">
<failure type="PHPUnit_Framework_ExpectationFailedException">Drupal\Tests\Core\Route\RoleAccessCheckTest::testRoleAccess with data set #2 ('role_test_3', array(Drupal\user\Entity\User))
Access granted for user with the roles role_test_1, role_test_2 on path: role_test_3
Failed asserting that false is true.
</failure>
</testcase>
</testsuite>
</testsuite>
</testsuite>
</testsuites>

View file

@ -0,0 +1,4 @@
<select name="test">
<option value="1">One</option>
<option value="2" selected="selected">Two</option>
</select>

View file

@ -0,0 +1,4 @@
<select name="test">
<option value="1">One</option>
<option value="2">Two</option>
</select>

View file

@ -0,0 +1,28 @@
<?php
namespace Drupal\Tests\simpletest\Unit;
/**
* This test crashes PHP.
*
* To avoid accidentally running, it is not in a normal PSR-4 directory, the
* file name does not adhere to PSR-4 and an environment variable also needs to
* be set for the crash to happen.
*
* @see \Drupal\Tests\simpletest\Unit\SimpletestPhpunitRunCommandTest::testSimpletestPhpUnitRunCommand()
*/
class SimpletestPhpunitRunCommandTestWillDie extends \PHPUnit_Framework_TestCase {
/**
* Performs the status specified by SimpletestPhpunitRunCommandTestWillDie.
*/
public function testWillDie() {
$status = (int) getenv('SimpletestPhpunitRunCommandTestWillDie');
if ($status == 0) {
$this->assertTrue(TRUE, 'Assertion to ensure test pass');
return;
}
exit($status);
}
}

View file

@ -0,0 +1,6 @@
name: PHPUnit Test
type: module
description: 'Provides dummy classes for use by SimpleTest tests.'
package: Testing
version: VERSION
core: 8.x

View file

@ -0,0 +1,6 @@
<?php
namespace Drupal\phpunit_test;
class PhpUnitTestDummyClass {
}

View file

@ -0,0 +1,8 @@
name: 'Simpletest test'
type: module
description: 'Support module for Simpletest tests.'
package: Testing
version: VERSION
core: 8.x
dependencies:
- entity_test

View file

@ -0,0 +1,34 @@
<?php
/**
* @file
* Install hooks for test module.
*/
use Drupal\entity_test\Entity\EntityTest;
/**
* Implements hook_install().
*/
function simpletest_test_install() {
$total = 2;
$operations = array();
for ($i = 1; $i <= $total; $i++) {
$operations[] = array('_simpletest_test_callback', array($i));
}
$batch = array(
'operations' => $operations,
);
batch_set($batch);
$batch =& batch_get();
$batch['progressive'] = FALSE;
batch_process();
}
/**
* Callback for batch operations.
*/
function _simpletest_test_callback($id) {
$entity = EntityTest::create(array('id' => $id));
$entity->save();
}

View file

@ -0,0 +1,23 @@
<?php
namespace Drupal\Tests\simpletest\Functional;
use Drupal\Tests\BrowserTestBase;
/**
* Fixture test that is executed during Simpletest UI testing.
*
* @see \Drupal\simpletest\Tests::testTestingThroughUI()
*
* @group simpletest
*/
class ThroughUITest extends BrowserTestBase {
/**
* This test method must always pass.
*/
public function testThroughUi() {
$this->pass('Success!');
}
}

View file

@ -0,0 +1,65 @@
<?php
namespace Drupal\Tests\simpletest\FunctionalJavascript;
use Drupal\FunctionalJavascriptTests\JavascriptTestBase;
/**
* Tests if we can execute JavaScript in the browser.
*
* @group javascript
*/
class BrowserWithJavascriptTest extends JavascriptTestBase {
public function testJavascript() {
$this->drupalGet('<front>');
$session = $this->getSession();
$session->resizeWindow(400, 300);
$javascript = <<<JS
(function(){
var w = window,
d = document,
e = d.documentElement,
g = d.getElementsByTagName('body')[0],
x = w.innerWidth || e.clientWidth || g.clientWidth,
y = w.innerHeight || e.clientHeight|| g.clientHeight;
return x == 400 && y == 300;
}());
JS;
$this->assertJsCondition($javascript);
}
public function testAssertJsCondition() {
$this->drupalGet('<front>');
$session = $this->getSession();
$session->resizeWindow(500, 300);
$javascript = <<<JS
(function(){
var w = window,
d = document,
e = d.documentElement,
g = d.getElementsByTagName('body')[0],
x = w.innerWidth || e.clientWidth || g.clientWidth,
y = w.innerHeight || e.clientHeight|| g.clientHeight;
return x == 400 && y == 300;
}());
JS;
// We expected the following assertion to fail because the window has been
// re-sized to have a width of 500 not 400.
$this->setExpectedException(\PHPUnit_Framework_AssertionFailedError::class);
$this->assertJsCondition($javascript, 100);
}
/**
* Tests creating screenshots.
*/
public function testCreateScreenshot() {
$this->drupalGet('<front>');
$this->createScreenshot('public://screenshot.jpg');
$this->assertFileExists('public://screenshot.jpg');
}
}

View file

@ -0,0 +1,46 @@
<?php
namespace Drupal\Tests\simpletest\FunctionalJavascript;
use Drupal\FunctionalJavascriptTests\JavascriptTestBase;
/**
* Tests Drupal settings retrieval in JavascriptTestBase tests.
*
* @group javascript
*/
class JavascriptGetDrupalSettingsTest extends JavascriptTestBase {
/**
* {@inheritdoc}
*/
public static $modules = ['test_page_test'];
/**
* Tests retrieval of Drupal settings.
*
* @see \Drupal\FunctionalJavascriptTests\JavascriptTestBase::getDrupalSettings()
*/
public function testGetDrupalSettings() {
$this->drupalLogin($this->drupalCreateUser());
$this->drupalGet('test-page');
// Check that we can read the JS settings.
$js_settings = $this->getDrupalSettings();
$this->assertSame('azAZ09();.,\\\/-_{}', $js_settings['test-setting']);
// Dynamically change the setting using Javascript.
$script = <<<EndOfScript
(function () {
drupalSettings['test-setting'] = 'foo';
})();
EndOfScript;
$this->getSession()->evaluateScript($script);
// Check that the setting has been changed.
$js_settings = $this->getDrupalSettings();
$this->assertSame('foo', $js_settings['test-setting']);
}
}

View file

@ -0,0 +1,46 @@
<?php
namespace Drupal\Tests\simpletest\Kernel\Migrate\d6;
use Drupal\config\Tests\SchemaCheckTestTrait;
use Drupal\Tests\migrate_drupal\Kernel\d6\MigrateDrupal6TestBase;
/**
* Upgrade variables to simpletest.settings.yml.
*
* @group migrate_drupal_6
*/
class MigrateSimpletestConfigsTest extends MigrateDrupal6TestBase {
use SchemaCheckTestTrait;
/**
* {@inheritdoc}
*/
public static $modules = array('simpletest');
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->installConfig(['simpletest']);
$this->executeMigration('d6_simpletest_settings');
}
/**
* Tests migration of simpletest variables to simpletest.settings.yml.
*/
public function testSimpletestSettings() {
$config = $this->config('simpletest.settings');
$this->assertIdentical(TRUE, $config->get('clear_results'));
$this->assertIdentical(CURLAUTH_BASIC, $config->get('httpauth.method'));
// NULL in the dump means defaults which is empty string. Same as omitting
// them.
$this->assertIdentical('', $config->get('httpauth.password'));
$this->assertIdentical('', $config->get('httpauth.username'));
$this->assertIdentical(TRUE, $config->get('verbose'));
$this->assertConfigSchema(\Drupal::service('config.typed'), 'simpletest.settings', $config->get());
}
}

View file

@ -0,0 +1,37 @@
<?php
namespace Drupal\Tests\simpletest\Kernel\Migrate\d7;
use Drupal\Tests\migrate_drupal\Kernel\d7\MigrateDrupal7TestBase;
/**
* Tests migration of SimpleTest's variables to configuration.
*
* @group simpletest
*/
class MigrateSimpletestSettingsTest extends MigrateDrupal7TestBase {
public static $modules = ['simpletest'];
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->installConfig(static::$modules);
$this->executeMigration('d7_simpletest_settings');
}
/**
* Tests migration of SimpleTest settings to configuration.
*/
public function testMigration() {
$config = \Drupal::config('simpletest.settings')->get();
$this->assertTrue($config['clear_results']);
$this->assertIdentical(CURLAUTH_BASIC, $config['httpauth']['method']);
$this->assertIdentical('testbot', $config['httpauth']['username']);
$this->assertIdentical('foobaz', $config['httpauth']['password']);
$this->assertTrue($config['verbose']);
}
}

View file

@ -0,0 +1,54 @@
<?php
/**
* @file
* Contains \Drupal\Tests\simpletest\Unit\AssertContentTraitTest.
*/
namespace Drupal\Tests\simpletest\Unit;
use Drupal\simpletest\AssertContentTrait;
use Drupal\Tests\UnitTestCase;
/**
* @coversDefaultClass \Drupal\simpletest\AssertContentTrait
* @group simpletest
*/
class AssertContentTraitTest extends UnitTestCase {
/**
* @covers ::getTextContent
*/
public function testGetTextContent() {
$test = new TestClass();
$raw_content = <<<EOT
<Head>
<style>
@import url("foo.css");
</style>
</head>
<body>
bar
</body>
EOT;
$test->_setRawContent($raw_content);
$this->assertNotContains('foo', $test->_getTextContent());
$this->assertNotContains('<body>', $test->_getTextContent());
$this->assertContains('bar', $test->_getTextContent());
}
}
class TestClass {
use AssertContentTrait;
public function _setRawContent($content) {
$this->setRawContent($content);
}
public function _getTextContent() {
return $this->getTextContent();
}
}

View file

@ -0,0 +1,49 @@
<?php
/**
* @file
* Contains \Drupal\Tests\simpletest\Unit\AssertHelperTraitTest.
*/
namespace Drupal\Tests\simpletest\Unit;
use Drupal\Core\Render\Markup;
use Drupal\simpletest\AssertHelperTrait;
use Drupal\Tests\UnitTestCase;
/**
* @coversDefaultClass \Drupal\simpletest\AssertHelperTrait
* @group simpletest
*/
class AssertHelperTraitTest extends UnitTestCase {
/**
* @covers ::castSafeStrings
* @dataProvider providerCastSafeStrings
*/
public function testCastSafeStrings($expected, $value) {
$class = new AssertHelperTestClass();
$this->assertSame($expected, $class->testMethod($value));
}
public function providerCastSafeStrings() {
$safe_string = Markup::create('test safe string');
return [
['test simple string', 'test simple string'],
[['test simple array', 'test simple array'], ['test simple array', 'test simple array']],
['test safe string', $safe_string],
[['test safe string', 'test safe string'], [$safe_string, $safe_string]],
[['test safe string', 'mixed array', 'test safe string'], [$safe_string, 'mixed array', $safe_string]],
];
}
}
class AssertHelperTestClass {
use AssertHelperTrait;
public function testMethod($value) {
return $this->castSafeStrings($value);
}
}

View file

@ -0,0 +1,21 @@
<?php
namespace Drupal\Tests\simpletest\Unit;
use Drupal\Tests\UnitTestCase;
/**
* Tests that classes are correctly loaded during PHPUnit initialization.
*
* @group simpletest
*/
class PhpUnitAutoloaderTest extends UnitTestCase {
/**
* Test loading of classes provided by test sub modules.
*/
public function testPhpUnitTestClassesLoading() {
$this->assertTrue(class_exists('\Drupal\phpunit_test\PhpUnitTestDummyClass'), 'Class provided by test module was not autoloaded.');
}
}

View file

@ -0,0 +1,40 @@
<?php
namespace Drupal\Tests\simpletest\Unit;
use Drupal\Tests\UnitTestCase;
/**
* Tests PHPUnit errors are getting converted to Simpletest errors.
*
* @group simpletest
*/
class PhpUnitErrorTest extends UnitTestCase {
/**
* Test errors reported.
*
* @covers ::simpletest_phpunit_xml_to_rows
*/
public function testPhpUnitXmlParsing() {
require_once __DIR__ . '/../../../simpletest.module';
$phpunit_error_xml = __DIR__ . '/../../fixtures/phpunit_error.xml';
$res = simpletest_phpunit_xml_to_rows(1, $phpunit_error_xml);
$this->assertEquals(count($res), 4, 'All testcases got extracted');
$this->assertNotEquals($res[0]['status'], 'pass');
$this->assertEquals($res[0]['status'], 'fail');
// Test nested testsuites, which appear when you use @dataProvider.
for ($i = 0; $i < 3; $i++) {
$this->assertNotEquals($res[$i + 1]['status'], 'pass');
$this->assertEquals($res[$i + 1]['status'], 'fail');
}
// Make sure simpletest_phpunit_xml_to_rows() does not balk if the test
// didn't run.
simpletest_phpunit_xml_to_rows(1, 'foobar');
}
}

View file

@ -0,0 +1,102 @@
<?php
namespace Drupal\Tests\simpletest\Unit;
use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\File\FileSystemInterface;
/**
* Tests simpletest_run_phpunit_tests() handles PHPunit fatals correctly.
*
* @group simpletest
*
* @runTestsInSeparateProcesses
*/
class SimpletestPhpunitRunCommandTest extends \PHPUnit_Framework_TestCase {
/**
* Path to the app root.
*
* @var string
*/
protected static $root;
/**
* {@inheritdoc}
*/
public static function setUpBeforeClass() {
parent::setUpBeforeClass();
// Figure out our app root.
self::$root = dirname(dirname(dirname(dirname(dirname(dirname(__DIR__))))));
// Include the files we need for tests. The stub test we will run is
// SimpletestPhpunitRunCommandTestWillDie which is located in
// simpletest_phpunit_run_command_test.php.
include_once self::$root . '/core/modules/simpletest/tests/fixtures/simpletest_phpunit_run_command_test.php';
// Since we're testing simpletest_run_phpunit_tests(), we need to include
// simpletest.module.
include_once self::$root . '/core/modules/simpletest/simpletest.module';
}
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
// Organize our mock container.
$container = new ContainerBuilder();
$container->set('app.root', self::$root);
$file_system = $this->prophesize(FileSystemInterface::class);
// The simpletest directory wrapper will always point to /tmp.
$file_system->realpath('public://simpletest')->willReturn(sys_get_temp_dir());
$container->set('file_system', $file_system->reveal());
\Drupal::setContainer($container);
}
/**
* Data provider for testSimpletestPhpUnitRunCommand().
*
* @return array
* Arrays of status codes and the label they're expected to have.
*/
public function provideStatusCodes() {
$data = [
[0, 'pass'],
[1, 'fail'],
[2, 'exception'],
];
// All status codes 3 and above should be labeled 'error'.
// @todo: The valid values here would be 3 to 127. But since the test
// touches the file system a lot, we only have 3, 4, and 127 for speed.
foreach ([3, 4, 127] as $status) {
$data[] = [$status, 'error'];
}
return $data;
}
/**
* Test the round trip for PHPUnit execution status codes.
*
* @covers ::simpletest_run_phpunit_tests
*
* @dataProvider provideStatusCodes
*/
public function testSimpletestPhpUnitRunCommand($status, $label) {
$test_id = basename(tempnam(sys_get_temp_dir(), 'xxx'));
putenv('SimpletestPhpunitRunCommandTestWillDie=' . $status);
$ret = simpletest_run_phpunit_tests($test_id, [SimpletestPhpunitRunCommandTestWillDie::class]);
$this->assertSame($ret[0]['status'], $label);
putenv('SimpletestPhpunitRunCommandTestWillDie');
unlink(simpletest_phpunit_xml_filepath($test_id));
}
/**
* {@inheritdoc}
*/
protected function tearDown() {
// We unset the $base_url global, since the test code sets it as a
// side-effect.
unset($GLOBALS['base_url']);
parent::tearDown();
}
}

View file

@ -0,0 +1,469 @@
<?php
namespace Drupal\Tests\simpletest\Unit;
use Drupal\Tests\UnitTestCase;
/**
* @requires extension curl
* @coversDefaultClass \Drupal\simpletest\TestBase
* @group simpletest
*/
class TestBaseTest extends UnitTestCase {
/**
* Helper method for constructing a mock TestBase object.
*
* TestBase is abstract, so we have to mock it. We'll also
* mock the storeAssertion() method so we don't need the database.
*
* @param string $test_id
* An identifying name for the mocked test.
*
* @return object
* Mock of Drupal\simpletest\TestBase.
*/
public function getTestBaseForAssertionTests($test_id) {
$mock_test_base = $this->getMockBuilder('Drupal\simpletest\TestBase')
->setConstructorArgs(array($test_id))
->setMethods(array('storeAssertion'))
->getMockForAbstractClass();
// Override storeAssertion() so we don't need a database.
$mock_test_base->expects($this->any())
->method('storeAssertion')
->will($this->returnValue(NULL));
return $mock_test_base;
}
/**
* Invoke methods that are protected or private.
*
* @param object $object
* Object on which to invoke the method.
* @param string $method_name
* Name of the method to invoke.
* @param array $arguments
* Array of arguments to be passed to the method.
*
* @return mixed
* Value returned by the invoked method.
*/
public function invokeProtectedMethod($object, $method_name, array $arguments) {
$ref_method = new \ReflectionMethod($object, $method_name);
$ref_method->setAccessible(TRUE);
return $ref_method->invokeArgs($object, $arguments);
}
/**
* Provides data for the random string validation test.
*
* @return array
* - The expected result of the validation.
* - The string to validate.
*/
public function providerRandomStringValidate() {
return array(
array(FALSE, ' curry paste'),
array(FALSE, 'curry paste '),
array(FALSE, 'curry paste'),
array(FALSE, 'curry paste'),
array(TRUE, 'curry paste'),
array(TRUE, 'thai green curry paste'),
array(TRUE, '@startswithat'),
array(TRUE, 'contains@at'),
);
}
/**
* @covers ::randomStringValidate
* @dataProvider providerRandomStringValidate
*/
public function testRandomStringValidate($expected, $string) {
$mock_test_base = $this->getMockForAbstractClass('Drupal\simpletest\TestBase');
$actual = $mock_test_base->randomStringValidate($string);
$this->assertEquals($expected, $actual);
}
/**
* Provides data for testRandomString() and others.
*
* @return array
* - The number of items (characters, object properties) we expect any of
* the random functions to give us.
*/
public function providerRandomItems() {
return [
[NULL],
[0],
[1],
[2],
[3],
[4],
[7],
];
}
/**
* @covers ::randomString
* @dataProvider providerRandomItems
*/
public function testRandomString($length) {
$mock_test_base = $this->getMockForAbstractClass('Drupal\simpletest\TestBase');
$string = $mock_test_base->randomString($length);
$this->assertEquals($length, strlen($string));
// randomString() should always include an ampersand ('&') and a
// greater than ('>') if $length is greater than 3.
if ($length > 4) {
$this->assertContains('&', $string);
$this->assertContains('>', $string);
}
}
/**
* @covers ::randomObject
* @dataProvider providerRandomItems
*/
public function testRandomObject($size) {
$test_base = $this->getTestBaseForAssertionTests('test_id');
// Note: count((array)object) works for now, maybe not later.
$this->assertEquals($size, count((array) $test_base->randomObject($size)));
}
/**
* @covers ::checkRequirements
*/
public function testCheckRequirements() {
$test_base = $this->getTestBaseForAssertionTests('test_id');
$this->assertInternalType(
'array',
$this->invokeProtectedMethod($test_base, 'checkRequirements', array())
);
}
/**
* Data provider for testAssert().
*
* @return array
* Standard dataProvider array of arrays:
* - Expected result from assert().
* - Expected status stored in TestBase->assertions.
* - Status, passed to assert().
* - Message, passed to assert().
* - Group, passed to assert().
* - Caller, passed to assert().
*/
public function providerAssert() {
return array(
array(TRUE, 'pass', TRUE, 'Yay pass', 'test', array()),
array(FALSE, 'fail', FALSE, 'Boo fail', 'test', array()),
array(TRUE, 'pass', 'pass', 'Yay pass', 'test', array()),
array(FALSE, 'fail', 'fail', 'Boo fail', 'test', array()),
array(FALSE, 'exception', 'exception', 'Boo fail', 'test', array()),
array(FALSE, 'debug', 'debug', 'Boo fail', 'test', array()),
);
}
/**
* @covers ::assert
* @dataProvider providerAssert
*/
public function testAssert($expected, $assertion_status, $status, $message, $group, $caller) {
$test_id = 'luke_i_am_your_' . $assertion_status;
$test_base = $this->getTestBaseForAssertionTests($test_id);
// Verify some startup values.
$this->assertAttributeEmpty('assertions', $test_base);
if (is_string($status)) {
$this->assertEquals(0, $test_base->results['#' . $status]);
}
// assert() is protected so we have to make it accessible.
$ref_assert = new \ReflectionMethod($test_base, 'assert');
$ref_assert->setAccessible(TRUE);
// Call assert() from within our hall of mirrors.
$this->assertEquals(
$expected,
$ref_assert->invokeArgs($test_base,
array($status, $message, $group, $caller)
)
);
// Check the side-effects of assert().
if (is_string($status)) {
$this->assertEquals(1, $test_base->results['#' . $status]);
}
$this->assertAttributeNotEmpty('assertions', $test_base);
// Make a ReflectionProperty for the assertions property,
// since it's protected.
$ref_assertions = new \ReflectionProperty($test_base, 'assertions');
$ref_assertions->setAccessible(TRUE);
$assertions = $ref_assertions->getValue($test_base);
$assertion = reset($assertions);
$this->assertEquals($assertion_status, $assertion['status']);
$this->assertEquals($test_id, $assertion['test_id']);
$this->assertEquals(get_class($test_base), $assertion['test_class']);
$this->assertEquals($message, $assertion['message']);
$this->assertEquals($group, $assertion['message_group']);
}
/**
* Data provider for assertTrue().
*/
public function providerAssertTrue() {
return array(
array(TRUE, TRUE),
array(FALSE, FALSE),
);
}
/**
* @covers ::assertTrue
* @dataProvider providerAssertTrue
*/
public function testAssertTrue($expected, $value) {
$test_base = $this->getTestBaseForAssertionTests('test_id');
$this->assertEquals(
$expected,
$this->invokeProtectedMethod($test_base, 'assertTrue', array($value))
);
}
/**
* @covers ::assertFalse
* @dataProvider providerAssertTrue
*/
public function testAssertFalse($expected, $value) {
$test_base = $this->getTestBaseForAssertionTests('test_id');
$this->assertEquals(
(!$expected),
$this->invokeProtectedMethod($test_base, 'assertFalse', array($value))
);
}
/**
* Data provider for assertNull().
*/
public function providerAssertNull() {
return array(
array(TRUE, NULL),
array(FALSE, ''),
);
}
/**
* @covers ::assertNull
* @dataProvider providerAssertNull
*/
public function testAssertNull($expected, $value) {
$test_base = $this->getTestBaseForAssertionTests('test_id');
$this->assertEquals(
$expected,
$this->invokeProtectedMethod($test_base, 'assertNull', array($value))
);
}
/**
* @covers ::assertNotNull
* @dataProvider providerAssertNull
*/
public function testAssertNotNull($expected, $value) {
$test_base = $this->getTestBaseForAssertionTests('test_id');
$this->assertEquals(
(!$expected),
$this->invokeProtectedMethod($test_base, 'assertNotNull', array($value))
);
}
/**
* Data provider for tests of equality assertions.
*
* Used by testAssertIdentical(), testAssertEqual(), testAssertNotIdentical(),
* and testAssertNotEqual().
*
* @return
* Array of test data.
* - Expected assertion value for identical comparison.
* - Expected assertion value for equal comparison.
* - First value to compare.
* - Second value to compare.
*/
public function providerEqualityAssertions() {
return [
// Integers and floats.
[TRUE, TRUE, 0, 0],
[FALSE, TRUE, 0, 0.0],
[FALSE, TRUE, '0', 0],
[FALSE, TRUE, '0.0', 0.0],
[FALSE, FALSE, 23, 77],
[TRUE, TRUE, 23.0, 23.0],
// Strings.
[FALSE, FALSE, 'foof', 'yay'],
[TRUE, TRUE, 'yay', 'yay'],
// Bools with type conversion.
[TRUE, TRUE, TRUE, TRUE],
[TRUE, TRUE, FALSE, FALSE],
[FALSE, TRUE, NULL, FALSE],
[FALSE, TRUE, 'TRUE', TRUE],
[FALSE, FALSE, 'FALSE', FALSE],
[FALSE, TRUE, 0, FALSE],
[FALSE, TRUE, 1, TRUE],
[FALSE, TRUE, -1, TRUE],
[FALSE, TRUE, '1', TRUE],
[FALSE, TRUE, '1.3', TRUE],
// Null.
[FALSE, FALSE, 'NULL', NULL],
[TRUE, TRUE, NULL, NULL],
];
}
/**
* @covers ::assertIdentical
* @dataProvider providerEqualityAssertions
*/
public function testAssertIdentical($expected_identical, $expected_equal, $first, $second) {
$test_base = $this->getTestBaseForAssertionTests('test_id');
$this->assertEquals(
$expected_identical,
$this->invokeProtectedMethod($test_base, 'assertIdentical', array($first, $second))
);
}
/**
* @covers ::assertNotIdentical
* @dataProvider providerEqualityAssertions
*/
public function testAssertNotIdentical($expected_identical, $expected_equal, $first, $second) {
$test_base = $this->getTestBaseForAssertionTests('test_id');
$this->assertEquals(
(!$expected_identical),
$this->invokeProtectedMethod($test_base, 'assertNotIdentical', array($first, $second))
);
}
/**
* @covers ::assertEqual
* @dataProvider providerEqualityAssertions
*/
public function testAssertEqual($expected_identical, $expected_equal, $first, $second) {
$test_base = $this->getTestBaseForAssertionTests('test_id');
$this->assertEquals(
$expected_equal,
$this->invokeProtectedMethod($test_base, 'assertEqual', array($first, $second))
);
}
/**
* @covers ::assertNotEqual
* @dataProvider providerEqualityAssertions
*/
public function testAssertNotEqual($expected_identical, $expected_equal, $first, $second) {
$test_base = $this->getTestBaseForAssertionTests('test_id');
$this->assertEquals(
(!$expected_equal),
$this->invokeProtectedMethod($test_base, 'assertNotEqual', array($first, $second))
);
}
/**
* Data provider for testAssertIdenticalObject().
*/
public function providerAssertIdenticalObject() {
$obj1 = new \stdClass();
$obj1->foof = 'yay';
$obj2 = $obj1;
$obj3 = clone $obj1;
$obj4 = new \stdClass();
return array(
array(TRUE, $obj1, $obj2),
array(TRUE, $obj1, $obj3),
array(FALSE, $obj1, $obj4),
);
}
/**
* @covers ::assertIdenticalObject
* @dataProvider providerAssertIdenticalObject
*/
public function testAssertIdenticalObject($expected, $first, $second) {
$test_base = $this->getTestBaseForAssertionTests('test_id');
$this->assertEquals(
$expected,
$this->invokeProtectedMethod($test_base, 'assertIdenticalObject', array($first, $second))
);
}
/**
* @covers ::pass
*/
public function testPass() {
$test_base = $this->getTestBaseForAssertionTests('test_id');
$this->assertEquals(
TRUE,
$this->invokeProtectedMethod($test_base, 'pass', array())
);
}
/**
* @covers ::fail
*/
public function testFail() {
$test_base = $this->getTestBaseForAssertionTests('test_id');
$this->assertEquals(
FALSE,
$this->invokeProtectedMethod($test_base, 'fail', array())
);
}
/**
* Data provider for testError().
*
* @return array
* - Expected status for assertion.
* - Group for use in assert().
*/
public function providerError() {
return array(
array('debug', 'User notice'),
array('exception', 'Not User notice'),
);
}
/**
* @covers ::error
* @dataProvider providerError
*/
public function testError($status, $group) {
// Mock up a TestBase object.
$mock_test_base = $this->getMockBuilder('Drupal\simpletest\TestBase')
->setMethods(array('assert'))
->getMockForAbstractClass();
// Set expectations for assert().
$mock_test_base->expects($this->once())
->method('assert')
// The first argument to assert() should be the expected $status. This is
// the most important expectation of this test.
->with($status)
// Arbitrary return value.
->willReturn("$status:$group");
// Invoke error().
$this->assertEquals(
"$status:$group",
$this->invokeProtectedMethod($mock_test_base, 'error', array('msg', $group))
);
}
/**
* @covers ::getRandomGenerator
*/
public function testGetRandomGenerator() {
$test_base = $this->getTestBaseForAssertionTests('test_id');
$this->assertInstanceOf(
'Drupal\Component\Utility\Random',
$this->invokeProtectedMethod($test_base, 'getRandomGenerator', array())
);
}
}

View file

@ -0,0 +1,426 @@
<?php
/**
* @file
* Contains \Drupal\Tests\simpletest\Unit\TestInfoParsingTest.
*/
namespace Drupal\Tests\simpletest\Unit;
use Composer\Autoload\ClassLoader;
use Drupal\Core\Extension\Extension;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\simpletest\TestDiscovery;
use Drupal\Tests\UnitTestCase;
use org\bovigo\vfs\vfsStream;
/**
* @coversDefaultClass \Drupal\simpletest\TestDiscovery
* @group simpletest
*/
class TestInfoParsingTest extends UnitTestCase {
/**
* @covers ::getTestInfo
* @dataProvider infoParserProvider
*/
public function testTestInfoParser($expected, $classname, $doc_comment = NULL) {
$info = TestDiscovery::getTestInfo($classname, $doc_comment);
$this->assertEquals($expected, $info);
}
public function infoParserProvider() {
// A module provided unit test.
$tests[] = [
// Expected result.
[
'name' => 'Drupal\Tests\simpletest\Unit\TestInfoParsingTest',
'group' => 'simpletest',
'description' => 'Tests \Drupal\simpletest\TestDiscovery.',
'type' => 'PHPUnit-Unit',
],
// Classname.
'Drupal\Tests\simpletest\Unit\TestInfoParsingTest',
];
// A core unit test.
$tests[] = [
// Expected result.
[
'name' => 'Drupal\Tests\Core\DrupalTest',
'group' => 'DrupalTest',
'description' => 'Tests \Drupal.',
'type' => 'PHPUnit-Unit',
],
// Classname.
'Drupal\Tests\Core\DrupalTest',
];
// Functional PHPUnit test.
$tests[] = [
// Expected result.
[
'name' => 'Drupal\FunctionalTests\BrowserTestBaseTest',
'group' => 'browsertestbase',
'description' => 'Tests BrowserTestBase functionality.',
'type' => 'PHPUnit-Functional',
],
// Classname.
'Drupal\FunctionalTests\BrowserTestBaseTest',
];
// kernel PHPUnit test.
$tests['phpunit-kernel'] = [
// Expected result.
[
'name' => '\Drupal\Tests\file\Kernel\FileItemValidationTest',
'group' => 'file',
'description' => 'Tests that files referenced in file and image fields are always validated.',
'type' => 'PHPUnit-Kernel',
],
// Classname.
'\Drupal\Tests\file\Kernel\FileItemValidationTest',
];
// Simpletest classes can not be autoloaded in a PHPUnit test, therefore
// provide a docblock.
$tests[] = [
// Expected result.
[
'name' => 'Drupal\simpletest\Tests\ExampleSimpleTest',
'group' => 'simpletest',
'description' => 'Tests the Simpletest UI internal browser.',
'type' => 'Simpletest',
],
// Classname.
'Drupal\simpletest\Tests\ExampleSimpleTest',
// Doc block.
"/**
* Tests the Simpletest UI internal browser.
*
* @group simpletest
*/
",
];
// Test with a different amount of leading spaces.
$tests[] = [
// Expected result.
[
'name' => 'Drupal\simpletest\Tests\ExampleSimpleTest',
'group' => 'simpletest',
'description' => 'Tests the Simpletest UI internal browser.',
'type' => 'Simpletest',
],
// Classname.
'Drupal\simpletest\Tests\ExampleSimpleTest',
// Doc block.
"/**
* Tests the Simpletest UI internal browser.
*
* @group simpletest
*/
*/
",
];
// Make sure that a "* @" inside a string does not get parsed as an
// annotation.
$tests[] = [
// Expected result.
[
'name' => 'Drupal\simpletest\Tests\ExampleSimpleTest',
'group' => 'simpletest',
'description' => 'Tests the Simpletest UI internal browser. * @',
'type' => 'Simpletest',
],
// Classname.
'Drupal\simpletest\Tests\ExampleSimpleTest',
// Doc block.
"/**
* Tests the Simpletest UI internal browser. * @
*
* @group simpletest
*/
",
];
// Multiple @group annotations.
$tests[] = [
// Expected result.
[
'name' => 'Drupal\simpletest\Tests\ExampleSimpleTest',
'group' => 'Test',
'description' => 'Tests the Simpletest UI internal browser.',
'type' => 'Simpletest',
],
// Classname.
'Drupal\simpletest\Tests\ExampleSimpleTest',
// Doc block.
"/**
* Tests the Simpletest UI internal browser.
*
* @group Test
* @group simpletest
*/
",
];
// @dependencies annotation.
$tests[] = [
// Expected result.
[
'name' => 'Drupal\simpletest\Tests\ExampleSimpleTest',
'description' => 'Tests the Simpletest UI internal browser.',
'type' => 'Simpletest',
'requires' => ['module' => ['test']],
'group' => 'simpletest',
],
// Classname.
'Drupal\simpletest\Tests\ExampleSimpleTest',
// Doc block.
"/**
* Tests the Simpletest UI internal browser.
*
* @dependencies test
* @group simpletest
*/
",
];
// Multiple @dependencies annotation.
$tests[] = [
// Expected result.
[
'name' => 'Drupal\simpletest\Tests\ExampleSimpleTest',
'description' => 'Tests the Simpletest UI internal browser.',
'type' => 'Simpletest',
'requires' => ['module' => ['test', 'test1', 'test2']],
'group' => 'simpletest',
],
// Classname.
'Drupal\simpletest\Tests\ExampleSimpleTest',
// Doc block.
"/**
* Tests the Simpletest UI internal browser.
*
* @dependencies test, test1, test2
* @group simpletest
*/
",
];
// Multi-line summary line.
$tests[] = [
// Expected result.
[
'name' => 'Drupal\simpletest\Tests\ExampleSimpleTest',
'description' => 'Tests the Simpletest UI internal browser. And the summary line continues an there is no gap to the annotation.',
'type' => 'Simpletest',
'group' => 'simpletest',
],
// Classname.
'Drupal\simpletest\Tests\ExampleSimpleTest',
// Doc block.
"/**
* Tests the Simpletest UI internal browser. And the summary line continues an
* there is no gap to the annotation.
*
* @group simpletest
*/
",
];
return $tests;
}
/**
* @covers ::getTestInfo
* @expectedException \Drupal\simpletest\Exception\MissingGroupException
* @expectedExceptionMessage Missing @group annotation in Drupal\KernelTests\field\BulkDeleteTest
*/
public function testTestInfoParserMissingGroup() {
$classname = 'Drupal\KernelTests\field\BulkDeleteTest';
$doc_comment = <<<EOT
/**
* Bulk delete storages and fields, and clean up afterwards.
*/
EOT;
TestDiscovery::getTestInfo($classname, $doc_comment);
}
/**
* @covers ::getTestInfo
*/
public function testTestInfoParserMissingSummary() {
$classname = 'Drupal\KernelTests\field\BulkDeleteTest';
$doc_comment = <<<EOT
/**
* @group field
*/
EOT;
$info = TestDiscovery::getTestInfo($classname, $doc_comment);
$this->assertEmpty($info['description']);
}
protected function setupVfsWithTestClasses() {
vfsStream::setup('drupal');
$test_file = <<<EOF
<?php
/**
* Test description
* @group example
*/
class FunctionalExampleTest {}
EOF;
vfsStream::create([
'modules' => [
'test_module' => [
'tests' => [
'src' => [
'Functional' => [
'FunctionalExampleTest.php' => $test_file,
'FunctionalExampleTest2.php' => str_replace(['FunctionalExampleTest', '@group example'], ['FunctionalExampleTest2', '@group example2'], $test_file),
],
'Kernel' => [
'KernelExampleTest3.php' => str_replace(['FunctionalExampleTest', '@group example'], ['KernelExampleTest3', '@group example2'], $test_file),
],
],
],
],
],
]);
}
/**
* @covers ::getTestClasses
*/
public function testGetTestClasses() {
$this->setupVfsWithTestClasses();
$class_loader = $this->prophesize(ClassLoader::class);
$module_handler = $this->prophesize(ModuleHandlerInterface::class);
$test_discovery = new TestTestDiscovery('vfs://drupal', $class_loader->reveal(), $module_handler->reveal());
$extensions = [
'test_module' => new Extension('vfs://drupal', 'module', 'modules/test_module/test_module.info.yml'),
];
$test_discovery->setExtensions($extensions);
$result = $test_discovery->getTestClasses();
$this->assertCount(2, $result);
$this->assertEquals([
'example' => [
'Drupal\Tests\test_module\Functional\FunctionalExampleTest' => [
'name' => 'Drupal\Tests\test_module\Functional\FunctionalExampleTest',
'description' => 'Test description',
'group' => 'example',
'type' => 'PHPUnit-Functional',
],
],
'example2' => [
'Drupal\Tests\test_module\Functional\FunctionalExampleTest2' => [
'name' => 'Drupal\Tests\test_module\Functional\FunctionalExampleTest2',
'description' => 'Test description',
'group' => 'example2',
'type' => 'PHPUnit-Functional',
],
'Drupal\Tests\test_module\Kernel\KernelExampleTest3' => [
'name' => 'Drupal\Tests\test_module\Kernel\KernelExampleTest3',
'description' => 'Test description',
'group' => 'example2',
'type' => 'PHPUnit-Kernel',
],
],
], $result);
}
/**
* @covers ::getTestClasses
*/
public function testGetTestClassesWithSelectedTypes() {
$this->setupVfsWithTestClasses();
$class_loader = $this->prophesize(ClassLoader::class);
$module_handler = $this->prophesize(ModuleHandlerInterface::class);
$test_discovery = new TestTestDiscovery('vfs://drupal', $class_loader->reveal(), $module_handler->reveal());
$extensions = [
'test_module' => new Extension('vfs://drupal', 'module', 'modules/test_module/test_module.info.yml'),
];
$test_discovery->setExtensions($extensions);
$result = $test_discovery->getTestClasses(NULL, ['PHPUnit-Kernel']);
$this->assertCount(2, $result);
$this->assertEquals([
'example' => [
],
'example2' => [
'Drupal\Tests\test_module\Kernel\KernelExampleTest3' => [
'name' => 'Drupal\Tests\test_module\Kernel\KernelExampleTest3',
'description' => 'Test description',
'group' => 'example2',
'type' => 'PHPUnit-Kernel',
],
],
], $result);
}
}
class TestTestDiscovery extends TestDiscovery {
/**
* @var \Drupal\Core\Extension\Extension[]
*/
protected $extensions = [];
public function setExtensions(array $extensions) {
$this->extensions = $extensions;
}
/**
* {@inheritdoc}
*/
protected function getExtensions() {
return $this->extensions;
}
/**
* @covers ::getPhpunitTestSuite
* @dataProvider providerTestGetPhpunitTestSuite
*/
public function testGetPhpunitTestSuite($classname, $expected) {
$this->assertEquals($expected, TestDiscovery::getPhpunitTestSuite($classname));
}
public function providerTestGetPhpunitTestSuite() {
$data = [];
$data['simpletest-webtest'] = ['\Drupal\rest\Tests\NodeTest', FALSE];
$data['simpletest-kerneltest'] = ['\Drupal\hal\Tests\FileNormalizeTest', FALSE];
$data['module-unittest'] = [static::class, 'Unit'];
$data['module-kerneltest'] = ['\Drupal\KernelTests\Core\Theme\TwigMarkupInterfaceTest', 'Kernel'];
$data['module-functionaltest'] = ['\Drupal\FunctionalTests\BrowserTestBaseTest', 'Functional'];
$data['module-functionaljavascripttest'] = ['\Drupal\Tests\toolbar\FunctionalJavascript\ToolbarIntegrationTest', 'FunctionalJavascript'];
$data['core-unittest'] = ['\Drupal\Tests\ComposerIntegrationTest', 'Unit'];
$data['core-unittest2'] = ['Drupal\Tests\Core\DrupalTest', 'Unit'];
$data['core-kerneltest'] = ['\Drupal\KernelTests\KernelTestBaseTest', 'Kernel'];
$data['core-functionaltest'] = ['\Drupal\FunctionalTests\ExampleTest', 'Functional'];
$data['core-functionaljavascripttest'] = ['\Drupal\FunctionalJavascriptTests\ExampleTest', 'FunctionalJavascript'];
return $data;
}
}
namespace Drupal\simpletest\Tests;
use Drupal\simpletest\WebTestBase;
/**
* Tests the Simpletest UI internal browser.
*
* @group simpletest
*/
class ExampleSimpleTest extends WebTestBase {
}

View file

@ -0,0 +1,235 @@
<?php
namespace Drupal\Tests\simpletest\Unit;
use Drupal\Tests\UnitTestCase;
/**
* @requires extension curl
* @coversDefaultClass \Drupal\simpletest\WebTestBase
* @group simpletest
*/
class WebTestBaseTest extends UnitTestCase {
/**
* Provides data for testing the assertFieldByName() helper.
*
* @return array
* An array of values passed to the test method.
*/
public function providerAssertFieldByName() {
$data = array();
$data[] = array('select_2nd_selected', 'test', '1', FALSE);
$data[] = array('select_2nd_selected', 'test', '2', TRUE);
$data[] = array('select_none_selected', 'test', '', FALSE);
$data[] = array('select_none_selected', 'test', '1', TRUE);
$data[] = array('select_none_selected', 'test', NULL, TRUE);
return $data;
}
/**
* Tests the assertFieldByName() helper.
*
* @param string $filename
* Name of file containing the output to test.
* @param string $name
* Name of field to assert.
* @param string $value
* Value of the field to assert.
* @param bool $expected
* The expected result of the assert.
*
* @see \Drupal\simpletest\WebTestBase::assertFieldByName()
*
* @dataProvider providerAssertFieldByName
* @covers ::assertFieldByName
*/
public function testAssertFieldByName($filename, $name, $value, $expected) {
$content = file_get_contents(__DIR__ . '/../../fixtures/' . $filename . '.html');
$web_test = $this->getMockBuilder('Drupal\simpletest\WebTestBase')
->disableOriginalConstructor()
->setMethods(array('getRawContent', 'assertTrue', 'pass'))
->getMock();
$web_test->expects($this->any())
->method('getRawContent')
->will($this->returnValue($content));
$web_test->expects($this->once())
->method('assertTrue')
->with($this->identicalTo($expected),
$this->identicalTo('message'),
$this->identicalTo('Browser'));
$test_method = new \ReflectionMethod('Drupal\simpletest\WebTestBase', 'assertFieldByName');
$test_method->setAccessible(TRUE);
$test_method->invokeArgs($web_test, array($name, $value, 'message'));
}
/**
* Data provider for testClickLink().
*
* In the test method, we mock drupalGet() to return a known string:
* 'This Text Returned By drupalGet()'. Since clickLink() can only return
* either the value of drupalGet() or FALSE, our expected return value is the
* same as this mocked return value when we expect a link to be found.
*
* @see https://www.drupal.org/node/1452896
*
* @return array
* Array of arrays of test data. Test data is structured as follows:
* - Expected return value of clickLink().
* - Parameter $label to clickLink().
* - Parameter $index to clickLink().
* - Test data to be returned by mocked xpath(). Return an empty array here
* to mock no link found on the page.
*/
public function providerTestClickLink() {
return array(
// Test for a non-existent label.
array(
FALSE,
'does_not_exist',
0,
array(),
),
// Test for an existing label.
array(
'This Text Returned By drupalGet()',
'exists',
0,
array(0 => array('href' => 'this_is_a_url')),
),
// Test for an existing label that isn't the first one.
array(
'This Text Returned By drupalGet()',
'exists',
1,
array(
0 => array('href' => 'this_is_a_url'),
1 => array('href' => 'this_is_another_url'),
),
),
);
}
/**
* Test WebTestBase::clickLink().
*
* @param mixed $expected
* Expected return value of clickLink().
* @param string $label
* Parameter $label to clickLink().
* @param int $index
* Parameter $index to clickLink().
* @param array $xpath_data
* Test data to be returned by mocked xpath().
*
* @dataProvider providerTestClickLink
* @covers ::clickLink
*/
public function testClickLink($expected, $label, $index, $xpath_data) {
// Mock a WebTestBase object and some of its methods.
$web_test = $this->getMockBuilder('Drupal\simpletest\WebTestBase')
->disableOriginalConstructor()
->setMethods(array(
'pass',
'fail',
'getUrl',
'xpath',
'drupalGet',
'getAbsoluteUrl',
))
->getMock();
// Mocked getUrl() is only used for reporting so we just return a string.
$web_test->expects($this->any())
->method('getUrl')
->will($this->returnValue('url_before'));
// Mocked xpath() should return our test data.
$web_test->expects($this->any())
->method('xpath')
->will($this->returnValue($xpath_data));
if ($expected === FALSE) {
// If link does not exist clickLink() will not try to do a drupalGet() or
// a getAbsoluteUrl()
$web_test->expects($this->never())
->method('drupalGet');
$web_test->expects($this->never())
->method('getAbsoluteUrl');
// The test should fail and not pass.
$web_test->expects($this->never())
->method('pass');
$web_test->expects($this->once())
->method('fail')
->will($this->returnValue(NULL));
}
else {
// Mocked getAbsoluteUrl() should return whatever comes in.
$web_test->expects($this->once())
->method('getAbsoluteUrl')
->with($xpath_data[$index]['href'])
->will($this->returnArgument(0));
// We're only testing clickLink(), so drupalGet() always returns a string.
$web_test->expects($this->once())
->method('drupalGet')
->with($xpath_data[$index]['href'])
->will($this->returnValue('This Text Returned By drupalGet()'));
// The test should pass and not fail.
$web_test->expects($this->never())
->method('fail');
$web_test->expects($this->once())
->method('pass')
->will($this->returnValue(NULL));
}
// Set the clickLink() method to public so we can test it.
$clicklink_method = new \ReflectionMethod($web_test, 'clickLink');
$clicklink_method->setAccessible(TRUE);
$this->assertSame($expected, $clicklink_method->invoke($web_test, $label, $index));
}
/**
* @dataProvider providerTestGetAbsoluteUrl
*/
public function testGetAbsoluteUrl($href, $expected_absolute_path) {
$web_test = $this->getMockBuilder('Drupal\simpletest\WebTestBase')
->disableOriginalConstructor()
->setMethods(['getUrl'])
->getMock();
$web_test->expects($this->any())
->method('getUrl')
->willReturn('http://example.com/drupal/current-path?foo=baz');
$GLOBALS['base_url'] = 'http://example.com';
$GLOBALS['base_path'] = 'drupal';
$get_absolute_url_method = new \ReflectionMethod($web_test, 'getAbsoluteUrl');
$get_absolute_url_method->setAccessible(TRUE);
$this->assertSame($expected_absolute_path, $get_absolute_url_method->invoke($web_test, $href));
unset($GLOBALS['base_url'], $GLOBALS['base_path']);
}
/**
* Provides test data for testGetAbsoluteUrl.
*
* @return array
*/
public function providerTestGetAbsoluteUrl() {
$data = [];
$data['host'] = ['http://example.com/drupal/test-example', 'http://example.com/drupal/test-example'];
$data['path'] = ['/drupal/test-example', 'http://example.com/drupal/test-example'];
$data['path-with-query'] = ['/drupal/test-example?foo=bar', 'http://example.com/drupal/test-example?foo=bar'];
$data['just-query'] = ['?foo=bar', 'http://example.com/drupal/current-path?foo=bar'];
return $data;
}
}