Files @ cec84c4675ce
Branch filter:

Location: kallithea/conftest.py - annotation

Thomas De Schampheleire
tests: remove race condition in test_forgot_password

One in so many times, test_forgot_password failed with:

kallithea/tests/functional/test_login.py:427: in test_forgot_password
assert '\n%s\n' % token in body
E assert ('\n%s\n' % 'd71ad3ed3c6ca637ad00b7098828d33c56579201') in
"Password Reset Request\n\nHello passwd reset,\n\nWe have received a
request to reset the password for your account.\n\nTo
s...7e89326ca372ade1d424dafb106d824cddb\n\nIf it weren't you who
requested the password reset, just disregard this message.\n"

i.e. the expected token is not the one in the email.

The token is calculated based on a timestamp (among others). And the token
is calculated twice: once in the real code and once in the test, each time
on a slightly different timestamp. Even though there is flooring of the
timestamp to a second resolution, there will always be a race condition
where the two timestamps floor to a different second, e.g. 4.99 vs 5.01.

The problem can be reproduced reliably by adding a sleep of e.g. 2 seconds
before generating the password reset mail (after the test has already
calculated the expected token).

Solve this problem by mocking the time.time() used to generate the
timestamp, so that the timestamp used for the real token is the same as the
one used for the expected token in the test.
import os

import mock
import pytest


here = os.path.dirname(__file__)

def pytest_ignore_collect(path):
    # ignore all files outside the 'kallithea' directory
    if not str(path).startswith(os.path.join(here, 'kallithea')):
        return True

    # during doctest verification, normally all python files will be imported.
    # Thus, files that cannot be imported normally should be ignored.
    # Files that generate ImportErrors are ignored via
    # '--doctest-ignore-import-errors' (pytest.ini)
    kallithea_ignore_paths = (
        # AttributeError: 'module' object has no attribute 'config'
        '/kallithea/alembic/env.py',
        # collection of the following file messes up the rest of test execution
        '/kallithea/tests/scripts/manual_test_concurrency.py',
    )
    if str(path).endswith(kallithea_ignore_paths):
        return True

@pytest.fixture()
def doctest_mock_ugettext(request):
    """Mock ugettext ('_') in the module using this fixture.

    Intended to be used for doctests.

    In a doctest, enable this fixture using:
        >>> getfixture('doctest_mock_ugettext')
    """
    m = __import__(request.module.__name__, globals(), locals(), [None], 0)
    with mock.patch.object(m, '_', lambda s: s):
        yield