提交 e5cb4bc2 authored 作者: 陈泽健's avatar 陈泽健

上传预定系统登录模块代码

上级 27893344
# 默认忽略的文件
/shelf/
/workspace.xml
# 基于编辑器的 HTTP 客户端请求
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml
预定系统标准版
\ 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.10 (pythonProject1)" />
</component>
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.10 (pythonProject1)" 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
......@@ -4,7 +4,7 @@
<option name="autoReloadType" value="SELECTIVE" />
</component>
<component name="ChangeListManager">
<list default="true" id="06a1baf7-1c6d-45e8-b480-862f7355d667" name="更改" comment="" />
<list default="true" id="63769e74-10f9-467e-9dd8-5f198f917cec" name="更改" comment="" />
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
......@@ -13,75 +13,136 @@
<component name="FileTemplateManagerImpl">
<option name="RECENT_TEMPLATES">
<list>
<option value="Python Unit Test" />
<option value="Python Script" />
</list>
</option>
</component>
<component name="ProjectColorInfo">{
&quot;associatedIndex&quot;: 8
&quot;associatedIndex&quot;: 7
}</component>
<component name="ProjectId" id="2mlzK6w4y2eioNx1HV3sIDOBuAa" />
<component name="ProjectId" id="2mPF5l1gB6OIns7dktvs9fKz8QA" />
<component name="ProjectViewState">
<option name="hideEmptyMiddlePackages" value="true" />
<option name="showLibraryContents" value="true" />
</component>
<component name="PropertiesComponent">{
&quot;keyToString&quot;: {
&quot;Python 测试.Login_By_ActPwd_PyTest.test_login_from_csv 的 Python 测试.executor&quot;: &quot;Run&quot;,
&quot;Python 测试.Python 测试 (Login_By_ActPwd_PyTest.py 内).executor&quot;: &quot;Run&quot;,
&quot;RunOnceActivity.ShowReadmeOnStart&quot;: &quot;true&quot;,
&quot;last_opened_file_path&quot;: &quot;D:/PycharmData/Meeting2.0/登录模块/Base&quot;,
&quot;node.js.detected.package.eslint&quot;: &quot;true&quot;,
&quot;node.js.detected.package.tslint&quot;: &quot;true&quot;,
&quot;node.js.selected.package.eslint&quot;: &quot;(autodetect)&quot;,
&quot;node.js.selected.package.tslint&quot;: &quot;(autodetect)&quot;,
&quot;nodejs_package_manager_path&quot;: &quot;npm&quot;,
&quot;vue.rearranger.settings.migration&quot;: &quot;true&quot;
<component name="PropertiesComponent"><![CDATA[{
"keyToString": {
"Python 测试.Login_Test.MyTestCase 的 Python 测试.executor": "Run",
"Python 测试.Login_Test.MyTestCase.test 的 Python 测试.executor": "Run",
"Python 测试.Login_Test.MyTestCase.test_login_errorLimit 的 Python 测试.executor": "Run",
"Python 测试.Login_Test.MyTestCase.test_login_from_csv 的 Python 测试.executor": "Run",
"Python 测试.Login_Test.MyTestCase.test_login_success 的 Python 测试.executor": "Run",
"Python 测试.Python 测试 (LoginBy_ActAndPwd_PyTest.py 内).executor": "Run",
"Python 测试.Python 测试 (Login_PyTest.py 内).executor": "Run",
"Python 测试.Python 测试 (Login_Pytest2.py 内).executor": "Run",
"Python 测试.Python 测试 (Login_Test.py 内).executor": "Run",
"Python.Login_CZJ.executor": "Run",
"Python.Login_Test_CZJ (1).executor": "Run",
"RunOnceActivity.ShowReadmeOnStart": "true",
"last_opened_file_path": "D:/PycharmData/预定系统标准版",
"node.js.detected.package.eslint": "true",
"node.js.detected.package.tslint": "true",
"node.js.selected.package.eslint": "(autodetect)",
"node.js.selected.package.tslint": "(autodetect)",
"nodejs_package_manager_path": "npm",
"settings.editor.selected.configurable": "preferences.pluginManager",
"vue.rearranger.settings.migration": "true"
}
}</component>
}]]></component>
<component name="RecentsManager">
<key name="CopyFile.RECENT_KEYS">
<recent name="D:\PycharmData\Meeting2.0\登录模块\Base" />
<recent name="D:\PycharmData\Meeting2.0\登录模块\Page" />
<key name="MoveFile.RECENT_KEYS">
<recent name="D:\PycharmData\pythonProject1\预定标准\登录模块" />
</key>
</component>
<component name="RunManager" selected="Python 测试.Python 测试 (Login_By_ActPwd_PyTest.py 内)">
<configuration name="Login_By_ActPwd_PyTest.test_login_from_csv 的 Python 测试" type="tests" factoryName="Autodetect" temporary="true" nameIsGenerated="true">
<module name="Meeting2.0" />
<component name="RunManager" selected="Python 测试.Python 测试 (LoginBy_ActAndPwd_PyTest.py 内)">
<configuration name="Python 测试 (D:/PycharmData/预定系统标准版/登录模块/page/Login_PyTest.py 内)" type="tests" factoryName="Autodetect" temporary="true" nameIsGenerated="true">
<module name="预定系统标准版" />
<option name="ENV_FILES" value="" />
<option name="INTERPRETER_OPTIONS" value="" />
<option name="PARENT_ENVS" value="true" />
<option name="SDK_HOME" value="" />
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$/登录模块/Page" />
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$/登录模块/page" />
<option name="IS_MODULE_SDK" value="true" />
<option name="ADD_CONTENT_ROOTS" value="true" />
<option name="ADD_SOURCE_ROOTS" value="true" />
<EXTENSION ID="PythonCoverageRunConfigurationExtension" runner="coverage.py" />
<option name="_new_additionalArguments" value="&quot;&quot;" />
<option name="_new_target" value="&quot;Login_By_ActPwd_PyTest.test_login_from_csv&quot;" />
<option name="_new_targetType" value="&quot;PYTHON&quot;" />
<option name="_new_target" value="&quot;$PROJECT_DIR$/登录模块/page/Login_PyTest.py&quot;" />
<option name="_new_targetType" value="&quot;PATH&quot;" />
<method v="2" />
</configuration>
<configuration name="Python 测试 (D:/PycharmData/预定系统标准版/登录模块/page/Login_Pytest2.py 内)" type="tests" factoryName="Autodetect" temporary="true" nameIsGenerated="true">
<module name="预定系统标准版" />
<option name="ENV_FILES" value="" />
<option name="INTERPRETER_OPTIONS" value="" />
<option name="PARENT_ENVS" value="true" />
<option name="SDK_HOME" value="" />
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$/登录模块/page" />
<option name="IS_MODULE_SDK" value="true" />
<option name="ADD_CONTENT_ROOTS" value="true" />
<option name="ADD_SOURCE_ROOTS" value="true" />
<EXTENSION ID="PythonCoverageRunConfigurationExtension" runner="coverage.py" />
<option name="_new_additionalArguments" value="&quot;&quot;" />
<option name="_new_target" value="&quot;$PROJECT_DIR$/登录模块/page/Login_Pytest2.py&quot;" />
<option name="_new_targetType" value="&quot;PATH&quot;" />
<method v="2" />
</configuration>
<configuration name="Python 测试 (Login_By_ActPwd_PyTest.py 内)" type="tests" factoryName="Autodetect" temporary="true" nameIsGenerated="true">
<module name="Meeting2.0" />
<configuration name="Python 测试 (LoginBy_ActAndPwd_PyTest.py 内)" type="tests" factoryName="Autodetect" temporary="true" nameIsGenerated="true">
<module name="预定系统标准版" />
<option name="ENV_FILES" value="" />
<option name="INTERPRETER_OPTIONS" value="" />
<option name="PARENT_ENVS" value="true" />
<option name="SDK_HOME" value="" />
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$/登录模块/Page" />
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$/登录模块/page" />
<option name="IS_MODULE_SDK" value="true" />
<option name="ADD_CONTENT_ROOTS" value="true" />
<option name="ADD_SOURCE_ROOTS" value="true" />
<EXTENSION ID="PythonCoverageRunConfigurationExtension" runner="coverage.py" />
<option name="_new_additionalArguments" value="&quot;&quot;" />
<option name="_new_target" value="&quot;$PROJECT_DIR$/登录模块/Page/Login_By_ActPwd_PyTest.py&quot;" />
<option name="_new_target" value="&quot;$PROJECT_DIR$/登录模块/page/LoginBy_ActAndPwd_PyTest.py&quot;" />
<option name="_new_targetType" value="&quot;PATH&quot;" />
<method v="2" />
</configuration>
<configuration name="Python 测试 (Login_Test_UnitTest.py 内)" type="tests" factoryName="Autodetect" temporary="true" nameIsGenerated="true">
<module name="预定系统标准版" />
<option name="ENV_FILES" value="" />
<option name="INTERPRETER_OPTIONS" value="" />
<option name="PARENT_ENVS" value="true" />
<option name="SDK_HOME" value="" />
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$/登录模块/page" />
<option name="IS_MODULE_SDK" value="true" />
<option name="ADD_CONTENT_ROOTS" value="true" />
<option name="ADD_SOURCE_ROOTS" value="true" />
<EXTENSION ID="PythonCoverageRunConfigurationExtension" runner="coverage.py" />
<option name="_new_additionalArguments" value="&quot;&quot;" />
<option name="_new_target" value="&quot;$PROJECT_DIR$/登录模块/page/Login_Test_UnitTest.py&quot;" />
<option name="_new_targetType" value="&quot;PATH&quot;" />
<method v="2" />
</configuration>
<configuration name="登录模块.page.Login_Test_UnitTest 的 Python 测试" type="tests" factoryName="Autodetect" temporary="true" nameIsGenerated="true">
<module name="预定系统标准版" />
<option name="ENV_FILES" value="" />
<option name="INTERPRETER_OPTIONS" value="" />
<option name="PARENT_ENVS" value="true" />
<option name="SDK_HOME" value="" />
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$/登录模块/page" />
<option name="IS_MODULE_SDK" value="true" />
<option name="ADD_CONTENT_ROOTS" value="true" />
<option name="ADD_SOURCE_ROOTS" value="true" />
<EXTENSION ID="PythonCoverageRunConfigurationExtension" runner="coverage.py" />
<option name="_new_additionalArguments" value="&quot;&quot;" />
<option name="_new_target" value="&quot;登录模块.page.Login_Test_UnitTest&quot;" />
<option name="_new_targetType" value="&quot;PYTHON&quot;" />
<method v="2" />
</configuration>
<recent_temporary>
<list>
<item itemvalue="Python 测试.Python 测试 (Login_By_ActPwd_PyTest.py 内)" />
<item itemvalue="Python 测试.Login_By_ActPwd_PyTest.test_login_from_csv 的 Python 测试" />
<item itemvalue="Python 测试.Python 测试 (LoginBy_ActAndPwd_PyTest.py 内)" />
<item itemvalue="Python 测试.Python 测试 (D:/PycharmData/预定系统标准版/登录模块/page/Login_PyTest.py 内)" />
<item itemvalue="Python 测试.Python 测试 (D:/PycharmData/预定系统标准版/登录模块/page/Login_Pytest2.py 内)" />
<item itemvalue="Python 测试.Python 测试 (Login_Test_UnitTest.py 内)" />
<item itemvalue="Python 测试.登录模块.page.Login_Test_UnitTest 的 Python 测试" />
</list>
</recent_temporary>
</component>
......@@ -96,14 +157,23 @@
<component name="SpellCheckerSettings" RuntimeDictionaries="0" Folders="0" CustomDictionaries="0" DefaultDictionary="应用程序级" UseSingleDictionary="true" transferred="true" />
<component name="TaskManager">
<task active="true" id="Default" summary="默认任务">
<changelist id="06a1baf7-1c6d-45e8-b480-862f7355d667" name="更改" comment="" />
<created>1727665883468</created>
<changelist id="63769e74-10f9-467e-9dd8-5f198f917cec" name="更改" comment="" />
<created>1726970122280</created>
<option name="number" value="Default" />
<option name="presentableId" value="Default" />
<updated>1727665883468</updated>
<workItem from="1727665886774" duration="11715000" />
<workItem from="1728370368628" duration="1408000" />
<workItem from="1728371792771" duration="1037000" />
<updated>1726970122280</updated>
<workItem from="1726970123695" duration="31693000" />
<workItem from="1727095378299" duration="9072000" />
<workItem from="1727143346632" duration="15217000" />
<workItem from="1727163581288" duration="9108000" />
<workItem from="1727182815172" duration="5276000" />
<workItem from="1727188242736" duration="2168000" />
<workItem from="1727225088964" duration="10301000" />
<workItem from="1727258378123" duration="5624000" />
<workItem from="1727274398017" duration="3245000" />
<workItem from="1727493678249" duration="636000" />
<workItem from="1727663202507" duration="896000" />
<workItem from="1728388575086" duration="863000" />
</task>
<servers />
</component>
......@@ -111,6 +181,9 @@
<option name="version" value="3" />
</component>
<component name="com.intellij.coverage.CoverageDataManagerImpl">
<SUITE FILE_PATH="coverage/Meeting2_0$.coverage" NAME=" 覆盖结果" MODIFIED="1728372005510" SOURCE_PROVIDER="com.intellij.coverage.DefaultCoverageFileProvider" RUNNER="coverage.py" COVERAGE_BY_TEST_ENABLED="false" COVERAGE_TRACING_ENABLED="false" WORKING_DIRECTORY="$PROJECT_DIR$/登录模块/Page" />
<SUITE FILE_PATH="coverage/pythonProject1$Login_Test_CZJ__1_.coverage" NAME="Login_Test_CZJ (1) 覆盖结果" MODIFIED="1726983885714" SOURCE_PROVIDER="com.intellij.coverage.DefaultCoverageFileProvider" RUNNER="coverage.py" COVERAGE_BY_TEST_ENABLED="false" COVERAGE_TRACING_ENABLED="false" WORKING_DIRECTORY="$PROJECT_DIR$/预定标准/登录模块" />
<SUITE FILE_PATH="coverage/pythonProject1$.coverage" NAME=" 覆盖结果" MODIFIED="1727161759018" SOURCE_PROVIDER="com.intellij.coverage.DefaultCoverageFileProvider" RUNNER="coverage.py" COVERAGE_BY_TEST_ENABLED="false" COVERAGE_TRACING_ENABLED="false" WORKING_DIRECTORY="$PROJECT_DIR$/登录模块/page" />
<SUITE FILE_PATH="coverage/$.coverage" NAME=" 覆盖结果" MODIFIED="1728389350052" SOURCE_PROVIDER="com.intellij.coverage.DefaultCoverageFileProvider" RUNNER="coverage.py" COVERAGE_BY_TEST_ENABLED="false" COVERAGE_TRACING_ENABLED="false" WORKING_DIRECTORY="$PROJECT_DIR$/登录模块/page" />
<SUITE FILE_PATH="coverage/pythonProject1$Login_CZJ.coverage" NAME="Login_CZJ 覆盖结果" MODIFIED="1726982554636" SOURCE_PROVIDER="com.intellij.coverage.DefaultCoverageFileProvider" RUNNER="coverage.py" COVERAGE_BY_TEST_ENABLED="false" COVERAGE_TRACING_ENABLED="false" WORKING_DIRECTORY="$PROJECT_DIR$/预定标准/登录模块" />
</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$">
<excludeFolder url="file://$MODULE_DIR$/.venv" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
\ No newline at end of file
import pytest
import logging
import os
import csv
from selenium.common import StaleElementReferenceException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from 登录模块.base.Broswer_driver import Browser_driver
# 初始化日志记录器
logging.basicConfig(level=logging.ERROR, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
def read_csv_data(file_path=None):
"""
读取 CSV 文件数据
"""
# 初始化数据列表,用于存储 CSV 文件中的数据
data = []
# 使用环境变量或参数指定文件路径
if file_path is None:
file_path = os.getenv('CSV_FILE_PATH', 'Login_Test.csv')
try:
# 打开 CSV 文件,使用 utf-8 编码读取
with open(file_path, mode='r', encoding='utf-8') as csvfile:
# 使用 csv.DictReader 读取 CSV 文件,自动将每行数据转换为字典
csv_reader = csv.DictReader(csvfile)
# 遍历每行数据,提取用户名、密码和验证码,将其作为元组添加到数据列表中
for row in csv_reader:
data.append((row['username'], row['password'], row['verification_code']))
except FileNotFoundError:
# 如果 CSV 文件未找到,记录错误日志并退出测试
logger.error("CSV 文件未找到,请检查文件路径")
pytest.exit("CSV 文件未找到,请检查文件路径")
except csv.Error as e:
# 如果 CSV 格式错误,记录错误日志并退出测试
logger.error(f"CSV 格式错误: {e}")
pytest.exit(f"CSV 格式错误: {e}")
except Exception as e:
# 如果有其他异常发生,记录错误日志并退出测试
logger.error(f"出现错误: {e}")
pytest.exit(f"出现错误: {e}")
# 返回读取的数据列表
return data
@pytest.fixture(scope='session')
def driver():
"""
初始化浏览器并打开指定URL
"""
url = 'https://nat.ubainsyun.com:11046' # 通过配置文件获取URL
# url = 'https://192.168.5.218'
logging.info("'----------' 正在初始化浏览器 '----------'")
try:
driver = Browser_driver().browser_init() # 初始化浏览器驱动
logging.info("'----------' 浏览器初始化成功 '----------'")
except Exception as e:
logging.error(f"浏览器初始化失败: {e}")
raise
driver.implicitly_wait(10) # 设置隐式等待时间为10秒
driver.maximize_window() # 最大化浏览器窗口
logging.info("'----------' 正在打开URL '----------'")
try:
driver.get(url)
logging.info(f"成功打开URL: {url}")
except Exception as e:
logging.error(f"打开URL失败: {e}")
raise
handle_ssl_warning(driver) # 处理可能存在的SSL证书警告
yield driver
driver.quit() # 在测试结束后关闭浏览器
def handle_ssl_warning(driver):
"""
处理 SSL 证书警告
此函数用于在网页浏览器中处理 SSL 证书错误。它通过点击特定的按钮来忽略 SSL 警告,以便在自动化测试中继续进行。
参数:
- driver: WebDriver实例,用于控制网页浏览器的行为
异常:
- 如果在处理 SSL 警告过程中发生任何错误,会记录错误信息并抛出异常
"""
try:
# 记录处理 SSL 证书警告的开始信息
logging.info("'----------' 正在处理SSL证书警告 '----------'")
# 等待并点击“详细信息”按钮
WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, '//*[@id="details-button"]'))
).click()
# 等待并点击“继续”链接,以忽略 SSL 警告
WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, '//*[@id="proceed-link"]'))
).click()
# 等待页面加载完成
WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.TAG_NAME, 'body'))
)
# 记录处理 SSL 证书警告完成的信息
logging.info("'----------' SSL证书警告处理完成 '----------'")
except Exception as e:
# 记录处理 SSL 证书警告过程中遇到的错误,并抛出异常
logging.error(f"处理 SSL 证书警告遇到错误: {e}")
raise
def _find_element(driver, by, value):
"""
查找元素,并处理可能的异常
该函数尝试在给定的驱动程序(driver)中查找一个元素,该元素由定位方式(by)和定位值(value)共同确定。
如果在查找过程中出现StaleElementReferenceException异常,即元素可能不再附属于当前页面,
则函数会再次尝试查找该元素,以确保元素被正确找到并返回。
参数:
- driver: WebDriver实例,用于操作浏览器。
- by: 字符串,指定查找元素的定位方式(如ID, XPATH等)。
- value: 字符串,定位方式对应的值。
返回:
- 找到的元素对象。
"""
try:
# 使用WebDriverWait等待最多20秒,直到元素被定位到。
# 这里使用presence_of_element_located预期条件,以等待元素出现在DOM中。
return WebDriverWait(driver, 20).until(
EC.presence_of_element_located((by, value))
)
except StaleElementReferenceException:
# 如果抛出StaleElementReferenceException异常,说明页面可能已经变化,
# 导致原先的元素引用失效。这时再次尝试查找元素。
return WebDriverWait(driver, 20).until(
EC.presence_of_element_located((by, value))
)
def perform_login(driver, username, password, verification_code):
"""
执行登录操作
参数:
- driver: 浏览器驱动
- username: 用户名
- password: 密码
- verification_code: 验证码
该函数通过浏览器驱动模拟用户登录过程,依次输入用户名、密码和验证码,然后点击登录按钮。
登录后,根据返回的页面判断登录是否成功,并记录相应的日志信息。
"""
# 隐式等待确保元素能被找到
driver.implicitly_wait(5)
# 刷新页面以确保登录页面最新
driver.refresh()
try:
# 清除并输入用户名
username_input = _find_element(driver, By.XPATH,
'//*[@id="app"]/div/div[3]/div[1]/div[2]/div/form/div[1]/div/input')
username_input.clear()
username_input.send_keys(username)
# 清除并输入密码
password_input = _find_element(driver, By.XPATH,
'//*[@id="app"]/div/div[3]/div[1]/div[2]/div/form/div[2]/div/input')
password_input.clear()
password_input.send_keys(password)
# 清除并输入验证码
verification_input = _find_element(driver, By.XPATH,
'//*[@id="app"]/div/div[3]/div[1]/div[2]/div/form/div[3]/div[1]/div/input')
verification_input.clear()
verification_input.send_keys(verification_code)
# 点击登录按钮
login_button = _find_element(driver, By.XPATH, '//*[@id="app"]/div/div[3]/div[1]/div[2]/div/form/div[4]/input')
login_button.click()
# 检查登录是否成功
if check_login_null(driver):
# 登录失败,必填项不能为空
logger.info("登录失败,必填项不能为空!断言成功!")
elif check_login_success(driver):
# 登录成功
logger.info("登录成功,断言成功!")
return_to_login_page(driver) # 返回登录页面
elif check_login_failure(driver):
# 登录失败,必填项错误
logger.info("登录失败, 必填项错误!断言成功!")
else:
# 登录状态未知
logger.error("登录状态未知,断言失败!")
pytest.fail("登录状态未知,断言失败!")
except StaleElementReferenceException as e:
# 元素已失效,重新查找
logger.error(f"元素已失效,重新查找... {e}")
pytest.fail(f"元素已失效,重新查找... {e}")
except Exception as e:
# 登录操作失败
logger.error(f"登录操作失败: {e}")
pytest.fail(f"登录操作失败: {e}")
def return_to_login_page(driver):
"""
返回登录页面
通过点击退出按钮操作,实现从当前页面返回登录页面的功能。
参数:
- driver: WebDriver实例,用于操作浏览器。
返回值:
"""
try:
# 定位到退出按钮并点击
logout_button = _find_element(driver, By.XPATH, '//*[@id="app"]/div/div[1]/div/img[3]')
logout_button.click()
# 记录日志,表明已成功尝试返回登录页面
logging.info("已成功返回登录页面")
# 刷新页面,并等待一段时间以确保页面加载完成
driver.refresh()
driver.implicitly_wait(5)
except Exception as e:
# 如果发生异常,记录错误日志并使测试用例失败
logger.error(f"返回登录页面失败: {e}")
pytest.fail(f"返回登录页面失败: {e}")
def check_login_null(driver):
"""
检查登录失败,必填项为空的情况
"""
try:
# 使用WebDriverWait等待器,等待最多10秒,直到登录失败的提示元素可见
login_element_text = WebDriverWait(driver, 10).until(
EC.visibility_of_element_located((By.XPATH, '/html/body/div[2]/p'))
).text
# 断言登录失败后,提示信息中包含'请输入'关键词
assert "请输入" in login_element_text, "登录失败后未找到'请输入'提示语"
return True
except Exception as e:
# 异常情况下,记录错误日志,并返回False表示检查未通过
logger.error(f"登录失败检查失败: {e}")
return False
def check_login_success(driver):
"""
检查登录成功的情况
"""
try:
# 等待并获取登录成功后的欢迎信息
message_element_text = WebDriverWait(driver, 10).until(
EC.visibility_of_element_located((By.XPATH, "//*[contains(text(), '欢迎')]"))
).text
# 断言欢迎信息是否符合预期
assert "欢迎 预定标准版测试" == message_element_text, "登录成功后找到'欢迎 预定标准版测试'提示语"
# 如果一切正常,返回True
return True
except Exception as e:
# 如果检查过程中发生异常,记录错误信息,并返回False
logger.error(f"登录成功检查失败: {e}")
return False
def check_login_failure(driver):
"""
检查登录失败的情况
"""
try:
# 使用WebDriverWait等待,直到定位到特定XPath的元素可见,获取该元素的文本
login_element_text = WebDriverWait(driver, 10).until(
EC.visibility_of_element_located((By.XPATH, '//*[@id="app"]/div/div[3]/div[1]/div[1]/div[1]'))
).text
# 断言登录元素的文本是否为"账号登录",如果符合,则说明登录失败检查成功
assert "账号登录" == login_element_text, "登录失败后未找到'账号登录'提示语"
return True
except Exception as e:
# 如果发生异常,记录错误信息并返回False,表示登录失败检查失败
logger.error(f"登录失败检查失败: {e}")
return False
@pytest.mark.parametrize("username,password,verification_code", read_csv_data())
def test_login_from_csv(driver, username, password, verification_code):
"""
从 CSV 文件读取并测试登录情况
"""
# 初始化日志记录,标记测试开始
logger.info(f"'----------' 开始执行测试 '----------'")
# 执行登录操作,传递驱动、用户名、密码和验证码
perform_login(driver, username, password, verification_code)
# 登录操作完成后,记录日志,标记测试结束
logger.info(f"'----------' 执行完成测试 '----------'")
# 隐式等待,确保后续操作前页面加载完成
driver.implicitly_wait(10)
if __name__ == '__main__':
pytest.main()
# import pytest
# import logging
# import os
# import csv
# 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.common import StaleElementReferenceException
# from selenium.webdriver import Chrome
#
# from 登录模块.base.Base import Base
# from 登录模块.base.Broswer_driver import Browser_driver
#
# # 初始化日志记录器
# logging.basicConfig(level=logging.ERROR, format='%(asctime)s - %(levelname)s - %(message)s')
# logger = logging.getLogger(__name__)
#
# def read_csv_data(file_path=None):
# """
# 读取 CSV 文件数据
# """
# data = []
# if file_path is None:
# file_path = os.getenv('CSV_FILE_PATH', 'Login_Test.csv')
#
# try:
# with open(file_path, mode='r', encoding='utf-8') as csvfile:
# csv_reader = csv.DictReader(csvfile)
# for row in csv_reader:
# data.append((row['username'], row['password'], row['verification_code']))
# except FileNotFoundError:
# logger.error("CSV 文件未找到,请检查文件路径")
# pytest.exit("CSV 文件未找到,请检查文件路径")
# except csv.Error as e:
# logger.error(f"CSV 格式错误: {e}")
# pytest.exit(f"CSV 格式错误: {e}")
# except Exception as e:
# logger.error(f"出现错误: {e}")
# pytest.exit(f"出现错误: {e}")
#
# return data
#
# @pytest.fixture(scope='session')
# def driver():
# """
# 初始化浏览器并打开指定URL
# """
# url = 'https://nat.ubainsyun.com:11046'
# logging.info("'----------' 正在初始化浏览器 '----------'")
# try:
# driver = Browser_driver().browser_init()
# logging.info("'----------' 浏览器初始化成功 '----------'")
# except Exception as e:
# logging.error(f"浏览器初始化失败: {e}")
# raise
#
# driver.implicitly_wait(10)
# driver.maximize_window()
# logging.info("'----------' 正在打开URL '----------'")
#
# try:
# driver.get(url)
# logging.info(f"成功打开URL: {url}")
# except Exception as e:
# logging.error(f"打开URL失败: {e}")
# raise
#
# yield driver
# driver.quit()
#
# def test_login_from_csv(driver):
# """
# 从 CSV 文件读取并测试登录情况
# """
# logger.info(f"'----------' 开始执行测试 '----------'")
# base = Base(driver)
#
# for username, password, verification_code in read_csv_data():
# base.perform_login(username, password, verification_code)
#
# logger.info(f"'----------' 执行完成测试 '----------'")
# driver.implicitly_wait(10)
#
# if __name__ == '__main__':
# pytest.main()
import pytest
import logging
import os
import csv
import configparser
from selenium.common import StaleElementReferenceException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from 登录模块.base.Broswer_driver import Browser_driver
# 初始化日志记录器
logging.basicConfig(level=logging.ERROR, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
def read_csv_data(file_path=None):
"""
读取 CSV 文件数据
"""
data = []
if file_path is None:
file_path = os.getenv('CSV_FILE_PATH', 'Login_Test.csv')
try:
with open(file_path, mode='r', encoding='utf-8') as csvfile:
csv_reader = csv.DictReader(csvfile)
for row in csv_reader:
data.append((row['username'], row['password'], row['verification_code']))
except FileNotFoundError:
logger.error("CSV 文件未找到,请检查文件路径")
pytest.exit("CSV 文件未找到,请检查文件路径")
except csv.Error as e:
logger.error(f"CSV 格式错误: {e}")
pytest.exit(f"CSV 格式错误: {e}")
except Exception as e:
logger.error(f"出现错误: {e}")
pytest.exit(f"出现错误: {e}")
return data
@pytest.fixture(scope='session')
def driver():
"""
初始化浏览器并打开指定URL
"""
url = 'https://nat.ubainsyun.com:11046'
logging.info("'----------' 正在初始化浏览器 '----------'")
try:
driver = Browser_driver().browser_init()
logging.info("'----------' 浏览器初始化成功 '----------'")
except Exception as e:
logging.error(f"浏览器初始化失败: {e}")
raise
driver.implicitly_wait(10)
driver.maximize_window()
logging.info("'----------' 正在打开URL '----------'")
try:
driver.get(url)
logging.info(f"成功打开URL: {url}")
except Exception as e:
logging.error(f"打开URL失败: {e}")
raise
handle_ssl_warning(driver)
yield driver
driver.quit()
def handle_ssl_warning(driver):
"""
处理 SSL 证书警告
"""
try:
logging.info("'----------' 正在处理SSL证书警告 '----------'")
WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, '//*[@id="details-button"]'))
).click()
WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, '//*[@id="proceed-link"]'))
).click()
WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.TAG_NAME, 'body'))
)
logging.info("'----------' SSL证书警告处理完成 '----------'")
except Exception as e:
logging.error(f"处理 SSL 证书警告遇到错误: {e}")
raise
def _find_element(driver, by, value):
"""
查找元素,并处理可能的异常
"""
try:
return WebDriverWait(driver, 20).until(
EC.presence_of_element_located((by, value))
)
except StaleElementReferenceException:
return WebDriverWait(driver, 20).until(
EC.presence_of_element_located((by, value))
)
def send_sms_verification_code(driver, phone_number):
"""
模拟发送短信验证码
"""
# 假设有一个发送短信验证码的API接口
# 这里只是一个示例,实际应用中需要调用真实的API
logging.info(f"模拟发送短信验证码至 {phone_number}")
def perform_login(driver, username, password, verification_code):
"""
执行登录操作
"""
driver.implicitly_wait(5)
driver.refresh()
try:
username_input = _find_element(driver, By.XPATH, '//*[@id="app"]/div/div[3]/div[1]/div[2]/div/form/div[1]/div/input')
username_input.clear()
username_input.send_keys(username)
password_input = _find_element(driver, By.XPATH, '//*[@id="app"]/div/div[3]/div[1]/div[2]/div/form/div[2]/div/input')
password_input.clear()
password_input.send_keys(password)
# 假设验证码已经发送并接收
send_sms_verification_code(driver, username) # 发送验证码
verification_input = _find_element(driver, By.XPATH, '//*[@id="app"]/div/div[3]/div[1]/div[2]/div/form/div[3]/div[1]/div/input')
verification_input.clear()
verification_input.send_keys(verification_code)
login_button = _find_element(driver, By.XPATH, '//*[@id="app"]/div/div[3]/div[1]/div[2]/div/form/div[4]/input')
login_button.click()
if check_login_null(driver):
logger.info("登录失败,必填项不能为空!断言成功!")
elif check_login_success(driver):
logger.info("登录成功,断言成功!")
return_to_login_page(driver)
elif check_login_failure(driver):
logger.info("登录失败, 必填项错误!断言成功!")
else:
logger.error("登录状态未知,断言失败!")
pytest.fail("登录状态未知,断言失败!")
except StaleElementReferenceException as e:
logger.error(f"元素已失效,重新查找... {e}")
pytest.fail(f"元素已失效,重新查找... {e}")
except Exception as e:
logger.error(f"登录操作失败: {e}")
pytest.fail(f"登录操作失败: {e}")
def return_to_login_page(driver):
"""
返回登录页面
"""
try:
logout_button = _find_element(driver, By.XPATH, '//*[@id="app"]/div/div[1]/div/img[3]')
logout_button.click()
logging.info("已成功返回登录页面")
driver.refresh()
driver.implicitly_wait(5)
except Exception as e:
logger.error(f"返回登录页面失败: {e}")
pytest.fail(f"返回登录页面失败: {e}")
def check_login_null(driver):
"""
检查登录失败,必填项为空的情况
"""
try:
login_element_text = WebDriverWait(driver, 10).until(
EC.visibility_of_element_located((By.XPATH, '/html/body/div[2]/p'))
).text
assert "请输入" in login_element_text, "登录失败后未找到'请输入'提示语"
return True
except Exception as e:
logger.error(f"登录失败检查失败: {e}")
return False
def check_login_success(driver):
"""
检查登录成功的情况
"""
try:
message_element_text = WebDriverWait(driver, 10).until(
EC.visibility_of_element_located((By.XPATH, "//*[contains(text(), '欢迎')]"))
).text
assert "欢迎 预定标准版测试" == message_element_text, "登录成功后找到'欢迎 预定标准版测试'提示语"
return True
except Exception as e:
logger.error(f"登录成功检查失败: {e}")
return False
def check_login_failure(driver):
"""
检查登录失败的情况
"""
try:
login_element_text = WebDriverWait(driver, 10).until(
EC.visibility_of_element_located((By.XPATH, '//*[@id="app"]/div/div[3]/div[1]/div[1]/div[1]'))
).text
assert "账号登录" == login_element_text, "登录失败后未找到'账号登录'提示语"
return True
except Exception as e:
logger.error(f"登录失败检查失败: {e}")
return False
@pytest.mark.parametrize("username,password,verification_code", read_csv_data())
def test_login_from_csv(driver, username, password, verification_code):
"""
从 CSV 文件读取并测试登录情况
"""
logger.info(f"'----------' 开始执行测试 '----------'")
perform_login(driver, username, password, verification_code)
logger.info(f"'----------' 执行完成测试 '----------'")
driver.implicitly_wait(10)
if __name__ == '__main__':
pytest.main()
username,password,verification_code
admin@czj,Ubains@4321,
,Ubains@4321,csba
admin@czj,Ubains@4321,
,Ubains@4321,csba
admin@czj,Ubains@4321,
,Ubains@4321,csba
admin@czj2,Ubains@4321,csba
admin@czj,Ubains@4321,csba
admin@,Ubains@4321,csba
admin@czj,Ubains@4321,
,Ubains@4321,csba
admin@czj,Ubains@4321,
,Ubains@4321,csba
admin@czj,Ubains@4321,
,Ubains@4321,csba
admin@czj2,Ubains@4321,csba
admin@czj,Ubains@4321,csba
admin@,Ubains@4321,csba
admin@czj,Ubains@4321,
,Ubains@4321,csba
admin@czj,Ubains@4321,
admin@czj,Ubains@4321,
,Ubains@4321,csba
admin@czj,Ubains@4321,
,Ubains@4321,csba
admin@czj,Ubains@4321,
,Ubains@4321,csba
admin@czj2,Ubains@4321,csba
admin@czj,Ubains@4321,csba
admin@,Ubains@4321,csba
admin@czj,Ubains@4321,
,Ubains@4321,csba
admin@czj,Ubains@4321,
,Ubains@4321,csba
admin@czj,Ubains@4321,
,Ubains@4321,csba
admin@czj2,Ubains@4321,csba
admin@czj,Ubains@4321,csba
admin@,Ubains@4321,csba
admin@czj,Ubains@4321,
,Ubains@4321,csba
admin@czj,Ubains@4321,
,Ubains@4321,csba
admin@czj,Ubains@4321,
,Ubains@4321,csba
admin@czj2,Ubains@4321,csba
admin@czj,Ubains@4321,csba
admin@,Ubains@4321,csba
admin@czj,Ubains@4321,
,Ubains@4321,csba
admin@czj,Ubains@4321,
,Ubains@4321,csba
admin@czj,Ubains@4321,
,Ubains@4321,csba
admin@czj2,Ubains@4321,csba
admin@czj,Ubains@4321,csba
admin@,Ubains@4321,csba
admin@czj,Ubains@4321,
,Ubains@4321,csba
admin@czj,Ubains@4321,
,Ubains@4321,csba
admin@czj,Ubains@4321,
,Ubains@4321,csba
admin@czj2,Ubains@4321,csba
admin@czj,Ubains@4321,csba
admin@,Ubains@4321,csba
admin@czj,Ubains@4321,
,Ubains@4321,csba
admin@czj,Ubains@4321,
,Ubains@4321,csba
admin@czj,Ubains@4321,
,Ubains@4321,csba
admin@czj2,Ubains@4321,csba
admin@czj,Ubains@4321,csba
\ No newline at end of file
import pytest
import logging
from selenium import webdriver
from selenium.common import StaleElementReferenceException
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import csv
from 登录模块.base.Broswer_driver import Browser_driver
def read_csv_data():
"""
读取 CSV 文件数据
"""
data = []
try:
with open('Login_Test.csv', mode='r', encoding='utf-8') as csvfile:
csv_reader = csv.DictReader(csvfile)
for row in csv_reader:
data.append((row['username'], row['password'], row['verification_code']))
except FileNotFoundError:
logger.error("CSV 文件未找到,请检查文件路径")
pytest.exit("CSV 文件未找到,请检查文件路径")
except Exception as e:
logger.error(f"出现错误: {e}")
pytest.exit(f"出现错误: {e}")
return data
# 设置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
@pytest.fixture(scope='session')
def driver():
"""
初始化浏览器并打开指定URL
"""
url = 'https://192.168.5.218'
logging.info("'----------' 正在初始化浏览器 '----------'")
try:
driver = Browser_driver().browser_init() # 初始化浏览器驱动
logging.info("'----------' 浏览器初始化成功 '----------'")
except Exception as e:
logging.error(f"浏览器初始化失败: {e}")
raise
driver.implicitly_wait(10) # 设置隐式等待时间为10秒
driver.maximize_window() # 最大化浏览器窗口
logging.info("'----------' 正在打开URL '----------'")
try:
driver.get(url)
logging.info(f"成功打开URL: {url}")
except Exception as e:
logging.error(f"打开URL失败: {e}")
raise
handle_ssl_warning(driver) # 处理可能存在的SSL证书警告
yield driver
driver.quit() # 在测试结束后关闭浏览器
def handle_ssl_warning(driver):
"""处理 SSL 证书警告"""
try:
logging.info("'----------' 正在处理SSL证书警告 '----------'")
WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, '//*[@id="details-button"]'))
).click()
WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, '//*[@id="proceed-link"]'))
).click()
# 等待页面加载完成
WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.TAG_NAME, 'body'))
)
logging.info("'----------' SSL证书警告处理完成 '----------'")
except Exception as e:
logging.error(f"处理 SSL 证书警告遇到错误: {e}")
raise
def _find_element(driver, by, value):
"""
查找元素,并处理可能的异常
"""
try:
return WebDriverWait(driver, 20).until(
EC.presence_of_element_located((by, value))
)
except StaleElementReferenceException:
return WebDriverWait(driver, 20).until(
EC.presence_of_element_located((by, value))
)
def perform_login(driver, username, password, verification_code):
"""
执行登录操作
"""
try:
# 清除并输入用户名
username_input = _find_element(driver, By.XPATH,
'//*[@id="app"]/div/div[3]/div[1]/div[2]/div/form/div[1]/div/input')
username_input.clear()
username_input.send_keys(username)
# 清除并输入密码
password_input = _find_element(driver, By.XPATH,
'//*[@id="app"]/div/div[3]/div[1]/div[2]/div/form/div[2]/div/input')
password_input.clear()
password_input.send_keys(password)
# 清除并输入验证码
verification_input = _find_element(driver, By.XPATH,
'//*[@id="app"]/div/div[3]/div[1]/div[2]/div/form/div[3]/div[1]/div/input')
verification_input.clear()
verification_input.send_keys(verification_code)
# 点击登录按钮
login_button = _find_element(driver, By.XPATH, '//*[@id="app"]/div/div[3]/div[1]/div[2]/div/form/div[4]/input')
login_button.click()
if username | password | verification_code == "":
check_login_null(driver)
logger.info("登录失败,必填项不能为空!断言成功!\n")
elif check_login_failure(driver):
logger.info("登录失败, 必填项错误!断言成功!\n")
elif check_login_success(driver):
logger.info("登录成功,断言成功!\n")
return_to_login_page(driver) # 返回登录页面
# # 检查登录是否成功
# if check_login_null(driver):
# logger.info("登录失败,必填项不能为空!断言成功!\n")
#
# elif check_login_success(driver):
# logger.info("登录成功,断言成功!\n")
# return_to_login_page(driver) # 返回登录页面
# elif check_login_failure(driver):
# logger.info("登录失败, 必填项错误!断言成功!\n")
else:
logger.error("登录状态未知,断言失败!\n")
pytest.fail("登录状态未知,断言失败!")
except StaleElementReferenceException as e:
logger.error(f"元素已失效,重新查找... {e}\n")
pytest.fail(f"元素已失效,重新查找... {e}")
except Exception as e:
logger.error(f"登录操作失败: {e}\n")
pytest.fail(f"登录操作失败: {e}")
def return_to_login_page(driver):
"""
返回登录页面
"""
try:
logout_button = _find_element(driver, By.XPATH, '//*[@id="app"]/div/div[1]/div/div[1]/div[2]/div[2]')
logout_button.click()
logging.info("已成功返回登录页面\n")
except Exception as e:
logger.error(f"返回登录页面失败: {e}\n")
pytest.fail(f"返回登录页面失败: {e}")
def check_login_null(driver):
"""
检查登录失败,必填项为空的情况
"""
try:
login_element_text = WebDriverWait(driver, 10).until(
EC.visibility_of_element_located((By.XPATH, '/html/body/div[2]/p'))
).text
assert "请输入" in login_element_text, "登录失败后未找到'请输入'提示语"
return True
except Exception as e:
logger.error(f"登录失败检查失败: {e}")
return False
def check_login_success(driver):
"""
检查登录成功的情况
"""
try:
message_element_text = WebDriverWait(driver, 10).until(
EC.visibility_of_element_located((By.XPATH, "//*[contains(text(), '欢迎')]"))
).text
assert "欢迎 预定标准版测试" == message_element_text, "登录成功后找到'欢迎 预定标准版测试'提示语"
driver.find_element(By.XPATH, '//*[@id="app"]/div/div[1]/div/img[3]').click()
driver.refresh()
driver.implicitly_wait(5)
return True
except Exception as e:
logger.error(f"登录成功检查失败: {e}")
return False
def check_login_failure(driver):
"""
检查登录失败的情况
"""
try:
login_element_text = WebDriverWait(driver, 10).until(
EC.visibility_of_element_located((By.XPATH, '//*[@id="app"]/div/div[3]/div[1]/div[1]/div[1]'))
).text
assert "账号登录" == login_element_text, "登录失败后未找到'账号登录'提示语"
return True
except Exception as e:
logger.error(f"登录失败检查失败: {e}")
return False
@pytest.mark.parametrize("username,password,verification_code", read_csv_data())
def test_login_from_csv(driver, username, password, verification_code):
"""
从 CSV 文件读取并测试登录情况
"""
logger.info(f"'----------' 开始执行测试 '----------'\n")
perform_login(driver, username, password, verification_code)
logger.info(f"'----------' 执行完成测试 '----------'\n")
driver.implicitly_wait(10)
if __name__ == '__main__':
pytest.main()
import logging
import pytest
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.common import StaleElementReferenceException
class Base:
def __init__(self, driver):
self.driver = driver
self.logger = logging.getLogger(__name__)
def find_element(self, by, value):
"""
查找元素,并处理可能的异常
"""
try:
return WebDriverWait(self.driver, 30).until(
EC.presence_of_element_located((by, value))
)
except StaleElementReferenceException:
return WebDriverWait(self.driver, 30).until(
EC.presence_of_element_located((by, value))
)
def perform_login(self, username, password, verification_code):
"""
执行登录操作
"""
self.driver.implicitly_wait(5)
self.driver.refresh()
try:
# 清除并输入用户名
username_input = self.find_element(By.XPATH, '//*[@id="app"]/div/div[3]/div[1]/div[2]/div/form/div[1]/div/input')
username_input.clear()
username_input.send_keys(username)
# 清除并输入密码
password_input = self.find_element(By.XPATH, '//*[@id="app"]/div/div[3]/div[1]/div[2]/div/form/div[2]/div/input')
password_input.clear()
password_input.send_keys(password)
# 清除并输入验证码
verification_input = self.find_element(By.XPATH, '//*[@id="app"]/div/div[3]/div[1]/div[2]/div/form/div[3]/div[1]/div/input')
verification_input.clear()
verification_input.send_keys(verification_code)
# 点击登录按钮
login_button = self.find_element(By.XPATH, '//*[@id="app"]/div/div[3]/div[1]/div[2]/div/form/div[4]/input')
login_button.click()
# 检查登录是否成功
if self.check_login_null():
self.logger.info("登录失败,必填项不能为空!断言成功!")
elif self.check_login_success():
self.logger.info("登录成功,断言成功!")
self.return_to_login_page()
elif self.check_login_failure():
self.logger.info("登录失败, 必填项错误!断言成功!")
else:
self.logger.error("登录状态未知,断言失败!")
pytest.fail("登录状态未知,断言失败!")
except StaleElementReferenceException as e:
self.logger.error(f"元素已失效,重新查找... {e}")
pytest.fail(f"元素已失效,重新查找... {e}")
except Exception as e:
self.logger.error(f"登录操作失败: {e}")
pytest.fail(f"登录操作失败: {e}")
def return_to_login_page(self):
"""
返回登录页面
"""
try:
# 定位到退出按钮并点击
logout_button = self.find_element(By.XPATH, '//*[@id="app"]/div/div[1]/div/img[3]')
logout_button.click()
# 记录日志,表明已成功尝试返回登录页面
self.logger.info("已成功返回登录页面")
# 刷新页面,并等待一段时间以确保页面加载完成
self.driver.refresh()
self.driver.implicitly_wait(5)
except Exception as e:
# 如果发生异常,记录错误日志并使测试用例失败
self.logger.error(f"返回登录页面失败: {e}")
pytest.fail(f"返回登录页面失败: {e}")
def check_login_null(self):
"""
检查登录失败,必填项为空的情况
"""
try:
login_element_text = WebDriverWait(self.driver, 10).until(
EC.visibility_of_element_located((By.XPATH, '/html/body/div[2]/p'))
).text
# 断言登录失败后,提示信息中包含'请输入'关键词
assert "请输入" in login_element_text, "登录失败后未找到'请输入'提示语"
return True
except Exception as e:
self.logger.error(f"登录失败检查失败: {e}")
return False
def check_login_success(self):
"""
检查登录成功的情况
"""
try:
message_element_text = WebDriverWait(self.driver, 10).until(
EC.visibility_of_element_located((By.XPATH, "//*[contains(text(), '欢迎')]"))
).text
# 断言欢迎信息是否符合预期
assert "欢迎 预定标准版测试" == message_element_text, "登录成功后找到'欢迎 预定标准版测试'提示语"
return True
except Exception as e:
self.logger.error(f"登录成功检查失败: {e}")
return False
def check_login_failure(self):
"""
检查登录失败的情况
"""
try:
login_element_text = WebDriverWait(self.driver, 10).until(
EC.visibility_of_element_located((By.XPATH, '//*[@id="app"]/div/div[3]/div[1]/div[1]/div[1]'))
).text
# 断言登录元素的文本是否为"账号登录",如果符合,则说明登录失败检查成功
assert "账号登录" == login_element_text, "登录失败后未找到'账号登录'提示语"
return True
except Exception as e:
self.logger.error(f"登录失败检查失败: {e}")
return False
from time import sleep
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager
from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
class BasePage(object):
def __init__(self):
print('初始化开始!')
# 自动下载驱动
# self.driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()))
# 直接指定下载好的 ChromeDriver 路径
# # try:
self.driver_path = "C:\Program Files\Google\Chrome\Application\chromedriver.exe" # 替换为实际路径
self.driver = webdriver.Chrome(service=ChromeService(self.driver_path))
sleep(5)
print('初始化成功,驱动正常!')
# except Exception as e:
# print(f"初始化失败: {e}")
import os
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
import logging
# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
class Browser_driver(object):
def browser_init(self):
# logging.info('初始化开始!')
# 动态获取 chromedriver 路径
driver_path = os.getenv('CHROMEDRIVER_PATH', "C:\\Program Files\\Google\\Chrome\\Application\\chromedriver.exe")
try:
# 尝试使用指定路径初始化 WebDriver
self.driver = webdriver.Chrome(service=Service(driver_path))
# 设置隐式等待时间
self.driver.implicitly_wait(5) # 延长至5秒
# logging.info('初始化成功,驱动正常!')
except Exception as e:
logging.error(f'初始化失败: {e}')
raise
return self.driver
\ No newline at end of file
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论