2

I am writing a module to return common parent of 2 revision in a linear entity. For example : After editing a node 5 times, we get a graph similar to 1->2->3->4->5 where 1 is the actual node and 5 is the last revision. I wrote a function which would return the common parent of 2 revision ID. It would return 3 for (4,5) and 2 for (3,4). The code is the following one.

namespace Drupal\conflict;

use Drupal\conflict\ConflictManagerInterface;
use Drupal\conflict\ConflictAncestorResolverInterface;

class ConflictManager implements ConflictManagerInterface {

    protected $resolvers = [];

    public function applies() {
        return TRUE;
    }

    public function addAncestorResolver(ConflictAncestorResolverInterface $resolver)
    {
        $this->resolvers[] = $resolver;
    }    

    public function resolveLowestCommonAncestor($revision1, $revision2)
    {
        foreach ($this->resolvers as $resolver) {
            if ($resolver->applies()) {
                return $resolver->resolve($revision1, $revision2);
            }
        }
        echo "No revision found";
        return -1;
    }

    public function resolve($revision1, $revision2) {
        if ($revision1 < $revision2) {
            return $revision1-1;
        }
        return $revision2-1;
    }
}

To test the above written code, I have written a test case:

namespace Drupal\conflict\Tests;  

use Drupal\Tests\UnitTestCase;
use Drupal\Core\Entity\Entity;
use Drupal\conflict;

class SimpleLcaTest extends UnitTestCase {

    public function basicTest() {
        $entity = EntityTest::create(['label' => 'revision 1']);
        $entity->save();
        $entity->label = 'revision 2';
        $entity->save();
        $entity->label = 'revision 3';
        $entity->save();

        $revision2 = entity_revision_load('entity_test', 2);
        $revision3 = entity_revision_load('entity_test', 3);

        $manager = Drupal::service('conflict.manager');
        $revisionLca = $manager->resolveLowestCommonAncestor($revision2, $revision3);
        $this->assertTrue($revisionLca->label() == 'revision 1');
     }
}

When I try to run test via console using run-test.sh, I get the following error:

Exception 'PDOException' with message 'SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'file' cannot be null

enter image description here

5

You can't create and save entities in a unit test.

That's what kernel tests are for. You will also need to install the necessary entity schema then, make sure the necessary modules are enabled. One way to do that is to extend from EntityKernelTestBase.

Also, I strongly recommend to run the phpunit tests directly with phpunit, the error reporting is much better and it's faster as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.