from ..db.models import Datum, TestDatum, Action, ActionType


def test_can_create_test(client, user, test_dict):
    assert len(user.tests) == 0
    resp = client.post('/tests', headers=user.auth_headers, json=test_dict)
    assert 'created_at' in resp
    assert 'id' in resp
    assert set(resp['data'].keys()) == set(map(lambda d: d['label'], test_dict['data']))
    for key in resp['data'].keys():
        datum_id = resp['data'][key]['id']
        datum = Datum.query.filter_by(id=datum_id).first()
        test_datum = TestDatum.query.filter_by(test_id=resp['id'], datum_id=datum_id).first()
        assert datum.name == resp['data'][key]['name']
        assert datum.type.value == resp['data'][key]['type']
        assert datum.value == resp['data'][key]['value']
        assert test_datum.disposition.value == resp['data'][key]['disposition']
    assert len(user.tests) == 1

    action = Action.query.filter_by(type=ActionType.CREATE_TEST, user_id=user.id, obj1_id=resp['id']).first()
    assert action is not None


def test_cant_create_test_with_duplicate_labels(client, user, test_dict):
    label_to_duplicate = list(map(lambda d: d['label'], test_dict['data']))[0]
    test_dict['data'].append({'label': label_to_duplicate})
    resp = client.post('/tests', headers=user.auth_headers, json=test_dict, raw=True)
    assert resp.status_code == 500
    assert 'duplicate test data label' in resp.get_json()['error']


def test_cant_create_test_with_datum_that_doesnt_exist(client, user, test_dict):
    test_dict['data'].append({'label': 'foo', 'datum_id': 0})
    resp = client.post('/tests', headers=user.auth_headers, json=test_dict, raw=True)
    assert resp.status_code == 500
    resp = resp.get_json()
    assert 'it does not exist' in resp['error']
    assert resp['datum_id'] == 0


def test_cant_create_duplicate_test(client, user, test_dict):
    client.post('/tests', headers=user.auth_headers, json=test_dict)
    resp = client.post('/tests', headers=user.auth_headers, json=test_dict, raw=True)
    assert resp.status_code == 500
    resp = resp.get_json()
    assert 'already exists' in resp['error']
    assert resp['test_id'] is not None


def test_can_get_test_details(client, user, test):
    resp = client.get(f'/tests/{test.id}', headers=user.auth_headers)
    assert resp['id'] == test.id

    action = Action.query.filter_by(type=ActionType.LIST_TEST, user_id=user.id, obj1_id=test.id).first()
    assert action is not None
