clean install

This commit is contained in:
matze committed 2024-12-10 15:08:16 +01:00
commit e14eb2d8fd
31193 files changed
+3555714

No files matched your search

@@ -0,0 +1,391 @@
<?php
namespace Drupal\Tests\fraction\Functional;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\Tests\BrowserTestBase;
use Drupal\Core\StringTranslation\StringTranslationTrait;
/**
* Tests the creation of fraction fields.
*
* @group Fraction
*/
class FractionFieldTest extends BrowserTestBase {
use StringTranslationTrait;
/**
* Modules to enable.
*
* @var array
*/
protected static $modules = ['node', 'entity_test', 'field_ui', 'fraction'];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->drupalLogin($this->drupalCreateUser([
'view test entity',
'administer entity_test content',
'administer content types',
'administer node fields',
'administer node display',
'administer node form display',
'bypass node access',
'administer entity_test fields',
'access administration pages',
]));
}
/**
* Test decimal widget field.
*/
public function testFractionWidgetDecimal() {
$max = 100;
$min = 10;
// Create a field with settings to validate.
$field_name = mb_strtolower($this->randomMachineName());
FieldStorageConfig::create([
'field_name' => $field_name,
'entity_type' => 'entity_test',
'type' => 'fraction',
])->save();
FieldConfig::create([
'field_name' => $field_name,
'entity_type' => 'entity_test',
'bundle' => 'entity_test',
'settings' =>
[
'max' => $max,
'min' => $min,
],
])->save();
/** @var \Drupal\Core\Entity\EntityDisplayRepositoryInterface $display_repository */
$display_repository = \Drupal::service('entity_display.repository');
$display_repository->getFormDisplay('entity_test', 'entity_test')
->setComponent($field_name, ['type' => 'fraction_decimal'])
->save();
$display_repository->getViewDisplay('entity_test', 'entity_test')
->setComponent($field_name, ['type' => 'fraction_decimal'])
->save();
// Display creation form.
$this->drupalGet('entity_test/add');
$this->assertSession()->fieldValueEquals("{$field_name}[0][decimal]", '');
// Submit decimal value.
$value = '14.5678';
$edit = [
"{$field_name}[0][decimal]" => $value,
];
$this->submitForm($edit, $this->t('Save'));
preg_match('|entity_test/manage/(\d+)|', $this->getUrl(), $match);
$id = $match[1];
$this->assertSession()->pageTextContains($this->t('entity_test @id has been created.', ['@id' => $id]));
$this->assertSession()->responseContains($value);
// Try to create entries with more than one decimal separator; assert fail.
$wrong_entries = [
'3.14.159',
'0..45469',
'..4589',
'6.459.52',
'6.3..25',
];
foreach ($wrong_entries as $wrong_entry) {
$this->drupalGet('entity_test/add');
$edit = [
"{$field_name}[0][decimal]" => $wrong_entry,
];
$this->submitForm($edit, $this->t('Save'));
$this->assertSession()->responseContains($this->t('%name must be a number.', ['%name' => $field_name]));
}
// Try to create entries with minus sign not in the first position.
$wrong_entries = [
'3-3',
'4-',
'1.3-',
'1.2-4',
'-10-10',
];
foreach ($wrong_entries as $wrong_entry) {
$this->drupalGet('entity_test/add');
$edit = [
"{$field_name}[0][decimal]" => $wrong_entry,
];
$this->submitForm($edit, $this->t('Save'));
$this->assertSession()->responseContains($this->t('%name must be a number.', ['%name' => $field_name]));
}
// Try to set a value above the maximum value.
$this->drupalGet('entity_test/add');
$edit = [
"{$field_name}[0][decimal]" => $max + 0.123,
];
$this->submitForm($edit, $this->t('Save'));
$this->assertSession()->responseContains($this->t('%name: the value may be no greater than %maximum.', ['%name' => $field_name, '%maximum' => $max]));
// Try to set a value below the minimum value.
$this->drupalGet('entity_test/add');
$edit = [
"{$field_name}[0][decimal]" => $min - 0.123,
];
$this->submitForm($edit, $this->t('Save'));
$this->assertSession()->responseContains($this->t('%name: the value may be no less than %minimum.', ['%name' => $field_name, '%minimum' => $min]));
// Test the fraction decimal element limits.
$this->drupalGet('entity_test/add');
$edit = [
"{$field_name}[0][decimal]" => 10.1234567891,
];
$this->submitForm($edit, $this->t('Save'));
$this->assertSession()->responseContains($this->t('The maximum number of digits after the decimal place is 9.'));
}
/**
* Test decimal widget field with negative values.
*/
public function testFractionWidgetDecimalNegative() {
// Create the test field.
$field_name = mb_strtolower($this->randomMachineName());
FieldStorageConfig::create([
'field_name' => $field_name,
'entity_type' => 'entity_test',
'type' => 'fraction',
])->save();
FieldConfig::create([
'field_name' => $field_name,
'entity_type' => 'entity_test',
'bundle' => 'entity_test',
])->save();
/** @var \Drupal\Core\Entity\EntityDisplayRepositoryInterface $display_repository */
$display_repository = \Drupal::service('entity_display.repository');
$display_repository->getFormDisplay('entity_test', 'entity_test')
->setComponent($field_name, ['type' => 'fraction_decimal'])
->save();
$display_repository->getViewDisplay('entity_test', 'entity_test')
->setComponent($field_name, ['type' => 'fraction_decimal'])
->save();
// Display creation form.
$this->drupalGet('entity_test/add');
$this->assertSession()->fieldValueEquals("{$field_name}[0][decimal]", '');
// Submit negative decimal value.
$value = '-14.5678';
$edit = [
"{$field_name}[0][decimal]" => $value,
];
$this->submitForm($edit, $this->t('Save'));
preg_match('|entity_test/manage/(\d+)|', $this->getUrl(), $match);
$id = $match[1];
$this->assertSession()->pageTextContains($this->t('entity_test @id has been created.', ['@id' => $id]));
$this->assertSession()->responseContains($value);
}
/**
* Test decimal widget field.
*/
public function testFractionWidgetFraction() {
$max = 100;
$min = 10;
// Create a field with settings to validate.
$field_name = mb_strtolower($this->randomMachineName());
FieldStorageConfig::create([
'field_name' => $field_name,
'entity_type' => 'entity_test',
'type' => 'fraction',
])->save();
FieldConfig::create([
'field_name' => $field_name,
'entity_type' => 'entity_test',
'bundle' => 'entity_test',
'settings' =>
[
'max' => $max,
'min' => $min,
],
])->save();
/** @var \Drupal\Core\Entity\EntityDisplayRepositoryInterface $display_repository */
$display_repository = \Drupal::service('entity_display.repository');
$display_repository->getFormDisplay('entity_test', 'entity_test')
->setComponent($field_name, ['type' => 'fraction'])
->save();
$display_repository->getViewDisplay('entity_test', 'entity_test')
->setComponent($field_name, ['type' => 'fraction'])
->save();
// Display creation form.
$this->drupalGet('entity_test/add');
$this->assertSession()->fieldValueEquals("{$field_name}[0][fraction][numerator]", '');
$this->assertSession()->fieldValueEquals("{$field_name}[0][fraction][denominator]", '');
// Submit fraction value.
$edit = [
"{$field_name}[0][fraction][numerator]" => 150,
"{$field_name}[0][fraction][denominator]" => 10,
];
$this->submitForm($edit, $this->t('Save'));
preg_match('|entity_test/manage/(\d+)|', $this->getUrl(), $match);
$id = $match[1];
$this->assertSession()->pageTextContains($this->t('entity_test @id has been created.', ['@id' => $id]));
$this->assertSession()->responseContains('150');
$this->assertSession()->responseContains('10');
// Try to set a value above the maximum value.
$this->drupalGet('entity_test/add');
$edit = [
"{$field_name}[0][fraction][numerator]" => 15000,
"{$field_name}[0][fraction][denominator]" => 10,
];
$this->submitForm($edit, $this->t('Save'));
$this->assertSession()->responseContains($this->t('%name: the value may be no greater than %maximum.', ['%name' => $field_name, '%maximum' => $max]));
// Try to set a value below the minimum value.
$this->drupalGet('entity_test/add');
$edit = [
"{$field_name}[0][fraction][numerator]" => 1,
"{$field_name}[0][fraction][denominator]" => 10,
];
$this->submitForm($edit, $this->t('Save'));
$this->assertSession()->responseContains($this->t('%name: the value may be no less than %minimum.', ['%name' => $field_name, '%minimum' => $min]));
// Empty denominator.
$this->drupalGet('entity_test/add');
$edit = [
"{$field_name}[0][fraction][numerator]" => 1,
];
$this->submitForm($edit, $this->t('Save'));
$this->assertSession()->responseContains($this->t('The denominator of a fraction cannot be zero or empty (if a numerator is provided).'));
// Numerators must be between -9223372036854775808 and 9223372036854775807.
$this->drupalGet('entity_test/add');
$edit = [
"{$field_name}[0][fraction][numerator]" => '-9223372036854775809',
"{$field_name}[0][fraction][denominator]" => 10,
];
$this->submitForm($edit, $this->t('Save'));
$this->assertSession()->responseContains($this->t('The numerator of a fraction must be between -9223372036854775808 and 9223372036854775807.'));
$this->drupalGet('entity_test/add');
$edit = [
"{$field_name}[0][fraction][numerator]" => '9223372036854775808',
"{$field_name}[0][fraction][denominator]" => 10,
];
$this->submitForm($edit, $this->t('Save'));
$this->assertSession()->responseContains($this->t('The numerator of a fraction must be between -9223372036854775808 and 9223372036854775807.'));
// Denominators must be between 0 and 2147483647.
$this->drupalGet('entity_test/add');
$edit = [
"{$field_name}[0][fraction][numerator]" => 10,
"{$field_name}[0][fraction][denominator]" => -1,
];
$this->submitForm($edit, $this->t('Save'));
$this->assertSession()->responseContains($this->t('The denominator of a fraction must be greater than 0 and less than 2147483647.'));
$this->drupalGet('entity_test/add');
$edit = [
"{$field_name}[0][fraction][numerator]" => 10,
"{$field_name}[0][fraction][denominator]" => 2147483648,
];
$this->submitForm($edit, $this->t('Save'));
$this->assertSession()->responseContains($this->t('The denominator of a fraction must be greater than 0 and less than 2147483647.'));
}
/**
* Test min/max with decimal values.
*/
public function testFractionWidgetMinMaxDecimal() {
$this->drupalCreateContentType(['type' => 'article']);
$page = $this->getSession()->getPage();
$assert_session = $this->assertSession();
$this->drupalGet('/admin/structure/types/manage/article/fields/add-field');
$page->selectFieldOption('new_storage_type', 'fraction');
$page->fillField('label', 'Fraction field');
$page->fillField('field_name', 'fraction_field');
$page->pressButton('Save and continue');
$page->pressButton('Save field settings');
$page->fillField('settings[min]', 10.5);
$page->fillField('settings[max]', 100.5);
$page->pressButton('Save settings');
$assert_session->pageTextContains('Saved Fraction field configuration.');
}
/**
* Tests that editing an empty fraction doesn't show a 0.
*
* @see https://www.drupal.org/project/fraction/issues/3096236
*/
public function testFractionWidgetDecimalEditNull() {
// Create a field with settings to validate.
$field_name = mb_strtolower($this->randomMachineName());
FieldStorageConfig::create([
'field_name' => $field_name,
'entity_type' => 'entity_test',
'type' => 'fraction',
])->save();
FieldConfig::create([
'field_name' => $field_name,
'entity_type' => 'entity_test',
'bundle' => 'entity_test',
])->save();
/** @var \Drupal\Core\Entity\EntityDisplayRepositoryInterface $display_repository */
$display_repository = \Drupal::service('entity_display.repository');
$display_repository->getFormDisplay('entity_test', 'entity_test')
->setComponent($field_name, ['type' => 'fraction_decimal'])
->save();
$display_repository->getViewDisplay('entity_test', 'entity_test')
->setComponent($field_name, ['type' => 'fraction_decimal'])
->save();
// Display creation form.
$this->drupalGet('entity_test/add');
$this->assertSession()->fieldValueEquals("{$field_name}[0][decimal]", '');
// Submit decimal value.
$value = '1.234';
$edit = [
"{$field_name}[0][decimal]" => $value,
];
$this->submitForm($edit, $this->t('Save'));
preg_match('|entity_test/manage/(\d+)|', $this->getUrl(), $match);
$id = $match[1];
$this->assertSession()->pageTextContains($this->t('entity_test @id has been created.', ['@id' => $id]));
$this->assertSession()->responseContains($value);
// Empty the field.
$edit = [
"{$field_name}[0][decimal]" => NULL,
];
$this->drupalGet("entity_test/manage/$id/edit");
$this->submitForm($edit, $this->t('Save'));
$this->assertSession()->responseNotContains($value);
// The field should have no value (not 0, just empty).
$this->drupalGet("entity_test/manage/$id/edit");
$xpath = $this->assertSession()->buildXPathQuery('//input[@name=:value]', [':value' => "{$field_name}[0][decimal]"]);
$elements = $this->xpath($xpath);
$element = reset($elements);
$this->assertSame($element->getValue(), '', 'Field is empty');
}
}
@@ -0,0 +1,138 @@
<?php
namespace Drupal\Tests\fraction\Kernel;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\fraction\Fraction;
use Drupal\fraction\Plugin\Field\FieldType\FractionItem;
use Drupal\node\Entity\Node;
use Drupal\node\Entity\NodeType;
use Drupal\Tests\field\Kernel\FieldKernelTestBase;
/**
* Class to test the FractionItem field.
*
* @group Fraction
*/
class FractionFieldTest extends FieldKernelTestBase {
/**
* Field name to use.
*/
const FIELD_NAME = 'field_fraction_test';
/**
* {@inheritdoc}
*/
protected static $modules = ['node', 'fraction'];
/**
* {@inheritdoc}
*/
public function setUp(): void {
parent::setUp();
$this->installEntitySchema('node');
$this->installSchema('node', ['node_access']);
NodeType::create([
'type' => 'article',
'label' => 'Article',
])->save();
$this->fieldTestData->{$this::FIELD_NAME . '_storage'} = FieldStorageConfig::create([
'entity_type' => 'node',
'field_name' => self::FIELD_NAME,
'type' => 'fraction',
]);
$this->fieldTestData->{$this::FIELD_NAME . '_storage'}->save();
$this->fieldTestData->{$this::FIELD_NAME} = FieldConfig::create([
'entity_type' => 'node',
'field_name' => self::FIELD_NAME,
'bundle' => 'article',
]);
$this->fieldTestData->{$this::FIELD_NAME}->save();
}
/**
* Test field properties.
*/
public function testFieldProperties() {
// Check for the correct main property name.
$this->assertNull(FractionItem::mainPropertyName(), 'The fraction item main property name is NULL.');
// Check for correct property definitions.
$definitions = FractionItem::propertyDefinitions($this->fieldTestData->{$this::FIELD_NAME . '_storage'});
$properties = ['numerator', 'denominator', 'fraction', 'decimal'];
foreach ($properties as $property) {
$this->assertNotEmpty($definitions[$property], "The fraction item has a $property property.");
}
// Ensure the decimal property is not internal to be included in JSON:API.
$this->assertFalse($definitions['decimal']->isInternal(), 'The fraction item decimal property is not internal.');
}
/**
* Tests setting the fraction field item from a decimal.
*/
public function testSetValue() {
// Setup the entity and field.
$node = Node::create([
'type' => 'article',
'title' => 'test',
]);
$node->save();
$fraction_field = $node->get(self::FIELD_NAME);
// Confirm that an empty field returns a null values.
$fraction_field->set(0, NULL);
$this->assertEquals(NULL, $fraction_field->first()->numerator);
$this->assertEquals(NULL, $fraction_field->first()->denominator);
$this->assertEquals(NULL, $fraction_field->first()->get('fraction')->getValue());
$this->assertEquals(NULL, $fraction_field->first()->get('decimal')->getValue());
// Set value with a decimal.
$fraction_field->set(0, 1.2);
$this->assertEquals(12, $fraction_field->first()->numerator);
$this->assertEquals(10, $fraction_field->first()->denominator);
$this->assertEquals('12/10', $fraction_field->first()->get('fraction')->getValue()->toString());
$this->assertEquals('1.2', $fraction_field->first()->get('decimal')->getValue());
// Change the value.
$fraction_field->set(0, 12.3);
$this->assertEquals(123, $fraction_field->first()->numerator);
$this->assertEquals(10, $fraction_field->first()->denominator);
$this->assertEquals('123/10', $fraction_field->first()->get('fraction')->getValue()->toString());
$this->assertEquals('12.3', $fraction_field->first()->get('decimal')->getValue());
// Set value with the decimal property.
$fraction_field->set(0, ['decimal' => 45.6]);
$this->assertEquals(456, $fraction_field->first()->numerator);
$this->assertEquals(10, $fraction_field->first()->denominator);
$this->assertEquals('456/10', $fraction_field->first()->get('fraction')->getValue()->toString());
$this->assertEquals('45.6', $fraction_field->first()->get('decimal')->getValue());
}
/**
* Tests setting the sample value.
*/
public function testGenerateSampleValue() {
$node = Node::create([
'type' => 'article',
'title' => 'test',
]);
$node->save();
$node->get(self::FIELD_NAME)->generateSampleItems();
$this->entityValidateAndSave($node);
$result = $node->get(self::FIELD_NAME)->getValue();
$result = reset($result);
$this->assertTrue(is_array($result));
$this->assertArrayHasKey('numerator', $result);
$this->assertArrayHasKey('denominator', $result);
$this->assertTrue($result['denominator'] > 0, TRUE);
}
}
@@ -0,0 +1,222 @@
<?php
namespace Drupal\Tests\fraction\Kernel;
use Drupal\Core\Database\Database;
use Drupal\Core\Utility\UpdateException;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\KernelTests\Core\Entity\EntityKernelTestBase;
use Drupal\node\Entity\NodeType;
/**
* Provides tests for updating the schema from signed to unsigned.
*
* @group Fraction
*/
class FractionUpdateTest extends EntityKernelTestBase {
/**
* Connection to the database.
*
* @var \Drupal\Core\Database\Connection
*/
protected $connection;
/**
* Database schema instance.
*
* @var \Drupal\Core\Database\Schema
*/
protected $schema;
/**
* Modules to enable.
*
* @var array
*/
protected static $modules = [
'fraction',
'fraction_test',
'node',
];
/**
* Fields to check the update.
*
* @var array
*/
protected $fieldsToUpdate;
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->connection = Database::getConnection();
$this->schema = $this->connection->schema();
$node_type = NodeType::create(['type' => 'article', 'name' => 'Article']);
$node_type->save();
FieldStorageConfig::create([
'field_name' => 'field_fraction_node',
'entity_type' => 'node',
'type' => 'fraction',
'cardinality' => -1,
])->save();
FieldConfig::create([
'field_name' => 'field_fraction_node',
'entity_type' => 'node',
'bundle' => 'article',
'label' => $this->randomMachineName() . '_label',
])->save();
FieldStorageConfig::create([
'field_name' => 'field_fraction_user',
'entity_type' => 'user',
'type' => 'fraction',
'cardinality' => -1,
])->save();
FieldConfig::create([
'field_name' => 'field_fraction_user',
'entity_type' => 'user',
'bundle' => 'user',
'label' => $this->randomMachineName() . '_label',
])->save();
$this->fieldsToUpdate = [
[
'table_name' => 'node_field_data',
'columns' => [
'numerator' => 'fraction__numerator',
'denominator' => 'fraction__denominator',
],
],
[
'table_name' => 'node__field_fraction_node',
'columns' => [
'numerator' => 'field_fraction_node_numerator',
'denominator' => 'field_fraction_node_denominator',
],
],
[
'table_name' => 'user__field_fraction_user',
'columns' => [
'numerator' => 'field_fraction_user_numerator',
'denominator' => 'field_fraction_user_denominator',
],
],
];
// Revert all the fields (with no data) to be unsigned so the post_update
// hook can be run.
foreach ($this->fieldsToUpdate as $field) {
$this->schema->changeField($field['table_name'], $field['columns']['denominator'], $field['columns']['denominator'], [
'type' => 'int',
'not null' => TRUE,
'unsigned' => TRUE,
'default' => 1,
]);
}
}
/**
* Tests the denominator update.
*/
public function testUpdateDenominatorSigned() {
// Unsigned fields should reject negative values.
foreach ($this->fieldsToUpdate as $field) {
if ($field['table_name'] == 'node_field_data') {
continue;
}
$this->assertFalse($this->tryUnsignedInsert($field['table_name'], $field['columns']), 'Column rejected a negative value.');
}
// Run the fraction update only.
$post_update_registry = $this->container->get('update.post_update_registry');
foreach ($post_update_registry->getUpdateFunctions('fraction') as $function) {
$function();
}
// Once the field is changed, negative values should be accepted. There's
// no unintrusive way to consistently check the actual SQL schema, so
// checking that there's a change on behaviour regarding signed/unsigned is
// the fastest way to check.
foreach ($this->fieldsToUpdate as $field) {
if ($field['table_name'] == 'node_field_data') {
continue;
}
$this->assertTrue($this->tryUnsignedInsert($field['table_name'], $field['columns']), 'Column accepted a negative value.');
}
}
/**
* Tests that data over the limit triggers a message on update.
*/
public function testUpdateDenominatorSignedException() {
// Unsigned fields should reject negative values.
foreach ($this->fieldsToUpdate as $field) {
if ($field['table_name'] == 'node_field_data') {
continue;
}
$this->assertFalse($this->tryUnsignedInsert($field['table_name'], $field['columns']), 'Column rejected a negative value.');
}
// Insert a value higher than the signed int bounds so that, when checked
// will trigger the update exception.
$this->container->get('database')->insert('node__field_fraction_node')
->fields(
[
'entity_id' => 1,
'revision_id' => 1,
'delta' => 0,
'field_fraction_node_numerator' => 9,
'field_fraction_node_denominator' => 2147483699,
]
)
->execute();
try {
// Run the fraction update only.
$post_update_registry = $this->container->get('update.post_update_registry');
foreach ($post_update_registry->getUpdateFunctions('fraction') as $function) {
$function();
}
// If the code reach this point, means that the update succeeded.
$this->fail('Failed due to update going through when it should not.');
}
catch (UpdateException $e) {
foreach ($this->fieldsToUpdate as $field) {
if ($field['table_name'] == 'node_field_data') {
continue;
}
$this->assertFalse($this->tryUnsignedInsert($field['table_name'], $field['columns']), 'Column rejected a negative value.');
}
}
}
/**
* Tries to insert a negative value into columns defined as unsigned.
*
* @see \Drupal\KernelTests\Core\Database\SchemaTest::tryUnsignedInsert()
*/
public function tryUnsignedInsert($table_name, $columns) {
try {
$this->container->get('database')->insert($table_name)
->fields(
[
'entity_id' => 1,
'revision_id' => 1,
'delta' => 0,
$columns['numerator'] => 1,
$columns['denominator'] => -10,
]
)
->execute();
return TRUE;
}
catch (\Exception $e) {
return FALSE;
}
}
}
@@ -0,0 +1,184 @@
<?php
namespace Drupal\Tests\fraction\Kernel\Plugin\Constraints;
use Drupal\Core\Entity\EntityConstraintViolationList;
use Drupal\Core\Validation\Plugin\Validation\Constraint\PrimitiveTypeConstraint;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\fraction\Fraction;
use Drupal\fraction\Plugin\Validation\Constraint\FractionConstraint;
use Drupal\KernelTests\Core\Entity\EntityKernelTestBase;
use Drupal\node\Entity\NodeType;
/**
* Tests Constraint for Fraction.
*
* @group Fraction
*/
class FractionConstraintTest extends EntityKernelTestBase {
/**
* {@inheritDoc}
*/
protected static $modules = ['node', 'fraction'];
/**
* EntityInterface.
*
* @var \Drupal\Core\Entity\EntityInterface
*/
protected $entity;
/**
* Field name.
*
* @var string
*/
const FIELD_NAME = 'field_fraction_test';
/**
* {@inheritDoc}
*/
protected function setUp(): void {
parent::setUp();
NodeType::create([
'type' => 'article',
'label' => 'Article',
])->save();
FieldStorageConfig::create([
'entity_type' => 'node',
'field_name' => self::FIELD_NAME,
'type' => 'fraction',
'cardinality' => 1,
])->save();
FieldConfig::create([
'entity_type' => 'node',
'field_name' => self::FIELD_NAME,
'bundle' => 'article',
])->save();
$this->entity = $this->entityTypeManager->getStorage('node')->create([
'type' => 'article',
'title' => 'test',
self::FIELD_NAME => [
'numerator' => 1,
'denominator' => 1,
],
]);
}
/**
* Tests constraints.
*/
public function testConstraints() {
$violations = $this->entity->validate();
$this->assertCount(0, $violations);
$this->assertViolations($violations);
$this->entity->{self::FIELD_NAME} = ['denominator' => '0', 'numerator' => '1'];
$violations = $this->entity->validate();
$this->assertCount(1, $violations);
$this->entity->{self::FIELD_NAME} = ['denominator' => '2147483649', 'numerator' => '1'];
$violations = $this->entity->validate();
$this->assertCount(1, $violations);
$this->assertViolations($violations);
$this->entity->{self::FIELD_NAME} = ['denominator' => '123456', 'numerator' => '1'];
$violations = $this->entity->validate();
$this->assertCount(0, $violations);
$this->entity->{self::FIELD_NAME} = ['denominator' => '1', 'numerator' => '9223372036854775808'];
$violations = $this->entity->validate();
$this->assertCount(2, $violations);
$this->assertViolations($violations);
$this->entity->{self::FIELD_NAME} = ['denominator' => '1', 'numerator' => '-9223372036854775809'];
$violations = $this->entity->validate();
$this->assertCount(2, $violations);
$this->assertViolations($violations);
$this->entity->{self::FIELD_NAME} = ['denominator' => '1', 'numerator' => '92233720368547758'];
$violations = $this->entity->validate();
$this->assertCount(0, $violations);
$this->entity->{self::FIELD_NAME} = ['decimal' => '1.255'];
$violations = $this->entity->validate();
$this->assertCount(0, $violations);
$decimal = '9223372.993685481231231';
$this->entity->{self::FIELD_NAME} = $this->generateFraction($decimal);
$violations = $this->entity->validate();
$this->assertCount(2, $violations);
$this->assertViolations($violations);
$decimal = '11.1234';
$this->entity->{self::FIELD_NAME} = $this->generateFraction($decimal);
$violations = $this->entity->validate();
$this->assertCount(0, $violations);
$decimal = '8.1251251251';
$this->entity->{self::FIELD_NAME} = $this->generateFraction($decimal);
$violations = $this->entity->validate();
$this->assertCount(1, $violations);
$this->assertViolations($violations);
$decimal = '8.12512512';
$this->entity->{self::FIELD_NAME} = $this->generateFraction($decimal);
$violations = $this->entity->validate();
$this->assertCount(0, $violations);
}
/**
* Helper method that generates fraction from decimal to set it on field.
*
* @param string $decimal
* Decimal to convert to fraction.
*
* @return array
* Array to be set on field.
*/
protected function generateFraction(string $decimal) {
$fraction = Fraction::createFromDecimal($decimal);
$numerator = $fraction->getNumerator();
$denominator = $fraction->getDenominator();
// Set the numerator and denominator values for the field and store
// them in array which will be saved on the field.
return [
'decimal' => $decimal,
'numerator' => $numerator,
'denominator' => $denominator,
];
}
/**
* Helper method to validate.
*
* @param \Drupal\Core\Entity\EntityConstraintViolationList $violations
* Violation list.
*/
protected function assertViolations(EntityConstraintViolationList $violations) {
foreach ($violations as $violation) {
$constraint = $violation->getConstraint();
if (!($constraint instanceof FractionConstraint || $constraint instanceof PrimitiveTypeConstraint)) {
$this->fail('Wrong type of constraint');
}
}
}
}
@@ -0,0 +1,147 @@
<?php
namespace Drupal\Tests\fraction\Unit\Feeds\Target;
use Drupal\Core\Form\FormState;
use Drupal\fraction\Feeds\Target\FractionTarget;
use Drupal\Tests\feeds\Unit\Feeds\Target\FieldTargetTestBase;
/**
* @coversDefaultClass \Drupal\fraction\Feeds\Target\FractionTarget
* @group feeds
*/
class FractionTargetTest extends FieldTargetTestBase {
/**
* The ID of the plugin.
*
* @var string
*/
protected static $pluginId = 'fraction';
/**
* {@inheritdoc}
*/
protected function getTargetClass() {
return FractionTarget::class;
}
/**
* @covers ::prepareValue
*/
public function testPrepareValueFraction() {
$method = $this->getMethod('Drupal\fraction\Feeds\Target\FractionTarget', 'prepareTarget')->getClosure();
$configuration = [
'feed_type' => $this->createMock('Drupal\feeds\FeedTypeInterface'),
'target_definition' => $method($this->getMockFieldDefinition()),
'type' => 'fraction',
];
$target = new FractionTarget($configuration, 'fraction', []);
$method = $this->getProtectedClosure($target, 'prepareValue');
// Test a basic fraction: 1/2.
$values = ['value' => '1/2'];
$method(0, $values);
$this->assertSame($values['numerator'], '1');
$this->assertSame($values['denominator'], '2');
// Test that a zero numerator results in an empty fraction.
$values = ['value' => '0/1'];
$method(0, $values);
$this->assertSame($values['numerator'], '');
$this->assertSame($values['denominator'], '');
// Test that a zero denominator results in an empty fraction.
$values = ['value' => '1/0'];
$method(0, $values);
$this->assertSame($values['numerator'], '');
$this->assertSame($values['denominator'], '');
// Test that a negative numerator works.
$values = ['value' => '-1/2'];
$method(0, $values);
$this->assertSame($values['numerator'], '-1');
$this->assertSame($values['denominator'], '2');
// Test that a negative denominator results in an empty fraction.
$values = ['value' => '1/-2'];
$method(0, $values);
$this->assertSame($values['numerator'], '');
$this->assertSame($values['denominator'], '');
// Test that a decimal value results in an empty fraction.
$values = ['value' => '1.0'];
$method(0, $values);
$this->assertSame($values['numerator'], '');
$this->assertSame($values['denominator'], '');
// Test that a non-numeric value results in an empty fraction.
$values = ['value' => 'te/st'];
$method(0, $values);
$this->assertSame($values['numerator'], '');
$this->assertSame($values['denominator'], '');
}
/**
* @covers ::prepareValue
*/
public function testPrepareValueDecimal() {
$method = $this->getMethod('Drupal\fraction\Feeds\Target\FractionTarget', 'prepareTarget')->getClosure();
$configuration = [
'feed_type' => $this->createMock('Drupal\feeds\FeedTypeInterface'),
'target_definition' => $method($this->getMockFieldDefinition()),
'type' => 'decimal',
];
$target = new FractionTarget($configuration, 'fraction', []);
$method = $this->getProtectedClosure($target, 'prepareValue');
// Test a basic decimal.
$values = ['value' => 0.5];
$method(0, $values);
$this->assertSame($values['numerator'], '5');
$this->assertSame($values['denominator'], '10');
// Test a negative decimal.
$values = ['value' => -1];
$method(0, $values);
$this->assertSame($values['numerator'], '-1');
$this->assertSame($values['denominator'], '1');
// Test that a zero value results in 0/1.
$values = ['value' => 0];
$method(0, $values);
$this->assertSame($values['numerator'], '0');
$this->assertSame($values['denominator'], '1');
// Test that an empty value results in an empty fraction.
$values = ['value' => ''];
$method(0, $values);
$this->assertSame($values['numerator'], '');
$this->assertSame($values['denominator'], '');
// Test that a string value results in an empty fraction.
$values = ['value' => 'test'];
$method(0, $values);
$this->assertSame($values['numerator'], '');
$this->assertSame($values['denominator'], '');
}
/**
* @covers ::buildConfigurationForm
*/
public function testBuildConfigurationForm() {
$method = $this->getMethod('Drupal\fraction\Feeds\Target\FractionTarget', 'prepareTarget')->getClosure();
$configuration = [
'feed_type' => $this->createMock('Drupal\feeds\FeedTypeInterface'),
'target_definition' => $method($this->getMockFieldDefinition()),
];
$target = new FractionTarget($configuration, 'fraction', []);
$target->setStringTranslation($this->getStringTranslationStub());
$form_state = new FormState();
$form = $target->buildConfigurationForm([], $form_state);
$this->assertSame(count($form), 1);
$this->assertArrayHasKey('type', $form);
}
}
@@ -0,0 +1,184 @@
<?php
namespace Drupal\Tests\fraction\Unit;
use Drupal\Tests\UnitTestCase;
use Drupal\fraction\Fraction;
/**
* Provides tests for the Fraction class.
*
* @group Fraction
*/
class FractionTest extends UnitTestCase {
/**
* Returns a Fraction object from a numerator and denominator.
*
* This allows for easier chaining of Fraction methods in tests.
*
* @param int $numerator
* The fraction's numerator.
* @param int $denominator
* The fraction's denominator.
*
* @return \Drupal\fraction\Fraction
* Returns a $this->fraction object.
*/
protected function fraction($numerator = 0, $denominator = 1) {
return new Fraction($numerator, $denominator);
}
/**
* Test the Fraction class and it's methods.
*/
public function testFraction() {
// Test creation of a fraction.
$fraction = $this->fraction(1, 2);
$numerator = $fraction->getNumerator();
$denominator = $fraction->getDenominator();
$message = 'A fraction of 1/2 should return a numerator of 1.';
$this->assertEquals($numerator, '1', $message);
$message = 'A fraction of 1/2 should return a denominator of 2.';
$this->assertEquals($denominator, '2', $message);
// Test creation of an empty fraction.
$fraction = $this->fraction();
$numerator = $fraction->getNumerator();
$denominator = $fraction->getDenominator();
$message = 'An empty fraction should return a numerator of 0.';
$this->assertEquals($numerator, '0', $message);
$message = 'An empty fraction should return a denominator of 1.';
$this->assertEquals($denominator, '1', $message);
// Test returning a fraction as a string.
$result = $this->fraction(1, 2)->toString();
$message = 'A fraction with a numerator of 1 and a denominator of 2 should return a string of "1/2".';
$this->assertEquals($result, '1/2', $message);
// Test returning a fraction as a string with a different separator.
$result = $this->fraction(1, 2)->toString(':');
$message = 'A fraction with a numerator of 1 and a denominator of 2 should return a string of "1:2" (when a colon separator is specified).';
$this->assertEquals($result, '1:2', $message);
// Test division by zero.
$result = $this->fraction(1, 0)->toString();
$message = 'A fraction of 1/0 should return 0/1 (avoid division by zero).';
$this->assertEquals($result, '0/1', $message);
// Test normalization of negative fractions.
$result = $this->fraction(-1, 2)->toString();
$message = 'A fraction of -1/2 should normalize to -1/2.';
$this->assertEquals($result, '-1/2', $message);
$result = $this->fraction(1, -2)->toString();
$message = 'A fraction of 1/-2 should normalize to -1/2.';
$this->assertEquals($result, '-1/2', $message);
$result = $this->fraction(-1, -2)->toString();
$message = 'A fraction of -1/-2 should normalize to 1/2.';
$this->assertEquals($result, '1/2', $message);
// Test converting a fraction to a decimal.
$result = $this->fraction(1, 2)->toDecimal(1);
$message = 'A fraction of 1/2 should return a decimal of 0.5 (with precision 1)';
$this->assertEquals($result, '0.5', $message);
// Test decimal precision (rounding up).
$result = $this->fraction(1, 2)->toDecimal(0);
$message = 'A fraction of 1/2 with no precision should round to 1.';
$this->assertEquals($result, '1', $message);
// Test decimal precision (rounding down).
$result = $this->fraction(2, 5)->toDecimal(0);
$message = 'A fraction of 2/5 with no precision should round to 0.';
$this->assertEquals($result, '0', $message);
// Test automatic precision for base-10 denominator.
$result = $this->fraction(1, 1000)->toDecimal(2, TRUE);
$message = 'A fraction of 1/1000 with precision 2 and auto-precision enabled should round to 0.001.';
$this->assertEquals($result, '0.001', $message);
// Test automatic precision for denominator of 1.
$result = $this->fraction(3, 1)->toDecimal(0, TRUE);
$message = 'A fraction of 3/1 should return a decimal of 3 (with precision 0, auto_precision)';
$this->assertEquals($result, '3', $message);
// Test automatic precision for terminating fractions.
$result = $this->fraction(1, 8)->toDecimal(0, TRUE);
$message = 'A fraction of 1/8 should return a decimal of 0.125 (with precision 0, auto_precision)';
$this->assertEquals($result, '0.125', $message);
// Test automatic precision for fractions with a denominator greater than
// 2147483647.
$result = $this->fraction(1, 2147483648)->toDecimal(0, TRUE);
$message = 'A fraction of 1/2147483648 should return a decimal of 0.0000000004656612873077392578125 (with precision 0, auto_precision)';
$this->assertEquals('0.0000000004656612873077392578125', $result, $message);
// Test automatic precision for non-terminating fractions: 1/6.
$result = $this->fraction(1, 6)->toDecimal(3, TRUE);
$message = 'A fraction of 1/6 should return a decimal of 0.167 (with precision 0, auto_precision)';
$this->assertEquals($result, '0.167', $message);
// Test automatic precision for non-terminating fractions: 1/3.
$result = $this->fraction(1, 3)->toDecimal(3, TRUE);
$message = 'A fraction of 1/3 should return a decimal of 0.333 (with precision 3, auto_precision)';
$this->assertEquals($result, '0.333', $message);
// Test creation of a fraction from a decimal.
$result = Fraction::createFromDecimal(0.5)->toString();
$message = 'The createFromDecimal() method should create a fraction of 5/10 from a decimal of 0.5.';
$this->assertEquals($result, '5/10', $message);
// Test calculation of greatest common divisor.
$result = $this->fraction(5, 10)->gcd();
$message = 'The greatest common divisor of 1/2 is 5.';
$this->assertEquals($result, '5', $message);
// Test reduction of a fraction to its simplest form.
$result = $this->fraction(5, 10)->reduce()->toString();
$message = 'A fraction of 5/10 should be reducible to 1/2.';
$this->assertEquals($result, '1/2', $message);
// Test fraction addition.
$result = $this->fraction(1, 2)->add($this->fraction(1, 3))->toString();
$message = '1/2 + 1/3 = 5/6';
$this->assertEquals($result, '5/6', $message);
// Test fraction subtraction.
$result = $this->fraction(2, 3)->subtract($this->fraction(1, 7))->toString();
$message = '2/3 - 1/7 = 11/21';
$this->assertEquals($result, '11/21', $message);
// Test fraction multiplication.
$result = $this->fraction(2, 5)->multiply($this->fraction(1, 4))->toString();
$message = '2/5 * 1/4 = 1/10';
$this->assertEquals($result, '1/10', $message);
// Test fraction division.
$result = $this->fraction(5, 7)->divide($this->fraction(1, 5))->toString();
$message = '5/7 / 1/5 = 25/7';
$this->assertEquals($result, '25/7', $message);
// Test fraction reciprocation.
$result = $this->fraction(1, 2)->reciprocate()->toString();
$message = 'The reciprocal of 1/2 is 2/1.';
$this->assertEquals($result, '2/1', $message);
// Test that reciprocation of a zero numerator does not result in division
// by zero.
$result = $this->fraction(0, 1)->reciprocate()->toString();
$message = 'The reciprocal of 0/1 is 0/1 (avoid division by zero).';
$this->assertEquals($result, '0/1', $message);
// Test that decimal arithmetic results are reduced.
$result = Fraction::createFromDecimal('0.1')->add(Fraction::createFromDecimal('0.2'))->toDecimal(0, TRUE);
$message = '0.1 + 0.2 = 0.3';
$this->assertEquals('0.3', $result, $message);
// Test floating point arithmetic.
$result = Fraction::createFromDecimal('3')->subtract(Fraction::createFromDecimal('2.99'))->toDecimal(0, TRUE);
$message = '3 - 2.99 = 0.01';
$this->assertEquals('0.01', $result, $message);
}
}
@@ -0,0 +1,81 @@
<?php
namespace Drupal\Tests\fraction\Unit\process;
use Drupal\Tests\migrate\Unit\process\MigrateProcessTestCase;
use Drupal\fraction\Plugin\migrate\process\DecimalFraction;
/**
* Tests the decimal fraction process plugin.
*
* @group migrate
* @coversDefaultClass \Drupal\fraction\Plugin\migrate\process\DecimalFraction
*/
class DecimalFractionTest extends MigrateProcessTestCase {
/**
* {@inheritdoc}
*/
protected function setUp(): void {
$this->plugin = new DecimalFraction([], 'decimal_fraction', []);
parent::setUp();
}
/**
* Test decimal fraction plugin.
*
* @dataProvider decimalFractionDataProvider
*/
public function testDecimalFraction($input, $expected_output) {
$output = $this->plugin->transform($input, $this->migrateExecutable, $this->row, 'destinationproperty');
$this->assertSame($output['numerator'], $expected_output['numerator']);
$this->assertSame($output['denominator'], $expected_output['denominator']);
}
/**
* Data provider for testDecimalFraction().
*
* @return array
* Array of input values and expected output values.
*/
public function decimalFractionDataProvider() {
return [
'basic decimal' => [
'input' => 0.5,
'expected_output' => [
'numerator' => '5',
'denominator' => '10',
],
],
'negative decimal' => [
'input' => -1,
'expected_output' => [
'numerator' => '-1',
'denominator' => '1',
],
],
'zero value' => [
'input' => 0,
'expected_output' => [
'numerator' => '0',
'denominator' => '1',
],
],
'empty string' => [
'input' => '',
'expected_output' => [
'numerator' => '',
'denominator' => '',
],
],
'string' => [
'input' => 'test',
'expected_output' => [
'numerator' => '',
'denominator' => '',
],
],
];
}
}