python+selenium9--unittest框架+HTMLTestRunner

Unitest是python里面的单元测试框架,方便组建测试用例,执行用例,并生成测试报告

  • 注意:
  • 测试类,继承单元测试unitest.TestCase这个类
  • 测试方法(用例)必须以test开头
  • 测试类就是多个用例的一个集合,相当于是测试用例的一个模
import unittest

class TestCase(unittest.TestCase):

    def testPlus(self):
        a = 2
        b = 3
        c = a + b
        self.assertEqual(c,5)

    def testReduce(self):
        a = 5
        b = 3
        c = a - b
        self.assertEqual(c,2)

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

 

前置条件setUp(self):每个用例执行前,执行一次

后置条件teardown(self):每个用例执行后,执行一次

import unittest

class TestCase(unittest.TestCase):

def setUp(self):
print("每个用例执行前执行一次")

def tearDown(self):
print("每个用例执行后执行一次")
def test001(self):
print("测试用例001")
def test002(self):
print("测试用例002")

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

 

结果:

Testing started at 13:08 ...
每个用例执行前执行一次
测试用例001
每个用例执行后执行一次
每个用例执行前执行一次
测试用例002
每个用例执行后执行一次

Process finished with exit code 0

 

前置setUpClass:只执行一次前置,必须加@classmethod

后置tearDownClass:只执行一次结束,必须加@classmethod

例:

import unittest

class TestCase(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        print("只开始执行一次")
    @classmethod
    def tearDownClass(cls):
        print("只结束执行一次")

    def setUp(self):
        print("每个用例执行前执行一次")

    def tearDown(self):
        print("每个用例执行后执行一次")
    def test001(self):
        print("测试用例001")
    def test002(self):
        print("测试用例002")

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

 

结果:

Testing started at 13:12 ...
只开始执行一次
每个用例执行前执行一次
测试用例001
每个用例执行后执行一次
每个用例执行前执行一次
测试用例002
每个用例执行后执行一次
只结束执行一次

Process finished with exit code 0

项目框架

一级目录:项目名称

  二级文件夹:report

  二级文件夹:test_cases

    可以建三级子文件夹

    (待执行的脚本用test开头)

  二级文件夹:common

     存放一些公共模块,如HTMLTestRunner.py

  主函数:run_all.py

 

 

 

公共类

#gonggonglei.py

from time import sleep


class GongGongLei():
    """公共类"""

    def __init__(self, driver):
        self.driver = driver

    def Login(self, username, password):
        """登录方法"""
        self.driver.find_element_by_css_selector("#account").clear()
        self.driver.find_element_by_css_selector("#account").send_keys(username)
        self.driver.find_element_by_css_selector("[name='password']").clear()
        self.driver.find_element_by_css_selector("[name='password']").send_keys(password)
        self.driver.find_element_by_css_selector("#submit").click()
        sleep(3)

    def Is_login(self):
        t = ""
        try:
            t = self.driver.find_element_by_css_selector("#userMenu>a").text
            print("成功获取信息:%s" % t)
        except:
            t = ""
        return t

    def is_alert_exist(self):
        try:
            sleep(2)
            alert = self.driver.switch_to.alert
            text = alert.text
            alert.accept()
            return text
        except:
            return ""

 

测试用例

#test_login.py

from selenium import webdriver
from common.gonggonglei import GongGongLei
from time import sleep
import unittest


class LoginCase(unittest.TestCase):
    """登录测试类"""

    # @classmethod
    # def setUpClass(cls):
    #     cls.
    #
    # @classmethod
    # def tearDownClass(cls):
    #     cls.driver.quit()


    def setUp(self):
        self.driver = webdriver.Firefox()
        self.url = "http://127.0.0.1/zentao/user-login.html"
        self.driver.get(self.url)
        self.driver.implicitly_wait(10)
        # self.driver.switch_to.alert().text()

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


    def testlogin01(self):
        """登录成功测试用例"""
        GongGongLei(self.driver).Login("admin", "123456")
        sleep(2)
        t = GongGongLei(self.driver).Is_login()
        exp = "admin"
        self.assertTrue(t == exp)

    def testlogin02(self):
        """登录失败测试用例"""
        GongGongLei(self.driver).Login("admin1", "123456")
        sleep(2)
        t = GongGongLei(self.driver).is_alert_exist()
        exp = "登录失败,请检查您的用户名或密码是否填写正确。"
        self.assertTrue(t == exp)



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

 

run_all.py

# run_all.py

from common.HTMLTestRunner_cn import HTMLTestRunner
import unittest
import os

#获取当前运行的根目录
dirpath = os.path.dirname(os.path.realpath(__file__))
print("当前运行的根目录是%s" %dirpath)
#获取用例目录用join拼接
casepath = os.path.join(dirpath, "test_cases")
print("用例目录是%s" %casepath)
#获取报告的目录
reportpath = os.path.join(dirpath, "report", "report.html")
print("报告的目录是%s" %reportpath)

#查找用例
all_case = unittest.defaultTestLoader.discover(start_dir= casepath,
                                               pattern='test*.py',
                                               top_level_dir=None)

# start_dir 测试文件的路径
# pattern 匹配规则,*匹配多个字符
# top_level_dir = None
#     None 表示该文件就是顶层目录(这个参数一般不用动)


fp = open(reportpath, "wb")

runner = HTMLTestRunner(stream=fp,
                        title="禅道登录自动化",
                        description="登录自动化")

runner.run(all_case)

 

报告

 

 

 报告中无中文注释,可以添加个参数verbosity=2

 

posted @ 2020-09-21 22:46  莫使娇躯空对月  阅读(216)  评论(0编辑  收藏  举报