fj1*_*23x 3 python abstract-class unit-testing exception 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
Run Code Online (Sandbox Code Playgroud)
我正在使用abc做抽象方法,所以,当我这样做时:
hello = Hello()
Run Code Online (Sandbox Code Playgroud)
并引发此错误: 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
Run Code Online (Sandbox Code Playgroud)
额外的问题:任何人都知道如何在python 2.6中断言消息异常?(你不能使用with:for raise断言.)
如何测试这种抽象方法以获得100%的代码覆盖率?
如何创建抽象方法的文档字符串而不是使用pass这里提到的,/sf/answers/1349313591/?它还可以用于提供有关该方法在子类中应该执行的操作的一些信息.
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
Run Code Online (Sandbox Code Playgroud)
test_abstract.py,
import unittest
import abstract
class TestB(unittest.TestCase):
def test(self):
self.assertEqual(abstract.B().some_method(), 1)
Run Code Online (Sandbox Code Playgroud)
然后,使用python 2.6.8,nosetests --with-xcoverage输出,
.
Name Stmts Miss Cover Missing
----------------------------------------
abstract 7 0 100%
----------------------------------------------------------------------
Ran 1 test in 0.004s
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1699 次 |
| 最近记录: |