Exemple #1
0
 def run(self):
     cov = Coverage(data_suffix=True)
     cov._warn_no_data = True
     cov._warn_unimported_source = True
     cov.start()
     try:
         super().run()
     finally:
         cov.stop()
         cov.save()
Exemple #2
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...")
Exemple #3
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)