简体   繁体   English

__init__ 用于 unittest.TestCase

[英]__init__ for unittest.TestCase

I'd like to add a couple of things to what the unittest.TestCase class does upon being initialized but I can't figure out how to do it.我想为unittest.TestCase类在初始化时所做的事情添加一些东西,但我不知道如何去做。

Right now I'm doing this:现在我正在这样做:

#filename test.py

class TestingClass(unittest.TestCase):

    def __init__(self):
        self.gen_stubs()

    def gen_stubs(self):
        # Create a couple of tempfiles/dirs etc etc.
        self.tempdir = tempfile.mkdtemp()
        # more stuff here

I'd like all the stubs to be generated only once for this entire set of tests.我希望为整个测试集只生成一次所有存根。 I can't use setUpClass() because I'm working on Python 2.4 (I haven't been able to get that working on python 2.7 either).我不能使用setUpClass()因为我正在使用 Python 2.4(我也无法在 python 2.7 上使用它)。

What am I doing wrong here?我在这里做错了什么?

I get this error:我收到此错误:

 `TypeError: __init__() takes 1 argument (2 given)` 

...and other errors when I move all of the stub code into __init__ when I run it with the command python -m unittest -v test . ...和其他错误,当我使用命令python -m unittest -v test运行所有存根代码到__init__时。

Try this:尝试这个:

class TestingClass(unittest.TestCase):

    def __init__(self, *args, **kwargs):
        super(TestingClass, self).__init__(*args, **kwargs)
        self.gen_stubs()

You are overriding the TestCase 's __init__ , so you might want to let the base class handle the arguments for you.您正在覆盖TestCase__init__ ,因此您可能希望让基类为您处理参数。

Just wanted to add some clarifications about overriding the init function of只是想添加一些关于覆盖 init 函数的说明

unittest.TestCase

The function will be called before each method in your test class.该函数将在测试类中的每个方法之前调用。 Please note that if you want to add some expensive computations that should be performed once before running all test methods please use the SetUpClass classmethod请注意,如果您想添加一些在运行所有测试方法之前应该执行一次的昂贵计算,请使用SetUpClass类方法

@classmethod
def setUpClass(cls):
    cls.attribute1 = some_expensive_computation()

This function will be called once before all test methods of the class.该函数将在类的所有测试方法之前调用一次 See setUp for a method that is called before each test method.有关在每个测试方法之前调用的方法,请参阅setUp

Install unittest2 and use that package's unittest.安装 unittest2 并使用该包的 unittest。

import unittest2 

and then use the setupModule / tearDownModule or setupClass / tearDown class for special initialization logic然后使用 setupModule/tearDownModule 或 setupClass/tearDown 类进行特殊的初始化逻辑

More info: http://www.voidspace.org.uk/python/articles/unittest2.shtml更多信息: http : //www.voidspace.org.uk/python/articles/unittest2.shtml

Also most likely your are creating an integration test more than an unittest.也很可能您正在创建一个集成测试而不是单元测试。 Choose a good name for the Tests to differentiate them or put in a different container module.为测试选择一个好名字以区分它们或放入不同的容器模块中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM