In this section
- Test Board test · cosmic / tools/explore/chess/test_board.py lines 1–189
- Test No Tmp test · cosmic / tools/explore/chess/test_no_tmp.py lines 1–74
- Test Page test · cosmic / tools/explore/chess/test_page.py lines 1–115
- Test Rules test · cosmic / tools/explore/chess/test_rules.py lines 1–259
Test Board
A test in the chess folder of Cosmic that checks Board and Rules. It checks schema (`check_schema`), sets up (`setUp`) and sets up class (`setUpClass`).
testcosmic / tools/explore/chess/test_board.py · lines 1–189 of 189 · Entry point · pattern synthetic_graph (shared by 2 files)
- What it does
- It tests its inputs. Defines 15 functions or classes, including synthetic_graph, check_schema, Synthetic, setUp, test_label_propagation_ignores_comment_url. Uses libraries json, os, sys, tempfile, unittest. Side effects: reads or writes files.
- Inputs & outputs
- In: JSON file communities.json; JSON file g.json; JSON file board.json. Out: JSON file.
- Downstream impact
- Used directly by 1 file: Test No Tmp (cosmic).
- What it achieves
- Tests for `chess/board.py` (unittest, no network).
- Why it matters
- Checked by Test No Tmp.
- Application
- cosmic · tools/explore/chess · test
- Uses
- Board (import), Rules (import), json, os, sys, tempfile, unittest
- Used by
- imported by Test No Tmp (import)
- Produces
- synthetic_graph, check_schema, Synthetic, RealGraph
- Defines here
- synthetic_graph, check_schema, Synthetic, setUp, test_label_propagation_ignores_comment_url, test_schema_and_rules, test_metrics_from_evidence, test_deterministic, test_lab_overlay_used_only_when_matching, test_too_few_communities, test_main_writes_file, RealGraph, setUpClass, test_computed, test_lab
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 tools/explore/chess/test_board.py:1-189 · blob eca443201b09a3ae23cc9dcbd3230c407f42fbcb · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: unknown · users: none · canonical: unknown
#!/usr/bin/env python3
"""Tests for chess/board.py (unittest, no network). Run: python -m unittest tools/explore/chess/test_board.py
Synthetic build graphs exercise the rules; the real build_graph.json (and the lab overlay) are used
when present on this machine, otherwise those tests are skipped.
"""
import json
import os
import sys
import tempfile
import unittest
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import board as B # noqa: E402
import rules as R # noqa: E402
TYPES = {'king': 1, 'queen': 1, 'rook': 2, 'bishop': 2, 'knight': 2, 'pawn': 8}
KEYS = ['id', 'side', 'type', 'square', 'community', 'label', 'size', 'lines', 'repos', 'role', 'centrality',
'reach', 'unique', 'files', 'why']
def synthetic_graph(n_comm=40):
"""n_comm chains of files; community k has 3 + (n_comm - k) files, lives in repo 'core' when k is even.
Every chain's last file imports the hub file 0 of community 0 (making it central); comment-url edges
that would merge everything are added and must be ignored."""
files, edges = [], []
heads = []
for k in range(n_comm):
size = 3 + (n_comm - k)
start = len(files)
heads.append(start)
word = 'alpha%s' % chr(97 + k % 26) + chr(97 + k // 26)
for j in range(size):
files.append({'id': len(files), 'repo': 'core' if k % 2 == 0 else 'side%d' % k, 'lines': 10 + j,
'role': 'render' if j % 3 else 'test', 'reachable': j % 4 != 0,
'canonical_status': 'duplicate_candidate' if j == 1 else 'unknown',
'name_words': ['tools', word, 'v%d' % j, 'widget', 'index']})
if j:
edges.append([start + j, start + j - 1, 'import', ''])
if j > 1:
edges.append([start + j, start + j - 2, 'script-src', ''])
if k:
edges.append([len(files) - 1, 0, 'import', ''])
files.append({'id': len(files), 'repo': 'side1', 'lines': 1, 'role': 'other', 'reachable': False,
'canonical_status': 'unknown', 'name_words': []}) # isolated: no community
for k in range(1, n_comm):
edges.append([heads[k], heads[k - 1], 'comment-url', 'url'])
return {'cut': 'test-cut', 'files': files, 'edges': edges,
'repos': [{'repo': 'core', 'core': True}] + [{'repo': 'side%d' % k, 'core': False} for k in range(n_comm)]}
def check_schema(tc, board):
tc.assertEqual(board['schema'], 'explore-chess-board-v1')
tc.assertEqual(board['rules_version'], R.RULES_VERSION)
tc.assertEqual(set(board['sides']), {'white', 'black'})
pieces = board['pieces']
tc.assertEqual(len(pieces), 32)
start = R.start_piece_ids()
tc.assertEqual({p['square']: p['id'] for p in pieces}, start)
tc.assertEqual(len({p['community'] for p in pieces}), 32)
for side in ('white', 'black'):
mine = [p for p in pieces if p['side'] == side]
tc.assertEqual(len(mine), 16)
tc.assertEqual({t: sum(1 for p in mine if p['type'] == t) for t in TYPES}, TYPES)
for p in mine:
tc.assertEqual(p['id'][0], side[0])
tc.assertEqual(R.Board().piece_at(p['square']), (side, p['type']))
king = [p for p in mine if p['type'] == 'king'][0]
queen = [p for p in mine if p['type'] == 'queen'][0]
tc.assertEqual(king['centrality'], max(p['centrality'] for p in mine))
tc.assertEqual(queen['size'], max(p['size'] for p in mine if p is not king))
rest = sorted((p for p in mine if p['type'] not in ('king', 'queen')),
key=lambda p: (1, B.PAWN_FILES.index(p['square'][0])) if p['type'] == 'pawn'
else (0, 'ahcfbg'.index(p['square'][0])))
cs = [p['centrality'] for p in rest]
tc.assertEqual(cs, sorted(cs, reverse=True))
for p in pieces:
tc.assertEqual(list(p), KEYS)
for k in ('centrality', 'reach', 'unique'):
tc.assertTrue(0 <= p[k] <= 1, (k, p[k]))
tc.assertTrue(0 < len(p['files']) <= 200)
tc.assertLessEqual(len(p['files']), p['size'])
tc.assertTrue(p['label'] and p['why'] and '\n' not in p['why'])
tc.assertTrue(p['why'].startswith(p['type'].capitalize()))
tc.assertEqual(len({p['label'] for p in pieces}), 32)
white_core = set(p['community'] for p in pieces if p['side'] == 'white')
tc.assertEqual(len(white_core), 16)
tc.assertTrue(all(r['community'] not in {p['community'] for p in pieces} for r in board['reserve']))
class Synthetic(unittest.TestCase):
def setUp(self):
self.g = synthetic_graph()
def test_label_propagation_ignores_comment_url(self):
col = B.label_propagation(len(self.g['files']), B.edge_lists(self.g))
self.assertEqual(col[-1], -1)
arcs = set(B.edge_lists(self.g))
for e in self.g['edges']:
if e[2] == 'comment-url':
self.assertNotIn((e[0], e[1]), arcs)
self.assertEqual(len({c for c in col if c >= 0}), 40) # one community per chain
def test_schema_and_rules(self):
board = B.build_board(self.g, lab_path='')
self.assertEqual(board['communities_source'], 'computed')
check_schema(self, board)
# white = higher core share: the core repo holds the even communities
for p in board['pieces']:
if p['side'] == 'white':
self.assertEqual(p['repos'], ['core'])
def test_metrics_from_evidence(self):
board = B.build_board(self.g, lab_path='')
files = self.g['files']
for p in board['pieces']:
members = [f for f in files if f['id'] in set(p['files'])]
self.assertTrue(all(f['repo'] in p['repos'] for f in members))
if len(p['files']) == p['size']:
self.assertEqual(p['lines'], sum(f['lines'] for f in members))
self.assertAlmostEqual(p['reach'], round(sum(f['reachable'] for f in members) / p['size'], 4))
self.assertAlmostEqual(p['unique'], round(sum(f['canonical_status'] != 'duplicate_candidate'
for f in members) / p['size'], 4))
self.assertNotIn('index', p['label'].lower().split())
self.assertFalse(any(w.startswith('v') and w[1:].isdigit() for w in p['label'].lower().replace(',', '').split()))
def test_deterministic(self):
a = json.dumps(B.build_board(self.g, lab_path=''), sort_keys=True)
b = json.dumps(B.build_board(synthetic_graph(), lab_path=''), sort_keys=True)
self.assertEqual(a, b)
def test_lab_overlay_used_only_when_matching(self):
n = len(self.g['files'])
col = B.label_propagation(n, B.edge_lists(self.g))
lab = {'schema': 'explore-lab-overlay-v1', 'exp': 'communities', 'cut': 'test-cut', 'n': n,
'cols': {'c': [c + 100 if c >= 0 else -1 for c in col]}}
with tempfile.TemporaryDirectory() as d:
path = os.path.join(d, 'communities.json')
with open(path, 'w') as fh:
json.dump(lab, fh)
board = B.build_board(self.g, lab_path=path)
self.assertEqual(board['communities_source'], 'lab')
self.assertTrue(all(p['community'] >= 100 for p in board['pieces']))
lab['cut'] = 'other-cut'
with open(path, 'w') as fh:
json.dump(lab, fh)
self.assertEqual(B.build_board(self.g, lab_path=path)['communities_source'], 'computed')
def test_too_few_communities(self):
with self.assertRaises(ValueError):
B.build_board(synthetic_graph(20), lab_path='')
def test_main_writes_file(self):
with tempfile.TemporaryDirectory() as d:
gp, out = os.path.join(d, 'g.json'), os.path.join(d, 'sub', 'board.json')
with open(gp, 'w') as fh:
json.dump(self.g, fh)
B.main(['--graph', gp, '--lab', '', '--out', out])
with open(out) as fh:
first = fh.read()
B.main(['--graph', gp, '--lab', '', '--out', out])
with open(out) as fh:
self.assertEqual(fh.read(), first)
check_schema(self, json.loads(first))
@unittest.skipUnless(os.path.exists(B.DEFAULT_GRAPH), 'real build_graph.json not on this machine')
class RealGraph(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.g = B.load_json(B.DEFAULT_GRAPH)
def test_computed(self):
a = B.build_board(self.g, lab_path='')
check_schema(self, a)
self.assertEqual(a['cut'], self.g['cut'])
self.assertEqual(json.dumps(a), json.dumps(B.build_board(self.g, lab_path='')))
n = len(self.g['files'])
for p in a['pieces']:
self.assertTrue(all(0 <= i < n for i in p['files']))
@unittest.skipUnless(os.path.exists(B.DEFAULT_LAB), 'lab overlay absent')
def test_lab(self):
a = B.build_board(self.g, lab_path=B.DEFAULT_LAB)
check_schema(self, a)
if __name__ == '__main__':
unittest.main()Test No Tmp
A test in the chess folder of Cosmic that checks Test Board and Board. It is built from the no tmp test class (`NoTmpTest`).
testcosmic / tools/explore/chess/test_no_tmp.py · lines 1–74 of 74 · Entry point · pattern NoTmpTest (shared by 2 files)
- What it does
- It tests its inputs. Defines NoTmpTest, test_sources_have_no_host_paths, test_pipeline_from_build_graph_only, test_page_computes_board_when_missing, test_missing_graph_is_a_clear_error. Uses libraries json, os, re, subprocess, sys. Side effects: reads or writes files; starts processes.
- Inputs & outputs
- In: JSON file build_graph.json; JSON file board.json; JSON file games.json. Out: JSON file.
- Downstream impact
- It is itself an entry point (test); no other file was found loading it.
- What it achieves
- CI check: the chess generators run on a clean machine (no /tmp inputs, no lab overlay), as `extras.py` runs them.
- Why it matters
- Guards the behaviour of Test Board, Board and Tournament.
- Application
- cosmic · tools/explore/chess · test
- Uses
- Test Board (import), Board (script call), Tournament (script call), Page (script call), json, os, re, subprocess, sys, tempfile, unittest
- Used by
- none found
- Produces
- NoTmpTest
- Defines here
- NoTmpTest, test_sources_have_no_host_paths, test_pipeline_from_build_graph_only, test_page_computes_board_when_missing, test_missing_graph_is_a_clear_error
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 tools/explore/chess/test_no_tmp.py:1-74 · blob 897e5e4c0b395ee12502d1d8ba6c6a5ce7b2f1cb · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: unknown · users: none · canonical: unknown
"""CI check: the chess generators run on a clean machine (no /tmp inputs, no lab overlay), as extras.py runs them.
python -m unittest tools/explore/chess/test_no_tmp.py
"""
import json
import os
import re
import subprocess
import sys
import tempfile
import unittest
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
from test_board import synthetic_graph # noqa: E402
GENERATORS = ['board.py', 'tournament.py', 'page.py']
class NoTmpTest(unittest.TestCase):
def test_sources_have_no_host_paths(self):
for g in GENERATORS:
with open(os.path.join(HERE, g), encoding='utf-8') as fh:
src = fh.read()
self.assertIsNone(re.search(r"['\"]/(tmp|home/claude)/", src), g)
def test_pipeline_from_build_graph_only(self):
work = tempfile.mkdtemp()
g = synthetic_graph()
g['cut'] = 'ci'
gpath = os.path.join(work, 'build_graph.json')
with open(gpath, 'w') as fh:
json.dump(g, fh)
out = os.path.join(work, 'out')
os.makedirs(out)
env = dict(os.environ, EXPLORE_GRAPH=gpath, EXTRA_OUT=out)
env.pop('CHESS_BOARD', None)
steps = [['board.py', '--out', os.path.join(out, 'board.json'), '--lab', ''],
['tournament.py', '--board', os.path.join(out, 'board.json'), '--out',
os.path.join(out, 'games.json'), '--games', '2', '--ply-cap', '20'],
['page.py', '--board', os.path.join(out, 'board.json'), '--games', os.path.join(out, 'games.json'),
'--out', out]]
for st in steps:
p = subprocess.run([sys.executable, os.path.join(HERE, st[0])] + st[1:], cwd=out, env=env,
capture_output=True, text=True, timeout=300)
self.assertEqual(p.returncode, 0, st[0] + ': ' + p.stderr[-800:])
with open(os.path.join(out, 'board.json')) as fh:
self.assertEqual(json.load(fh)['communities_source'], 'computed')
self.assertTrue(os.path.getsize(os.path.join(out, 'index.html')) > 1000)
def test_page_computes_board_when_missing(self):
work = tempfile.mkdtemp()
g = synthetic_graph()
gpath = os.path.join(work, 'build_graph.json')
with open(gpath, 'w') as fh:
json.dump(g, fh)
env = dict(os.environ, EXPLORE_GRAPH=gpath, EXTRA_OUT=work)
p = subprocess.run([sys.executable, os.path.join(HERE, 'page.py')], cwd=work, env=env,
capture_output=True, text=True, timeout=300)
self.assertEqual(p.returncode, 0, p.stderr[-800:])
self.assertIn('computed the board', p.stderr)
def test_missing_graph_is_a_clear_error(self):
work = tempfile.mkdtemp()
env = dict(os.environ, EXTRA_OUT=work)
env.pop('EXPLORE_GRAPH', None)
p = subprocess.run([sys.executable, os.path.join(HERE, 'board.py')], cwd=work, env=env,
capture_output=True, text=True, timeout=60)
self.assertNotEqual(p.returncode, 0)
self.assertIn('build_graph.json not found', p.stderr)
if __name__ == '__main__':
unittest.main()Test Page
A test in the chess folder of Cosmic that checks Page.
testcosmic / tools/explore/chess/test_page.py · lines 1–115 of 115 · Entry point · pattern test_no_external_hosts (shared by 2 files)
- What it does
- It tests cables. Defines 11 functions or classes, including tiny_graph, PageTest, setUpClass, test_noscript_lists_pieces_with_links, test_no_external_hosts. Uses libraries json, os, re, sys, tempfile. Side effects: reads or writes files; makes network requests.
- Why it exists in the grid workflow
- Domain terms in the code: cables.
- Inputs & outputs
- In: JSON file graph.json; JSON file missing.json; JSON file data.json. Out: JSON file.
- Downstream impact
- It is itself an entry point (test); no other file was found loading it.
- What it achieves
- It sets up class (`setUpClass`) and is built from the tiny graph helper (`tiny_graph`) and the page test class (`PageTest`). Tests for the code chess page builder: python -m unittest `tools/explore/chess/test_page.py`.
- Why it matters
- Guards the behaviour of Page.
- Application
- cosmic · tools/explore/chess · test
- Uses
- Page (import), json, os, re, sys, tempfile, unittest
- Used by
- none found
- Produces
- tiny_graph, PageTest
- Defines here
- tiny_graph, PageTest, setUpClass, test_noscript_lists_pieces_with_links, test_no_external_hosts, test_data_embedded_and_matches_file, test_theme_switch_and_controls_present, test_file_links_and_topics, test_fixture_games_replay_consistently, test_cut_mismatch_drops_links, test_template_has_no_cdn
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 tools/explore/chess/test_page.py:1-115 · blob 7b02293a2ba15e9feeb2d82b1e44eb02f0901d8c · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, network · domain stage: unknown · users: none · canonical: unknown
"""Tests for the code chess page builder: python -m unittest tools/explore/chess/test_page.py"""
import json
import os
import re
import sys
import tempfile
import unittest
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import page # noqa: E402
CUT = '2026-12-05T00:00:00+00:00'
def tiny_graph(cut=CUT):
files = []
for i in range(40):
files.append({'id': i, 'repo': ['gridatlas', 'satnav', 'other'][i % 3], 'path': 'p/f%d.js' % i,
'title': 'File </script> %d' % i, 'lines': 10 + i, 'section': 1 + i % 4, 'block': 1 + i % 3,
'role': ['geodesy', 'render'][i % 2], 'reachable': i % 2 == 0, 'dependents': [],
'canonical_status': 'duplicate_candidate' if i % 5 == 0 else 'unknown'})
return {'schema': 'explore-build-graph-v1', 'cut': cut,
'roles': [{'id': k, 'title': t, 'colour': c} for k, t, c in page.ROLES],
'topics': [{'id': 'cables', 'title': 'Cables and conductors'}],
'sections': [{'section': s, 'url': 's/%04d.html' % s, 'topic': 'cables'} for s in range(1, 5)],
'files': files}
class PageTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.tmp = tempfile.mkdtemp()
g = os.path.join(cls.tmp, 'graph.json')
with open(g, 'w') as fh:
json.dump(tiny_graph(), fh)
cls.out = os.path.join(cls.tmp, 'out')
missing = os.path.join(cls.tmp, 'missing.json')
page.main(['--board', missing, '--games', missing, '--graph', g, '--out', cls.out])
with open(os.path.join(cls.out, 'index.html'), encoding='utf-8') as fh:
cls.html = fh.read()
with open(os.path.join(cls.out, 'data.json'), encoding='utf-8') as fh:
cls.data = json.load(fh)
def test_noscript_lists_pieces_with_links(self):
m = re.search(r'<noscript>(.*?)</noscript>', self.html, re.S)
self.assertTrue(m)
ns = m.group(1)
self.assertGreaterEqual(ns.count('<li>'), 32)
self.assertIn('href="../s/0001.html#f', ns)
self.assertIn('href="../topics/cables.html"', ns)
def test_no_external_hosts(self):
self.assertIsNone(re.search(r'(src|href)\s*=\s*["\']?(https?:)?//', self.html, re.I))
self.assertNotIn('@import', self.html)
self.assertIsNone(re.search(r'\bfetch\(|XMLHttpRequest|import\(', self.html))
self.assertIsNone(re.search(r'https?://(?!www\.w3\.org)', self.html))
def test_data_embedded_and_matches_file(self):
m = re.search(r'<script type="application/json" id="data">(.*?)</script>', self.html, re.S)
self.assertTrue(m, 'data block')
emb = json.loads(m.group(1))
self.assertEqual(emb, self.data)
self.assertEqual(emb['schema'], page.PAGE_SCHEMA)
self.assertEqual(len(emb['pieces']), 32)
self.assertEqual(len([p for p in emb['players'] if p['side'] == 'white']), 5)
self.assertEqual(len([p for p in emb['players'] if p['side'] == 'black']), 5)
self.assertTrue(emb['fixture'])
# a title containing </script> must not end the data block early
self.assertEqual(self.html.count('</script>'), 2)
def test_theme_switch_and_controls_present(self):
self.assertIn('id="theme"', self.html)
self.assertIn('role="switch"', self.html)
self.assertIn('data-theme=rb', self.html) # red-and-black CSS
for i in ('playbtn', 'prev', 'next', 'first', 'last', 'scrub', 'players', 'games', 'table', 'card'):
self.assertIn('id="%s"' % i, self.html)
self.assertIn('How to read this', self.html)
self.assertIn('not a judgement', self.html)
self.assertIn('width=device-width', self.html)
def test_file_links_and_topics(self):
p = self.data['pieces'][0]
f = self.data['files'][str(p['files'][0])]
self.assertRegex(f['u'], r'^\.\./s/\d{4}\.html#f\d+$')
self.assertEqual(p['topics'][0]['u'], '../topics/cables.html')
def test_fixture_games_replay_consistently(self):
pos = {p['square']: p['id'] for p in self.data['pieces']}
for g in self.data['games']:
st = dict(pos)
for m in g['moves']:
self.assertEqual(st.get(m['from']), m['piece'], (g['white'], m))
st.pop(m['from'])
if m['piece'].endswith('-k') and abs(ord(m['from'][0]) - ord(m['to'][0])) == 2:
rf, rt = ('h', 'f') if m['to'][0] == 'g' else ('a', 'd')
st[rt + m['from'][1]] = st.pop(rf + m['from'][1])
if '-p-' in m['piece'] and m['from'][0] != m['to'][0] and m['to'] not in st:
st.pop(m['to'][0] + m['from'][1])
st[m['to']] = m['piece']
def test_cut_mismatch_drops_links(self):
board = page.fixture_board(tiny_graph())
board['cut'] = 'another cut'
d = page.build_data(board, page.fixture_games(board), tiny_graph())
self.assertTrue(d['graph_mismatch'])
self.assertEqual(d['files'], {})
def test_template_has_no_cdn(self):
for name in ('index.html', 'chess.js', 'chess.css'):
src = page.read_template(name)
self.assertNotRegex(src, r'https?://', name)
if __name__ == '__main__':
unittest.main()Test Rules
A test in the chess folder of Cosmic that checks Rules. It is built from the play step (`play`), the perft class (`Perft`) and the count step (`count`).
testcosmic / tools/explore/chess/test_rules.py · lines 1–259 of 259 · Entry point · pattern test_round_trip (shared by 2 files)
- What it does
- It tests its inputs. Defines 34 functions or classes, including play, Perft, test_start, test_kiwipete, test_more_positions. Uses libraries os, sys, time, unittest, random.
- Downstream impact
- It is itself an entry point (test); no other file was found loading it.
- What it achieves
- Tests for `chess/rules.py` (unittest).
- Why it matters
- Guards the behaviour of Rules.
- Application
- cosmic · tools/explore/chess · test
- Uses
- Rules (import), os, sys, time, unittest, random
- Used by
- none found
- Produces
- play, Perft, Fen, SpecialMoves, GameEnd, SanAndIds
- Defines here
- play, Perft, test_start, test_kiwipete, test_more_positions, test_legal_moves_match_perft1, test_pin_aware_generator, count, test_speed, Fen, test_round_trip, test_push_pop_restores, test_counters, test_bad_fen, SpecialMoves, test_castling_both_sides, test_castling_blocked_by_attack, test_castling_rights_lost, test_en_passant, test_en_passant_pinned, test_promotion, GameEnd, test_fools_mate, test_stalemate, test_threefold, test_threefold_ignores_impossible_en_passant, test_fifty_moves, test_mate_beats_fifty, test_insufficient, SanAndIds
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 tools/explore/chess/test_rules.py:1-259 · blob 3476f32487a7fe8af3bf9aca1deedc277572a586 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: unknown · users: none · canonical: unknown
#!/usr/bin/env python3
"""Tests for chess/rules.py (unittest). Run: python -m unittest tools/explore/chess/test_rules.py"""
import os
import sys
import time
import unittest
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import rules as R # noqa: E402
KIWIPETE = 'r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq - 0 1'
POS3 = '8/2p5/3p4/KP5r/1R3p1k/8/4P1P1/8 w - - 0 1'
POS4 = 'r3k2r/Pppp1ppp/1b3nbN/nP6/BBP1P3/q4N2/Pp1P2PP/R2Q1RK1 w kq - 0 1'
POS5 = 'rnbq1k1r/pp1Pbppp/2p5/8/2B5/8/PPP1NnPP/RNBQK2R w KQ - 1 8'
def play(board, *ucis):
for u in ucis:
board.push_uci(u)
return board
class Perft(unittest.TestCase):
def test_start(self):
b = R.Board()
for d, n in enumerate((20, 400, 8902, 197281), 1):
self.assertEqual(b.perft(d), n, 'depth %d' % d)
self.assertEqual(b.fen(), R.START_FEN)
def test_kiwipete(self):
b = R.Board(KIWIPETE)
for d, n in enumerate((48, 2039, 97862), 1):
self.assertEqual(b.perft(d), n, 'depth %d' % d)
def test_more_positions(self):
self.assertEqual(R.Board(POS3).perft(4), 43238)
self.assertEqual(R.Board(POS4).perft(3), 9467)
self.assertEqual(R.Board(POS5).perft(3), 62379)
def test_legal_moves_match_perft1(self):
for fen in (R.START_FEN, KIWIPETE, POS3, POS4, POS5):
b = R.Board(fen)
self.assertEqual(len(b.legal_moves()), b.perft(1))
def test_pin_aware_generator(self):
# legal_moves() skips make/unmake for safe moves; count trees with it against known perft values
def count(b, d):
if d == 1:
return len(b.legal_moves())
n = 0
for m in b.legal_moves():
b._make(m)
n += count(b, d - 1)
b._unmake()
return n
self.assertEqual(count(R.Board(KIWIPETE), 3), 97862)
self.assertEqual(count(R.Board(POS3), 4), 43238)
self.assertEqual(count(R.Board(POS4), 3), 9467)
self.assertEqual(count(R.Board(POS5), 3), 62379)
def test_speed(self):
t = time.time()
R.Board().perft(3)
self.assertLess(time.time() - t, 2.0)
class Fen(unittest.TestCase):
def test_round_trip(self):
for fen in (R.START_FEN, KIWIPETE, POS3, POS4, POS5, '4k3/8/8/3pP3/8/8/8/4K3 w - d6 0 3',
'8/8/8/8/8/8/8/K6k b - - 99 120'):
self.assertEqual(R.Board(fen).fen(), fen)
def test_push_pop_restores(self):
b = R.Board(KIWIPETE)
for m in b.legal_moves():
b.push(m)
b.pop()
self.assertEqual(b.fen(), KIWIPETE)
def test_counters(self):
b = play(R.Board(), 'e2e4')
self.assertEqual(b.fen(), 'rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq e3 0 1')
play(b, 'g8f6', 'g1f3')
self.assertEqual(b.fen().split()[-2:], ['2', '2'])
def test_bad_fen(self):
for bad in ('', '8/8/8 w - - 0 1', 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBN w KQkq - 0 1',
'8/8/8/8/8/8/8/8 w - - 0 1', 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR x KQkq - 0 1'):
with self.assertRaises((ValueError, KeyError, IndexError)):
R.Board(bad)
class SpecialMoves(unittest.TestCase):
def test_castling_both_sides(self):
b = R.Board('r3k2r/8/8/8/8/8/8/R3K2R w KQkq - 0 1')
sans = sorted(b.san(m) for m in b.legal_moves() if m[3] == R.CASTLE)
self.assertEqual(sans, ['O-O', 'O-O-O'])
play(b, 'e1g1')
self.assertEqual(b.fen(), 'r3k2r/8/8/8/8/8/8/R4RK1 b kq - 1 1')
play(b, 'e8c8')
self.assertEqual(b.fen(), '2kr3r/8/8/8/8/8/8/R4RK1 w - - 2 2')
def test_castling_blocked_by_attack(self):
# f1 attacked by the bishop on c4: no O-O; d1 free and unattacked: O-O-O allowed
b = R.Board('4k3/8/8/8/2b5/8/8/R3K2R w KQ - 0 1')
self.assertEqual([b.san(m) for m in b.legal_moves() if m[3] == R.CASTLE], ['O-O-O'])
# in check: no castling at all
b = R.Board('4k3/8/8/8/8/8/4r3/R3K2R w KQ - 0 1')
self.assertFalse([m for m in b.legal_moves() if m[3] == R.CASTLE])
# b1 attacked does not stop O-O-O (only the king's path matters)
b = R.Board('4k3/8/8/8/8/8/8/Rn2K3 w Q - 0 1')
self.assertFalse([m for m in b.legal_moves() if m[3] == R.CASTLE]) # b1 occupied
b = R.Board('1r2k3/8/8/8/8/8/8/R3K3 w Q - 0 1')
self.assertEqual([b.san(m) for m in b.legal_moves() if m[3] == R.CASTLE], ['O-O-O'])
def test_castling_rights_lost(self):
b = play(R.Board('r3k2r/8/8/8/8/8/8/R3K2R w KQkq - 0 1'), 'h1h8')
self.assertEqual(b.fen().split()[2], 'Qq') # white h-rook moved and took the black h-rook
b = play(R.Board('r3k2r/8/8/8/8/8/8/R3K2R w KQkq - 0 1'), 'e1e2')
self.assertEqual(b.fen().split()[2], 'kq')
def test_en_passant(self):
b = play(R.Board(), 'e2e4', 'a7a6', 'e4e5', 'd7d5')
ep = [m for m in b.legal_moves() if m[3] == R.EP]
self.assertEqual([b.san(m) for m in ep], ['exd6'])
b.push(ep[0])
self.assertIsNone(b.piece_at('d5'))
self.assertEqual(b.piece_at('d6'), ('white', 'pawn'))
b.pop()
self.assertEqual(b.piece_at('d5'), ('black', 'pawn'))
# only on the very next ply
play(b, 'a2a3', 'a6a5')
self.assertFalse([m for m in b.legal_moves() if m[3] == R.EP])
def test_en_passant_pinned(self):
# capturing en passant would expose the white king on the 5th rank
b = R.Board('8/8/8/K2pP2r/8/8/8/7k w - d6 0 1')
self.assertFalse([m for m in b.legal_moves() if m[3] == R.EP])
def test_promotion(self):
b = R.Board('8/4P1k1/8/8/8/8/8/4K3 w - - 0 1')
promos = sorted(b.uci(m) for m in b.legal_moves() if m[2])
self.assertEqual(promos, ['e7e8b', 'e7e8n', 'e7e8q', 'e7e8r'])
m = b.parse_uci('e7e8q')
self.assertEqual(b.san(m), 'e8=Q')
b.push(m)
self.assertEqual(b.piece_at('e8'), ('white', 'queen'))
b.pop()
self.assertEqual(b.piece_at('e7'), ('white', 'pawn'))
b = R.Board('3r2k1/4P3/8/8/8/8/8/4K3 w - - 0 1')
self.assertEqual(b.san(b.parse_uci('e7d8q')), 'exd8=Q+')
class GameEnd(unittest.TestCase):
def test_fools_mate(self):
b = play(R.Board(), 'f2f3', 'e7e5', 'g2g4')
m = b.parse_uci('d8h4')
self.assertEqual(b.san(m), 'Qh4#')
b.push(m)
self.assertTrue(b.is_checkmate())
self.assertEqual(b.outcome(), ('0-1', 'checkmate'))
def test_stalemate(self):
b = R.Board('7k/5Q2/6K1/8/8/8/8/8 b - - 0 1')
self.assertTrue(b.is_stalemate())
self.assertEqual(b.outcome(), ('1/2-1/2', 'stalemate'))
def test_threefold(self):
b = R.Board()
for _ in range(2):
play(b, 'g1f3', 'g8f6', 'f3g1', 'f6g8')
self.assertTrue(b.is_threefold())
self.assertEqual(b.outcome(), ('1/2-1/2', 'threefold repetition'))
self.assertIsNone(b.outcome(claim_draw=False))
b.pop()
self.assertFalse(b.is_threefold())
def test_threefold_ignores_impossible_en_passant(self):
# after 1.e4 the e3 square is in the FEN but no capture is possible: same position as later
b = play(R.Board(), 'e2e4', 'g8f6', 'g1f3', 'f6g8', 'f3g1', 'g8f6', 'g1f3', 'f6g8', 'f3g1')
self.assertTrue(b.is_threefold())
def test_fifty_moves(self):
b = R.Board('8/8/8/8/8/8/R7/K6k w - - 99 80')
self.assertIsNone(b.outcome())
play(b, 'a2b2')
self.assertTrue(b.is_fifty_moves())
self.assertEqual(b.outcome(), ('1/2-1/2', 'fifty-move rule'))
def test_mate_beats_fifty(self):
b = R.Board('7k/8/6K1/8/8/8/8/R7 w - - 99 80')
play(b, 'a1a8')
self.assertEqual(b.outcome(), ('1-0', 'checkmate'))
def test_insufficient(self):
for fen, dead in (('8/8/8/8/8/8/8/K6k w - - 0 1', True), ('8/8/8/8/8/8/8/KN5k w - - 0 1', True),
('8/8/8/8/8/8/8/KB4bk w - - 0 1', False), ('8/8/8/8/8/8/8/KB3b1k w - - 0 1', True),
('8/8/8/8/8/8/8/KNN4k w - - 0 1', False), ('8/8/8/8/8/8/8/KP5k w - - 0 1', False)):
self.assertEqual(R.Board(fen).is_insufficient_material(), dead, fen)
class SanAndIds(unittest.TestCase):
def test_disambiguation(self):
b = R.Board('4k3/8/8/8/8/8/8/R4RK1 w - - 0 1')
self.assertEqual(b.san(b.parse_uci('a1d1')), 'Rad1')
b = R.Board('4k3/8/8/8/8/8/8/R3K2R w - - 0 1')
self.assertEqual(b.san(b.parse_uci('a1d1')), 'Rd1') # the h1 rook is blocked by the king
b = R.Board('4k3/8/8/8/R7/8/8/R3K3 w - - 0 1')
self.assertEqual(b.san(b.parse_uci('a1a2')), 'R1a2')
b = R.Board('k7/8/8/8/8/2Q1Q3/8/2Q1K3 w - - 0 1')
self.assertEqual(b.san(b.parse_uci('c3d2')), 'Qc3d2')
def test_start_ids(self):
ids = R.start_piece_ids()
self.assertEqual(len(ids), 32)
self.assertEqual(len(set(ids.values())), 32)
self.assertEqual((ids['e1'], ids['d8'], ids['a1'], ids['g8'], ids['e2']), ('w-k', 'b-q', 'w-r-a', 'b-n-g', 'w-p-e'))
def test_id_tracking(self):
b = play(R.Board(track_ids=True), 'e2e4', 'd7d5')
rec = b.move_record(b.parse_uci('e4d5'))
self.assertEqual({k: rec[k] for k in ('piece', 'from', 'to', 'capture', 'check', 'san')},
{'piece': 'w-p-e', 'from': 'e4', 'to': 'd5', 'capture': 'b-p-d', 'check': False, 'san': 'exd5'})
play(b, 'e4d5', 'g8f6', 'g1f3', 'e7e6', 'f1e2', 'f8e7')
b.push_uci('e1g1')
self.assertEqual((b.id_at('g1'), b.id_at('f1')), ('w-k', 'w-r-h'))
b.pop()
self.assertEqual((b.id_at('e1'), b.id_at('h1'), b.id_at('f1')), ('w-k', 'w-r-h', None))
b = play(R.Board(track_ids=True), 'e2e4', 'a7a6', 'e4e5', 'd7d5')
self.assertEqual(b.move_record(b.parse_uci('e5d6'))['capture'], 'b-p-d')
def test_random_games_consistent(self):
# deterministic pseudo-random playouts: push/pop and ids stay consistent with the board
import random
rng = random.Random(7)
for _ in range(20):
b = R.Board(track_ids=True)
fens = [b.fen()]
while b.outcome() is None and len(fens) < 300:
legal = b.legal_moves()
brute = []
for m in b.pseudo_moves():
b._make(m)
if not b.in_check(-b.side):
brute.append(m)
b._unmake()
self.assertEqual(sorted(legal), sorted(brute))
b.push(rng.choice(legal))
fens.append(b.fen())
for sq in R.SQUARES:
self.assertEqual(bool(b.b[sq]), b.ids[sq] is not None)
while b.stack:
self.assertEqual(b.fen(), fens.pop())
b.pop()
self.assertEqual(b.fen(), R.START_FEN)
if __name__ == '__main__':
unittest.main()