def test_get_named_config(test_type, environment, expected): """Assert that the named configurations can be loaded. Or that a KeyError is returned for missing config types. """ if test_type == 'valid': assert isinstance(config.get_named_config(environment), expected) else: with pytest.raises(KeyError): config.get_named_config(environment)
async def run(loop, application: Flask = None): """Run the methods for applying future effective filings.""" if application is None: application = create_app() queue_service = ServiceWorker(loop=loop, nats_connection_options=default_nats_options, stan_connection_options=default_stan_options, config=config.get_named_config('production')) await queue_service.connect() with application.app_context(): try: filings = get_filings(app=application) if not filings: application.logger.debug(f'No PAID filings found to apply.') for filing in filings: filing_id = filing['filing']['header']['filingId'] effective_date = filing['filing']['header']['effectiveDate'] # NB: effective_date and now are both UTC now = datetime.utcnow().replace(tzinfo=timezone.utc) valid = effective_date and parse(effective_date) <= now if valid: msg = {'filing': {'id': filing_id}} await queue_service.publish(subject, msg) application.logger.debug( f'Successfully put filing {filing_id} on the queue.') except Exception as err: application.logger.error(err)
def app(): """Return a session-wide application configured in TEST mode.""" # _app = create_app('testing') _app = Flask('testing') print(config) _app.config.from_object(get_named_config('testing')) _db.init_app(_app) return _app
def status(self): """Calculate the status based on the config value.""" current_time = datetime.now() if self.invitation_status_code == 'PENDING': expiry_time = self.sent_date + timedelta( days=int(get_named_config().TOKEN_EXPIRY_PERIOD)) if current_time >= expiry_time: return 'EXPIRED' return self.invitation_status_code
def app(): """Return a session-wide application configured in TEST mode.""" _app = Flask('testing') print(config) _app.config.from_object(get_named_config('testing')) _db.init_app(_app) queue.init_app(_app, asyncio.new_event_loop()) return _app
def create_app(environment='production'): """Create instance of service.""" app = Flask(__name__) app.config.from_object(get_named_config(environment)) db.init_app(app) app.app_context().push() current_app.logger.debug( 'created the Flask App and pushed the App Context') return app
def test_invitations_status_expiry(session): # pylint:disable=unused-argument """Assert can set the status from PENDING to EXPIRED.""" sent_date = datetime.now() - timedelta( days=int(get_named_config().TOKEN_EXPIRY_PERIOD) + 1) invitation = factory_invitation_model(session=session, status='PENDING', sent_date=sent_date) session.add(invitation) session.commit() result: str = invitation.status assert result == 'EXPIRED'
async def run(loop, application: Flask = None): application = create_app() queue_service = ServiceWorker(loop=loop, nats_connection_options=default_nats_options, stan_connection_options=default_stan_options, config=config.get_named_config('production')) await queue_service.connect() with application.app_context(): try: # get updater-job token creds = { 'username': application.config['USERNAME'], 'password': application.config['PASSWORD'] } auth = requests.post(application.config['AUTH_URL'], json=creds, headers={'Content-Type': 'application/json'}) if auth.status_code != 200: application.logger.error( f'file_future_effective failed to authenticate {auth.json()} {auth.status_code}' ) raise Exception # TODO token = dict(auth.json())['access_token'] filings = get_filings(app=application) if not filings: application.logger.debug( f'No completed filings to send to colin.') for filing in filings: filing_id = filing["filing"]["header"]["filingId"] payment_id = filing["filing"]["header"]["paymentToken"] effective_date = filing["filing"]["header"]["effectiveDate"] # TODO Use UTC time? now = datetime.utcnow().replace(tzinfo=timezone.utc) valid = effective_date and parse(effective_date) <= now if valid: msg = format_message(filing_id, payment_id, 'COMPLETE') await queue_service.publish(subject, msg) #await queue.async_publish_filing(filing_id, 'COMPLETED', payment_id) application.logger.error( f'Successfully updated filing {filing_id}') except Exception as err: application.logger.error(err)
# Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an 'AS IS' BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Service for managing the documents.""" from jinja2 import Environment, FileSystemLoader from auth_api.models import Documents as DocumentsModel from auth_api.schemas import DocumentSchema from config import get_named_config from sbc_common_components.tracing.service_tracing import ServiceTracing # noqa: I001 ENV = Environment(loader=FileSystemLoader('.'), autoescape=True) CONFIG = get_named_config() @ServiceTracing.trace(ServiceTracing.enable_tracing, ServiceTracing.should_be_tracing) class Documents: """Manages the documents in DB. This service manages retrieving the documents. """ def __init__(self, model): """Return an invitation service instance.""" self._model = model @ServiceTracing.disable_tracing def as_dict(self):
from random import randint from auth_api import status as http_status from auth_api.schemas import utils as schema_utils from auth_api.services.keycloak import KeycloakService from auth_api.utils.constants import IdpHint from config import get_named_config from tests.utilities.factory_scenarios import BulkUserTestScenario, TestJwtClaims, \ TestOrgInfo from tests.utilities.factory_utils import (factory_auth_header, factory_invitation_anonymous) KEYCLOAK_SERVICE = KeycloakService() CONFIG = get_named_config('testing') def test_add_user(client, jwt, session): # pylint:disable=unused-argument """Assert that a user can be POSTed.""" headers = factory_auth_header(jwt=jwt, claims=TestJwtClaims.public_user_role) rv = client.post('/api/v1/users', headers=headers, content_type='application/json') assert rv.status_code == http_status.HTTP_201_CREATED assert schema_utils.validate(rv.json, 'anonymous_user_response') def test_add_user_admin_valid_bcros(client, jwt, session, keycloak_mock): # pylint:disable=unused-argument """Assert that an org admin can create members."""
from sqlalchemy.exc import OperationalError from urllib3.exceptions import NewConnectionError from config import get_named_config # pylint: disable=import-error from solr_names_updater.names_processors.names import ( # noqa: I001 process_add_to_solr as process_names_add, # noqa: I001 process_delete_from_solr as process_names_delete # noqa: I001 ) # noqa: I001 from solr_names_updater.names_processors.possible_conflicts import ( # noqa: I001 process_add_to_solr as process_possible_conflicts_add, # noqa: I001 process_delete_from_solr as process_possible_conflicts_delete # noqa: I001, I005 ) # noqa: I001 qsm = QueueServiceManager() # pylint: disable=invalid-name APP_CONFIG = get_named_config(os.getenv('DEPLOYMENT_ENV', 'production')) FLASK_APP = Flask(__name__) FLASK_APP.config.from_object(APP_CONFIG) db.init_app(FLASK_APP) def is_names_event_msg_type(msg: dict): """Check message is of type nr state change.""" if msg and msg.get('type', '') == 'bc.registry.names.events': return True return False def is_processable(msg: dict): """Determine if message is processable using message type of msg."""
def expires_on(self): """Calculate the expiry date based on the config value.""" if self.invitation_status_code == 'PENDING': return self.sent_date + timedelta( days=int(get_named_config().TOKEN_EXPIRY_PERIOD)) return None
"""s2i based launch script to run the service.""" import os import time import uuid from datetime import datetime, timezone from flask import Flask, current_app from namex.models import Request, State, db from namex.services import queue from queue_common.messages import create_cloud_event_msg from sqlalchemy import text import config from utils.logging import setup_logging APP_CONFIG = config.get_named_config(os.getenv('FLASK_ENV', 'production')) def create_app(): """Return a configured Flask App using the Factory method.""" app = Flask(__name__) app.config.from_object(APP_CONFIG) queue.init_app(app) db.init_app(app) register_shellcontext(app) return app