Public repository: timo / schach

Reader

Ein aufgeräumtes Schach-Programm für GNOME

schach / tests / test_export.py · 26.3 KB · at 3c63b1d52560 · raw

Outline: 72 definitions
1
import io
2
from html import escape as html_escape, unescape
3
import re
4
import shutil
5
import subprocess
6
import tempfile
7
import unittest
8
9
import chess
10
import chess.pgn
11
12
from schach import export, notation, savegames
13
14
MOVES = "e4 e5 Nf3 Nc6 Bc4 Nd4 Nxe5 Qg5 Nxf7 Qxg2 Rf1 Qxe4+ Be2 Nf3#".split()
15
16
17
def sample():
18
    board = chess.Board()
19
    for san in MOVES:
20
        board.push_san(san)
21
    return savegames.GameState(
22
        board=board, human=chess.WHITE, elo=1500, symbols={5: "!", 6: "??", 13: "!!"},
23
        evals={i: 50.0 + i for i in range(len(MOVES))}, names=("Florian", "Max"), mode="review",
24
        name="Vereinsabend",
25
    )
26
27
28
def opts(**kw):
29
    kw.setdefault("theme", "cburnett")
30
    return export.Options(**kw)
31
32
33
class TextFormatsTest(unittest.TestCase):
34
    def test_fen_of_shown_position(self):
35
        fen = export.export("fen", sample(), opts(plies=2))
36
        self.assertEqual(fen.strip(), "rnbqkbnr/pppp1ppp/8/4p3/4P3/8/PPPP1PPP/RNBQKBNR w KQkq - 0 2")
37
38
    def test_fen_ignores_game_scope(self):
39
        self.assertEqual(export.export("fen", sample(), opts(scope="game", plies=0)).strip(), chess.STARTING_FEN)
40
41
    def test_pgn_game_keeps_or_drops_annotations(self):
42
        full = export.export("pgn", sample(), opts(scope="game"))
43
        self.assertIn("$4", full)
44
        self.assertIn("[%wp", full)
45
        bare = export.export("pgn", sample(), opts(scope="game", symbols=False, evals=False))
46
        self.assertNotIn("$", bare.split("\n\n", 1)[1])
47
        self.assertNotIn("[%wp", bare)
48
        game = chess.pgn.read_game(io.StringIO(bare))
49
        self.assertEqual(len(list(game.mainline_moves())), len(MOVES))
50
51
    def test_pgn_position_is_setup_without_moves(self):
52
        text = export.export("pgn", sample(), opts(plies=4))
53
        game = chess.pgn.read_game(io.StringIO(text))
54
        self.assertEqual(game.headers["White"], "Florian")
55
        self.assertEqual(list(game.mainline_moves()), [])
56
        self.assertEqual(game.board().fen(), export.board_at(sample(), 4).fen())
57
        self.assertNotIn("SchachHuman", text)
58
59
    def test_ascii_board_and_moves(self):
60
        text = export.export("ascii", sample(), opts(scope="game", plies=0, notation="de"))
61
        self.assertIn("8 | t s l d k l s t |", text)
62
        self.assertIn("1 | T S L D K L S T |", text)
63
        self.assertIn("2. Sf3 Sc6 3. Lc4 Sd4!", text)
64
        self.assertIn("Florian – Max", text)
65
        self.assertIn("0–1", text)
66
        self.assertTrue(text.isascii() is False)  # Gedankenstrich im Kopf
67
68
    def test_ascii_flipped_and_english(self):
69
        text = export.export("ascii", sample(), opts(plies=0, flipped=True, notation="en", players=False))
70
        lines = text.splitlines()
71
        self.assertEqual(lines[1], "1 | R N B K Q B N R |")
72
        self.assertEqual(lines[-4].strip(), "h g f e d c b a")
73
        self.assertNotIn("Florian", text)
74
75
    def test_caption(self):
76
        board = export.board_at(sample(), 8)
77
        self.assertEqual(export.caption(board, "de"), "Stellung nach 4… Dg5 · Weiß am Zug")
78
        self.assertTrue(export.caption(sample().board).endswith("Weiß ist matt"))
79
        self.assertTrue(export.caption(chess.Board()).startswith("Ausgangsstellung"))
80
81
82
class VariationTest(unittest.TestCase):
83
    """Nebenvarianten vom Analysebrett: in PGN und HTML, abschaltbar."""
84
85
    def state(self):
86
        state = sample()
87
        m = chess.Move.from_uci
88
        # nach 3. Lc4 (Halbzug 4): 3… Sf6 statt 3… Sd4, mit Kommentar, Pfeil und Fortsetzung
89
        state.variations = {4: [(m("g8f6"), "So spielt Maia 600 oft.", ((chess.G8, chess.F6, "threat"),),
90
                                 [(m("f3g5"), "Du greifst f7 an.", (), [])])]}
91
        return state
92
93
    def test_pgn_contains_variation_with_comment_and_arrow(self):
94
        text = savegames.to_pgn(self.state())
95
        self.assertIn("( 3... Nf6 { [%cal Yg8f6] So spielt Maia 600 oft. } 4. Ng5 { Du greifst f7 an. } )", text)
96
        game = chess.pgn.read_game(io.StringIO(text))
97
        self.assertEqual([n.san() for n in game.mainline()], MOVES)  # Hauptlinie bleibt die Partie
98
99
    def test_export_can_drop_variations(self):
100
        with_them = export.export("pgn", self.state(), opts(scope="game"))
101
        without = export.export("pgn", self.state(), opts(scope="game", variations=False))
102
        self.assertIn("3... Nf6", with_them)
103
        self.assertNotIn("3... Nf6", without)
104
105
    def test_saved_variations_come_back(self):
106
        state = self.state()
107
        loaded = savegames.from_pgn(savegames.to_pgn(state))
108
        # Kommentar ohne [%cal]; die Drohung kommt als Lichess-Gelb zurück (gelb bleibt gelb beim Zeichnen)
109
        (move, comment, shapes, children, name), = loaded.variations[4]
110
        self.assertEqual((move, comment), state.variations[4][0][:2])
111
        self.assertEqual([c[:4] for c in children], state.variations[4][0][3])
112
        self.assertEqual(shapes, ((chess.G8, chess.F6, "yellow"),))
113
        self.assertEqual(name, "")
114
115
    def test_variation_name_survives_saving(self):
116
        state = self.state()
117
        move, comment, shapes, children = state.variations[4][0]
118
        state.variations = {4: [(move, comment, shapes, children, "Zweispringerspiel")]}
119
        text = savegames.to_pgn(state)
120
        self.assertIn("( { Zweispringerspiel } 3... Nf6", text)
121
        self.assertEqual(savegames.from_pgn(text).variations[4][0][4], "Zweispringerspiel")
122
123
    def test_drawn_shapes_on_the_game_come_back_in_lichess_colors(self):
124
        state = sample()
125
        state.shapes = {-1: ((chess.E2, chess.E4, "green"),),
126
                        2: ((chess.F7, chess.F7, "red"), (chess.B1, chess.C3, "blue"), (chess.D8, chess.H4, "yellow"))}
127
        text = savegames.to_pgn(state)
128
        self.assertIn("[%csl Rf7]", text)
129
        self.assertIn("[%cal Bb1c3,Yd8h4]", text)
130
        loaded = savegames.from_pgn(text)
131
        self.assertEqual(loaded.shapes, state.shapes)
132
        self.assertEqual(state.truncated(1).shapes, {-1: state.shapes[-1]})
133
134
    def test_branching_off_keeps_earlier_variations_only(self):
135
        state = self.state()
136
        self.assertEqual(state.truncated(3).variations, {})  # Variante hängt nach Halbzug 4, also dahinter
137
        self.assertEqual(state.truncated(4).variations, state.variations)  # hängt noch am letzten Zug
138
139
    def test_html_shows_variation_without_commands(self):
140
        page = export.export("html", self.state(), opts(scope="game"))
141
        self.assertIn("( 3... Nf6 { So spielt Maia 600 oft. } 4. Ng5", unescape(page))
142
143
144
class LatexTest(unittest.TestCase):
145
    def test_game_splits_mainline_at_diagram(self):
146
        tex = export.export("latex", sample(), opts(scope="game", plies=8, flipped=True))
147
        self.assertIn("\\mainline{1. e4 e5 2. Nf3 Nc6 3. Bc4 Nd4! 4. Nxe5?? Qg5}", tex)
148
        self.assertIn("\\mainline{5. Nxf7", tex)
149
        self.assertIn("inverse", tex)
150
        self.assertIn("markfields={d8,g5}", tex)
151
        self.assertLess(tex.index("\\chessboard"), tex.index("\\mainline{5."))
152
153
    def test_position_sets_fen_and_escapes_names(self):
154
        state = sample()
155
        state.names = ("A & B", "50%")
156
        tex = export.export("latex", state, opts(plies=4, last_move=False))
157
        self.assertIn("setfen=" + export.board_at(state, 4).fen(), tex)
158
        self.assertIn("A \\& B -- 50\\%", tex)
159
        self.assertNotIn("markfields", tex)
160
161
    @unittest.skipUnless(export.latex_available(), "pdflatex fehlt")
162
    def test_pdf_via_latex(self):
163
        pdf = export.export("pdf-latex", sample(), opts(scope="game", plies=8))
164
        self.assertTrue(pdf.startswith(b"%PDF"))
165
166
167
class ImageAndPageTest(unittest.TestCase):
168
    def test_svg_and_png(self):
169
        svg = export.export("svg", sample(), opts(scope="game", plies=8))
170
        self.assertIn("<svg", svg)
171
        png = export.export("png", sample(), opts(plies=8, players=False, evals=False))
172
        self.assertTrue(png.startswith(b"\x89PNG"))
173
        width, height = int.from_bytes(png[16:20], "big"), int.from_bytes(png[20:24], "big")
174
        self.assertEqual((width, height), (800, 800))  # ohne Köpfe und Balken: quadratisch
175
176
    def test_pdf(self):
177
        for scope in ("position", "game"):
178
            pdf = export.export("pdf", sample(), opts(scope=scope, plies=8))
179
            self.assertTrue(pdf.startswith(b"%PDF"))
180
181
    @unittest.skipUnless(shutil.which("pdfinfo"), "pdfinfo fehlt")
182
    def test_long_game_pdf_gets_more_pages(self):
183
        state = sample()
184
        board = chess.Board()
185
        for _ in range(60):  # Springer hin und her: 120 Züge
186
            for san in ("Nf3", "Nf6", "Ng1", "Ng8"):
187
                board.push_san(san)
188
        state.board, state.symbols, state.evals = board, {}, {}
189
        pdf = export.export("pdf", state, opts(scope="game"))
190
        with tempfile.NamedTemporaryFile(suffix=".pdf") as fh:
191
            fh.write(pdf)
192
            fh.flush()
193
            info = subprocess.run(["pdfinfo", fh.name], capture_output=True, text=True).stdout
194
        self.assertEqual(int(re.search(r"Pages:\s+(\d+)", info).group(1)), 2)
195
196
    def test_html_game_has_one_group_per_position(self):
197
        page = export.export("html", sample(), opts(scope="game", plies=8))
198
        groups = re.findall(r'<g class="ply" data-ply="(\d+)"( style="display:none")?>', page)
199
        self.assertEqual(len(groups), len(MOVES) + 1)
200
        visible = [ply for ply, hidden in groups if not hidden]
201
        self.assertEqual(visible, ["8"])
202
        self.assertIn('"start": 8', page)
203
        self.assertIn("user-select: all", page)
204
        self.assertIn("Sxe5", page)
205
        # PGN mit Zügen als Spans, der gezeigte (8. Halbzug) ist markiert
206
        self.assertIn('<span class="mv sel" data-ply="8">Qg5</span>', page)
207
        self.assertEqual(len(re.findall(r'<span class="mv', page)), len(MOVES))
208
        # Zugzeichen farbig statt NAG-Nummer, auch im kopierbaren PGN
209
        self.assertRegex(page, r'data-ply="7">Nxe5<b class="s" style="color:#[0-9a-f]{6}">\?\?</b></span>')
210
        self.assertIn('"pgn": "[Event', page)
211
        self.assertIn("Nxe5??", page)
212
        self.assertNotIn("$4", page)
213
        self.assertNotIn("SchachHuman", page)
214
        # Gewinnchance nur als Balken, nicht im PGN der Seite
215
        self.assertNotIn("[%wp", page)
216
        # Nummer, Zug und Ergebnis bleiben zusammen
217
        self.assertIn('<span class="u">1. <span class="mv" data-ply="1">e4</span></span>', page)
218
        # (Die Testpartie ist die Falle des Blackburne-Shilling-Gambits: eco.db kennt sie bis zum Matt,
219
        # der lange Kommentar „Bis hier: …“ steht daher als eigener Teil vor dem Ergebnis.)
220
        self.assertRegex(page, r'data-ply="14">Nf3#<b[^>]*>!!</b></span></span> <span class="c">\{ Bis hier: C50 [^<]*\}</span> <span class="u">0-1</span>')
221
222
    def test_html_pgn_long_comment_may_wrap(self):
223
        game = chess.pgn.read_game(io.StringIO(export.export("pgn", sample(), opts(scope="game"))))
224
        game.end().comment = "sehr langer Kommentar " * 5
225
        html = export._html_pgn(str(game), None)
226
        self.assertRegex(html, r'</span> <span class="c">\{ sehr langer')  # nicht in der Einheit
227
        self.assertTrue(html.endswith('<span class="u">0-1</span>'))
228
229
    def test_html_position_only(self):
230
        page = export.export("html", sample(), opts(plies=3, players=False))
231
        self.assertEqual(len(re.findall(r'<g class="ply"', page)), 1)
232
        self.assertNotIn('class="moves"', page)
233
        self.assertNotIn("Florian", page)
234
235
    def test_html_escapes_script_end(self):
236
        state = sample()
237
        state.names = ("</script><b>", "Max")
238
        page = export.export("html", state, opts(scope="game"))
239
        self.assertEqual(page.count("</script>"), 2)
240
241
242
class OpeningTest(unittest.TestCase):
243
    def setUp(self):
244
        if export._names()._conn is None:
245
            self.skipTest("eco.db von PyChess fehlt")
246
247
    def test_game_pgn_names_opening_and_marks_book_end(self):
248
        text = export.export("pgn", sample(), opts(scope="game"))
249
        game = chess.pgn.read_game(io.StringIO(text))
250
        self.assertRegex(game.headers["ECO"], r"^[A-E]\d\d$")
251
        self.assertTrue(game.headers["Opening"])
252
        ply, eco, name = export.book_end(sample())
253
        self.assertIsNotNone(ply)
254
        node = list(game.mainline())[ply]
255
        self.assertTrue(node.comment.startswith(f"Bis hier: {eco} {name}"))
256
        self.assertIn("[%wp", node.comment)  # Bewertung bleibt in der Datei erhalten
257
        # Wieder einlesen: Balkenwert kommt trotz Eröffnungskommentar zurück
258
        self.assertEqual(savegames.from_pgn(text).evals[ply], sample().evals[ply])
259
260
    def test_position_at_start_has_no_opening(self):
261
        text = export.export("pgn", sample(), opts(plies=0))
262
        self.assertNotIn("[ECO", text)
263
        self.assertIn("[Opening", export.export("pgn", sample(), opts(plies=5)))
264
265
    def test_html_meta_shows_opening(self):
266
        page = export.export("html", sample(), opts(scope="game"))
267
        _, eco, name = export.book_end(sample())
268
        self.assertIn(html_escape(f"{eco} {name}"), page)
269
        self.assertIn("Bis hier:", page)
270
271
272
def png_chunks(data):
273
    """[(typ, inhalt)] einer PNG-Datei."""
274
    chunks, pos = [], 8
275
    while pos < len(data):
276
        length = int.from_bytes(data[pos:pos + 4], "big")
277
        chunks.append((data[pos + 4:pos + 8], data[pos + 8:pos + 8 + length]))
278
        pos += 12 + length
279
    return chunks
280
281
282
def frame_delays(data):
283
    """Dauer jedes Bilds in ms aus den fcTL-Blöcken."""
284
    return [round(int.from_bytes(body[20:22], "big") * 1000 / int.from_bytes(body[22:24], "big"))
285
            for kind, body in png_chunks(data) if kind == b"fcTL"]
286
287
288
class AnimationTest(unittest.TestCase):
289
    def test_apng_structure(self):
290
        data = export.export("apng", sample(), opts(scope="game"))
291
        self.assertTrue(data.startswith(b"\x89PNG\r\n\x1a\n"))
292
        chunks = png_chunks(data)
293
        kinds = [kind for kind, _ in chunks]
294
        self.assertEqual(kinds[:4], [b"IHDR", b"acTL", b"fcTL", b"IDAT"])  # erstes Bild auch ohne APNG sichtbar
295
        self.assertEqual(kinds[-1], b"IEND")
296
        frames = int.from_bytes(chunks[1][1][:4], "big")
297
        self.assertEqual(frames, len(MOVES) + 1)  # Ausgangsstellung + jeder Halbzug
298
        self.assertEqual(kinds.count(b"fcTL"), frames)
299
        # Folgenummern über fcTL und fdAT lückenlos ab 0
300
        numbers = [int.from_bytes(body[:4], "big") for kind, body in chunks if kind in (b"fcTL", b"fdAT")]
301
        self.assertEqual(numbers, list(range(len(numbers))))
302
        width = int.from_bytes(chunks[0][1][:4], "big")
303
        self.assertEqual(width, export.APNG_WIDTH)
304
305
    def test_frames_match_single_images(self):
306
        """Die Auflagen setzen sich genau zu den einzelnen Stellungen zusammen."""
307
        import cairo
308
        import io as io_mod
309
        try:
310
            from PIL import Image
311
        except ImportError:
312
            self.skipTest("Pillow fehlt")
313
        o = opts(scope="game", plies=6)
314
        state = sample()
315
        state.board = export.board_at(state, 6)
316
        animation = Image.open(io_mod.BytesIO(export.export("apng", state, o)))
317
        for index, (diagram, _delay) in enumerate(export._frames(state, o)):
318
            width = export.APNG_WIDTH
319
            surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, animation.size[1])
320
            cr = cairo.Context(surface)
321
            cr.set_source_rgb(*export.APNG_BACKGROUND)
322
            cr.paint()
323
            diagram.render(cr, 0, 0, width)
324
            out = io_mod.BytesIO()
325
            surface.write_to_png(out)
326
            animation.seek(index)
327
            self.assertEqual(animation.convert("RGBA").tobytes(),
328
                             Image.open(out).convert("RGBA").tobytes(), f"Bild {index}")
329
330
    def test_delays_fixed_or_from_move_times(self):
331
        state = sample()
332
        state.times = {ply: 500 * (ply + 1) for ply in range(len(MOVES))}
333
        fixed = frame_delays(export.export("apng", state, opts(scope="game")))
334
        self.assertEqual(fixed, [export.APNG_DELAY_MS] * len(MOVES) + [export.APNG_END_MS])
335
        timed = frame_delays(export.export("apng", state, opts(scope="game", move_times=True)))
336
        # Bild n steht, bis Halbzug n gespielt ist
337
        self.assertEqual(timed, [500 * (ply + 1) for ply in range(len(MOVES))] + [export.APNG_END_MS])
338
339
    def test_long_think_time_fits_into_frame_control(self):
340
        self.assertEqual(export._delay(90_000), (9000, 100))
341
        self.assertEqual(export._delay(10), (export.APNG_MIN_MS, 1000))
342
343
    def test_pgn_move_times_optional(self):
344
        state = sample()
345
        state.times = {0: 3500, 1: 61000}
346
        with_times = export.export("pgn", state, opts(scope="game", move_times=True))
347
        self.assertIn("[%emt 0:00:03.5]", with_times)
348
        self.assertIn("[%emt 0:01:01]", with_times)
349
        self.assertNotIn("%emt", export.export("pgn", state, opts(scope="game")))
350
        without_evals = export.export("pgn", state, opts(scope="game", move_times=True, evals=False))
351
        self.assertNotIn("%wp", without_evals)
352
        self.assertIn("%emt", without_evals)
353
354
355
@unittest.skipUnless(export.webp_available(), "Pillow mit WebP fehlt")
356
class WebpTest(unittest.TestCase):
357
    def open(self, data):
358
        from PIL import Image
359
        return Image.open(io.BytesIO(data))
360
361
    def test_position_is_still_image_like_png(self):
362
        image = self.open(export.export("webp", sample(), opts(plies=8)))
363
        self.assertEqual(image.format, "WEBP")
364
        self.assertFalse(getattr(image, "is_animated", False))
365
        png = self.open(export.export("png", sample(), opts(plies=8)))
366
        self.assertEqual(image.size, png.size)
367
        self.assertEqual(image.mode, "RGBA")  # durchsichtiger Rand bleibt durchsichtig
368
369
    def test_game_is_animation_with_same_frames_as_apng(self):
370
        state = sample()
371
        state.times = {ply: 300 * (ply + 1) for ply in range(len(MOVES))}
372
        o = opts(scope="game", move_times=True)
373
        webp = self.open(export.export("webp", state, o))
374
        apng = self.open(export.export("apng", state, o))
375
        self.assertEqual(webp.n_frames, len(MOVES) + 1)
376
        delays = []
377
        for index in range(webp.n_frames):
378
            webp.seek(index)
379
            webp.load()
380
            apng.seek(index)
381
            delays.append(webp.info["duration"])
382
            self.assertEqual(webp.convert("RGB").tobytes(), apng.convert("RGB").tobytes(), f"Bild {index}")
383
        self.assertEqual(delays, [300 * (ply + 1) for ply in range(len(MOVES))] + [export.APNG_END_MS])
384
385
    def test_filename_by_scope(self):
386
        self.assertRegex(export.filename("webp", sample(), opts()), r"^stellung-.*\.webp$")
387
        self.assertRegex(export.filename("webp", sample(), opts(scope="game")), r"^partie-animiert-.*\.webp$")
388
389
390
class MotionTest(unittest.TestCase):
391
    def test_castling_moves_king_and_rook(self):
392
        board = chess.Board("r3k2r/8/8/8/8/8/8/R3K2R w KQkq - 0 1")
393
        motion = export.move_motion(board, chess.Move.from_uci("e1g1"))
394
        self.assertEqual([(src, dst) for _p, src, dst in motion["movers"]],
395
                         [(chess.E1, chess.G1), (chess.H1, chess.F1)])
396
        self.assertIsNone(motion["captured"])
397
398
    def test_en_passant_captures_the_pawn_beside(self):
399
        board = chess.Board("4k3/8/8/3pP3/8/8/8/4K3 w - d6 0 1")
400
        motion = export.move_motion(board, chess.Move.from_uci("e5d6"))
401
        self.assertEqual(motion["captured"], (chess.Piece(chess.PAWN, chess.BLACK), chess.D5))
402
403
    def test_timeline_holds_then_glides(self):
404
        timeline, end = export._video_timeline(sample(), opts(scope="game"))
405
        steps = round(export.VIDEO_MOVE_MS * export.VIDEO_FPS / 1000)
406
        self.assertEqual(len(timeline), len(MOVES) * (1 + steps) + 1)
407
        self.assertEqual(end, len(MOVES) * export.APNG_DELAY_MS + export.APNG_END_MS)
408
        starts = [start for _d, start in timeline]
409
        self.assertEqual(starts, sorted(set(starts)))  # streng steigend
410
        # erster Zug: ruht, dann gleitet er in den letzten VIDEO_MOVE_MS vor 1,5 s
411
        self.assertEqual(starts[0], 0)
412
        self.assertEqual(starts[1], export.APNG_DELAY_MS - export.VIDEO_MOVE_MS)
413
        self.assertEqual(starts[1 + steps], export.APNG_DELAY_MS)
414
        gliding = timeline[1][0]
415
        self.assertIsNone(gliding.badge)
416
        self.assertLess(gliding._anim["progress"], 1)
417
        self.assertEqual(timeline[steps][0]._anim["progress"], 1)
418
419
420
def _probe(data, suffix):
421
    """(Codec, Breite, Höhe, Bildzahl, Zeit des letzten Bilds in s) eines Videos, gelesen mit ffprobe."""
422
    with tempfile.NamedTemporaryFile(suffix=suffix) as fh:
423
        fh.write(data)
424
        fh.flush()
425
        info = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "v:0", "-count_frames",
426
                               "-show_entries", "stream=codec_name,width,height,nb_read_frames",
427
                               "-of", "default=nw=1", fh.name], capture_output=True, text=True).stdout
428
        times = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries",
429
                                "frame=pts_time", "-of", "csv=p=0", fh.name], capture_output=True, text=True).stdout
430
    fields = dict(line.split("=", 1) for line in info.split())
431
    return (fields["codec_name"], int(fields["width"]), int(fields["height"]), int(fields["nb_read_frames"]),
432
            float(times.split()[-1]))
433
434
435
@unittest.skipUnless(shutil.which("ffprobe") and not export.video_problem("webm") and not export.video_problem("mp4"),
436
                     "ffmpeg mit libvpx-vp9 und libx264 fehlt")
437
class VideoTest(unittest.TestCase):
438
    def test_webm_and_mp4(self):
439
        steps = round(export.VIDEO_MOVE_MS * export.VIDEO_FPS / 1000)
440
        frames = len(MOVES) * (1 + steps) + 1
441
        end = (len(MOVES) * export.APNG_DELAY_MS + export.APNG_END_MS) / 1000
442
        last_shown = end - export.APNG_END_MS / 1000  # Schlussstellung beginnt hier, steht bis ``end``
443
        for fmt, codec in (("webm", "vp9"), ("mp4", "h264")):
444
            codec_name, width, height, count, last = _probe(
445
                export.export(fmt, sample(), opts(scope="game")), "." + fmt)
446
            self.assertEqual(codec_name, codec)
447
            self.assertEqual(width, export.APNG_WIDTH)
448
            self.assertEqual(height % 2, 0)
449
            self.assertGreaterEqual(count, frames, fmt)  # lange Ruhe wird in Stücken wiederholt
450
            self.assertGreaterEqual(last, last_shown - 0.01, fmt)
451
452
    def test_duration_follows_move_times(self):
453
        state = sample()
454
        state.times = {ply: 2000 for ply in range(len(MOVES))}
455
        data = export.export("webm", state, opts(scope="game", move_times=True))
456
        with tempfile.NamedTemporaryFile(suffix=".webm") as fh:
457
            fh.write(data)
458
            fh.flush()
459
            duration = float(subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format=duration",
460
                                             "-of", "csv=p=0", fh.name], capture_output=True, text=True).stdout)
461
        self.assertAlmostEqual(duration, (len(MOVES) * 2000 + export.APNG_END_MS) / 1000, delta=0.1)
462
463
464
class FfmpegLookupTest(unittest.TestCase):
465
    def test_configured_path_wins_and_must_exist(self):
466
        self.assertIsNone(export.find_ffmpeg("/gibt/es/nicht/ffmpeg"))
467
        self.assertIn("/gibt/es/nicht/ffmpeg", export.video_problem("webm", "/gibt/es/nicht/ffmpeg"))
468
        with self.assertRaises(export.ExportError):
469
            export.export("mp4", sample(), opts(scope="game", ffmpeg="/gibt/es/nicht/ffmpeg"))
470
471
    def test_without_ffmpeg_in_path(self):
472
        from unittest import mock
473
        with mock.patch("shutil.which", return_value=None):
474
            self.assertIsNone(export.find_ffmpeg())
475
            self.assertIn("Einstellungen", export.video_problem("webm"))
476
477
478
class MoveTimesTest(unittest.TestCase):
479
    def test_format_time(self):
480
        self.assertEqual([notation.format_time(ms) for ms in (800, 9940, 9960, 42000, 65000, 3725000)],
481
                         ["0,8 s", "9,9 s", "10 s", "42 s", "1:05", "1:02:05"])
482
483
    def test_html_shows_times_only_when_asked(self):
484
        state = sample()
485
        state.times = {0: 3500, 3: 65000}
486
        page = export.export("html", state, opts(scope="game", move_times=True))
487
        self.assertIn('<small class="t" title="Bedenkzeit">3,5 s</small>', page)
488
        self.assertIn(">1:05</small>", page)
489
        self.assertEqual(page.count('class="t"'), 2)  # nur Züge mit bekannter Zeit
490
        self.assertNotIn('class="t"', export.export("html", state, opts(scope="game")))
491
492
    @unittest.skipUnless(shutil.which("pdftotext"), "pdftotext fehlt")
493
    def test_pdf_shows_times_only_when_asked(self):
494
        state = sample()
495
        state.times = {0: 3500, 3: 65000}
496
497
        def text(**kw):
498
            with tempfile.NamedTemporaryFile(suffix=".pdf") as fh:
499
                fh.write(export.export("pdf", state, opts(scope="game", **kw)))
500
                fh.flush()
501
                return subprocess.run(["pdftotext", fh.name, "-"], capture_output=True, text=True).stdout
502
503
        self.assertIn("3,5 s", text(move_times=True))
504
        self.assertIn("1:05", text(move_times=True))
505
        self.assertNotIn("3,5 s", text())
506
507
    def test_saved_times_come_back(self):
508
        state = sample()
509
        state.times = {0: 1200, 3: 45600}
510
        self.assertEqual(savegames.from_pgn(savegames.to_pgn(state)).times, {0: 1200, 3: 45600})
511
        self.assertEqual(state.truncated(1).times, {0: 1200})
512
513
    def test_times_from_lichess_clock(self):
514
        pgn = ('[TimeControl "180+2"]\n\n'
515
               "1. e4 { [%clk 0:03:00] } e5 { [%clk 0:03:00] } "
516
               "2. Nf3 { [%clk 0:02:55] } Nc6 { [%clk 0:02:51.5] } *")
517
        times = savegames.from_pgn(pgn).times
518
        # Restzeit davor − Restzeit danach + Zuschlag
519
        self.assertEqual(times, {0: 2000, 1: 2000, 2: 7000, 3: 10500})
520
521
    def test_emt_wins_over_clock(self):
522
        pgn = '1. e4 { [%clk 0:03:00] [%emt 0:00:04] } *'
523
        self.assertEqual(savegames.from_pgn(pgn).times, {0: 4000})
524
525
    def test_no_clock_no_times(self):
526
        self.assertEqual(savegames.from_pgn("1. e4 e5 *").times, {})
527
528
529
class MetaTest(unittest.TestCase):
530
    def test_filename(self):
531
        self.assertRegex(export.filename("pdf", sample(), opts(scope="game")), r"^partie-\d{4}-\d\d-\d\d\.pdf$")
532
        self.assertRegex(export.filename("png", sample(), opts(scope="game")), r"^stellung-.*\.png$")
533
        self.assertRegex(export.filename("apng", sample(), opts()), r"^partie-animiert-.*\.png$")
534
535
    def test_every_format_has_writer(self):
536
        for fmt in export.FORMATS:
537
            if (fmt == "pdf-latex" or fmt == "webp" and not export.webp_available()
538
                    or fmt in export.VIDEO_CODECS and export.video_problem(fmt)):
539
                continue
540
            for scope in export.FORMATS[fmt].scopes:
541
                self.assertTrue(export.export(fmt, sample(), opts(scope=scope, plies=5)))
542
543
544
if __name__ == "__main__":
545
    unittest.main()