# barbacompta - invoicing for dummies
# Copyright (C) 2010-2020 Entr'ouvert
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import httmock
import pytest
import requests

from eo_gestion.chorus import chorus


@pytest.fixture(autouse=True)
def chorus_setup(settings, monkeypatch):
    settings.CHORUS_PLATFORM = 'qualif'
    settings.CHORUS_TECH_USER_LOGIN = 'login'
    settings.CHORUS_TECH_USER_PASSWORD = 'password'
    monkeypatch.setattr(chorus, 'get_piste_access_token', lambda: 'token')


PDF_BYTES = b'1'
PDF_NAME = 'F202000001.pdf'


@httmock.urlmatch()
def chorus_ok(url, request):
    return httmock.response(200, {'ok': 1})


@httmock.urlmatch()
def chorus_connection_error(url, request):
    raise requests.ConnectionError('bouh')


@httmock.urlmatch()
def chorus_error_500(url, request):
    return httmock.response(
        500,
        b'Pas content \xe9',
        headers={
            'Header Pourri': 'Héhé'.encode('latin1'),
            'Header-Ok': 'ok',
        },
    )


def test_push_to_chorus_ok():
    with httmock.HTTMock(chorus_ok):
        result = chorus.push_to_chorus(PDF_BYTES, PDF_NAME)
    assert result == {'http.response.status-code': 200, 'ok': 1}


def test_push_to_chorus_connection_error():
    with httmock.HTTMock(chorus_connection_error):
        result = chorus.push_to_chorus(PDF_BYTES, PDF_NAME)
    assert result == {'http.requests_error': 'bouh'}


def test_push_to_chorus_error_500():
    with httmock.HTTMock(chorus_error_500):
        result = chorus.push_to_chorus(PDF_BYTES, PDF_NAME)
    assert result == {
        'http.response.status-code': 500,
        'http.response.body': "b'Pas content \\xe9'",
        'http.response.headers': {
            'Header Pourri': 'H�h�',
            'Header-Ok': 'ok',
        },
    }
