Example #1
0
    def test_givenProviderFunctionWithReturnType_whenInitializingServiceLocator_thenFunctionIsBoundByReturnType(
            self):
        binder = ProviderBinder("", Registry())

        binder.bind(self.serviceLocator)

        self.assertEqual((SomeClass, provider_function), self.result[0])
Example #2
0
class RegistryTest(unittest.TestCase):
    def setUp(self):
        self.registry = Registry()

    def test_givenNeverRegisteredAnnotation_whenCheckingIsAnnotated_thenReturnFalse(
            self):
        is_annotated = self.registry.is_annotated(None, AN_ANNOTATION)

        self.assertFalse(is_annotated)
Example #3
0
    def test_givenProviderFunctionWithoutAReturnType_whenInitializingProviderBinder_thenThrowUndefinedReturnProviderFunctionException(
            self):
        @Provider
        def provider_function_without_a_defined_return_type():
            return SomeClass()

        binder = ProviderBinder("", Registry())

        with self.assertRaises(UndefinedReturnProviderFunction):
            binder.bind(self.serviceLocator)
    def setUp(self):
        self.routing_table = TreeRoutingTable()
        self.routing_table.register_route(GET, PATH, RESOURCE_CLASS,
                                          ROUTE_METHOD)
        self.route_handler_factory = RouteHandlerFactory(
            ServiceLocator(), Deserializer(Registry()),
            [RoutingRule("/", self.routing_table)],
            CorsRequestHandlerFactory([CorsRule("/", {})]))

        self.request_builder = RequestBuilder().method("GET").path(PATH)
class ParametrizedAnnotationTest(unittest.TestCase):
    def setUp(self):
        self.registry = Registry()

    def test_whenUsingParametrizedAnnotation_thenWrappedObjectsAreSavedInTheRegistry(
            self):
        wrapped_function = self.registry.get_annotated_in_package(
            myAnnotation, "")[0].registered

        self.assertEqual(some_wrapped_function, wrapped_function)

    def test_whenUsingParametrizedAnnotation_thenParametersAreStoredInTheRegistration(
            self):
        registration = self.registry.get_annotated_in_package(
            myAnnotation, "")[0]

        self.assertEqual(A_MESSAGE, registration.arguments['message'])
        self.assertFalse("value" in registration.arguments)

    def test_givenImplicitParameterName_whenUsingParametrizedAnnotation_thenParameterIsSavedAsTheDeclaredParameterName(
            self):
        registration = self.registry.get_annotated_in_package(
            implicit_parameter_annotation, "")[0]

        self.assertEqual(A_MESSAGE, registration.arguments['path'])

    def test_givenKeywordOnlyArguments_whenUsingParametrizedAnnotation_thenParametersAreSavedInTheRegistration(
            self):
        registration = self.registry.get_annotated_in_package(
            multipleParameterAnnotation, "")[0]

        self.assertEqual(A_MESSAGE, registration.arguments['message'])
        self.assertEqual(A_ROUTE, registration.arguments['route'])

    def test_givenMissingParameters_whenUsingOptionalArguments_thenPassNoneInstead(
            self):
        registration = self.registry.get_annotated_in_package(
            annotationWithOptionalParameters, "")[0]

        self.assertEqual(A_MESSAGE,
                         registration.arguments['mandatory_parameter'])
        self.assertIsNone(registration.arguments['optional_parameter'])
 def setUp(self):
     self.serviceLocator = ServiceLocator()
     self.serviceLocator.bind(ResourceClass, ResourceClass)
     registry = Registry()
     self.routingTable = ReflectiveRoutingTable(
         registry, [Registration(ResourceClass, arguments={"value": PATH})])
     self.deserializer = Deserializer(registry)
     self.resource_invocator = TestIntegratedResourceInvoker(
         self.serviceLocator, self.routingTable, self.deserializer)
     self.request = Request('GET', PATH, {}, "", "")
     ResourceClass.has_been_called = False
Example #7
0
    def __init__(self, registry: Registry, resources: List[Registration]):
        super().__init__()
        for resource in resources:
            for primitive in http_methods:
                routable_functions = registry.get_annotated_in_package(primitive, resource.registered.__module__)
                sub_paths = registry.get_annotated_in_package(Path, resource.registered.__module__)

                for route_function in routable_functions:
                    route_sub_path = Stream(sub_paths).firstMatch(lambda r: r.registered == route_function.registered)
                    resource_path = resource.arguments['value']

                    if not route_sub_path.isPresent():
                        self.register_route(primitive, resource_path, resource.registered,
                                            route_function.registered)
                    else:
                        sub_path = route_sub_path.get().arguments['value']
                        path = resource_path + sub_path if \
                            resource_path.endswith('/') or sub_path.startswith('/') \
                            else resource_path + '/' + sub_path

                        self.register_route(primitive, path, resource.registered, route_function.registered)
    def __init__(self,
                 url_pattern: str,
                 registry: Registry,
                 root_package_name: str,
                 regex_pattern: str = None):
        registrations = registry.get_annotated_in_package(
            RequestFilter, root_package_name)

        super().__init__(
            url_pattern,
            Stream(registrations).map(lambda r: r.registered).toList(),
            regex_pattern)
Example #9
0
    def __init__(self, root_module=None, *, debug: bool = False,
                 context: Union[AbstractContext, Type[ProductionJivagoContext]] = None):
        self.registry = Registry()
        self.root_module = root_module

        if context is None:
            self.context = DebugJivagoContext(self.root_module, self.registry) if debug else ProductionJivagoContext(
                self.root_module, self.registry)
        elif isinstance(context, type):
            self.context = context(self.root_module, self.registry)
        else:
            self.context = context

        self.print_banner()
        self.__initialize_logger()

        self.LOGGER.info(f"Using {self.context.__class__.__name__} with root package {root_module}.")

        if self.root_module:
            self.LOGGER.info("Discovering annotated classes")
            self.__import_package_recursive(root_module)

        self.context.configure_service_locator()
        self.serviceLocator = self.context.service_locator()

        self.serviceLocator.bind(ApplicationProperties, self.__load_application_properties(self.context))
        self.serviceLocator.bind(SystemEnvironmentProperties, self.__load_system_environment_properties())

        self.LOGGER.info("Running PreInit hooks")
        self.call_startup_hook(PreInit)

        self.router = self.context.create_router_config().build(self.registry, self.serviceLocator)

        self.LOGGER.info("Running Init hooks")
        self.call_startup_hook(Init)

        self.LOGGER.info("Starting background workers")
        self.backgroundWorkers = Stream(self.get_annotated(BackgroundWorker)).map(
            lambda clazz: self.serviceLocator.get(clazz)).map(lambda worker: Thread(target=worker.run, daemon=True))
        Stream(self.backgroundWorkers).forEach(lambda thread: thread.start())

        task_schedule_initializer = TaskScheduleInitializer(self.registry, self.root_module_name)
        self.task_scheduler: TaskScheduler = self.serviceLocator.get(TaskScheduler)
        task_schedule_initializer.initialize_task_scheduler(self.task_scheduler)

        self.LOGGER.info("Running PostInit hooks")
        self.call_startup_hook(PostInit)

        signal.signal(signal.SIGTERM, self.cleanup)
        signal.signal(signal.SIGINT, self.cleanup)
    def _find_dispatchers(
            self, registry: Registry, root_package_name: str,
            service_locator: ServiceLocator) -> List[MessageDispatcher]:
        dispatchers = []
        registrations = registry.get_annotated_in_package(
            EventHandler, root_package_name)

        for registration in registrations:
            if registration.is_function_registration():
                dispatchers.append(
                    MessageDispatcherFunction(
                        registration.arguments[EVENT_NAME_PARAMETER],
                        registration.registered))

            elif registration.is_class_registration() and issubclass(
                    registration.registered, Runnable):
                dispatchers.append(
                    MessageDispatcherRunnable(
                        registration.arguments[EVENT_NAME_PARAMETER],
                        registration.registered, self.service_locator))

        for registration in registry.get_annotated_in_package(
                EventHandlerClass, root_package_name):
            registered_class = registration.registered

            for handler_function in registry.get_annotated_in_package(
                    EventHandler, registered_class.__module__):
                if self._is_function_defined_inside_class(
                        handler_function.registered, registered_class):
                    dispatchers.append(
                        JitMessageDispatcherClass(
                            handler_function.arguments[EVENT_NAME_PARAMETER],
                            registered_class, handler_function.registered,
                            service_locator))

        return dispatchers
    def test_givenPrefixedRule_whenCreatingRouteHandlers_thenCreateResourceInvokerWithTruncatedPathForEveryRoute(
            self):
        request = self.request_builder.path("/prefix" + PATH).build()
        rule = RoutingRule("/prefix", self.routing_table)
        self.route_handler_factory = RouteHandlerFactory(
            ServiceLocator(), Deserializer(Registry()), [rule],
            CorsHandler([CorsRule("/", {})]))

        handlers: List[PathRewritingRouteHandlerDecorator] = [
            x
            for x in self.route_handler_factory.create_route_handlers(request)
        ]

        self.assertEqual(1, len(handlers))
        self.assertEqual(PATH, handlers[0].new_path)
Example #12
0
 def setUp(self):
     self.service_locator = ServiceLocator()
     self.registry = Registry()
     self.binder = AnnotatedClassBinder("", self.registry,
                                        _binding_annotation)
 def setUp(self):
     self.event_bus_initializer = ReflectiveEventBusInitializer(ServiceLocator(), Registry(), "")
Example #14
0
 def __init__(self, registry: Registry, root_package_name: str):
     resources = registry.get_annotated_in_package(Resource, root_package_name)
     super().__init__(registry, resources)
Example #15
0
 def get_annotated(self, annotation: Annotation) -> List[Type]:
     return Stream(Registry().get_annotated_in_package(annotation, self.root_module_name)).map(
         lambda registration: registration.registered).toList()
Example #16
0
 def setUp(self):
     self.registry = Registry()
 def setUp(self):
     self.serialization_handler = DtoSerializationHandler(Registry())
Example #18
0
 def __init__(self, registry=Registry()):
     self.registry = registry
     self.literals = {}
     self.components = {}
     self.providers = {}
     self.scopeCaches = []
Example #19
0
import logging

from jivago.jivago_application import JivagoApplication
from jivago.lang.registry import Registry

import prismarine
from prismarine.infrastructure.config.prismarine_context import PrismarineContext

logging.getLogger().setLevel(logging.INFO)
app = JivagoApplication(prismarine,
                        context=PrismarineContext(prismarine, Registry()))

if __name__ == '__main__':
    app.run_dev(host='0.0.0.0', port=4000)
Example #20
0
 def setUp(self):
     self.serviceLocator = ServiceLocator(Registry())
class TaskScheduleInitializerTest(unittest.TestCase):
    def setUp(self):
        self.registry = Registry()
        self.taskScheduleInitializer = TaskScheduleInitializer(
            self.registry, "")
        self.taskSchedulerMock: TaskScheduler = mock.create_autospec(
            TaskScheduler)

    def test_givenCronString_whenCreatingSchedule_thenScheduleWithCron(self):
        self.registry.content = {}
        self.registry.register(Scheduled,
                               ScheduledClass,
                               arguments={"cron": CRON_STRING})

        self.taskScheduleInitializer.initialize_task_scheduler(
            self.taskSchedulerMock)

        runnable_class, schedule = self.taskSchedulerMock.schedule_task.call_args[
            0]
        self.assertIsInstance(schedule, CronSchedule)

    def test_givenCronStartDate_whenCreatingSchedule_thenDoNotScheduleBeforeStartTime(
            self):
        self.registry.content = {}
        self.registry.register(Scheduled,
                               ScheduledClass,
                               arguments={
                                   "cron": CRON_STRING,
                                   "start": DATE_IN_THE_FUTURE
                               })

        self.taskScheduleInitializer.initialize_task_scheduler(
            self.taskSchedulerMock)

        runnable_class, schedule = self.taskSchedulerMock.schedule_task.call_args[
            0]
        self.assertTrue(schedule.next_start_time() > DATE_IN_THE_FUTURE)

    def test_givenSimpleTimeInterval_whenCreatingSchedule_thenScheduleEveryXSeconds(
            self):
        self.registry.content = {}
        self.registry.register(Scheduled,
                               ScheduledClass,
                               arguments={"every": TIME_INTERVAL})

        self.taskScheduleInitializer.initialize_task_scheduler(
            self.taskSchedulerMock)

        runnable_class, schedule = self.taskSchedulerMock.schedule_task.call_args[
            0]
        self.assertEqual(TIME_INTERVAL.interval_time_in_seconds,
                         schedule.interval)

    def test_givenSimpleTimeIntervalWithStartTime_whenCreatingSchedule_thenDoNotScheduleBeforeStartTime(
            self):
        self.registry.content = {}
        self.registry.register(Scheduled,
                               ScheduledClass,
                               arguments={
                                   "every": TIME_INTERVAL,
                                   "start": DATE_IN_THE_FUTURE
                               })

        self.taskScheduleInitializer.initialize_task_scheduler(
            self.taskSchedulerMock)

        runnable_class, schedule = self.taskSchedulerMock.schedule_task.call_args[
            0]
        self.assertTrue(schedule.next_start_time() > DATE_IN_THE_FUTURE)
Example #22
0
 def setUp(self):
     self.registry = Registry()
     self.service_locator = ServiceLocator()
 def setUp(self):
     self.registry = Registry()
     self.taskScheduleInitializer = TaskScheduleInitializer(
         self.registry, "")
     self.taskSchedulerMock: TaskScheduler = mock.create_autospec(
         TaskScheduler)