def test_driver_sends_mail(): app = App() app.bind('Test', object) app.bind('MailConfig', mail) app.bind('MailSmtpDriver', MailSmtpDriver)
class TestMailManager: def setup_method(self): self.app = App() self.app.bind('Test', object) self.app.bind('MailSmtpDriver', object) self.app.bind('MailConfig', mail) def test_mail_manager_loads_container(self): mailManager = MailManager() assert mailManager.load_container(self.app) 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 = MailManager(self.app) def test_manager_sets_driver(self): self.app.bind('MailMailtrapDriver', Mailgun) mailManager = 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 = 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_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_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)
class TestView(unittest.TestCase): def setUp(self): self.container = App() view = View(self.container) self.container.bind('View', view.render) self.container.bind('ViewClass', view) def test_view_extends_dictionary(self): view = self.container.make('View') self.assertEqual( view('test', { 'test': 'test' }).rendered_template, 'test') def test_view_exists(self): view = self.container.make('ViewClass') assert view.exists('index') self.assertFalse(view.exists('not_available')) def test_view_render_does_not_keep_previous_variables(self): view = self.container.make('ViewClass') view.render('test', {'var1': 'var1'}) view.render('test', {'var2': 'var2'}) self.assertNotIn('var1', view.dictionary) self.assertIn('var2', view.dictionary) def test_global_view_exists(self): view = self.container.make('ViewClass') self.assertTrue(view.exists('/resources/templates/index')) self.assertFalse(view.exists('/resources/templates/not_available')) def test_view_gets_global_template(self): view = self.container.make('View') self.assertEqual( view('/templates/test', { 'test': 'test' }).rendered_template, 'test') def test_view_extends_without_dictionary_parameters(self): view = self.container.make('ViewClass') view.share({'test': 'test'}) view = self.container.make('View') self.assertEqual(view('test').rendered_template, 'test') def test_render_from_container_as_view_class(self): self.container.make('ViewClass').share({'test': 'test'}) view = self.container.make('View') self.assertEqual(view('test').rendered_template, 'test') def test_composers(self): self.container.make('ViewClass').composer('test', {'test': 'test'}) view = self.container.make('View') self.assertEqual( self.container.make('ViewClass').composers, {'test': { 'test': 'test' }}) self.assertEqual(view('test').rendered_template, 'test') def test_composers_load_all_views_with_astericks(self): self.container.make('ViewClass').composer('*', {'test': 'test'}) self.assertEqual( self.container.make('ViewClass').composers, {'*': { 'test': 'test' }}) view = self.container.make('View') self.assertEqual(view('test').rendered_template, 'test') def test_composers_with_wildcard_base_view(self): self.container.make('ViewClass').composer('mail*', {'to': 'test_user'}) self.assertEqual( self.container.make('ViewClass').composers, {'mail*': { 'to': 'test_user' }}) view = self.container.make('View') self.assertIn('test_user', view('mail/welcome').rendered_template) def test_composers_with_wildcard_base_view_route(self): self.container.make('ViewClass').composer('mail*', {'to': 'test_user'}) self.assertEqual( self.container.make('ViewClass').composers, {'mail*': { 'to': 'test_user' }}) view = self.container.make('View') self.assertIn('test_user', view('mail/welcome').rendered_template) def test_render_deep_in_file_structure_with_package_loader(self): self.container.make('ViewClass').add_environment('storage') view = self.container.make('View') self.assertEqual( view('/templates/tests/test', { 'test': 'testing' }).rendered_template, 'testing') def test_composers_with_wildcard_lower_directory_view(self): self.container.make('ViewClass').composer('mail/welcome*', {'to': 'test_user'}) self.assertEqual( self.container.make('ViewClass').composers, {'mail/welcome*': { 'to': 'test_user' }}) view = self.container.make('View') self.assertIn('test_user', view('mail/welcome').rendered_template) def test_composers_with_wildcard_lower_directory_view_and_incorrect_shortend_wildcard( self): self.container.make('ViewClass').composer('mail/wel*', {'to': 'test_user'}) self.assertEqual( self.container.make('ViewClass').composers, {'mail/wel*': { 'to': 'test_user' }}) view = self.container.make('View') assert 'test_user' not in view('mail/welcome').rendered_template def test_composers_load_all_views_with_list(self): self.container.make('ViewClass').composer(['home', 'test'], {'test': 'test'}) self.assertEqual( self.container.make('ViewClass').composers, { 'home': { 'test': 'test' }, 'test': { 'test': 'test' } }) view = self.container.make('View') self.assertEqual(view('test').rendered_template, 'test') def test_view_share_updates_dictionary_not_overwrite(self): viewclass = self.container.make('ViewClass') viewclass.share({'test1': 'test1'}) viewclass.share({'test2': 'test2'}) self.assertEqual(viewclass._shared, { 'test1': 'test1', 'test2': 'test2' }) viewclass.render('test', {'var1': 'var1'}) self.assertEqual(viewclass.dictionary, { 'test1': 'test1', 'test2': 'test2', 'var1': 'var1' }) def test_adding_environment(self): viewclass = self.container.make('ViewClass') viewclass.add_environment('storage', loader=FileSystemLoader) self.assertEqual( viewclass.render('test_location', { 'test': 'testing' }).rendered_template, 'testing') def test_view_throws_exception_without_cache_binding(self): view = self.container.make('View') with self.assertRaises(RequiredContainerBindingNotFound): view('test_cache').cache_for('5', 'seconds') def test_view_can_add_custom_filters(self): view = self.container.make('ViewClass') view.filter('slug', self._filter_slug) self.assertEqual(view._filters, {'slug': self._filter_slug}) self.assertEqual( view.render('filter', { 'test': 'test slug' }).rendered_template, 'test-slug') @staticmethod def _filter_slug(item): return item.replace(' ', '-') def test_view_cache_caches_files(self): self.container.bind('CacheConfig', cache) self.container.bind('CacheDiskDriver', CacheDiskDriver) self.container.bind('CacheManager', CacheManager(self.container)) self.container.bind('Application', self.container) self.container.bind('Cache', self.container.make('CacheManager').driver('disk')) view = self.container.make('View') self.assertEqual( view('test_cache', { 'test': 'test' }).cache_for(1, 'second').rendered_template, 'test') self.assertEqual( open(glob.glob('bootstrap/cache/test_cache:*')[0]).read(), 'test') time.sleep(2) self.assertEqual( view('test_cache', { 'test': 'macho' }).cache_for(5, 'seconds').rendered_template, 'macho') time.sleep(2) self.assertEqual( open(glob.glob('bootstrap/cache/test_cache:*')[0]).read(), 'macho') self.assertEqual( view('test_cache', { 'test': 'macho' }).cache_for(1, 'second').rendered_template, 'macho') time.sleep(1) self.assertEqual( open(glob.glob('bootstrap/cache/test_cache:*')[0]).read(), 'macho') self.assertEqual( view('test_cache', { 'test': 'macho' }).cache_for('1', 'second').rendered_template, 'macho') def test_cache_throws_exception_with_incorrect_cache_type(self): self.container.bind('CacheConfig', cache) self.container.bind('CacheDiskDriver', CacheDiskDriver) self.container.bind('CacheManager', CacheManager(self.container)) self.container.bind('Application', self.container) self.container.bind('Cache', self.container.make('CacheManager').driver('disk')) view = self.container.make('View') with self.assertRaises(ValueError): view('test_exception', {'test': 'test'}).cache_for(1, 'monthss') def test_view_can_change_template_splice(self): self.container.make('ViewClass').set_splice('.') view = self.container.make('View') self.container.make('ViewClass').composer('mail/welcome', {'test': 'test'}) self.container.make('ViewClass').share({'test': 'John'}) self.assertIn('John', view('mail.welcome', { 'to': 'John' }).rendered_template) self.assertEqual( view('mail.composers', { 'test': 'John' }).rendered_template, 'John') self.assertEqual(view('mail.share').rendered_template, 'John') self.assertIn('John', view('mail/welcome', { 'to': 'John' }).rendered_template) self.container.make('ViewClass').set_splice('@') self.assertIn('John', view('mail@welcome', { 'to': 'John' }).rendered_template) self.assertIn( 'John', view('mail@composers', { 'test': 'John' }).rendered_template) self.assertIn('John', view('mail/welcome', { 'to': 'John' }).rendered_template) def test_can_add_tests_to_view(self): view = self.container.make('ViewClass') view.test('admin', self._is_admin) self.assertEqual(view._tests, {'admin': self._is_admin}) user = MockAdminUser self.assertEqual( view.render('admin_test', { 'user': user }).rendered_template, 'True') user.admin = 0 self.assertEqual( view.render('admin_test', { 'user': user }).rendered_template, 'False') def _is_admin(self, obj): return obj.admin == 1 def test_can_render_pubjs(self): view = self.container.make('ViewClass') view.add_extension('pypugjs.ext.jinja.PyPugJSExtension') self.assertEqual( view._jinja_extensions, ['jinja2.ext.loopcontrols', 'pypugjs.ext.jinja.PyPugJSExtension']) self.assertEqual( view.render('pug/hello.pug', { 'name': 'Joe' }).rendered_template, '<p>hello Joe</p>') def test_throws_exception_on_incorrect_type(self): view = self.container.make('ViewClass') with self.assertRaises(ViewException): assert view.render('test', {'', ''}) def test_can_use_dot_templates(self): view = self.container.make('ViewClass') self.assertEqual( view.render('mail.share', { 'test': 'test' }).rendered_template, 'test') def test_can_use_at_line_statements(self): view = self.container.make('ViewClass') self.assertIn( 'test this string', view.render('line-statements', { 'test': 'test this string' }).rendered_template)
class TestNotifiable: def setup_method(self): self.app = App() self.app.bind('Container', self.app) self.app.bind('ViewClass', View(self.app)) # self.app.make('ViewClass').add_environment('notifications/snippets') self.app.bind('View', View(self.app).render) self.app.bind('MailConfig', MockMailConfig) self.app.bind('MailTerminalDriver', MailTerminalDriver) self.app.bind('MailMailgunDriver', MailMailgunDriver) self.app.bind('MailManager', MailManager(self.app)) self.app.bind( 'Mail', self.app.make('MailManager').driver(MockMailConfig.DRIVER)) # Setup and test Queueing self.app.bind('QueueAsyncDriver', QueueAsyncDriver) self.app.bind('QueueConfig', queue) self.app.bind('Container', self.app) self.app.bind('QueueManager', QueueManager(self.app)) self.app.swap(Queue, self.app.make('QueueManager').driver('async')) self.notification = WelcomeNotification self.notify = Notify(self.app) def test_notification_sends_mail(self): assert self.notify.mail(WelcomeNotification, to='*****@*****.**') is None def test_notification_sends_slack(self): assert self.notify.slack(WelcomeNotification) is None def test_notify_returns_called_notification(self): self.notify.mail(WelcomeNotification) assert self.notify.called_notifications def test_notification_sets_protected_members(self): assert self.notify.mail(WelcomeNotification, to='*****@*****.**') is None assert self.notify.called_notifications[0]._to == '*****@*****.**' def test_mail_notification_appends_template(self): assert self.notify.mail(WelcomeNotification, to='*****@*****.**') is None assert 'We greatly value your service!' in self.notify.called_notifications[ 0].template def test_mail_notification_should_queue(self): assert self.notify.mail(ShouldQueueWelcomeNotification, to='*****@*****.**') is None def test_can_send_with_via_method(self): notifications = self.notify.via('mail').send( ShouldQueueWelcomeNotification, to="*****@*****.**").called_notifications assert isinstance(notifications[0], ShouldQueueWelcomeNotification)
""" First Entry For The WSGI Server """ from masonite.app import App from bootstrap.start import app from config import application, 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', app) 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
class TestRouteProvider: def setup_method(self): self.app = App() self.app.bind('Environ', generate_wsgi()) self.app.bind('WebRoutes', []) self.app.bind('Route', Route(self.app.make('Environ'))) self.app.bind('Request', Request(self.app.make('Environ')).load_app(self.app)) self.app.bind('Headers', []) self.app.bind('HttpMiddleware', []) view = View(self.app) self.app.bind('View', view.render) self.provider = RouteProvider() self.provider.app = self.app def test_controller_that_returns_a_view(self): self.app.make('Route').url = '/view' self.app.bind('WebRoutes', [get('/view', ControllerTest.test)]) self.provider.boot( self.app.make('WebRoutes'), self.app.make('Route'), self.app.make('Request'), self.app.make('Environ'), self.app.make('Headers'), ) assert self.app.make('Response') == 'test' def test_controller_does_not_return_with_non_matching_end_slash(self): self.app.make('Route').url = '/view' self.app.bind('WebRoutes', [get('/view/', ControllerTest.returns_a_view)]) self.provider.boot( self.app.make('WebRoutes'), self.app.make('Route'), self.app.make('Request'), self.app.make('Environ'), self.app.make('Headers'), ) assert self.app.make('Response') == 'Route not found. Error 404' def test_provider_runs_through_routes(self): self.app.make('Route').url = '/test' self.app.bind('WebRoutes', [get('/test', ControllerTest.show)]) self.provider.boot( self.app.make('WebRoutes'), self.app.make('Route'), self.app.make('Request'), self.app.make('Environ'), self.app.make('Headers'), ) assert self.app.make('Request').header('Content-Type') == 'text/html; charset=utf-8' def test_sets_request_params(self): self.app.make('Route').url = '/test/1' self.app.bind('WebRoutes', [get('/test/@id', ControllerTest.show)]) self.provider.boot( self.app.make('WebRoutes'), self.app.make('Route'), self.app.make('Request'), self.app.make('Environ'), self.app.make('Headers'), ) assert self.app.make('Request').param('id') == '1' def test_url_with_dots_finds_route(self): self.app.make('Route').url = '/test/user.endpoint' self.app.bind('WebRoutes', [get('/test/@endpoint', ControllerTest.show)]) self.provider.boot( self.app.make('WebRoutes'), self.app.make('Route'), self.app.make('Request'), self.app.make('Environ'), self.app.make('Headers'), ) assert self.app.make('Request').param('endpoint') == 'user.endpoint' def test_url_with_dashes_finds_route(self): self.app.make('Route').url = '/test/user-endpoint' self.app.bind('WebRoutes', [get('/test/@endpoint', ControllerTest.show)]) self.provider.boot( self.app.make('WebRoutes'), self.app.make('Route'), self.app.make('Request'), self.app.make('Environ'), self.app.make('Headers'), ) assert self.app.make('Request').param('endpoint') == 'user-endpoint' def test_route_subdomain_ignores_routes(self): self.app.make('Route').url = '/test' self.app.make('Environ')['HTTP_HOST'] = 'subb.domain.com' self.app.bind('WebRoutes', [get('/test', ControllerTest.show)]) request = self.app.make('Request') request.activate_subdomains() self.provider.boot( self.app.make('WebRoutes'), self.app.make('Route'), request, self.app.make('Environ'), self.app.make('Headers'), ) assert self.app.make('Response') == 'Route not found. Error 404' def test_controller_returns_json_response_for_dict(self): self.app.make('Route').url = '/view' self.app.bind('WebRoutes', [get('/view', ControllerTest.returns_a_dict)]) self.provider.boot( self.app.make('WebRoutes'), self.app.make('Route'), self.app.make('Request'), self.app.make('Environ'), self.app.make('Headers'), ) assert self.app.make('Response') == '{"id": 1}' assert self.app.make('Request').header('Content-Type') == 'application/json; charset=utf-8' def test_route_runs_str_middleware(self): self.app.make('Route').url = '/view' self.app.bind('RouteMiddleware', middleware.ROUTE_MIDDLEWARE) self.app.bind('WebRoutes', [ get('/view', ControllerTest.returns_a_dict).middleware('test') ] ) self.provider.boot( self.app.make('WebRoutes'), self.app.make('Route'), self.app.make('Request'), self.app.make('Environ'), self.app.make('Headers'), ) assert self.app.make('Request').path == 'test/middleware/before/ran' def test_route_runs_middleware_with_list(self): self.app.make('Route').url = '/view' self.app.bind('RouteMiddleware', middleware.ROUTE_MIDDLEWARE) self.app.bind('WebRoutes', [ get('/view', ControllerTest.returns_a_dict).middleware('middleware.test') ] ) self.provider.boot( self.app.make('WebRoutes'), self.app.make('Route'), self.app.make('Request'), self.app.make('Environ'), self.app.make('Headers'), ) assert self.app.make('Request').path == 'test/middleware/before/ran' assert self.app.make('Request').attribute == True
"""First Entry For The WSGI Server.""" from masonite.app import App from bootstrap.start import app from config import application, 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', app) 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)
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'
def setup_method(self): self.app = App() self.app.bind('Request', Request(None)) self.app.bind('MockObject', MockObject) self.app.bind('GetObject', GetObject)
def setup_method(self): self.app = App()
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'
class TestQueueDrivers(unittest.TestCase): def setUp(self): self.app = App() self.app.bind('QueueAsyncDriver', QueueAsyncDriver) self.app.bind('QueueAmqpDriver', QueueAmqpDriver) self.app.bind('QueueDatabaseDriver', QueueDatabaseDriver) self.app.bind('QueueConfig', queue) self.app.bind('Queueable', Queueable) self.app.bind('Container', self.app) self.app.bind('QueueManager', QueueManager(self.app)) self.app.bind('Queue', QueueManager(self.app).driver(self.app.make('QueueConfig').DRIVER)) self.drivers = ['async'] self.modes = ['threading', 'multiprocess'] if env('RUN_AMQP'): self.drivers.append('amqp') if env('RUN_QUEUE_DATABASE'): self.drivers.append('database') def test_async_driver_pushes_to_queue(self): for driver in self.drivers + ['database']: self.assertIsNone(self.app.make('QueueManager').driver(driver).push(Job), None) def test_async_driver_can_run_any_callback_method(self): for driver in self.drivers: self.assertIsNone(self.app.make('QueueManager').driver(driver).push(Random, callback="send"), None) def test_async_driver_can_run_any_method(self): for driver in self.drivers: self.assertIsNone(self.app.make('QueueManager').driver(driver).push(Random().send), None) def test_should_return_default_driver(self): self.assertIsInstance(self.app.make('Queue'), QueueAsyncDriver) self.assertIsInstance(self.app.make('Queue').driver('async'), QueueAsyncDriver) self.assertIsInstance(self.app.make('Queue').driver('default'), QueueAsyncDriver) def test_async_driver_modes(self): for mode in self.modes: self.assertIsNone(self.app.make('QueueManager').driver('async').push(Job, mode=mode), None) def test_async_driver_finds_mode(self): self.assertIsNone(self.app.make('QueueManager').driver('async').push(Job), None) def test_handle_unrecognized_mode(self): with self.assertRaises(QueueException): self.app.make('QueueManager').driver('async').push(Job, mode='blah') def test_async_driver_specify_workers(self): for mode in self.modes: self.assertIsNone(self.app.make('QueueManager').driver('async').push(Job, mode=mode, workers=2), None) def test_driver_can_wait(self): for driver in self.drivers: self.assertIsNone(self.app.make('QueueManager').driver(driver).push(Job, wait='10 seconds'), None) def test_driver_can_fail(self): for driver in self.drivers: self.assertIsNone(self.app.make('QueueManager').driver(driver).push(FailJob), None) def test_workers_are_nonnegative(self): with self.assertRaises(QueueException): for mode in self.modes: self.assertIsNone(self.app.make('QueueManager').driver('async').push(Job, mode=mode, workers=-1))
def test_controller_loads_app(): app = App() app.bind('object', object) controller = Controller().load_app(app) assert controller.app.providers == {'object': object}
class TestUploadManager: def setup_method(self): self.app = App() self.app.bind('Test', object) self.app.bind('StorageConfig', storage) self.app.bind('UploadDiskDriver', UploadDiskDriver) self.app.bind('Application', application) self.app.bind('UploadManager', UploadManager().load_container(self.app)) def test_upload_manager_grabs_drivers(self): assert isinstance( self.app.make('UploadManager').driver('disk'), UploadDiskDriver) def test_upload_manager_grabs_drivers_with_a_class(self): assert isinstance( self.app.make('UploadManager').driver(UploadDiskDriver), UploadDiskDriver) def test_upload_manager_throws_error_with_incorrect_file_type(self): with pytest.raises(UnacceptableDriverType): self.app.make('UploadManager').driver(static) def test_upload_manager_raises_driver_not_found_error(self): self.app = App() self.app.bind('Test', object) self.app.bind('StorageConfig', storage) with pytest.raises(DriverNotFound): assert self.app.bind('UploadManager', UploadManager().load_container(self.app)) def test_upload_manager_switches_drivers(self): self.app.bind('UploadTestDriver', UploadDiskDriver) assert isinstance( self.app.make('UploadManager').driver('disk'), UploadDiskDriver) assert isinstance( self.app.make('UploadManager').driver('test'), UploadDiskDriver) def test_upload_file(self): """ This test is responsible for checking if you upload a file correctly. """ assert UploadManager(self.app).driver('disk').store(ImageMock()) def test_upload_file_with_location(self): """ This test is responsible for checking if you upload a file correctly. """ assert UploadManager(self.app).driver('disk').store( ImageMock(), 'uploads') def test_upload_file_with_location_from_driver(self): """ This test is responsible for checking if you upload a file correctly. """ assert UploadManager(self.app).driver('disk').store( ImageMock(), 'disk.uploading') def test_upload_manage_accept_files(self): """ This test is responsible for checking if you upload a file correctly with a valid extension. """ assert UploadManager(self.app).driver('disk').accept( 'jpg', 'png').store(ImageMock()) def test_upload_manage_accept_files_error(self): """ This test should return an error because it is an invalid extension. """ with pytest.raises(FileTypeException): UploadManager(self.app).driver('disk').accept('png').store( ImageMock()) def test_upload_store_prepend(self): assert self.app.make('UploadManager').driver('disk').store_prepend( ImageMock(), 'hey') == 'heytest.jpg'
from masonite.app import App from bootstrap.start import app from config import application, 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', app) 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
def test_app_makes(): app = App() app.bind('Request', REQUEST) assert app.make('Request').cookies == []
class TestAsyncDriver: def setup_method(self): self.app = App() self.app.bind('QueueAsyncDriver', QueueAsyncDriver) self.app.bind('QueueAmqpDriver', QueueAmqpDriver) self.app.bind('QueueConfig', queue) self.app.bind('Queueable', Queueable) self.app.bind('Container', self.app) self.app.bind('QueueManager', QueueManager(self.app)) self.app.bind( 'Queue', QueueManager(self.app).driver(self.app.make('QueueConfig').DRIVER)) self.drivers = ['async'] if env('RUN_AMQP'): self.drivers.append('amqp') def test_async_driver_pushes_to_queue(self): for driver in self.drivers: assert self.app.make('QueueManager').driver(driver).push( Job) is None def test_async_driver_can_run_any_callback_method(self): for driver in self.drivers: assert self.app.make('QueueManager').driver(driver).push( Random, callback="send") is None def test_async_driver_can_run_any_method(self): for driver in self.drivers: assert self.app.make('QueueManager').driver(driver).push( Random().send) is None def test_should_return_default_driver(self): assert isinstance(self.app.make('Queue'), QueueAsyncDriver) assert isinstance( self.app.make('Queue').driver('async'), QueueAsyncDriver) assert isinstance( self.app.make('Queue').driver('default'), QueueAsyncDriver)
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 TestResponseProvider: def setup_method(self): self.app = App() self.provider = StartResponseProvider() self.app.bind('Response', None) self.app.bind('Request', Request(generate_wsgi()).load_app(self.app)) self.app.bind('Headers', []) self.provider.app = self.app def test_response_boot_throws_response_exception(self): with pytest.raises(ResponseError): self.provider.boot(self.app.make('Request'), self.app.make('Response'), self.app.make('Headers')) def test_response_encodes_header_response_to_bytes(self): encoded_bytes = bytes('test', 'utf-8') self.app.bind('Response', 'test') self.app.bind('StatusCode', '200 OK') self.provider.boot(self.app.make('Request'), self.app.make('Response'), self.app.make('Headers')) assert self.app.make('Headers')[0] == ("Content-Length", str(len(encoded_bytes))) def test_redirect_sets_redirection_headers(self): self.app.make('Request').redirect_url = '/redirection' self.provider.boot(self.app.make('Request'), self.app.make('Response'), self.app.make('Headers')) assert self.app.make('StatusCode') == '302 OK' assert ('Location', '/redirection') in self.app.make('Headers')
def create_container(self): container = App() container.bind('WSGI', object) container.bind('Application', application) """ |-------------------------------------------------------------------------- | 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('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) """ |-------------------------------------------------------------------------- | 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_REQUEST) """ |-------------------------------------------------------------------------- | Execute All Service Providers |-------------------------------------------------------------------------- | | Run all service provider boot methods if the wsgi attribute is true. | """ for provider in container.make('Application').PROVIDERS: located_provider = locate(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 TestRouteProvider: def setup_method(self): self.app = App() self.app.bind('Container', self.app) self.app.bind('Environ', generate_wsgi()) self.app.bind('Application', application) self.app.bind('WebRoutes', []) self.app.bind('Route', Route(self.app.make('Environ'))) self.app.bind('Request', Request( self.app.make('Environ')).load_app(self.app)) self.app.simple(Response(self.app)) self.app.bind('StatusCode', '404 Not Found') self.app.bind('HttpMiddleware', middleware.HTTP_MIDDLEWARE) view = View(self.app) self.app.bind('ViewClass', view) self.app.bind('View', view.render) self.provider = RouteProvider() self.provider.app = self.app def test_controller_that_returns_a_view(self): self.app.make('Route').url = '/view' self.app.bind('WebRoutes', [get('/view', ControllerTest.test)]) self.provider.boot( self.app.make('Route'), self.app.make('Request'), self.app.make(Response) ) assert self.app.make('Response') == 'test' self.app.make('Route').url = '/view/' self.app.bind('WebRoutes', [get('/view', ControllerTest.test)]) self.provider.boot( self.app.make('Route'), self.app.make('Request'), self.app.make(Response) ) # assert self.app.make('Response') == 'test' def test_controller_that_return_a_view_with_trailing_slash(self): self.app.make('Route').url = '/view/' self.app.bind('WebRoutes', [get('/view/', ControllerTest.test)]) self.provider.boot( self.app.make('Route'), self.app.make('Request'), self.app.make(Response) ) assert self.app.make('Response') == 'test' self.app.make('Route').url = '/view' self.app.bind('WebRoutes', [get('/view/', ControllerTest.test)]) print(self.app.providers) self.provider.boot( self.app.make('Route'), self.app.make('Request'), self.app.make(Response) ) assert self.app.make('Response') == 'test' def test_match_route_returns_controller(self): self.app.make('Route').url = '/view' self.app.bind( 'WebRoutes', [Match(['GET', 'POST']).route('/view', ControllerTest.returns_a_view)]) self.provider.boot( self.app.make('Route'), self.app.make('Request'), self.app.make(Response) ) assert self.app.make('Response') == 'hey' def test_provider_runs_through_routes(self): self.app.make('Route').url = '/test' self.app.bind('WebRoutes', [get('/test', ControllerTest.test)]) self.provider.boot( self.app.make('Route'), self.app.make('Request'), self.app.make(Response) ) assert self.app.make('Request').header( 'Content-Type') == 'text/html; charset=utf-8' def test_sets_request_params(self): self.app.make('Route').url = '/test/1' self.app.bind('WebRoutes', [get('/test/@id', ControllerTest.test)]) self.provider.boot( self.app.make('Route'), self.app.make('Request'), self.app.make(Response) ) assert self.app.make('Request').param('id') == '1' def test_url_with_dots_finds_route(self): self.app.make('Route').url = '/test/user.endpoint' self.app.bind( 'WebRoutes', [get('/test/@endpoint', ControllerTest.test)]) self.provider.boot( self.app.make('Route'), self.app.make('Request'), self.app.make(Response) ) assert self.app.make('Request').param('endpoint') == 'user.endpoint' def test_view_returns_with_route_view(self): self.app.make('Route').url = '/test/route' self.app.bind('WebRoutes', [ Get().view('/test/route', 'test', {'test': 'testing'}) ]) self.provider.boot( self.app.make('Route'), self.app.make('Request'), self.app.make(Response) ) assert self.app.make('Response') == 'testing' def test_url_with_dashes_finds_route(self): self.app.make('Route').url = '/test/user-endpoint' self.app.bind( 'WebRoutes', [get('/test/@endpoint', ControllerTest.test)]) self.provider.boot( self.app.make('Route'), self.app.make('Request'), self.app.make(Response) ) assert self.app.make('Request').param('endpoint') == 'user-endpoint' def test_param_returns_param(self): self.app.make('Route').url = '/test/1' self.app.bind('WebRoutes', [get('/test/@id', ControllerTest.param)]) self.provider.boot( self.app.make('Route'), self.app.make('Request'), self.app.make(Response) ) assert self.app.make('Response') == '1' def test_custom_route_compiler_returns_param(self): self.app.make('Route').url = '/test/1' self.app.make('Route').compile('signed', r'([\w.-]+)') self.app.bind('WebRoutes', [get('/test/@id:signed', ControllerTest.param)]) self.provider.boot( self.app.make('Route'), self.app.make('Request'), self.app.make(Response) ) assert self.app.make('Response') == '1' def test_route_subdomain_ignores_routes(self): self.app.make('Route').url = '/test' self.app.make('Environ')['HTTP_HOST'] = 'subb.domain.com' self.app.bind('WebRoutes', [get('/test', ControllerTest.test)]) request = self.app.make('Request') request.activate_subdomains() self.provider.boot( self.app.make('Route'), self.app.make('Request'), self.app.make(Response) ) assert self.app.make('Response') == 'Route not found. Error 404' def test_controller_returns_json_response_for_dict(self): self.app.make('Route').url = '/view' self.app.bind( 'WebRoutes', [get('/view', ControllerTest.returns_a_dict)]) self.provider.boot( self.app.make('Route'), self.app.make('Request'), self.app.make(Response) ) assert self.app.make('Request').header( 'Content-Type') == 'application/json; charset=utf-8' def test_route_runs_str_middleware(self): self.app.make('Route').url = '/view' self.app.bind('RouteMiddleware', middleware.ROUTE_MIDDLEWARE) self.app.bind('WebRoutes', [ get('/view', ControllerTest.returns_a_dict).middleware('test') ] ) self.provider.boot( self.app.make('Route'), self.app.make('Request'), self.app.make(Response) ) assert self.app.make('Request').path == 'test/middleware/before/ran' def test_route_runs_middleware_with_list(self): self.app.make('Route').url = '/view' self.app.bind('RouteMiddleware', middleware.ROUTE_MIDDLEWARE) self.app.bind('WebRoutes', [ get('/view', ControllerTest.returns_a_dict).middleware('middleware.test') ] ) self.provider.boot( self.app.make('Route'), self.app.make('Request'), self.app.make(Response) ) assert self.app.make('Request').path == 'test/middleware/before/ran' assert self.app.make('Request').attribute == True
class TestView: def setup_method(self): self.container = App() view = View(self.container) self.container.bind('View', view.render) self.container.bind('ViewClass', view) def test_view_compiles_jinja(self): assert view('test', {'test': 'test'}) == 'test' def test_view_extends_dictionary(self): view = self.container.make('View') assert view('test', {'test': 'test'}).rendered_template == 'test' def test_view_exists(self): view = self.container.make('ViewClass') assert view.exists('index') assert view.exists('not_available') is False def test_global_view_exists(self): view = self.container.make('ViewClass') assert view.exists('/resources/templates/index') assert view.exists('/resources/templates/not_available') is False def test_view_gets_global_template(self): view = self.container.make('View') assert view('/storage/test', { 'test': 'test' }).rendered_template == 'test' assert view('/storage/static/test', { 'test': 'test' }).rendered_template == 'test' def test_view_extends_without_dictionary_parameters(self): view = self.container.make('ViewClass') view.share({'test': 'test'}) view = self.container.make('View') assert view('test').rendered_template == 'test' def test_render_from_container_as_view_class(self): self.container.make('ViewClass').share({'test': 'test'}) view = self.container.make('View') assert view('test').rendered_template == 'test' def test_composers(self): self.container.make('ViewClass').composer('test', {'test': 'test'}) view = self.container.make('View') assert self.container.make('ViewClass').composers == { 'test': { 'test': 'test' } } assert view('test').rendered_template == 'test' def test_composers_load_all_views_with_astericks(self): self.container.make('ViewClass').composer('*', {'test': 'test'}) assert self.container.make('ViewClass').composers == { '*': { 'test': 'test' } } view = self.container.make('View') assert view('test').rendered_template == 'test' def test_composers_with_wildcard_base_view(self): self.container.make('ViewClass').composer('mail*', {'to': 'test_user'}) assert self.container.make('ViewClass').composers == { 'mail*': { 'to': 'test_user' } } view = self.container.make('View') assert 'test_user' in view('mail/welcome').rendered_template def test_composers_with_wildcard_base_view_route(self): self.container.make('ViewClass').composer('mail*', {'to': 'test_user'}) assert self.container.make('ViewClass').composers == { 'mail*': { 'to': 'test_user' } } view = self.container.make('View') assert 'test_user' in view('mail/welcome').rendered_template def test_render_deep_in_file_structure_with_package_loader(self): self.container.make('ViewClass').add_environment('storage') view = self.container.make('View') assert view('/storage/templates/tests/test', { 'test': 'testing' }).rendered_template == 'testing' def test_composers_with_wildcard_lower_directory_view(self): self.container.make('ViewClass').composer('mail/welcome*', {'to': 'test_user'}) assert self.container.make('ViewClass').composers == { 'mail/welcome*': { 'to': 'test_user' } } view = self.container.make('View') assert 'test_user' in view('mail/welcome').rendered_template def test_composers_with_wildcard_lower_directory_view_and_incorrect_shortend_wildcard( self): self.container.make('ViewClass').composer('mail/wel*', {'to': 'test_user'}) assert self.container.make('ViewClass').composers == { 'mail/wel*': { 'to': 'test_user' } } view = self.container.make('View') assert 'test_user' not in view('mail/welcome').rendered_template def test_composers_load_all_views_with_list(self): self.container.make('ViewClass').composer(['home', 'test'], {'test': 'test'}) assert self.container.make('ViewClass').composers == { 'home': { 'test': 'test' }, 'test': { 'test': 'test' } } view = self.container.make('View') assert view('test').rendered_template == 'test' def test_view_share_updates_dictionary_not_overwrite(self): viewclass = self.container.make('ViewClass') viewclass.share({'test1': 'test1'}) viewclass.share({'test2': 'test2'}) assert viewclass.dictionary == {'test1': 'test1', 'test2': 'test2'} def test_adding_environment(self): viewclass = self.container.make('ViewClass') viewclass.add_environment('storage', loader=FileSystemLoader) assert viewclass.render('test_location', { 'test': 'testing' }).rendered_template == 'testing' def test_view_throws_exception_without_cache_binding(self): view = self.container.make('View') with pytest.raises(RequiredContainerBindingNotFound): view('test_cache').cache_for('5', 'seconds') def test_view_can_add_custom_filters(self): view = self.container.make('ViewClass') view.filter('slug', self._filter_slug) assert view._filters == {'slug': self._filter_slug} assert view.render('filter', { 'test': 'test slug' }).rendered_template == 'test-slug' @staticmethod def _filter_slug(item): return item.replace(' ', '-') def test_view_cache_caches_files(self): self.container.bind('CacheConfig', cache) self.container.bind('CacheDiskDriver', CacheDiskDriver) self.container.bind('CacheManager', CacheManager(self.container)) self.container.bind('Application', self.container) self.container.bind('Cache', self.container.make('CacheManager').driver('disk')) view = self.container.make('View') assert view('test_cache', { 'test': 'test' }).cache_for(1, 'second').rendered_template == 'test' assert open( glob.glob('bootstrap/cache/test_cache:*')[0]).read() == 'test' time.sleep(2) assert view('test_cache', { 'test': 'macho' }).cache_for(5, 'seconds').rendered_template == 'macho' time.sleep(2) assert open( glob.glob('bootstrap/cache/test_cache:*')[0]).read() == 'macho' assert view('test_cache', { 'test': 'macho' }).cache_for(1, 'second').rendered_template == 'macho' time.sleep(1) assert open( glob.glob('bootstrap/cache/test_cache:*')[0]).read() == 'macho' assert view('test_cache', { 'test': 'macho' }).cache_for('1', 'second').rendered_template == 'macho' def test_cache_throws_exception_with_incorrect_cache_type(self): self.container.bind('CacheConfig', cache) self.container.bind('CacheDiskDriver', CacheDiskDriver) self.container.bind('CacheManager', CacheManager(self.container)) self.container.bind('Application', self.container) self.container.bind('Cache', self.container.make('CacheManager').driver('disk')) view = self.container.make('View') with pytest.raises(ValueError): view('test_exception', {'test': 'test'}).cache_for(1, 'monthss')
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('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 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
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 setUp(self): self.app = App() self.view = View(self.app) self.request = Request(generate_wsgi()).load_app(self.app) self.provider = HelpersProvider() self.provider.load_app(self.app).boot(self.view, self.request)
"""First Entry For The WSGI Server.""" from masonite.app import App from bootstrap.start import app from masonite.helpers import config """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", app) 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 config("providers.providers"): located_provider = provider() located_provider.load_app(container).register() if located_provider.wsgi: container.make("WSGIProviders").append(located_provider)
def setup_method(self): self.app = App() self.app.bind('Test', object) self.app.bind('MailSmtpDriver', object) self.app.bind('MailConfig', mail)
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
def setUp(self): self.container = App() view = View(self.container) self.container.bind('View', view.render) self.container.bind('ViewClass', view)
class TestCache(unittest.TestCase): def setUp(self): self.app = App() self.app.bind('CacheConfig', cache) self.app.bind('CacheDiskDriver', CacheDiskDriver) self.app.bind('CacheRedisDriver', CacheRedisDriver) self.app.bind('CacheManager', CacheManager(self.app)) self.app.bind('Application', self.app) self.app.bind('Cache', self.app.make('CacheManager').driver('disk')) self.drivers = ['disk'] if os.environ.get('REDIS_CACHE_DRIVER'): self.drivers.append('redis') def test_driver_disk_cache_store_for(self): for driver in self.drivers: self.app.bind('Cache', self.app.make( 'CacheManager').driver(driver)) key = "cache_driver_test" key_store = self.app.make('Cache').store_for( key, "macho", 5, "seconds") # This return one key like this: cache_driver_test:1519741028.5628147 self.assertEqual(key, key_store[:len(key)]) content = self.app.make('Cache').get(key) self.assertEqual(content, "macho") assert self.app.make('Cache').exists(key) assert self.app.make('Cache').is_valid(key) self.app.make('Cache').delete(key) assert not self.app.make('Cache').is_valid("error") def test_driver_disk_cache_store(self): for driver in self.drivers: self.app.bind('Cache', self.app.make( 'CacheManager').driver(driver)) key = "forever_cache_driver_test" key = self.app.make('Cache').store(key, "macho") # This return the same key because it's forever self.assertEqual(key, key) content = self.app.make('Cache').get(key) self.assertEqual(content, "macho") self.assertTrue(self.app.make('Cache').exists(key)) self.assertTrue(self.app.make('Cache').is_valid(key)) self.app.make('Cache').delete(key) def test_get_cache(self): for driver in self.drivers: self.app.bind('Cache', self.app.make( 'CacheManager').driver(driver)) cache_driver = self.app.make('Cache') cache_driver.store('key', 'value') self.assertEqual(cache_driver.get('key'), 'value') cache_driver.store_for('key_time', 'key value', 4, 'seconds') self.assertEqual(cache_driver.get('key_time'), 'key value') cache_driver.delete('key') cache_driver.delete('key_time') def test_cache_expired_before_get(self): for driver in self.drivers: self.app.bind('Cache', self.app.make( 'CacheManager').driver(driver)) cache_driver = self.app.make('Cache') cache_driver.store_for('key_for_1_second', 'value', 1, 'second') self.assertTrue(cache_driver.is_valid('key_for_1_second')) self.assertEqual(cache_driver.get('key_for_1_second'), 'value') time.sleep(2) self.assertFalse(cache_driver.is_valid('key_for_1_second')) self.assertIsNone(cache_driver.get('key_for_1_second')) for cache_file in glob.glob('bootstrap/cache/key*'): os.remove(cache_file) def test_cache_sets_times(self): for driver in self.drivers: self.app.bind('Cache', self.app.make( 'CacheManager').driver(driver)) cache_driver = self.app.make('Cache') cache_driver.store_for('key_for_1_minute', 'value', 1, 'minute') cache_driver.store_for('key_for_1_hour', 'value', 1, 'hour') cache_driver.store_for('key_for_1_day', 'value', 1, 'day') cache_driver.store_for('key_for_1_month', 'value', 1, 'month') cache_driver.store_for('key_for_1_year', 'value', 1, 'year') self.assertTrue(cache_driver.is_valid('key_for_1_minute')) self.assertTrue(cache_driver.is_valid('key_for_1_hour')) self.assertTrue(cache_driver.is_valid('key_for_1_day')) self.assertTrue(cache_driver.is_valid('key_for_1_month')) self.assertTrue(cache_driver.is_valid('key_for_1_year')) self.assertEqual(cache_driver.get('key_for_1_minute'), 'value') self.assertEqual(cache_driver.get('key_for_1_hour'), 'value') self.assertEqual(cache_driver.get('key_for_1_day'), 'value') self.assertEqual(cache_driver.get('key_for_1_month'), 'value') self.assertEqual(cache_driver.get('key_for_1_year'), 'value') for cache_file in glob.glob('bootstrap/cache/key*'): os.remove(cache_file)
def test_service_provider_loads_app(): app = App() provider = ServiceProvider() provider.load_app(app).boot() assert provider.app == app
def __init__(self, Request, app:App): ''' Inject Any Dependencies From The Service Container ''' self.request = Request self.response = app.make('Response')