Test Failed
Pull Request — master (#50)
by
unknown
01:52
created

LocalizedIntegerValue   A

Complexity

Total Complexity 1

Size/Duplication

Total Lines 4
Duplicated Lines 0 %

Test Coverage

Coverage 66.67%

Importance

Changes 0
Metric Value
wmc 1
c 0
b 0
f 0
dl 0
loc 4
rs 10
ccs 2
cts 3
cp 0.6667

1 Method

Rating   Name   Duplication   Size   Complexity  
A __int__() 0 2 1
1 1
import collections
2
3 1
from django.conf import settings
0 ignored issues
show
Configuration introduced by
The import django.conf could not be resolved.

This can be caused by one of the following:

1. Missing Dependencies

This error could indicate a configuration issue of Pylint. Make sure that your libraries are available by adding the necessary commands.

# .scrutinizer.yml
before_commands:
    - sudo pip install abc # Python2
    - sudo pip3 install abc # Python3
Tip: We are currently not using virtualenv to run pylint, when installing your modules make sure to use the command for the correct version.

2. Missing __init__.py files

This error could also result from missing __init__.py files in your module folders. Make sure that you place one file in each sub-folder.

Loading history...
4 1
from django.utils import translation
0 ignored issues
show
Configuration introduced by
The import django.utils could not be resolved.

This can be caused by one of the following:

1. Missing Dependencies

This error could indicate a configuration issue of Pylint. Make sure that your libraries are available by adding the necessary commands.

# .scrutinizer.yml
before_commands:
    - sudo pip install abc # Python2
    - sudo pip3 install abc # Python3
Tip: We are currently not using virtualenv to run pylint, when installing your modules make sure to use the command for the correct version.

2. Missing __init__.py files

This error could also result from missing __init__.py files in your module folders. Make sure that you place one file in each sub-folder.

Loading history...
5
6
7 1
class LocalizedValue(dict):
8
    """Represents the value of a :see:LocalizedField."""
9 1
    default_value = None
10
11 1
    def __init__(self, keys: dict=None):
12
        """Initializes a new instance of :see:LocalizedValue.
13
14
        Arguments:
15
            keys:
16
                The keys to initialize this value with. Every
17
                key contains the value of this field in a
18
                different language.
19
        """
20
21 1
        super().__init__({})
22 1
        self._interpret_value(keys)
23
24 1
    def get(self, language: str=None, default: str=None) -> str:
25
        """Gets the underlying value in the specified or
26
        primary language.
27
28
        Arguments:
29
            language:
30
                The language to get the value in.
31
32
        Returns:
33
            The value in the current language, or
34
            the primary language in case no language
35
            was specified.
36
        """
37
38 1
        language = language or settings.LANGUAGE_CODE
39 1
        return super().get(language, default)
40
41 1
    def set(self, language: str, value: str):
42
        """Sets the value in the specified language.
43
44
        Arguments:
45
            language:
46
                The language to set the value in.
47
48
            value:
49
                The value to set.
50
        """
51
52 1
        self[language] = value
53 1
        self.__dict__.update(self)
54 1
        return self
55
56 1
    def deconstruct(self) -> dict:
57
        """Deconstructs this value into a primitive type.
58
59
        Returns:
60
            A dictionary with all the localized values
61
            contained in this instance.
62
        """
63
64 1
        path = 'localized_fields.value.%s' % self.__class__.__name__
65 1
        return path, [self.__dict__], {}
66
67 1
    def _interpret_value(self, value):
68
        """Interprets a value passed in the constructor as
69
        a :see:LocalizedValue.
70
71
        If string:
72
            Assumes it's the default language.
73
74
        If dict:
75
            Each key is a language and the value a string
76
            in that language.
77
78
        If list:
79
            Recurse into to apply rules above.
80
81
        Arguments:
82
            value:
83
                The value to interpret.
84
        """
85
86 1
        for lang_code, _ in settings.LANGUAGES:
87 1
            self.set(lang_code, self.default_value)
88
89 1
        if isinstance(value, str):
90 1
            self.set(settings.LANGUAGE_CODE, value)
91
92 1
        elif isinstance(value, dict):
93 1
            for lang_code, _ in settings.LANGUAGES:
94 1
                lang_value = value.get(lang_code, self.default_value)
95 1
                self.set(lang_code, lang_value)
96
97 1
        elif isinstance(value, collections.Iterable):
98 1
            for val in value:
99 1
                self._interpret_value(val)
100
101 1
    def __str__(self) -> str:
102
        """Gets the value in the current language, or falls
103
        back to the primary language if there's no value
104
        in the current language."""
105
106 1
        fallbacks = getattr(settings, 'LOCALIZED_FIELDS_FALLBACKS', {})
107
108 1
        language = translation.get_language() or settings.LANGUAGE_CODE
109 1
        languages = fallbacks.get(language, [settings.LANGUAGE_CODE])[:]
110 1
        languages.insert(0, language)
111
112 1
        for lang_code in languages:
113 1
            value = self.get(lang_code)
114 1
            if value is not None:
115 1
                return value or ''
116
117 1
        return ''
118
119 1
    def __int__(self) -> int:
120
        return int(self.__str__())
121
122 1
    def __eq__(self, other):
123
        """Compares :paramref:self to :paramref:other for
124
        equality.
125
126
        Returns:
127
            True when :paramref:self is equal to :paramref:other.
128
            And False when they are not.
129
        """
130
131 1
        if not isinstance(other, type(self)):
132 1
            if isinstance(other, str):
133 1
                return self.__str__() == other
134 1
            return False
135
136 1
        for lang_code, _ in settings.LANGUAGES:
137 1
            if self.get(lang_code) != other.get(lang_code):
138 1
                return False
139
140 1
        return True
141
142 1
    def __ne__(self, other):
143
        """Compares :paramref:self to :paramerf:other for
144
        in-equality.
145
146
        Returns:
147
            True when :paramref:self is not equal to :paramref:other.
148
            And False when they are.
149
        """
150
151 1
        return not self.__eq__(other)
152
153 1
    def __setattr__(self, language: str, value: str):
154
        """Sets the value for a language with the specified name.
155
156
        Arguments:
157
            language:
158
                The language to set the value in.
159
160
            value:
161
                The value to set.
162
        """
163
164 1
        self.set(language, value)
165
166
    def __repr__(self):  # pragma: no cover
167
        """Gets a textual representation of this object."""
168
169
        return '%s<%s> 0x%s' % (self.__class__.__name__,
170
                                self.__dict__, id(self))
171
172
173 1
class LocalizedStringValue(LocalizedValue):
174 1
    default_value = ''
175
176 1
class LocalizedIntegerValue(LocalizedValue):
177
178 1
    def __int__(self) -> int:
179
        int(self.__str__())
180
181 1
class LocalizedFileValue(LocalizedValue):
182 1
    def __getattr__(self, name: str):
183
        """Proxies access to attributes to attributes of LocalizedFile"""
184
185 1
        value = self.get(translation.get_language())
186 1
        if hasattr(value, name):
187 1
            return getattr(value, name)
188 1
        raise AttributeError("'{}' object has no attribute '{}'".
189
                             format(self.__class__.__name__, name))
190
191 1
    def __str__(self) -> str:
192
        """Returns string representation of value"""
193 1
        return str(super().__str__())
194
195 1
    def localized(self):
196
        """Returns value for current language"""
197
        return self.get(translation.get_language())
198