【问题标题】:Python Unit Test - the else block doesn't execute, and if it does there is no logging [closed]Python单元测试- else块不执行,如果执行,则没有日志记录[关闭]
【发布时间】:2019-09-04 08:53:10
【问题描述】:

我正在用 Python 和 Selenium 构建一个 QA 系统。我实现了一个很酷的记录器模块,我真的很喜欢它。我的系统运行良好并记录了所有内容(但前提是断言正确)。例如,下面这个测试:

def test_mode_check(self):
    """ Tests if the website is in TEST_MODE """

    login_page = LoginPage(self.driver)

    if login_page.is_test_mode() is True:
        assert True
        logger.success(TEST_MODE_SUCCESSFUL)
    else:
        logger.warning(TEST_MODE_FAILURE)
        print("i reach this")
        assert False

稍微解释一下。 TEST_MODE是我为网站设置的环境变量,应该在测试前设置。因此,它检查它是否打开。 TEST_SUCCESSFUL 和 TEST_FAILURE 只是全局变量,它们包含带有适当消息的字符串。我正在使用的记录器称为“loguru”。此外,login_page.is_test_mode() 只是一个特定于页面的方法,它在页面上查找 TEST_MODE 视觉指示,如果找到则返回 TRUE。这是参考的方法:

def is_test_mode(self):
    """
    This function checks if the website is in test mode. The tests should not proceed if it is not in TEST_MODE.

    :return: True or False depending on the condition
    """

    if self.find_element(*self.locator.IS_TEST_MODE).text == \
            "The website is running in test mode. ":
        return True
    else:
        return False

因此,如果设置了 env 变量,则输出如下:

04/09/19 at 11:41:24 AM | SUCCESS  | TEST_MODE is set ✓


test_mode_check (tests.individual_tests.tests_preliminary.PreliminaryTests) ... OK (5.645s)

一切都很棒。但是,如果我故意删除 ENV 变量以测试错误日志记录,那么这是唯一发生的事情:

test_mode_check (tests.individual_tests.tests_preliminary.PreliminaryTests) ... ERROR (7.585422)
s

======================================================================
ERROR [7.585422s]: tests.individual_tests.tests_preliminary.PreliminaryTests.test_mode_check
... Traceback ...
# here goes the exception ... which basically says that the element is
# absent from the webpage

根本不显示我的警告消息,它提供更多信息。我还在 else 块 print('i reach this') 中尝试了打印功能,但没有显示任何内容。谁能给我任何提示?如果需要,我可以提供更多信息。

编辑:我正在使用unittest

【问题讨论】:

  • 您是否使用像 pytest 这样的框架来运行您的单元测试?
  • 哦,我忘了说。我正在使用默认的 Python 库 - unittest

标签: python selenium unit-testing testing qa


【解决方案1】:

可能是你的:

self.find_element(*self.locator.IS_TEST_MODE).text

函数抛出一个错误,你没有抓住它。尝试使用 try/except 代替它。

【讨论】:

    【解决方案2】:

    我使用了 try-catch 块,解决了我的问题:

        try:
            if login_page.is_test_mode() is True:
                assert True
                logger.success(TEST_MODE_SUCCESSFUL)
        except Exception as e:
            logger.warning(TEST_MODE_FAILURE)
            raise e
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-10
      • 1970-01-01
      • 2021-11-23
      • 2018-01-17
      • 2019-01-04
      相关资源
      最近更新 更多