1
1
mirror of https://github.com/dbcli/pgcli.git synced 2024-10-06 18:27:29 +03:00
pgcli/tests/utils.py

70 lines
2.0 KiB
Python
Raw Normal View History

import pytest
2015-02-09 01:54:57 +03:00
import psycopg2
import psycopg2.extras
2015-01-08 01:17:55 +03:00
from pgcli.main import format_output
from pgcli.pgexecute import register_json_typecasters
# TODO: should this be somehow be divined from environment?
POSTGRES_USER, POSTGRES_HOST = 'postgres', 'localhost'
def db_connection(dbname=None):
2015-05-14 18:40:27 +03:00
conn = psycopg2.connect(user=POSTGRES_USER, host=POSTGRES_HOST, database=dbname)
conn.autocommit = True
return conn
try:
conn = db_connection()
CAN_CONNECT_TO_DB = True
SERVER_VERSION = conn.server_version
json_types = register_json_typecasters(conn, lambda x: x)
JSON_AVAILABLE = 'json' in json_types
JSONB_AVAILABLE = 'jsonb' in json_types
except:
CAN_CONNECT_TO_DB = JSON_AVAILABLE = JSONB_AVAILABLE = False
SERVER_VERSION = 0
dbtest = pytest.mark.skipif(
not CAN_CONNECT_TO_DB,
reason="Need a postgres instance at localhost accessible by user 'postgres'")
requires_json = pytest.mark.skipif(
not JSON_AVAILABLE,
reason='Postgres server unavailable or json type not defined')
requires_jsonb = pytest.mark.skipif(
not JSONB_AVAILABLE,
reason='Postgres server unavailable or jsonb type not defined')
def create_db(dbname):
with db_connection().cursor() as cur:
try:
cur.execute('''CREATE DATABASE _test_db''')
except:
pass
def drop_tables(conn):
with conn.cursor() as cur:
cur.execute('''
DROP SCHEMA public CASCADE;
CREATE SCHEMA public;
DROP SCHEMA IF EXISTS schema1 CASCADE;
DROP SCHEMA IF EXISTS schema2 CASCADE''')
2015-01-08 01:17:55 +03:00
def run(executor, sql, join=False, expanded=False, pgspecial=None):
2015-01-08 01:17:55 +03:00
" Return string output for the sql to be run "
result = []
for title, rows, headers, status in executor.run(sql, pgspecial):
result.extend(format_output(title, rows, headers, status, 'psql',
expanded=expanded))
if join:
result = '\n'.join(result)
return result