Skip to content

Commit

Permalink
fix tests
Browse files Browse the repository at this point in the history
  • Loading branch information
jefer94 committed May 28, 2024
1 parent 9098034 commit 1804393
Show file tree
Hide file tree
Showing 10 changed files with 79 additions and 52 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -88,14 +88,17 @@ def setup():
def db(data={}):
return {
'delta': timedelta(seconds=3600),
'id': 0,
'ran_at': None,
'task_module': '',
'task_name': '',
**data,
}


def remove_ids(dbs):
return [x for x in dbs if x.pop('id')]


class TestIssue:

@pytest.mark.parametrize('with_supervisor, with_issues', [
Expand Down Expand Up @@ -131,10 +134,9 @@ def tests_older_issues_are_removed(self, database: dfx.Database, supervisor: Sup
} in supervisor.list()
assert supervisor.log('breathecode.payments.supervisors', 'supervise_all_consumption_sessions') == []
assert db({
'id': 1,
'task_module': 'breathecode.payments.supervisors',
'task_name': 'supervise_all_consumption_sessions',
}) in database.list_of('monitoring.Supervisor')
}) in remove_ids(database.list_of('monitoring.Supervisor'))
assert database.list_of('monitoring.SupervisorIssue') == []
assert call(supervisor.id('breathecode.payments.supervisors',
'supervise_all_consumption_sessions')) in run_supervisor_mock.call_args_list
Expand Down Expand Up @@ -166,10 +168,9 @@ def tests_recent_issues_keeps__available_attempts(self, bc: Breathecode, databas
assert supervisor.log('breathecode.payments.supervisors',
'supervise_all_consumption_sessions') == [x.error for x in model.supervisor_issue]
assert db({
'id': 1,
'task_module': 'breathecode.payments.supervisors',
'task_name': 'supervise_all_consumption_sessions',
}) in database.list_of('monitoring.Supervisor')
}) in remove_ids(database.list_of('monitoring.Supervisor'))
assert database.list_of('monitoring.SupervisorIssue') == bc.format.to_dict(model.supervisor_issue)
assert call(supervisor.id('breathecode.payments.supervisors',
'supervise_all_consumption_sessions')) in run_supervisor_mock.call_args_list
Expand Down Expand Up @@ -201,10 +202,9 @@ def tests_recent_issues_keeps__no_available_attempts(self, bc: Breathecode, data
assert supervisor.log('breathecode.payments.supervisors',
'supervise_all_consumption_sessions') == [x.error for x in model.supervisor_issue]
assert db({
'id': 1,
'task_module': 'breathecode.payments.supervisors',
'task_name': 'supervise_all_consumption_sessions',
}) in database.list_of('monitoring.Supervisor')
}) in remove_ids(database.list_of('monitoring.Supervisor'))
assert database.list_of('monitoring.SupervisorIssue') == bc.format.to_dict(model.supervisor_issue)
assert call(supervisor.id('breathecode.payments.supervisors',
'supervise_all_consumption_sessions')) in run_supervisor_mock.call_args_list
Expand Down Expand Up @@ -245,12 +245,11 @@ def tests_pending_to_be_scheduled(self, database: dfx.Database, supervisor: Supe
} in supervisor.list()
assert supervisor.log('breathecode.payments.supervisors', 'supervise_all_consumption_sessions') == []
assert db({
'id': 1,
'delta': delta,
'ran_at': ran_at,
'task_module': 'breathecode.payments.supervisors',
'task_name': 'supervise_all_consumption_sessions',
}) in database.list_of('monitoring.Supervisor')
}) in remove_ids(database.list_of('monitoring.Supervisor'))
assert database.list_of('monitoring.SupervisorIssue') == []
assert call(supervisor.id('breathecode.payments.supervisors',
'supervise_all_consumption_sessions')) in run_supervisor_mock.call_args_list
Expand Down Expand Up @@ -283,12 +282,11 @@ def tests_in_cooldown(self, database: dfx.Database, supervisor: Supervisor, patc
} in supervisor.list()
assert supervisor.log('breathecode.payments.supervisors', 'supervise_all_consumption_sessions') == []
assert db({
'id': 1,
'delta': delta,
'ran_at': ran_at,
'task_module': 'breathecode.payments.supervisors',
'task_name': 'supervise_all_consumption_sessions',
}) in database.list_of('monitoring.Supervisor')
}) in remove_ids(database.list_of('monitoring.Supervisor'))
assert database.list_of('monitoring.SupervisorIssue') == []
assert call(supervisor.id('breathecode.payments.supervisors',
'supervise_all_consumption_sessions')) not in run_supervisor_mock.call_args_list
Expand Down
6 changes: 3 additions & 3 deletions breathecode/notify/receivers.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,12 @@
from breathecode.mentorship.models import MentorshipSession
from breathecode.mentorship.serializers import SessionHookSerializer
from breathecode.mentorship.signals import mentorship_session_status
from breathecode.payments.models import PlanFinancing, Subscription
from breathecode.payments.serializers import GetPlanFinancingSerializer, GetSubscriptionSerializer
from breathecode.payments.signals import planfinancing_created, subscription_created
from breathecode.registry.models import Asset
from breathecode.registry.serializers import AssetHookSerializer
from breathecode.registry.signals import asset_status_updated
from breathecode.payments.signals import subscription_created, planfinancing_created
from breathecode.payments.models import PlanFinancing, Subscription
from breathecode.payments.serializers import GetPlanFinancingSerializer, GetSubscriptionSerializer

from .tasks import send_mentorship_starting_notification
from .utils.hook_manager import HookManager
Expand Down
9 changes: 4 additions & 5 deletions breathecode/payments/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -1090,11 +1090,11 @@ def save(self, *args, **kwargs) -> None:
self.full_clean()
on_create = self.pk is None

super().save(*args, **kwargs)

if on_create:
signals.planfinancing_created.send(instance=self, sender=self.__class__)

return super().save(*args, **kwargs)


class Subscription(AbstractIOweYou):
"""Allows to create a subscription to a plan and services."""
Expand Down Expand Up @@ -1146,14 +1146,13 @@ def clean(self) -> None:

def save(self, *args, **kwargs) -> None:
self.full_clean()

on_create = self.pk is None

super().save(*args, **kwargs)

if on_create:
signals.subscription_created.send(instance=self, sender=self.__class__)

return super().save(*args, **kwargs)


class SubscriptionServiceItem(models.Model):
subscription = models.ForeignKey(Subscription, on_delete=models.CASCADE, help_text='Subscription')
Expand Down
1 change: 1 addition & 0 deletions capyc/core/pytest/fixtures/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@
from .image import * # noqa: F401
from .no_http_requests import * # noqa: F401
from .random import * # noqa: F401
from .seed import * # noqa: F401
11 changes: 6 additions & 5 deletions capyc/core/pytest/fixtures/fake.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
from typing import Generator
from typing import Generator, Optional

import pytest
from faker import Faker as Fake

__all__ = ['fake', 'Fake']

FAKE = Fake()

@pytest.fixture(autouse=True)
def fake(seed: Optional[int]) -> Generator[Fake, None, None]:
f = Fake()
f.seed_instance(seed)

@pytest.fixture(scope='module')
def fake() -> Generator[Fake, None, None]:
return FAKE
yield f
11 changes: 6 additions & 5 deletions capyc/core/pytest/fixtures/random.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import random as r
import string
from typing import Any, Dict, Generator, Tuple, final
from typing import Any, Dict, Generator, Optional, Tuple, final

import pytest
from faker import Faker
Expand All @@ -14,8 +14,9 @@ class Random:
Random utils.
"""

def __init__(self, fake: Faker) -> None:
def __init__(self, fake: Faker, seed: Optional[int]) -> None:
self._fake = fake
r.seed(seed)

def seed(self, a=None, version=2) -> None:
"""Initialize internal state from a seed.
Expand Down Expand Up @@ -104,10 +105,10 @@ def string(self, size=0, lower=False, upper=False, symbol=False, number=False) -
return ''.join(r.choices(chars, k=size))


@pytest.fixture()
def random(fake) -> Generator[Random, None, None]:
@pytest.fixture(autouse=True)
def random(fake: Faker, seed: Optional[int]) -> Generator[Random, None, None]:
"""Image fixtures."""

x = Random(fake)
x = Random(fake, seed)

yield x
43 changes: 43 additions & 0 deletions capyc/core/pytest/fixtures/seed.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import random
from typing import Generator, Optional

import pytest

__all__ = ['seed', 'Seed', 'pytest_addoption', 'pytest_terminal_summary']

type Seed = Optional[int]
SEED = random.randint(0, 2 ** 32 - 1)
seed_used = None
SEED_KEY = '_+* SEED *+_'
END_KEY = '_+* END *+_'

def pytest_addoption(parser: pytest.Parser):
try:
parser.addoption('--seed', action='store', default=None, type=int, help='Set the random seed for tests')
except Exception:
...


def pytest_terminal_summary(terminalreporter, config: pytest.Config) -> None:
...
# if hasattr(config, END_KEY) is False:
# setattr(config, END_KEY, True)
# seed = getattr(config, SEED_KEY, None)
# terminalreporter.write_sep("=", "Capy Core Summary")
# terminalreporter.write_line(f"Seed: {seed}")



@pytest.fixture(autouse=True)
def seed(request: pytest.FixtureRequest) -> Generator[Optional[int], None, None]:
global SEED

seed = request.config.getoption('--seed')
if seed is None:
seed = SEED

# if hasattr(request.config, SEED_KEY) is False:
# setattr(request.config, SEED_KEY, seed)

yield seed
print(f'Seed used: {seed}')
2 changes: 1 addition & 1 deletion capyc/django/pytest/fixtures/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -524,5 +524,5 @@ def create(cls, **models):


@pytest.fixture
def database(db) -> Generator[Database, None, None]:
def database(db, seed) -> Generator[Database, None, None]:
yield Database()
2 changes: 1 addition & 1 deletion conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ def get_kwargs(random: Random) -> Generator[callable, None, None]:


@pytest.fixture
def bc():
def bc(seed):
return Breathecode(None)


Expand Down
26 changes: 5 additions & 21 deletions scripts/parallel_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,41 +2,25 @@

from __future__ import absolute_import

import argparse
import os
import random
import subprocess
import sys


def parse_arguments():
parser = argparse.ArgumentParser(description='Run pytest with optional seed.')
parser.add_argument('--seed', type=int, help='Seed for randomness')
parser.add_argument('pytest_args', nargs='*', help='Arguments to pass to pytest')
return parser.parse_args()


if __name__ == '__main__':
args = parse_arguments()
args = ''

if args.seed is None:
seed = random.randint(0, 4294967295)
else:
seed = args.seed
if len(sys.argv) > 1:
sys.argv.pop(0)
args = ' '.join(sys.argv)

pytest_args = ' '.join(args.pytest_args)
command = f'pytest {pytest_args} --disable-pytest-warnings -n auto --nomigrations --durations=1'
command = f'pytest {args} --disable-pytest-warnings -n auto --nomigrations --durations=1'
# command = f'pytest {pytest_args} -n auto --nomigrations --durations=1'

env = os.environ.copy()
env['ENV'] = 'test'
env['RANDOM_SEED'] = str(seed)

exit_code = subprocess.run(command, env=env, shell=True).returncode

print()
print(f'Seed {seed} used, you can provide it locally to reproduce random errors')

# python doesn't return 256
if exit_code:
sys.exit(1)

0 comments on commit 1804393

Please sign in to comment.