我有一个抽象类:
import abc class Hello(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def add(self, foo): pass @abc.abstractmethod def remove(self, foo): pass我正在使用abc做抽象方法,所以,当我这样做时:
hello = Hello()并引发此错误: TypeError: Can't instantiate abstract class Hello with abstract methods add, remove
所以我可以测试这种类型错误:
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: for raise assertions。)
如何测试这种抽象方法以获得100%的代码覆盖率?
I have an abstract class:
import abc class Hello(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def add(self, foo): pass @abc.abstractmethod def remove(self, foo): passI'm using abc for do abstract methods, so, when i do:
hello = Hello()and this error is raised: TypeError: Can't instantiate abstract class Hello with abstract methods add, remove
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 methodExtra question: anybody knows how can i assert the message exception in python 2.6? (you can't use the with: for raise assertions.)
How can i test this abstract methods for get the 100% of code coverage?
最满意答案
如何创建抽象方法的文档字符串而不是使用这里提到的pass , https://stackoverflow.com/a/19275908/469992 ? 它还可以用于提供有关该方法在子类中应该执行的操作的一些信息。
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 1test_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输出,
. Name Stmts Miss Cover Missing ---------------------------------------- abstract 7 0 100% ---------------------------------------------------------------------- Ran 1 test in 0.004sWhat 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,
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 1test_abstract.py,
import unittest import abstract class TestB(unittest.TestCase): def test(self): self.assertEqual(abstract.B().some_method(), 1)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更多推荐
发布评论