jeudi 3 septembre 2020

Create file from template in PHP using Laravel for Testing

What I want to archive:

I want to write a feature test using phpunit in Laravel.

What does the controller I want to test do:

It accepts uploads of test records to store it into a database. Each record consists of two files (xml, yml) with the same file name. Both files have to be read and stored in the database. The uploaded files are never stored on the server, they are directly processes.

What I want to test:

  • Upload a record and check if the correct data is in the database and available over the API
  • Check if I get the correct error if one file (xml or yml) is missing
  • Check if I get the right error if the files are not a valid record
  • and so on ...

What is my current problem?

I would like to use a template for the xml and yml files and use Faker to generate fake data for this test. The reason: Why not? My understanding of testing is, that you should test as many cases as possible and if static data is enough why do we use Faker and Factory in the Unit tests for the database and so on?

When I look at Laravel: Testing File Uploads, they generate there testing files with UploadedFile::fake(). My understanding of those files is, that they are empty and you can't use a template or something like that, to fill it with useful data. Most solutions I found just kept real files in their project. Like this.

I could use blade for this, like shown here, but I'm not really sure if I should abuse blade like this.

I could fully generate the xml and yml files using Yaml and XMLReader/XMLWriter, but there is a lot of unused text (unused by my application) in this files and I only need to fill data into some specific points.

Questions:

  • So what is the best way to create such a fake file? Should I use blade or twig or some other templating engine? A small solution would be appreciated.
  • Or should I generate the full file by myself and why is this better?
  • Or is there no point in generating fake data and I should use static data instead?

Here is my current test function:

public function testFullRecordUpload() {
    // Generate record files to upload
    // TODO Use template files with faker, or something like that
    $xml_file = UploadedFile::fake()->create('test_file.xml', $sizeInKilobytes = 566);
    $yml_file = UploadedFile::fake()->create('test_file.yml', $sizeInKilobytes = 20);

    // Send Files
    $response = $this->json('POST', '/upload', [
        'xml' => $xml_file,
        'yml' => $yml_file
    ]);

    // Check response
    $response->assertOk();

    // Check if the uploaded data is available over API
    // TODO
}

Aucun commentaire:

Enregistrer un commentaire