File: test_decorator.py

package info (click to toggle)
python-skbio 0.5.1-2
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 16,556 kB
  • ctags: 7,222
  • sloc: python: 42,085; ansic: 670; makefile: 180; sh: 10
file content (351 lines) | stat: -rw-r--r-- 11,870 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
# ----------------------------------------------------------------------------
# Copyright (c) 2013--, scikit-bio development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
# ----------------------------------------------------------------------------

import unittest
import inspect
import warnings

from skbio.util import classproperty
from skbio.util._decorator import overrides, classonlymethod
from skbio.util._decorator import (stable, experimental, deprecated,
                                   _state_decorator)
from skbio.util._exception import OverrideError


class TestClassOnlyMethod(unittest.TestCase):
    def test_works_on_class(self):
        class A:
            @classonlymethod
            def example(cls):
                return cls

        self.assertEqual(A.example(), A)

    def test_fails_on_instance(self):
        class A:
            @classonlymethod
            def example(cls):
                pass

        with self.assertRaises(TypeError) as e:
            A().example()

        self.assertIn('A.example', str(e.exception))
        self.assertIn('instance', str(e.exception))

    def test_matches_classmethod(self):
        class A:
            pass

        def example(cls, thing):
            """doc"""

        A.example1 = classmethod(example)
        A.example2 = classonlymethod(example)

        self.assertEqual(A.__dict__['example1'].__func__, example)
        self.assertEqual(A.__dict__['example2'].__func__, example)

        self.assertEqual(A.example1.__doc__, example.__doc__)
        self.assertEqual(A.example2.__doc__, example.__doc__)

        self.assertEqual(A.example1.__name__, example.__name__)
        self.assertEqual(A.example2.__name__, example.__name__)

    def test_passes_args_kwargs(self):
        self.ran_test = False

        class A:
            @classonlymethod
            def example(cls, arg1, arg2, kwarg1=None, kwarg2=None,
                        default=5):
                self.assertEqual(arg1, 1)
                self.assertEqual(arg2, 2)
                self.assertEqual(kwarg1, '1')
                self.assertEqual(kwarg2, '2')
                self.assertEqual(default, 5)
                self.ran_test = True

        A.example(1, *[2], kwarg2='2', **{'kwarg1': '1'})
        self.assertTrue(self.ran_test)


class TestOverrides(unittest.TestCase):
    def test_raises_when_missing(self):
        class A:
            pass

        with self.assertRaises(OverrideError):
            class B(A):
                @overrides(A)
                def test(self):
                    pass

    def test_doc_inherited(self):
        class A:
            def test(self):
                """Docstring"""
                pass

        class B(A):
            @overrides(A)
            def test(self):
                pass

        self.assertEqual(B.test.__doc__, "Docstring")

    def test_doc_not_inherited(self):
        class A:
            def test(self):
                """Docstring"""
                pass

        class B(A):
            @overrides(A)
            def test(self):
                """Different"""
                pass

        self.assertEqual(B.test.__doc__, "Different")


class TestClassProperty(unittest.TestCase):
    def test_getter_only(self):
        class Foo:
            _foo = 42

            @classproperty
            def foo(cls):
                return cls._foo

        # class-level getter
        self.assertEqual(Foo.foo, 42)

        # instance-level getter
        f = Foo()
        self.assertEqual(f.foo, 42)

        with self.assertRaises(AttributeError):
            f.foo = 4242


class TestStabilityState(unittest.TestCase):
    # the indentation spacing gets weird, so I'm defining the
    # input doc string explicitly and adding it after function
    # defintion
    _test_docstring = (" Add 42, or something else, to x.\n"
                       "\n"
                       "    Parameters\n"
                       "    ----------\n"
                       "    x : int, x\n"
                       "    y : int, optional\n")


class TestBase(TestStabilityState):

    def test_get_indentation_level(self):

        c = _state_decorator()
        self.assertEqual(c._get_indentation_level([]), 0)
        self.assertEqual(
            c._get_indentation_level([], default_no_existing_docstring=3), 3)
        self.assertEqual(c._get_indentation_level([""]), 4)
        self.assertEqual(
            c._get_indentation_level([""], default_existing_docstring=3), 3)

        in_ = (["summary"])
        self.assertEqual(c._get_indentation_level(in_), 4)
        in_ = (["summary", "", "", "    ", "", " ", ""])
        self.assertEqual(c._get_indentation_level(in_), 4)

        in_ = (["summary", "     More indentation", " Less indentation"])
        self.assertEqual(c._get_indentation_level(in_), 5)

    def test_update_docstring(self):
        c = _state_decorator()
        in_ = None
        exp = ("""State: Test!!""")
        self.assertEqual(c._update_docstring(in_, "Test!!"), exp)

        in_ = """"""
        exp = ("""\n\n    State: Test!!""")
        self.assertEqual(c._update_docstring(in_, "Test!!"), exp)

        in_ = ("""Short summary\n\n    Parameters\n\n----------\n    """
               """x : int\n""")
        exp = ("""Short summary\n\n    State: Test!!\n\n"""
               """    Parameters\n\n----------\n    x : int\n""")
        self.assertEqual(c._update_docstring(in_, "Test!!"), exp)

        in_ = ("""Short summary\n\n      Parameters\n\n----------\n      """
               """x : int\n""")
        exp = ("""Short summary\n\n      State: Test!!\n\n"""
               """      Parameters\n\n----------\n      x : int\n""")
        self.assertEqual(c._update_docstring(in_, "Test!!"), exp)

        in_ = ("""Short summary\n\n    Parameters\n\n----------\n    """
               """x : int\n""")
        exp = ("""Short summary\n\n    State: Test!!Test!!Test!!Test!!Test!!"""
               """Test!!Test!!Test!!Test!!Test!!Test!!Te\n           st!!T"""
               """est!!Test!!Test!!Test!!Test!!Test!!Test!!Test!!\n\n"""
               """    Parameters\n\n----------\n    x : int\n""")
        self.assertEqual(c._update_docstring(in_, "Test!!"*20), exp)


class TestStable(TestStabilityState):

    def _get_f(self, as_of):
        def f(x, y=42):
            return x + y
        f.__doc__ = self._test_docstring
        f = stable(as_of=as_of)(f)
        return f

    def test_function_output(self):
        f = self._get_f('0.1.0')
        self.assertEqual(f(1), 43)

    def test_function_docstring(self):
        f = self._get_f('0.1.0')
        e1 = (" Add 42, or something else, to x.\n\n"
              "    State: Stable as of 0.1.0.\n\n"
              "    Parameters")
        self.assertTrue(f.__doc__.startswith(e1))
        f = self._get_f('0.1.1')
        e1 = (" Add 42, or something else, to x.\n\n"
              "    State: Stable as of 0.1.1.\n\n"
              "    Parameters")
        self.assertTrue(f.__doc__.startswith(e1))

    def test_function_signature(self):
        f = self._get_f('0.1.0')

        parameters = [
            inspect.Parameter('x', inspect.Parameter.POSITIONAL_OR_KEYWORD),
            inspect.Parameter('y', inspect.Parameter.POSITIONAL_OR_KEYWORD,
                              default=42)
        ]
        expected = inspect.Signature(parameters)

        self.assertEqual(inspect.signature(f), expected)
        self.assertEqual(f.__name__, 'f')

    def test_missing_kwarg(self):
        self.assertRaises(ValueError, stable)
        self.assertRaises(ValueError, stable, '0.1.0')


class TestExperimental(TestStabilityState):

    def _get_f(self, as_of):
        def f(x, y=42):
            return x + y
        f.__doc__ = self._test_docstring
        f = experimental(as_of=as_of)(f)
        return f

    def test_function_output(self):
        f = self._get_f('0.1.0')
        self.assertEqual(f(1), 43)

    def test_function_docstring(self):
        f = self._get_f('0.1.0')
        e1 = (" Add 42, or something else, to x.\n\n"
              "    State: Experimental as of 0.1.0.\n\n"
              "    Parameters")
        self.assertTrue(f.__doc__.startswith(e1))
        f = self._get_f('0.1.1')
        e1 = (" Add 42, or something else, to x.\n\n"
              "    State: Experimental as of 0.1.1.\n\n"
              "    Parameters")
        self.assertTrue(f.__doc__.startswith(e1))

    def test_function_signature(self):
        f = self._get_f('0.1.0')

        parameters = [
            inspect.Parameter('x', inspect.Parameter.POSITIONAL_OR_KEYWORD),
            inspect.Parameter('y', inspect.Parameter.POSITIONAL_OR_KEYWORD,
                              default=42)
        ]
        expected = inspect.Signature(parameters)

        self.assertEqual(inspect.signature(f), expected)
        self.assertEqual(f.__name__, 'f')

    def test_missing_kwarg(self):
        self.assertRaises(ValueError, experimental)
        self.assertRaises(ValueError, experimental, '0.1.0')


class TestDeprecated(TestStabilityState):

    def _get_f(self, as_of, until, reason):
        def f(x, y=42):
            return x + y
        f.__doc__ = self._test_docstring
        f = deprecated(as_of=as_of, until=until, reason=reason)(f)
        return f

    def test_function_output(self):
        f = self._get_f('0.1.0', until='0.1.4',
                        reason='You should now use skbio.g().')
        self.assertEqual(f(1), 43)

    def test_deprecation_warning(self):
        f = self._get_f('0.1.0', until='0.1.4',
                        reason='You should now use skbio.g().')
        # adapted from SO example here: http://stackoverflow.com/a/3892301
        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter("always")
            f(1)
            self.assertTrue(issubclass(w[0].category, DeprecationWarning))
            expected_str = "is deprecated as of scikit-bio version 0.1.0"
            self.assertTrue(expected_str in str(w[0].message))

    def test_function_docstring(self):
        f = self._get_f('0.1.0', until='0.1.4',
                        reason='You should now use skbio.g().')
        e1 = (" Add 42, or something else, to x.\n\n"
              "    .. note:: Deprecated as of 0.1.0 for "
              "removal in 0.1.4. You should now use\n"
              "              skbio.g().\n\n"
              "    Parameters")
        self.assertTrue(f.__doc__.startswith(e1))

        f = self._get_f('0.1.1', until='0.1.5',
                        reason='You should now use skbio.h().')
        e1 = (" Add 42, or something else, to x.\n\n"
              "    .. note:: Deprecated as of 0.1.1 for "
              "removal in 0.1.5. You should now use\n"
              "              skbio.h().\n\n"
              "    Parameters")
        self.assertTrue(f.__doc__.startswith(e1))

    def test_function_signature(self):
        f = self._get_f('0.1.0', until='0.1.4',
                        reason='You should now use skbio.g().')

        parameters = [
            inspect.Parameter('x', inspect.Parameter.POSITIONAL_OR_KEYWORD),
            inspect.Parameter('y', inspect.Parameter.POSITIONAL_OR_KEYWORD,
                              default=42)
        ]
        expected = inspect.Signature(parameters)

        self.assertEqual(inspect.signature(f), expected)
        self.assertEqual(f.__name__, 'f')

    def test_missing_kwarg(self):
        self.assertRaises(ValueError, deprecated)
        self.assertRaises(ValueError, deprecated, '0.1.0')
        self.assertRaises(ValueError, deprecated, as_of='0.1.0')
        self.assertRaises(ValueError, deprecated, as_of='0.1.0', until='0.1.4')

if __name__ == '__main__':
    unittest.main()