vendredi 1 juillet 2016

How to test child class methods only without instantiating base class in Python?

I am a newbie of Python, I need to test the child class methods without initializing a base class instance because in the base class , there are lots of dependencies on network and some other components, my child class methods are standalone.

I tried to create a new child class by removing the base class methods from the child class,but it can't work. Here are the codes.

def remove_base(child_cls, base_cls):
    allmembers = inspect.getmembers(child_cls, predicate=inspect.ismethod)
    allmembers_dict = dict(allmembers)
    hbasemembers = inspect.getmembers(base_cls, predicate=inspect.ismethod)
    hbase_dict = dict(hbasemembers)
    child_class_member = set(allmembers_dict.keys()) - set(hbase_dict.keys())
    new_dict = {}
    for key in allmembers_dict.keys():
        for child_member in child_class_member:
            if key == child_member:
                new_dict[key] = allmembers_dict[key]
    return new_dict

class A:
    def add(self, i):
        print i + 1

class B(A):
    def sub(self, i):
        print i - 1

newB = type("newB", (object, ), remove_base(B, A))
b = newB()
b.sub(5)

The error message is :

TypeError: unbound method sub() must be called with B instance as first argument (got int instance instead)

I think the way of removing base class methods may be wrong. How to handle this problem?

Aucun commentaire:

Enregistrer un commentaire