使用 Python 和 Selenium 来建立一个简单的登入功能的自动测试。
步骤一:建立测试环境
确保你已经安装了Selenium套件:(Selenium: 用于自动化浏览器操作。)pip install selenium
下载Chrome WebDriver并确保它可以被 Python 找到。(Chrome WebDriver: 用于控制Chrome浏览器。)你可以从这里下载:https://sites.google.com/a/chromium.org/chromedriver/downloads
步骤二:建立网页(待测物)
登入页面 (login.html
)
<!DOCTYPE html><html><head> <title>Login Page</title> <script> function loginUser() { var username = document.getElementById("username").value; var password = document.getElementById("password").value; if (username === "testuser" && password === "testpassword") { document.getElementById("loginResult").innerHTML = "Login Successful!"; } else { document.getElementById("loginResult").innerHTML = "Invalid username or password"; } } </script></head><body> <h1>Login</h1> <div> <label for="username">Username:</label> <input type="text" id="username" name="username"> </div> <div> <label for="password">Password:</label> <input type="password" id="password" name="password"> </div> <div> <button onclick="loginUser()">Login</button> </div> <div id="loginResult"></div></body></html>
步骤三:建立测试
测试程式 (test_login.py
)
from selenium import webdriverdef test_login_functionality(): # 启动浏览器 driver = webdriver.Chrome() # 前往登入页面 driver.get("file:///path_to_login.html") # 替换成你的 login.html 档案路径 # 找到输入框,输入帐号密码 username = driver.find_element_by_id("username") password = driver.find_element_by_id("password") username.send_keys("testuser") password.send_keys("testpassword") # 找到登入按钮并点击 login_button = driver.find_element_by_tag_name("button") login_button.click() # 验证登入结果 login_result = driver.find_element_by_id("loginResult") assert login_result.text == "Login Successful!" # 关闭浏览器 driver.quit()
步骤四:执行测试
使用pytest执行你的测试:
python -m pytest test_login.py
这样,你就可以确保登入按钮能正确显示并执行登入功能了。