import pytest
from lxml import etree as ET

from yandex.maps.wiki.tasks import states
from yandex.maps.wiki.tasks import grinder
from yandex.maps.wiki.tasks import TASKS_NAMESPACE

NAMESPACES = {'ns': TASKS_NAMESPACE}

TASK_NAME = 'apply_shadow_attributes'

TEST_UID = 1
TEST_BRANCH_ID = 2
TEST_TASK_ID = 1


@pytest.mark.usefixtures('setup_acl_groups')
@pytest.mark.usefixtures('clean_schema')
@pytest.mark.parametrize('module_name', [TASK_NAME])
def test_apply_shadow_attributes(client, xmlschema, grinder_class):
    grinder_instance = grinder_class.return_value
    grinder_instance.submit.return_value = grinder.GrinderTaskId('test_id')
    grinder_instance.task_result.return_value = grinder.Result(states.PENDING, 'message')

    response = client.post('/tasks', data={
        'type': TASK_NAME,
        'uid': TEST_UID,
        'branch': TEST_BRANCH_ID
    })
    assert response.status_code == 200

    # test grinder

    grinder_instance.submit.assert_called_once_with({
        'type': TASK_NAME,
        'uid': TEST_UID,
        'taskId': TEST_TASK_ID,
        'branchId': TEST_BRANCH_ID
    })

    # test brief context

    root = ET.fromstring(response.data)
    xmlschema.assertValid(root)

    branch_element = root.find("./ns:task/ns:context/ns:apply-shadow-attributes-context/ns:branch", NAMESPACES)
    assert branch_element.text == str(TEST_BRANCH_ID)

    # test full context and result

    response = client.get('/tasks/' + str(TEST_TASK_ID), data={
        'uid': TEST_UID
    })
    assert response.status_code == 200

    root = ET.fromstring(response.data)
    xmlschema.assertValid(root)

    branch_element = root.find("./ns:task/ns:context/ns:apply-shadow-attributes-context/ns:branch", NAMESPACES)
    assert branch_element.text == str(TEST_BRANCH_ID)
