summaryrefslogtreecommitdiffstats
path: root/tests/conftest.py
blob: 691f558f6ed3087ac6f3b0f5eaa9e796eb2aaefb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
#!/usr/bin/env python
# -*- coding: utf-8 -*-

# This file is part of passerelle-atreal-openads - a Publik connector to openADS
#
# Copyright (C) 2019 Atreal
#
# 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/>.

"""Configuration and fixtures for tests files."""

import os
import base64
import datetime

import pytest

from httmock import urlmatch, HTTMock, response

import django_webtest

from django.core.cache import cache
from django.core.files import File
from django.http.request import HttpRequest, QueryDict
from django.utils.encoding import force_text

from atreal_openads.models import (
    ForwardFile,
    Guichet,
    Collectivite,
    AtrealOpenads
)


@pytest.fixture(autouse=True)
def media(settings, tmpdir):
    """Set the media root to a temp dir created."""
    settings.MEDIA_ROOT = str(tmpdir.mkdir('media'))


@pytest.fixture
def app(request):
    """Return a Django WebTest application."""
    wtm = django_webtest.WebTestMixin()
    wtm._patch_settings()  # pylint: disable=protected-access
    request.addfinalizer(wtm._unpatch_settings)  # pylint: disable=protected-access
    cache.clear()
    return django_webtest.DjangoTestApp()


@pytest.fixture
def endpoint_dummy_cache(monkeypatch):
    """Monkey patch the Django cache to a 'dummy' one for all passerelle views."""
    from django.core.cache import caches
    import passerelle.views
    monkeypatch.setattr(
        passerelle.views, 'cache', caches['dummy'])


@urlmatch()
def internal_server_error(url, request):  # pylint: disable=unused-argument
    """Return an HTTP 500 error."""
    return response(500, 'Internal server error')


@pytest.fixture
def mock_500():
    """Mock an Internal Server Error."""
    with HTTMock(internal_server_error):
        yield None


@pytest.fixture
def relax_openssl(tmpdir):
    '''OpenSSL default configuration has been really strict for some years,
    this fixture set a temporary really permisive ciphers list.'''

    openssl_cnf_path = tmpdir / 'openssl.cnf'
    with openssl_cnf_path.open('w') as file_pt:
        file_pt.write(u'''
[default_conf]
ssl_conf = ssl_sect

[ssl_sect]
system_default = system_default_sect

[system_default_sect]
CipherString = ALL''')
    old_value = os.environ.get('OPENSSL_CONF', None)
    try:
        os.environ['OPENSSL_CONF'] = str(openssl_cnf_path)
        yield
    finally:
        if old_value is None:
            del os.environ['OPENSSL_CONF']
        else:
            os.environ['OPENSSL_CONF'] = old_value


@pytest.fixture
def fake_conf():
    """Return a dictionnary containing configuration items."""
    conf = {
        'CONNECTOR_NAME': 'atreal-openads',
        'CONNECTOR_SLUG': 'atreal',
        'COLLECTIVITE': 79,
        'OPENADS_API_LOGIN': 'publik-passerelle',
        'OPENADS_API_PASSWORD': force_text(base64.urlsafe_b64encode(os.urandom(20))),
        'OPENADS_API_URL': 'http://openads.api/',

        'FAKE_COOKIE_CRSF': force_text(base64.urlsafe_b64encode(os.urandom(20))),
        'FAKE_NUMERO_DOSSIER': force_text(base64.urlsafe_b64encode(os.urandom(10))),

        'TESTS_DIR': os.path.dirname(__file__)
    }
    conf['RESOURCES_DIR'] = os.path.join(conf['TESTS_DIR'], 'resources')
    conf['TEST_FILE_CERFA_DIA'] = os.path.join(conf['RESOURCES_DIR'], 'cerfa_10072-02.pdf')
    conf['TEST_FILE_PLAN_CADASTRAL'] = os.path.join(conf['RESOURCES_DIR'], 'plancadastral.pdf')
    return conf


@pytest.fixture
# pylint: disable=unused-argument,redefined-outer-name,invalid-name
def atreal_openads(fake_conf, db):
    """Return an instance of a connector AtrealOpenads."""
    return AtrealOpenads.objects.create(  # pylint: disable=no-member
        slug=fake_conf['CONNECTOR_SLUG'],
        default_collectivite_openADS_id=fake_conf['COLLECTIVITE'],
        openADS_API_url=fake_conf['OPENADS_API_URL'],
        basic_auth_username=fake_conf['OPENADS_API_LOGIN'],
        basic_auth_password=fake_conf['OPENADS_API_PASSWORD']
    )


@pytest.fixture
# pylint: disable=unused-argument,redefined-outer-name,invalid-name
def collectivite_1(db, atreal_openads):
    """Return an instance of a 'Collectivite'."""
    return Collectivite.objects.create(  # pylint: disable=no-member
        name=u'Macollectivité',
        connecteur=atreal_openads,
        openADS_id='3'
    )


@pytest.fixture
# pylint: disable=unused-argument,redefined-outer-name,invalid-name
def collectivite_1_guichet(db, atreal_openads, collectivite_1):
    """Return an instance of a 'Guichet'."""
    return Guichet.objects.create(  # pylint: disable=no-member
        collectivite=collectivite_1,
        ouverture_jour_h=datetime.time(9, 0),
        fermeture_jour_h=datetime.time(17, 0),
        ouverture_sem_d=1,  # Lundi
        fermeture_sem_d=5,  # Vendredi
        ouverture_sem_h=datetime.time(8, 30),
        fermeture_sem_h=datetime.time(12, 15)
    )


@pytest.fixture
# pylint: disable=unused-argument,redefined-outer-name,invalid-name
def forwardfile_1(fake_conf, db, atreal_openads, collectivite_1):
    """Return an instance of a 'ForwardFile'."""
    return ForwardFile.objects.create(  # pylint: disable=no-member
        connecteur=atreal_openads,
        collectivite=collectivite_1,
        numero_demande='45641531',
        numero_dossier=fake_conf['FAKE_NUMERO_DOSSIER'],
        type_fichier='CERFA',
        orig_filename=os.path.basename(fake_conf['TEST_FILE_CERFA_DIA']),
        content_type='application/pdf',
        file_hash='ffdf456fdsvgb4bgfb6g4f5b',
        upload_file=File(open(fake_conf['TEST_FILE_CERFA_DIA'], 'rb'),
            name=os.path.basename(fake_conf['TEST_FILE_CERFA_DIA'])),
        upload_status='pending'
    )


@pytest.fixture
# pylint: disable=redefined-outer-name,invalid-name
def forwardfile_2(fake_conf, connecteur=None, collectivite=None):
    """Return a forward file object with some values but not saved in db."""
    return ForwardFile(
        connecteur=connecteur,
        collectivite=collectivite,
        numero_demande='45641531',
        numero_dossier=fake_conf['FAKE_NUMERO_DOSSIER'],
        type_fichier='CERFA',
        orig_filename=os.path.basename(fake_conf['TEST_FILE_CERFA_DIA']),
        content_type='application/pdf',
        file_hash='ffdf456fdsvgb4bgfb6g4f5b',
        upload_file=File(open(fake_conf['TEST_FILE_CERFA_DIA'], 'rb'),
            name=os.path.basename(fake_conf['TEST_FILE_CERFA_DIA'])),
        upload_status='pending'
    )


@pytest.fixture
def request_1():
    """Return an HttpRequest object with some default values."""
    req = HttpRequest()
    req._body = ''  # pylint: disable=protected-access
    req.path = '/'
    req.method = 'GET'
    req.encoding = 'utf-8'
    req.GET = QueryDict(mutable=True)  # required because of encoding setter
    req.POST = QueryDict(mutable=True)  # required because of encoding setter
    req.content_type = 'application/json'
    req.content_params = None
    req.COOKIES = {}
    req.META = {}
    req._read_started = False  # pylint: disable=protected-access
    return req