Reputation: 2031
So I am currently trying to develop a test framework in Python and I have developed a bunch of API methods to be used for this. This framework is to be used by number of different people with different experience and knowledge about the "system under test", so it has been decided that it would be useful to have both a simple API and a more "native" API available. The API methods are all interfacing the "System under test" using an ip-session and this session have to be the same during the whole test session. So far so good. However I have found that it might be useful to use both "simple API methods" and "native API methods" in the same test and they must somehow share this ip-session. Before this I made something like this:
nativeAPI(object):
def __init__(self):
self.session = createSession(password, systemip)
def someAPImethod(self):
return dosomeTestStuff(self.session)
simpleAPI(object):
def __init__(self):
self.session = createSession(password, systemip)
def someAPImethod(self):
return dosomeTestStuff(self.session)
#Test code written by a person using the framework could look something like this.
testMethods = nativeAPI()
testMethods.someAPImethod()
But now I would rather like to have something where the "testers" could use a syntax similar to this:
testMethods = createSession()
testMethods.nativeAPI.someAPIMethod()
I tried to do this using a "NativeAPI" class within the "createSession" class but ended up have problems with errors like : "unbound method must be called with instance as first argument". So I ask you: How am I supposed to handle this? What is a good design pattern in Python?
Upvotes: 0
Views: 64
Reputation: 1125308
I would make simpleAPI
a subclass of nativeAPI
.
That way you can always still use the nativeAPI
methods even when you have a simpleAPI
instance. Even better, simpleAPI
methods could be implemented in terms of the nativeAPI
, simplifying your code:
nativeAPI(object):
def __init__(self):
self.session = createSession(password, systemip)
def someAPImethod(self):
return dosomeTestStuff(self.session)
simpleAPI(nativeAPI):
def someSimpleAPImethod(self):
result = self.someAPImethod()
result.doSomethingToSimplify()
return result
Upvotes: 0
Reputation: 44623
Just create a simple object that contains a simple nativeAPI
instance in createSession
and return that:
class Wrapper(object):
def __init__(self, nativeAPI):
self.nativeAPI = nativeAPI
def createSession():
nativeAPI = ...
return Wrapper(nativeAPI)
Upvotes: 2