keboola/datadir-tests

Keboola Connection组件功能测试工具

5.6.0 2023-10-20 08:02 UTC

This package is auto-updated.

Last update: 2024-09-10 10:57:50 UTC


README

GitHub Actions

用法

在您的组件中需要此包

composer require keboola/datadir-tests`

在测试文件夹中创建一个类似生产环境目录结构的目录结构

/path/to/tests
└─test-name
  ├─expected-code
  ├─expected-stdout (optional)
  ├─expected-stderr (optional)
  ├─expected
  │ └─data
  │   └─out
  │     ├─files
  │     └─tables
  ├─source
  │ └─data
  │   └─in
  │     ├─files
  │     └─tables
  └─config.json

注意:使用 assertStringMatchesFormat 方法,将 expected-stdoutexpected-stderr 与实际输出进行比较,因此您可以使用 占位符

然后创建一个空的 /path/to/tests/DatadirTest,它扩展了 Keboola\DatadirTests\DatadirTestCase

<?php

declare(strict_types=1);

namespace MyComponent\Tests;

use Keboola\DatadirTests\DatadirTestCase;

class DatadirTest extends DatadirTestCase
{
}

使用以下命令运行

vendor/bin/phpunit /path/to/tests/DatadirTest.php`

该脚本然后将 /code/src/run.phpKBC_DATADIR 设置为测试目录执行。可以有任意数量的测试目录,脚本会自动使用 DatadirTestsFromDirectoryProvider 发现它们。您可以提供自己的提供者,该提供者实现了 DatadirTestsProviderInterface。它需要返回 !DatadirTestSpecificationInterface 实例的数组。

当存在 expected-code 文件时,会检查执行返回码。文件包含一个数字 - 执行代码,允许的值是 012

DatadirTestSpecificationInterface 是什么?

DatadirTestSpecificationInterface 包含您创建和断言数据目录测试所需的所有信息

  • getSourceDatadirDirectory(): ?string:返回初始化测试的目录。您应该准备 config.json 以及可能还需要 /in/files/in/tables 的内容。该目录将镜像到测试运行中的临时目录。如果为 null,则仅创建基本目录结构,您需要在临时目录中自己创建 config.json 等。
  • getExpectedReturnCode(): ?int:预期的退出码,null 表示“非零”
  • getExpectedStdout(): ?string:如果提供,整个 stdout 输出将与提供的值进行比较
  • getExpectedStderr(): ?string:如果提供,整个 stderr 输出将与提供的值进行比较
  • getExpectedOutDirectory(): ?string:如果提供,将在组件运行后将临时目录的 out 目录 与此目录进行比较。任何差异都会导致测试失败。

自定义测试

只需添加一个测试方法,并重用 AbstractDatadirTestCase 中现有的辅助方法。

public function testInvalidFile(): void
{
   // create specification manually
   $specification = new DatadirTestSpecification(
       __DIR__ . '/columns-auto/source/data',
       0,
       null,
       null,
       __DIR__ . '/columns-auto/expected/data/out'
   );
   
   // create temporary directory
   $tempDatadir = $this->getTempDatadir($specification);
   
   // modify temporary directory however you see fit
   file_put_contents($tempDatadir->getTmpFolder() . '/config.json', '{"parameters": []}');
   
   // run the script
   $process = $this->runScript($tempDatadir->getTmpFolder());
   
   // assert specification
   $this->assertMatchesSpecification($specification, $process, $tempDatadir->getTmpFolder());
}

环境变量

  • config.json 中,您可以使用环境变量的占位符。
  • 格式为 %env(TYPE:VAR_NAME)%,例如 %env(int:DB_PORT)%
  • config.json 中所有与指定格式匹配的字符串值都将被替换。
  • 它在 AbstractDatadirTestCase::modifyConfigJsonContent 中实现。
  • 允许的类型有 stringintfloatbool
  • 请参阅示例

功能调整

  • 要修改执行前的临时数据目录,您可以扩展方法 AbstractDatadirTestCase::setUpDatadir

开发

克隆此存储库,并使用以下命令初始化工作区

git clone https://github.com/keboola/datadir-tests
cd datadir-tests
docker-compose run --rm dev /bin/bash
$ composer install
$ composer ci

许可证

MIT 许可,请参阅 LICENSE 文件。