Ejemplo n.º 1
0
def test_quoted_db_uri(tmpdir):
    with mock.patch.object(PGCli, "connect") as mock_connect:
        cli = PGCli(pgclirc_file=str(tmpdir.join("rcfile")))
        cli.connect_uri("postgres://bar%5E:%[email protected]/testdb%5B")
    mock_connect.assert_called_with(
        database="testdb[", host="baz.com", user="******", passwd="]foo"
    )
Ejemplo n.º 2
0
def test_port_db_uri(tmpdir):
    with mock.patch.object(PGCli, "connect") as mock_connect:
        cli = PGCli(pgclirc_file=str(tmpdir.join("rcfile")))
        cli.connect_uri("postgres://*****:*****@baz.com:2543/testdb")
    mock_connect.assert_called_with(
        database="testdb", host="baz.com", user="******", passwd="foo", port="2543"
    )
Ejemplo n.º 3
0
def test_application_name_db_uri(tmpdir):
    with mock.patch.object(PGExecute, '__init__') as mock_pgexecute:
        mock_pgexecute.return_value = None
        cli = PGCli(pgclirc_file=str(tmpdir.join("rcfile")))
        cli.connect_uri('postgres://[email protected]/?application_name=cow')
    mock_pgexecute.assert_called_with('bar', 'bar', '', 'baz.com', '', '',
                                      application_name='cow')
Ejemplo n.º 4
0
def test_set_row_limit(over_default, over_limit, LIMIT):
    cli = PGCli(row_limit=LIMIT)
    stmt = "SELECT * FROM students"
    result = cli._should_show_limit_prompt(stmt, over_default)
    assert result is False

    result = cli._should_show_limit_prompt(stmt, over_limit)
    assert result is True
Ejemplo n.º 5
0
def test_default_row_limit(low_count, over_default):
    cli = PGCli()
    stmt = "SELECT * FROM students"
    result = cli._should_show_limit_prompt(stmt, low_count)
    assert result is False

    result = cli._should_show_limit_prompt(stmt, over_default)
    assert result is True
Ejemplo n.º 6
0
def pset_pager_mocks():
    cli = PGCli()
    cli.watch_command = None
    with mock.patch('pgcli.main.click.echo') as mock_echo, \
            mock.patch('pgcli.main.click.echo_via_pager') as mock_echo_via_pager, \
            mock.patch.object(cli, 'prompt_app') as mock_app:

        yield cli, mock_echo, mock_echo_via_pager, mock_app
Ejemplo n.º 7
0
def test_set_row_limit():
    cli = PGCli(row_limit=LIMIT)
    stmt = "SELECT * FROM students"
    result = cli._should_show_limit_prompt(stmt, over_default)
    assert result is False

    result = cli._should_show_limit_prompt(stmt, over_limit)
    assert result is True
Ejemplo n.º 8
0
def test_default_row_limit():
    cli = PGCli()
    stmt = "SELECT * FROM students"
    result = cli._should_show_limit_prompt(stmt, low_count)
    assert result is False

    result = cli._should_show_limit_prompt(stmt, over_default)
    assert result is True
Ejemplo n.º 9
0
def test_quoted_db_uri(tmpdir):
    with mock.patch.object(PGCli, 'connect') as mock_connect:
        cli = PGCli(pgclirc_file=str(tmpdir.join("rcfile")))
        cli.connect_uri('postgres://bar%5E:%[email protected]/testdb%5B')
    mock_connect.assert_called_with(database='testdb[',
                                    host='baz.com',
                                    user='******',
                                    passwd=']foo')
Ejemplo n.º 10
0
def test_quoted_db_uri(tmpdir):
    with mock.patch.object(PGCli, 'connect') as mock_connect:
        cli = PGCli(pgclirc_file=str(tmpdir.join("rcfile")))
        cli.connect_uri('postgres://bar%5E:%[email protected]/testdb%5B')
    mock_connect.assert_called_with(database='testdb[',
                                    host='baz.com',
                                    user='******',
                                    passwd=']foo')
Ejemplo n.º 11
0
def pset_pager_mocks():
    cli = PGCli()
    cli.watch_command = None
    with mock.patch('pgcli.main.click.echo') as mock_echo, \
            mock.patch('pgcli.main.click.echo_via_pager') as mock_echo_via_pager, \
            mock.patch.object(cli, 'prompt_app') as mock_app:

        yield cli, mock_echo, mock_echo_via_pager, mock_app
Ejemplo n.º 12
0
def test_application_name_db_uri(tmpdir):
    with mock.patch.object(PGExecute, "__init__") as mock_pgexecute:
        mock_pgexecute.return_value = None
        cli = PGCli(pgclirc_file=str(tmpdir.join("rcfile")))
        cli.connect_uri("postgres://[email protected]/?application_name=cow")
    mock_pgexecute.assert_called_with(
        "bar", "bar", "", "baz.com", "", "", application_name="cow"
    )
Ejemplo n.º 13
0
def test_row_limit_on_non_select():
    cli = PGCli()
    stmt = "UPDATE students set name='Boby'"
    result = cli._should_show_limit_prompt(stmt, None)
    assert result is False

    cli = PGCli(row_limit=0)
    result = cli._should_show_limit_prompt(stmt, over_default)
    assert result is False
Ejemplo n.º 14
0
def shell(ctx):
    """Run database shell"""
    app = factory(ctx.obj['CONFIG'])
    with app.app_context():
        pgcli = PGCli()
        database = str(app.extensions['sqlalchemy'].db.engine.url)
        pgcli.connect_uri(database)
        pgcli.logger.debug('Launch Params: \n\tdatabase: %r', database)
        pgcli.run_cli()
Ejemplo n.º 15
0
def test_port_db_uri(tmpdir):
    with mock.patch.object(PGCli, 'connect') as mock_connect:
        cli = PGCli(pgclirc_file=str(tmpdir.join("rcfile")))
        cli.connect_uri('postgres://*****:*****@baz.com:2543/testdb')
    mock_connect.assert_called_with(database='testdb',
                                    host='baz.com',
                                    user='******',
                                    passwd='foo',
                                    port='2543')
Ejemplo n.º 16
0
def test_port_db_uri(tmpdir):
    with mock.patch.object(PGCli, 'connect') as mock_connect:
        cli = PGCli(pgclirc_file=str(tmpdir.join("rcfile")))
        cli.connect_uri('postgres://*****:*****@baz.com:2543/testdb')
    mock_connect.assert_called_with(database='testdb',
                                    host='baz.com',
                                    user='******',
                                    passwd='foo',
                                    port='2543')
Ejemplo n.º 17
0
def sql_shell():
    try:
        from pgcli.main import PGCli
    except ImportError:
        print('PGCli was not found, please install it with: pip install pgcli')
        sys.exit(1)
    conn_string = server.config.database.connection_string.strip("'")

    pgcli = PGCli()
    pgcli.connect_uri(conn_string)
    pgcli.run_cli()
Ejemplo n.º 18
0
def test_watch_works(executor):
    cli = PGCli(pgexecute=executor)

    def run_with_watch(query,
                       target_call_count=1,
                       expected_output="",
                       expected_timing=None):
        """
        :param query: Input to the CLI
        :param target_call_count: Number of times the user lets the command run before Ctrl-C
        :param expected_output: Substring expected to be found for each executed query
        :param expected_timing: value `time.sleep` expected to be called with on every invocation
        """
        with mock.patch.object(cli, "echo_via_pager") as mock_echo, mock.patch(
                "pgcli.main.sleep") as mock_sleep:
            mock_sleep.side_effect = [None] * (target_call_count - 1) + [
                KeyboardInterrupt
            ]
            cli.handle_watch_command(query)
        # Validate that sleep was called with the right timing
        for i in range(target_call_count - 1):
            assert mock_sleep.call_args_list[i][0][0] == expected_timing
        # Validate that the output of the query was expected
        assert mock_echo.call_count == target_call_count
        for i in range(target_call_count):
            assert expected_output in mock_echo.call_args_list[i][0][0]

    # With no history, it errors.
    with mock.patch("pgcli.main.click.secho") as mock_secho:
        cli.handle_watch_command(r"\watch 2")
    mock_secho.assert_called()
    assert (r"\watch cannot be used with an empty query"
            in mock_secho.call_args_list[0][0][0])

    # Usage 1: Run a query and then re-run it with \watch across two prompts.
    run_with_watch("SELECT 111", expected_output="111")
    run_with_watch("\\watch 10",
                   target_call_count=2,
                   expected_output="111",
                   expected_timing=10)

    # Usage 2: Run a query and \watch via the same prompt.
    run_with_watch(
        "SELECT 222; \\watch 4",
        target_call_count=3,
        expected_output="222",
        expected_timing=4,
    )

    # Usage 3: Re-run the last watched command with a new timing
    run_with_watch("\\watch 5",
                   target_call_count=4,
                   expected_output="222",
                   expected_timing=5)
Ejemplo n.º 19
0
def test_application_name_db_uri(tmpdir):
    with mock.patch.object(PGExecute, '__init__') as mock_pgexecute:
        mock_pgexecute.return_value = None
        cli = PGCli(pgclirc_file=str(tmpdir.join("rcfile")))
        cli.connect_uri('postgres://[email protected]/?application_name=cow')
    mock_pgexecute.assert_called_with('bar',
                                      'bar',
                                      '',
                                      'baz.com',
                                      '',
                                      '',
                                      application_name='cow')
Ejemplo n.º 20
0
def test_ssl_db_uri(tmpdir):
    with mock.patch.object(PGCli, 'connect') as mock_connect:
        cli = PGCli(pgclirc_file=str(tmpdir.join("rcfile")))
        cli.connect_uri(
            'postgres://bar%5E:%[email protected]/testdb%5B?'
            'sslmode=verify-full&sslcert=m%79.pem&sslkey=my-key.pem&sslrootcert=c%61.pem')
    mock_connect.assert_called_with(database='testdb[',
                                    host='baz.com',
                                    user='******',
                                    passwd=']foo',
                                    sslmode='verify-full',
                                    sslcert='my.pem',
                                    sslkey='my-key.pem',
                                    sslrootcert='ca.pem')
Ejemplo n.º 21
0
def test_ssl_db_uri(tmpdir):
    with mock.patch.object(PGCli, 'connect') as mock_connect:
        cli = PGCli(pgclirc_file=str(tmpdir.join("rcfile")))
        cli.connect_uri('postgres://bar%5E:%[email protected]/testdb%5B?'
                        'sslmode=verify-full&sslcert=m%79.pem&sslkey='
                        'my-key.pem&sslrootcert=c%61.pem')
    mock_connect.assert_called_with(database='testdb[',
                                    host='baz.com',
                                    port=None,
                                    user='******',
                                    passwd=']foo',
                                    sslmode='verify-full',
                                    sslcert='my.pem',
                                    sslkey='my-key.pem',
                                    sslrootcert='ca.pem')
Ejemplo n.º 22
0
def test_i_works(tmpdir, executor):
    sqlfile = tmpdir.join("test.sql")
    sqlfile.write("SELECT NOW()")
    rcfile = str(tmpdir.join("rcfile"))
    cli = PGCli(pgexecute=executor, pgclirc_file=rcfile)
    statement = r"\i {0}".format(sqlfile)
    run(executor, statement, pgspecial=cli.pgspecial)
Ejemplo n.º 23
0
def test_ssl_db_uri(tmpdir):
    with mock.patch.object(PGCli, "connect") as mock_connect:
        cli = PGCli(pgclirc_file=str(tmpdir.join("rcfile")))
        cli.connect_uri(
            "postgres://bar%5E:%[email protected]/testdb%5B?"
            "sslmode=verify-full&sslcert=m%79.pem&sslkey=my-key.pem&sslrootcert=c%61.pem"
        )
    mock_connect.assert_called_with(
        database="testdb[",
        host="baz.com",
        user="******",
        passwd="]foo",
        sslmode="verify-full",
        sslcert="my.pem",
        sslkey="my-key.pem",
        sslrootcert="ca.pem",
    )
Ejemplo n.º 24
0
def test_pg_service_file(tmpdir):

    with mock.patch.object(PGCli, "connect") as mock_connect:
        cli = PGCli(pgclirc_file=str(tmpdir.join("rcfile")))
        with open(tmpdir.join(".pg_service.conf").strpath,
                  "w") as service_conf:
            service_conf.write("""File begins with a comment
            that is not a comment
            # or maybe a comment after all
            because psql is crazy

            [myservice]
            host=a_host
            user=a_user
            port=5433
            password=much_secure
            dbname=a_dbname

            [my_other_service]
            host=b_host
            user=b_user
            port=5435
            dbname=b_dbname
            """)
        os.environ["PGSERVICEFILE"] = tmpdir.join(".pg_service.conf").strpath
        cli.connect_service("myservice", "another_user")
        mock_connect.assert_called_with(
            database="a_dbname",
            host="a_host",
            user="******",
            port="5433",
            passwd="much_secure",
        )

    with mock.patch.object(PGExecute, "__init__") as mock_pgexecute:
        mock_pgexecute.return_value = None
        cli = PGCli(pgclirc_file=str(tmpdir.join("rcfile")))
        os.environ["PGPASSWORD"] = "******"
        cli.connect_service("my_other_service", None)
    mock_pgexecute.assert_called_with(
        "b_dbname",
        "b_user",
        "very_secure",
        "b_host",
        "5435",
        "",
        application_name="pgcli",
    )
    del os.environ["PGPASSWORD"]
    del os.environ["PGSERVICEFILE"]
Ejemplo n.º 25
0
def pgcli(info, pgclirc):
    '''Start a pgcli session.'''
    from flask.globals import _app_ctx_stack
    app = _app_ctx_stack.top.app
    pgcli = PGCli(pgclirc_file=pgclirc)
    pgcli.connect_uri(app.config['SQLALCHEMY_DATABASE_URI'])
    pgcli.run_cli()
Ejemplo n.º 26
0
def test_row_limit_on_non_select(over_default):
    cli = PGCli()
    stmt = "UPDATE students set name='Boby'"
    result = cli._should_show_limit_prompt(stmt, None)
    assert result is False

    cli = PGCli(row_limit=0)
    result = cli._should_show_limit_prompt(stmt, over_default)
    assert result is False
Ejemplo n.º 27
0
def test_row_limit_on_non_select(over_limit):
    cli = PGCli()
    stmt = "UPDATE students SET name='Boby'"
    result = cli._should_limit_output(stmt, over_limit)
    assert result is False

    cli = PGCli(row_limit=0)
    result = cli._should_limit_output(stmt, over_limit)
    assert result is False
Ejemplo n.º 28
0
def test_row_limit_without_LIMIT_clause(LIMIT, over_limit):
    cli = PGCli(row_limit=LIMIT)
    stmt = "SELECT * FROM students"

    result = cli._should_limit_output(stmt, over_limit)
    assert result is True

    cli = PGCli(row_limit=0)
    result = cli._should_limit_output(stmt, over_limit)
    assert result is False
Ejemplo n.º 29
0
def sql_shell():
    try:
        from pgcli.main import PGCli
    except ImportError:
        print('PGCli was not found, please install it with: pip install pgcli')
        sys.exit(1)
    conn_string = server.config.database.connection_string.strip("'")

    pgcli = PGCli()
    pgcli.connect_uri(conn_string)
    pgcli.run_cli()
Ejemplo n.º 30
0
def sql_shell():
    conn_string = faraday.server.config.database.connection_string.strip("'")
    conn_string = urlparse(conn_string)
    parsed_conn_string = ("user={username} password={password} host={hostname} dbname={dbname}"
                          .format(username=conn_string.username,
                                  password=conn_string.password,
                                  hostname=conn_string.hostname,
                                  dbname=conn_string.path[1:]))
    pgcli = PGCli()
    pgcli.connect_uri(parsed_conn_string)
    pgcli.run_cli()
Ejemplo n.º 31
0
def sql_shell():
    try:
        from pgcli.main import PGCli
    except ImportError:
        print('PGCli was not found, please install it with: pip install pgcli')
        sys.exit(1)
    conn_string = faraday.server.config.database.connection_string.strip("'")
    conn_string = urlparse(conn_string)
    parsed_conn_string = ("user={username} password={password} host={hostname} dbname={dbname}"
                          .format(username=conn_string.username,
                                  password=conn_string.password,
                                  hostname=conn_string.hostname,
                                  dbname=conn_string.path[1:]))
    pgcli = PGCli()
    pgcli.connect_uri(parsed_conn_string)
    pgcli.run_cli()
Ejemplo n.º 32
0
from pgcli.main import PGCli
from mock import Mock

DEFAULT = PGCli().row_limit
LIMIT = DEFAULT + 1000

over_default = Mock()
over_default.configure_mock(rowcount=DEFAULT + 10)

over_limit = Mock()
over_limit.configure_mock(rowcount=LIMIT + 10)

low_count = Mock()
low_count.configure_mock(rowcount=1)


def test_default_row_limit():
    cli = PGCli()
    stmt = "SELECT * FROM students"
    result = cli._should_show_limit_prompt(stmt, low_count)
    assert result is False

    result = cli._should_show_limit_prompt(stmt, over_default)
    assert result is True


def test_set_row_limit():
    cli = PGCli(row_limit=LIMIT)
    stmt = "SELECT * FROM students"
    result = cli._should_show_limit_prompt(stmt, over_default)
    assert result is False
Ejemplo n.º 33
0
def test_missing_rc_dir(tmpdir):
    rcfile = str(tmpdir.join("subdir").join("rcfile"))

    PGCli(pgclirc_file=rcfile)
    assert os.path.exists(rcfile)
Ejemplo n.º 34
0
def test_no_limit():
    cli = PGCli(row_limit=0)
    stmt = "SELECT * FROM students"

    result = cli._should_show_limit_prompt(stmt, over_limit)
    assert result is False
Ejemplo n.º 35
0
def test_no_limit(over_limit):
    cli = PGCli(row_limit=0)
    stmt = "SELECT * FROM students"

    result = cli._should_show_limit_prompt(stmt, over_limit)
    assert result is False
Ejemplo n.º 36
0
def default_pgcli_obj():
    return PGCli()
Ejemplo n.º 37
0
def pgspecial():
    return PGCli().pgspecial