# authentic2 - versatile identity manager
# Copyright (C) 2010-2021 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/>.
# authentic2

import threading

from django.core.exceptions import MultipleObjectsReturned
from django.db import connection

from authentic2.custom_user.models import User
from authentic2.utils.models import safe_get_or_create


def test_safe_get_or_create(transactional_db, concurrency):
    EMAIL = 'john.doe@example.net'
    barrier = threading.Barrier(concurrency)
    users = []
    exceptions = []
    threads = []

    def thread_run():
        try:
            barrier.wait()
            user, created = safe_get_or_create(User, email=EMAIL, defaults={'email': EMAIL})
        except Exception as e:
            exceptions.append(e)
        else:
            if created:
                users.append(user)
        finally:
            connection.close()

    for _ in range(concurrency):
        threads.append(threading.Thread(target=thread_run))
        threads[-1].start()
    for thread in threads:
        thread.join()
    assert len(users) == 1
    assert User.objects.count() == 1
    assert all(isinstance(exception, MultipleObjectsReturned) for exception in exceptions)
    assert len(exceptions) < (0.1 * concurrency)  # 10% of failure is ok with a lot of concurrency
    users[0].delete()
