我已经对 unittest.TestCase 进行了子类化。每次我想使用@unittest.skipIf 时,我还应该导入unittest 吗?
I have subclassed unittest.TestCase. Should I still be importing unittest every time I want to use @unittest.skipIf?
我已经使用了很多 python unittest 并且有一个装饰器方法可以用来有条件地跳过这样的测试:
import unittest
class TestStringMethods(unittest.TestCase):
@unittest.skipIf(1 == 1, 'Skipped because 1 does indeed equal 1')
def test_upper(self):
self.assertEqual('foo'.upper(), 'FOO')
虽然我想向 unittest.TestCase class 添加一些功能,所以我对其进行了子class编辑以开始添加我自己的自定义代码:
import unittest
class CustomTestCase(unittest.TestCase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs) # Just use whatever is in TestCase's init + our stuff
self.foo = 'foo' # our stuff
self.bar = 'bar'
def mymethod(self, param1, param2): # Some custom method I wanted to make for these custom test cases
pass
要继续使用 @unittest.skipIf
,我一直将 import unittest
放在我的任何 CustomTestCase
测试文件的顶部,但我想知道这是否是正确的处理方式。我进口的东西是否超过了我的需要?还是我什么都不担心?
您已经子类化的事实与您的要求无关。一般来说,子类导入或使用它们的超类是没有问题的:事实上,它们必须在定义它们时导入它们的超类。这就是问题所在(超类不应该知道它的子类)。
To continue using @unittest.skipIf I have been sticking import
unittest at the top of any of my CustomTestCase test files, but I
wonder if thats the correct way to be doing things. Am I importing
more than I need?
如果你想使用 unittest
模块的任何属性(包括 skipIf
装饰器),那么你必须将它导入到相关模块中。没有比这更复杂的了。
如果您担心 header 守卫之类的东西,就像您需要 C/C++ 开发一样,请不要担心。它不像 #include
预处理器指令那样工作(即它实际上没有在您的文件中包含 unittest
模块的源代码)。
如果您担心导入 unittest
的次数太多,请不要担心。 import
像 unittest
这样的模块到给定项目的许多不同模块中是非常常见的。
Or am I worried about nothing?
是的。需要的时候就import unittest
,省心!
HTH.
我已经使用了很多 python unittest 并且有一个装饰器方法可以用来有条件地跳过这样的测试:
import unittest
class TestStringMethods(unittest.TestCase):
@unittest.skipIf(1 == 1, 'Skipped because 1 does indeed equal 1')
def test_upper(self):
self.assertEqual('foo'.upper(), 'FOO')
虽然我想向 unittest.TestCase class 添加一些功能,所以我对其进行了子class编辑以开始添加我自己的自定义代码:
import unittest
class CustomTestCase(unittest.TestCase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs) # Just use whatever is in TestCase's init + our stuff
self.foo = 'foo' # our stuff
self.bar = 'bar'
def mymethod(self, param1, param2): # Some custom method I wanted to make for these custom test cases
pass
要继续使用 @unittest.skipIf
,我一直将 import unittest
放在我的任何 CustomTestCase
测试文件的顶部,但我想知道这是否是正确的处理方式。我进口的东西是否超过了我的需要?还是我什么都不担心?
您已经子类化的事实与您的要求无关。一般来说,子类导入或使用它们的超类是没有问题的:事实上,它们必须在定义它们时导入它们的超类。这就是问题所在(超类不应该知道它的子类)。
To continue using @unittest.skipIf I have been sticking import unittest at the top of any of my CustomTestCase test files, but I wonder if thats the correct way to be doing things. Am I importing more than I need?
如果你想使用 unittest
模块的任何属性(包括 skipIf
装饰器),那么你必须将它导入到相关模块中。没有比这更复杂的了。
如果您担心 header 守卫之类的东西,就像您需要 C/C++ 开发一样,请不要担心。它不像 #include
预处理器指令那样工作(即它实际上没有在您的文件中包含 unittest
模块的源代码)。
如果您担心导入 unittest
的次数太多,请不要担心。 import
像 unittest
这样的模块到给定项目的许多不同模块中是非常常见的。
Or am I worried about nothing?
是的。需要的时候就import unittest
,省心!
HTH.