Skip to content

Instantly share code, notes, and snippets.

@goulu
Last active May 16, 2019 18:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save goulu/6eea0db5119c9fb9a07c7e428570fb8c to your computer and use it in GitHub Desktop.
Save goulu/6eea0db5119c9fb9a07c7e428570fb8c to your computer and use it in GitHub Desktop.
very (un)useful class for test driven development: objects of the PassAll class will pass any test you can think of :-D
import inspect
import re
regexes=[
r"assert\((.*)(==|!=|>|<)(.*)\)",
#TODO: expand for test frameworks like unittest, nose ...
]
def _make_true(op,value):
# returns a value that satisfies comparizon
if op in ['==','<=','>='] :
return value
elif op=='>':
try:
return value+1
except:
return value+['x']
else:
try:
return value-1
except:
return value[:-1]
class PassAll:
# objects of this class pass any tests :-)
def __init__(self,*args,**kwargs):
# universal constructor
pass
def __getattr__(self,name):
# for any attribute, return something that will satify a test in the calling code
code=inspect.stack()[1].code_context[0]
for pattern in regexes:
m=re.search(pattern,code)
if m:
break
if m is None:
return True #try...
value=_make_true(m.group(2),eval(m.group(3)))
if '(' in m.group(1) :
# attr is supposed to be a function, so return one accepting any parameter and returning the expected result
def f(*args,**kwargs) : return value
return f
else:
return value
# test it. I mean... see how it works:
import math
p=PassAll(1,2,l=[3,4],s="string")
assert(p.anything=='result')
assert(p.notequal!=('a','tuple'))
assert(p.positive>0)
assert(p.negative<0)
assert(p.sinus(1)==math.sin(1))
print("all tests passed!")
@goulu
Copy link
Author

goulu commented May 16, 2019

A stupid challenge I posed to myself while attending a Test Driven Development Course :-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment