Public repository: timo / schach

Reader

Ein aufgeräumtes Schach-Programm für GNOME

schach / tests / test_opening.py · 12.7 KB · at 3c63b1d52560 · raw

Outline: 32 definitions
1
import os
2
import unittest
3
4
import chess
5
6
from schach import opening
7
8
9
def play(*sans):
10
    board = chess.Board()
11
    for san in sans:
12
        board.push_san(san)
13
    return board
14
15
16
class CourseTest(unittest.TestCase):
17
    @classmethod
18
    def setUpClass(cls):
19
        cls.courses = {c.title: c for c in opening.load_courses()}
20
        cls.book = opening.Book()
21
        cls.names = opening.Names()
22
23
    def test_courses_load(self):
24
        self.assertIn("Italienisch", self.courses)
25
        self.assertIn("Spanisch", self.courses)
26
        self.assertEqual(self.courses["Italienisch"].color, chess.WHITE)
27
        for title in ("Zweispringerspiel", "Spanisch mit Schwarz", "Skandinavisch"):
28
            self.assertEqual(self.courses[title].color, chess.BLACK)
29
        for course in self.courses.values():
30
            self.assertTrue(course.welcome)
31
            self.assertGreaterEqual(opening.main_line_length(course), 10)
32
33
    def test_every_course_position_is_reachable_and_legal(self):
34
        for course in self.courses.values():
35
            self.assertIn(opening.key(course.start()), course.positions)
36
37
    def test_arrows_parsed_and_hidden_from_text(self):
38
        course = opening.parse_course(
39
            '[Event "T"]\n\n{ Start [%csl Re4] } 1. e4 { Zentrum! [%cal Gd1h5,Gf1c4] } *')
40
        option = course.options(chess.Board())[0]
41
        self.assertEqual(option.comment, "Zentrum!")
42
        self.assertEqual(option.shapes, ((chess.D1, chess.H5, "green"), (chess.F1, chess.C4, "green")))
43
        self.assertEqual(course.welcome, "Start")
44
        self.assertEqual(course.welcome_shapes, ((chess.E4, chess.E4, "red"),))
45
46
    def test_warum_variation_is_demo_not_option(self):
47
        course = opening.parse_course(
48
            '[Event "T"]\n\n1. e4 e5 2. Nf3 { Angriff auf e5. } '
49
            '( 2. Qh5 { [%warum] Stell dir vor … } 2... Nc6 { Gedeckt. [%cal Gc6e5] } ) 2... Nc6 *')
50
        before = play("e4", "e5")
51
        self.assertEqual([o.move.uci() for o in course.options(before)], ["g1f3"])
52
        [demo] = course.demos_for(before, chess.Move.from_uci("g1f3"))
53
        self.assertEqual([m.uci() for m, _c, _s in demo.steps], ["d1h5", "b8c6"])
54
        self.assertEqual(demo.steps[0][1], "Stell dir vor …")
55
        self.assertEqual(demo.steps[1][2], ((chess.C6, chess.E5, "green"),))
56
        self.assertEqual(demo.board_at(1).fen().split()[0], "r1bqkbnr/pppp1ppp/2n5/4p2Q/4P3/8/PPPP1PPP/RNB1KBNR")
57
        self.assertEqual(course.demos_for(before, chess.Move.from_uci("d1h5")), [])
58
        self.assertEqual(demo.title, "")
59
        titled = opening.parse_course('[Event "T"]\n\n1. e4 ( 1. e4 { [%warum Wozu e4?] x } ) *')
60
        self.assertEqual(titled.demos_for(chess.Board(), chess.Move.from_uci("e2e4"))[0].title, "Wozu e4?")
61
62
    def test_several_demos_per_move_and_demo_for_alternative(self):
63
        course = opening.parse_course(
64
            '[Event "T"]\n\n1. e4 e5 2. Nf3 ( 2. Nf3 { [%warum Wozu Sf3?] a } 2... Nc6 ) '
65
            '( 2. Qh5 { [%warum Und Dh5?] b } 2... Nc6 ) ( 2. Bc4 { auch gut } ) '
66
            '( 2. Bc4 { [%warum Warum Lc4?] c } 2... Nf6 ) 2... Nc6 *')
67
        before = play("e4", "e5")
68
        main = course.demos_for(before, chess.Move.from_uci("g1f3"))
69
        self.assertEqual([d.title for d in main], ["Wozu Sf3?", "Und Dh5?"])  # Was-wäre-wenn hängt am Hauptzug
70
        alt = course.demos_for(before, chess.Move.from_uci("f1c4"))
71
        self.assertEqual([d.title for d in alt], ["Warum Lc4?"])  # erklärt die Alternative selbst
72
        self.assertEqual({o.move.uci() for o in course.options(before)}, {"g1f3", "f1c4"})
73
74
    def test_options_main_first(self):
75
        italian = self.courses["Italienisch"]
76
        options = italian.options(play("e4", "e5", "Nf3", "Nc6", "Bc4"))
77
        self.assertEqual(options[0].move, chess.Move.from_uci("f8c5"))
78
        self.assertTrue(options[0].main)
79
        self.assertEqual({o.move.uci() for o in options}, {"f8c5", "g8f6", "f8e7"})
80
81
    def test_transposition_continues_main_line(self):
82
        italian = self.courses["Italienisch"]
83
        # 3...Sf6 4.d3 Lc5 5.c3 ist dieselbe Stellung wie 3...Lc5 4.c3 Sf6 5.d3
84
        via_side = play("e4", "e5", "Nf3", "Nc6", "Bc4", "Nf6", "d3", "Bc5", "c3")
85
        via_main = play("e4", "e5", "Nf3", "Nc6", "Bc4", "Bc5", "c3", "Nf6", "d3")
86
        self.assertEqual(opening.key(via_side), opening.key(via_main))
87
        self.assertTrue(italian.options(via_side))
88
89
    def test_judge(self):
90
        italian = self.courses["Italienisch"]
91
        before = play("e4", "e5", "Nf3", "Nc6")
92
        verdict = opening.judge(italian, self.book, self.names, before, chess.Move.from_uci("f1c4"))
93
        self.assertEqual(verdict.kind, "course")
94
        self.assertIn("f7", verdict.option.comment)
95
        spanish = opening.judge(italian, self.book, self.names, before, chess.Move.from_uci("f1b5"))
96
        self.assertEqual(spanish.kind, "book")
97
        weird = opening.judge(italian, self.book, self.names, before, chess.Move.from_uci("h2h4"))
98
        self.assertEqual(weird.kind, "other")
99
100
    def test_judge_transposition(self):
101
        italian = self.courses["Italienisch"]
102
        # Andere Zugfolge in eine Kursstellung: 4.d3 vor c3 in der Hauptvariante
103
        before = play("e4", "e5", "Nf3", "Nc6", "Bc4", "Bc5")
104
        verdict = opening.judge(italian, self.book, self.names, before, chess.Move.from_uci("d2d3"))
105
        self.assertIn(verdict.kind, ("transposition", "book", "other"))
106
        before = play("e4", "e5", "Nf3", "Nc6", "Bc4", "Nf6", "d3", "Bc5")
107
        self.assertEqual(
108
            opening.judge(italian, self.book, self.names, before, chess.Move.from_uci("c2c3")).kind, "course"
109
        )
110
111
112
class NamesTest(unittest.TestCase):
113
    def test_english_names_translated_whole(self):
114
        self.assertEqual(opening._german("King's Pawn"), "Königsbauernspiel")
115
        self.assertEqual(opening._german("Queen's Pawn Game"), "Damenbauernspiel")
116
        self.assertEqual(opening._german("Dutch Defense: Leningrad Variation"), "Holländisch: Leningrad-Variante")
117
        self.assertEqual(opening._german("Caro-Kann Defense: Advance Variation"), "Caro-Kann: Vorstoßvariante")
118
        self.assertEqual(opening._german("Rat Defense: Small Center"), "Rat Defense: Small Center")  # lieber ganz englisch
119
120
    def test_names(self):
121
        names = opening.Names()
122
        self.assertTrue(names.name(play("e4", "e5", "Nf3", "Nc6", "Bc4")).startswith("Italien"))
123
        self.assertTrue(names.name(play("e4", "e5", "Nf3", "Nc6", "Bb5")).startswith("Spanisch"))
124
        self.assertEqual(names.exact(play("c4")), "Englisch")  # nicht „Abarten von Holländisch“
125
        # unbekannte Stellung: Name der letzten bekannten
126
        self.assertTrue(names.name(play("e4", "e5", "Nf3", "Nc6", "Bc4", "h6", "a3", "a6")))
127
128
129
class BookTest(unittest.TestCase):
130
    def test_book_knows_main_moves(self):
131
        moves = [m.uci() for m, _w in opening.Book().moves(play("e4", "e5", "Nf3", "Nc6"))]
132
        self.assertEqual(moves[:2], ["f1b5", "f1c4"])
133
134
135
if __name__ == "__main__":
136
    unittest.main()
137
138
139
class BooksTest(unittest.TestCase):
140
    """Mehrere Polyglot-Bücher: Fundorte, Doppelte, Vereinigung."""
141
142
    @staticmethod
143
    def _write_book(path, entries):
144
        import struct
145
        data = b"".join(struct.pack(">QHHI", key, raw, weight, 0) for key, raw, weight in sorted(entries))
146
        with open(path, "wb") as fh:
147
            fh.write(data)
148
149
    @staticmethod
150
    def _raw(move):
151
        promo = {None: 0, chess.KNIGHT: 1, chess.BISHOP: 2, chess.ROOK: 3, chess.QUEEN: 4}[move.promotion]
152
        return (chess.square_file(move.to_square) | chess.square_rank(move.to_square) << 3
153
                | chess.square_file(move.from_square) << 6 | chess.square_rank(move.from_square) << 9 | promo << 12)
154
155
    def setUp(self):
156
        import tempfile
157
        self.dir = tempfile.TemporaryDirectory()
158
        self.addCleanup(self.dir.cleanup)
159
        start = chess.polyglot.zobrist_hash(chess.Board())
160
        e4, d4, c4 = (chess.Move.from_uci(u) for u in ("e2e4", "d2d4", "c2c4"))
161
        self.a = os.path.join(self.dir.name, "a.bin")
162
        self.b = os.path.join(self.dir.name, "b_buch.bin")
163
        self._write_book(self.a, [(start, self._raw(e4), 3), (start, self._raw(d4), 1)])
164
        self._write_book(self.b, [(start, self._raw(c4), 10)])
165
        self.e4, self.d4, self.c4 = e4, d4, c4
166
167
    def test_paths_without_duplicates(self):
168
        link = os.path.join(self.dir.name, "link.bin")
169
        os.symlink(self.a, link)
170
        paths = opening.book_paths(extra=[link, "/gibt/es/nicht.bin"], book_dir=self.dir.name, builtin=None)
171
        self.assertEqual(paths, [link, self.b])  # a.bin ist dieselbe Datei wie link.bin
172
173
    def test_copy_of_builtin_counts_once(self):
174
        import shutil
175
        copy = os.path.join(self.dir.name, "kopie.bin")
176
        shutil.copy(opening.BOOK_PATH, copy)
177
        paths = opening.book_paths(book_dir=self.dir.name)
178
        self.assertEqual(paths[0], opening.BOOK_PATH)
179
        self.assertNotIn(copy, paths)
180
181
    def test_bundled_data_present(self):
182
        self.assertTrue(opening.Book().available)
183
        board = chess.Board()
184
        for san in ("e4", "e5", "Nf3", "Nc6", "Bc4"):
185
            board.push_san(san)
186
        self.assertIn("Italien", opening.Names().name(board) or "")
187
188
    def test_union(self):
189
        books = opening.Books([self.a, self.b])
190
        self.assertEqual([b.name for b in books.books], ["a", "b buch"])
191
        board = chess.Board()
192
        self.assertTrue(books.contains(board, self.c4))
193
        self.assertTrue(books.contains(board, self.e4))
194
        shares = dict(books.moves(board))
195
        self.assertAlmostEqual(shares[self.c4], 0.5)  # je Buch normiert, dann gemittelt
196
        self.assertAlmostEqual(shares[self.e4], 0.375)
197
        self.assertAlmostEqual(sum(shares.values()), 1)
198
199
    def test_missing_and_empty(self):
200
        books = opening.Books([os.path.join(self.dir.name, "fehlt.bin")])
201
        self.assertEqual(books.books, [])
202
        self.assertEqual(books.moves(chess.Board()), [])
203
        self.assertFalse(books.contains(chess.Board(), self.e4))
204
205
206
class SquareNamesTest(unittest.TestCase):
207
    def test_squares_in_comment(self):
208
        from schach.training import squares_in
209
        text = "Lc4 zielt auf f7. Sxe5, Sbd2, exd5 und e4 – aber nicht Ende4 oder a10. Die f7-Schwäche!"
210
        found = [(text[a:b], chess.square_name(sq), piece, extra) for a, b, sq, piece, extra in squares_in(text)]
211
        self.assertEqual(found, [("Lc4", "c4", "L", ""), ("f7", "f7", None, ""), ("Sxe5", "e5", "S", ""),
212
                                 ("Sbd2", "d2", "S", "b"), ("exd5", "d5", "P", "e"), ("e4", "e4", None, ""),
213
                                 ("f7", "f7", None, "")])
214
215
    def test_mover_finds_the_piece(self):
216
        from schach.training import mover
217
        board = chess.Board()
218
        for san in ("e4", "e5", "Nf3", "Nc6"):
219
            board.push_san(san)
220
        self.assertEqual(mover(board, "L", "", chess.C4), chess.F1)  # Lc4 kommt noch: Pfeil von f1
221
        self.assertEqual(mover(board, "S", "", chess.F6), chess.G8)  # auch für die andere Seite
222
        self.assertIsNone(mover(board, "S", "", chess.F3))  # steht schon dort
223
        self.assertIsNone(mover(board, None, "", chess.E4))  # nur ein Feld
224
        start = chess.Board()
225
        self.assertEqual(mover(start, "L", "", chess.F4), chess.C1)  # Aufbau-Plan: der schwarzfeldrige Läufer
226
        self.assertEqual(mover(start, "S", "", chess.D2), chess.B1)  # nur einer passt
227
        self.assertIsNone(mover(start, "T", "", chess.D1))  # zwei Türme könnten: lieber kein Pfeil
228
229
    def test_mover_finds_capturing_pawn(self):
230
        from schach.training import mover, route
231
        # nach 7. Lb3: c4 ist leer, die Drohung bxc4 zeigt trotzdem vom Bauern b5 aus
232
        board = chess.Board("rn1qkb1r/5ppp/2pp1n2/1p2p3/4P1b1/1B1P1N2/PPP2PPP/RNBQR1K1 b kq - 1 7")
233
        self.assertEqual(mover(board, "P", "b", chess.C4), chess.B5)
234
        self.assertEqual(route(board, "Das wehrt die Drohung bxc4 ab.", "P", "b", chess.C4), (chess.B5, None))
235
        self.assertIsNone(mover(board, "P", "e", chess.C4))  # auf der e-Linie greift kein Bauer c4 an
236
237
    def test_route_bridges_over_earlier_move(self):
238
        from schach.training import route
239
        start = chess.Board()
240
        text = "Aufbau d4–Lf4–e3–Sf3–c3–Ld3–Sbd2, dann e4 oder Se5."
241
        self.assertEqual(route(start, text, "S", "", chess.E5), (chess.G1, chess.F3))  # g1→f3→e5
242
        self.assertEqual(route(start, text, "L", "", chess.F4), (chess.C1, None))  # geht direkt
243
        self.assertEqual(route(start, "Plan: Se5", "S", "", chess.E5), (None, None))  # keine Brücke im Text
244
245
    def test_mark_squares_leaves_tags_alone(self):
246
        from schach.training import mark_squares
247
        out = mark_squares("<span alpha='70%'>Warum?</span>\n<b>3. Lc4</b> – auf f7")
248
        self.assertIn("<span alpha='70%'>Warum?</span>", out)
249
        self.assertEqual(out.count("<i>"), 2)
250
        self.assertIn("<i>Lc4</i></b>", out)