From 0f8b50b02c3346a2f2f7a43dde0c9a80074cbee8 Mon Sep 17 00:00:00 2001
From: Paul Marillonnet <pmarillonnet@entrouvert.com>
Date: Wed, 26 Jan 2022 10:20:19 +0100
Subject: [PATCH 2/3] tests: initiate module, for later unit testing
 implementation (#61045)

---
 tests/conftest.py | 80 +++++++++++++++++++++++++++++++++++++++++++++++
 tests/settings.py | 22 +++++++++++++
 tests/test_all.py | 11 +++++++
 tests/utils.py    | 24 ++++++++++++++
 4 files changed, 137 insertions(+)
 create mode 100644 tests/conftest.py
 create mode 100644 tests/settings.py
 create mode 100644 tests/test_all.py
 create mode 100644 tests/utils.py

diff --git a/tests/conftest.py b/tests/conftest.py
new file mode 100644
index 0000000..fad7911
--- /dev/null
+++ b/tests/conftest.py
@@ -0,0 +1,80 @@
+import django_webtest
+import pytest
+
+try:
+    import pathlib
+except ImportError:
+    import pathlib2 as pathlib
+
+from django.contrib.auth import get_user_model
+from django_rbac.utils import get_ou_model
+
+User = get_user_model()
+TEST_DIR = pathlib.Path(__file__).parent
+
+
+@pytest.fixture
+def app(request, db, settings, tmpdir):
+    wtm = django_webtest.WebTestMixin()
+    wtm._patch_settings()
+    request.addfinalizer(wtm._unpatch_settings)
+    settings.MEDIA_DIR = str(tmpdir.mkdir('media'))
+    return django_webtest.DjangoTestApp(extra_environ={'HTTP_HOST': 'localhost'})
+
+
+class AllHook:
+    def __init__(self):
+        self.calls = {}
+        from authentic2 import hooks
+
+        hooks.get_hooks.cache.clear()
+
+    def __call__(self, hook_name, *args, **kwargs):
+        calls = self.calls.setdefault(hook_name, [])
+        calls.append({'args': args, 'kwargs': kwargs})
+
+    def __getattr__(self, name):
+        return self.calls.get(name, [])
+
+    def clear(self):
+        self.calls = {}
+
+
+@pytest.fixture
+def user(db):
+    user = User.objects.create(
+        username='john.doe',
+        email='john.doe@example.net',
+        first_name='John',
+        last_name='Doe',
+        email_verified=True,
+    )
+    user.set_password('john.doe')
+    return user
+
+
+@pytest.fixture
+def hooks(settings):
+    if hasattr(settings, 'A2_HOOKS'):
+        hooks = settings.A2_HOOKS
+    else:
+        hooks = settings.A2_HOOKS = {}
+    hook = hooks['__all__'] = AllHook()
+    yield hook
+    hook.clear()
+    del settings.A2_HOOKS['__all__']
+
+
+@pytest.fixture
+def admin(db):
+    user = User(username='admin', email='admin@example.net', is_superuser=True, is_staff=True)
+    user.set_password('admin')
+    user.save()
+    return user
+
+
+@pytest.fixture(autouse=True)
+def clean_caches():
+    from authentic2.apps.journal.models import event_type_cache
+
+    event_type_cache.cache.clear()
diff --git a/tests/settings.py b/tests/settings.py
new file mode 100644
index 0000000..e0bd2f7
--- /dev/null
+++ b/tests/settings.py
@@ -0,0 +1,22 @@
+import os
+
+ALLOWED_HOSTS = ['localhost']
+
+DATABASES = {
+    'default': {
+        'ENGINE': 'django.db.backends.postgresql_psycopg2',
+        'NAME': 'authentic2-auth-fedict',
+    }
+}
+
+if 'postgres' in DATABASES['default']['ENGINE']:
+    for key in ('PGPORT', 'PGHOST', 'PGUSER', 'PGPASSWORD'):
+        if key in os.environ:
+            DATABASES['default'][key[2:]] = os.environ[key]
+
+LANGUAGE_CODE = 'en'
+A2_FC_CLIENT_ID = ''
+A2_FC_CLIENT_SECRET = ''
+
+# test hook handlers
+A2_HOOKS_PROPAGATE_EXCEPTIONS = True
diff --git a/tests/test_all.py b/tests/test_all.py
new file mode 100644
index 0000000..7de9df8
--- /dev/null
+++ b/tests/test_all.py
@@ -0,0 +1,11 @@
+import pytest
+from django.contrib.auth import get_user_model
+from utils import login
+
+User = get_user_model()
+
+pytestmark = pytest.mark.django_db
+
+
+def test_dummy(app):
+    assert 1
diff --git a/tests/utils.py b/tests/utils.py
new file mode 100644
index 0000000..f8fae5c
--- /dev/null
+++ b/tests/utils.py
@@ -0,0 +1,24 @@
+from authentic2.utils.misc import make_url
+from django.urls import reverse
+
+
+def login(app, user, path=None, password=None, remember_me=None):
+    if path:
+        real_path = make_url(path)
+        login_page = app.get(real_path, status=302).maybe_follow()
+    else:
+        login_page = app.get(reverse('auth_login'))
+    assert login_page.request.path == reverse('auth_login')
+    form = login_page.form
+    form.set('username', user.username if hasattr(user, 'username') else user)
+    # password is supposed to be the same as username
+    form.set('password', password or user.username)
+    if remember_me is not None:
+        form.set('remember_me', bool(remember_me))
+    response = form.submit(name='login-password-submit').follow()
+    if path:
+        assert response.request.path == real_path
+    else:
+        assert response.request.path == reverse('auth_homepage')
+    assert '_auth_user_id' in app.session
+    return response
-- 
2.34.1

