🚗

go-gremlinsを使ったミューテーションテストを試してみる

に公開

はじめに

Go Weeklyでgo-gremlinsというツールが紹介されており、名前に惹かれて調べてみました。
go-gremlinsはGo向けに作られたOSSのミューテーションテストツールです。
https://gremlins.dev/latest/

ミューテーションテストとは?

ミューテーションテストとは、実行されるコードの中にミュータント(意図的に変異させたバグ)を仕込み、作成済みのテストケースでミュータントを検出できるかどうか確かめるテストです。テストの品質を評価するために使用されます。

go-gremlinsの使い方

インストールとツール実行はシンプルです。

# インストール
go install github.com/go-gremlins/gremlins/cmd/gremlins@v0.6.0

# ツール実行 
gremlins unleash [実行対象のディレクトリpath]

※brew installや公式のDocker imageを使った実行もできます。詳しくは下記をご覧ください。
https://gremlins.dev/latest/install/

ツールを実行すると、テストケースでカバーされたコード上の算術演算子や比較演算子などが変異し、ミューテーションテストの結果が出力されます。

例えば、算術演算子では下記のように変異します。

元のコード 変異後
+ -
- +
* /
/ *
% *

実際にツール実行する

実際にコードを使って試していきます。

サンプルコード

単純な四則演算の関数と、それらに対応するテストコードを書いています。

calc.go
package calc

import "errors"

// Add returns the sum of a and b
func Add(a, b int) int {
	return a + b
}

// Subtract returns the difference of a and b
func Subtract(a, b int) int {
	return a - b
}

// Multiply returns the product of a and b
func Multiply(a, b int) int {
	return a * b
}

// Divide returns the quotient of a divided by b
func Divide(a, b int) (int, error) {
	if b == 0 {
		return 0, errors.New("division by zero")
	}
	return a / b, nil
}
calc_test.go
package calc

import (
	"testing"
)

func TestAddition(t *testing.T) {
	tests := []struct {
		name string
		a    int
		b    int
		want int
	}{
		{name: "100 + 0", a: 100, b: 0, want: 100},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			result := Add(tt.a, tt.b)
			if result != tt.want {
				t.Errorf("Add(%v, %v) = %v, want %v", tt.a, tt.b, result, tt.want)
			}
		})
	}
}

func TestSubtraction(t *testing.T) {
	tests := []struct {
		name string
		a    int
		b    int
		want int
	}{
		{name: "30 - 0", a: 30, b: 0, want: 30},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			result := Subtract(tt.a, tt.b)
			if result != tt.want {
				t.Errorf("Subtract(%v, %v) = %v, want %v", tt.a, tt.b, result, tt.want)
			}
		})
	}
}

func TestDivide(t *testing.T) {
	tests := []struct {
		name    string
		a       int
		b       int
		want    int
		wantErr bool
	}{
		{name: "10 / 2", a: 10, b: 2, want: 5, wantErr: false},
		{name: "10 / 0 (error)", a: 10, b: 0, want: 0, wantErr: true},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got, err := Divide(tt.a, tt.b)

			if tt.wantErr {
				if err == nil {
					t.Errorf("Divide(%v, %v) expected error but got nil", tt.a, tt.b)
				}
				return
			}

			if err != nil {
				t.Errorf("Divide(%v, %v) unexpected error: %v", tt.a, tt.b, err)
				return
			}

			if got != tt.want {
				t.Errorf("Divide(%v, %v) = %v, want %v", tt.a, tt.b, got, tt.want)
			}
		})
	}
}

Gremlinsの実行結果

実行結果
$ gremlins unleash --workers=1 ./calc
# TIMED OUTが頻発するため--workersを1に指定している。
#参考:https://gremlins.dev/latest/usage/commands/unleash/workers/?h=timed+out

Starting...
Gathering coverage... go: no module dependencies to download
done in 478.479333ms
       LIVED ARITHMETIC_BASE at calc.go:7:11
       LIVED INVERT_NEGATIVES at calc.go:12:11
       LIVED ARITHMETIC_BASE at calc.go:12:11
 NOT COVERED ARITHMETIC_BASE at calc.go:17:11
      KILLED CONDITIONALS_NEGATION at calc.go:22:7
      KILLED ARITHMETIC_BASE at calc.go:25:11

Mutation testing completed in 1 second 904 milliseconds
Killed: 2, Lived: 3, Not covered: 1
Timed out: 0, Not viable: 0, Skipped: 0
Test efficacy: 40.00%
Mutator coverage: 83.33%

実行したところ、Killed: 2, Lived: 3, Not covered: 1, Timed out: 0, Not viable: 0, Skipped: 0 という結果になりました。

Killedはミュータントによってテストが通らなかったことを意味します。つまり、意図しない変更をテストによって検知できている望ましい状態です。

Livedはミュータントが存在してもテストが通ってしまった望ましくない状態を意味します。

Not coveredはミューテーションされる箇所がテストケースでカバーされていないことを意味しています。

どこでlived,not coveredになってる?

例えばLIVED ARITHMETIC_BASE at calc.go:7:11を見てみます。
7行目はAdd関数を定義している行なので、もう一度addの実装およびテストコードを見ると、
現在100+0のみのテストケースが用意されています。
ARITHMETIC_BASEと出ているように算術演算子の変異によるlivedなので、
「return a + bがreturn a - bになってもテストケース通ってるよ!」ということになります。
確かに100 + 0も100 - 0も結果は100になるので納得です。

// Add returns the sum of a and b
func Add(a, b int) int {
	return a + b
}
func TestAddition(t *testing.T) {
	tests := []struct {
		name string
		a    int
		b    int
		want int
	}{
		{name: "100 + 0", a: 100, b: 0, want: 100},
		// {name: "1 + 1", a: 1, b: 1, want: 2},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			result := Add(tt.a, tt.b)
			if result != tt.want {
				t.Errorf("Add(%v, %v) = %v, want %v", tt.a, tt.b, result, tt.want)
			}
		})
	}
}

また、Not Coveredについては掛け算のテストをそもそも作っていないことが原因です。

テストケースを修正してリトライ

上記実行結果を踏まえてテストケースを修正しました。

package calc

import (
	"testing"
)

func TestAddition(t *testing.T) {
	tests := []struct {
		name string
		a    int
		b    int
		want int
	}{
		{name: "100 + 0", a: 100, b: 0, want: 100},
		{name: "1 + 1", a: 1, b: 1, want: 2}, // 追加
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			result := Add(tt.a, tt.b)
			if result != tt.want {
				t.Errorf("Add(%v, %v) = %v, want %v", tt.a, tt.b, result, tt.want)
			}
		})
	}
}

func TestSubtraction(t *testing.T) {
	tests := []struct {
		name string
		a    int
		b    int
		want int
	}{
		{name: "30 - 0", a: 30, b: 0, want: 30},
		{name: "30 - 1", a: 30, b: 1, want: 29}, // 追加
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			result := Subtract(tt.a, tt.b)
			if result != tt.want {
				t.Errorf("Subtract(%v, %v) = %v, want %v", tt.a, tt.b, result, tt.want)
			}
		})
	}
}

// 追加
func TestMultiply(t *testing.T) {
	tests := []struct {
		name string
		a    int
		b    int
		want int
	}{
		{name: "1 * 1", a: 1, b: 1, want: 1},
		{name: "2 * 5", a: 2, b: 5, want: 10},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			result := Multiply(tt.a, tt.b)
			if result != tt.want {
				t.Errorf("Multiply(%v, %v) = %v, want %v", tt.a, tt.b, result, tt.want)
			}
		})
	}
}

func TestDivide(t *testing.T) {
	tests := []struct {
		name    string
		a       int
		b       int
		want    int
		wantErr bool
	}{
		{name: "10 / 2", a: 10, b: 2, want: 5, wantErr: false},
		{name: "10 / 0 (error)", a: 10, b: 0, want: 0, wantErr: true},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got, err := Divide(tt.a, tt.b)

			if tt.wantErr {
				if err == nil {
					t.Errorf("Divide(%v, %v) expected error but got nil", tt.a, tt.b)
				}
				return
			}

			if err != nil {
				t.Errorf("Divide(%v, %v) unexpected error: %v", tt.a, tt.b, err)
				return
			}

			if got != tt.want {
				t.Errorf("Divide(%v, %v) = %v, want %v", tt.a, tt.b, got, tt.want)
			}
		})
	}
}

無事ミュータントを全部倒すことができました。

実行結果(2回目)
gremlins unleash --workers=1 ./calc

Starting...
Gathering coverage... go: no module dependencies to download
done in 942.662834ms
      KILLED ARITHMETIC_BASE at calc.go:7:11
      KILLED INVERT_NEGATIVES at calc.go:12:11
      KILLED ARITHMETIC_BASE at calc.go:12:11
      KILLED ARITHMETIC_BASE at calc.go:17:11
      KILLED CONDITIONALS_NEGATION at calc.go:22:7
      KILLED ARITHMETIC_BASE at calc.go:25:11

Mutation testing completed in 2 seconds 705 milliseconds
Killed: 6, Lived: 0, Not covered: 0
Timed out: 0, Not viable: 0, Skipped: 0
Test efficacy: 100.00%
Mutator coverage: 100.00%

go-gremlinsを使ってみて

コマンド1つでテストの品質を確認できるのは嬉しいです!

一方で、ミューテーションテストの並列実行はサポートしているものの、実行に時間がかかるので例えばCIに組み込む場合は工夫がいるなと思いました。

また、バージョンがまだv0.x.xで、下位互換性は保証されていないとのことですが、直近でアップデートされているので今後のアップデートに注目していきます!

Discussion