提交 d8d160aa authored 作者: 彭甘宇's avatar 彭甘宇

使用自动化测试hytest框架

上级 f901b59d
# 默认忽略的文件
/shelf/
/workspace.xml
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding">
<file url="file://$PROJECT_DIR$/测试数据/登录用户数据.csv" charset="GBK" />
</component>
</project>
\ No newline at end of file
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="PyPep8Inspection" enabled="true" level="WEAK WARNING" enabled_by_default="true">
<option name="ignoredErrors">
<list>
<option value="W292" />
</list>
</option>
</inspection_tool>
<inspection_tool class="PyPep8NamingInspection" enabled="true" level="WEAK WARNING" enabled_by_default="true">
<option name="ignoredErrors">
<list>
<option value="N812" />
</list>
</option>
</inspection_tool>
</profile>
</component>
\ No newline at end of file
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Black">
<option name="sdkName" value="Python 3.12" />
</component>
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.10" project-jdk-type="Python SDK" />
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/运维标准版.iml" filepath="$PROJECT_DIR$/.idea/运维标准版.iml" />
</modules>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="jdk" jdkName="Python 3.10" jdkType="Python SDK" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
\ No newline at end of file
1、整合脚本使用hytest框架,需要手动下载本地环境:pip install hytest
\ No newline at end of file
# from lib.login import *
# def suite_setup():
# INFO('初始化浏览器')
# open_browser()
#
#
# def suite_teardown():
# INFO('进行清除操作')
# wd = GSTORE['wd']
# wd.quit()
#
\ No newline at end of file
from lib.login import *
# def suite_setup():
# INFO('初始化浏览器')
# open_browser()
# # run_login_tests()
#
#
# def suite_teardown():
# INFO('进行清除操作')
# wd = GSTORE['wd']
# wd.quit()
class user_login_001:
name = 'login_test_01'
def teststeps(self):
STEP(1, '打开网页')
open_browser()
wd = GSTORE['wd']
STEP(2, '用户登录')
user_login("admin@pgy1", "ub@123456", "csba")
# run_login_tests()
STEP(3, '验证是否登录成功')
get_menu = WebDriverWait(wd, 10).until(
EC.presence_of_element_located((By.CSS_SELECTOR, '.el-message__content'))
)
get_menu1 = get_menu.text
CHECK_POINT('检查是否出现弹窗', get_menu1 == "操作成功!")
def suite_teardown():
wd.quit()
class user_login_002:
name = 'login_test_02'
def teststeps(self):
STEP(1, '打开网页')
wd = GSTORE['wd']
STEP(2, '用户登录')
user_login("admin@pgy", "ub@123456", "csba")
# run_login_tests()
STEP(3, '验证是否登录成功')
get_menu = WebDriverWait(wd, 10).until(
EC.presence_of_element_located((By.CSS_SELECTOR, '.el-message__content'))
)
get_menu1 = get_menu.text
CHECK_POINT('检查是否出现弹窗', get_menu1 == "操作成功!")
STEP(4, '清除数据')
def suite_teardown():
INFO('进行清除操作')
wd.quit()
from selenium import webdriver
from hytest import *
import pandas as pd
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.edge.options import Options
from time import sleep
def open_browser():
INFO('打开浏览器')
# wd = webdriver.Chrome()
edge_options = Options()
edge_options.add_argument('--ignore-certificate-errors')
edge_options.add_argument('--disable-blink-features=AutomationControlled')
wd = webdriver.Edge(options=edge_options)
GSTORE['wd'] = wd
# wd.get('https://rms.ubainsyun.com/#/login')
wd.get('https://192.168.1.118:8443/#/login')
wd.implicitly_wait(10)
def user_login(username, password, captcha):
wd = GSTORE['wd']
INFO('输入登录账号')
username_input = WebDriverWait(wd, 3).until(
EC.presence_of_element_located((By.XPATH, "//input[@placeholder='请输入登录账号']"))
)
username_input.clear()
username_input.send_keys(username)
INFO('输入登录密码')
password_input = WebDriverWait(wd, 3).until(
EC.presence_of_element_located((By.XPATH, "//input[@placeholder='请输入登录密码']"))
)
password_input.clear()
password_input.send_keys(password)
INFO('输入验证码')
captcha_input = WebDriverWait(wd, 3).until(
EC.presence_of_element_located((By.XPATH, "//input[@placeholder='请输入验证码(区分大小写)']"))
)
captcha_input.clear()
captcha_input.send_keys(captcha)
INFO('点击登录按钮')
login_button = WebDriverWait(wd, 3).until(
EC.element_to_be_clickable((By.XPATH, "//div[@class='loginButton']"))
)
login_button.click()
sleep(2)
def validate_input(username, password, captcha):
if not isinstance(username, str) or not isinstance(password, str) or not isinstance(captcha, str):
raise ValueError("Invalid input type")
if len(username) < 1 or len(password) < 1 or len(captcha) < 1:
raise ValueError("Input cannot be empty")
def run_login_tests(df):
# 遍历每一行
for index, row in df.iterrows():
username = row.get('username', None)
password = row.get('password', None)
captcha = row.get('captcha', None)
if username and password and captcha:
try:
validate_input(username, password, captcha)
user_login(username, password, captcha)
except ValueError as e:
print(f"Invalid input at row {index}: {e}")
def main():
# 获取当前脚本的目录
current_dir = os.path.dirname(os.path.abspath(__file__))
csv_file_path = os.path.join(current_dir, '../testdata/登录信息.csv')
try:
if not os.path.exists(csv_file_path):
print(f"File not found: {csv_file_path}")
return
df = pd.read_csv(csv_file_path, encoding='utf-8')
run_login_tests(df)
except Exception as e:
print(f"An error occurred: {e}")
if __name__ == "__main__":
main()
username,password,captcha
ywys@pgy,ub@1234567,csba
\ No newline at end of file
import pandas as pd
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.edge.service import Service
from selenium.webdriver.edge.options import Options
import logging
import time
file_path = r'C:\Users\EDY\Desktop\git\运维自动化脚本\运维集控\项目测试\运维标准版\登录用户数据.xlsx'
df = pd.read_excel(file_path)
#driver = webdriver.Chrome()
edge_options = Options()
edge_options.add_argument('--ignore-certificate-errors')
edge_options.add_argument('--disable-blink-features=AutomationControlled')
driver = webdriver.Edge(options=edge_options)
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
def login(account, password, captcha_solution):
try:
# 定位并填写用户名
username_input = WebDriverWait(driver, 3).until(
EC.presence_of_element_located((By.XPATH, "//input[@placeholder='请输入登录账号']"))
)
username_input.clear()
username_input.send_keys(account)
# 定位并填写密码
password_input = WebDriverWait(driver, 3).until(
EC.presence_of_element_located((By.XPATH, "//input[@placeholder='请输入登录密码']"))
)
password_input.clear()
password_input.send_keys(password)
# 定位并填写验证码
captcha_input = WebDriverWait(driver, 3).until(
EC.presence_of_element_located((By.XPATH, "//input[@placeholder='请输入验证码(区分大小写)']"))
)
captcha_input.clear()
captcha_input.send_keys(captcha_solution)
# 登录
login_button = WebDriverWait(driver, 3).until(
EC.element_to_be_clickable((By.XPATH, "//div[@class='loginButton']"))
)
login_button.click()
time.sleep(5)
try:
success_popup = WebDriverWait(driver, 5).until(
EC.presence_of_element_located((By.XPATH, "//*[contains(text(), '操作成功!')]"))
)
logging.info(f"登录成功: {account}")
return True
except:
try:
error_popup = WebDriverWait(driver, 3).until(
EC.presence_of_element_located(
(By.XPATH, "//*[contains(text(), '输入的用户或密码不一致') or contains(text(), '验证码无效,请重新输入')]"))
)
logging.error(f"登录失败: {account}")
return False
except:
logging.error(f"登录失败: {account}")
return False
except Exception as e:
logging.error(f"发生错误: {e}")
return False
# 打开登录页面
driver.get("https://192.168.1.118:8443/#/login")
for index, row in df.iterrows():
account = row['account']
password = row['password']
captcha_solution = row['certcode']
login_result = login(account, password, captcha_solution)
driver.refresh()
# 关闭浏览器
driver.quit()
\ No newline at end of file
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论