Add kfet_config tests

- KFetConfig `set` method now takes model instance instead of their pk
  for this type of entries.
- Add tests for KFetConfig class: tests against types currently used by
  kfet app (duration, modelinstance, decimal).
- These tests are located in `kfet/tests/test_config.py`. We should
  separate tests suites by file like this, considering what they are about.
- KFetConfig method `set_many` renamed to `set` (because it also updates
  only one).
This commit is contained in:
Aurélien Delobelle 2017-04-04 17:05:55 +02:00
parent ce2a05766d
commit 714903210c
4 changed files with 83 additions and 13 deletions

View file

@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-
from django.core.exceptions import ValidationError
from django.db import models
from djconfig import config
@ -15,26 +16,51 @@ class KFetConfig(object):
prefix = 'kfet_'
def __getattr__(self, key):
return getattr(config, self.get_dj_key(key))
return getattr(config, self._get_dj_key(key))
def list(self):
"""Get list of kfet app configuration.
Returns:
(key, value) for each configuration entry as list.
"""
# prevent circular imports
from kfet.forms import KFetConfigForm
return [(field.label, getattr(config, name), )
for name, field in KFetConfigForm.base_fields.items()]
def get_dj_key(self, key):
def _get_dj_key(self, key):
return '{}{}'.format(self.prefix, key)
def set_many(self, **kwargs):
def set(self, **kwargs):
"""Update configuration value(s).
Args:
**kwargs: Keyword arguments. Keys must be in kfet config.
Config entries are updated to given values.
"""
# prevent circular imports
from kfet.forms import KFetConfigForm
# get old config
new_cfg = KFetConfigForm().initial
new_cfg.update({self.get_dj_key(key): value
for key, value in kwargs.items()})
# update to new config
for key, value in kwargs.items():
dj_key = self._get_dj_key(key)
if isinstance(value, models.Model):
new_cfg[dj_key] = value.pk
else:
new_cfg[dj_key] = value
# save new config
cfg_form = KFetConfigForm(new_cfg)
if cfg_form.is_valid():
cfg_form.save()
else:
raise ValidationError()
raise ValidationError(
'Invalid values in kfet_config.set: %(fields)s',
params={'fields': list(cfg_form.errors)})
kfet_config = KFetConfig()

View file

@ -1,5 +0,0 @@
# -*- coding: utf-8 -*-
from django.test import TestCase
# Écrire les tests ici

49
kfet/tests/test_config.py Normal file
View file

@ -0,0 +1,49 @@
# -*- coding: utf-8 -*-
from decimal import Decimal
from django.test import TestCase
from django.utils import timezone
import djconfig
from gestioncof.models import User
from kfet.config import kfet_config
from kfet.models import Account
class ConfigTest(TestCase):
"""Tests suite for kfet configuration."""
def setUp(self):
# load configuration as in djconfig middleware
djconfig.reload_maybe()
def test_get(self):
self.assertTrue(hasattr(kfet_config, 'subvention_cof'))
def test_set_decimal(self):
"""Test field of decimal type."""
subvention_cof = Decimal('10')
# IUT
kfet_config.set(subvention_cof=subvention_cof)
# check
self.assertEqual(kfet_config.subvention_cof, subvention_cof)
def test_set_modelinstance(self):
"""Test field of model instance type."""
user = User.objects.create(username='foo_user')
account = Account.objects.create(trigramme='FOO',
cofprofile=user.profile)
# IUT
kfet_config.set(addcost_for=account)
# check
self.assertEqual(kfet_config.addcost_for, account)
def test_set_duration(self):
"""Test field of duration type."""
cancel_duration = timezone.timedelta(days=2, hours=4)
# IUT
kfet_config.set(cancel_duration=cancel_duration)
# check
self.assertEqual(kfet_config.cancel_duration, cancel_duration)

View file

@ -944,8 +944,8 @@ def kpsul_update_addcost(request):
account = trigramme and Account.objects.get(trigramme=trigramme) or None
amount = addcost_form.cleaned_data['amount']
kfet_config.set_many(addcost_for=account and account.pk or None,
addcost_amount=amount)
kfet_config.set(addcost_for=account,
addcost_amount=amount)
data = {
'addcost': {