def get_format_validators(include=None, dic=False): """Get all FormatValidators. :param include: List of FormatValidators to include :param dic: Should return a dict :return: List of FormatValidator-objects if dic False otherwise dict """ format_validator_classes = [ import_string(cls) for cls in settings.FORMAT_VALIDATOR_CLASSES ] + base_format_validators if include is not None: format_validator_classes = [ fvc for fvc in format_validator_classes if fvc.slug in include ] if dic: return {ds.slug: ds for ds in format_validator_classes} return [ FormatValidator( slug=ds.slug, name=LocalizedValue(ds.name).translate(), regex=ds.regex, error_msg=LocalizedValue(ds.error_msg).translate(), ) for ds in format_validator_classes ]
def test_eq(): """Tests whether the __eq__ operator of :see:LocalizedValue works properly.""" a = LocalizedValue({'en': 'a', 'ar': 'b'}) b = LocalizedValue({'en': 'a', 'ar': 'b'}) assert a == b b.en = 'b' assert a != b
def test_eq(): """Tests whether the __eq__ operator of :see:LocalizedValue works properly.""" a = LocalizedValue({"en": "a", "ar": "b"}) b = LocalizedValue({"en": "a", "ar": "b"}) assert a == b b.en = "b" assert a != b
def test_str_fallback(): """Tests whether the :see:LocalizedValue class's __str__'s fallback functionality works properly.""" test_value = 'myvalue' localized_value = LocalizedValue({settings.LANGUAGE_CODE: test_value}) other_language = settings.LANGUAGES[-1][0] # make sure that, by default it returns # the value in the default language assert str(localized_value) == test_value # make sure that it falls back to the # primary language when there's no value # available in the current language translation.activate(other_language) assert str(localized_value) == test_value # make sure that it's just __str__ falling # back and that for the other language # there's no actual value assert localized_value.get(other_language) != test_value
def test_init_default_values(): """Tests whether the __init__ function of the :see:LocalizedValue accepts the default value or an empty dict properly.""" value = LocalizedValue() for lang_code, _ in settings.LANGUAGES: assert getattr(value, lang_code) is None
def test_get_prep_value(): """Tests whether the :see:get_prep_value function returns correctly value.""" value = LocalizedValue({"en": None}) assert LocalizedFileField().get_prep_value(None) is None assert isinstance(LocalizedFileField().get_prep_value(value), dict) assert LocalizedFileField().get_prep_value(value)["en"] == ""
def test_get_explicit(): """Tests whether the the :see:LocalizedValue class's :see:get function works properly when specifying an explicit value.""" keys = get_init_values() localized_value = LocalizedValue(keys) for language, value in keys.items(): assert localized_value.get(language) == value
def test_init(): """Tests whether the __init__ function of the :see:LocalizedValue class works as expected.""" keys = get_init_values() value = LocalizedValue(keys) for lang_code, _ in settings.LANGUAGES: assert getattr(value, lang_code, None) == keys[lang_code]
def test_translate_none(): """Tests whether the :see:LocalizedValue class's translate() method properly returns None when there is no value.""" # with no value, we always expect it to return None localized_value = LocalizedValue() assert localized_value.translate() is None assert str(localized_value) == "" # with no value for the default language, the default # behavior is to return None, unless a custom fallback # chain is configured, which there is not for this test other_language = settings.LANGUAGES[-1][0] localized_value = LocalizedValue({other_language: "hey"}) translation.activate(settings.LANGUAGE_CODE) assert localized_value.translate() is None assert str(localized_value) == ""
def _get_test_value(): """Gets a :see:LocalizedValue instance for testing.""" value = LocalizedValue() for lang_code, lang_name in settings.LANGUAGES: value.set(lang_code, "<script>%s</script>" % lang_name) return value
def test_get_default_language(): """Tests whether the :see:LocalizedValue class's see:get function properly gets the value in the default language.""" keys = get_init_values() localized_value = LocalizedValue(keys) for language, _ in keys.items(): translation.activate(language) assert localized_value.get() == keys[settings.LANGUAGE_CODE]
def test_init_array(): """Tests whether the __init__ function of :see:LocalizedValue properly handles an array. Arrays can be passed to LocalizedValue as a result of a ArrayAgg operation. """ value = LocalizedValue(["my value"]) assert value.get(settings.LANGUAGE_CODE) == "my value"
def test_deconstruct(): """Tests whether the :see:LocalizedValue class's :see:deconstruct function works properly.""" keys = get_init_values() value = LocalizedValue(keys) path, args, kwargs = value.deconstruct() assert args[0] == keys
def test_translate_custom_language(): """Tests whether the :see:LocalizedValue class's translate() ignores the active language when one is specified explicitely.""" localized_value = LocalizedValue( {settings.LANGUAGE_CODE: settings.LANGUAGE_CODE, "ro": "ro"} ) with translation.override("en"): assert localized_value.translate("ro") == "ro"
def test_translate(): """Tests whether the :see:LocalizedValue class's __str__ works properly.""" keys = get_init_values() localized_value = LocalizedValue(keys) for language, value in keys.items(): translation.activate(language) assert localized_value.translate() == value
def test_set(): """Tests whether the :see:LocalizedValue class's see:set function works properly.""" localized_value = LocalizedValue() for language, value in get_init_values(): localized_value.set(language, value) assert localized_value.get(language) == value assert getattr(localized_value, language) == value
def test_get_context_required(): """Tests whether the :see:get_context correctly handles 'required' attribute, separately for each subwidget.""" widget = LocalizedFieldWidget() widget.widgets[0].is_required = True widget.widgets[1].is_required = False context = widget.get_context(name='test', value=LocalizedValue(), attrs=dict(required=True)) assert context['widget']['subwidgets'][0]['attrs']['required'] assert 'required' not in context['widget']['subwidgets'][1]['attrs']
def test_get_prep_value(): """"Tests whether the :see:get_prep_value function produces the expected dictionary.""" input_data = get_init_values() localized_value = LocalizedValue(input_data) output_data = LocalizedField().get_prep_value(localized_value) for language, value in input_data.items(): assert language in output_data assert output_data.get(language) == value
def test_get_context_required(): """Tests whether the :see:get_context correctly handles 'required' attribute, separately for each subwidget.""" widget = LocalizedFieldWidget() widget.widgets[0].is_required = True widget.widgets[1].is_required = False context = widget.get_context( name="test", value=LocalizedValue(), attrs=dict(required=True) ) assert context["widget"]["subwidgets"][0]["attrs"]["required"] assert "required" not in context["widget"]["subwidgets"][1]["attrs"]
def load(self): if is_iterable_and_no_string(self.data): if not 0 < len(self.data) < 3: raise DataSourceException( f"Failed to parse data:\n{self.data}") elif len(self.data) == 1: return str(self.data[0]), str(self.data[0]) elif isinstance(self.data[1], dict): label = LocalizedValue(self.data[1]) return (str(self.data[0]), str(label.translate())) return str(self.data[0]), str(self.data[1]) return str(self.data), str(self.data)
def test_get_context_langs(): """Tests whether the :see:get_context contains 'lang_code' and 'lang_name' attribute for each subwidget.""" widget = LocalizedFieldWidget() context = widget.get_context(name='test', value=LocalizedValue(), attrs=dict()) subwidgets_context = context['widget']['subwidgets'] for widget, context in zip(widget.widgets, subwidgets_context): assert 'lang_code' in context assert 'lang_name' in context assert widget.lang_code == context['lang_code'] assert widget.lang_name == context['lang_name']
def test_get_prep_value_clean(self): """Tests whether the :see:get_prep_value produces None as the output when it is passed an empty, but valid LocalizedValue value but, only when null=True.""" localized_value = LocalizedValue() with self.assertRaises(IntegrityError): LocalizedField(null=False).get_prep_value(localized_value) assert not LocalizedField(null=True).get_prep_value(localized_value) assert not LocalizedField().clean(None) assert not LocalizedField().clean(['huh'])
def test_decompress(): """Tests whether a :see:LocalizedValue instance can correctly be "decompressed" over the available widgets.""" localized_value = LocalizedValue() for lang_code, lang_name in settings.LANGUAGES: localized_value.set(lang_code, lang_name) widget = LocalizedFieldWidget() decompressed_values = widget.decompress(localized_value) for (lang_code, _), value in zip(settings.LANGUAGES, decompressed_values): assert localized_value.get(lang_code) == value
def test_get_context_langs(): """Tests whether the :see:get_context contains 'lang_code' and 'lang_name' attribute for each subwidget.""" widget = LocalizedFieldWidget() context = widget.get_context( name="test", value=LocalizedValue(), attrs=dict() ) subwidgets_context = context["widget"]["subwidgets"] for widget, context in zip(widget.widgets, subwidgets_context): assert "lang_code" in context assert "lang_name" in context assert widget.lang_code == context["lang_code"] assert widget.lang_name == context["lang_name"]
def test_str_fallback_custom_fallback(): """Tests whether the :see:LocalizedValue class's __str__'s fallback functionality properly respects the LOCALIZED_FIELDS_FALLBACKS setting.""" settings.LOCALIZED_FIELDS_FALLBACKS = {'nl': ['ro']} localized_value = LocalizedValue({ settings.LANGUAGE_CODE: settings.LANGUAGE_CODE, 'ro': 'ro' }) with translation.override('nl'): assert str(localized_value) == 'ro'
def get_prep_value(self, value): """Returns field's value prepared for saving into a database.""" if isinstance(value, LocalizedValue): prep_value = LocalizedValue() for k, v in value.__dict__.items(): if v is None: prep_value.set(k, "") else: # Need to convert File objects provided via a form to # unicode for database insertion prep_value.set(k, str(v)) return super().get_prep_value(prep_value) return super().get_prep_value(value)
def test_translate_fallback_custom_fallback(): """Tests whether the :see:LocalizedValue class's translate()'s fallback functionality properly respects the LOCALIZED_FIELDS_FALLBACKS setting.""" fallbacks = {"nl": ["ro"]} localized_value = LocalizedValue( {settings.LANGUAGE_CODE: settings.LANGUAGE_CODE, "ro": "ro"} ) with override_settings(LOCALIZED_FIELDS_FALLBACKS=fallbacks): with translation.override("nl"): assert localized_value.translate() == "ro"
def test_localized_ref(cls): """Tests whether the :see:LocalizedRef expression properly works.""" obj = cls.TestModel1.objects.create(name="bla bla") for i in range(0, 10): cls.TestModel2.objects.create( text=LocalizedValue( dict( en="text_%d_en" % i, ro="text_%d_ro" % i, nl="text_%d_nl" % i, )), other=obj, ) def create_queryset(ref): return cls.TestModel1.objects.annotate(mytexts=ref).values_list( "mytexts", flat=True) # assert that it properly selects the currently active language for lang_code, _ in settings.LANGUAGES: translation.activate(lang_code) queryset = create_queryset(LocalizedRef("features__text")) for index, value in enumerate(queryset): assert translation.get_language() in value assert str(index) in value # ensure that the default language is used in case no # language is active at all translation.deactivate_all() queryset = create_queryset(LocalizedRef("features__text")) for index, value in enumerate(queryset): assert settings.LANGUAGE_CODE in value assert str(index) in value # ensures that overriding the language works properly queryset = create_queryset(LocalizedRef("features__text", "ro")) for index, value in enumerate(queryset): assert "ro" in value assert str(index) in value # ensures that using this in combination with ArrayAgg works properly queryset = create_queryset( ArrayAgg(LocalizedRef("features__text", "ro"))).first() assert isinstance(queryset, list) for value in queryset: assert "ro" in value
def test_localized_lookup(self): """Tests whether localized lookup properly works.""" self.TestModel.objects.create(text=LocalizedValue( dict(en='text_en', ro='text_ro', nl='text_nl')), ) # assert that it properly lookups the currently active language for lang_code, _ in settings.LANGUAGES: translation.activate(lang_code) assert self.TestModel.objects.filter(text='text_' + lang_code).exists() # ensure that the default language is used in case no # language is active at all translation.deactivate_all() assert self.TestModel.objects.filter(text='text_en').exists() # ensure that hstore lookups still work assert self.TestModel.objects.filter(text__ro='text_ro').exists()
def get_data_sources(dic=False): """Get all configured DataSources. :param dic: Should return a dict :return: List of DataSource-objects if dic False otherwise dict """ data_source_classes = [ import_string(cls) for cls in settings.DATA_SOURCE_CLASSES ] if dic: return {ds.__name__: ds for ds in data_source_classes} return [ DataSource( name=ds.__name__, info=LocalizedValue(ds.info).translate() if isinstance( ds.info, dict) else ds.info, ) for ds in data_source_classes ]