Skip to content

Instantly share code, notes, and snippets.

@MichaelBlume
Last active December 25, 2015 11:19
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 MichaelBlume/6968441 to your computer and use it in GitHub Desktop.
Save MichaelBlume/6968441 to your computer and use it in GitHub Desktop.
obj: reify for python
# Writing some unit tests in Python, I found myself homesick for Clojure's `reify`.
from functools import partial
class Blank(object): pass
def obj(*fs):
o = Blank()
for f in fs:
setattr(o, f.func_name, partial(f, o))
return o
#Use it like this:
from nose.tools import eq_
import json
def cut_suffix_strict(s, suffix):
ok_(s.endswith(suffix), '%s does not end with %s' % (s, suffix))
return s[:-len(suffix)]
def fake_conn(bucket_name, folder_name, mappings):
def get_bucket(self, passed_bucket_name):
eq_(bucket_name, passed_bucket_name)
def get_key(self, path):
passed_folder, full_key = path.split('/')
eq_(passed_folder, folder_name)
key = cut_suffix_strict(full_key, '.json')
def get_contents_as_string(self):
return json.dumps(mappings[key])
return obj(get_contents_as_string)
return obj(get_key)
return obj(get_bucket)
# Calling fake_conn() gets you an object mocking boto's S3Connection class.
# You can call get_bucket() on it to get a fake bucket, call get_key() on that to get a fake key, etc.
# Unlike reify, you don't pass in an interface/protocol -- none of those in Python.
# Like reify, your functions should take a self param.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment