def test_autoparams_on_classmethod_ob_object(self): class Test: # note inject must be *before* classmethod! @classmethod @inject.autoparams() def func(cls, a=1, b: 'B' = None, *, c: 'C' = None): return cls, a, b, c def config(binder): binder.bind('B', 2) binder.bind('C', 3) inject.configure(config) test = Test assert test.func() == (Test, 1, 2, 3) assert test.func(10) == (Test, 10, 2, 3) assert test.func(10, 20) == (Test, 10, 20, 3) assert test.func(10, 20, c=30) == (Test, 10, 20, 30) assert test.func(a='a') == (Test, 'a', 2, 3) assert test.func(b='b') == (Test, 1, 'b', 3) assert test.func(c='c') == (Test, 1, 2, 'c') assert test.func(a=10, c=30) == (Test, 10, 2, 30) assert test.func(c=30, b=20, a=10) == (Test, 10, 20, 30) assert test.func(10, b=20) == (Test, 10, 20, 3)
def test(self): class Config(object): def __init__(self, greeting): self.greeting = greeting class Cache(object): config = inject.attr(Config) def load_greeting(self): return self.config.greeting class User(object): cache = inject.attr(Cache) def __init__(self, name): self.name = name def greet(self): return '%s, %s' % (self.cache.load_greeting(), self.name) def config(binder): binder.bind(Config, Config('Hello')) inject.configure(config) user = User('John Doe') greeting = user.greet() assert greeting == 'Hello, John Doe'
def test_request_response_no_such_command(): #----------------------------------- # preparations #----------------------------------- # cleanup a bit inject.clear() def my_config(binder): binder.bind('settings', None) inject.configure(my_config) log.startLogging(sys.stdout) server = Server(port=9996, no_ssl=True) server.bind() client = Client(port=9996, no_ssl=True) yield client.connect() with pytest.raises(ApiError): yield client.call_sync('hoho') client.shutdown() server.shutdown()
def test_request_response(): #----------------------------------- # preparations #----------------------------------- # cleanup a bit inject.clear() def my_config(binder): binder.bind('settings', None) inject.configure(my_config) # log.startLogging(sys.stdout) server = Server(port=9998, no_ssl=True) server.bind() client = Client(port=9998, no_ssl=True) yield client.connect() response = yield client.call_sync('ping') assert response == 'pong' client.shutdown() server.shutdown()
def mqtt_bridge_node(): # init node rospy.init_node('mqtt_bridge_node') # load parameters topic_params_string = rospy.get_param("~topic_params", {}) topic_params = json.loads(topic_params_string) host = topic_params["host"] port = topic_params["port"] keepalive = topic_params["keepalive"] protocol = topic_params["protocol"] mqtt_params = { "client": { "protocol": protocol }, "connection": { "host": host, "port": port, "keepalive": keepalive } } conn_params = mqtt_params["connection"] mqtt_private_path = "device/001" bridge_params = topic_params["bridge"] # create mqtt client mqtt_client_factory_name = rospy.get_param( "~mqtt_client_factory", ".mqtt_client:default_mqtt_client_factory") mqtt_client_factory = lookup_object(mqtt_client_factory_name) mqtt_client = mqtt_client_factory(mqtt_params) # load serializer and deserializer serializer = "json:dumps" deserializer = "json:loads" # dependency injection config = create_config(mqtt_client, serializer, deserializer, mqtt_private_path) inject.configure(config) # configure and connect to MQTT broker mqtt_client.on_connect = _on_connect mqtt_client.on_disconnect = _on_disconnect mqtt_client.connect(**conn_params) # configure bridges bridges = [] for bridge_args in bridge_params: bridges.append(create_bridge(**bridge_args)) # start MQTT loop mqtt_client.loop_start() # register shutdown callback and spin rospy.on_shutdown(mqtt_client.disconnect) rospy.on_shutdown(mqtt_client.loop_stop) rospy.spin()
def test_param_by_class(self): @inject.param('val', int) def test_func(val): return val inject.configure(lambda binder: binder.bind(int, 123)) assert test_func() == 123
def test_is_configured__should_return_true_when_injector_present(self): assert inject.is_configured() is False inject.configure() assert inject.is_configured() is True inject.clear() assert inject.is_configured() is False
def main(): params = { "redis_host": "localhost", "redis_port": "6379", "redis_db": "2", } inject.configure(create_config(params)) register_readmodel_updater()
def configure_container(fast_admin): """Configure inject function.""" def di_config(binder: inject.Binder) -> None: # noqa: WPS430 """Add container bindings.""" binder.bind('fast_admin', fast_admin) binder.bind('pg_connection_provider', configure_pg_connection) inject.configure(di_config)
def test_attr_on_dataclass_class_var_works(self): @dataclass class MyClass: field: ClassVar[int] = inject.attr_dc(int) inject.configure(lambda binder: binder.bind(int, 123)) assert MyClass().field == 123 assert MyClass.field == 123
def test_async_param(self): @inject.param('val') async def test_func(val): return val inject.configure(lambda binder: binder.bind('val', 123)) assert inspect.iscoroutinefunction(test_func) assert self.run_async(test_func()) == 123
def test_autoparams_by_class(self): @inject.autoparams() def test_func(val: int = None): return val inject.configure(lambda binder: binder.bind(int, 123)) assert test_func() == 123 assert test_func(val=321) == 321
def test_param_by_name(self): @inject.param('val') def test_func(val=None): return val inject.configure(lambda binder: binder.bind('val', 123)) assert test_func() == 123 assert test_func(val=321) == 321
def build_container(**kwargs): authenticator = _construct_authenticator(kwargs['token']) def _inject_config(binder): binder.bind(MyCloudAuthenticator, authenticator) binder.bind(MyCloudRequestExecutor, MyCloudRequestExecutor(authenticator)) inject.configure(_inject_config)
def init_injection(output_path='', format_type='', is_cli=False, is_cache=False): global __output_path, __format, __is_cli, __is_cache __output_path = output_path __format = format_type __is_cli = is_cli __is_cache = is_cache inject.configure(config)
def test_params(self): @inject.params(val=int) def test_func(val): return val inject.configure(lambda binder: binder.bind(int, 123)) assert test_func() == 123 assert test_func(321) == 321 assert test_func(val=42) == 42
def test_class_attr(self): class MyClass(object): field = inject.attr(int) inject.configure(lambda binder: binder.bind(int, 123)) value0 = MyClass.field value1 = MyClass.field assert value0 == 123 assert value1 == 123
def test_autoparams_omits_return_type(self): @inject.autoparams() def test_func(a: str) -> int: return a def config(binder): binder.bind(str, 'bazinga') inject.configure(config) assert test_func() == 'bazinga'
def test_async_params(self): @inject.params(val=int) async def test_func(val): return val inject.configure(lambda binder: binder.bind(int, 123)) assert inspect.iscoroutinefunction(test_func) assert self.run_async(test_func()) == 123 assert self.run_async(test_func(321)) == 321 assert self.run_async(test_func(val=42)) == 42
def configure_environment(self): def confiigurator(binder): binder.bind('Version', os.getenv('VERSION')) binder.bind('Logger', logging.getLogger()) binder.bind('Router', Router()) binder.bind_to_provider( 'Client', lambda: getattr(threading.local(), 'client', None)) if not Configurator.__environment_configured: inject.configure(confiigurator) Configurator.__environment_configured = True
def post_setup(cls): super(Common, cls).post_setup() def configure_feature_services(binder): for feature in cls.FEATURES: feature.append_services(binder) inject.configure(configure_feature_services) for feature in cls.FEATURES: feature.on_startup()
def test_attr_dc(self): @dataclass class MyClass(object): field = inject.attr_dc(int) inject.configure(lambda binder: binder.bind(int, 123)) my = MyClass() value0 = my.field value1 = my.field assert value0 == 123 assert value1 == 123
def configure_inject(c: MatchMakerConfig) -> None: def config(binder: inject.Binder) -> None: binder.bind(PlayerCacheInterface, DynamoPlayerCacheAdapter(c.player_table)) binder.bind(GameCacheInterface, DynamoGameCacheAdapter(c.game_table)) binder.bind(GameQueueInterface, SQSGameQueueAdapter(c.match_queue_name)) inject.configure(config)
def create_app(inject_config=app_config): """Create app.""" app = Flask(__name__) app.json_encoder = CustomJSONEncoder inject.configure(inject_config) with app.app_context(): from . import routes app.register_error_handler(HTTPException, handle_http_exception) app.register_blueprint(routes.api) return app
def test_autoparams_only_selected(self): @inject.autoparams('a', 'c') def test_func(a: 'A', b: 'B', *, c: 'C'): return a, b, c def config(binder): binder.bind('A', 1) binder.bind('B', 2) binder.bind('C', 3) inject.configure(config) self.assertRaises(TypeError, test_func) self.assertRaises(TypeError, test_func, a=1, c=3)
def do_inject(config): logger.Logger.debug('injecting') mysql_conf = {'user': config['mysql.user'], 'passwd': config['mysql.password'], 'db': config['mysql.db'], 'host': config['mysql.host'], 'conv': {}} #conv is added to return all the values as strings which is good for google sql_db = MySQLdb.connect(**mysql_conf) def my_config(binder): binder.bind(SQLDb, sql_db) inject.configure(my_config)
def main(): try: inject.configure(di_configuration) p = create_parser() parsed = p.parse_args(sys.argv[1:]) setup_logging(parsed.config[0]) check_parsed_command(parsed) parsed.func(parsed) except Exception as e: logging.error(str(e)) logging.debug('Exiting with FAILED result', exc_info=True) exit(1)
def configure_injection(): def configuration(binder: inject.Binder): env = os.environ.get('ENV') or "dev" if env == "dev": binder.bind(TicketRepository, InMemoryTicketRepository()) binder.bind(AccountRepository, InMemoryAccountRepository()) elif env == "prod": pass elif env == "test": pass else: raise ValueError("Invalid env") inject.configure(configuration)
def main(): _setup_logging() inject.configure(di_configuration) try: raw_ctx = parse_opts(args=sys.argv[1:], standalone_mode=False, obj={}) if type(raw_ctx) is not dict: exit(1) app_context = raw_ctx['result'] pub = app_context.publisher offset = pub.publish(app_context.type, app_context.payload) logging.info('Written to epoch: %s', offset) except Exception: logging.exception('Exiting with failure')
async def bootstrap(env): configure_logging(env) dsn = "postgresql://{user}:{password}@{host}:{port}/{dbname}".format( **config.get_db_config(env)) sa = orm.SQLAlchemy(dsn) sa.configure_mappings() sa.create_all_tables() pool = await init_pg_pool(dsn) db = ConnectionManager(pool) binder_config = partial(configure_binder, pool, db) inject.configure(binder_config)
def do_inject(config): sugar_db = litesugarcrm.LiteSugarCRM(config['sugar.user'], config['sugar.password']) mysql_conf = {'user': config['mysql.user'], 'passwd': config['mysql.password'], 'db': config['mysql.db'], 'host': config['mysql.host'], 'charset': 'utf8'} sql_db = MySQLdb.connect(**mysql_conf) def my_config(binder): binder.bind(SugarDb, sugar_db) binder.bind(SQLDb, sql_db) inject.configure(my_config) Logger.info('Starting')
def inject_dependencies(Session: typing.Callable[[], orm.Session]): session = Session() def inject_config(binder: inject.Binder) -> None: # Queries binder.bind(queries.GettingRssPageQuery, orm_queries.ORMGettingRssPageQuery(session)) binder.bind(queries.GettingRssPagesQuery, orm_queries.ORMGettingRssPagesQuery(session)) # Repositories binder.bind(repositories.RssPageRepo, orm_repositories.RssPageRepo(session)) inject.configure(inject_config, bind_in_runtime=False)
def test_transfers(self): inject.configure(infura_config) inspector = BlockInspector() while True: block = inspector.get_next_block() if block is None: continue txs = import_block(block) for tx in txs: pprint(TransactionMapper.transaction_to_dict(tx)) break
def initialize(conf_file_name=None): """This function initializes whole TwitterSentimentAnalysis package It must be called before any use of TwitterSentimentAnalysis package Args: conf_file_name (string): A path to non default configuration file """ global __core_initialized if __core_initialized: return global configuration_file_path if conf_file_name is not None: configuration_file_path = os.path.join(base_dir, conf_file_name) inject.configure(__main_config) __tweepy_parse_json() __core_initialized = True
def test_autoparams_with_defaults(self): @inject.autoparams() def test_func(a=1, b: 'B' = None, *, c: 'C' = 300): return a, b, c def config(binder): binder.bind('B', 2) binder.bind('C', 3) inject.configure(config) assert test_func() == (1, 2, 3) assert test_func(10) == (10, 2, 3) assert test_func(10, 20) == (10, 20, 3) assert test_func(10, 20, c=30) == (10, 20, 30) assert test_func(a='a') == ('a', 2, 3) assert test_func(b='b') == (1, 'b', 3) assert test_func(c='c') == (1, 2, 'c') assert test_func(a=10, c=30) == (10, 2, 30) assert test_func(c=30, b=20, a=10) == (10, 20, 30) assert test_func(10, b=20) == (10, 20, 3)
def test_params_with_defaults(self): # note the inject overrides default parameters @inject.params(b='B', c='C') def test_func(a=1, b=None, c=300): return a, b, c def config(binder): binder.bind('B', 2) binder.bind('C', 3) inject.configure(config) assert test_func() == (1, 2, 3) assert test_func(10) == (10, 2, 3) assert test_func(10, 20) == (10, 20, 3) assert test_func(10, 20, 30) == (10, 20, 30) assert test_func(a='a') == ('a', 2, 3) assert test_func(b='b') == (1, 'b', 3) assert test_func(c='c') == (1, 2, 'c') assert test_func(a=10, c=30) == (10, 2, 30) assert test_func(c=30, b=20, a=10) == (10, 20, 30) assert test_func(10, b=20) == (10, 20, 3)
def test_autoparams_multi(self): @inject.autoparams() def test_func(a: 'A', b: 'B', *, c: 'C'): return a, b, c def config(binder): binder.bind('A', 1) binder.bind('B', 2) binder.bind('C', 3) inject.configure(config) assert test_func() == (1, 2, 3) assert test_func(10) == (10, 2, 3) assert test_func(10, 20) == (10, 20, 3) assert test_func(10, 20, c=30) == (10, 20, 30) assert test_func(a='a') == ('a', 2, 3) assert test_func(b='b') == (1, 'b', 3) assert test_func(c='c') == (1, 2, 'c') assert test_func(a=10, c=30) == (10, 2, 30) assert test_func(c=30, b=20, a=10) == (10, 20, 30) assert test_func(10, b=20) == (10, 20, 3)
def do_inject(): """ :return: Nothing """ mysql_conf = {'user': config['mysql.user'], 'passwd': config['mysql.password'], 'db': config['mysql.db'], 'host': config['mysql.host'], 'charset': 'utf8'} sql_db = MySQLdb.connect(**mysql_conf) jira_opts = {'server': config['jira.url']} jira_auth = (config['jira.user'], config['jira.password']) jira = JIRA(options=jira_opts, basic_auth=jira_auth) # injecting mysql and jira def my_config(binder): binder.bind(SQLDb, sql_db) binder.bind(Jira, jira) Logger.debug("Injection complete") inject.configure(my_config)
def test_autoparams_on_method(self): class Test: @inject.autoparams() def func(self, a=1, b: 'B' = None, *, c: 'C' = None): return self, a, b, c def config(binder): binder.bind('B', 2) binder.bind('C', 3) inject.configure(config) test = Test() assert test.func() == (test, 1, 2, 3) assert test.func(10) == (test, 10, 2, 3) assert test.func(10, 20) == (test, 10, 20, 3) assert test.func(10, 20, c=30) == (test, 10, 20, 30) assert test.func(a='a') == (test, 'a', 2, 3) assert test.func(b='b') == (test, 1, 'b', 3) assert test.func(c='c') == (test, 1, 2, 'c') assert test.func(a=10, c=30) == (test, 10, 2, 30) assert test.func(c=30, b=20, a=10) == (test, 10, 20, 30) assert test.func(10, b=20) == (test, 10, 20, 3)
def test_params_on_classmethod(self): class Test: # note inject must be *before* classmethod! @classmethod @inject.params(b='B', c='C') def func(cls, a=1, b=None, c=None): return cls, a, b, c def config(binder): binder.bind('B', 2) binder.bind('C', 3) inject.configure(config) assert Test.func() == (Test, 1, 2, 3) assert Test.func(10) == (Test, 10, 2, 3) assert Test.func(10, 20) == (Test, 10, 20, 3) assert Test.func(10, 20, 30) == (Test, 10, 20, 30) assert Test.func(a='a') == (Test, 'a', 2, 3) assert Test.func(b='b') == (Test, 1, 'b', 3) assert Test.func(c='c') == (Test, 1, 2, 'c') assert Test.func(a=10, c=30) == (Test, 10, 2, 30) assert Test.func(c=30, b=20, a=10) == (Test, 10, 20, 30) assert Test.func(10, b=20) == (Test, 10, 20, 3)
def test_configure__should_create_injector(self): injector0 = inject.configure() injector1 = inject.get_injector() assert injector0 assert injector0 is injector1
def test_configure__already_configured(self): inject.configure() self.assertRaisesRegexp(InjectorException, 'Injector is already configured', inject.configure)
# -*- coding: utf-8 -*- ''' Se conecta al router wamp y hace correr el Wamp de Users ''' import inject inject.configure() if __name__ == '__main__': import sys import logging sys.path.insert(0, '../python') logging.basicConfig(level=logging.DEBUG) logging.getLogger().setLevel(logging.DEBUG) from autobahn.asyncio.wamp import ApplicationRunner from actions.systems.tutors.tutors import TutorsWamp from model.registry import Registry reg = inject.instance(Registry) registry = reg.getRegistry('wamp') url = registry.get('url') realm = registry.get('realm') debug = registry.get('debug') runner = ApplicationRunner(url=url, realm=realm) runner.run(TutorsWamp)
if __name__ == '__main__': ## Send args to listener and close from piony.system.client import Client client = Client() client.connect() if client.socket.waitForConnected(2000): # DEV: send also [0] element -- to use client pwd for pathes in cmdline client.send(sys.argv[1:]) client.socket.close() else: from signal import signal, SIGINT, SIG_DFL ## Close on 'Ctrl-C' system signal. ## WARNING: No cleanup possible (can't implement because of Qt). signal(SIGINT, SIG_DFL) import inject from piony.gstate import GState def config(binder): binder.bind(GState, GState(sys.argv)) inject.configure(config) from PyQt5.QtWidgets import QApplication from piony.main import MainApplication app = QApplication(sys.argv) main = MainApplication() sys.exit(app.exec_())
def test_clear_and_configure(self): injector0 = inject.configure() injector1 = inject.clear_and_configure() # No exception. assert injector0 assert injector1 assert injector1 is not injector0
def test_instance(self): inject.configure(lambda binder: binder.bind(int, 123)) instance = inject.instance(int) assert instance == 123
from model.config import Config #logging.getLogger().setLevel(logging.INFO) from autobahn.asyncio.wamp import ApplicationSession from asyncio import coroutine ''' python3 findByUserId.py userId python3 findByUserId.py d44e92c1-d277-4a45-81dc-a72a76f6ef8d ''' def config_injector(binder): binder.bind(Config,Config('server-config.cfg')) inject.configure(config_injector) config = inject.instance(Config) class WampMain(ApplicationSession): def __init__(self,config=None): #logging.debug('instanciando WampMain') ApplicationSession.__init__(self, config) @coroutine def onJoin(self, details): if len(sys.argv) < 3: sys.exit("Error de parámetros")
def test_configure__should_add_bindings(self): injector = inject.configure(lambda binder: binder.bind(int, 123)) instance = injector.get_instance(int) assert instance == 123