Browse Source

Implementing mlstring + tests

Yann Weber 8 years ago
parent
commit
7910374183

Lodel/__init__.py → lodel/__init__.py View File


Lodel/editorialmodel/__init__.py → lodel/editorial_model/__init__.py View File


Lodel/leapi/__init__.py → lodel/leapi/__init__.py View File


Lodel/leapi/datahandlers/__init__.py → lodel/leapi/datahandlers/__init__.py View File


+ 0
- 0
lodel/utils/__init__.py View File


+ 98
- 0
lodel/utils/mlstring.py View File

@@ -0,0 +1,98 @@
1
+#-*- coding: utf-8 -*-
2
+
3
+import copy
4
+import json
5
+
6
+## @brief Stores multilangage string
7
+class MlString(object):
8
+    
9
+    __default_lang = 'eng'
10
+
11
+    langs = [
12
+        'fre',
13
+        'eng',
14
+        'ger',
15
+        'esp',
16
+    ]
17
+
18
+    ## @brief Create a new MlString instance
19
+    # @param arg str | dict : Can be a json string, a string or a dict
20
+    def __init__(self, arg):
21
+        self.values = dict()
22
+        if isinstance(arg, str):
23
+            self.values[self.__default_lang] = arg
24
+        elif isinstance(arg, dict):
25
+            for lang, value in arg.items():
26
+                if not self.lang_is_valid(lang):
27
+                    raise ValueError('Invalid lang found in argument : "%s"' % lang)
28
+                self.values[lang] = value
29
+        elif isinstance(arg, MlString):
30
+            self.values = copy.copy(arg.values)
31
+        else:
32
+            raise ValueError('<class str>, <class dict> or <class MlString> expected, but %s found' % type(arg))
33
+    
34
+    ## @brief Return a translation given a lang
35
+    # @param lang str
36
+    def get(self, lang):
37
+        if not self.lang_is_valid(lang):
38
+            raise ValueError("Invalid lang : '%s'" % lang)
39
+        elif lang in self.values:
40
+            return self.values[lang]
41
+        else:
42
+           return str(self)
43
+
44
+    ## @brief Set a translation
45
+    # @param lang str : the lang
46
+    # @param val str | None:  the translation if None delete the translation
47
+    def set(self, lang, val):
48
+        if not self.lang_is_valid(lang):
49
+            raise ValueError("Invalid lang : '%s'" % lang)
50
+        if not isinstance(val, str) and val is not None:
51
+            raise ValueError("Expected a <class str> as value but got %s" % type(val))
52
+        if val is None:
53
+            del(self.values[lang])
54
+        else:
55
+            self.values[lang] = val
56
+
57
+    ## @brief Checks that given lang is valid
58
+    # @param lang str : the lang
59
+    @classmethod
60
+    def lang_is_valid(cls, lang):
61
+        if not isinstance(lang, str):
62
+            raise ValueError('Invalid value for lang. Str expected but %s found' % type(lang))
63
+        return lang in cls.langs
64
+
65
+    ## @brief Get or set the default lang
66
+    @classmethod
67
+    def default_lang(cls, lang = None):
68
+        if lang is None:
69
+            return cls.__default_lang
70
+        if not cls.lang_is_valid(lang):
71
+            raise ValueError('lang "%s" is not valid"' % lang)
72
+        cls.__default_lang = lang
73
+    
74
+    ## @brief Return a mlstring loaded from a json string
75
+    # @param json_str str : Json string
76
+    @classmethod
77
+    def from_json(cls, json_str):
78
+        return MlString(json.loads(json_str))
79
+
80
+    def __hash__(self):
81
+        res = ''
82
+        for lang in sorted(list(self.values.keys())):
83
+            res = hash((res, lang, self.values[lang]))
84
+        return res
85
+
86
+    def __eq__(self, a):
87
+        return hash(self) == hash(a)
88
+    
89
+    ## @return The default langage translation or any available translation
90
+    def __str__(self):
91
+        if self.__default_lang in self.values:
92
+            return self.values[self.__default_lang]
93
+        else:
94
+            return self.values[list(self.values.keys())[0]]
95
+
96
+    def __repr__(self):
97
+        return repr(self.values)
98
+    

+ 49
- 0
runtest View File

@@ -0,0 +1,49 @@
1
+#!/bin/bash
2
+#
3
+# Usage : ./runtest [OPTIONS] [test_module[.test_class][ test_module2[.test_class2]...]
4
+#########
5
+#
6
+# Options list :
7
+################
8
+#
9
+# -b, --buffer
10
+#
11
+#    The standard output and standard error streams are buffered during the test run. Output during a passing test is discarded. Output is echoed normally on test fail or error and is added to the failure messages.
12
+#
13
+# -c, --catch
14
+#
15
+#    Control-C during the test run waits for the current test to end and then reports all the results so far. A second control-C raises the normal KeyboardInterrupt exception.
16
+#
17
+#
18
+# -f, --failfast
19
+#
20
+#    Stop the test run on the first error or failure.
21
+#
22
+# -h, --help
23
+#
24
+#    Get some help
25
+#
26
+# -v, --verbose
27
+#
28
+#   higher verbosity
29
+#
30
+# Examples :
31
+############
32
+#
33
+# Running all discoverables tests :
34
+# ./runtest
35
+#
36
+# Running only Em test about component object (only tests about the __init__ and modify_rank methods) with higher verbosity and failfast :
37
+# ./runtest -fv EditorialModel.test.test_component.TestInit EditorialModel.test.test_component.TestModifyRank
38
+#
39
+#
40
+# Running only Em tests
41
+# ./runtest discover EditorialModel
42
+#
43
+# More details :
44
+################
45
+#
46
+# https://docs.python.org/3.4/library/unittest.html
47
+#
48
+
49
+python -W ignore -m unittest $@

+ 82
- 0
tests/test_mlstrings.py View File

@@ -0,0 +1,82 @@
1
+#-*- coding: utf-8 -*-
2
+
3
+import unittest
4
+import copy
5
+
6
+from lodel.utils.mlstring import MlString
7
+
8
+class MlStringTestCase(unittest.TestCase):
9
+    
10
+    examples = {
11
+            'eng': 'Hello world !',
12
+            'fre': 'Bonjour monde !',
13
+            'ger': 'Hallo welt !',
14
+        }
15
+
16
+    def test_init_str(self):
17
+        """ Test MlString instanciation with string as argument """
18
+        testlangs = ['eng', 'fre']
19
+        teststrs = ['hello', 'Hello world !', '{helloworld !!!]}']
20
+        for lang in testlangs:
21
+            for teststr in teststrs:
22
+                MlString.default_lang(lang)
23
+                mls_test = MlString(teststr)
24
+                self.assertEqual(teststr, str(mls_test))
25
+                self.assertEqual(teststr, mls_test.get(lang))
26
+
27
+    def test_init_dict(self):
28
+        """ Test MlString instanciation with dict as argument """
29
+        mls = MlString(self.examples)
30
+        for lang, val in self.examples.items():
31
+            self.assertEqual(mls.get(lang), val)
32
+
33
+    def test_init_json(self):
34
+        """ Test MlString instanciation using a json string """
35
+        testval = '{"eng":"Hello world !", "fre":"Bonjour monde !", "ger":"Hallo welt !"}'
36
+        mls = MlString.from_json(testval)
37
+        for lang in self.examples:
38
+            self.assertEqual(mls.get(lang), self.examples[lang])
39
+
40
+    def test_get(self):
41
+        """ Test MlString get method """
42
+        mls = MlString(self.examples)
43
+        for lang, val in self.examples.items():
44
+            self.assertEqual(mls.get(lang), val)
45
+        # A lang that is not set
46
+        self.assertEqual(mls.get('esp'), str(mls))
47
+        # A deleted lang
48
+        mls.set('fre', None)
49
+        self.assertEqual(mls.get('fre'), str(mls))
50
+
51
+    def test_eq(self):
52
+        """ Test MlString comparison functions """
53
+        for val in ['hello world', self.examples]:
54
+            mls1 = MlString(val)
55
+            mls2 = MlString(val)
56
+            self.assertTrue(mls1 == mls2)
57
+            self.assertEqual(hash(mls1), hash(mls2))
58
+
59
+        mls1 = MlString('Hello world !')
60
+        mls2 = MlString('hello world !')
61
+        self.assertTrue(mls1 != mls2)
62
+        self.assertNotEqual(hash(mls1), hash(mls2))
63
+
64
+        modexamples = copy.copy(self.examples)
65
+        modexamples['eng'] = 'hello world !'
66
+        mls1 = MlString(modexamples)
67
+        mls2 = MlString(self.examples)
68
+        self.assertTrue(mls1 != mls2)
69
+        self.assertNotEqual(hash(mls1), hash(mls2))
70
+
71
+        mls1 = MlString(self.examples)
72
+        mls2 = MlString(self.examples)
73
+        mls1.set('eng', None)
74
+        self.assertTrue(mls1 != mls2)
75
+        self.assertNotEqual(hash(mls1), hash(mls2))
76
+        
77
+        mls1 = MlString(self.examples)
78
+        mls2 = MlString(self.examples)
79
+        mls1.set('eng', 'hello world !')
80
+        self.assertTrue(mls1 != mls2)
81
+        self.assertNotEqual(hash(mls1), hash(mls2))
82
+

Loading…
Cancel
Save