1#!/usr/bin/env python3
2#
3# Functional test that boots a VM and run OCR on the framebuffer
4#
5# Copyright (c) 2019 Philippe Mathieu-Daudé <f4bug@amsat.org>
6#
7# This work is licensed under the terms of the GNU GPL, version 2 or
8# later.  See the COPYING file in the top-level directory.
9
10import os
11import time
12
13from qemu_test import QemuSystemTest, Asset
14from unittest import skipUnless
15
16from qemu_test.tesseract import tesseract_available, tesseract_ocr
17
18PIL_AVAILABLE = True
19try:
20    from PIL import Image
21except ImportError:
22    PIL_AVAILABLE = False
23
24
25class NextCubeMachine(QemuSystemTest):
26
27    timeout = 15
28
29    ASSET_ROM = Asset(('https://sourceforge.net/p/previous/code/1350/tree/'
30                       'trunk/src/Rev_2.5_v66.BIN?format=raw'),
31                      '1b753890b67095b73e104c939ddf62eca9e7d0aedde5108e3893b0ed9d8000a4')
32
33    def check_bootrom_framebuffer(self, screenshot_path):
34        rom_path = self.ASSET_ROM.fetch()
35
36        self.vm.add_args('-bios', rom_path)
37        self.vm.launch()
38
39        self.log.info('VM launched, waiting for display')
40        # TODO: wait for the 'displaysurface_create 1120x832' trace-event.
41        time.sleep(2)
42
43        self.vm.cmd('human-monitor-command',
44                    command_line='screendump %s' % screenshot_path)
45
46    @skipUnless(PIL_AVAILABLE, 'Python PIL not installed')
47    def test_bootrom_framebuffer_size(self):
48        self.set_machine('next-cube')
49        screenshot_path = os.path.join(self.workdir, "dump.ppm")
50        self.check_bootrom_framebuffer(screenshot_path)
51
52        width, height = Image.open(screenshot_path).size
53        self.assertEqual(width, 1120)
54        self.assertEqual(height, 832)
55
56    # Tesseract 4 adds a new OCR engine based on LSTM neural networks. The
57    # new version is faster and more accurate than version 3. The drawback is
58    # that it is still alpha-level software.
59    @skipUnless(tesseract_available(4), 'tesseract OCR tool not available')
60    def test_bootrom_framebuffer_ocr_with_tesseract(self):
61        self.set_machine('next-cube')
62        screenshot_path = os.path.join(self.workdir, "dump.ppm")
63        self.check_bootrom_framebuffer(screenshot_path)
64        lines = tesseract_ocr(screenshot_path)
65        text = '\n'.join(lines)
66        self.assertIn('Testing the FPU', text)
67        self.assertIn('System test failed. Error code', text)
68        self.assertIn('Boot command', text)
69        self.assertIn('Next>', text)
70
71if __name__ == '__main__':
72    QemuSystemTest.main()
73