概要
いつも忘れるので、以下自分用のメモです。
たまに、go test
の結果をプログラム側からいじりたいので json形式 で欲しいときがあります。
go test
には、-json
フラグがあるので、それを指定すると結果が JSON で取得できます。
(昔は、go tool test2json ってコマンドでやっていた記憶がありますが、現在は -json
があるので、test2json
を直接呼ぶことは無いですね)
たとえば、こんな感じになります。
gitpod /workspace/gomy (master) $ go test -json ./ctxs {"Time":"2022-08-16T10:27:03.469961409Z","Action":"run","Package":"github.com/devlights/gomy/ctxs","Test":"TestWhenAll"} {"Time":"2022-08-16T10:27:03.470091149Z","Action":"output","Package":"github.com/devlights/gomy/ctxs","Test":"TestWhenAll","Output":"=== RUN TestWhenAll\n"} {"Time":"2022-08-16T10:27:03.470107069Z","Action":"run","Package":"github.com/devlights/gomy/ctxs","Test":"TestWhenAll/100,200,300"} {"Time":"2022-08-16T10:27:03.470160369Z","Action":"output","Package":"github.com/devlights/gomy/ctxs","Test":"TestWhenAll/100,200,300","Output":"=== RUN TestWhenAll/100,200,300\n"} ・ ・ 割愛
このままだと見づらいので、基本は jq とか使って見やすくしますね。
gitpod /workspace/gomy (master) $ go test -json ./ctxs | jq . { "Time": "2022-08-16T10:28:17.512617308Z", "Action": "run", "Package": "github.com/devlights/gomy/ctxs", "Test": "TestWhenAll" } { "Time": "2022-08-16T10:28:17.512683788Z", "Action": "output", "Package": "github.com/devlights/gomy/ctxs", "Test": "TestWhenAll", "Output": "=== RUN TestWhenAll\n" } { "Time": "2022-08-16T10:28:17.512690738Z", "Action": "run", "Package": "github.com/devlights/gomy/ctxs", "Test": "TestWhenAll/100,200,300" } ・ ・ 割愛
フィールドの内容については、ヘルプに記載されています。
欲しいのが run
だけだったら、以下のようにします。
gitpod /workspace/gomy (master) $ go test -json ./ctxs | jq 'select( .Action == "run" )' { "Time": "2022-08-16T10:30:35.110910545Z", "Action": "run", "Package": "github.com/devlights/gomy/ctxs", "Test": "TestWhenAll" } { "Time": "2022-08-16T10:30:35.111099634Z", "Action": "run", "Package": "github.com/devlights/gomy/ctxs", "Test": "TestWhenAll/100,200,300" } { "Time": "2022-08-16T10:30:35.111110865Z", "Action": "run", "Package": "github.com/devlights/gomy/ctxs", "Test": "TestWhenAll/100,500" } { "Time": "2022-08-16T10:30:35.111147514Z", "Action": "run", "Package": "github.com/devlights/gomy/ctxs", "Test": "TestWhenAny" } { "Time": "2022-08-16T10:30:35.111154485Z", "Action": "run", "Package": "github.com/devlights/gomy/ctxs", "Test": "TestWhenAny/100,200,300" } { "Time": "2022-08-16T10:30:35.111161814Z", "Action": "run", "Package": "github.com/devlights/gomy/ctxs", "Test": "TestWhenAny/100,500" } { "Time": "2022-08-16T10:30:35.111190945Z", "Action": "run", "Package": "github.com/devlights/gomy/ctxs", "Test": "ExampleToDoneCh" } { "Time": "2022-08-16T10:30:35.111204574Z", "Action": "run", "Package": "github.com/devlights/gomy/ctxs", "Test": "ExampleWhenAll" } { "Time": "2022-08-16T10:30:35.111220494Z", "Action": "run", "Package": "github.com/devlights/gomy/ctxs", "Test": "ExampleWhenAny" }
参考情報
過去の記事については、以下のページからご参照下さい。
サンプルコードは、以下の場所で公開しています。