1#!/usr/bin/env python3 2# -*- coding: utf-8 -*- 3# Copyright (C) 2024 Huawei Device Co., Ltd. 4# Licensed under the Apache License, Version 2.0 (the "License"); 5# you may not use this file except in compliance with the License. 6# You may obtain a copy of the License at 7# 8# http://www.apache.org/licenses/LICENSE-2.0 9# 10# Unless required by applicable law or agreed to in writing, software 11# distributed under the License is distributed on an "AS IS" BASIS, 12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13# See the License for the specific language governing permissions and 14# limitations under the License. 15 16import os 17import zipfile 18import subprocess 19import re 20import time 21import json 22 23OUTPUT_PATH = "testModule" 24 25def GetPathByAttribute(tree, key, value): 26 attributes = tree['attributes'] 27 if attributes is None: 28 print("tree contains no attributes") 29 return None 30 path = [] 31 if attributes.get(key) == value: 32 return path 33 for index, child in enumerate(tree['children']): 34 child_path = path + [index] 35 result = GetPathByAttribute(child, key, value) 36 if result is not None: 37 return child_path + result 38 return None 39 40def GetElementByPath(tree, path): 41 if len(path) == 1: 42 return tree['children'][path[0]] 43 return GetElementByPath(tree['children'][path[0]], path[1:]) 44 45def GetLocationByText(tree, text): 46 path = GetPathByAttribute(tree, "text", text) 47 if path is None or len(path) == 0: 48 print(f"text not find in layout file") 49 element = GetElementByPath(tree, path) 50 locations = element['attributes']['bounds'].replace('[', '').replace(']', ' ').replace(',',' ').strip().split() 51 return int((int(locations[0]) + int(locations[2])) / 2), int((int(locations[1]) + int(locations[3])) / 2) 52 53def GetLayoutTree(): 54 output = subprocess.check_output("hdc shell uitest dumpLayout", text=True) 55 path = output.strip().split(":")[-1] 56 output = subprocess.check_output(f"hdc file recv {path} {OUTPUT_PATH}/layout.json") 57 with open(f"{OUTPUT_PATH}/layout.json", encoding="utf-8") as f: 58 tree = json.load(f) 59 return tree 60 61def TouchButtonByText(text): 62 layoutTree = GetLayoutTree() 63 location = GetLocationByText(layoutTree, text) 64 output = subprocess.check_output(f"hdc shell uitest uiInput click {location[0]} {location[1]}")