from yaml import load, SafeLoader
from os import environ
from pytest import raises

from psycopg2 import connect, OperationalError


def test_postgresql_wrong_password():
    conf_file = f'{environ["MACHINE_TEST_DIR"]}/postgresql.yml'
    with open(conf_file) as yaml:
        data = load(yaml, Loader=SafeLoader)
    with raises(OperationalError):
        connect(host=data['address'], user=data['user'], password='a', database=data['dbname'])


def test_postgresql_connection():
    conf_file = f'{environ["MACHINE_TEST_DIR"]}/postgresql.yml'
    with open(conf_file) as yaml:
        data = load(yaml, Loader=SafeLoader)
    db = connect(host=data['address'], user=data['user'], password=data['password'], database=data['dbname'])
    db.close()


def test_postgresql_migration():
    conf_file = f'{environ["MACHINE_TEST_DIR"]}/postgresql.yml'
    with open(conf_file) as yaml:
        data = load(yaml, Loader=SafeLoader)
    db = connect(host=data['address'], user=data['user'], password=data['password'], database=data['dbname'])
    cursor = db.cursor()
    if 'FIRST_RUN' in environ:
        sql = """CREATE TABLE test (col  CHAR(20) NOT NULL)"""
        cursor.execute(sql)
        sql = """INSERT INTO test (col) VALUES ('test')"""
        cursor.execute(sql)
        db.commit()
    sql = """SELECT * FROM test"""
    cursor.execute(sql)
    results = cursor.fetchall()
    assert len(results) == 1
    results[0] == ('test',)
    cursor.close()
    db.close()


def test_postgresql_insert():
    conf_file = f'{environ["MACHINE_TEST_DIR"]}/postgresql.yml'
    with open(conf_file) as yaml:
        data = load(yaml, Loader=SafeLoader)
    db = connect(host=data['address'], user=data['user'], password=data['password'], database=data['dbname'])
    cursor = db.cursor()
    sql = """INSERT INTO test (col) VALUES ('test2')"""
    cursor.execute(sql)
    db.commit()
    #
    sql = """SELECT * FROM test WHERE col = 'test2'"""
    cursor.execute(sql)
    results = cursor.fetchall()
    assert len(results) == 1
    results[0] == ('test2',)
    cursor.close()
    db.close()


def test_postgresql_delete():
    conf_file = f'{environ["MACHINE_TEST_DIR"]}/postgresql.yml'
    with open(conf_file) as yaml:
        data = load(yaml, Loader=SafeLoader)
    db = connect(host=data['address'], user=data['user'], password=data['password'], database=data['dbname'])
    cursor = db.cursor()
    sql = """DELETE FROM test WHERE col = 'test2'"""
    cursor.execute(sql)
    db.commit()
    #
    sql = """SELECT * FROM test WHERE col = 'test2'"""
    cursor.execute(sql)
    results = cursor.fetchall()
    assert len(results) == 0
    cursor.close()
    db.close()
