登录并下单自动化测试login_order.py
举例:登录并下单自动化测试
#coding=utf-8
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
import time
import unittest
import configparser
class LoginOrderTest(unittest.TestCase):
def setUp(self):
self.driver=webdriver.Chrome()
self.driver.maximize_window()
self.driver.implicitly_wait(10)
self.driver.get("http://xdclass.net")
def tearDown(self):
print("用例执行结果")
pass
def test_logion_order(self):
"登录下单测试用例"
#读取配置文件获取用户名和密码
conf=configparser.ConfigParser(allow_no_value=True)
conf.read("./config/conf.ini")
username=conf.get('usercount','username')
password=conf.get('usercount','password')
driver=self.driver
login_element = driver.find_element_by_css_selector("#app > div > div:nth-child(1) > div.header > div.r_userinfo.f_r > div.login > span:nth-child(2)")
#对登录按钮触发点击事件,也可以直接调用 login_element.click()
ActionChains(driver).click(login_element).perform()
#定位输入用户名和密码输入框
#注入输入框输入值之前最好先清理
driver.find_element_by_css_selector("[type='text']").clear()
driver.find_element_by_css_selector("[type='text']").send_keys(username)
driver.find_element_by_css_selector("[type='password']").clear()
driver.find_element_by_css_selector("[type='password']").send_keys(password)
driver.find_element_by_class_name("btn").click()
#鼠标移动至登录之后的用户头像
user_info_element = driver.find_element_by_xpath('//*[@id="app"]/div/div[1]/div[2]/div[4]/div[5]/img')
ActionChains(driver).move_to_element(user_info_element).perform()
#判断登录是否成功
#获取登录之后的用户名称
user_name_element = driver.find_element_by_xpath('//*[@id="app"]/div/div[1]/div[2]/div[6]/div/div/div[1]/p')
name = user_name_element.text
#对登录之后的用户进行断言
self.assertEqual(name,'dechaohu',msg='用户名不匹配,登录失败')
if name == 'dechaohu':
#定位到某课程
driver.find_element_by_css_selector("#app > div > div.hot > div > div.content > a:nth-child(1) > div > img").click()
time.sleep(2)
#定位到某课程后点击开始学习
#定义所有窗口句柄(前提是放在所有窗口都已弹出动作之后,该两句一般是一起连用)
handles = driver.window_handles
#切换至最新的窗口句柄
driver.switch_to.window(handles[-1])
#点击立即购买
driver.find_element_by_css_selector("#app > div > div.details_container.clearfix > div.body.w > div.r_container.f_r > div.gostudy > div.buy_tolearn > a").click()
#定位课程价格
price_element=driver.find_element_by_css_selector("#app > div > div.payconfirm > div.price.w > div.l_content.f_l > i:nth-child(2)")
#获取课程价格值
price_num=price_element.text
#对课程价格断言
self.assertEqual(price_num,'¥1399',msg='购买失败')
driver.close()
if __name__ == '__main__':
unittest.main()