kfet -- Init KFetConfig, even without request, for easy testing

This commit is contained in:
Aurélien Delobelle 2018-10-02 12:02:24 +02:00
parent 0f688a8f1c
commit 22011faba9

View file

@ -1,25 +1,39 @@
from django.core.exceptions import ValidationError from django.core.exceptions import ValidationError
from django.db import models from django.db import models
from djconfig import config import djconfig
class KFetConfig(object): class KFetConfig(object):
"""kfet app configuration. """kfet app configuration.
Enhance isolation with backend used to store config. Enhance isolation with backend used to store config.
Usable after DjConfig middleware was called.
""" """
prefix = 'kfet_' prefix = 'kfet_'
def __init__(self):
# Set this to False again to reload the config, e.g for testing
# purposes.
self._conf_init = False
def _check_init(self):
# For initialization purposes, we call 'reload_maybe' directly
# (normaly done once per request in middleware).
# Note it should be called only once across requests, if you use
# kfet_config instance below.
if not self._conf_init:
djconfig.reload_maybe()
self._conf_init = True
def __getattr__(self, key): def __getattr__(self, key):
self._check_init()
if key == 'subvention_cof': if key == 'subvention_cof':
# Allows accessing to the reduction as a subvention # Allows accessing to the reduction as a subvention
# Other reason: backward compatibility # Other reason: backward compatibility
reduction_mult = 1 - self.reduction_cof/100 reduction_mult = 1 - self.reduction_cof/100
return (1/reduction_mult - 1) * 100 return (1/reduction_mult - 1) * 100
return getattr(config, self._get_dj_key(key)) return getattr(djconfig.config, self._get_dj_key(key))
def list(self): def list(self):
"""Get list of kfet app configuration. """Get list of kfet app configuration.
@ -30,7 +44,8 @@ class KFetConfig(object):
""" """
# prevent circular imports # prevent circular imports
from kfet.forms import KFetConfigForm from kfet.forms import KFetConfigForm
return [(field.label, getattr(config, name), ) self._check_init()
return [(field.label, getattr(djconfig.config, name), )
for name, field in KFetConfigForm.base_fields.items()] for name, field in KFetConfigForm.base_fields.items()]
def _get_dj_key(self, key): def _get_dj_key(self, key):
@ -47,6 +62,7 @@ class KFetConfig(object):
# prevent circular imports # prevent circular imports
from kfet.forms import KFetConfigForm from kfet.forms import KFetConfigForm
self._check_init()
# get old config # get old config
new_cfg = KFetConfigForm().initial new_cfg = KFetConfigForm().initial
# update to new config # update to new config