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: Use avocado.utils.wait.wait_for to catch the
41        #       'displaysurface_create 1120x832' trace-event.
42        time.sleep(2)
43
44        self.vm.cmd('human-monitor-command',
45                    command_line='screendump %s' % screenshot_path)
46
47    @skipUnless(PIL_AVAILABLE, 'Python PIL not installed')
48    def test_bootrom_framebuffer_size(self):
49        self.set_machine('next-cube')
50        screenshot_path = os.path.join(self.workdir, "dump.ppm")
51        self.check_bootrom_framebuffer(screenshot_path)
52
53        width, height = Image.open(screenshot_path).size
54        self.assertEqual(width, 1120)
55        self.assertEqual(height, 832)
56
57    # Tesseract 4 adds a new OCR engine based on LSTM neural networks. The
58    # new version is faster and more accurate than version 3. The drawback is
59    # that it is still alpha-level software.
60    @skipUnless(tesseract_available(4), 'tesseract OCR tool not available')
61    def test_bootrom_framebuffer_ocr_with_tesseract(self):
62        self.set_machine('next-cube')
63        screenshot_path = os.path.join(self.workdir, "dump.ppm")
64        self.check_bootrom_framebuffer(screenshot_path)
65        lines = tesseract_ocr(screenshot_path)
66        text = '\n'.join(lines)
67        self.assertIn('Testing the FPU', text)
68        self.assertIn('System test failed. Error code', text)
69        self.assertIn('Boot command', text)
70        self.assertIn('Next>', text)
71
72if __name__ == '__main__':
73    QemuSystemTest.main()
74