def create(self):
        from masonite.app import App
        from config import providers

        """
        |--------------------------------------------------------------------------
        | Instantiate Container And Perform Important Bindings
        |--------------------------------------------------------------------------
        |
        | Some Service providers need important bindings like the WSGI application
        | and the application configuration file before they boot.
        |
        """

        container = App()

        container.bind('WSGI', self.app)
        # container.bind('Application', application)
        container.bind('Container', container)

        container.bind('Providers', [])
        container.bind('WSGIProviders', [])

        """
        |--------------------------------------------------------------------------
        | Bind all service providers
        |--------------------------------------------------------------------------
        |
        | Let's register everything into the Service Container. Once everything is
        | in the container we can run through all the boot methods. For reasons
        | some providers don't need to execute with every request and should
        | only run once when the server is started. Providers will be ran
        | once if the wsgi attribute on a provider is False.
        |
        """

        for provider in providers.PROVIDERS:
            located_provider = provider()
            located_provider.load_app(container).register()
            if located_provider.wsgi:
                container.make('WSGIProviders').append(located_provider)
            else:
                container.make('Providers').append(located_provider)

        for provider in container.make('Providers'):
            container.resolve(provider.boot)

        """
        |--------------------------------------------------------------------------
        | Get the application from the container
        |--------------------------------------------------------------------------
        |
        | Some providers may change the WSGI Server like wrapping the WSGI server
        | in a Whitenoise container for an example. Let's get a WSGI instance
        | from the container and pass it to the application variable. This
        | will allow WSGI servers to pick it up from the command line
        |
        """

        return container
Example #2
0
class TestServiceProvider:

    def setup_method(self):
        self.app = App()
        self.provider = ServiceProvider()
        self.provider.load_app(self.app).boot()

    def test_service_provider_loads_app(self):
        assert self.provider.app == self.app

    def test_can_call_container_with_self_parameter(self):
        self.app.bind('Request', object)
        self.app.bind('Get', object)

        assert self.app.resolve(ContainerTest().boot) == self.app.make('Request')

    def test_can_call_container_with_annotations_from_variable(self):
        request = Request(generate_wsgi())

        self.app.bind('Request', request)
        self.app.bind('Get', Get().route('url', None))

        assert self.app.resolve(ContainerTest().testboot) == self.app.make('Request')
    
    def test_can_call_container_with_annotation_with_self_parameter(self):
        self.app.bind('Request', Request)
        self.app.bind('Get', Get().route('url', None))

        assert self.app.resolve(ContainerTest().testboot) == self.app.make('Request')
Example #3
0
def test_throws_exception_if_too_many_bindings():
    app = App()
    REQUEST.cookies = ['hey']
    app.bind('Request', REQUEST)
    app.bind('Route', Get().route('test/', None))
    with pytest.raises(TypeError, message="should raise error"):
        app.resolve(functest)
Example #4
0
class TestMiddleware:
    def setup_method(self):
        self.app = App()
        self.app.bind('Environ', generate_wsgi())
        self.app.bind('Application', application)
        self.app.make('Environ')
        self.app.bind('StatusCode', '404 Not Found Error')
        self.app.bind('Request',
                      Request(self.app.make('Environ')).load_app(self.app))
        self.app.simple(Response(self.app))
        self.app.bind('Csrf', Csrf(self.app.make('Request')))
        self.app.bind('Route', Route(self.app.make('Environ')))

        self.app.bind('ViewClass', View(self.app))

        self.app.bind(
            'WebRoutes',
            [Get().route('/', 'TestController@show').middleware('test')])

        self.app.bind('HttpMiddleware', [MiddlewareHttpTest])
        self.app.bind('RouteMiddleware', {'test': MiddlewareTest})

        self.provider = RouteProvider()
        self.provider.app = self.app

    def test_route_middleware_runs(self):
        self.app.resolve(self.provider.boot)
        assert self.app.make('Request').path == '/test/middleware'

    def test_http_middleware_runs(self):
        self.app.resolve(self.provider.boot)
        assert self.app.make('Request').path == '/test/middleware'
        assert self.app.make('Request').environ['HTTP_TEST'] == 'test'
    def test_request_gets_input_from_container(self):
        container = App()
        container.bind('Application', application)
        container.bind('Providers', providers)
        container.bind('WSGI', object)
        container.bind('Environ', wsgi_request)

        for provider in container.make('Providers').PROVIDERS:
            container.resolve(provider().load_app(container).register)

        container.bind('Response', 'test')
        container.bind('WebRoutes', [
            Get().route('url', None),
            Get().route('url/', None),
            Get().route('url/@firstname', None),
        ])

        container.bind('Response', 'Route not found. Error 404')

        for provider in container.make('Providers').PROVIDERS:
            located_provider = provider().load_app(container)

            container.resolve(provider().load_app(container).boot)

        assert container.make('Request').input('application') == 'Masonite'
        assert container.make('Request').all() == {'application': 'Masonite'}
        container.make('Request').environ['REQUEST_METHOD'] = 'POST'
        assert container.make('Request').environ['REQUEST_METHOD'] == 'POST'
        assert container.make('Request').input('application') == 'Masonite'
    def create_container(self):
        container = App()

        container.bind('WSGI', object)
        container.bind('Application', application)
        container.bind('Providers', providers)

        """
        |--------------------------------------------------------------------------
        | Bind all service providers
        |--------------------------------------------------------------------------
        |
        | Let's register everything into the Service Container. Once everything is
        | in the container we can run through all the boot methods. For reasons
        | some providers don't need to execute with every request and should
        | only run once when the server is started. Providers will be ran
        | once if the wsgi attribute on a provider is False.
        |
        """

        for provider in container.make('Providers').PROVIDERS:
            provider().load_app(container).register()

        for provider in container.make('Providers').PROVIDERS:
            located_provider = provider().load_app(container)

            if located_provider.wsgi is False:
                container.resolve(located_provider.boot)

            """
        |--------------------------------------------------------------------------
        | Startup the Service Container
        |--------------------------------------------------------------------------
        |
        | Instantiate the Service Container so we can bind classes into it and 
        | bind the environ variable that is created by the WSGI server into
        | the container.
        |
        """

        container.bind('Environ', generate_wsgi())

        """
        |--------------------------------------------------------------------------
        | Execute All Service Providers
        |--------------------------------------------------------------------------
        |
        | Run all service provider boot methods if the wsgi attribute is true.
        |
        """

        for provider in container.make('Providers').PROVIDERS:
            located_provider = provider().load_app(container)
            container.bind('Response', 'test')
            if located_provider.wsgi is True:
                container.resolve(located_provider.boot)

        self.container = container
        return self
class TestController:
    
    def setup_method(self):
        self.app = App()
        self.app.bind('object', object)
    
    def test_controller_loads_app(self):
        controller = Controller().load_app(self.app)
        assert controller.app.providers == {'object': object}

    def test_controller_loads_app(self):
        app = App()
        app.bind('object', object)

        controller = Controller().load_app(app)
        assert controller.app.providers == {'object': object}


    def test_string_controller_constructor_resolves_container(self):
        self.app.bind('Request', Request)

        # Create the route
        route = get('/url', 'ControllerTest@show')

        # Resolve the controller constructor
        controller = self.app.resolve(route.controller)

        # Resolve the method
        response = self.app.resolve(getattr(controller, route.controller_method))

        assert isinstance(route.controller, ControllerTest.__class__)
        assert route.controller_method == 'show'
        assert isinstance(response, Request.__class__)


    def test_object_controller_constructor_resolves_container(self):
        self.app.bind('Request', Request)

        # Create the route
        route = get('/url', ControllerTest.show)

        # Resolve the controller constructor
        controller = self.app.resolve(route.controller)

        # Resolve the method
        response = self.app.resolve(
            getattr(controller, route.controller_method))

        assert isinstance(route.controller, ControllerTest.__class__)
        assert route.controller_method == 'show'
        assert isinstance(response, Request.__class__)
def test_can_call_container_with_self_parameter():
    app = App()

    app.bind('Request', object)
    app.bind('Get', object)

    assert app.resolve(ContainerTest().boot) == app.make('Request')
def test_can_call_container_with_annotation_with_self_parameter():
    app = App()

    app.bind('Request', Request)
    app.bind('Get', Get().route('url', None))

    assert app.resolve(ContainerTest().testboot) == app.make('Request')
Example #10
0
 def test_can_pass_variables(self):
     app = App()
     req = Request()
     app.bind('Request', req)
     obj = app.resolve(self._test_resolves_variables, 'test1', 'test2')
     self.assertEqual(obj[0], 'test1')
     self.assertEqual(obj[1], req)
     self.assertEqual(obj[2], 'test2')
Example #11
0
 def test_can_pass_variables(self):
     app = App()
     req = Request()
     app.bind('Request', req)
     obj = app.resolve(self._test_resolves_variables, 'test1', 'test2')
     assert obj[0] == 'test1'
     assert obj[1] == req
     assert obj[2] == 'test2'
Example #12
0
class TestMiddleware(unittest.TestCase):
    def setUp(self):
        self.app = App()
        self.app.bind('Environ', generate_wsgi())
        self.app.bind('Application', application)
        self.app.make('Environ')
        self.app.bind('StatusCode', None)
        self.app.bind('Request',
                      Request(self.app.make('Environ')).load_app(self.app))
        self.app.simple(Response(self.app))
        self.app.bind('Csrf', Csrf(self.app.make('Request')))
        self.app.bind('Route', Route(self.app.make('Environ')))

        self.app.bind('ViewClass', View(self.app))

        self.app.bind(
            'WebRoutes',
            [Get().route('/', 'TestController@show').middleware('test')])

        self.app.bind('HttpMiddleware', [MiddlewareHttpTest])

        self.app.bind('RouteMiddleware', {
            'test': MiddlewareTest,
            'throttle:1,2': MiddlewareValueTest
        })

        self.provider = RouteProvider()
        self.provider.app = self.app

    def test_route_middleware_runs(self):
        self.app.resolve(self.provider.boot)
        self.assertEqual(self.app.make('Request').path, '/test/middleware')

    def test_http_middleware_runs(self):
        self.app.resolve(self.provider.boot)
        self.assertEqual(self.app.make('Request').path, '/test/middleware')
        self.assertEqual(self.app.make('Request').environ['HTTP_TEST'], 'test')

    def test_route_middleware_can_pass_values(self):
        route = self.app.make('WebRoutes')[0]
        route.request = self.app.make('Request')
        route.list_middleware = ['throttle:1,2']
        route.run_middleware('before')
        self.assertEqual(route.request.value1, '1')
        self.assertEqual(route.request.value2, '2')
def test_can_call_container_with_annotations_from_variable():
    app = App()

    request = Request(wsgi_request)

    app.bind('Request', request)
    app.bind('Get', Get().route('url', None))

    assert app.resolve(ContainerTest().testboot) == app.make('Request')
Example #14
0
class TestApp:

    def setup_method(self):
        self.app = App()

    def test_app_binds(self):
        self.app.bind('test1', object)
        self.app.bind('test2', object)
        assert self.app.providers == {'test1': object, 'test2': object}

    def test_app_makes(self):
        self.app.bind('Request', REQUEST)
        assert self.app.make('Request').cookies == []

    def test_throws_exception_if_too_many_bindings(self):
        REQUEST.cookies = ['hey']
        self.app.bind('Request', REQUEST)
        self.app.bind('Route', Get().route('test/', None))
        with pytest.raises(ContainerError, message="should raise error"):
            self.app.resolve(self._functest)

    def _functest(Request, get: Get, post: Post):
        return Request.cookies
Example #15
0
class TestController(unittest.TestCase):
    def setUp(self):
        self.app = App()
        self.app.bind('object', object)

    def test_string_controller_constructor_resolves_container(self):
        self.app.bind('Request', Request)

        # Create the route
        route = get('/url', 'ControllerTest@show')

        # Resolve the controller constructor
        controller = self.app.resolve(route.controller)

        # Resolve the method
        response = self.app.resolve(
            getattr(controller, route.controller_method))

        self.assertIsInstance(route.controller, ControllerTest.__class__)
        self.assertEqual(route.controller_method, 'show')
        self.assertIsInstance(response, Request)

    def test_object_controller_constructor_resolves_container(self):
        self.app.bind('Request', Request)
        # Create the route
        route = get('/url', ControllerTest.show)

        # Resolve the controller constructor
        controller = self.app.resolve(route.controller)

        # Resolve the method
        response = self.app.resolve(
            getattr(controller, route.controller_method))

        self.assertIsInstance(route.controller, ControllerTest.__class__)
        self.assertEqual(route.controller_method, 'show')
        self.assertIsInstance(response, Request)
Example #16
0
    def create(self):
        from masonite.app import App
        from config import providers

        container = App()

        container.bind('Container', container)

        container.bind('ProvidersConfig', providers)
        container.bind('Providers', [])
        container.bind('WSGIProviders', [])

        for provider in container.make('ProvidersConfig').PROVIDERS:
            located_provider = provider()
            located_provider.load_app(container).register()
            if located_provider.wsgi:
                container.make('WSGIProviders').append(located_provider)
            else:
                container.make('Providers').append(located_provider)

        for provider in container.make('Providers'):
            container.resolve(provider.boot)

        return container
Example #17
0
class TestResponse:
    def setup_method(self):
        self.app = App()
        self.request = Request(generate_wsgi()).load_app(self.app)
        self.app.bind('Request', self.request)
        self.response = Response(self.app)

    def test_can_set_json(self):
        self.response.json({'test': 'value'})

        assert self.request.is_status(200)
        assert self.request.header('Content-Length') == '17'
        assert self.request.header(
            'Content-Type') == 'application/json; charset=utf-8'

    def test_redirect(self):
        self.response.redirect('/some/test')

        assert self.request.is_status(302)
        assert self.request.header('Location', '/some/test')

    def test_response_does_not_override_header_from_controller(self):
        self.response.view(self.app.resolve(ControllerTest().change_header))

        assert self.request.header('Content-Type') == 'application/xml'

    def test_view(self):
        view = View(self.app).render('test', {'test': 'test'})

        self.response.view(view)

        assert self.app.make('Response') == 'test'
        assert self.request.is_status(200)

        self.response.view('foobar')

        assert self.app.make('Response') == 'foobar'

    def test_view_can_return_integer_as_string(self):
        self.response.view(1)

        assert self.app.make('Response') == '1'
        assert self.request.is_status(200)
Example #18
0
| some providers don't need to execute with every request and should
| only run once when the server is started. Providers will be ran
| once if the wsgi attribute on a provider is False.
|
"""

for provider in container.make('ProvidersConfig').PROVIDERS:
    located_provider = provider()
    located_provider.load_app(container).register()
    if located_provider.wsgi:
        container.make('WSGIProviders').append(located_provider)
    else:
        container.make('Providers').append(located_provider)

for provider in container.make('Providers'):
    container.resolve(provider.boot)

"""
|--------------------------------------------------------------------------
| Get the application from the container
|--------------------------------------------------------------------------
|
| Some providers may change the WSGI Server like wrapping the WSGI server
| in a Whitenoise container for an example. Let's get a WSGI instance
| from the container and pass it to the application variable. This
| will allow WSGI servers to pick it up from the command line
|
"""

application = container.make('WSGI')
Example #19
0
|
| Let's register everything into the Service Container. Once everything is
| in the container we can run through all the boot methods. For reasons
| some providers don't need to execute with every request and should
| only run once when the server is started. Providers will be ran
| once if the wsgi attribute on a provider is False.
|
'''

for provider in container.make('Application').PROVIDERS:
    locate(provider)().load_app(container).register()

for provider in container.make('Application').PROVIDERS:
    located_provider = locate(provider)().load_app(container)

    if located_provider.wsgi is False:
        container.resolve(locate(provider)().load_app(container).boot)
'''
|--------------------------------------------------------------------------
| Get the application from the container
|--------------------------------------------------------------------------
|
| Some providers may change the WSGI Server like wrapping the WSGI server
| in a Whitenoise container for an example. Let's get a WSGI instance
| from the container and pass it to the application variable. This
| will allow WSGI servers to pick it up from the command line
|
'''

application = container.make('WSGI')
Example #20
0
|
| Let's register everything into the Service Container. Once everything is
| in the container we can run through all the boot methods. For reasons
| some providers don't need to execute with every request and should
| only run once when the server is started. Providers will be ran
| once if the wsgi attribute on a provider is False.
|
"""

for provider in container.make('ProvidersConfig').PROVIDERS:
    located_provider = provider()
    located_provider.load_app(container).register()
    if located_provider.wsgi:
        container.make('WSGIProviders').append(located_provider)
    else:
        container.resolve(located_provider.boot)
        container.make('Providers').append(located_provider)
"""
|--------------------------------------------------------------------------
| Get the application from the container
|--------------------------------------------------------------------------
|
| Some providers may change the WSGI Server like wrapping the WSGI server
| in a Whitenoise container for an example. Let's get a WSGI instance
| from the container and pass it to the application variable. This
| will allow WSGI servers to pick it up from the command line
|
"""

application = container.make('WSGI')
Example #21
0
class TestApp:

    def setup_method(self):
        self.app = App()

    def test_app_binds(self):
        self.app.bind('test1', object)
        self.app.bind('test2', object)
        assert self.app.providers == {'test1': object, 'test2': object}

    def test_app_makes(self):
        self.app.bind('Request', REQUEST)
        assert self.app.make('Request').cookies == []

    def test_can_set_container_hook(self):
        self.app.on_bind('Request', self._func_on_bind)
        self.app.bind('Request', REQUEST)
        assert self.app.make('Request').path == '/test/on/bind'

    def _func_on_bind(self, request, container):
        request.path = '/test/on/bind'

    def test_can_set_container_hook_with_obj_binding(self):
        self.app.on_bind(Request, self._func_on_bind_with_obj)
        self.app.bind('Request', REQUEST)
        assert self.app.make('Request').path == '/test/on/bind/obj'

    def _func_on_bind_with_obj(self, request, container):
        request.path = '/test/on/bind/obj'

    def test_can_fire_container_hook_on_make(self):
        self.app.on_make(Request, self._func_on_make)
        self.app.bind('Request', REQUEST)
        assert self.app.make('Request').path == '/test/on/make'

    def _func_on_make(self, request, container):
        request.path = '/test/on/make'

    def test_can_fire_hook_on_resolve(self):
        self.app.on_resolve(Request, self._func_on_resolve)
        self.app.bind('Request', REQUEST)
        assert self.app.resolve(self._resolve_request).path == '/on/resolve'

    def test_can_fire_hook_on_resolve_class(self):
        self.app.on_resolve(Request, self._func_on_resolve_class)
        self.app.bind('Request', REQUEST)
        assert self.app.resolve(
            self._resolve_reques_class).path == '/on/resolve/class'

    def test_can_resolve_parameter_with_keyword_argument_setting(self):
        self.app.bind('Request', REQUEST)
        self.app.resolve_parameters = True
        assert self.app.resolve(
            self._resolve_parameter) == REQUEST

    def _func_on_resolve(self, request, container):
        request.path = '/on/resolve'

    def _func_on_resolve_class(self, request, container):
        request.path = '/on/resolve/class'

    def _resolve_request(self, request: Request):
        return request

    def _resolve_parameter(self, Request):
        return Request

    def _resolve_reques_class(self, request: Request):
        return request
class TestMailManager:
    def setup_method(self):
        self.app = App()
        self.app = self.app.bind('Container', self.app)

        self.app.bind('Test', object)
        self.app.bind('MailSmtpDriver', object)
        self.app.bind('MailConfig', mail)
        self.app.bind('View', View(self.app).render)
        self.app.bind('ViewClass', View(self.app))

    def test_mail_manager_loads_container(self):
        mailManager = MailManager()
        assert mailManager.load_container(self.app)

    def test_mail_manager_resolves_from_contract(self):
        self.app.bind('MailManager', MailManager())
        assert self.app.resolve(
            self._test_resolve) == self.app.make('MailManager')

    def _test_resolve(self, mail: MailManagerContract):
        return mail

    def test_creates_driver(self):
        mailManager = MailManager()

        assert mailManager.load_container(self.app).manage_driver == object

    def test_does_not_create_driver_with_initilization_container(self):

        mailManager = MailManager(self.app)

        assert mailManager.manage_driver == None

    def test_does_not_raise_drivernotfound_exception(self):
        MailManager(self.app)

    def test_manager_sets_driver(self):
        self.app.bind('MailMailtrapDriver', Mailgun)
        MailManager(self.app).driver('mailtrap')

    def test_manager_sets_driver_throws_driver_not_found_exception(self):
        with pytest.raises(DriverNotFound,
                           message="Should raise DriverNotFound error"):
            MailManager(self.app).driver('mailtrap')

    def test_drivers_are_resolvable_by_container(self):
        self.app.bind('MailSmtpDriver', MailDriver)

        assert isinstance(MailManager(self.app).driver('smtp'), MailDriver)

    def test_driver_loads_template(self):
        self.app.bind('MailSmtpDriver', MailDriver)

        driver = MailManager(self.app).driver('smtp')

        assert driver.template('test', {'test': 'test'}).message_body == 'test'

    def test_send_mail(self):
        self.app.bind('MailSmtpDriver', MailDriver)
        assert MailManager(self.app).driver('smtp').to('*****@*****.**')

    def test_send_mail_with_from(self):
        self.app.bind('MailSmtpDriver', MailDriver)

        assert MailManager(
            self.app).driver('smtp').to('*****@*****.**').send_from(
                '*****@*****.**'
            ).from_address == '*****@*****.**'

    def test_send_mail_sends(self):
        if env('RUN_MAIL'):
            self.app.bind('MailSmtpDriver', MailDriver)

            assert MailManager(
                self.app).driver('smtp').to('*****@*****.**').send('hi')

    def test_send_mail_sends_with_queue(self):
        if env('RUN_MAIL'):
            self.app.bind('MailSmtpDriver', MailDriver)

            assert MailManager(self.app).driver('smtp').to(
                '*****@*****.**').queue().send('hi') == None

    def test_send_mail_with_subject(self):
        self.app.bind('MailSmtpDriver', MailDriver)

        assert MailManager(self.app).driver('smtp').to('').subject(
            'test').message_subject == 'test'

    def test_send_mail_with_callable(self):
        self.app.bind('MailSmtpDriver', MailDriver)
        user = User
        user.email = '*****@*****.**'
        assert MailManager(self.app).driver('smtp').to(User)

    def test_switch_mail_manager(self):
        self.app.bind('MailSmtpDriver', MailDriver)
        self.app.bind('MailTestDriver', Mailgun)

        mail_driver = MailManager(self.app).driver('smtp')

        assert isinstance(mail_driver.driver('test'), Mailgun)

    def test_mail_helper_method_resolves_a_driver(self):
        assert isinstance(mail_helper(), MailContract)
class TestApp:
    def setup_method(self):
        self.app = App()

    def test_app_binds(self):
        self.app.bind('test1', object)
        self.app.bind('test2', object)
        assert self.app.providers == {'test1': object, 'test2': object}

    def test_app_makes(self):
        self.app.bind('Request', REQUEST)
        assert self.app.make('Request').cookies == []

    def test_throws_exception_if_too_many_bindings(self):
        REQUEST.cookies = ['hey']
        self.app.bind('Request', REQUEST)
        self.app.bind('Route', Get().route('test/', None))
        with pytest.raises(ContainerError, message="should raise error"):
            self.app.resolve(self._functest)

    def _functest(Request, get: Get, post: Post):
        return Request.cookies

    def test_can_set_container_hook(self):
        self.app.on_bind('Request', self._func_on_bind)
        self.app.bind('Request', REQUEST)
        assert self.app.make('Request').path == '/test/on/bind'

    def _func_on_bind(self, request, container):
        request.path = '/test/on/bind'

    def test_can_set_container_hook_with_obj_binding(self):
        self.app.on_bind(Request, self._func_on_bind_with_obj)
        self.app.bind('Request', REQUEST)
        assert self.app.make('Request').path == '/test/on/bind/obj'

    def _func_on_bind_with_obj(self, request, container):
        request.path = '/test/on/bind/obj'

    def test_can_fire_container_hook_on_make(self):
        self.app.on_make(Request, self._func_on_make)
        self.app.bind('Request', REQUEST)
        assert self.app.make('Request').path == '/test/on/make'

    def _func_on_make(self, request, container):
        request.path = '/test/on/make'

    def test_can_fire_hook_on_resolve(self):
        self.app.on_resolve(Request, self._func_on_resolve)
        self.app.bind('Request', REQUEST)
        assert self.app.resolve(self._resolve_request).path == '/on/resolve'

    def test_can_fire_hook_on_resolve_class(self):
        self.app.on_resolve(Request, self._func_on_resolve_class)
        self.app.bind('Request', REQUEST)
        assert self.app.resolve(
            self._resolve_reques_class).path == '/on/resolve/class'

    def _func_on_resolve(self, request, container):
        request.path = '/on/resolve'

    def _func_on_resolve_class(self, request, container):
        request.path = '/on/resolve/class'

    def _resolve_request(self, Request):
        return Request

    def _resolve_reques_class(self, request: Request):
        return request
Example #24
0
class TestResponse:
    def setup_method(self):
        self.app = App()
        self.request = Request(generate_wsgi()).load_app(self.app)
        self.app.bind('Request', self.request)
        self.app.bind('StatusCode', None)
        self.response = Response(self.app)
        self.app.bind('Response', self.response)

    def test_can_set_json(self):
        self.response.json({'test': 'value'})

        assert self.request.is_status(200)
        assert self.request.header('Content-Length') == '17'
        assert self.request.header(
            'Content-Type') == 'application/json; charset=utf-8'

    def test_redirect(self):
        self.response.redirect('/some/test')

        assert self.request.is_status(302)
        assert self.request.header('Location', '/some/test')

    def test_response_does_not_override_header_from_controller(self):
        self.response.view(self.app.resolve(ControllerTest().change_header))

        assert self.request.header('Content-Type') == 'application/xml'

    def test_view(self):
        view = View(self.app).render('test', {'test': 'test'})

        self.response.view(view)

        assert self.app.make('Response') == 'test'
        assert self.request.is_status(200)

        self.response.view('foobar')

        assert self.app.make('Response') == 'foobar'

    def test_view_can_return_integer_as_string(self):
        self.response.view(1)

        assert self.app.make('Response') == '1'
        assert self.request.is_status(200)

    def test_view_can_set_own_status_code_to_404(self):
        self.response.view(self.app.resolve(ControllerTest().change_404))
        assert self.request.is_status(404)

    def test_view_can_set_own_status_code(self):

        self.response.view(self.app.resolve(ControllerTest().change_status))
        assert self.request.is_status(203)

    def test_view_should_return_a_json_response_when_retrieve_a_user_from_model(
            self):

        assert isinstance(MockUser(), Model)
        self.response.view(MockUser().all())

        json_response = '[{"name": "TestUser", "email": "*****@*****.**"}, {"name": "TestUser", "email": "*****@*****.**"}]'
        assert self.app.make('Response') == json_response

        self.response.view(MockUser().find(1))

        json_response = '{"name": "TestUser", "email": "*****@*****.**"}'
        assert self.app.make('Response') == json_response
Example #25
0
class TestResponse(unittest.TestCase):
    def setUp(self):
        self.app = App()
        self.request = Request(generate_wsgi()).load_app(self.app)
        self.app.bind('Request', self.request)
        self.app.bind('StatusCode', None)
        self.response = Response(self.app)
        self.app.bind('Response', self.response)

    def test_can_set_json(self):
        self.response.json({'test': 'value'})

        self.assertTrue(self.request.is_status(200))
        self.assertEqual(self.request.header('Content-Length'), '17')
        self.assertEqual(self.request.header('Content-Type'),
                         'application/json; charset=utf-8')

    def test_redirect(self):
        self.response.redirect('/some/test')

        self.request.header('Location', '/some/test')
        self.assertTrue(self.request.is_status(302))
        self.assertEqual(self.request.header('Location'), '/some/test')

    def test_response_does_not_override_header_from_controller(self):
        self.response.view(self.app.resolve(ControllerTest().change_header))

        self.assertEqual(self.request.header('Content-Type'),
                         'application/xml')

    def test_view(self):
        view = View(self.app).render('test', {'test': 'test'})

        self.response.view(view)

        self.assertEqual(self.app.make('Response'), 'test')
        self.assertTrue(self.request.is_status(200))

        self.response.view('foobar')

        self.assertEqual(self.app.make('Response'), 'foobar')

    def test_view_can_return_integer_as_string(self):
        self.response.view(1)

        self.assertEqual(self.app.make('Response'), '1')
        self.assertTrue(self.request.is_status(200))

    def test_view_can_set_own_status_code_to_404(self):
        self.response.view(self.app.resolve(ControllerTest().change_404))
        self.assertTrue(self.request.is_status(404))

    def test_view_can_set_own_status_code(self):

        self.response.view(self.app.resolve(ControllerTest().change_status))
        self.assertTrue(self.request.is_status(203))

    def test_view_should_return_a_json_response_when_retrieve_a_user_from_model(
            self):

        self.assertIsInstance(MockUser(), Model)
        self.response.view(MockUser().all())

        self.assertIn('"name": "TestUser"', self.app.make('Response'))
        self.assertIn('"email": "*****@*****.**"', self.app.make('Response'))

        self.response.view(MockUser().find(1))

        self.assertIn('"name": "TestUser"', self.app.make('Response'))
        self.assertIn('"email": "*****@*****.**"', self.app.make('Response'))
Example #26
0
class TestApp(unittest.TestCase):
    def setUp(self):
        self.app = App()

    def test_app_binds(self):
        self.app.bind('test1', object)
        self.app.bind('test2', object)
        self.assertEqual(self.app.providers, {
            'test1': object,
            'test2': object
        })

    def test_app_makes(self):
        self.app.bind('Request', REQUEST)
        self.assertEqual(self.app.make('Request').cookies, [])

    def test_app_makes_and_resolves(self):
        self.app.bind('Request', REQUEST)
        self.app.bind('MockMail', MockMail)
        mockmail = self.app.make('MockMail')
        self.assertIsInstance(mockmail.request, Request)

    def test_app_makes_different_instances(self):
        self.app.bind('MockMail', MockMail)
        self.app.bind('Request', REQUEST)
        m1 = self.app.make('MockMail')
        m2 = self.app.make('MockMail')

        self.assertNotEqual(id(m1), id(m2))

    def test_app_makes_singleton_instance(self):
        self.app.bind('Request', REQUEST)
        self.app.singleton('MockMail', MockMail)
        m1 = self.app.make('MockMail')
        m2 = self.app.make('MockMail')

        self.assertEqual(id(m1), id(m2))
        self.assertEqual(id(m1.request), id(m2.request))

        m1.request.test = 'test'
        self.assertEqual(m2.request.test, 'test')

    def test_can_set_container_hook(self):
        self.app.on_bind('Request', self._func_on_bind)
        self.app.bind('Request', REQUEST)
        self.assertEqual(self.app.make('Request').path, '/test/on/bind')

    def _func_on_bind(self, request, container):
        request.path = '/test/on/bind'

    def test_can_set_container_hook_with_obj_binding(self):
        self.app.on_bind(Request, self._func_on_bind_with_obj)
        self.app.bind('Request', REQUEST)
        self.assertEqual(self.app.make('Request').path, '/test/on/bind/obj')

    def _func_on_bind_with_obj(self, request, container):
        request.path = '/test/on/bind/obj'

    def test_can_fire_container_hook_on_make(self):
        self.app.on_make(Request, self._func_on_make)
        self.app.bind('Request', REQUEST)
        self.assertEqual(self.app.make('Request').path, '/test/on/make')
        self.assertEqual(self.app.make('Request').path, '/test/on/make')

    def _func_on_make(self, request, container):
        request.path = '/test/on/make'

    def test_can_fire_hook_on_resolve(self):
        self.app.on_resolve(Request, self._func_on_resolve)
        self.app.bind('Request', REQUEST)
        self.assertEqual(
            self.app.resolve(self._resolve_request).path, '/on/resolve')
        self.assertEqual(
            self.app.resolve(self._resolve_request).path, '/on/resolve')

    def test_can_fire_hook_on_resolve_class(self):
        self.app.on_resolve(Request, self._func_on_resolve_class)
        self.app.bind('Request', REQUEST)
        self.assertEqual(
            self.app.resolve(self._resolve_reques_class).path,
            '/on/resolve/class')
        self.assertEqual(
            self.app.resolve(self._resolve_reques_class).path,
            '/on/resolve/class')

    def test_can_resolve_parameter_with_keyword_argument_setting(self):
        self.app.bind('Request', REQUEST)
        self.app.resolve_parameters = True
        self.assertEqual(self.app.resolve(self._resolve_parameter), REQUEST)
        self.assertEqual(self.app.resolve(self._resolve_parameter), REQUEST)

    def _func_on_resolve(self, request, container):
        request.path = '/on/resolve'

    def _func_on_resolve_class(self, request, container):
        request.path = '/on/resolve/class'

    def _resolve_request(self, request: Request):
        return request

    def _resolve_parameter(self, Request):
        return Request

    def _resolve_reques_class(self, request: Request):
        return request
class TestMailManager(unittest.TestCase):
    def setUp(self):
        self.app = App()
        self.app = self.app.bind('Container', self.app)

        self.app.bind('Test', object)
        self.app.bind('MailSmtpDriver', object)
        self.app.bind('MailConfig', mail)
        self.app.bind('View', View(self.app).render)
        self.app.bind('ViewClass', View(self.app))

    def test_mail_manager_loads_container(self):
        mailManager = MailManager(self.app)
        self.assertTrue(mailManager.load_container(self.app))

    def test_mail_manager_resolves_from_contract(self):
        self.app.singleton('MailManager', MailManager)
        self.assertEqual(self.app.resolve(self._test_resolve),
                         self.app.make('MailManager'))

    def _test_resolve(self, mail: MailManagerContract):
        return mail

    def test_creates_driver(self):
        mailManager = MailManager(self.app)

        self.assertIsInstance(mailManager.manage_driver, object)

    def test_does_not_create_driver_with_initilization_container(self):

        mailManager = MailManager(self.app)

        self.assertEqual(mailManager.manage_driver, None)

    def test_does_not_raise_drivernotfound_exception(self):
        MailManager(self.app)

    def test_manager_sets_driver(self):
        self.app.bind('MailMailtrapDriver', Mailgun)
        MailManager(self.app).driver('mailtrap')

    def test_manager_sets_driver_throws_driver_not_found_exception(self):
        with self.assertRaises(DriverNotFound):
            MailManager(self.app).driver('mailtrap')

    def test_drivers_are_resolvable_by_container(self):
        self.app.bind('MailSmtpDriver', MailDriver)

        self.assertIsInstance(MailManager(self.app).driver('smtp'), MailDriver)

    def test_driver_loads_template(self):
        self.app.bind('MailSmtpDriver', MailDriver)

        driver = MailManager(self.app).driver('smtp')

        self.assertEqual(
            driver.template('test', {
                'test': 'test'
            }).message_body, 'test')

    def test_send_mail(self):
        self.app.bind('MailSmtpDriver', MailDriver)
        self.assertTrue(
            MailManager(self.app).driver('smtp').to('*****@*****.**'))

    def test_send_mail_with_from(self):
        self.app.bind('MailSmtpDriver', MailDriver)

        self.assertEqual(
            MailManager(
                self.app).driver('smtp').to('*****@*****.**').send_from(
                    '*****@*****.**').from_address,
            '*****@*****.**')

    def test_send_mail_sends(self):
        if env('RUN_MAIL'):
            self.app.bind('MailSmtpDriver', MailDriver)

            self.assertTrue(
                MailManager(self.app).driver('smtp').to(
                    '*****@*****.**').send('hi'))

    def test_send_mail_sends_with_queue(self):
        if env('RUN_MAIL'):
            self.app.bind('MailSmtpDriver', MailDriver)

            self.assertEqual(
                MailManager(self.app).driver('smtp').to(
                    '*****@*****.**').queue().send('hi'), None)

    def test_send_mail_with_subject(self):
        self.app.bind('MailSmtpDriver', MailDriver)

        self.assertEqual(
            MailManager(self.app).driver('smtp').to('').subject(
                'test').message_subject, 'test')

    def test_send_mail_with_callable(self):
        self.app.bind('MailSmtpDriver', MailDriver)
        user = User
        user.email = '*****@*****.**'
        self.assertTrue(MailManager(self.app).driver('smtp').to(User))

    def test_switch_mail_manager(self):
        self.app.bind('MailSmtpDriver', MailDriver)
        self.app.bind('MailTestDriver', Mailgun)

        mail_driver = MailManager(self.app).driver('smtp')

        self.assertIsInstance(mail_driver.driver('test'), Mailgun)

    def test_mail_helper_method_resolves_a_driver(self):
        self.assertIsInstance(mail_helper(), MailContract)
Example #28
0
container.bind("Container", container)

container.bind("Providers", [])
container.bind("WSGIProviders", [])
"""Bind all service providers
Let's register everything into the Service Container. Once everything is
in the container we can run through all the boot methods. For reasons
some providers don't need to execute with every request and should
only run once when the server is started. Providers will be ran
once if the wsgi attribute on a provider is False.
"""

for provider in providers.PROVIDERS:
    located_provider = provider()
    located_provider.load_app(container).register()
    if located_provider.wsgi:
        container.make("WSGIProviders").append(located_provider)
    else:
        container.make("Providers").append(located_provider)

for provider in container.make("Providers"):
    container.resolve(provider.boot)
"""Get the application from the container
Some providers may change the WSGI Server like wrapping the WSGI server
in a Whitenoise container for an example. Let's get a WSGI instance
from the container and pass it to the application variable. This
will allow WSGI servers to pick it up from the command line
"""

application = container.make("WSGI")
Example #29
0
class TestContainer:
    def setup_method(self):
        self.app = App()
        self.app.bind('Request', Request(None))
        self.app.bind('MockObject', MockObject)
        self.app.bind('GetObject', GetObject)

    def test_container_gets_direct_class(self):
        assert isinstance(self.app.make('Request'), Request)

    def test_container_resolves_object(self):
        assert isinstance(self.app.resolve(self._function_test),
                          MockObject.__class__)

    def _function_test(self, MockObject):
        return MockObject

    def test_container_resolving_annotation(self):
        assert isinstance(self.app.resolve(self._function_test_annotation),
                          MockObject.__class__)

    def _function_test_annotation(self, mock: MockObject):
        return mock

    def test_container_resolving_instance_of_object(self):
        assert isinstance(self.app.resolve(self._function_test_annotation),
                          GetObject.__class__)

    def test_container_resolving_similiar_objects(self):
        self.app.bind('GetAnotherObject', GetAnotherObject)

        obj = self.app.resolve(
            self._function_test_find_method_on_similiar_objects)
        assert obj[0] == 2
        assert obj[1] == 1

    def _function_test_find_method_on_similiar_objects(self,
                                                       user: GetAnotherObject,
                                                       country: GetObject):
        return [user().find(), country().find()]

    def test_raises_error_when_getting_instances_of_classes(self):
        with pytest.raises(ContainerError):
            assert self.app.resolve(
                self._function_test_find_method_on_similiar_objects)

    def _function_test_double_annotations(self, mock: MockObject,
                                          request: Request):
        return {'mock': MockObject, 'request': Request}

    def test_container_resolving_multiple_annotations(self):
        assert isinstance(
            self.app.resolve(self._function_test_double_annotations)['mock'],
            MockObject.__class__)
        assert isinstance(
            self.app.resolve(
                self._function_test_double_annotations)['request'],
            Request.__class__)

    def test_container_contract_returns_upload_disk_driver(self):
        self.app.bind('UploadDiskDriver', UploadDiskDriver)
        assert isinstance(self.app.resolve(self._function_test_contracts),
                          UploadDiskDriver.__class__)

    def _function_test_contracts(self, upload: UploadContract):
        return upload

    def _function_test_contract_and_annotations(self, UploadDiskDriver,
                                                request: Request, MockObject):
        return MockObject

    def test_container_injects_dependencies_in_any_order(self):
        self.app.bind('UploadDiskDriver', UploadDiskDriver)
        assert isinstance(
            self.app.resolve(self._function_test_contract_and_annotations),
            MockObject.__class__)

    def _function_not_in_container(self, NotIn):
        return NotIn

    def test_container_raises_value_error(self):
        with pytest.raises(ContainerError):
            assert self.app.resolve(self._function_not_in_container)

    def test_container_collects_correct_objects(self):
        self.app.bind('ExceptionHook', object)
        self.app.bind('SentryExceptionHook', object)
        self.app.bind('ExceptionHandler', object)

        assert self.app.collect('*ExceptionHook') == {
            'ExceptionHook': object,
            'SentryExceptionHook': object
        }
        assert self.app.collect('Exception*') == {
            'ExceptionHook': object,
            'ExceptionHandler': object
        }
        assert self.app.collect('Sentry*Hook') == {
            'SentryExceptionHook': object
        }
        with pytest.raises(AttributeError):
            self.app.collect('Sentry')

    def test_container_collects_correct_subclasses_of_objects(self):
        self.app.bind('GetAnotherObject', GetAnotherObject)
        objects = self.app.collect(MockObject)

        assert 'GetAnotherObject' in objects
        assert 'GetObject' in objects

    def test_strict_container_raises_exception(self):
        self.app = App(strict=True)

        self.app.bind('Request', object)

        with pytest.raises(StrictContainerException):
            self.app.bind('Request', object)

    def test_override_container_does_not_override(self):
        self.app = App(override=False)

        self.app.bind('Request', 'test')
        self.app.bind('Request', 'override')
        assert self.app.make('Request') == 'test'
Example #30
0
class TestValidationProvider(unittest.TestCase):
    def setUp(self):
        from masonite.request import Request
        self.app = App()
        self.app.bind('Request', Request().load_app(self.app))
        self.provider = ValidationProvider().load_app(self.app)
        self.provider.register()
        self.app.resolve(self.provider.boot)

    def test_loaded_validator_class(self):
        self.assertIsInstance(self.app.make(Validator), Validator)

    def test_loaded_registry(self):
        self.assertTrue(self.app.make(Validator).numeric)

    def test_request_validation(self):
        request = self.app.make('Request')
        validate = self.app.make('Validator')

        request.request_variables = {'id': 1, 'name': 'Joe'}

        validated = request.validate(validate.required(['id', 'name']))

        self.assertEqual(len(validated), 0)

        validated = request.validate(validate.required(['user']))

        self.assertEqual(validated, {'user': ['The user field is required.']})

    def test_request_validation_redirects_back_with_session(self):
        wsgi = generate_wsgi()
        self.app.bind('Application', self.app)
        self.app.bind('SessionCookieDriver', SessionCookieDriver)
        self.app.bind('Environ', wsgi)

        request = self.app.make('Request')
        request.load_environ(wsgi)

        request.request_variables = {'id': 1, 'name': 'Joe'}

        errors = request.validate(required('user'))

        request.session = SessionManager(self.app).driver('cookie')
        request.key('UKLAdrye6pZG4psVRPZytukJo2-A_Zxbo0VaqR5oig8=')
        self.assertEqual(
            request.redirect('/login').with_errors(errors).redirect_url,
            '/login')
        self.assertEqual(
            request.redirect('/login').with_errors(errors).session.get(
                'errors'), {'user': ['The user field is required.']})

    def test_confirmed(self):
        validate = Validator().validate(
            {
                'password': '******',
                'password_confirmation': 'secret',
            }, confirmed(['password']))

        self.assertEqual(len(validate), 0)

        validate = Validator().validate({
            'password': '******',
        }, confirmed(['password']))

        self.assertEqual(
            validate,
            {'password': ['The password confirmation does not match.']})

        validate = Validator().validate({}, confirmed(['password']))

        self.assertEqual(
            validate,
            {'password': ['The password confirmation does not match.']})

        validate = Validator().validate(
            {
                'password': '******',
                'password_confirmation': 'foo',
            }, confirmed(['password']))

        self.assertEqual(
            validate,
            {'password': ['The password confirmation does not match.']})
Example #31
0
    def create_container(self,
                         wsgi=generate_wsgi(),
                         container=None,
                         routes=[]):
        from config import application, providers
        if not container:
            container = App(remember=False)

        container.bind('WSGI', wsgi)
        container.bind('Application', application)
        container.bind('Container', container)
        container.bind('ProvidersConfig', providers)
        container.bind('Providers', [])
        container.bind('WSGIProviders', [])
        """
        |--------------------------------------------------------------------------
        | Bind all service providers
        |--------------------------------------------------------------------------
        |
        | Let's register everything into the Service Container. Once everything is
        | in the container we can run through all the boot methods. For reasons
        | some providers don't need to execute with every request and should
        | only run once when the server is started. Providers will be ran
        | once if the wsgi attribute on a provider is False.
        |
        """

        for provider in container.make('ProvidersConfig').PROVIDERS:
            located_provider = provider()
            located_provider.load_app(container).register()
            if located_provider.wsgi:
                container.make('WSGIProviders').append(located_provider)
            else:
                container.make('Providers').append(located_provider)

        for provider in container.make('Providers'):
            container.resolve(provider.boot)
        """
        |--------------------------------------------------------------------------
        | Startup the Service Container
        |--------------------------------------------------------------------------
        |
        | Instantiate the Service Container so we can bind classes into it and
        | bind the environ variable that is created by the WSGI server into
        | the container.
        |
        """

        container.bind('Environ', wsgi)
        """
        |--------------------------------------------------------------------------
        | Execute All Service Providers
        |--------------------------------------------------------------------------
        |
        | Run all service provider boot methods if the wsgi attribute is true.
        |
        """

        if routes:
            container.bind('WebRoutes', routes)

        for provider in container.make('WSGIProviders'):
            container.resolve(provider.boot)

        self.container = container
        return self