View source
<?php
namespace Drupal\Tests\Component\Plugin\Context;
use Drupal\Component\Plugin\Context\Context;
use PHPUnit\Framework\TestCase;
class ContextTest extends TestCase {
public function providerGetContextValue() {
return [
[
'context_value',
'context_value',
FALSE,
'data_type',
],
[
NULL,
NULL,
FALSE,
'data_type',
],
[
'will throw exception',
NULL,
TRUE,
'data_type',
],
];
}
public function testGetContextValue($expected, $context_value, $is_required, $data_type) {
$mock_context = $this
->getMockBuilder('Drupal\\Component\\Plugin\\Context\\Context')
->disableOriginalConstructor()
->onlyMethods([
'getContextDefinition',
])
->getMock();
if ($context_value) {
$ref_context_value = new \ReflectionProperty($mock_context, 'contextValue');
$ref_context_value
->setAccessible(TRUE);
$ref_context_value
->setValue($mock_context, $context_value);
$this
->assertEquals($context_value, $mock_context
->getContextValue());
}
else {
$mock_definition = $this
->getMockBuilder('Drupal\\Component\\Plugin\\Context\\ContextDefinitionInterface')
->onlyMethods([
'isRequired',
'getDataType',
])
->getMockForAbstractClass();
$mock_definition
->expects($this
->once())
->method('isRequired')
->willReturn($is_required);
$mock_definition
->expects($this
->exactly($is_required ? 1 : 0))
->method('getDataType')
->willReturn($data_type);
$mock_context
->expects($this
->once())
->method('getContextDefinition')
->willReturn($mock_definition);
if ($is_required) {
$this
->expectException('Drupal\\Component\\Plugin\\Exception\\ContextException');
$this
->expectExceptionMessage(sprintf("The %s context is required and not present.", $data_type));
}
$this
->assertEquals($context_value, $mock_context
->getContextValue());
}
}
public function providerHasContextValue() {
return [
[
TRUE,
FALSE,
],
[
TRUE,
0,
],
[
TRUE,
-0,
],
[
TRUE,
0.0,
],
[
TRUE,
-0.0,
],
[
TRUE,
'',
],
[
TRUE,
'0',
],
[
TRUE,
[],
],
[
FALSE,
NULL,
],
];
}
public function testHasContextValue($has_context_value, $default_value) : void {
$mock_definition = $this
->getMockBuilder('Drupal\\Component\\Plugin\\Context\\ContextDefinitionInterface')
->onlyMethods([
'getDefaultValue',
])
->getMockForAbstractClass();
$mock_definition
->expects($this
->atLeastOnce())
->method('getDefaultValue')
->willReturn($default_value);
$context = new Context($mock_definition);
$this
->assertSame($has_context_value, $context
->hasContextValue());
$this
->assertSame($default_value, $context
->getContextValue());
}
public function testDefaultValue() {
$mock_definition = $this
->getMockBuilder('Drupal\\Component\\Plugin\\Context\\ContextDefinitionInterface')
->onlyMethods([
'getDefaultValue',
])
->getMockForAbstractClass();
$mock_definition
->expects($this
->once())
->method('getDefaultValue')
->willReturn('test');
$context = new Context($mock_definition);
$this
->assertEquals('test', $context
->getContextValue());
}
}