Is there a downside for using __init__(self) instead of setup(self) for a nose test class?

旧城冷巷雨未停 提交于 2019-12-01 01:47:13

问题


Running nosetests -s for

class TestTemp():

    def __init__(self):
        print '__init__'
        self.even = 0

    def setup(self):
        print '__setup__'
        self.odd = 1

    def test_even(self):
        print 'test_even'
        even_number = 10
        assert even_number % 2 == self.even

    def test_odd(self):
        print 'test_odd'
        odd_number = 11
        assert odd_number % 2 == self.odd

prints out the following.

__init__
__init__
__setup__
test_even
.__setup__
test_odd
.

The test instances are created before tests are run, while setup runs right before the test.

For the general case, __init__() and setup() accomplish the same thing, but is there a downside for using __init__() instead of setup()? Or using both?


回答1:


While __init__ may work as a replacement for setUp, you should stick to setUp because it is part of the stylized protocol for writing tests. It also has a counterpart, tearDown, which __init__ does not, as well as class- and module-level counterparts which __init__ does not.

Writing test classes is different than writing normal classes, so you should stick to the style used to write test classes.




回答2:


Yes, you are supposed to create a clean slate for the tests, and keep your individual tests isolated.

It appears the test instances (one per test) are created in one batch, while setup is called right before each test. If your setup needs to reset external state, you'll need to do this in setup; if you were to do this in __init__ individual tests can screw up that external state for the rest of the test run.



来源:https://stackoverflow.com/questions/14286722/is-there-a-downside-for-using-init-self-instead-of-setupself-for-a-nose-t

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!