PHP | infection

PHPUnit で単体テストはやっているが、テスト項目に自信がなかったので infection を使ってみました。infection はソースコードにわざとバグを紛れ込ませることで、テスト項目の不備を見つけ出す仕組みらしい。バグを生成することを mutation と呼ぶらしいけど、時節柄、mutaion で検索すると変異株の話題ばかりで関連記事を探すのに苦労した。

インストール

Composer でインストールする。

1
# composer require --dev infection/infection

対話的に設定ファイルを作成する。

1
# vendor/bin/infection

色々聞かれるので答えていくと、カレンto
ディレクトリーに設定ファイル infection.json.dist が作成される。

1
2
3
4
5
6
7
8
9
10
11
12
13
{
"source": {
"directories": [
"app"
]
},
"logs": {
"text": "infection.log"
},
"mutators": {
"@default": true
}
}

infection を実行する

実行する前に、環境変数 XDEBUG_MODE を設定する。これを行わないと、実行時にエラーとして表示される。

1
# export XDEBUG_MODE=coverage

設定後に、infection を実行する。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# vendor/bin/infection

____ ____ __ _
/ _/___ / __/__ _____/ /_(_)___ ____
/ // __ \/ /_/ _ \/ ___/ __/ / __ \/ __ \
_/ // / / / __/ __/ /__/ /_/ / /_/ / / / /
/___/_/ /_/_/ \___/\___/\__/_/\____/_/ /_/

Infection - PHP Mutation Testing Framework version 0.21.0@dfacb1e3d9def7fd34c6fb8df4d4bd098815dc82


Running initial test suite...

PHPUnit version: 8.5.13

13 [============================] < 1 sec

Generate mutants...

Processing source code files: 13/13
.: killed, M: escaped, U: uncovered, E: fatal error, T: timed out, S: skipped

UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU ( 50 / 110)
UUUUUUUUUUU.MM...MM.MM.....MM.MM......MM.MM....... (100 / 110)
.......... (110 / 110)

110 mutations were generated:
35 mutants were killed
61 mutants were not covered by tests
14 covered mutants were not detected
0 errors were encountered
0 time outs were encountered
0 mutants required more time than configured

Metrics:
Mutation Score Indicator (MSI): 31%
Mutation Code Coverage: 44%
Covered Code MSI: 71%

Please note that some mutants will inevitably be harmless (i.e. false positives).

Time: 4s. Memory: 18.00MB

実行時に作成される infection.log を見ると、生成された Mutaion の内容を確認できる。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Escaped mutants:
================

1) /root/src/app/Strategy/RandomStrategy.php:6 [M] FunctionCallRemoval

--- Original
+++ New
@@ @@
{
public static function randomize(array $data) : array
{
- shuffle($data);
+
return $data;
}
}

内容を精査して Muation しているわけではないので無意味なものもあるらしいが、考慮不足をなくすために使えるかどうか利用してみたい。