File indexing completed on 2024-04-21 05:44:58
0001 #!/usr/bin/env python3 0002 0003 # SPDX-License-Identifier: MIT 0004 # SPDX-FileCopyrightText: 2023 Fushan Wen <qydwhotmail@gmail.com> 0005 0006 import base64 0007 import os 0008 import tempfile 0009 import time 0010 import unittest 0011 0012 import cv2 as cv 0013 import numpy as np 0014 from appium import webdriver 0015 from appium.options.common.base import AppiumOptions 0016 0017 0018 class ImageComparisonTest(unittest.TestCase): 0019 0020 driver: webdriver.Remote 0021 0022 @classmethod 0023 def setUpClass(cls) -> None: 0024 options = AppiumOptions() 0025 # The app capability may be a command line or a desktop file id. 0026 options.set_capability("app", f"{os.getenv('QML_EXEC', '/usr/bin/qml6')} {os.path.dirname(os.path.realpath(__file__))}/imagecomparison.qml") 0027 options.set_capability("timeouts", {'implicit': 30000}) 0028 # Boilerplate, always the same 0029 cls.driver = webdriver.Remote(command_executor='http://127.0.0.1:4723', options=options) 0030 time.sleep(3) # Make sure the window appears in the screenshot 0031 0032 @classmethod 0033 def tearDownClass(cls) -> None: 0034 # Make sure to terminate the driver again, lest it dangles. 0035 cls.driver.quit() 0036 0037 def test_matchTemplate(self) -> None: 0038 with tempfile.TemporaryDirectory() as temp_dir: 0039 saved_image_path: str = os.path.join(temp_dir, "screenshot.png") 0040 self.assertTrue(self.driver.get_screenshot_as_file(saved_image_path)) 0041 cv_first_image = cv.imread(saved_image_path, cv.IMREAD_COLOR) 0042 first_image = base64.b64encode(cv.imencode('.png', cv_first_image)[1].tobytes()) 0043 0044 cv_second_image = np.zeros((100, 100, 3), dtype=np.uint8) 0045 cv_second_image[:, :] = [0, 0, 255] # Red 0046 second_image = base64.b64encode(cv.imencode('.png', cv_second_image)[1].tobytes()) 0047 0048 result = self.driver.find_image_occurrence(first_image.decode(), second_image.decode()) 0049 self.assertEqual(result["rect"]["width"], cv_second_image.shape[1]) 0050 self.assertEqual(result["rect"]["height"], cv_second_image.shape[0]) 0051 0052 cv_second_image[:, :] = [0, 255, 0] # Green, which doesn't exist in the screenshot 0053 second_image = base64.b64encode(cv.imencode('.png', cv_second_image)[1].tobytes()) 0054 self.assertRaises(Exception, self.driver.find_image_occurrence, first_image.decode(), second_image.decode()) 0055 0056 0057 if __name__ == '__main__': 0058 unittest.main()