PHPUnitでテストを追加・実行していると、プロジェクトのコードベースが成長するにつれてテストの実行に時間がかかるようになります。数行の修正でも毎回全specを実行する運用だと、プルリクエストごとにCIの待ち時間が伸びがちです。
CircleCIのSmarter Testingは、変更したファイルに関係するテストだけを選んで実行する仕組みです。
この記事では、PHPUnit 9向けにCircleCIのTest Impact AnalysisをCLIで試す手順をまとめます。
PHPUnitプロジェクトでテストが通ることを確認する
まずはじめに、プロジェクトをセットアップしましょう。ルートにcomposer.jsonを作成し、続けて同じ階層にphpunit.xmlも追加します。
{
"require-dev": {
"phpunit/phpunit": "^9.6"
}
}
phpunit.xmlではbootstrapとカバレッジ対象のsrcを指定し、tests配下の*Test.phpをテスト対象にします。
<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="tests/bootstrap.php">
<testsuites>
<testsuite name="all">
<directory suffix="Test.php">tests</directory>
</testsuite>
</testsuites>
<coverage>
<include>
<directory suffix=".php">src</directory>
</include>
</coverage>
</phpunit>
簡単な例として、税金の計算処理を実装しましょう。
<?php
final class Price
{
public static function withTax(int $amount): int
{
return (int) round($amount * 1.1);
}
}
続いてテスト選択の振る舞いなどを確認するため、もう1つの処理ファイルを作ります。
<?php
final class Discount
{
private const RATES = ['gold' => 0.2, 'silver' => 0.1, 'none' => 0.0];
public static function rate(string $rank): float
{
return self::RATES[$rank];
}
}
続いてPHPUnitのテストを実行する準備をしましょう。
<?php
require __DIR__ . '/../src/Price.php';
require __DIR__ . '/../src/Discount.php';
require __DIR__ . '/Support/PriceTestTrait.php';
共有するassertionはtests/Support/PriceTestTrait.phpです。
<?php
trait PriceTestTrait
{
public function test1000円は税込1100円(): void
{
$this->assertSame(1100, Price::withTax(1000));
}
}
tests/PriceTest.phpは通常の単体テストです。
<?php
use PHPUnit\Framework\TestCase;
final class PriceTest extends TestCase
{
public function test100円は税込110円(): void
{
$this->assertSame(110, Price::withTax(100));
}
}
tests/PriceProviderTest.phpはDataProviderを使ったテストとして実装します。
<?php
use PHPUnit\Framework\TestCase;
final class PriceProviderTest extends TestCase
{
public static function cases(): array
{
return [[200, 220], [300, 330]];
}
/** @dataProvider cases */
public function test税込価格(int $amount, int $expected): void
{
$this->assertSame($expected, Price::withTax($amount));
}
}
続いてtraitを使うテストやJSON fixturesを読むテストも追加しておきましょう。
<?php
use PHPUnit\Framework\TestCase;
final class PriceSharedTest extends TestCase
{
use PriceTestTrait;
}
tests/DiscountDataTest.phpはJSON fixturesを読むテストです。
<?php
use PHPUnit\Framework\TestCase;
final class DiscountDataTest extends TestCase
{
public static function cases(): array
{
$rows = json_decode(file_get_contents(__DIR__ . '/fixtures/discount_cases.json'), true);
return array_map(fn ($r) => [$r['rank'], $r['rate']], $rows);
}
/** @dataProvider cases */
public function test割引率(string $rank, float $rate): void
{
$this->assertSame($rate, Discount::rate($rank));
}
}
tests/fixtures/discount_cases.jsonを次の内容で作成します。ファイルをそろえたら、ルートで依存関係を入れてPHPUnitを実行します。
[
{"rank": "gold", "rate": 0.2},
{"rank": "silver", "rate": 0.1}
]
testsが通れば、PHPUnit側の準備は完了です。
composer install --no-interaction
vendor/bin/phpunit
PHPUnit向けにJUnitとLCOVを用意する
Smarter Testingでは、独立して実行できるテストの単位をtest atomと呼びます。この記事ではtests配下の*Test.php1本が1 atomで、runにはJUnit XML、analysisにはLCOVが必要です。
PHPUnit 9はCLI引数で複数ファイルを一度に実行できません。選択されたatomは<file>で列挙した一時設定を書き、1回のphpunitでJUnitを出してください。カバレッジはCloverからLCOVへ変換し、両方を.circleci/phpunit-testsuite.phpにまとめます。
<?php
declare(strict_types=1);
if ($argc < 3) {
fwrite(STDERR, "Usage: php .circleci/phpunit-testsuite.php run|analyze <output>\n");
exit(1);
}
[, $mode, $out] = $argv;
if ($mode !== 'run' && $mode !== 'analyze') {
fwrite(STDERR, "Unknown mode: {$mode}\n");
exit(1);
}
if (!is_dir('vendor')) {
passthru('composer install --no-interaction -q', $code);
if ($code !== 0) {
exit($code);
}
}
exit($mode === 'run' ? runJunit($out) : analyzeLcov($out));
/** @return list<string> */
function readAtoms(): array
{
$atoms = [];
while (($line = fgets(STDIN)) !== false) {
$atom = trim($line);
if ($atom === '') {
continue;
}
$atoms[] = assertTestAtom($atom);
}
return $atoms;
}
function assertTestAtom(string $atom): string
{
$normalized = preg_replace('#^\./#', '', $atom) ?? $atom;
if (
str_contains($normalized, "\0")
|| str_contains($normalized, '..')
|| !preg_match('#^tests/.+Test\.php$#', $normalized)
|| !is_file($normalized)
) {
fwrite(STDERR, "Atom must be an existing tests/**/*Test.php path: {$atom}\n");
exit(1);
}
return $normalized;
}
function runJunit(string $out): int
{
$atoms = readAtoms();
if ($atoms === []) {
fwrite(STDERR, "No test atoms on stdin\n");
return 1;
}
$dir = dirname($out);
if ($dir !== '' && $dir !== '.' && !is_dir($dir)) {
mkdir($dir, 0777, true);
}
// bootstrap は設定ファイルからの相対パスなので、リポジトリルートに一時XMLを置く
$config = getcwd() . '/phpunit.selected.' . bin2hex(random_bytes(8)) . '.xml';
$filesXml = '';
foreach ($atoms as $atom) {
$filesXml .= ' <file>' . htmlspecialchars($atom, ENT_XML1 | ENT_QUOTES, 'UTF-8') . "</file>\n";
}
file_put_contents($config, <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="tests/bootstrap.php">
<testsuites>
<testsuite name="selected">
{$filesXml} </testsuite>
</testsuites>
</phpunit>
XML);
$cmd = sprintf(
'vendor/bin/phpunit --configuration %s --log-junit %s',
escapeshellarg($config),
escapeshellarg($out)
);
passthru($cmd, $status);
unlink($config);
return $status;
}
function analyzeLcov(string $out): int
{
$atoms = readAtoms();
if (count($atoms) !== 1) {
fwrite(STDERR, "analyze expects exactly one test atom on stdin\n");
return 1;
}
$clover = sys_get_temp_dir() . '/clover.' . bin2hex(random_bytes(8)) . '.xml';
$cmd = sprintf(
'vendor/bin/phpunit --coverage-clover %s %s > /dev/null 2>&1',
escapeshellarg($clover),
escapeshellarg($atoms[0])
);
passthru($cmd);
if (!is_file($clover) || filesize($clover) === 0) {
fwrite(STDERR, "coverage clover is empty (is PCOV installed?)\n");
@unlink($clover);
return 1;
}
cloverToLcov($clover, $out);
unlink($clover);
return 0;
}
function cloverToLcov(string $cloverFile, string $out): void
{
$xml = simplexml_load_file($cloverFile);
if ($xml === false) {
fwrite(STDERR, "Failed to load Clover XML: {$cloverFile}\n");
exit(1);
}
$dir = dirname($out);
if ($dir !== '' && $dir !== '.' && !is_dir($dir)) {
mkdir($dir, 0777, true);
}
$fh = fopen($out, 'w');
foreach ($xml->xpath('//file') as $file) {
$path = (string) $file['name'];
$hits = [];
foreach ($file->line as $line) {
$type = (string) $line['type'];
if ($type !== 'stmt' && $type !== 'method') {
continue;
}
$num = (int) $line['num'];
$count = (int) $line['count'];
if (!isset($hits[$num]) || $count > $hits[$num]) {
$hits[$num] = $count;
}
}
if ($hits === []) {
continue;
}
ksort($hits, SORT_NUMERIC);
fwrite($fh, "TN:\n");
fwrite($fh, "SF:{$path}\n");
$lh = 0;
foreach ($hits as $num => $count) {
fwrite($fh, "DA:{$num},{$count}\n");
if ($count > 0) {
$lh++;
}
}
fwrite($fh, 'LF:' . count($hits) . "\n");
fwrite($fh, "LH:{$lh}\n");
fwrite($fh, "end_of_record\n");
}
fclose($fh);
}
test-suites.ymlを作り、ローカルで検証する
.circleci/test-suites.ymlを作りましょう。
---
name: phpunit tests
discover: find tests -type f -name '*Test.php'
run: php .circleci/phpunit-testsuite.php run "<< outputs.junit >>"
analysis: php .circleci/phpunit-testsuite.php analyze "<< outputs.lcov >>"
outputs:
junit: test-reports/junit.xml
options:
test-impact-analysis: true
store-test-results: true
test-selection-rules:
- test-atom: tests/DiscountDataTest.php
include:
- tests/fixtures/*.json
- test-atom: tests/PriceSharedTest.php
include:
- tests/Support/*.php
discoverはtest atomを列挙し、runは渡されたatomを実行してJUnit XMLを書き出します。Test Impact Analysis用に足すのがanalysisです。atomごとにLCOVを返し、optionsのtest-impact-analysis: trueで機能を有効にしてください。
上のtest-selection-rulesは、カバレッジに載らないfixturesと共有trait向けです。自分のプロジェクトでは次で宣言候補を洗い出し、ヒットしたテストごとに読み込み先をincludeへ書いてください。
grep -rlE "file_get_contents|json_decode|Yaml::parse" tests --include='*Test.php'
grep -rlE "^\s*use [A-Za-z]+Trait;" tests --include='*Test.php'
doctorで確かめる
設定を書いたらdoctorで確かめます。The CircleCI CLIを用意したうえでtestsuite拡張を入れ、analysis用にローカルPHPへPCOVも入れてください。
circleci extension install testsuite
pecl install pcov
php -m | grep -i pcov
circleci testsuite doctor "phpunit tests"
runとanalysisがsuccessなら設定は通っています。ログには選択されたatom数と実行コマンドが出ます。
checking run command can run discovered test atoms...
"output": "Ran 4 test atoms",
"state": "success"
checking analysis command can analyze test atoms...
"output": "4 test atoms are impacted by source files",
"state": "success"
CircleCI CLIで初回impact dataを作成する
CircleCI CLIでcircleci setupを実行し、Personal API Tokenを登録してください。Project Settings → OverviewのProject IDを<project-uuid>に置き換え、default branchをチェックアウトした状態で次を実行します。
circleci testsuite run "phpunit tests" \
--analyze-tests=impacted \
--project-id <project-uuid>
初回はimpact dataが無いので全atomが選ばれ、続けてanalysisが走る状態です。
Selecting tests...
Selecting all test atoms, no impact analysis available
Selected 4 test atoms, Skipped 0 test atoms
Running 4 test atoms
...
Analyzing 4 test atoms
Found 1 files impacting test tests/PriceTest.php
Found 1 files impacting test tests/PriceProviderTest.php
Found 1 files impacting test tests/PriceSharedTest.php
Found 1 files impacting test tests/DiscountDataTest.php
Updated test impact data in 0s
手元でTest Impact Analysisの選択を確認する
src/Price.phpに、計算結果を変えない次の変更を入れます。
public static function withTax(int $amount): int
{
- return (int) round($amount * 1.1);
+ return (int) round($amount * 1.1 + 0);
}
同じコマンドを再実行してください。
circleci testsuite run "phpunit tests" \
--analyze-tests=impacted \
--project-id <project-uuid>
ログでは、関係する3 atomだけが選ばれます。
3 test atoms impacted by modified files
Selected 3 test atoms, Skipped 1 test atoms in 2ms
選ばれるのはPrice::withTaxを呼ぶPriceTest、PriceProviderTest、PriceSharedTest(trait経由)です。DiscountDataTestだけがスキップされます。確認が終わったら変更を戻してください。
git checkout -- src/Price.php
fixtures変更でatomが選ばれることを確かめる
JSON fixturesの行を1つ足してください。noneの割引率は0.0なので、この行は失敗する内容です。
[
{"rank": "gold", "rate": 0.2},
- {"rank": "silver", "rate": 0.1}
+ {"rank": "silver", "rate": 0.1},
+ {"rank": "none", "rate": 0.5}
]
同じコマンドを再実行すると、include rule経由でDiscountDataTest.phpが選ばれます。
1 test atoms impacted by include rule
Selected 1 test atoms, Skipped 3 test atoms
確認が終わったら戻してください。
git checkout -- tests/fixtures/discount_cases.json
共有traitの変更でatomが選ばれることを確かめる
tests/Support/PriceTestTrait.phpに、結果を変えない次の変更を入れてください。
public function test1000円は税込1100円(): void
{
- $this->assertSame(1100, Price::withTax(1000));
+ $this->assertSame(1100, Price::withTax(1000) + 0);
}
同じコマンドを再実行すると、PriceSharedTest.phpが選ばれます。
1 test atoms impacted by include rule
Selected 1 test atoms, Skipped 3 test atoms in 0s
確認が終わったら戻してください。
git checkout -- tests/Support/PriceTestTrait.php
.circleci/config.ymlにtestsuite runを組み込む
CIのテスト実行はcircleci testsuite run "phpunit tests"に置き換えてください。JUnitの取り込みはstore-test-results: trueに任せるため、store_test_resultsステップは不要です。
version: 2.1
jobs:
test:
docker:
- image: cimg/php:8.3
steps:
- checkout
- run: |
sudo pecl install pcov
php -m | grep -i pcov
- run: composer install --no-interaction
- run: circleci testsuite run "phpunit tests"
workflows:
test:
jobs:
- test
cimg/phpにはPCOVが入っていないので、ジョブ内のsudo pecl install pcovが必要です(cimg/php の README)。
feature branchでは--analyze-testsの既定がnoneです。導入直後にanalysisも実行するなら、上のcircleci testsuite runに--analyze-tests=impactedを付けてください(ブランチ別のデフォルト)。
GitHubにpushしてCircleCIでtestsuite runを確認する
git add .
git commit -m "Enable PHPUnit Test Impact Analysis"
git push origin main
GitHub連携の手順はCircleCIをGitHubと連携してパイプラインを動かすも参照してください。ジョブログにはSelected N test atomsの行が出ます。
## circleci testsuite run "phpunit tests"
- Status: succeeded
Selected 4 test atoms, Skipped 0 test atoms in 1ms
Ran 4 test atoms in 246ms
## Uploading test results
- Status: succeeded
Archiving the following test results
* /home/circleci/project/test-reports/junit.xml
.circleci/config.ymlを新規追加した最初のpushでは、full-test-run-pathsにより全atomが実行されます。
Selecting all test atoms, 'full-test-run-paths' detected new file: .circleci/config.yml
Selected 4 test atoms, Skipped 0 test atoms in 1ms
まとめ
PHPUnitでTest Impact Analysisを使うには、JUnitとLCOVを返す.circleci/phpunit-testsuite.phpと、impact data用の.circleci/test-suites.ymlが必要です。カバレッジに載る依存なら、ソースを変えたときに関係するtest atomだけが選ばれます。
一方、JSON fixturesや共有traitへの依存はカバレッジだけでは残りません。選ばれない変更は、テストの読み込み先を辿ってtest-selection-rulesのincludeに書いてください。宣言のあとは、circleci testsuite runのログで意図したatomだけが選ばれているかを確認します。
