Python 学习 python 自动化,在 unittest 中遇到的问题

高高 · 2019年06月04日 · 最后由 cwen 回复于 2021年02月25日 · 1745 次阅读

学习 python+selenium+unittest 有一段时间了,这个遇到的问题实在是令人费解,希望有遇到过类似问题的大佬,可以指点迷津🙏 🙏

  • 运行环境
    • JetBrains PyCharm 2019.1.1 专业版
    • Python 3.7
    • Win 10

遇到的问题:我希望我在断言失败之后,自动截图,并且关闭弹窗,所以我把这个方法封装到了一个基类中。然后就出现问题了。当我在 test_case.py 文件中直接运行,就只会打开一个浏览器窗口,如果我在 test.runner.py 文件中运行就会出现两个浏览器窗口。代码如下:

test_case.py 文件
import unittest
import time

from Base.web_base_driver import WebBaseDriver
from Page.zn_brain import YlfManage
from Page.zn_console import UserConsole


class BaseClass(unittest.TestCase):
    driver = WebBaseDriver("Chrome")
    driver.implicitly_wai(5)
    driver.maximize_window()
    driver.quit_browser()
    screens_path = "../Screenshots/%d-%s失败.png"

    def error_screen(self, e_name):
        self.driver.driver.save_screenshot(self.screens_path % (int(time.time()), e_name))

    def check_assert(self, result_ele, expect, e_name):
        close_button = "s,[class='ivu-icon ivu-icon-ios-close-empty']"
        self.driver.sleep(1)
        try:
            get_result = self.driver.get_element(result_ele)
            self.assertEqual(get_result.text, expect, "%s失败" % e_name)
        except AssertionError:
            self.error_screen(e_name)
            self.driver.sleep(1)
            self.driver.click(close_button)
            raise AssertionError

class BrainTest(BaseClass):
    URL = "xxxxxxxxx"
    ALL_NAME = "香港"
    device_assert = "s,[class='nav-text ivu-tabs-nav']>div"

    @classmethod
    def setUpClass(cls):
        cls.driver.navigate(cls.URL)
        cls.zn_rm = YlfManage(cls.driver)
        cls.zn_rm.brain_login()

    @classmethod
    def tearDownClass(cls):
        cls.driver.sleep(5)
        cls.driver.quit_browser()

    def setUp(self):
        self.result_ele = 's,.ivu-table-row:nth-child(1)>td:nth-child(1)'
        self.driver.sleep(1)

    def test_01_c_dc(self):
        """xxxxxxxxx"""
        self.zn_rm.click_resource_mg()
        self.zn_rm.click_center_mg()
        self.zn_rm.create_dc(self.ALL_NAME)
        self.check_assert(self.result_ele, "%sIDC" % self.ALL_NAME, "xxxxxxxxx")

class ZnConsoleTest(BaseClass):
    CONSOLE_URL = "xxxxxxxxxxx"

    @classmethod
    def setUpClass(cls):
        cls.driver.navigate(cls.CONSOLE_URL)
        cls.zn_rm = UserConsole(cls.driver)
        cls.zn_rm.console_login()

    @classmethod
    def tearDownClass(cls):
        cls.driver.sleep(5)
        cls.driver.quit_browser()

    def setUp(self):
        self.result_ele = 's,.ivu-table-row:nth-child(1)>td:nth-child(1)'
        self.driver.sleep(1)

    def test_21_c_console_source(self):
        """xxxxxxxxx"""
        self.zn_rm.click_ylf_business()
        self.zn_rm.add_source_ip("1.1.1.1")
test_runner.py 文件
import unittest
import datetime

from Base import html_test_runner


class ZNTestRunner(object):
    CASE_PATH = "E:\\OneDrive\\zhian_antu\\Test_cases"

    def run(self):
        time_stamp = datetime.datetime.now()
        time = time_stamp.strftime('%Y.%m.%d_%H.%M.%S')
        discover = unittest.defaultTestLoader.discover(self.CASE_PATH, pattern="test_zn*.py")
        test_suite = unittest.TestSuite()
        test_suite.addTest(discover)
        print("本次执行测试用例数量:", test_suite.countTestCases())
        report_path = "E:\\OneDrive\\zhian_antu\\report\\zn_test_report_%s.html" % time
        report_file = open(report_path, mode="wb")
        test_runner = html_test_runner.HtmlTestRunner(stream=report_file,
                                                      title="自动化测试报告",
                                                      description="测试详情")
        test_runner.run(test_suite)


if __name__ == '__main__':
    aa = ZNTestRunner()
    aa.run()
共收到 14 条回复 时间 点赞

好像要自己评论一下才能在首页显示

testunit 的运行方式应该是在一套虚拟环境中,类的静态变量在不同 testsuit 里面应该是隔离的,楼主还是换一个方式吧!另外也不推荐这样使用全局变量,容易出现各种难搞的问题。

BaseClassdriver.quit_browser()后,BrainTest.setUpClasscls.driver.navigate(cls.CONSOLE_URL)还能执行么?

Tony 回复

嗯嗯 ,好的,非常感谢,您这边有什么好的建议吗?

hellohell 回复

不能,我写这个就是不想跑下面的代码了,一运行就是代开浏览器,然后关闭,然后打开然后关闭。

高高 回复

那看这个代码那块应该报错啊

hellohell 回复

报错倒是没有,就是用例执行失败

是 E 还是 F?

hellohell 回复

获取 driver 的时候使用单利模式

高高 #11 · 2019年06月05日 Author
zhuhfamy 回复


这样写的应该没有问题把,因为我不写这个 BaseClass 就是只打开一次浏览器的。

unittest 其实使用难度有点大,推荐使用 pytest。

我不是很懂你这个 unittest 调用,addTest() 运行了一次, run() 也运行了一次吧? 你试着调试下面的代码,你试一试要么直接 run(discover),或者 addTest()

你不应该在 BaseClass 类中调用开启和关闭浏览器。肯定会一打开后就关闭了。打开浏览器放在 setUpClass 里面,关闭放在 tearDownClass 里面。

需要 登录 後方可回應,如果你還沒有帳號按這裡 注册