def configure(context=None, force=False): context = context or {} context['restfulpy_root'] = path.dirname(__file__) nanohttp_configure(context=context, force=force) settings.merge(__builtin_config)
def configure(self, files=None, context=None, force=False): _context = { 'process_name': self.process_name, 'root_path': self.root_path, 'data_dir': join(self.root_path, 'data'), 'restfulpy_dir': abspath(dirname(__file__)) } if context: _context.update(context) configure(context=_context, force=force) settings.merge(self.__configuration__) files = ([files] if isinstance(files, str) else files) or [] local_config_file = join(user_config_dir(), '%s.yml' % self.name) if exists(local_config_file): # pragma: no cover files.insert(0, local_config_file) for filename in files: with open(filename, 'rb') as f: header = f.read(4) if header == b'#enc': content = self.__configuration_cipher__.decrypt(f.read()) else: content = header + f.read() settings.merge(content.decode())
def configure(self, *args, **kwargs): super().configure(*args, **kwargs) settings.merge(""" auth: jwt_algorithm: HS256 jwt_secret_key: DSXdzzxxOiIxMjM0NTY3ODkwIiwFtZSI6IkpvadG4gRG9lrr """)
def test_messaging_model(db): __configuration__ = ''' messaging: default_sender: [email protected] default_messenger: restfulpy.mockup.MockupMessenger ''' settings.merge(__configuration__) session = db() mockup_messenger = create_messenger() message = Email(to='*****@*****.**', subject='Test Subject', body={'msg': 'Hello'}) session.add(message) session.commit() message.do_({}) assert mockup_messenger.last_message == { 'body': { 'msg': 'Hello' }, 'subject': 'Test Subject', 'to': '*****@*****.**' }
def thirdparty_mockup_server(): class Root(RegexRouteController): def __init__(self): super().__init__([ ('/apiv1/issues', self.handler), ]) @json(verbs=['sent', 'mentioned']) def handler(self): if context.query['roomId'] == 'bad': raise HTTPBadRequest() raise HTTPNoContent() app = MockupApplication('mockup-thirdparty', Root()) with mockup_http_server(app) as (server, url): settings.merge(f''' webhooks: sent: url: {url} mentioned: url: {url} ''') yield app
def maestro_mockup_server(): class Root(RegexRouteController): def __init__(self): super().__init__([ ('/apiv1/issues', self.send), ]) @json(verbs=['send', 'mention']) def send(self): time.sleep(0.5) app = MockupApplication('maestro-mockup', Root()) with mockup_http_server(app) as (server, url): settings.merge(f''' webhooks: sent: url: {url}/apiv1/issues verb: send mentioned: url: {url}/apiv1/issues verb: mention ''') yield app
def oauth_mockup_server(root_controller): app = MockupApplication('root', root_controller) with http_server(app) as (server, url): settings.merge(f''' tokenizer: url: {url} ''') yield app
def configure_app(cls): super().configure_app() settings.merge(""" logging: loggers: default: level: info """)
def configure_app(cls): cls.application.configure(force=True) settings.merge(""" jwt: max_age: .8 refresh_token: max_age: 2.2 """)
def configure_app(cls): super().configure_app() settings.merge(''' logging: loggers: default: level: debug ''')
def db(): _configuration = ''' db: test_url: postgresql://postgres:postgres@localhost/restfulpy_test administrative_url: postgresql://postgres:postgres@localhost/postgres ''' configure(force=True) settings.merge(_configuration) # Overriding the db uri becase this is a test session, so db.test_uri will # be used instead of the db.uri settings.db.url = settings.db.test_url # Drop the previosely created db if exists. with DBManager(url=settings.db.test_url) as m: m.drop_database() m.create_database() # An engine to create db schema and bind future created sessions engine = create_engine() # A session factory to create and store session to close it on tear down sessions = [] def _connect(*a, expire_on_commit=False, **kw): new_session = session_factory( bind=engine, *a, expire_on_commit=expire_on_commit, **kw ) sessions.append(new_session) return new_session session = _connect(expire_on_commit=True) # Creating database objects setup_schema(session) session.commit() # Closing the session to free the connection for future sessions. session.close() # Preparing and binding the application shared scoped session, due the # some errors when a model trying use the mentioned session internally. init_model(engine) yield _connect # Closing all sessions created by the test writer for s in sessions: s.close() close_all_sessions() engine.dispose() # Dropping the previously created database with DBManager(url=settings.db.test_url) as m: m.drop_database()
def test_server_timestamp_header(self): with self.given('Geting server\'s timestamp'): assert status == 200 assert 'X-Server-Timestamp' in response.headers settings.merge('timestamp: false') when('With default configuration') assert status == 200 assert 'X-Server-Timestamp' not in response.headers
def configure_app(cls): cls.application.configure(force=True) settings.merge(cls.__configuration__) settings.merge(''' logging: loggers: default: level: debug ''')
def configure_application(cls): cls.__application__.configure(force=True) if cls.__configuration__: settings.merge(cls.__configuration__) # Overriding the db uri becase this is a test session, so db.test_uri # will be used instead of the db.uri settings.db.url = settings.db.test_url
def configure(context=None, force=False): context = context or {} nanohttp_configure( context=context, force=force ) settings.merge(__builtin_config)
def configure_app(cls): cls.application.configure(force=True, context=dict(unittest=True)) settings.merge(""" messaging: default_messenger: restfulpy.testing.MockupMessenger logging: loggers: default: level: critical """)
def test_login_with_cas(self): token = JwtPrincipal( dict(email='*****@*****.**', title='user2', referenceId=2)).dump().decode() self._authentication_token = token with cas_mockup_server(): settings.merge(f''' oauth: member: url: {settings.tokenizer.url}/apiv1/members verb: get ''') with self.given(title='Try to access an authorized resource', description='Members are got from the cas', url='/apiv1/resources', headers={'X-Oauth2-Access-Token: access token2'}): assert status == 200 mismathc_token = JwtPrincipal( dict(email='*****@*****.**', title='user3', referenceId=3)).dump().decode() when('Token not match the CAS member', authorization=mismathc_token) assert status == 400 when('Try to pass with bad token', authorization='Invalid Token') assert status == 400 when('Try to access an unauthorized resource', authorization=None) assert status == 401 member_token = JwtPrincipal( dict(email='*****@*****.**', title='user1', referenceId=1)).dump().decode() when('Member exist in database', authorization=member_token, headers=Remove('X-Oauth2-Access-Token')) assert status == 200 with cas_server_status('503 Service Not Available'): when('CAS server is not available') assert status == '800 CAS Server Not Available' with cas_server_status('500 Internal Service Error'): when('CAS server faces with internal error') assert status == '801 CAS Server Internal Error' with cas_server_status('404 Not Found'): when('CAS server is not found') assert status == '617 CAS Server Not Found'
def configure(config=None, files=None, context=None, force=False): context = context or {} nanohttp_configure(context=context, force=force) settings.merge(BUILTIN_CONFIGURATION) if config: settings.merge(config) if files: for f in files: settings.load_file(f)
def test_principal(): __configuration__ = ''' jwt: secret: JWT-SECRET algorithm: HS256 max_age: 86400 # 24 Hours refresh_token: secret: JWT-REFRESH-SECRET algorithm: HS256 max_age: 2678400 # 30 Days ''' configure(force=True) settings.merge(__configuration__) principal = JWTPrincipal(dict( email='*****@*****.**', id=1, sessionId=1, roles=['admin'] )) assert principal.email == '*****@*****.**' assert principal.id == 1 assert principal.session_id == 1 assert principal.roles == ['admin'] assert principal.is_in_roles('admin') is True assert principal.is_in_roles('admin', 'god') is True encoded = principal.dump() principal = JWTPrincipal.load(encoded.decode()) assert principal.email == '*****@*****.**' assert principal.id == 1 assert principal.session_id == 1 assert principal.roles == ['admin'] assert principal.is_in_roles('admin') is True assert principal.is_in_roles('admin', 'god') is True principal = JWTPrincipal.load(encoded.decode(), force=True) assert principal.email == '*****@*****.**' assert principal.id == 1 assert principal.session_id == 1 assert principal.roles == ['admin'] assert principal.is_in_roles('admin') is True assert principal.is_in_roles('admin', 'god') is True principal =\ JWTPrincipal.load((b'Bearer %s' % encoded).decode(), force=True) assert principal.email == '*****@*****.**' assert principal.id == 1 assert principal.session_id == 1 assert principal.roles == ['admin'] assert principal.is_in_roles('admin') is True assert principal.is_in_roles('admin', 'god') is True
def configure(self, *args, **kwargs): super().configure(*args, **kwargs) settings.merge(""" template: test_dir1: directories: - %(microhttp_dir)s/tests/stuff/template_dir1 test_dir2: directories: - %(microhttp_dir)s/tests/stuff/template_dir2 """) template.configure()
def configure_app(cls): super().configure_app() settings.merge(""" logging: handlers: console: level: warning sms: provider: stemerald.tests.helpers.MockupSmsProvider """)
def test_model(db): session = db() __configuration__ = ''' timezone: ''' settings.merge(__configuration__) with Context({}): author1 = Author(title='author1', email='*****@*****.**', first_name='author 1 first name', last_name='author 1 last name', phone=None, password='******', birth=date(1, 1, 1), weight=1.1) post1 = Post(title='First post', author=author1, tag_time=time(1, 1, 1)) session.add(post1) session.commit() assert post1.id == 1 post1_dict = post1.to_dict() assert { 'author': { 'email': '*****@*****.**', 'firstName': 'author 1 first name', 'id': 1, 'lastName': 'author 1 last name', 'phone': None, 'title': 'author1', 'birth': '0001-01-01', 'weight': 1.100, 'age': 18 }, 'authorId': 1, 'comments': [], 'id': 1, 'tags': [], 'title': 'First post', 'tagTime': '01:01:01', }.items() < post1_dict.items() assert 'createdAt' in post1_dict assert 'modifiedAt' in post1_dict author1_dict = author1.to_dict() assert 'fullName' not in author1_dict
def configure(self, *args, **kwargs): super().configure(*args, **kwargs) settings.merge(""" i18n: locales: - en_US - fa_IR localedir: %(microhttp_dir)s/tests/stuff/i18n domain: microhttp_app default: en_us """) i18n.configure()
def application_factory(cls): app = super().application_factory() app.configure(force=True, context=dict(unittest=True)) settings.merge(''' messaging: default_messenger: restfulpy.testing.MockupMessenger logging: loggers: default: level: critical ''') settings.db.url = settings.db.test_url return app
def configure_app(cls): super().configure_app() settings.merge(""" shaparak: provider: stemerald.tests.test_transaction_shaparak_in.MockupShaparakProvider pay_ir: post_redirect_url: http://stacrypt.io/apiv2/transactions/shaparak-ins/pay-irs result_redirect_url: http://stacrypt.io/payment_redirect """)
def configure(config=None, files=None, context=None, force=False): context = context or {} context['restfulpy_root'] = path.dirname(__file__) nanohttp_configure(context=context, force=force) settings.merge(__builtin_config) if config: settings.merge(config) if files: for f in files: settings.load_files(f)
def configure_application(cls): cls.__application__.configure(force=True) settings.merge(''' logging: loggers: default: level: critical ''') if cls.__configuration__: settings.merge(cls.__configuration__) # Overriding the db uri becase this is a test session, so db.test_uri # will be used instead of the db.uri settings.db.url = settings.db.test_url
def oauth_mockup_server(): class Root(RegexRouteController): def __init__(self): super().__init__([ ('/apiv1/accesstokens', self.create), ('/apiv1/members/me', self.get), ]) @json def create(self): code = context.form.get('code') if _cas_server_status != 'idle': raise HTTPStatus(_cas_server_status) if not code.startswith('authorization code'): return dict(accessToken='token is damage', memberId=1) return dict(accessToken='access token', memberId=1) @json def get(self): access_token = context.environ['HTTP_AUTHORIZATION'] if _cas_server_status != 'idle': raise HTTPStatus(_cas_server_status) if 'access token' in access_token: return dict( id=1, title='manager1', firstName='manager1_first_name', lastName='manager1_last_name', email='*****@*****.**', avatar='avatar1', ) raise HTTPForbidden() app = MockupApplication('root', Root()) with mockup_http_server(app) as (server, url): settings.merge(f''' tokenizer: url: {url} oauth: secret: oauth2-secret application_id: 1 url: {url} ''') yield app
def test_messenger_factory(): __configuration__ = ''' messaging: default_messenger: restfulpy.messaging.ConsoleMessenger ''' configure(force=True) settings.merge(__configuration__) console_messenger = create_messenger() assert isinstance(console_messenger, ConsoleMessenger) settings.messaging.default_messenger =\ 'restfulpy.messaging.providers.SmtpProvider' smtp_messenger = create_messenger() assert isinstance(smtp_messenger, SmtpProvider)
def configure(self, filename=None, context=None, force=False): _context = { 'appname': self.name, 'dbname': self.name.lower(), 'approot': self.path, } if context: _context.update(context) configure(context=_context, force=force) if self.__configuration__: settings.merge(self.__configuration__) if filename is not None: settings.loadfile(filename)