Reject out-of-range endgame FENs at entry (#25)

Add FEN.piece_count/1 and reject positions with more than 7 pieces in the Endgame changeset, so an 8+ piece FEN fails at entry instead of saving and then blocking at play.

Accumulate all FEN issues rather than letting a later check overwrite an earlier one, and guard the seed FENs with a test (dropping the out-of-range seed that bypassed the changeset).
This commit is contained in:
2026-11-03 12:18:22 +01:00
parent dd060531d3
commit ff7adcf308
6 changed files with 128 additions and 10 deletions
+24
View File
@@ -115,6 +115,30 @@ defmodule Chesstrainer.EndgamesTest do
assert [msg] = errors_on(changeset).fen
assert msg =~ "active color"
end
test "rejects a FEN with more than 7 pieces" do
attrs = %{
fen: "3k4/2n2B2/1KP5/2B2p2/5b1p/7P/8/8 b - - 0 1",
color: :black,
result: :win,
rating: 1500
}
assert {:error, changeset} = Endgames.create_endgame(attrs)
assert [msg] = errors_on(changeset).fen
assert msg =~ "more than 7 pieces"
end
test "accepts a FEN with exactly 7 pieces" do
attrs = %{
fen: "6k1/5p2/6p1/8/7p/8/6PP/6K1 b - - 0 1",
color: :black,
result: :win,
rating: 1500
}
assert {:ok, %Endgame{}} = Endgames.create_endgame(attrs)
end
end
describe "themes" do
+23
View File
@@ -59,4 +59,27 @@ defmodule Chesstrainer.FENTest do
assert FEN.normalize(fen) == fen
end
end
describe "piece_count/1" do
test "counts kings and pieces, ignoring empty squares and slashes" do
assert FEN.piece_count("8/8/3k4/8/8/3K1R2/8/8 w - - 0 1") == 3
end
test "counts a full seven-piece position" do
assert FEN.piece_count("6k1/5p2/6p1/8/7p/8/6PP/6K1 b - - 0 0") == 7
end
test "counts a position beyond the tablebase range" do
assert FEN.piece_count("3k4/2n2B2/1KP5/2B2p2/5b1p/7P/8/8 b - - 0 1") == 10
end
test "counts a board field without clocks" do
assert FEN.piece_count("8/8/3k4/8/8/3K1R2/8/8") == 3
end
test "returns nil for a malformed board" do
assert FEN.piece_count("not a fen") == nil
assert FEN.piece_count(nil) == nil
end
end
end
+24
View File
@@ -0,0 +1,24 @@
defmodule Chesstrainer.SeedsTest do
use ExUnit.Case, async: true
alias Chesstrainer.FEN
Code.require_file("../../priv/repo/seeds/endgames.ex", __DIR__)
describe "seed endgames" do
test "are normalised and within tablebase range" do
for endgame <- Chesstrainer.Repo.Seeds.Endgames.all() do
fen = FEN.normalize(endgame.fen)
assert length(String.split(fen, " ")) == 6,
"seed FEN must have 6 fields: #{endgame.fen}"
refute String.ends_with?(fen, " 0"),
"seed FEN keeps fullmove 0 after normalisation: #{endgame.fen}"
assert FEN.piece_count(fen) <= 7,
"seed FEN has more than 7 pieces: #{endgame.fen}"
end
end
end
end