This repository has been archived on 2023-02-22. You can view files and clone it, but cannot push or open issues or pull requests.
passerelle-atreal-openads/tests/conftest.py

226 lines
7.4 KiB
Python

#!/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