我如何在python 2.6中测试抽象方法 [英] how can i test an abstract method in python 2.6
问题描述
我有一个抽象类:
import abc
class Hello(object):
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def add(self, foo):
pass
@abc.abstractmethod
def remove(self, foo):
pass
I我正在使用abc做抽象方法,所以,当我这样做时:
I'm using abc for do abstract methods, so, when i do:
hello = Hello()
并引发此错误: TypeError:无法实例化抽象类使用抽象方法添加,删除Hello
所以我可以使用以下方式测试此类型错误:
So I can test this type error with:
self.assertRaises(Exception, Hello) # but this only test the constructor and i can't get the 100% of code coverage. I need call the add method and the remove method
其他问题:任何人都知道如何断言消息python 2.6中的异常? (您不能使用 with:
来提出断言。)
Extra question: anybody knows how can i assert the message exception in python 2.6? (you can't use the with:
for raise assertions.)
我如何测试此抽象方法以用于获得100%的代码覆盖率?
How can i test this abstract methods for get the 100% of code coverage?
推荐答案
如何创建抽象方法的文档字符串而不是使用 pass
如此处所述, https://stackoverflow.com/a/19275908/469992 吗?它也可以用来提供有关该方法在子类中应该做什么的一些信息。
What about creating a doc string of the abstract method instead of using pass
as mentioned here, https://stackoverflow.com/a/19275908/469992 ? It can also be used to give some information about what the method is supposed to do in the sub classes.
abstract.py,
abstract.py,
from abc import ABCMeta, abstractmethod
class A(object):
__metaclass__ = ABCMeta
@abstractmethod
def some_method(self):
"This method should ..."
class B(A):
def some_method(self):
return 1
test_abstract.py,
test_abstract.py,
import unittest
import abstract
class TestB(unittest.TestCase):
def test(self):
self.assertEqual(abstract.B().some_method(), 1)
然后,使用python 2.6.8, nosetests --with -xcoverage
输出,
Then, using python 2.6.8, nosetests --with-xcoverage
outputs,
.
Name Stmts Miss Cover Missing
----------------------------------------
abstract 7 0 100%
----------------------------------------------------------------------
Ran 1 test in 0.004s
这篇关于我如何在python 2.6中测试抽象方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!