Selenium2+python自动化(unittest)

# coding:utf-8
from selenium import webdriver
import unittest
import time
class Bolg(unittest.TestCase):
    u'''登录博客'''
    def setUp(self):
        self.driver = webdriver.Firefox()
        url = "https://passport.cnblogs.com/user/signin"
        self.driver.get(url)
        self.driver.implicitly_wait(30)

    def login(self, username, psw):
        u'''这里写了一个登录的方法,账号和密码参数化'''
        self.driver.find_element_by_id("input1").send_keys(username)
        self.driver.find_element_by_id("input2").send_keys(psw)
        self.driver.find_element_by_id("signin").click()
        time.sleep(3)

    def is_login_sucess(self):
        u'''判断是否获取到登录账户名称'''
        try:
            text = self.driver.find_element_by_id("lnk_current_user").text
            print text
            return True
        except:
            return False

    def test_01(self):
        u'''登录案例参考:账号,密码自己设置'''
        self.login(u"you", u"xxxx")  # 调用登录方法
        # 判断结果
        result = self.is_login_sucess()
        self.assertTrue(result)

    def test_02(self):
        u'''登录案例参考:账号,密码自己设置'''
        self.login(u"you", u"xxxx")  # 调用登录方法
        # 判断结果   
        result = self.is_login_sucess()
        self.assertTrue(result)

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

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

 

导入HTMLTestRunner

这个模块下载不能通过pip安装了,只能下载后手动导入,下载地址:http://tungwaiyip.info/software/HTMLTestRunner.html,Download下HTMLTestRunner.py文件就是我们需要下载的包,下载后手动拖到python安装文件的Lib目录下

参考代码:

下面的代码文件路径用的相对路径,这样就避免代码换个地址找不到路径的情况了

# coding:utf-8
import unittest
import os
import HTMLTestRunner

# python2.7要是报编码问题,就加这三行,python3不用加

import sys
reload(sys)
sys.setdefaultencoding('utf8')

# 用例路径
case_path = os.path.join(os.getcwd(), "case")
# 报告存放路径
report_path = os.path.join(os.getcwd(), "report")
def all_case():
    discover = unittest.defaultTestLoader.discover(case_path,
                                                    pattern="test*.py",
                                                    top_level_dir=None)
    print(discover)
    return discover

if __name__ == "__main__":
    # runner = unittest.TextTestRunner()
    # runner.run(all_case())

    # html报告文件路径
    report_abspath = os.path.join(report_path, "result.html")
    fp = open(report_abspath, "wb")
    runner = HTMLTestRunner.HTMLTestRunner(stream=fp,
                                           title=u'自动化测试报告,测试结果如下:',
                                           description=u'用例执行情况:')

    # 调用add_case函数返回值
    runner.run(all_case())
    fp.close()

posted on 2018-12-24 17:01  油条哥  阅读(174)  评论(0编辑  收藏  举报