from unittest import mock

import pytest
from django.core.management import call_command
from django.core.management.base import CommandError

from passerelle.apps.base_adresse.models import BaseAdresse


def test_cron_frequencies(db):
    for frequency in ('hourly', 'daily', 'weekly', 'monthly'):
        call_command('cron', frequency)
    with pytest.raises(CommandError):
        call_command('cron', 'randomly')


def test_cron_error(db, caplog):
    BaseAdresse.objects.create(slug='base-adresse')
    excep = Exception('hello')
    with mock.patch(
        'passerelle.apps.base_adresse.models.AddressResource.hourly', new=mock.Mock(side_effect=excep)
    ):
        with pytest.raises(CommandError):
            call_command('cron', 'hourly')
        assert caplog.records[0].message == 'connector "base-adresse.base-adresse" error running hourly job'
