import pytest
import main
import pymysql.cursors


def get_query_result(sql, data=None):
    with pymysql.connect(host='localhost', user='root', password='test', database='db') as conn:
        with conn.cursor() as cursor:
            cursor.execute(sql, data)
            return cursor.fetchall()


def test_empty_questions_array():
    """Tests behavior of question parser function when input is empty"""
    questions = main.get_questions('../json/questions_empty.json')
    assert len(questions) == 0


def test_all_tables_created():
    """Tests if all tables from ddl.sql file are created successfully"""
    main.create_tables()
    table_count = get_query_result('SHOW TABLES IN db')[0][0]
    assert table_count == 10


def test_question_answer_data_inserted():
    """Tests if question and answer data are inserted into the DB"""
    main.create_tables()
    questions = main.get_questions('../json/questions_empty.json')
    main.insert_question_answer_data(questions)

    question_count = get_query_result('SELECT COUNT(*) FROM Question')[0][0]
    assert question_count > 0

    answer_count = get_query_result('SELECT COUNT(*) FROM Answer')[0][0]
    assert answer_count > 0
