├── .gitignore ├── Disclaimer.md ├── LICENSE ├── NOTICE.md ├── README.md ├── bean ├── __init__.py ├── case.py └── step.py ├── decoder.py ├── exporter ├── __init__.py ├── appium.py └── macaca.py ├── handler.py ├── requirements.txt ├── shell.py └── util └── __init__.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by https://www.gitignore.io/api/python,pycharm 2 | # Edit at https://www.gitignore.io/?templates=python,pycharm 3 | 4 | ### PyCharm ### 5 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm 6 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 7 | 8 | # idea 9 | .idea/ 10 | 11 | # Gradle and Maven with auto-import 12 | # When using Gradle or Maven with auto-import, you should exclude module files, 13 | # since they will be recreated, and may cause churn. Uncomment if using 14 | # auto-import. 15 | # *.iml 16 | # *.ipr 17 | 18 | # CMake 19 | cmake-build-*/ 20 | 21 | # File-based project format 22 | *.iws 23 | 24 | # IntelliJ 25 | out/ 26 | 27 | # mpeltonen/sbt-idea plugin 28 | .idea_modules/ 29 | 30 | # JIRA plugin 31 | atlassian-ide-plugin.xml 32 | 33 | # Crashlytics plugin (for Android Studio and IntelliJ) 34 | com_crashlytics_export_strings.xml 35 | crashlytics.properties 36 | crashlytics-build.properties 37 | fabric.properties 38 | 39 | ### PyCharm Patch ### 40 | # Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721 41 | 42 | # *.iml 43 | # modules.xml 44 | # .idea/misc.xml 45 | # *.ipr 46 | 47 | ### Python ### 48 | # Byte-compiled / optimized / DLL files 49 | __pycache__/ 50 | *.py[cod] 51 | *$py.class 52 | 53 | # C extensions 54 | *.so 55 | 56 | # Distribution / packaging 57 | .Python 58 | build/ 59 | develop-eggs/ 60 | dist/ 61 | downloads/ 62 | eggs/ 63 | .eggs/ 64 | lib/ 65 | lib64/ 66 | parts/ 67 | sdist/ 68 | var/ 69 | wheels/ 70 | pip-wheel-metadata/ 71 | share/python-wheels/ 72 | *.egg-info/ 73 | .installed.cfg 74 | *.egg 75 | MANIFEST 76 | 77 | # PyInstaller 78 | # Usually these files are written by a python script from a template 79 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 80 | *.manifest 81 | *.spec 82 | 83 | # Installer logs 84 | pip-log.txt 85 | pip-delete-this-directory.txt 86 | 87 | # Unit test / coverage reports 88 | htmlcov/ 89 | .tox/ 90 | .nox/ 91 | .coverage 92 | .coverage.* 93 | .cache 94 | nosetests.xml 95 | coverage.xml 96 | *.cover 97 | .hypothesis/ 98 | .pytest_cache/ 99 | 100 | # Translations 101 | *.mo 102 | *.pot 103 | 104 | # Scrapy stuff: 105 | .scrapy 106 | 107 | # Sphinx documentation 108 | docs/_build/ 109 | 110 | # PyBuilder 111 | target/ 112 | 113 | # pyenv 114 | .python-version 115 | 116 | # pipenv 117 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 118 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 119 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 120 | # install all needed dependencies. 121 | #Pipfile.lock 122 | 123 | # celery beat schedule file 124 | celerybeat-schedule 125 | 126 | # SageMath parsed files 127 | *.sage.py 128 | 129 | # Spyder project settings 130 | .spyderproject 131 | .spyproject 132 | 133 | # Rope project settings 134 | .ropeproject 135 | 136 | # Mr Developer 137 | .mr.developer.cfg 138 | .project 139 | .pydevproject 140 | 141 | # mkdocs documentation 142 | /site 143 | 144 | # mypy 145 | .mypy_cache/ 146 | .dmypy.json 147 | dmypy.json 148 | 149 | # Pyre type checker 150 | .pyre/ 151 | 152 | # End of https://www.gitignore.io/api/python,pycharm -------------------------------------------------------------------------------- /Disclaimer.md: -------------------------------------------------------------------------------- 1 | SoloPi开源自动化测试工具与配套工具的功能是我们针对不同用户的需求而特别提供。SoloPi与配套工具提供的应用、代码和资料的著作权均归SoloPi所有,用户具有自由的使用权。 2 | 3 | 如果用户下载、安装、使用、修改本工具及相关代码,即表明用户信任该工具。那么,用户在使用本工具时造成对用户自己或他人任何形式的损失和伤害,SoloPi与配套工具不承担任何责任。 4 | 5 | 本工具不含有任何旨在破坏用户计算机数据和获取用户隐私信息的恶意代码;本工具使用过程中获取到的操作信息在打印日志时默认会进行脱敏,且不会进行上传;当应用出现异常时,用户可手动选择是否通过邮件上报故障日志,不会泄漏用户隐私。 6 | 7 | 对于用户从非工具发布站点下载的应用,本工具无法保证其是否感染计算机病毒、是否隐藏有伪装的特洛伊木马程序或者黑客软件。用户使用此类软件,将可能导致不可预测的风险,建议用户不要轻易下载、安装、使用。本工具不承担由此产生的一切法律责任。 8 | 9 | 用户不得利用本工具提供的功能误导、欺骗他人;用户仅可将本工具用于学习交流,不得用于非法用途;不得故意避开或者破坏本工具为保护著作权而采取的技术措施。 10 | 11 | 本工具提供的功能经过详细的测试,但不能保证与所有的软硬件系统完全兼容,不能保证本工具完全没有错误。如果出现不兼容及软件错误的情况,用户可以到交流群获得技术支持。我们将尽力为用户解决问题、解答疑问。 12 | 13 | 使用本工具所提供的系统所产生的风险由用户自行承担。在适用法律允许的最大范围内,对因使用或不能使用本系统所产生的损害及风险,本工具不承担任何相关责任。 14 | 15 | 如果本协议中的任何条款无论因何种原因完全或部分无效或不具有执行力,或违反任何适用的法律条款,则该条款被视为删除,但本协议的其余条款仍有效并且具有约束力。 16 | 17 | 作者有权根据有关法律、法规的变化以及工具的发展需求等因素修改本协议。若新旧协议有冲突,以最新版本协议为准。如果用户继续使用本系统,则视为您接受本协议的变动。 18 | 19 | 本协议的一切解释权与修改权归本工具所有。 -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright 2015-present, Ant Financial Services Group 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /NOTICE.md: -------------------------------------------------------------------------------- 1 | # The Open Source Projects we used. 2 | 3 | ## Appium 4 | 5 | > https://github.com/appium/appium 6 | 7 | Copyright Appium 8 | 9 | Licensed under the Apache License, Version 2.0 (the "License"); you may not use 10 | this file except in compliance with the License. You may obtain a copy of the 11 | License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable 12 | law or agreed to in writing, software distributed under the License is distributed 13 | on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 14 | or implied. See the License for the specific language governing permissions and 15 | imitations under the License. 16 | 17 | > Apache License 2.0: http://www.apache.org/licenses/LICENSE-2.0 18 | 19 | 20 | ## Macaca 21 | 22 | > https://github.com/alibaba/macaca 23 | 24 | MIT LICENSE 25 | 26 | Copyright (c) 2015-present Alibaba Group Holding Limited and other contributors. 27 | 28 | Permission is hereby granted, free of charge, to any person obtaining 29 | a copy of this software and associated documentation files (the 30 | "Software"), to deal in the Software without restriction, including 31 | without limitation the rights to use, copy, modify, merge, publish, 32 | distribute, sublicense, and/or sell copies of the Software, and to 33 | permit persons to whom the Software is furnished to do so, subject to 34 | the following conditions: 35 | 36 | The above copyright notice and this permission notice shall be 37 | included in all copies or substantial portions of the Software. 38 | 39 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 40 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 41 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 42 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 43 | LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 44 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 45 | WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SoloPi-Converter 2 | 3 | ## Thanks 4 | 感谢前期参与SoloPi脚本转化工作的同学:https://testerhome.com/topics/20346 5 | 6 | ## Introduction (简介) 7 | 8 | SoloPi 用例转化工具,支持将 SoloPi JSON 用例转化为其他自动化脚本语言,目前支持转化为 Appium 和 Macaca 脚本。 9 | 10 | ## Features (功能) 11 | 12 | * 支持自定义控件查找方式 13 | 14 | * 多种类型转化格式 15 | 16 | * 便于扩展其他转换类型 17 | 18 | ## Limitation (限制) 19 | 20 | - Python 3.6+ 21 | - Pillow 22 | 23 | ## Getting Started (必看) 24 | 25 | 0. 在SoloPi设置里,将`用例加密秘钥`设置为空,然后在用例列表中长按导出用例 26 | 1. 执行入口 `python3 handler.py` 27 | 2. 输入 SoloPi 脚本地址 28 | 3. 选择转化类型(目前支持 Appium 和 Macaca ) 29 | 3. 选择输出目录 30 | 4. 每一步单独选择查找方式 31 | 5. 导出完成,可以在对应目录查看导出的用例脚本,导出的脚本文件会被命名为 main.xxx 。 32 | 33 | ## 代码导读 34 | 35 | - bean: 用例格式定义。 36 | - decoder.py: 解析 SoloPi 原始用例 37 | - exporter: 实际导出用例的 module ,已实现 Appium 和 Macaca 导出,其他语言可以通过扩展 BaseExporter 的形式来实现。 38 | - handler.py: 主流程执行器 39 | - shell.py: 用于处理用户输入、选择 40 | - util: 常用功能 41 | 42 | ## Related projects (相关的项目) 43 | 44 | [SoloPi 自动化测试工具](https://github.com/alipay/SoloPi) 45 | 46 | [版权声明](NOTICE.md) 47 | 48 | ## Discuss (讨论群) 49 | 50 | 面向行业测试相关从业人员,对工具有什么意见或者建议的话也欢迎Issue、PR或加群讨论。 51 | 52 | - 钉钉群(一群已满,请添加二群): 53 | 54 | ![group](https://gw.alipayobjects.com/mdn/rms_e29b5f/afts/img/A*K6wzRZfxDv8AAAAAAAAAAABkARQnAQ) 55 | 56 | * 除了钉钉群外,我们在TesterHome也有相关板块,可以在社区里留言回复 https://testerhome.com/topics/node152 57 | 58 | ## Contribution (参与贡献) 59 | 60 | 独乐乐不如众乐乐,开源的核心还是在于技术的分享交流,当你对开源项目产生了一些想法时,有时还会有更加Smart的表达方式,比如(Thanks to uiautomator2): 61 | 62 | - 我们的业务需要这项功能 ==> 我加了个功能,可以在很多场景用到,已经提交MR了。 63 | 64 | - 这块儿功能有更详细的文档吗? ==> 这块内容我改了一下,更方便使用了,帮忙合并一下。 65 | 66 | - 我在XXX上怎么用不了啊? ==> 在XXX手机上功能有点问题,我已经修复了。 67 | 68 | - 我刚用了XXX功能,怎么和文档上不一样啊? ==> 我根据文档试用了一下,碰到了一些坑,这是我在ATA、Lark发的踩坑贴,有些内容可以补充一下。 69 | 70 | - 这个是不是一直维护啊? ==> 我能做些什么? 71 | 72 | 当然,Star、Fork、Merge Request、Issue等功能也随时欢迎大家使用哈! 73 | 74 | 如果你有什么好的想法,也可以与我们直接联系,进行更加深入的讨论,我们希望将这套移动端的测试工具框架进行更好的推广,欢迎大家多多宣传。 75 | 76 | ## License (协议) 77 | 78 | This project is under the Apache 2.0 License. See the [LICENSE](LICENSE) file for the full license text. 79 | 80 | ```text 81 | Copyright (C) 2015-present, Ant Financial Services Group 82 | 83 | Licensed under the Apache License, Version 2.0 (the "License"); 84 | you may not use this file except in compliance with the License. 85 | You may obtain a copy of the License at 86 | 87 | http://www.apache.org/licenses/LICENSE-2.0 88 | 89 | Unless required by applicable law or agreed to in writing, software 90 | distributed under the License is distributed on an "AS IS" BASIS, 91 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 92 | See the License for the specific language governing permissions and 93 | limitations under the License. 94 | ``` 95 | 96 | ## Disclaimer (免责声明) 97 | 98 | [免责声明](Disclaimer.md) 99 | -------------------------------------------------------------------------------- /bean/__init__.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one or more 2 | # contributor license agreements. See the NOTICE file distributed with 3 | # this work for additional information regarding copyright ownership. 4 | # The ASF licenses this file to You under the Apache License, Version 2.0 5 | # (the "License"); you may not use this file except in compliance with 6 | # the License. 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 | 16 | class Rect(object): 17 | """ 18 | Wrapper for Rectangle type 19 | """ 20 | 21 | def __init__(self, left: int, top: int, right: int, bottom: int) -> None: 22 | self.left = left 23 | self.top = top 24 | self.right = right 25 | self.bottom = bottom 26 | 27 | def width(self) -> int: 28 | return self.right - self.left 29 | 30 | def height(self) -> int: 31 | return self.bottom - self.top 32 | 33 | def center_x(self) -> int: 34 | return int((self.right + self.left) / 2) 35 | 36 | def center_y(self) -> int: 37 | return int((self.top + self.bottom) / 2) -------------------------------------------------------------------------------- /bean/case.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one or more 2 | # contributor license agreements. See the NOTICE file distributed with 3 | # this work for additional information regarding copyright ownership. 4 | # The ASF licenses this file to You under the Apache License, Version 2.0 5 | # (the "License"); you may not use this file except in compliance with 6 | # the License. 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 | 16 | from datetime import datetime 17 | 18 | 19 | class CaseInfo(object): 20 | 21 | def __init__(self, case_name: str, case_desc: str, target_app_label: str, target_app_package: str, 22 | create_time: datetime, modify_time: datetime, platform: str, step_count: int = None, root: str = None, 23 | img_root: str = None): 24 | self.img_root = img_root 25 | self.root = root 26 | self.case_name = case_name 27 | self.case_desc = case_desc 28 | self.target_app_label = target_app_label 29 | self.target_app_package = target_app_package 30 | self.create_time = create_time 31 | self.modify_time = modify_time 32 | self.platform = platform 33 | self.step_count = step_count 34 | 35 | 36 | class Case(object): 37 | def __init__(self, case_info: CaseInfo, case_list: list): 38 | self.case_info = case_info 39 | self.case_list = case_list -------------------------------------------------------------------------------- /bean/step.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one or more 2 | # contributor license agreements. See the NOTICE file distributed with 3 | # this work for additional information regarding copyright ownership. 4 | # The ASF licenses this file to You under the Apache License, Version 2.0 5 | # (the "License"); you may not use this file except in compliance with 6 | # the License. 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 | 16 | from bean import Rect 17 | 18 | 19 | class Node(object): 20 | def __init__(self, node_type: str, text: str, xpath: str, 21 | description: str, res_id: str, class_name: str, bound: Rect, capture: bytearray): 22 | self.node_type = node_type 23 | self.text = text 24 | self.xpath = xpath 25 | self.description = description 26 | self.res_id = res_id 27 | self.class_name = class_name 28 | self.bound = bound 29 | self.capture = capture 30 | 31 | def has_capture(self) -> bool: 32 | return self.capture is not None 33 | 34 | def export_capture(self, file: str) -> bool: 35 | """ 36 | Export capture to file 37 | :param file: target file 38 | """ 39 | if not self.has_capture(): 40 | return False 41 | with open(file, "wb") as f: 42 | f.write(self.capture) 43 | return True 44 | 45 | 46 | class Method(object): 47 | def __init__(self, method: str, param: dict): 48 | self.method = method 49 | self.param = dict(param) 50 | 51 | def get_param(self, key: str, default=None): 52 | val = self.param.get(key) 53 | if val is None: 54 | return default 55 | return val 56 | 57 | 58 | class Step(object): 59 | """ 60 | SoloPi Step Item 61 | """ 62 | 63 | def __init__(self, node: Node, method: Method) -> None: 64 | super().__init__() 65 | self.node = node 66 | self.method = method 67 | -------------------------------------------------------------------------------- /decoder.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one or more 2 | # contributor license agreements. See the NOTICE file distributed with 3 | # this work for additional information regarding copyright ownership. 4 | # The ASF licenses this file to You under the Apache License, Version 2.0 5 | # (the "License"); you may not use this file except in compliance with 6 | # the License. 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 | 16 | from bean.case import CaseInfo, Case 17 | from datetime import datetime 18 | 19 | from bean.step import * 20 | from util import * 21 | 22 | 23 | class Decoder(object): 24 | """ 25 | SoloPi Case Decoder 26 | """ 27 | 28 | def decode(self, content: str) -> Case: 29 | case = json.loads(content) 30 | if case is None or type(case) is not dict: 31 | return None 32 | 33 | advance = json.loads(case.get('advanceSettings')) 34 | platform = un_empty(advance.get('platform'), 'Android') 35 | case_info = CaseInfo(case.get('caseName'), case.get('caseDesc'), case.get('targetAppLabel'), 36 | case.get('targetAppPackage'), datetime.fromtimestamp(case.get('gmtCreate') / 1000), 37 | datetime.fromtimestamp(case.get('gmtModify') / 1000), platform) 38 | 39 | case_wrap = json.loads(case.get('operationLog')) 40 | case_list = case_wrap.get('steps') 41 | 42 | real_step_list = [] 43 | for case in case_list: 44 | step = self.decode_step(case) 45 | if step is not None: 46 | real_step_list.append(step) 47 | 48 | case_info.step_count = len(real_step_list) 49 | return Case(case_info, real_step_list) 50 | 51 | def decode_step(self, case) -> Step: 52 | node_map = case.get('operationNode') 53 | method_map = case.get('operationMethod') 54 | if method_map is None: 55 | return None 56 | 57 | target_node = None 58 | if node_map is not None: 59 | target_node = self.decode_node(node_map) 60 | 61 | target_method = Method(method_map.get('actionEnum'), method_map.get('operationParam')) 62 | return Step(target_node, target_method) 63 | 64 | def decode_node(self, node): 65 | rect_map = node.get('nodeBound') 66 | rect = Rect(rect_map.get('left'), rect_map.get('top'), rect_map.get('right'), rect_map.get('bottom')) 67 | extra = node.get('extra') 68 | capture = None 69 | if extra is not None: 70 | capture_str = extra.get('captureImage') 71 | if capture_str is not None and not is_empty(capture_str): 72 | capture = decode_base64(capture_str) 73 | return Node(node.get('nodeType'), node.get('text'), node.get('xpath'), node.get('description'), 74 | node.get('resourceId'), node.get('className'), rect, capture) 75 | -------------------------------------------------------------------------------- /exporter/__init__.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one or more 2 | # contributor license agreements. See the NOTICE file distributed with 3 | # this work for additional information regarding copyright ownership. 4 | # The ASF licenses this file to You under the Apache License, Version 2.0 5 | # (the "License"); you may not use this file except in compliance with 6 | # the License. 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 | 16 | from abc import abstractmethod 17 | 18 | from bean.case import CaseInfo 19 | from bean.step import Step 20 | 21 | 22 | class BaseExporter(object): 23 | """ 24 | Export SoloPi case to file 25 | """ 26 | 27 | @staticmethod 28 | @abstractmethod 29 | def get_name() -> str: 30 | """ 31 | Get name for this exporter 32 | """ 33 | pass 34 | 35 | @abstractmethod 36 | def get_file_extension(self) -> str: 37 | """ 38 | Get File Extension for this type 39 | :return: 40 | """ 41 | pass 42 | 43 | def export_head(self, case_info: CaseInfo) -> str: 44 | """ 45 | Export file head, you can export some universal method in this part 46 | """ 47 | return "" 48 | 49 | @abstractmethod 50 | def export_step(self, step: Step, index: int, case_info: CaseInfo) -> str: 51 | """ 52 | Export every step 53 | """ 54 | pass 55 | 56 | def export_tail(self, case_info: CaseInfo) -> str: 57 | """ 58 | Export file tail, for driver stop 59 | """ 60 | return "" 61 | -------------------------------------------------------------------------------- /exporter/appium.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one or more 2 | # contributor license agreements. See the NOTICE file distributed with 3 | # this work for additional information regarding copyright ownership. 4 | # The ASF licenses this file to You under the Apache License, Version 2.0 5 | # (the "License"); you may not use this file except in compliance with 6 | # the License. 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 | 16 | import os 17 | 18 | from bean.case import CaseInfo 19 | from bean.step import Step, Node, Method 20 | from exporter import BaseExporter 21 | from shell import require_selection 22 | from util import * 23 | 24 | 25 | class AppiumExporter(BaseExporter): 26 | """ 27 | Appium Export 28 | """ 29 | 30 | STEP_INDEX_MAP = { 31 | "Text": lambda x: "driver.find_element_by_name(%s)" % unquotation(x.text), 32 | "Description": lambda x: "driver.find_element_by_accessibility_id(%s)" % unquotation(x.description), 33 | "Xpath": lambda x: "driver.find_element_by_xpath(%s)" % unquotation(x.xpath), 34 | "ResourceId": lambda x: "driver.find_element_by_id(%s)" % unquotation(x.res_id), 35 | "ClassName": lambda x: "driver.find_element_by_tag_name(\"%s\")" % x.class_name, 36 | "Capture": lambda x: "driver.find_element_by_image(\"%s\")" % x 37 | } 38 | HEAD_INFO = '''from appium import webdriver 39 | from appium.webdriver.common.touch_action import TouchAction 40 | from PIL import Image 41 | import re 42 | import os 43 | import time 44 | 45 | def load_x_y(rect, percent): 46 | try: 47 | xs, ys = percent.split(',', 1) 48 | x = int(rect.left + float(xs) * rect.width()) 49 | y = int(rect.top + float(ys) * rect.height()) 50 | return x, y 51 | except: 52 | return rect.center_x(), rect.center_y() 53 | 54 | def swipe(driver, rect, from_percent, to_percent, duration): 55 | fx, fy = load_x_y(rect, from_percent) 56 | tx, ty = load_x_y(rect, to_percent) 57 | driver.swipe(fx, fy, tx, ty, duration) 58 | 59 | def wait_node(get_node, max_time): 60 | n = None 61 | start = time.time() 62 | while time.time() - start < max_time: 63 | try: 64 | n = get_node() 65 | if n is not None: 66 | break 67 | except: 68 | pass 69 | return n is not None 70 | 71 | 72 | class WrapTouchAction: 73 | def __init__(self, driver, rect=None, percent=None, x=None, y=None) -> None: 74 | touch = TouchAction(driver) 75 | if x is None or y is None: 76 | if percent is None or ',' not in percent: 77 | x = rect.center_x() 78 | y = rect.center_y() 79 | else: 80 | x, y = load_x_y(rect, percent) 81 | touch.press(x=x, y=y) 82 | self.touch = touch 83 | 84 | def move_to(self, rect=None, percent=None, x=None, y=None, time=500): 85 | if x is None or y is None: 86 | if percent is None or ',' not in percent: 87 | x = rect.center_x() 88 | y = rect.center_y() 89 | else: 90 | x, y = load_x_y(rect, percent) 91 | self.touch.move_to(x=x, y=y).wait(time) 92 | return self 93 | 94 | def perform(self): 95 | self.touch.release().perform() 96 | 97 | PLATFORM = '%s' 98 | PACKAGE = '%s' 99 | ACTIVITY = '' 100 | 101 | desired_caps = {} 102 | desired_caps['platformName'] = PLATFORM 103 | desired_caps['platformVersion'] = '' 104 | desired_caps['deviceName'] = '' 105 | desired_caps['appPackage'] = PACKAGE 106 | desired_caps['appActivity'] = ACTIVITY 107 | 108 | driver = webdriver.Remote('', desired_caps) 109 | 110 | # Take Screenshot to get real screen size 111 | assert driver.get_screenshot_as_file("/tmp/_solo_test.png") 112 | screen = Image.open('/tmp/_solo_test.png') 113 | width, height = screen.size 114 | screen.close() 115 | os.remove('/tmp/_solo_test.png') 116 | SCREEN = {'x': 0, 'y': 0, 'height': height, 'width': width} 117 | ''' 118 | 119 | TAIL_INFO = '\ndriver.quit()' 120 | 121 | SELECT_NODE_ATTR_INFO = '''Please select an attribute below for node location''' 122 | 123 | @staticmethod 124 | def get_name() -> str: 125 | return "Appium(Python)" 126 | 127 | def get_file_extension(self) -> str: 128 | return "py" 129 | 130 | def export_head(self, case_info: CaseInfo) -> str: 131 | return self.HEAD_INFO % (case_info.platform, case_info.target_app_package) 132 | 133 | def export_tail(self, case_info: CaseInfo) -> str: 134 | return self.TAIL_INFO 135 | 136 | def export_step(self, step: Step, index: int, case_info: CaseInfo) -> str: 137 | if step.node is not None: 138 | return self.export_node_step(step.node, step.method, index, case_info) 139 | else: 140 | return self.export_global_step(step.method, index, case_info) 141 | 142 | def export_node_step(self, node: Node, method: Method, index: int, case_info: CaseInfo) -> str: 143 | node_location = self.read_node_locate_way(node, index, case_info.img_root, case_info.root) 144 | return export_node_action(node_location, method) 145 | 146 | def export_global_step(self, method: Method, index: int, case_info: CaseInfo) -> str: 147 | return export_method_action(method) 148 | 149 | def read_node_locate_way(self, node: Node, index: int, img_root: str, root: str) -> str: 150 | selections = [] 151 | display = [] 152 | if not is_empty(node.text): 153 | selections.append("Text") 154 | display.append("Text: " + node.text) 155 | 156 | if not is_empty(node.description): 157 | selections.append("Description") 158 | display.append("Description: " + node.text) 159 | 160 | if not is_empty(node.res_id): 161 | selections.append("ResourceId") 162 | display.append("ResourceId: " + node.res_id) 163 | 164 | if not is_empty(node.class_name): 165 | selections.append("ClassName") 166 | display.append("ClassName: " + node.class_name) 167 | 168 | if not is_empty(node.xpath): 169 | selections.append("Xpath") 170 | display.append("Xpath: " + node.xpath) 171 | 172 | target_location = None 173 | if img_root is not None and node.capture is not None: 174 | node.export_capture("/tmp/tmp.jpg") 175 | target_location = os.path.join(img_root, '%d.png' % (index + 1)) 176 | export_png("/tmp/tmp.jpg", target_location) 177 | 178 | selections.append("Capture") 179 | display.append("Capture: " + target_location) 180 | 181 | selection = require_selection(self.SELECT_NODE_ATTR_INFO, display) 182 | if selection < 0: 183 | return "" 184 | 185 | # Get location way 186 | select_type = selections[selection] 187 | if select_type == 'Capture': 188 | return self.STEP_INDEX_MAP[select_type](target_location.replace(root + '/', '')) 189 | else: 190 | return self.STEP_INDEX_MAP[select_type](node) 191 | 192 | 193 | 194 | def load_x_y(percent): 195 | try: 196 | xs, ys = percent.split(',', 1) 197 | return float(xs), float(ys) 198 | except: 199 | return 0.5, 0.5 200 | 201 | 202 | def export_node_action(node_location: str, method: Method) -> str: 203 | me = method.method 204 | px, py = load_x_y(method.get_param("localClickPos", "0.5,0.5")) 205 | text = method.get_param("text") 206 | if me == 'CLICK' or me == 'CLICK_QUICK': 207 | return "%s.click()" % node_location 208 | elif me == 'CLICK_IF_EXISTS': 209 | return '''try: 210 | %s.click() 211 | except NoSuchElementException: 212 | pass''' % node_location 213 | elif me == 'LONG_CLICK': 214 | return '''action = TouchAction(driver) 215 | action.long_press(%s, duration=%s) 216 | action.perform()''' % (node_location, method.get_param("text", "2000")) 217 | elif me == 'SCROLL_TO_BOTTOM': 218 | text = un_empty(text, "100") 219 | ty = py + int(text) / 100 220 | return '''rect = %s.rect 221 | swipe(rect, '%s,%s', '%s,%s', 300)''' % (node_location, px, py, px, ty) 222 | elif me == 'SCROLL_TO_TOP': 223 | text = un_empty(text, "100") 224 | ty = py - int(text) / 100 225 | return '''rect = %s.rect 226 | swipe(rect, '%s,%s', '%s,%s', 300)''' % (node_location, px, py, px, ty) 227 | elif me == 'SCROLL_TO_RIGHT': 228 | text = un_empty(text, "100") 229 | tx = px + int(text) / 100 230 | return '''rect = %s.rect 231 | swipe(rect, '%s,%s', '%s,%s', 300)''' % (node_location, px, py, tx, py) 232 | elif me == 'SCROLL_TO_LEFT': 233 | text = un_empty(text, "100") 234 | tx = px - int(text) / 100 235 | return '''rect = %s.rect 236 | swipe(rect, '%s,%s', '%s,%s', 300)''' % (node_location, px, py, tx, py) 237 | elif me == 'INPUT' or me == 'SAFETY_INPUT': 238 | text = un_empty(text, "") 239 | return '''%s.send_keys(%s) 240 | driver.execute_script("mobile: hideKeyboard")''' % (node_location, unquotation(text)) 241 | elif me == 'INPUT_SEARCH': 242 | text = un_empty(text, "") 243 | return '''ele = %s 244 | ele.send_keys(%s) 245 | driver.execute_script("mobile:performEditorAction", {"action": "done"})''' % (node_location, unquotation(text)) 246 | elif me == 'ASSERT': 247 | assert_mode = method.get_param('assertMode') 248 | assert_content = method.get_param('assertInputContent') 249 | if assert_mode == 'assert_accurate': 250 | return "assert %s.text == %s" % (node_location, unquotation(assert_content)) 251 | elif assert_mode == 'assert_contain': 252 | return "assert %s in %s.text" % (unquotation(assert_content), node_location) 253 | elif assert_mode == 'assert_regular': 254 | return "assert re.match(r%s, %s.text) is not None" % (unquotation('^' + assert_content + '$'), node_location) 255 | elif assert_mode == 'assert_dayu': 256 | return "assert float(%s.text) > float('%s')" % (node_location, assert_content) 257 | elif assert_mode == 'assert_dayuAndEqual': 258 | return "assert float(%s.text) >= float('%s')" % (node_location, assert_content) 259 | elif assert_mode == 'assert_equal': 260 | return "assert float(%s.text) == float('%s')" % (node_location, assert_content) 261 | elif assert_mode == 'assert_xiaoyu': 262 | return "assert float(%s.text) < float('%s')" % (node_location, assert_content) 263 | elif assert_mode == 'assert_xiaoyuAndEqual': 264 | return "assert float(%s.text) <= float('%s')" % (node_location, assert_content) 265 | else: 266 | return "" 267 | elif me == 'GESTURE': 268 | points_str = method.get_param('gesturePath') 269 | ges_filter = int(method.get_param('gestureFilter')) 270 | points = json.loads(points_str) 271 | action = 'rect = %s.rect\nWrapTouchAction(driver, rect, "%s,%s")' % \ 272 | (node_location, points[0]['x'], points[0]['y']) 273 | for i in range(1, len(points)): 274 | point = points[i] 275 | action += '.move_to(rect, "%s,%s", time=%s)' % (point.get('x'), point.get('y'), ges_filter) 276 | 277 | return action + '.perform()' 278 | elif me == 'SLEEP_UNTIL': 279 | max_time = int(text) / 1000 280 | return 'assert wait_node(lambda: %s, %s)' % (node_location, max_time) 281 | else: 282 | return "" 283 | 284 | 285 | def export_method_action(method: Method) -> str: 286 | me = method.method 287 | text = method.get_param("text") 288 | if me == 'BACK': 289 | return 'driver.back()' 290 | elif me == 'MENU': 291 | return 'driver.keyevent(1)' 292 | elif me == 'KEYCODE_GLOBAL': 293 | return 'driver.press_keycode(%s)' % text 294 | elif me == 'HANDLE_ALERT': 295 | return '''try : 296 | alert = driver.switchTo().alert() 297 | alert.accpet() 298 | except: 299 | pass''' 300 | elif me == 'JUMP_TO_PAGE': 301 | return '''driver.execute_script('mobile: shell', { 302 | 'command': 'am', 303 | 'args': ['start', '\'%s\''], 304 | 'includeStderr': True, 305 | 'timeout': 5000 306 | })''' % method.get_param('scheme') 307 | elif me == 'GLOBAL_GESTURE': 308 | points_str = method.get_param('gesturePath') 309 | ges_filter = int(method.get_param('gestureFilter')) 310 | points = json.loads(points_str) 311 | action = 'WrapTouchAction(driver, SCREEN, "%s,%s")' % \ 312 | (points[0]['x'], points[0]['y']) 313 | for i in range(1, len(points)): 314 | point = points[i] 315 | action += '.move_to(SCREEN, "%s,%s", time=%s)' % (point.get('x'), point.get('y'), ges_filter) 316 | 317 | return action + '.perform()' 318 | elif me == 'HOME': 319 | return 'driver.keyevent(3)' 320 | elif me == 'EXECUTE_SHELL': 321 | if text.startswith('adb shell '): 322 | text = text[10:] 323 | split = text.split(' ') 324 | return '''driver.execute_script('mobile: shell', { 325 | 'command': %s, 326 | 'args': %s, 327 | 'includeStderr': True, 328 | 'timeout': 5000 329 | })''' % (unquotation(split[0]), unquotation(split[1:])) 330 | elif me == 'GLOBAL_SCROLL_TO_BOTTOM': 331 | distance = method.get_param('scrollDistance') 332 | time = method.get_param('ScrollTime') 333 | distance = int(un_empty(distance, '40')) / 100 334 | distance = max(min(distance, 0.9), 0.1) 335 | time = un_empty(time, '300') 336 | return 'swipe(SCREEN, \'%s,%s\', \'%s,%s\', %s)' % (0.5, 0.5 - distance / 2, 0.5, 0.5 + distance / 2, time) 337 | elif me == 'GLOBAL_SCROLL_TO_TOP': 338 | distance = method.get_param('scrollDistance') 339 | time = method.get_param('ScrollTime') 340 | distance = int(un_empty(distance, '40')) / 100 341 | distance = max(min(distance, 0.9), 0.1) 342 | time = un_empty(time, '300') 343 | return 'swipe(SCREEN, \'%s,%s\', \'%s,%s\', %s)' % (0.5, 0.5 + distance / 2, 0.5, 0.5 - distance / 2, time) 344 | elif me == 'GLOBAL_SCROLL_TO_RIGHT': 345 | distance = method.get_param('scrollDistance') 346 | time = method.get_param('ScrollTime') 347 | distance = int(un_empty(distance, '40')) / 100 348 | distance = max(min(distance, 0.9), 0.1) 349 | time = un_empty(time, '300') 350 | return 'swipe(SCREEN, \'%s,%s\', \'%s,%s\', %s)' % (0.5 - distance / 2, 0.5, 0.5 + distance / 2, 0.5, time) 351 | elif me == 'GLOBAL_SCROLL_TO_LEFT': 352 | distance = method.get_param('scrollDistance') 353 | time = method.get_param('ScrollTime') 354 | distance = int(un_empty(distance, '40')) / 100 355 | distance = max(min(distance, 0.9), 0.1) 356 | time = un_empty(time, '300') 357 | return 'swipe(SCREEN, \'%s,%s\', \'%s,%s\', %s)' % (0.5 + distance / 2, 0.5, 0.5 - distance / 2, 0.5, time) 358 | elif me == 'SLEEP': 359 | return 'time.sleep(%s)' % (int(text) / 1000) 360 | elif me == 'RESTART_APP' or me == 'GOTO_INDEX': 361 | return '''driver.close_app() 362 | time.sleep(1000) 363 | driver.start_activity(PACKAGE, ACTIVITY) 364 | ''' 365 | elif me == 'SCREENSHOT': 366 | return 'driver.save_screenshot(\'%s.png\')' % text 367 | elif me == 'KILL_PROCESS': 368 | return 'driver.close_app()' 369 | else: 370 | return "" 371 | -------------------------------------------------------------------------------- /exporter/macaca.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one or more 2 | # contributor license agreements. See the NOTICE file distributed with 3 | # this work for additional information regarding copyright ownership. 4 | # The ASF licenses this file to You under the Apache License, Version 2.0 5 | # (the "License"); you may not use this file except in compliance with 6 | # the License. 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 | 16 | from bean.case import CaseInfo 17 | from bean.step import Step, Node, Method 18 | from exporter import BaseExporter 19 | from shell import require_selection 20 | from util import * 21 | 22 | 23 | class MacacaExporter(BaseExporter): 24 | """ 25 | Macaca Export 26 | """ 27 | 28 | STEP_INDEX_MAP = { 29 | "Text": lambda x: "driver.element_by_name(%s)" % unquotation(x.text), 30 | "Description": lambda x: "driver.element_by_accessibility_id(%s)" % unquotation(x.description), 31 | "Xpath": lambda x: "driver.element_by_xpath(%s)" % unquotation(x.xpath), 32 | "ResourceId": lambda x: "driver.element_by_id(%s)" % unquotation(x.res_id), 33 | "ClassName": lambda x: "driver.element_by_tag_name(\"%s\")" % x.class_name, 34 | } 35 | HEAD_INFO = '''import time 36 | import os 37 | 38 | from macaca import WebDriver 39 | from PIL import Image 40 | 41 | PACKAGE = '%s' 42 | 43 | def load_x_y(rect, percent): 44 | try: 45 | xs, ys = percent.split(',', 1) 46 | x = int(rect.left + float(xs) * rect.width()) 47 | y = int(rect.top + float(ys) * rect.height()) 48 | return x, y 49 | except: 50 | return rect.center_x(), rect.center_y() 51 | 52 | def swipe(driver, rect, from_percent, to_percent, duration): 53 | fx, fy = load_x_y(rect, from_percent) 54 | tx, ty = load_x_y(rect, to_percent) 55 | driver.touch('drag', { 56 | 'fromX': fx, 57 | 'fromY': fy, 58 | 'toX': tx, 59 | 'toY': ty, 60 | 'steps': duration 61 | }) 62 | 63 | def wait_node(get_node, max_time): 64 | n = None 65 | start = time.time() 66 | while time.time() - start < max_time: 67 | try: 68 | n = get_node() 69 | if n is not None: 70 | break 71 | except: 72 | pass 73 | return n is not None 74 | 75 | 76 | class WrapTouchAction: 77 | def __init__(self, rect=None, percent=None, x=None, y=None) -> None: 78 | points = [] 79 | if x is None or y is None: 80 | if percent is None or ',' not in percent: 81 | x = rect.center_x() 82 | y = rect.center_y() 83 | else: 84 | x, y = load_x_y(rect, percent) 85 | points.append([x, y, 0]) 86 | self.points = points 87 | 88 | def move_to(self, rect=None, percent=None, x=None, y=None, time=500): 89 | if x is None or y is None: 90 | if percent is None or ',' not in percent: 91 | x = rect.center_x() 92 | y = rect.center_y() 93 | else: 94 | x, y = load_x_y(rect, percent) 95 | self.points.append([x, y, time]) 96 | return self 97 | 98 | def perform(self, driver): 99 | if len(self.points) < 2: 100 | return 101 | 102 | points = self.points 103 | actions = [{ 104 | 'type': 'drag', 105 | 'fromX': points[0][0], 106 | 'fromY': points[0][1], 107 | 'toX': points[1][0], 108 | 'toY': points[1][1], 109 | 'steps': points[1][2] 110 | }] 111 | 112 | for i in range(2, len(points)): 113 | actions.append({ 114 | 'type': 'drag', 115 | 'toX': points[i][0], 116 | 'toY': points[i][1], 117 | 'steps': points[i][2] 118 | }) 119 | 120 | driver.touch(actions) 121 | 122 | desired_caps = { 123 | 'browserName': 'Chrome', # Electon, Safari(iOS). 124 | 'platformName': '%s', # iOS, Android. 125 | 'platformVersion': '*', 126 | 'autoAcceptAlerts': True # Accept the Alerts in page automaticalliy. 127 | } 128 | 129 | server_url = 'http://127.0.0.1:3456/wd/hub/' 130 | 131 | # You can omit the server_url if you use the default url above. 132 | driver = WebDriver(desired_caps, server_url) 133 | 134 | # Take Screenshot to get real screen size 135 | driver.save_screenshot("/tmp/_solo_test.png") 136 | screen = Image.open('/tmp/_solo_test.png') 137 | width, height = screen.size 138 | screen.close() 139 | os.remove('/tmp/_solo_test.png') 140 | SCREEN = {'x': 0, 'y': 0, 'height': height, 'width': width} 141 | ''' 142 | 143 | TAIL_INFO = '\ndriver.quit()' 144 | 145 | SELECT_NODE_ATTR_INFO = '''Please select an attribute below for node location''' 146 | 147 | @staticmethod 148 | def get_name() -> str: 149 | return "Macaca(Python)" 150 | 151 | def get_file_extension(self) -> str: 152 | return "py" 153 | 154 | def export_head(self, case_info: CaseInfo) -> str: 155 | return self.HEAD_INFO % (case_info.target_app_package, case_info.platform) 156 | 157 | def export_tail(self, case_info: CaseInfo) -> str: 158 | return self.TAIL_INFO 159 | 160 | def export_step(self, step: Step, index: int, case_info: CaseInfo) -> str: 161 | if step.node is not None: 162 | return self.export_node_step(step.node, step.method, index, case_info) 163 | else: 164 | return self.export_global_step(step.method, index, case_info) 165 | 166 | def export_node_step(self, node: Node, method: Method, index: int, case_info: CaseInfo) -> str: 167 | node_location = self.read_node_locate_way(node) 168 | return export_node_action(node_location, method) 169 | 170 | def export_global_step(self, method: Method, index: int, case_info: CaseInfo) -> str: 171 | return export_method_action(method) 172 | 173 | def read_node_locate_way(self, node: Node) -> str: 174 | selections = [] 175 | display = [] 176 | if not is_empty(node.text): 177 | selections.append("Text") 178 | display.append("Text: " + node.text) 179 | 180 | if not is_empty(node.description): 181 | selections.append("Description") 182 | display.append("Description: " + node.text) 183 | 184 | if not is_empty(node.res_id): 185 | selections.append("ResourceId") 186 | display.append("ResourceId: " + node.res_id) 187 | 188 | if not is_empty(node.class_name): 189 | selections.append("ClassName") 190 | display.append("ClassName: " + node.class_name) 191 | 192 | if not is_empty(node.xpath): 193 | selections.append("Xpath") 194 | display.append("Xpath: " + node.xpath) 195 | 196 | selection = require_selection(self.SELECT_NODE_ATTR_INFO, display) 197 | if selection < 0: 198 | return "" 199 | 200 | # Get location way 201 | select_type = selections[selection] 202 | return self.STEP_INDEX_MAP[select_type](node) 203 | 204 | 205 | def load_x_y(percent): 206 | try: 207 | xs, ys = percent.split(',', 1) 208 | return float(xs), float(ys) 209 | except: 210 | return 0.5, 0.5 211 | 212 | 213 | def export_node_action(node_location: str, method: Method) -> str: 214 | me = method.method 215 | px, py = load_x_y(method.get_param("localClickPos", "0.5,0.5")) 216 | text = method.get_param("text") 217 | if me == 'CLICK' or me == 'CLICK_QUICK': 218 | return "%s.click()" % node_location 219 | elif me == 'CLICK_IF_EXISTS': 220 | return '''try: 221 | %s.click() 222 | except NoSuchElementException: 223 | pass''' % node_location 224 | elif me == 'LONG_CLICK': 225 | return '%s.touch(\'press\', {\'steps\': %s})' % (node_location, method.get_param("text", "2000")) 226 | elif me == 'SCROLL_TO_BOTTOM': 227 | text = un_empty(text, "100") 228 | ty = py + int(text) / 100 229 | return '''rect = %s.rect 230 | swipe(rect, '%s,%s', '%s,%s', 300)''' % (node_location, px, py, px, ty) 231 | elif me == 'SCROLL_TO_TOP': 232 | text = un_empty(text, "100") 233 | ty = py - int(text) / 100 234 | return '''rect = %s.rect 235 | swipe(rect, '%s,%s', '%s,%s', 300)''' % (node_location, px, py, px, ty) 236 | elif me == 'SCROLL_TO_RIGHT': 237 | text = un_empty(text, "100") 238 | tx = px + int(text) / 100 239 | return '''rect = %s.rect 240 | swipe(rect, '%s,%s', '%s,%s', 300)''' % (node_location, px, py, tx, py) 241 | elif me == 'SCROLL_TO_LEFT': 242 | text = un_empty(text, "100") 243 | tx = px - int(text) / 100 244 | return '''rect = %s.rect 245 | swipe(rect, '%s,%s', '%s,%s', 300)''' % (node_location, px, py, tx, py) 246 | elif me == 'INPUT' or me == 'SAFETY_INPUT': 247 | text = un_empty(text, "") 248 | return '''%s.keys(%s) 249 | driver.execute_script("mobile: hideKeyboard")''' % (node_location, unquotation(text)) 250 | elif me == 'INPUT_SEARCH': 251 | text = un_empty(text, "") 252 | return '''%s.keys(%s) 253 | driver.execute_script("mobile:performEditorAction", {"action": "done"})''' % (node_location, unquotation(text)) 254 | elif me == 'ASSERT': 255 | assert_mode = method.get_param('assertMode') 256 | assert_content = method.get_param('assertInputContent') 257 | if assert_mode == 'assert_accurate': 258 | return "assert %s.text == %s" % (node_location, unquotation(assert_content)) 259 | elif assert_mode == 'assert_contain': 260 | return "assert %s in %s.text" % (unquotation(assert_content), node_location) 261 | elif assert_mode == 'assert_regular': 262 | return "assert re.match(r%s, %s.text) is not None" % ( 263 | unquotation('^' + assert_content + '$'), node_location) 264 | elif assert_mode == 'assert_dayu': 265 | return "assert float(%s.text) > float('%s')" % (node_location, assert_content) 266 | elif assert_mode == 'assert_dayuAndEqual': 267 | return "assert float(%s.text) >= float('%s')" % (node_location, assert_content) 268 | elif assert_mode == 'assert_equal': 269 | return "assert float(%s.text) == float('%s')" % (node_location, assert_content) 270 | elif assert_mode == 'assert_xiaoyu': 271 | return "assert float(%s.text) < float('%s')" % (node_location, assert_content) 272 | elif assert_mode == 'assert_xiaoyuAndEqual': 273 | return "assert float(%s.text) <= float('%s')" % (node_location, assert_content) 274 | else: 275 | return "" 276 | elif me == 'GESTURE': 277 | points_str = method.get_param('gesturePath') 278 | ges_filter = int(method.get_param('gestureFilter')) 279 | points = json.loads(points_str) 280 | action = 'rect = %s.rect\nWrapTouchAction(rect, "%s,%s")' % \ 281 | (node_location, points[0]['x'], points[0]['y']) 282 | for i in range(1, len(points)): 283 | point = points[i] 284 | action += '.move_to(rect, "%s,%s", time=%s)' % (point.get('x'), point.get('y'), ges_filter) 285 | 286 | return action + '.perform(driver)' 287 | elif me == 'SLEEP_UNTIL': 288 | max_time = int(text) 289 | return node_location.replace('.element', '.wait_for_element').replace('")', '", timeout=%s)' % max_time) 290 | else: 291 | return "" 292 | 293 | 294 | def export_method_action(method: Method) -> str: 295 | me = method.method 296 | text = method.get_param("text") 297 | if me == 'BACK': 298 | return 'driver.back()' 299 | elif me == 'MENU': 300 | return 'driver.keyevent(1)' 301 | elif me == 'KEYCODE_GLOBAL': 302 | return 'driver.press_keycode(%s)' % text 303 | elif me == 'HANDLE_ALERT': 304 | return '''try : 305 | driver.acceptAlert() 306 | except: 307 | pass''' 308 | elif me == 'JUMP_TO_PAGE': 309 | return '''driver.execute_script('mobile: shell', { 310 | 'command': 'am', 311 | 'args': ['start', '\'%s\''], 312 | 'includeStderr': True, 313 | 'timeout': 5000 314 | })''' % method.get_param('scheme') 315 | elif me == 'GLOBAL_GESTURE': 316 | points_str = method.get_param('gesturePath') 317 | ges_filter = int(method.get_param('gestureFilter')) 318 | points = json.loads(points_str) 319 | action = 'WrapTouchAction(driver, SCREEN, "%s,%s")' % \ 320 | (points[0]['x'], points[0]['y']) 321 | for i in range(1, len(points)): 322 | point = points[i] 323 | action += '.move_to(SCREEN, "%s,%s", time=%s)' % (point.get('x'), point.get('y'), ges_filter) 324 | 325 | return action + '.perform()' 326 | elif me == 'HOME': 327 | return 'driver.keyevent(3)' 328 | elif me == 'EXECUTE_SHELL': 329 | if text.startswith('adb shell '): 330 | text = text[10:] 331 | split = text.split(' ') 332 | return '''driver.execute_script('mobile: shell', { 333 | 'command': %s, 334 | 'args': %s, 335 | 'includeStderr': True, 336 | 'timeout': 5000 337 | })''' % (unquotation(split[0]), unquotation(split[1:])) 338 | elif me == 'GLOBAL_SCROLL_TO_BOTTOM': 339 | distance = method.get_param('scrollDistance') 340 | time = method.get_param('ScrollTime') 341 | distance = int(un_empty(distance, '40')) / 100 342 | distance = max(min(distance, 0.9), 0.1) 343 | time = un_empty(time, '300') 344 | return 'swipe(SCREEN, \'%s,%s\', \'%s,%s\', %s)' % (0.5, 0.5 - distance / 2, 0.5, 0.5 + distance / 2, time) 345 | elif me == 'GLOBAL_SCROLL_TO_TOP': 346 | distance = method.get_param('scrollDistance') 347 | time = method.get_param('ScrollTime') 348 | distance = int(un_empty(distance, '40')) / 100 349 | distance = max(min(distance, 0.9), 0.1) 350 | time = un_empty(time, '300') 351 | return 'swipe(SCREEN, \'%s,%s\', \'%s,%s\', %s)' % (0.5, 0.5 + distance / 2, 0.5, 0.5 - distance / 2, time) 352 | elif me == 'GLOBAL_SCROLL_TO_RIGHT': 353 | distance = method.get_param('scrollDistance') 354 | time = method.get_param('ScrollTime') 355 | distance = int(un_empty(distance, '40')) / 100 356 | distance = max(min(distance, 0.9), 0.1) 357 | time = un_empty(time, '300') 358 | return 'swipe(SCREEN, \'%s,%s\', \'%s,%s\', %s)' % (0.5 - distance / 2, 0.5, 0.5 + distance / 2, 0.5, time) 359 | elif me == 'GLOBAL_SCROLL_TO_LEFT': 360 | distance = method.get_param('scrollDistance') 361 | time = method.get_param('ScrollTime') 362 | distance = int(un_empty(distance, '40')) / 100 363 | distance = max(min(distance, 0.9), 0.1) 364 | time = un_empty(time, '300') 365 | return 'swipe(SCREEN, \'%s,%s\', \'%s,%s\', %s)' % (0.5 + distance / 2, 0.5, 0.5 - distance / 2, 0.5, time) 366 | elif me == 'SLEEP': 367 | return 'time.sleep(%s)' % (int(text) / 1000) 368 | elif me == 'RESTART_APP' or me == 'GOTO_INDEX': 369 | return '''driver.close_app() 370 | time.sleep(1000) 371 | driver.execute_script('mobile: shell', { 372 | 'command': am, 373 | 'args': ['start', PACKAGE], 374 | 'includeStderr': True, 375 | 'timeout': 5000 376 | })''' 377 | elif me == 'SCREENSHOT': 378 | return 'driver.save_screenshot(\'%s.png\')' % text 379 | elif me == 'KILL_PROCESS': 380 | return 'driver.close()' 381 | else: 382 | return "" 383 | -------------------------------------------------------------------------------- /handler.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one or more 2 | # contributor license agreements. See the NOTICE file distributed with 3 | # this work for additional information regarding copyright ownership. 4 | # The ASF licenses this file to You under the Apache License, Version 2.0 5 | # (the "License"); you may not use this file except in compliance with 6 | # the License. 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 | 16 | import os 17 | 18 | from decoder import Decoder 19 | from exporter import BaseExporter 20 | from exporter.appium import AppiumExporter 21 | from exporter.macaca import MacacaExporter 22 | from shell import * 23 | from util import is_empty 24 | 25 | EXPORTERS = { 26 | AppiumExporter.get_name(): AppiumExporter, 27 | MacacaExporter.get_name(): MacacaExporter 28 | } 29 | 30 | TAG = "main" 31 | 32 | 33 | def main(): 34 | path = read("Please input SoloPi case path:") 35 | content = None 36 | with open(path) as f: 37 | content = f.read() 38 | 39 | if is_empty(content): 40 | log(TAG, "Path %s is invalid" % path) 41 | return 42 | 43 | case = Decoder().decode(content) 44 | if case is None: 45 | log(TAG, "Path %s is invalid" % path) 46 | return 47 | 48 | selections = [] 49 | for key in EXPORTERS: 50 | selections.append(key) 51 | 52 | # config export folder 53 | select = require_selection("Please select transform format", selections) 54 | handler: BaseExporter = EXPORTERS[selections[select]]() 55 | 56 | folder = read("Please input export folder:") 57 | os.mkdir(folder) 58 | 59 | main_file = os.path.join(folder, 'main.' + handler.get_file_extension()) 60 | img_folder = os.path.join(folder, 'screenshots') 61 | os.mkdir(img_folder) 62 | 63 | case_info = case.case_info 64 | case_info.root = folder 65 | case_info.img_root = img_folder 66 | 67 | case_list = case.case_list 68 | 69 | # export to main file 70 | with open(main_file, 'w') as f: 71 | f.write(handler.export_head(case_info)) 72 | f.write('\n') 73 | for i in range(len(case_list)): 74 | f.write(handler.export_step(case_list[i], i + 1, case_info)) 75 | f.write('\n') 76 | f.write(handler.export_tail(case_info)) 77 | 78 | log(TAG, "Export finished") 79 | 80 | 81 | if __name__ == '__main__': 82 | main() 83 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | Pillow -------------------------------------------------------------------------------- /shell.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one or more 2 | # contributor license agreements. See the NOTICE file distributed with 3 | # this work for additional information regarding copyright ownership. 4 | # The ASF licenses this file to You under the Apache License, Version 2.0 5 | # (the "License"); you may not use this file except in compliance with 6 | # the License. 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 | 16 | 17 | def require_selection(info: str, selection: list) -> int: 18 | """ 19 | Read User Selection 20 | :param info: 21 | :param selection: 22 | :return: 23 | """ 24 | if selection is None or len(selection) == 0: 25 | # no selection provided 26 | return -1 27 | 28 | print(info) 29 | for i in range(len(selection)): 30 | print("[%d] %s" % (i + 1, selection[i])) 31 | 32 | i = 0 33 | while i < 3: 34 | raw_input = input("Please select[%d-%d]:" % (1, len(selection))) 35 | try: 36 | select = int(raw_input) 37 | if len(selection) >= select > 0: 38 | return select - 1 39 | except: 40 | print("Invalid input: %s" % raw_input) 41 | i += 1 42 | return -1 43 | 44 | 45 | def read(info: str) -> str: 46 | return input(info) 47 | 48 | 49 | def log(tag: str, info: str): 50 | print('[%s] %s' % (tag, info)) 51 | -------------------------------------------------------------------------------- /util/__init__.py: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one or more 2 | # contributor license agreements. See the NOTICE file distributed with 3 | # this work for additional information regarding copyright ownership. 4 | # The ASF licenses this file to You under the Apache License, Version 2.0 5 | # (the "License"); you may not use this file except in compliance with 6 | # the License. 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 | 16 | import json 17 | import base64 18 | 19 | from PIL import Image 20 | 21 | 22 | def unquotation(content: str) -> str: 23 | """ 24 | remove quotation 25 | :param content: 26 | :return: 27 | """ 28 | return json.dumps(content, ensure_ascii=False) 29 | 30 | 31 | def export_png(source: str, target: str): 32 | """ 33 | export image to png 34 | :param source: 35 | :param target: 36 | :return: 37 | """ 38 | img = Image.open(source) 39 | img = img.convert('RGB') 40 | img.save(target) 41 | 42 | 43 | def is_empty(content: str): 44 | """ 45 | :param content: 46 | :return: is empty 47 | """ 48 | if content is None or len(content.strip()) == 0: 49 | return True 50 | return False 51 | 52 | 53 | def un_empty(content: str, default: str): 54 | """ 55 | Ensure not empty 56 | :param content: 57 | :param default: 58 | :return: 59 | """ 60 | if is_empty(content): 61 | return default 62 | return content 63 | 64 | 65 | def decode_base64(content: str) -> bytearray: 66 | """ 67 | decode base64 string to bytearray 68 | :param content: 69 | :return: 70 | """ 71 | base64_info = content.encode('ascii') 72 | return bytearray(base64.b64decode(base64_info)) 73 | --------------------------------------------------------------------------------