一、项目结构

在report目录 下,再新建一层image,用来存放运行过程中的截图

一、编写浏览器驱动脚本:models-driver.py

from selenium.webdriver import Remote
from selenium import webdriver

#启动浏览器驱动
def borwser():
#driver = webdriver.Firefox()
#driver = Remote(command_executor='http://' + host +'/wd/hub',desired_capabilities = dri )

driver = Remote(command_executor='http://localhost:4444/wd/hub',
desired_capabilities={'platform': 'ANY',
'browserName':'firefox',
'version': '',
'javascriptEnabled': True
})

return driver

if __name__ == '__main__':
dr = borwser()
dr.get("http://www.baidu.com")
dr.quit()

注意:desired_capabilities的写法要符合规范,否则会报webdriver.py的各种错误

 二、编写基础类脚本page_obj\base.py

class Page(object):
'''
页面基本类,用于所有页面的继承
'''
bbs_url = 'http://bbs.meizu.cn'
def __init__(self,selenium_driver,base_url = bbs_url,parent = None):
self.base_url = bbs_url
self.driver = selenium_driver
self.timeout = 30
self.parent = parent

def _open(self,url):
url = self.base_url + url
self.driver.get (url)
assert self.on_page(),'Did not land on &s' %url

#定位单个元素
def _find_element(self,*loc):
return self.driver.find_element(*loc)

#定位多个元素
def _find_elements(self,*loc):
return self.driver.find_elements(*loc)

#打开浏览器地址
def open(self):
self._open(self.url)

def on_page(self):
return self.driver.current_url == (self.base_url + self.url)

def script(self,src):
return self.driver.execute_script(src)

 三、编写浏览器启动脚本:test_case\models\myunit.py

from selenium import webdriver
from .driver import browser
import unittest
import os

#把浏览器引过来,以后不用动,打开浏览器,等待10秒,窗口最大化
class MyTest(unittest.TestCase):
def setUp(self):
self.driver = browser()
self.driver.implicitly_wait(10)
self.driver.maxmize_window()


def tearDown(self):
self.driver.quit()

四、编写截图保存功能脚本:test_case\models\function.py

from selenium import webdriver
import os

#截图保存
def insert_img(driver,file_name):
base_dir = os.path.dirname(os.path.dirname(__file__))
base_dir = str(base_dir)
base_dir = base_dir.replace('\\','/')
base = base_dir.split('/test_case')[0]
file_path = base + "/report/image/" + file_name
driver.get_screenshot_as_file(file_path)

#以下内容为做实验,实际使用时,可注释,执行后,在D:\selenium-zidonghua\myproject\bbs\report\image目录下,生成一张baidu.png图片
if __name__ == "__main__":
driver =webdriver.Firefox()
driver.get("http://www.baidu.com")
insert_img(driver,'baidu.png')
driver.quit() 

五、编写登录页的类脚本:test_case\page_obj\loginPage.py

#coding=utf-8
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from base import Page
from time import sleep

class login(Page):
"""
用户登录界面
"""
url = '/'

#ActionChains
#bbs_login_user_loc = (By.XPATH,"//div[@id='mzCust']/div/img") #或者使用以下语句代替,根据实据情况
bbs_login_user_loc = (By.CLASS_NAME,"alertDialogContent")
bbs_login_button_loc = (By.ID,"mzLogin")

def bbs_login(self):
self.find_element (*self.bbs_login_user_loc).click()
sleep(1)
self.find_element(*self.bbs_login_buton_loc).click()
sleep(1)

#如果以上语句鼠标悬停无法出来,可使用直接打开这个相应的页面
#self._open("/login.php?")

login_username_loc = (By.ID,'account')
login_password_loc = (By.ID,'password')
login_button_loc = (By.ID,'login')

#登录用户名
def login_username(self,username):
self.find_element(*self,login_username_loc).send_keys(username)

#登录密码
def login_password(self,password):
self.find_element(*self,login_password_loc).send_keys(password)

#登录按钮
def login_button(self):
self.find_element(*self,login_button_loc).click()


#定义统一登录入口
def user_login(self,username='username',password='111111'):
"""获取用户名密码登录"""
self.open()
self.bbs_login()
self.login_username(username)
self.login_password_loc(password)
self.login_button()
sleep(2)

user_error_hint_loc = (By.XPATH,"//span[@for='account']")
pass_error_hint_loc = (By.XPATH,"//span[@for = 'password']")
user_login_success_loc = (By.ID,'mzCustName')

#用户名错误提示
def user_error_hint(self):
return self.find_element(*self.user_error_hint_loc).text

#密码错误提示
def user_error_hint(self):
return self.find_element(*self.pawd_error_hint_loc).text

#登录成功用户名
def user_login_success(self):
return self.find_element(*self.user_login_success_loc).text

六、编写登录的测试用例test_case\login_sta.py

#coding=utf-8
from time import sleep
import unittest,random,sys
sys.path.append("./models/")
sys.path.append(".page_obj")
from modeles import myunit,function
from page_obj.loginPage import login

class loginTest(myunit.MyTest):
"""社区登录测试"""

#测试登录用户
def user_login_verify(self,username='',password=''):
login(self.driver).user_login(username,password)

def test_login1(self):
"""用户名、密码为空登录"""
self.user_login_verify()
po = login(self.driver)
self.assertEqual(po.user_error_hint(),'账号不能为空')
self.assertEqual(po.pawd_error_hint(),'密码不能为空')
function.insert_img(self.driver,"user_pawd_empth.jpg")


def test_login2(self):
"""用户名正确、密码为空登录"""
self.user_login_verify(username = 'pytest')
po = login(self.driver)
self.assertEqual (po.pawd_error_hint(),"密码不能为空")
function.insert_img(self.driver,"pawd_empth.jpg")

def test_login3(self):
"""用户名为空,密码正确"""
self.user_login_verify(password = '123456')
po = login(self.driver)
self.assertEqual (po.user_error_hint(),'账号不能为空')
function.insert_img(self.driver,"user_empty.jpg")

def test_login4(self):
"""用户名与密码不匹配"""
character = random.choise('fjdsljfldsjfldsjfldsfdsfdf')
username = "zhangsan" + character
self.user_login_verify(usesrname=username,password = '123456')
po = login(self.driver)
self.assertEqual (po.pawd_error_hint(),'密码与账号不匹配')
function.insert_img(self.driver,"user_pawd_error.jpg")

def test_login5(self):
"""用户名密码正确"""
self.user_login_verify(username='zhangsan',passwd='123456'
sleep (2)
po = login(self,driver)
self.assertEqual(po.user_login_success(),"张三")
function.insert_img(self.driver,"user_pawd_true.jpg")

if __name__ == "__main__":
unittest.main()

七、编写最终的运行脚本,并发送运行报告的邮件:与项目bbs同级:run_bbs_case.py

#coding=utf-8
from HTMLTestRunner import HTMLTestRunner
from email.mime.text import MIMEText
from email.header import header
import smtplib
import unittest
import time
import os

#===============定义发送邮件==================
def send_mail(file_new):
f = open(file_new,'rb')
mail_body = f.read()
f.close()

msg = MIMEText(mail_body,'html','utf-8')
msg[Subject] = Header("自动化测试报告")

smtp = smtplib.SMTP()
smtp.connect("smtp.126.com")
smtp.login("username@126.com","123456")
smtp.sendmail("username@126.com","receive@126.com",msg.as_string())
smtp.quit()
print("email has send out!")

#=====查找测试报告目录,找到最新生成的测试报告文件======
def new_report(testreport):
lists = os.listdir(testreport)
lists.sort(key=lamba fn:os.path.gettime(testreport + "\\" + fn))
file_new = os.path.jooin(testreport,list[-1])
print (file_new)
return file_new

if __name__ == "__main__":
now = time.strftime("%Y-%m-%d %H_%M_%S")
filename = './bbs/report' + now +'result.html'
fp = open (filename,'wb')
runner = HTMLTestRunner(stream = fp,
title='自动化测试报告',
description='环境:win10')
discover = unittest.defaultTestLoader.discover('./bbs/test_case',
pattern = '*_sta.py')
runner.run(discover)
fp.close()
file_path = new_report('./bbs/report/')
send_mail(file_path)