Monday, 15 July 2013

unit testing - How to structure Python module to make it both extensible and testible? -



unit testing - How to structure Python module to make it both extensible and testible? -

i'm writing couple python modules used in own application handling crypto-currencies. many of functions homecoming based upon given string:

def dostuff(coin, value): if coin == 'btc': homecoming dosomethingwithbtc(value, 'some_string') elif coin == 'ltc': homecoming somemodule.doltc(value, 1) elif coin == 'doge': homecoming othermod.doge(value, 52, true) else: homecoming 'some terrible error occurred.'

as can see, key 1 of predefined set of strings (crypto-currencies). @ moment there 3 in set, want extend number in future. i've got dozen more functions in module, @ moment take same 3 strings, when add together one, functions need extended.

i've got unit tests module in want test whether functions able take (currently 3) items set key. calling them, of them stuff can't test in unit tests. 1 of them makes (bitcoin) payments example.

i thought of using inspect module source code of functions , see if contains line containing key == 'x', x each item pre-defined set. although guess work, doesn't sound pythonic me.

does know how can create these functions such can test whether able handle currencies in pre-defined set without calling functions? tips welcome!

using if-cascades not pythonic either. if have many methods each key, utilize classes , access them via dictionary:

class btc(object): def do_stuff(self, value): homecoming dosomethingwithbtc(value, 'some_string') class ltc(object): ... currencie_instances = { 'btc': btc(), 'ltc': ltc(), } def do_stuff(key, value): homecoming currencie_instances[key].do_stuff(value)

that way, don't have alter stuff-methods, 1 dictionary.

python unit-testing module structure

No comments:

Post a Comment