当前位置:网站首页>Appium+pytest+allure realizes app automated testing, which is a small test
Appium+pytest+allure realizes app automated testing, which is a small test
2022-07-21 22:23:00 【Test kid】
Hi, Hello everyone .Appium combination Pytest Develop App When automating tests , Do you know how to run use cases automatically and execute concurrently ? Don't talk too much , Go straight to the code , After all, it's not easy for everyone to see , So attach the code , Interested in their own research , To get the source code of the framework, you can go to ITester Software testing official account background reply “APP frame ”.
One 、 Project introduction
1、 Project environment
The project environment is as follows :
- Python
- pytest
- allure
- appium
- node
- Night God Simulator
2、 Project environment
The screenshot of the project structure is as follows :
Project structure description :
- base: The basic method of storage ;
- cases: Store test cases ;
- common: Some common methods ;
- config: Store the configuration file ;
- log: Log files ;
- image: Store test screenshots ;
- Page: The location element of the test ;
- report: Test report ;
- pytest.ini:pytest Startup profile ;
- requirements.txt: What needs to be installed py modular ;
- run.py: Run the file .
Two 、 Project implementation
1、base_page.py
base/base_page.py: Encapsulate some methods , Element Click 、 Input 、 lookup , There are also some public methods that you need to encapsulate here .
2、check_port.py
common/check_port.py: Check whether the port is occupied , If occupied, release .
#!/usr/bin/python3
# -*- coding:utf-8 -*-
# @Software:PyCharm
# @File : check_port.py
import socket
import os
def check_port(host, port):
""" Detect whether the specified port is occupied """
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # establish socket object
try:
s.connect((host, port))
s.shutdown(2)
except OSError:
print('port %s is available! ' % port)
return True
else:
print('port %s already be in use !' % port)
return False
def release_port(port):
""" Release the specified port """
cmd_find = 'netstat -aon | findstr {}'.format(port) # Find the... Of the corresponding port pid
print(cmd_find)
# Returns the result after the command is executed
result = os.popen(cmd_find).read()
print(result)
if str(port) and 'LISTENING' in result:
# Get the corresponding port pid process
i = result.index('LISTENING')
start = i + len('LISTENING') + 7
end = result.index('\n')
pid = result[start:end]
cmd_kill = 'taskkill -f -pid %s' % pid # Close the of the occupied port pid
print(cmd_kill)
os.popen(cmd_kill)
else:
print('port %s is available !' % port)
if __name__ == '__main__':
host = '127.0.0.1'
port = 4723
if not check_port(host, port):
print(" Port occupied ")
release_port(port)
3、get_main_js.py
common/get_main_js.py: obtain main.js, Use main.js start-up appium server.
#!/usr/bin/python3
# -*- coding:utf-8 -*-
# @Software:PyCharm
# @File : get_main_js.py
import subprocess
from config.root_config import LOG_DIR
"""
obtain main.js The location of , Use main.js start-up appium server
"""
class MainJs(object):
""" Get started appium Service main.js command """
def __init__(self, cmd: str = "where main.js"):
self.cmd = cmd
def get_cmd_result(self):
p = subprocess.Popen(self.cmd,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
with open(LOG_DIR + "/" + "cmd.txt", "w", encoding="utf-8") as f:
f.write(p.stdout.read().decode("gbk"))
with open(LOG_DIR + "/" + "cmd.txt", "r", encoding="utf-8") as f:
cmd_result = f.read().strip("\n")
return cmd_result
if __name__ == '__main__':
main = MainJs("where main.js")
print(main.get_cmd_result())
4、desired_caps.yaml
config/desired_caps.yml:app Automation test project related yaml.
5、root_config.py
config/root_config.py: Project file and path configuration information .
6、conftest.py
conftest.py:
#!/usr/bin/python3
# -*- coding:utf-8 -*-
# @Software:PyCharm
# @File : root_config.py
from drivers.app_driver import BaseDriver
import pytest
import time
from common.check_port import release_port
base_driver = None
def pytest_addoption(parser):
parser.addoption("--cmdopt", action="store", default="device_info", help=None)
@pytest.fixture(scope="session")
def cmd_opt(request):
return request.config.getoption("--cmdopt")
@pytest.fixture(scope="session")
def common_driver(cmd_opt):
cmd_opt = eval(cmd_opt)
print("cmd_opt", cmd_opt)
global base_driver
base_driver = BaseDriver(cmd_opt)
time.sleep(1)
driver = base_driver.get_base_driver()
yield driver
# driver.close_app()
driver.quit()
release_port(cmd_opt["server_port"])
7、test_concurrent.py
cases/test_concurrent.py: Draw the password and unlock .
#!/usr/bin/python3
# -*- coding:utf-8 -*-
# @Software:PyCharm
# @File : test_concurrent.py
import pytest
import time
from appium.webdriver.common.mobileby import MobileBy
from base.base_page import Base
class TestGesture(object):
def test_gesture_password(self, common_driver):
""" Simply do a process of drawing gesture password """
driver = common_driver
base = Base(driver)
base.skip_welcome_page('left', 3) # Sliding screen
time.sleep(3) # To see the effect of the slide screen
driver.start_activity(app_package="com.xxzb.fenwoo",
app_activity=".activity.user.CreateGesturePwdActivity")
commit_btn = (MobileBy.ID, 'com.xxzb.fenwoo:id/right_btn')
password_gesture = (MobileBy.ID, 'com.xxzb.fenwoo:id/gesturepwd_create_lockview')
element_commit = base.find_element(commit_btn)
element_commit.click()
password_element = base.find_element(password_gesture)
base.gesture_password(password_element, 1, 2, 3, 6, 5, 4, 7, 8, 9)
time.sleep(5) # See the effect
if __name__ == '__main__':
pytest.main()
8、run_case.py
run_case.py: Run the file .
#!/usr/bin/python3
# -*- coding:utf-8 -*-
# @Software:PyCharm
# @File : run_case.py
import pytest
import os
from multiprocessing import Pool
device_infos = [
{
"platform_version": "5.1.1",
"server_port": "4723",
"device_port": "62001",
},
{
"platform_version": "5.1.1",
"server_port": "4725",
"device_port": "62025",
}
]
def main(device_info):
pytest.main(["--cmdopt={}".format(device_info),
"--alluredir", "./allure-results", "-vs"])
os.system("allure generate allure-results -o allure-report --clean")
if __name__ == "__main__":
with Pool(2) as pool:
pool.map(main, device_infos)
pool.close()
pool.join()
3、 ... and 、 Project summary
1、 Project effect
As shown below , Finally, start APP, Draw unlock pattern , Get into APP Home page .
2、 Project ideas
Pytest As a unit testing framework , To complete the App Test automation requires Pytest and Appium Integration , Simultaneous utilization Allure Complete the output of test report . To write App The steps of automated testing are as follows :
1) Design to be tested APP Automated test cases for ;
2) newly build app Test project ;
3) To configure conftestpy Documents, etc. ;
4) Write the whole app Test case run file ;
5) Turn the designed automated test cases into scripts ;
3、 Project summary
The above is only a preliminary implementation of the requirement of multi mobile phone concurrency , It is hoped that more specifications of the project need to be introduced PO Design patterns , secondly base_page.py You can also encapsulate more methods , Only a few methods are encapsulated in the above code , If this concurrency is really introduced into the project, it certainly needs to be improved , Interested partners can try .
Finally, I also sorted out some software testing learning materials , It should be very helpful for small partners learning software testing , In order to better organize each module
Need my keywords for private messages 【555】 Get it for free Note that the keywords are :555
Full set of software test automation test teaching video
300G Download tutorial materials 【 Video tutorial +PPT+ Project source code 】
A complete set of software testing automation testing factory has been
边栏推荐
- Using kubekey to build kubernetes/kubesphere environment“
- 一起学习多线程、进程、开发板
- 10 classic C language interview basic algorithms
- Super practical 12 SQL optimization schemes
- 一起学习gcc gdb makefile
- 编写一个彻底拦截用户操作的程序
- Li Mu's learning notes of hands-on learning in depth (4) Chapter 1 preparatory knowledge section 2 data preprocessing
- Li Mu's learning notes of hands-on learning in depth (3) Chapter 1 preparatory knowledge section 1 data operation
- It turns out that someone plays vscode into idea, which is a little powerful
- 前 3 名突然变了?揭秘 7 月编程语言最新排行榜
猜你喜欢
liteos连接器脚本(二)
Why not use scheduled tasks to close orders?
nmn产品真的有其效果吗,服用几个月nmn后有哪些效果
Do you still have certificates to participate in the open source community?
一起学习gcc gdb makefile
Liteos opening
手把手教你如何使用Charles抓包
通用流程编排引擎介绍
关于对自动化测试的理解:目的与本质!(新手必看)
Learning notes for beginners to OpenGL (II) Download glew, configure the environment of glew and initialization of glew
随机推荐
liteos开篇
Digital transformation | shell uses polarion software to digitize and process capital project data
Super practical 12 SQL optimization schemes
Imitate memz to make a special effect program
Addition, subtraction, multiplication and division of numbers of string type
New text document
Do you know how to build data-driven, keyword driven and hybrid selenium framework
Huawei liteos memory management source code and architecture analysis
The top three suddenly changed? Unveil the latest ranking of programming languages in July
Some superficial research and development stages involve software summarization
[ALM] Introduction to the demand management solution of polaron ALM
liteos连接器脚本(一)
ALM系统如何通过容器管理物件(以Polarion为例)
如何写好技术安全需求TSR?
Database foundation
前 3 名突然变了?揭秘 7 月编程语言最新排行榜
Working mode of arm and register organization (review)
UI自动化测试之ddt实战
Qt5 GUI
Healthcare technology innovators use polarion software to reduce test creation time by up to 75%