Problem/Motivation
The ResourceTestBase has a static property of $uniqueFieldNames for tracking unique field names on an entity. This is used to prevent errors when modifying and creating entities in tests.
These fields are not taken into account when the \Drupal\Tests\jsonapi\Functional\ResourceTestBase::getEntityDuplicate method is used.
I had to extend this method to fix the problem, where the sku field is unique.
/**
* {@inheritdoc}
*/
protected function getEntityDuplicate(EntityInterface $original, $key) {
$dupe = parent::getEntityDuplicate($original, $key);
assert($dupe instanceof ProductVariationInterface);
$dupe->setSku('XYZ789');
return $dupe;
}
Steps to reproduce
See #3128322: Filtering variations over JSON:API is always access false
Proposed resolution
Respect unique fields when making a duplicate. It is done there:
protected function getModifiedEntityForPostTesting() {
$document = $this->getPostDocument();
// Ensure that all the unique fields of the entity type get a new random
// value.
foreach (static::$uniqueFieldNames as $field_name) {
$field_definition = $this->entity->getFieldDefinition($field_name);
$field_type_class = $field_definition->getItemDefinition()->getClass();
$document['data']['attributes'][$field_name] = $field_type_class::generateSampleValue($field_definition);
}
Remaining tasks
User interface changes
API changes
Data model changes
Release notes snippet
Comments
Comment #2
mglamanThe only instance of Drupal core using this property is in FeedTest
Comment #3
mglamanThis removes the need to manually fix unique fields in a test which extends ResourceTestBase for JSON:API integration testing.
Comment #5
mglamanTest only patch was the failure
Comment #8
bbralaAwesome contribution mglaman. Looking good but really do need this targeted on 9.3.x.
Comment #9
imalabyaRe-rolled the patch at #3
Comment #10
mglamanThanks for the reroll imalabya!
Comment #11
bbralaWell done, nice work. :)
Comment #12
alexpottgenerateSampleValue() is not guaranteed to return a different value. Imo you should try a few times if you get the same value and fail if you don't get a new value.
Comment #13
bbralaExcellent point. Thanks.