Python-即使出现一些错误,如何继续我的测试脚本

Posted

技术标签:

【中文标题】Python-即使出现一些错误,如何继续我的测试脚本【英文标题】:Python-How to continue my test script even if some error comes 【发布时间】:2018-12-20 09:11:30 【问题描述】:

这是我的代码。我编写了可以测试多个测试用例的脚本。当出现错误时,此脚本会引发异常,但是我希望它保留错误计数及其描述,并在测试执行后记录它是成功还是失败。更重要的是应该以任何方式运行完整的测试脚本。

from selenium import webdriver
from generic_functions.FindElement import HandyWrappers
from generic_functions.takescreenshots import Screenshot
from generic_functions.error_handle import CatchExceptions
import os
import time
import unittest


class TestEnrollment(unittest.TestCase):
    driverLocation = 
    "C:\\Users\\Sales\\Desktop\\Automation\\Trendz\\libs\\chromedriver.exe"
    os.environ["webdriver.chrome.driver"] = driverLocation
    driver = webdriver.Chrome(driverLocation)
    driver.maximize_window()
    driver.implicitly_wait(10)


def test_login(self):
    try:
        baseURL = "https://portal.ABCD.com"
        driver = self.driver
        driver.get(baseURL)
        hw = HandyWrappers(driver)

        username = hw.getElement(".//form[@id='login-form']/fieldset/section[1]/label[2]/input[@name='email']",
                                 locatorType="xpath")
        username.send_keys("ABCD@live.com")
        time.sleep(2)

        password = hw.getElement(".//form[@id='login-form']/fieldset/section[2]/label[2]/input[@name='password']",
                                 locatorType="xpath")
        password.send_keys("ABCD09")

        signIn = hw.getElement(".//form[@id='login-form']/footer/button[contains(text(),'Sign in')]",
                               locatorType="xpath")
        signIn.click()

        self.assertTrue(driver.find_element_by_xpath(".//header[@id='header']/section/div/div[@id='logout']/span/a12"), "Sign Out")


    except Exception as err:
          raise err

def test_menu_enr(self):
    driver = self.driver
    hw = HandyWrappers(driver)

    find_enrollment = hw.getElement(".//aside[@id='left-panel']/nav/ul[14]/li/a/span", locatorType="xpath")
    find_enrollment.click()


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

【问题讨论】:

你在test_login 中有raise err,当异常发生时会抛出错误。删除它并打印错误,如print(err) 是的。我已经做到了。但它显示“测试结果正常”。但是有一个错误,必须在最终结果中@REDDYPRASAD 基本上我必须在我的测试报告中记录该错误。如果我按照你说的那样做,那么它永远不会出现错误计数。 【参考方案1】:

不要提出,使用passcontinue

def test_login():
   try:
       ... 
   except Exception:
       # log the exception here
       pass  # or you could use 'continue'

注意:也必须调查一下diff bw pass and continue

【讨论】:

我按照你说的尝试过,但它没有给我错误计数但是有一个错误。【参考方案2】:

收集某个列表中的所有错误,然后在测试结束时断言错误列表

from selenium import webdriver
from generic_functions.FindElement import HandyWrappers
from generic_functions.takescreenshots import Screenshot
from generic_functions.error_handle import CatchExceptions
import os
import time
import unittest


class TestEnrollment(unittest.TestCase):
    driverLocation = "C:\\Users\\Sales\\Desktop\\Automation\\Trendz\\libs\\chromedriver.exe"
    os.environ["webdriver.chrome.driver"] = driverLocation
    driver = webdriver.Chrome(driverLocation)
    driver.maximize_window()
    driver.implicitly_wait(10)

    def setUp(self):
        self.errors = []

    def tearDown(self):
        self.assertEqual([], self.errors)

    def test_login(self):
        try:
            baseURL = "https://portal.ABCD.com"
            driver = self.driver
            driver.get(baseURL)
            hw = HandyWrappers(driver)

            username = hw.getElement(".//form[@id='login-form']/fieldset/section[1]/label[2]/input[@name='email']",
                                     locatorType="xpath")
            username.send_keys("ABCD@live.com")
            time.sleep(2)

            password = hw.getElement(".//form[@id='login-form']/fieldset/section[2]/label[2]/input[@name='password']",
                                     locatorType="xpath")
            password.send_keys("ABCD09")

            signIn = hw.getElement(".//form[@id='login-form']/footer/button[contains(text(),'Sign in')]",
                                   locatorType="xpath")
            signIn.click()

            self.assertTrue(driver.find_element_by_xpath(
                ".//header[@id='header']/section/div/div[@id='logout']/span/a12"), "Sign Out")

        except Exception as err:
            self.errors.append(err)

    def test_menu_enr(self):
        driver = self.driver
        hw = HandyWrappers(driver)

        find_enrollment = hw.getElement(
            ".//aside[@id='left-panel']/nav/ul[14]/li/a/span", locatorType="xpath")
        find_enrollment.click()


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

tearDown 方法将在最后运行并显示所有错误消息(如果有)

据我所知,这不是理想的解决方案。它是一种黑客修复

【讨论】:

是的,只有当我在函数中调用断言时它才对我有用,否则它会引发错误。 如果断言中没有出现错误,请告诉我该怎么做。 如果不存在错误意味着代码运行良好。我们不必做任何事情。你想做什么??【参考方案3】:

如果您将 selenium webdriver 与 Python unittest 一起使用(看起来像您),SeleniumBase 框架具有内置的漂亮的 delayed_assert_textdelayed_assert_element 方法,用于在测试结束时处理测试失败。您可以使用 pip 安装 seleniumbase,或者从 github 克隆 repo。

以下代码取自this example。

from seleniumbase import BaseCase

class MyTestClass(BaseCase):

    def test_delayed_asserts(self):
        self.open('http://xkcd.com/993/')
        self.wait_for_element('#comic')
        self.delayed_assert_element('img[]')
        self.delayed_assert_element('img[]')  # Will Fail
        self.delayed_assert_element('#comicmap')
        self.delayed_assert_text('Fake Item', '#middleContainer')  # Will Fail
        self.delayed_assert_text('Random', '#middleContainer')
        self.delayed_assert_element('a[name="Super Fake !!!"]')  # Will Fail
        self.process_delayed_asserts()

在脚本内部,有多个断言会失败,但只有在调用self.process_delayed_asserts() 之后才会失败。这是运行后的输出:

pytest delayed_assert_test.py

=============================== test session starts ===============================
platform darwin -- Python 3.6.5, pytest-3.7.3, py-1.5.4, pluggy-0.7.1

delayed_assert_test.py F

==================================== FAILURES =====================================
________________________ MyTestClass.test_delayed_asserts _________________________
E               Exception: 
E               *** DELAYED ASSERTION FAILURES FOR: examples.delayed_assert_test.MyTestClass.test_delayed_asserts
E               CHECK #2: (https://xkcd.com/993/)
E                Element img[] was not visible after 1 second!
E               CHECK #4: (https://xkcd.com/993/)
E                Expected text Fake Item for #middleContainer was not visible after 1 second!
E               CHECK #6: (https://xkcd.com/993/)
E                Element a[name="Super Fake !!!"] was not visible after 1 second!

Exception
============================ 1 failed in 7.53 seconds =============================

【讨论】:

以上是关于Python-即使出现一些错误,如何继续我的测试脚本的主要内容,如果未能解决你的问题,请参考以下文章

Pentaho 数据集成,插入/更新步骤即使在发现一些错误后仍继续

python+selenium 在执行测试脚本时,遇到错误如何能继续执行下去而不停止

即使内容不够大,也将页脚强制放在屏幕底部(不粘)

CSS:即使在滚动时也使页脚始终位于页面底部

即使应用程序在 ios 中被杀死或从后台删除,如何继续更新我的位置?

即使在应用退出后,如何使用 UIAutomation 工具继续测试 iOS 应用?