一、简单版_面向对象/ 面向过程实现登入网易云音乐
二、本文主要结合unittest测试框架,实现代码与测试用例分离。
1. web element and operation
页面代码部分:163_music_web.py
from selenium import webdriver
from selenium.webdriver.common.by import By
class Login_163_Music():
_login_locator = (By.CSS_SELECTOR, 'a.link.s-fc3')
_other_login_mode_locator =(By.CSS_SELECTOR ,'a.u-btn2.other')
_phone_number_login_locator = (By.CSS_SELECTOR ,'a.u-btn2.u-btn2-2')
_privacy_policy_checkout_loactor = (By.CSS_SELECTOR ,'input#j-official-terms')
_input_phone_number_locator = (By.CSS_SELECTOR , 'input.j-phone.txt.u-txt')
_input_password_locator = (By.CSS_SELECTOR , 'input#pw.j-pwd.u-txt')
_login_button_locator = (By.CSS_SELECTOR, 'a.j-primary.u-btn2.u-btn2-2')
_locate_mark_locator = (By.CSS_SELECTOR, 'i.u-icn.u-icn-25')
def __init__(self,url):
self.driver = webdriver.Chrome()
self.driver.implicitly_wait(4)
self.driver.maximize_window()
self.driver.get(url)
def click_login(self):
self.driver.find_element(*self._login_locator).click()
def select_other_login_mode(self):
self.driver.find_element(*self._other_login_mode_locator).click()
def check_privacy_policy_checkout(self):
if not self.driver.find_element(*self._privacy_policy_checkout_loactor).is_selected():
self.driver.find_element(*self._privacy_policy_checkout_loactor).click()
def phone_number_login(self):
self.driver.find_element(*self._phone_number_login_locator).click()
def input_phone_number_account(self,phone_number):
self.driver.find_element(*self._input_phone_number_locator).send_keys(phone_number)
def input_password(self,password):
self.driver.find_element(*self._input_password_locator).send_keys(password)
def click_login_button(self):
self.driver.find_element(*self._login_button_locator).click()
def close_window(self):
self.driver.quit()
def is_login_scuccessfully(self):
if self.driver.find_element(*self._locate_mark_locator).is_displayed:
#print ' login failed'
raise 'login failed'
2. testcase
测试用例部分,通过具体测试步骤调用163_music_web.py中相应的方法,组合起来实现自动化。
本次测试用例:选取的是错误的手机号码+随意的密码,登入失败
test_login.py
import unittest
from wangyi_music_web import Login_163_Music
class TestLogin(unittest.TestCase):
def test_login_wangyiyun(self):
login = Login_163_Music('https://music.163.com/')
login.click_login()
login.select_other_login_mode()
login.check_privacy_policy_checkout()
login.phone_number_login()
login.input_phone_number_account('165564464654')
login.input_password('hfied')
login.click_login_button()
login.is_login_scuccessfully()
login.close_window()
if __name__ =='__main__':
unittest.main()