django-countries icon indicating copy to clipboard operation
django-countries copied to clipboard

[Random Crash] Usually during unittests

Open DEKHTIARJonathan opened this issue 1 year ago • 1 comments

I'm having a weird crash - totally random and hard to reproduce:

tests/factories.py:68: in ProjectFactory
    country = random.choice(countries)[0]
/opt/hostedtoolcache/Python/3.13.1/x64/lib/python3.13/random.py:352: in choice
    return seq[self._randbelow(len(seq))]
/opt/hostedtoolcache/Python/3.13.1/x64/lib/python3.13/site-packages/django_countries/__init__.py:588: in __getitem__
    return next(itertools.islice(self.__iter__(), index, index + 1))
E   StopIteration

Probably means that self.__iter__() returns an empty result for some reasons. I believe it may happen when something doesn't get initialized. No idea what and why.

Any idea what the issue could be ?

DEKHTIARJonathan avatar Dec 20 '24 00:12 DEKHTIARJonathan

In case someone else has the issue, I haven't found the reason, but an additional "sleep" at the initialization addresses the issue:

  • conftest.py:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import time

import pytest


# Note: This wait time is necessary because of django-countries sometimes being not
# ready. Simple workaround to fix the issue and barely noticeable.
def pytest_sessionstart(session):
    """Hook to delay the start of the pytest session."""
    initial_wait_time = 0.2  # seconds
    print(f"Waiting for {initial_wait_time} seconds before starting pytest session...")  # noqa: T201
    time.sleep(initial_wait_time)

DEKHTIARJonathan avatar Jan 09 '25 04:01 DEKHTIARJonathan

Shrug -- not sure why this would be an issue, it's not something I've ever faced. If we find some more debugging information as to why then that'd be good, but I'll just close as a "weird bug with a workaround if you get it". Thanks for the report and the workaround, @DEKHTIARJonathan

SmileyChris avatar Nov 24 '25 19:11 SmileyChris

@SmileyChris FYI the workaround makes the issue a little less frequent but does still occur.

I think you have a race condition or lazy loading somewhere.

DEKHTIARJonathan avatar Nov 24 '25 20:11 DEKHTIARJonathan