何を「分岐」として集めるか
C1 で通すべき判定は、構文木のノードでいえば次の5種類だ。ノード名は tree-sitter-java 0.23.5 のもので、調べ方は tree-sitter シリーズ PART 03 で説明している。
| kind | ノード | 結果 | 補足 |
|---|---|---|---|
if | if_statement | true / false | else if は else 側に入れ子の if_statement がある形なので、別の判定として数える |
ternary | ternary_expression | true / false | 式の途中にも現れる |
switch | switch_expression | case ごと+default | 文の switch も、矢印(->)の switch も同じノード |
loop | for_statement / enhanced_for_statement / while_statement / do_statement | 1回以上 / 0回 | do-while の「0回」は実際にはありえない |
catch | catch_clause | 例外なし / catch | JaCoCo は分岐として数えないが、テストでは通したい |
逆に、次のものは集めない。
- ラムダ式と匿名クラスの中:
list.forEach(x -> { if (...) ... })の if は、外側のメソッドとは別の単位として呼ばれる。外側のテストから狙って通すのは難しいので対象外にする - ライブラリの中の分岐:
Optional.orElseやObjects.requireNonNullElseの中身はソースにないので見えない
もう1つ大事なのが && と || だ。customerId == null || customerId.isBlank() は if としては1つの判定だが、2つの条件(ここでは アトム と呼ぶ)からできている。短絡評価があるので、どのアトムまで評価されるかで経路が変わる。分岐表にはアトムの数も入れておき、PART 05 で組み合わせを作るときに使う。
if_statement の中身を確かめる
cancelOrder の if (found.isEmpty()) { return false; } を S 式で表示すると、次のようになる(str(node) の出力)。
(if_statement
condition: (parenthesized_expression
(method_invocation object: (identifier) name: (identifier) arguments: (argument_list)))
consequence: (block
(return_statement (false))))条件は condition、true 側は consequence、false 側は alternative フィールドで取れる。この if には else がないので alternative は None になる。true 側のブロックが return_statement で終わっているので「true のときはメソッドを抜ける」とわかる。この情報が、PART 05 で主経路(抜けない側)を選ぶ根拠になる。
分岐表を作るスクリプト
tree-sitter シリーズの共通モジュール ts_common.py(PART 02 で作成)を同じフォルダに置いて使う。
"""メソッドごとに分岐(判定)を抽出し、分岐表を CSV / JSON で出力する"""
import csv
import json
import sys
from dataclasses import dataclass, asdict
from ts_common import parse_file, text
LOOP_NODES = {"for_statement", "enhanced_for_statement", "while_statement", "do_statement"}
@dataclass
class Branch:
id: str # B1, B2 ...(メソッド内の出現順)
method: str
line: int # 1 始まり
kind: str # if / ternary / switch / loop / catch
condition: str
outcomes: list # 取りうる結果
atoms: int # && / || で分かれた条件の数
exits: list # 結果ごとに、その先で return / throw するか
def atoms_of(expr):
"""&& / || で結ばれた条件を、末端の条件(アトム)に分解する"""
if expr.type == "parenthesized_expression":
return atoms_of(expr.named_children[0])
if expr.type == "binary_expression" and expr.child_by_field_name("operator").type in ("&&", "||"):
return atoms_of(expr.child_by_field_name("left")) + atoms_of(expr.child_by_field_name("right"))
return [expr]
def ends_with_exit(node):
"""ブロックや文が return / throw で終わるか(途中で抜けるか)"""
if node is None:
return False
if node.type in ("return_statement", "throw_statement"):
return True
if node.type in ("block", "switch_block_statement_group"):
stmts = [c for c in node.named_children if c.type not in ("line_comment", "block_comment", "switch_label")]
return bool(stmts) and ends_with_exit(stmts[-1])
if node.type == "if_statement":
alt = node.child_by_field_name("alternative")
return ends_with_exit(node.child_by_field_name("consequence")) and ends_with_exit(alt)
return False
def switch_outcomes(node):
"""switch の case ごとに (ラベル, 本体) を返す。本体のない case(フォールスルー)は次の case にまとめ、
default が無ければ補う"""
result, pending = [], []
for rule in node.child_by_field_name("body").named_children:
if rule.type not in ("switch_rule", "switch_block_statement_group"):
continue
labels = [c for c in rule.named_children if c.type == "switch_label"]
names = pending + [text(v) for lab in labels for v in lab.named_children]
if any(not lab.named_children for lab in labels):
names.append("default")
stmts = [c for c in rule.named_children if c.type != "switch_label"]
if not stmts:
pending = names
continue
pending = []
body = stmts[0] if rule.type == "switch_rule" else rule
result.append((",".join(names), body))
if not any("default" in n.split(",") for n, _ in result):
result.append(("default", None))
return result
def extract(method_node):
name = text(method_node.child_by_field_name("name"))
branches = []
def add(kind, node, cond, outcomes, atoms, exits):
branches.append(Branch(f"B{len(branches) + 1}", name, node.start_point[0] + 1,
kind, cond, outcomes, atoms, exits))
def walk(node):
t = node.type
if t == "if_statement":
cond = node.child_by_field_name("condition")
add("if", node, text(cond), ["true", "false"], len(atoms_of(cond)),
[ends_with_exit(node.child_by_field_name("consequence")),
ends_with_exit(node.child_by_field_name("alternative"))])
elif t == "ternary_expression":
cond = node.child_by_field_name("condition")
add("ternary", node, text(cond), ["true", "false"], len(atoms_of(cond)), [False, False])
elif t == "switch_expression":
outs = switch_outcomes(node)
add("switch", node, text(node.child_by_field_name("condition")),
[n for n, _ in outs], 1, [ends_with_exit(b) for _, b in outs])
elif t in LOOP_NODES:
head = node.child_by_field_name("condition") or node.child_by_field_name("value")
add("loop", node, text(head) if head else "", ["1回以上", "0回"], 1, [False, False])
elif t == "catch_clause":
ctype = node.named_children[0].child_by_field_name("type") or node.named_children[0]
add("catch", node, text(ctype).split()[0], ["例外なし", "catch"], 1, [False, False])
for child in node.named_children:
if child.type not in ("lambda_expression", "class_body"): # ラムダ・匿名クラスの中は対象外
walk(child)
walk(method_node.child_by_field_name("body"))
return branches
def extract_file(path):
_, tree = parse_file(path)
result = []
stack = [tree.root_node]
while stack:
node = stack.pop()
if node.type in ("method_declaration", "constructor_declaration") and node.child_by_field_name("body"):
result.extend(extract(node))
stack.extend(reversed(node.named_children))
return result
if __name__ == "__main__":
rows = extract_file(sys.argv[1])
with open("branches.json", "w", encoding="utf-8") as f:
json.dump([asdict(b) for b in rows], f, ensure_ascii=False, indent=2)
with open("branches.csv", "w", encoding="utf-8-sig", newline="") as f:
w = csv.writer(f)
w.writerow(["method", "id", "line", "kind", "condition", "outcomes", "atoms", "exits"])
for b in rows:
w.writerow([b.method, b.id, b.line, b.kind, b.condition,
" / ".join(b.outcomes), b.atoms, " / ".join("exit" if e else "-" for e in b.exits)])
for b in rows:
print(f"{b.method:12} {b.id:3} L{b.line:<3} {b.kind:8} {b.condition:42} {b.outcomes} atoms={b.atoms}")要所を3つ説明する。
atoms_of:&& と || を分解する
二項演算子のうち && と || だけを左右に分解し、それ以外(== や <、メソッド呼び出しなど)をアトムとして返す。かっこ(parenthesized_expression)は外して中を見る。a || (b && c) は3つのアトムになる。
ends_with_exit:その先で抜けるか
ブロックの最後の文が return か throw なら「抜ける」と判定する。if / else の両方が抜けるなら、その if 文全体も抜けるものとして扱う。途中の return まで追うと複雑になるので、「最後の文」だけを見る割り切りにしている。PART 02 の題材なら、これで足りる。
switch_outcomes:case をまとめ、default を補う
従来の書き方の case 1: case 2: ... は、tree-sitter では本体のない switch_block_statement_group が並ぶ形になる。本体のない case は次の case にまとめて 1,2 という1つの結果にする。default が書かれていない switch にも「どの case にも当たらない」経路はあるので、結果の一覧に default を補う。
⚠️ break のないフォールスルーは追わない
case 1: a(); case 2: b(); break; のように、本体があるのに break で終わらない case は、次の case の本体まで続けて実行される。このスクリプトは case ごとに本体を分けて扱うので、この流れは表現できない。意図的なフォールスルーはまれなので、見つけたら手で確認する前提にしている。
OrderService の分岐表
python branches.py ../src/main/java/com/example/order/OrderService.javaplaceOrder B1 L24 if (customerId == null || customerId.isBlank()) ['true', 'false'] atoms=2
placeOrder B2 L27 if (lines.isEmpty()) ['true', 'false'] atoms=1
placeOrder B3 L31 loop lines ['1回以上', '0回'] atoms=1
placeOrder B4 L33 if (stock < line.quantity()) ['true', 'false'] atoms=1
placeOrder B5 L38 ternary order.total() >= 10000 ['true', 'false'] atoms=1
placeOrder B6 L42 catch MailException ['例外なし', 'catch'] atoms=1
cancelOrder B1 L50 if (found.isEmpty()) ['true', 'false'] atoms=1
cancelOrder B2 L54 switch (order.getStatus()) ['NEW,PAID', 'SHIPPED', 'default'] atoms=1同時に出力される branches.csv は Excel でそのまま開ける(BOM 付き UTF-8)。exits 列は、結果ごとにその先で抜けるかを表す。
method,id,line,kind,condition,outcomes,atoms,exits
placeOrder,B1,24,if,(customerId == null || customerId.isBlank()),true / false,2,exit / -
placeOrder,B2,27,if,(lines.isEmpty()),true / false,1,exit / -
placeOrder,B3,31,loop,lines,1回以上 / 0回,1,- / -
placeOrder,B4,33,if,(stock < line.quantity()),true / false,1,exit / -
placeOrder,B5,38,ternary,order.total() >= 10000,true / false,1,- / -
placeOrder,B6,42,catch,MailException,例外なし / catch,1,- / -
cancelOrder,B1,50,if,(found.isEmpty()),true / false,1,exit / -
cancelOrder,B2,54,switch,(order.getStatus()),"NEW,PAID / SHIPPED / default",1,- / exit / exitPART 02 で手で書き出した8つの判定と一致した。行番号も、JaCoCo のレポートで分岐が数えられていた行(24・27・31・33・38・50・54)と同じだ。catch だけは catch キーワードの行(42)になる。JaCoCo は catch を分岐として数えないので、PART 07 では catch 本体の行のカバレッジで確かめる。
else if の連鎖と && を含む例
PART 08 で使うもう1つの題材 PointService(会員ランクとキャンペーンでポイントを計算するサービス)でも試しておく。中心になるメソッドは次のとおり。
public int calcPoints(String memberId, int amount, boolean usesCard) {
if (amount <= 0) {
return 0;
}
int points = amount / 100;
Rank rank = memberRepository.findRank(memberId);
if (rank == Rank.GOLD) {
points = points * 2;
} else if (rank == Rank.SILVER) {
points = points * 3 / 2;
}
if (usesCard && campaignClient.isActive("CARD2026")) {
points += 50;
}
return points;
}calcPoints B1 L20 if (amount <= 0) ['true', 'false'] atoms=1
calcPoints B2 L25 if (rank == Rank.GOLD) ['true', 'false'] atoms=1
calcPoints B3 L27 if (rank == Rank.SILVER) ['true', 'false'] atoms=1
calcPoints B4 L30 if (usesCard && campaignClient.isActive("CARD2026")) ['true', 'false'] atoms=2
grant B1 L38 loop amounts ['1回以上', '0回'] atoms=1
grant B2 L41 if (total > MAX_POINTS_PER_GRANT) ['true', 'false'] atoms=1
grant B3 L44 if (total > 0) ['true', 'false'] atoms=1else if は B2 の false 側にある別の if(B3)として現れる。B3 は B2 が false のときしか評価されないので、B3 を通すテストは「B2 が false」になる入力も持っていなければならない。こうした 判定どうしの前後関係 は分岐表には書かれていない。PART 05 で、メソッドを先頭からたどりながら解決する。
分岐表でわかること・わからないこと
| わかること | わからないこと(PART 05 で扱う) |
|---|---|
| 判定の数と種類、行番号 | 判定どうしの前後関係(どの判定を通ってから来るか) |
アトムの数(&& / || の組み合わせの多さ) | 各アトムを true / false にする具体的な値 |
| 結果ごとに抜けるか(主経路を選ぶ手がかり) | その結果に、そもそも到達できるか(for の 0 回など) |
| switch の case の一覧 | enum の定数のうち case にないもの(default 用の値) |
表の右側を埋めるには、条件式に出てくる名前が「引数なのか、モックの戻り値なのか、ローカル変数なのか」を知る必要がある。その前提として、まずテスト対象クラスの外部依存を整理する。
✅ 次の記事では…
PART 04 では、テスト対象クラスのコンストラクタ引数を調べ、どれをモックにし、どれを固定値や実物で渡すかを自動で決める。