# Path: cliche/cli.py
# @group()
# def cli():
#     """cliche for integrated command for cliche.io service."""
# 
# @cli.command()
# @option('--host', '-h')
# @option('--port', '-p', type=int)
# @option('--threaded', is_flag=True)
# @option('--processes', type=int, default=1)
# @option('--passthrough-errors', is_flag=True)
# @option('--debug/--no-debug', '-d/-D', default=None,
#         help='enable the Werkzeug debugger'
#              ' (DO NOT use in production code)')
# @option('--reload/--no-reload', '-r/-R', default=None,
#         help='monitor Python files for changes'
#              ' (not 100% safe for production use)')
# @config
# def runserver(host, port, threaded, processes,
#               passthrough_errors, debug, reload):
#     """Run the Flask development server i.e. app.run()"""
# 
#     if flask_app.debug:
#         # scss compile automatically in debug mode
#         flask_app.wsgi_app = SassMiddleware(flask_app.wsgi_app, {
#             'cliche.web': ('static/sass', 'static/css', '/static/css')
#         })
# 
#     if debug is None:
#         debug = flask_app.debug
#     if reload is None:
#         reload = flask_app.debug
# 
#     flask_setup_sentry()
# 
#     flask_app.run(host=host,
#                   port=port,
#                   debug=debug,
#                   use_debugger=debug,
#                   use_reloader=reload,
#                   threaded=threaded,
#                   processes=processes,
#                   passthrough_errors=passthrough_errors)
# 
# @cli.command()
# @config
# def shell():
#     """Run a Python shell inside Flask application context."""
#     with flask_app.test_request_context():
#         context = dict(app=_request_ctx_stack.top.app)
# 
#         # Use basic python shell
#         code.interact(local=context)
# 
# @cli.command()
# @argument('revision', default='head')
# @config
# def upgrade(revision):
#     """Create the database tables, or upgrade it to the latest revision."""
# 
#     logging_config = dict(ALEMBIC_LOGGING)
#     logging.config.dictConfig(logging_config)
#     with flask_app.app_context():
#         engine = get_database_engine()
#         try:
#             upgrade_database(engine, revision)
#         except CommandError as e:
#             if revision != 'head':
#                 try:
#                     downgrade_database(engine, revision)
#                 except CommandError as e:
#                     echo(e, file=sys.stderr)
#                     raise SystemExit(1)
#             else:
#                 echo(e, file=sys.stderr)
#                 raise SystemExit(1)
# 
# Path: cliche/orm.py
# def make_repr(self):
# def get_alembic_config(engine):
# def initialize_database(engine):
# def get_database_revision(engine):
#     def get_revision(rev, context):
# def upgrade_database(engine, revision='head'):
#     def upgrade(rev, context):
#         def update_current_rev(old, new):
# def downgrade_database(engine, revision):
# def import_all_modules(dry_run=False):  # FIXME
# 
# Path: cliche/web/app.py
# def setup_sentry():
# def get_sentry() -> Sentry:
# def index():
# def check_login_status():
# def template_processor():
# def add_login_header(response):


import subprocess
from cliche.cli import cli, runserver, shell, upgrade
from cliche.orm import Base
from cliche.web.app import app

def test_cli(fx_cli_runner):
    """empty command"""
    result = fx_cli_runner.invoke(cli, [])
    assert result.exit_code == 0
    assert 'Usage: cli' in result.output


def test_upgrade_empty_cmd(fx_cli_runner):
    result = fx_cli_runner.invoke(upgrade, [])
    assert result.exit_code == 1
    assert 'The -c/--config' in result.output


def test_upgrade_wrong_path():
    """wrong path"""
    p = subprocess.Popen(
        ['cliche', 'upgrade', '-c', 'invalid.cfg.py'],
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE
    )
    out, err = p.communicate()
    exit_code = p.returncode
    assert 'Invalid value for "--config"' in err.decode('u8')
    assert exit_code == 2


def test_upgrade_fine_use_metadata(fx_cfg_yml_file_use_db_url):
    """work normally, no additional options"""
    database_engine = app.config['DATABASE_ENGINE']

# Path: cliche/cli.py
# @group()
# def cli():
#     """cliche for integrated command for cliche.io service."""
# 
# @cli.command()
# @option('--host', '-h')
# @option('--port', '-p', type=int)
# @option('--threaded', is_flag=True)
# @option('--processes', type=int, default=1)
# @option('--passthrough-errors', is_flag=True)
# @option('--debug/--no-debug', '-d/-D', default=None,
#         help='enable the Werkzeug debugger'
#              ' (DO NOT use in production code)')
# @option('--reload/--no-reload', '-r/-R', default=None,
#         help='monitor Python files for changes'
#              ' (not 100% safe for production use)')
# @config
# def runserver(host, port, threaded, processes,
#               passthrough_errors, debug, reload):
#     """Run the Flask development server i.e. app.run()"""
# 
#     if flask_app.debug:
#         # scss compile automatically in debug mode
#         flask_app.wsgi_app = SassMiddleware(flask_app.wsgi_app, {
#             'cliche.web': ('static/sass', 'static/css', '/static/css')
#         })
# 
#     if debug is None:
#         debug = flask_app.debug
#     if reload is None:
#         reload = flask_app.debug
# 
#     flask_setup_sentry()
# 
#     flask_app.run(host=host,
#                   port=port,
#                   debug=debug,
#                   use_debugger=debug,
#                   use_reloader=reload,
#                   threaded=threaded,
#                   processes=processes,
#                   passthrough_errors=passthrough_errors)
# 
# @cli.command()
# @config
# def shell():
#     """Run a Python shell inside Flask application context."""
#     with flask_app.test_request_context():
#         context = dict(app=_request_ctx_stack.top.app)
# 
#         # Use basic python shell
#         code.interact(local=context)
# 
# @cli.command()
# @argument('revision', default='head')
# @config
# def upgrade(revision):
#     """Create the database tables, or upgrade it to the latest revision."""
# 
#     logging_config = dict(ALEMBIC_LOGGING)
#     logging.config.dictConfig(logging_config)
#     with flask_app.app_context():
#         engine = get_database_engine()
#         try:
#             upgrade_database(engine, revision)
#         except CommandError as e:
#             if revision != 'head':
#                 try:
#                     downgrade_database(engine, revision)
#                 except CommandError as e:
#                     echo(e, file=sys.stderr)
#                     raise SystemExit(1)
#             else:
#                 echo(e, file=sys.stderr)
#                 raise SystemExit(1)
# 
# Path: cliche/orm.py
# def make_repr(self):
# def get_alembic_config(engine):
# def initialize_database(engine):
# def get_database_revision(engine):
#     def get_revision(rev, context):
# def upgrade_database(engine, revision='head'):
#     def upgrade(rev, context):
#         def update_current_rev(old, new):
# def downgrade_database(engine, revision):
# def import_all_modules(dry_run=False):  # FIXME
# 
# Path: cliche/web/app.py
# def setup_sentry():
# def get_sentry() -> Sentry:
# def index():
# def check_login_status():
# def template_processor():
# def add_login_header(response):


# Path: tests/cli_test.py
import subprocess
from cliche.cli import cli, runserver, shell, upgrade
from cliche.orm import Base
from cliche.web.app import app


def test_cli(fx_cli_runner):
    """empty command"""
    result = fx_cli_runner.invoke(cli, [])
    assert result.exit_code == 0
    assert 'Usage: cli' in result.output


def test_upgrade_empty_cmd(fx_cli_runner):
    result = fx_cli_runner.invoke(upgrade, [])
    assert result.exit_code == 1
    assert 'The -c/--config' in result.output


def test_upgrade_wrong_path():
    """wrong path"""
    p = subprocess.Popen(
        ['cliche', 'upgrade', '-c', 'invalid.cfg.py'],
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE
    )
    out, err = p.communicate()
    exit_code = p.returncode
    assert 'Invalid value for "--config"' in err.decode('u8')
    assert exit_code == 2


def test_upgrade_fine_use_metadata(fx_cfg_yml_file_use_db_url):
    """work normally, no additional options"""
    database_engine = app.config['DATABASE_ENGINE']

    Base.metadata.drop_all(bind=database_engine)