【问题标题】:Testing within a python class method在 python 类方法中进行测试
【发布时间】:2016-08-27 06:42:02
【问题描述】:

我在 python 中使用 unittest 来测试一个项目。该项目定义了旨在供其他 python 开发人员子类化的类。然后可以运行该项目并利用用户编写的子类。

我想测试子类的方法是否被项目传递了正确的数据。我怎样才能做到这一点?从项目子类化的测试类中调用unittest.TestCase.assert* 方法并不简单。

我尝试将TestCase 对象设置为全局变量,并从子类方法中调用TestCase 对象的断言方法,但全局变量似乎没有在测试类方法的范围内定义.

例子

import unittest
import myproject


class TestProjectClass(unittest.TestCase):
    def test_within_class_method(self):
        myproject.run(config_file_pointing_to_ProjectClass)     # Calls SomeUsersClass.project_method()


class SomeUsersClass(myproject.UserClassTemplate):
    def project_method(self, data_passed_by_project):
        #want to test data_passed_by_project in here
        pass

【问题讨论】:

  • 如何运行测试?你在用什么测试运行器类?
  • 测试由 PyCharm 'run unit tests in tedting.py' 运行,目前尚不清楚它们是如何做到的。
  • 问题不清楚吗?我会期待更多的答案。

标签: python class python-unittest


【解决方案1】:

我能够通过使用raise 将自定义异常传递给unittest.TestCase 来完成这项工作。自定义异常可以包含任何需要测试的数据。我没有在这里展示它,但test_helper.py 只是Exception 的一个简单的子类。

import unittest
import myproject
from test_helper import PassItUpForTesting


class TestProjectClass(unittest.TestCase):
    def test_within_class_method(self):
        try:
            # The following line calls SomeUsersClass.project_method()
            myproject.run(config_file_pointing_to_ProjectClass)
        except PassItUpForTesting as e:
            # Test things using e.args[0] here
            # Example test
            self.assertEqual(e.args[0].some_attribute_of_the_data,
                             e.args[0].some_other_attribute_of_the_data)


class SomeUsersClass(myproject.UserClassTemplate):
    def project_method(self, data_passed_by_project):
        #want to test data_passed_by_project in here
        raise PassItUpForTesting(data_passed_by_project)

(由于某种原因,在同一个文件中定义自定义异常不起作用,因为在用户类中创建的异常实例没有被识别为自定义异常的实例。通过 @987654326 检查异常@ 透露异常类型的出现方式不同。所以我将异常放在另一个模块中,导入它,它就起作用了。)

【讨论】:

    【解决方案2】:

    你可以在 docstring 中尝试 unittest。

    看看这个:

    http://docs.python-guide.org/en/latest/writing/tests/#doctest

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-25
      • 1970-01-01
      • 2023-03-25
      • 2018-12-23
      • 1970-01-01
      • 2011-09-09
      • 1970-01-01
      相关资源
      最近更新 更多