Exemplo n.º 1
0
 def __call__(self, match):
     super().__call__(match)
     return '"%s_REMOVE_ME_AFTERWARDS%s_REGEX_BACKUP_%s%s_REMOVE_ME_AFTERWARDS"' % (
         PROGRAM.upper(),
         PROGRAM.upper(),
         str(RegexEscapeBase.count).zfill(7),
         PROGRAM.upper()
     )
Exemplo n.º 2
0
def _graphql_undo_escapes(text: str) -> str:
    text = text.replace('"%s_REMOVE_ME_AFTERWARDS' % PROGRAM.upper(), '')
    text = text.replace('%s_REMOVE_ME_AFTERWARDS"' % PROGRAM.upper(), '')
    logging.debug('Before re.escape:\n%s', text)
    text = re.escape(text)
    logging.debug('After re.escape:\n%s', text)
    for i, match in enumerate(RegexEscapeBase.matches):
        logging.debug('Replacing %s with %s', '%s_REGEX_BACKUP_%s' % (PROGRAM.upper(), str(i).zfill(7)),
                      str(match.group()).zfill(7))
        text = text.replace('%s_REGEX_BACKUP_%s' % (PROGRAM.upper(), str(i).zfill(7)), str(match.group()).zfill(7))
    return text
Exemplo n.º 3
0
 def __init__(
     self,
     source: str,
     schema: dict,
     rendering_queue: RenderingQueue,
     is_file: bool = True,
     load_override: Union[dict, None] = None
 ):
     self.source = source
     self.source_text = None if is_file else source
     data_dir_override = environ.get('%s_DATA_DIR' % PROGRAM.upper(), None)
     if data_dir_override is not None:
         self.source_dir = path.abspath(data_dir_override)
     else:
         self.source_dir = path.dirname(path.abspath(source)) if source is not None and is_file else None
     self.data = None
     self.schema = schema
     self.rendering_queue = rendering_queue
     if load_override is not None:
         self.data = load_override
     else:
         self.load()
         self.validate()
     self.template_engine = _detect_engine(self.data, 'config')
     self.stats = stats
     self.logs = logs
     self.services, self.config_root = self.analyze(self.data)
     self.globals = self.config_root.globals
Exemplo n.º 4
0
    async def get(self):
        data = {'services': []}

        service = self.http_server.definition.services[self.service_id]
        data['services'].append(
            dict((k, getattr(service, k)) for k in UNHANDLED_SERVICE_KEYS
                 if getattr(service, k) is not None))
        data['services'][0]['endpoints'] = self.build_unhandled_requests(
            self.service_id)

        imaginary_config = copy.deepcopy(self.http_server.definition.data)
        imaginary_config['services'] = data['services']

        unhandled_data_enabled = False
        service = self.http_server.definition.services[self.service_id]
        for rule in self.http_server._apps.apps[
                service.
                internal_http_service_id].default_router.rules[0].target.rules:
            if rule.target == GenericHandler:
                if rule.target_kwargs['unhandled_data']:
                    unhandled_data_enabled = True
                break

        self.set_header('x-%s-unhandled-data' % PROGRAM.lower(),
                        'true' if unhandled_data_enabled else 'false')

        if not self.validate(imaginary_config):  # pragma: no cover
            return

        self.dump(data)
Exemplo n.º 5
0
    async def get(self):
        data = {'services': []}

        for i, service in enumerate(HttpService.services):
            endpoints = self.build_unhandled_requests(i)
            if not endpoints:
                continue
            new_service = dict((k, getattr(service, k))
                               for k in UNHANDLED_SERVICE_KEYS
                               if getattr(service, k) is not None)
            new_service['endpoints'] = endpoints
            data['services'].append(new_service)

        if data['services'] and not self.validate(data):  # pragma: no cover
            return

        unhandled_data_enabled = False
        break_parent = False
        for app in self.http_server._apps.apps:
            if break_parent:
                break
            for rule in app.default_router.rules[0].target.rules:
                if rule.target == GenericHandler:
                    if rule.target_kwargs['unhandled_data']:
                        unhandled_data_enabled = True
                    if unhandled_data_enabled:
                        break_parent = True
                        break

        self.set_header('x-%s-unhandled-data' % PROGRAM.lower(),
                        'true' if unhandled_data_enabled else 'false')

        self.dump(data)
Exemplo n.º 6
0
def _get_log_root(enabled):
    return {
        "log": {
            "_enabled": enabled,
            "version": "1.2",
            "creator": {
                "name": "%s" % PROGRAM.capitalize(),
                "version": "%s" % mockintosh.__version__
            },
            "entries": []
        }
    }
Exemplo n.º 7
0
def initiate(argv=None):
    if should_cov:  # pragma: no cover
        signal.signal(signal.SIGTERM, _gracefully_exit)
        logging.debug('Starting coverage')
        from coverage import Coverage
        cov = Coverage(data_suffix=True, config_file='.coveragerc')
        cov._warn_no_data = True
        cov._warn_unimported_source = True
        cov.start()
        atexit.register(_cov_exit, cov)

    """The top-level method to serve as the entry point of Mockintosh.

    This method is the entry point defined in `setup.py` for the `mockintosh` executable that
    placed a directory in `$PATH`.

    This method parses the command-line arguments and handles the top-level initiations accordingly.
    """

    ap = CustomArgumentParser(formatter_class=argparse.RawTextHelpFormatter)
    ap.add_argument(
        'source',
        help='Path to configuration file and (optional) a list of the service names\n'
             'to specify the services to be listened.',
        nargs='+'
    )
    ap.add_argument('-q', '--quiet', help='Less logging messages, only warnings and errors', action='store_true')
    ap.add_argument('-v', '--verbose', help='More logging messages, including debug', action='store_true')
    ap.add_argument(
        '-i',
        '--interceptor',
        help='A list of interceptors to be called in <package>.<module>.<function> format',
        action='append',
        nargs='+'
    )
    ap.add_argument('-l', '--logfile', help='Also write log into a file', action='store')
    ap.add_argument('-b', '--bind', help='Address to specify the network interface', action='store')
    ap.add_argument(
        '-c',
        '--convert',
        help='Convert an OpenAPI Specification (Swagger) 2.0 / 3.0 / 3.1 file to %s config. '
             'Example: `$ mockintosh petstore.json -c dev.json json`' % PROGRAM.capitalize(),
        action='store',
        nargs='+',
        metavar=('filename', 'format')
    )
    ap.add_argument('--enable-tags', help='A comma separated list of tags to enable', action='store')
    ap.add_argument('--sample-config', help='Writes sample config file to disk', action='store_true')
    args = vars(ap.parse_args(argv))

    interceptors, address, tags = _handle_cli_args(args)

    logging.debug('Current working dir: %s', os.getcwd())

    if args['sample_config']:
        fname = os.path.abspath(args['source'][0])
        shutil.copy(os.path.join(__location__, "res", "sample.yml"), fname)
        logging.info("Created sample configuration file in %r", fname)
        logging.info("To run it, use the following command:\n    mockintosh %s", os.path.basename(fname))
        return 0

    debug_mode = environ.get('DEBUG', False) or environ.get('MOCKINTOSH_DEBUG', False)
    if debug_mode:
        logging.debug('Tornado Web Server\'s debug mode is enabled!')

    source = args['source'][0]
    services_list = args['source'][1:]
    convert_args = args['convert']

    load_override = None
    logging.debug("Source absolute path: %s", os.path.abspath(source))

    if convert_args:
        if len(convert_args) < 2:
            convert_args.append('yaml')
        elif convert_args[1] != 'json':
            convert_args[1] = 'yaml'

        logging.info(
            "Converting OpenAPI Specification %s to ./%s in %s format...",
            source,
            convert_args[0],
            convert_args[1].upper()
        )
        target_path = _handle_oas_input(source, convert_args)
        logging.info("The transpiled config %s is ready at %s", convert_args[1].upper(), target_path)
    else:
        try:
            load_override = _handle_oas_input(source, ['config.yaml', 'yaml'], True)
            logging.info("Automatically transpiled the config YAML from OpenAPI Specification.")
        except (ValidationError, AttributeError):
            logging.debug("The input is not a valid OpenAPI Specification, defaulting to Mockintosh config.")
        except ResolutionError:  # pragma: no cover
            pass

        logging.info("%s v%s is starting...", PROGRAM.capitalize(), __version__)

        if not cov_no_run:  # pragma: no cover
            while run(source, debug=debug_mode, interceptors=interceptors, address=address,
                      services_list=services_list, tags=tags, load_override=load_override):
                logging.info("Restarting...")
Exemplo n.º 8
0
def initiate():
    if should_cov:  # pragma: no cover
        signal.signal(signal.SIGTERM, gracefully_exit)
        logging.debug('Starting coverage')
        from coverage import Coverage
        cov = Coverage(data_suffix=True, config_file='.coveragerc')
        cov._warn_no_data = True
        cov._warn_unimported_source = True
        cov.start()
        atexit.register(cov_exit, cov)
    """The top-level method to serve as the entry point of Mockintosh.

    This method is the entry point defined in `setup.py` for the `mockintosh` executable that
    placed a directory in `$PATH`.

    This method parses the command-line arguments and handles the top-level initiations accordingly.
    """

    ap = CustomArgumentParser(formatter_class=argparse.RawTextHelpFormatter)
    ap.add_argument(
        'source',
        help=
        'Path to configuration file and (optional) a list of the service names\n'
        'to specify the services to be listened.',
        nargs='+')
    ap.add_argument('-q',
                    '--quiet',
                    help='Less logging messages, only warnings and errors',
                    action='store_true')
    ap.add_argument('-v',
                    '--verbose',
                    help='More logging messages, including debug',
                    action='store_true')
    ap.add_argument(
        '-i',
        '--interceptor',
        help=
        'A list of interceptors to be called in <package>.<module>.<function> format',
        action='append',
        nargs='+')
    ap.add_argument('-l',
                    '--logfile',
                    help='Also write log into a file',
                    action='store')
    ap.add_argument('-b',
                    '--bind',
                    help='Address to specify the network interface',
                    action='store')
    args = vars(ap.parse_args())

    interceptors = import_interceptors(args['interceptor'])

    address = args['bind'] if args['bind'] is not None else ''

    fmt = "[%(asctime)s %(name)s %(levelname)s] %(message)s"
    if args['quiet']:
        logging.basicConfig(level=logging.WARNING, format=fmt)
    elif args['verbose']:
        logging.basicConfig(level=logging.DEBUG, format=fmt)
    else:
        logging.basicConfig(level=logging.INFO, format=fmt)

    if args['logfile']:
        handler = logging.FileHandler(args['logfile'])
        handler.setFormatter(logging.Formatter(fmt))
        logging.getLogger('').addHandler(handler)

    logging.info("%s v%s is starting..." % (PROGRAM.capitalize(), __version__))

    debug_mode = environ.get('DEBUG', False) or environ.get(
        'MOCKINTOSH_DEBUG', False)
    if debug_mode:
        logging.debug('Tornado Web Server\'s debug mode is enabled!')

    source = args['source'][0]
    services_list = args['source'][1:]

    if not cov_no_run:  # pragma: no cover
        run(source,
            debug=debug_mode,
            interceptors=interceptors,
            address=address,
            services_list=services_list)
Exemplo n.º 9
0
 def __call__(self, match):
     super().__call__(match)
     return '%s_REGEX_BACKUP_%s' % (
         PROGRAM.upper(),
         str(RegexEscapeBase.count).zfill(7)
     )