Last active
May 30, 2018 11:38
-
-
Save messa/0d5942fed052966d6352376ef01f0de3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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