0

I'm using a Kernel test in Drupal to add a new instance of my custom entity. In the postSave() method of my entity, I generate a PDF using TCPDF. In the browser, this all works well and I can see the generated PDF in my file system. My issue is that when I run PHPUnit from the CLI, it produces my entity fine but it can't assert that the file exists.

class CustomEntityAddTest extends EntityKernelTestBase 
{

  /**
   * A list of modules to be enabled to run this test
   *
   * @var array
   */
  public static $modules = ['block', 'datetime', 'custom_entity', 'entity_reference', 'file', 'migrate', 'options', 'system', 'taxonomy', 'text'];

  /**
   * The Directory where generated PDFs are stored
   */
  const FILES_DIRECTORY = \Drupal\custom_entity\Entity\CustomEntity::DP_DIRECTORY_BASE;

  public function setUp() {

    parent::setUp();
  }

  /**
   * Undocumented function
   *
   * @return void
   */
  public function testAdd() {

    $custom_entity = CustomEntity::create([
      'user_id' => 1,
      'status' => 0,
      'title' => 'First Test!',
      'inventco' => CustomEntity::generateSubmissionID(),
      'abstract' => 'Test abstract',
      'created' => time(),
      'changed' => time(),
    ]);

    $this->assertInstanceOf(CustomEntity::class, $custom_entity, "An entity was not created");

    $inventco = $custom_entity->get('inventco')->getString();

    // debugging
    $path = "/var/www/drupalvm/docroot/sites/default/files/private/{$inventco}/{$inventco}_frontpage.pdf";
    print_r(scandir("/var/www/drupalvm/docroot/sites/default/files/private/{$inventco}"));
    print($path);
    // Assert DP files exist
    $this->assertFileExists($path, "Generated PDF does not exist");
  }
}

How can I assert that the file was produced? I've checked that the filepath is correct.

3
  • 2
    It looks like you've forgotten to save $custom_entity?
    – Andy
    Jul 17, 2018 at 11:35
  • That and ensure you’re running PHPUnit inside the VM and not outside.
    – Kevin
    Jul 17, 2018 at 11:58
  • Ah yes I think the issue that I wasn't calling the save() method. I have another issue about the php stream wrappers not being registered which I might need to open another question for. Also, yes running in VM Jul 18, 2018 at 10:11

1 Answer 1

0

It was because I hadn't called the save method on the $custom_entity object.

Credit and thanks to Andy

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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