fj123x fj123x - 21 days ago 5x
Python Question

how can i test an abstract method in python 2.6

I have an abstract class:

import abc

class Hello(object):
__metaclass__ = abc.ABCMeta

def add(self, foo):

def remove(self, foo):

I'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 method

Extra question: anybody knows how can i assert the message exception in python 2.6? (you can't use the
for raise assertions.)

How can i test this abstract methods for get the 100% of code coverage?


What about creating a doc string of the abstract method instead of using pass as mentioned here, ? It can also be used to give some information about what the method is supposed to do in the sub classes.,

from abc import ABCMeta, abstractmethod                                            

class A(object):                                                                   
    __metaclass__ = ABCMeta                                                        

    def some_method(self):                                                         
        "This method should ..."                                                   

class B(A):                                                                        
    def some_method(self):                                                         
        return 1,

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