Skip to content

Instantly share code, notes, and snippets.

@messa
Last active May 30, 2018 11:38
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 messa/0d5942fed052966d6352376ef01f0de3 to your computer and use it in GitHub Desktop.
Save messa/0d5942fed052966d6352376ef01f0de3 to your computer and use it in GitHub Desktop.
# my_app/container.py
from .clients import ShopifyClient
from .model import Model, connect_db
from .util import System
factories = {
'system': lambda cx: System(), # obsahuje wrapper okolo datetime a tak, pro snadnější mockování v testech
'model': lambda cx: Model(db=connect_db(cx['conf'].db), system=cx['system']),
'shopify_client': lambda cx: ShopifyClient(cx['conf'].shopify),
}
class Container:
'''
Tento objekt má úmyslně stejné API jako dict, aby se místo něj dal
v testech použít prostě dict.
'''
def __init__(self, conf):
self._items = {
'conf': conf,
}
def __getitem__(self, key):
if key not in self._items:
self._items[key] = factories[key](self)
return self._items[key]
# my_app/main.py
from .container import Container
def main():
p = argparse.ArgumentParser()
p.add_argument('conf')
args = p.parse_args()
container = Container(Configuration(args.conf))
run_something(container)
def run_something(container):
model = container['model']
model.delej_neco()
# tests/test_something.py
def test_something(container, db):
run_something(container)
assert db['neco'].count() == 42
@fixture
def container(system, model, shopify_client):
# no a tady můžu jako DI kontejner použít prostě dict
return {
'system': system, # obsahuje wrapper okolo datetime a tak, pro snadnější mockování v testech
'model': model,
'shopify_client': shopify_client,
}
@fixture
def system():
return MockSDeterministickymDatumemRandomemATak()
@fixture
def model(test_db, system):
return Model(test_db, system)
@fixture
def shopify_client():
return ShopifyAPIMock()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment