array-split 0.6.5__zip

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,147 @@
1
+ """
2
+ ===================================
3
+ The :mod:`array_split.tests` Module
4
+ ===================================
5
+
6
+ Module for running all :mod:`array_split` unit-tests, including :mod:`unittest` test-cases
7
+ and :mod:`doctest` tests for module doc-strings and sphinx (RST) documentation.
8
+ Execute as::
9
+
10
+ python -m array_split.tests
11
+
12
+ .. currentmodule:: array_split.tests
13
+
14
+
15
+ Classes and Functions
16
+ =====================
17
+
18
+ .. autosummary::
19
+ :toctree: generated/
20
+
21
+ MultiPlatformAnd23Checker - Customised doctest output checking.
22
+ DocTestTestSuite - Loads all module and file doctests as single :mod:`unittest` suite.
23
+ load_tests - Returns suite of :mod:`doctest` and :mod:`unittest` tests.
24
+
25
+ """
26
+ # pylint: disable=unused-import
27
+ from __future__ import absolute_import
28
+ import sys as _sys
29
+ import re as _re
30
+ import unittest as _unittest
31
+ import doctest as _doctest
32
+ import os.path
33
+ import array_split as _array_split
34
+ from array_split import split as _split
35
+
36
+ from .license import license as _license, copyright as _copyright, version as _version
37
+ from .split_test import SplitTest # noqa: F401,F403
38
+
39
+ __author__ = "Shane J. Latham"
40
+ __license__ = _license()
41
+ __copyright__ = _copyright()
42
+ __version__ = _version()
43
+
44
+ _doctest_OuputChecker = _doctest.OutputChecker
45
+
46
+
47
+ class MultiPlatformAnd23Checker(_doctest_OuputChecker):
48
+
49
+ """
50
+ Overrides the :meth:`doctest.OutputChecker.check_output` method
51
+ to remove the :samp:`'L'` from integer literals
52
+ """
53
+
54
+ def check_output(self, want, got, optionflags):
55
+ """
56
+ For python-2 replaces "124L" with "124". For python 2 and 3,
57
+ replaces :samp:`", dtype=int64)"` with :samp:`")"`.
58
+
59
+ See :meth:`doctest.OutputChecker.check_output`.
60
+
61
+ """
62
+ if _sys.version_info[0] <= 2:
63
+ got = _re.sub("([0-9]+)L", "\\1", got)
64
+
65
+ got = _re.sub(", dtype=int64\\)", ")", got)
66
+
67
+ return _doctest_OuputChecker.check_output(self, want, got, optionflags)
68
+
69
+
70
+ _doctest.OutputChecker = MultiPlatformAnd23Checker
71
+
72
+
73
+ class DocTestTestSuite(_unittest.TestSuite):
74
+
75
+ """
76
+ Adds :mod:`array_split` doctests as `unittest.TestCase` objects.
77
+ """
78
+
79
+ def __init__(self):
80
+ """
81
+ Uses :meth:`unittest.TestSuite.addTests` to add :obj:`doctest.DocFileSuite`
82
+ and :obj:`doctest.DocTestSuite` tests.
83
+ """
84
+ readme_file_name = \
85
+ os.path.realpath(
86
+ os.path.join(os.path.dirname(__file__), "..", "README.rst")
87
+ )
88
+ examples_rst_file_name = \
89
+ os.path.realpath(
90
+ os.path.join(
91
+ os.path.dirname(__file__),
92
+ "..",
93
+ "docs",
94
+ "source",
95
+ "examples",
96
+ "index.rst"
97
+ )
98
+ )
99
+ suite = _unittest.TestSuite()
100
+ if os.path.exists(readme_file_name):
101
+ suite.addTests(
102
+ _doctest.DocFileSuite(
103
+ readme_file_name,
104
+ module_relative=False,
105
+ optionflags=_doctest.NORMALIZE_WHITESPACE
106
+ )
107
+ )
108
+ if os.path.exists(examples_rst_file_name):
109
+ suite.addTests(
110
+ _doctest.DocFileSuite(
111
+ examples_rst_file_name,
112
+ module_relative=False,
113
+ optionflags=_doctest.NORMALIZE_WHITESPACE
114
+ )
115
+ )
116
+ suite.addTests(
117
+ _doctest.DocTestSuite(
118
+ _array_split,
119
+ optionflags=_doctest.NORMALIZE_WHITESPACE
120
+ )
121
+ )
122
+ suite.addTests(
123
+ _doctest.DocTestSuite(
124
+ _split,
125
+ optionflags=_doctest.NORMALIZE_WHITESPACE
126
+ )
127
+ )
128
+
129
+ _unittest.TestSuite.__init__(self, suite)
130
+
131
+
132
+ def load_tests(loader, tests, pattern): # pylint: disable=unused-argument
133
+ """
134
+ Loads :mod:`array_split.split_test` tests and :obj:`DocTestTestSuite`
135
+ tests.
136
+ """
137
+ suite = loader.loadTestsFromNames(["array_split.split_test", ])
138
+ suite.addTests(DocTestTestSuite())
139
+ return suite
140
+
141
+
142
+ __all__ = [s for s in dir() if not s.startswith('_')]
143
+
144
+ if __name__ == "__main__":
145
+ # import logging
146
+ # logging.basicConfig(level=logging.DEBUG)
147
+ _unittest.main()
@@ -0,0 +1,352 @@
1
+ """
2
+ ======================================
3
+ The :mod:`array_split.unittest` Module
4
+ ======================================
5
+
6
+ Some simple wrappers of python built-in :mod:`unittest` module
7
+ for :mod:`array_split` unit-tests.
8
+
9
+ .. currentmodule:: array_split.unittest
10
+
11
+ Classes and Functions
12
+ =====================
13
+
14
+ .. autosummary::
15
+ :toctree: generated/
16
+
17
+ main - Convenience command-line test-case *search and run* function.
18
+ TestCase - Extends :obj:`unittest.TestCase` with :obj:`TestCase.assertArraySplitEqual`.
19
+
20
+ """
21
+ from __future__ import absolute_import
22
+
23
+ import unittest as _builtin_unittest
24
+ import numpy as _np
25
+ from .license import license as _license, copyright as _copyright, version as _version
26
+ from . import logging as _logging
27
+
28
+ __author__ = "Shane J. Latham"
29
+ __license__ = _license()
30
+ __copyright__ = _copyright()
31
+ __version__ = _version()
32
+
33
+ # pylint: disable=invalid-name
34
+ # pylint: disable=arguments-differ
35
+ # pylint: disable=trailing-whitespace
36
+ # pylint: disable=no-member
37
+ # pylint: disable=deprecated-method
38
+ # pylint: disable=broad-except
39
+ # pylint: disable=too-many-locals
40
+ # pylint: disable=protected-access
41
+ # pylint: disable=too-many-branches
42
+
43
+
44
+ def main(module_name, log_level=_logging.DEBUG, init_logger_names=None):
45
+ """
46
+ Small wrapper for :func:`unittest.main` which initialises :mod:`logging.Logger` objects.
47
+ Loads a set of tests from module and runs them;
48
+ this is primarily for making test modules conveniently executable.
49
+ The simplest use for this function is to include the following line at
50
+ the end of a test module::
51
+
52
+ array_split.unittest.main(__name__)
53
+
54
+ If :samp:`__name__ == "__main__"`, then *discoverable* :obj:`unittest.TestCase`
55
+ test cases are executed.
56
+ Logging level can be explicitly set for a group of modules using::
57
+
58
+ import logging
59
+
60
+ array_split.unittest.main(
61
+ __name__,
62
+ logging.DEBUG,
63
+ [__name__, "module_name_0", "module_name_1", "package.module_name_2"]
64
+ )
65
+
66
+
67
+ :type module_name: :obj:`str`
68
+ :param module_name: If :samp:`{module_name} == "__main__"` then unit-tests
69
+ are *discovered* and run.
70
+ :type log_level: :obj:`int`
71
+ :param log_level: The default logging level for all
72
+ :obj:`array_split.logging.Logger` objects.
73
+ :type init_logger_names: sequence of :obj:`str`
74
+ :param init_logger_names: List of logger names to initialise
75
+ (using :func:`array_split.logging.initialise_loggers`). If :samp:`None`,
76
+ then the list defaults to :samp:`[{module_name}, "array_split"]`. If list
77
+ is empty no loggers are initialised.
78
+
79
+ """
80
+ if module_name == "__main__":
81
+ if init_logger_names is None:
82
+ init_logger_names = [module_name, "array_split"]
83
+
84
+ if len(init_logger_names) > 0:
85
+ _logging.initialise_loggers(
86
+ init_logger_names, log_level=log_level)
87
+
88
+ _builtin_unittest.main()
89
+
90
+
91
+ def _fix_docstring_for_sphinx(docstr):
92
+ """
93
+ Remove 8-space indentation from lines of specified :samp:`{docstr}` string.
94
+ """
95
+ lines = docstr.split("\n")
96
+ for i in range(len(lines)):
97
+ if lines[i].find(" " * 8) == 0:
98
+ lines[i] = lines[i][8:]
99
+ return "\n".join(lines)
100
+
101
+
102
+ class TestCase(_builtin_unittest.TestCase):
103
+
104
+ """
105
+ Extends :obj:`unittest.TestCase` with the :meth:`assertArraySplitEqual`.
106
+ """
107
+
108
+ def assertArraySplitEqual(self, splt1, splt2):
109
+ """
110
+ Compares :obj:`list` of :obj:`numpy.ndarray` results returned by :func:`numpy.array_split`
111
+ and :func:`array_split.split.array_split` functions.
112
+
113
+ :type splt1: :obj:`list` of :obj:`numpy.ndarray`
114
+ :param splt1: First object in equality comparison.
115
+ :type splt2: :obj:`list` of :obj:`numpy.ndarray`
116
+ :param splt2: Second object in equality comparison.
117
+ :raises unittest.AssertionError: If any element of :samp:`{splt1}` is not equal to
118
+ the corresponding element of :samp:`splt2`.
119
+ """
120
+ self.assertEqual(len(splt1), len(splt2))
121
+ for i in range(len(splt1)):
122
+ self.assertTrue(
123
+ (
124
+ _np.all(_np.array(splt1[i]) == _np.array(splt2[i]))
125
+ or
126
+ ((_np.array(splt1[i]).size == 0) and (_np.array(splt2[i]).size == 0))
127
+ ),
128
+ msg=(
129
+ "element %d of split is not equal %s != %s"
130
+ %
131
+ (i, _np.array(splt1[i]), _np.array(splt2[i]))
132
+ )
133
+ )
134
+
135
+ #
136
+ # Method over-rides below are just to avoid sphinx warnings
137
+ #
138
+ def assertItemsEqual(self, *args, **kwargs):
139
+ """
140
+ See :obj:`unittest.TestCase.assertItemsEqual`.
141
+ """
142
+ _builtin_unittest.TestCase.assertItemsEqual(self, *args, **kwargs)
143
+
144
+ def assertListEqual(self, *args, **kwargs):
145
+ """
146
+ See :obj:`unittest.TestCase.assertListEqual`.
147
+ """
148
+ _builtin_unittest.TestCase.assertListEqual(self, *args, **kwargs)
149
+
150
+ def assertRaisesRegexp(self, *args, **kwargs):
151
+ """
152
+ See :obj:`unittest.TestCase.assertRaisesRegexp`.
153
+ """
154
+ _builtin_unittest.TestCase.assertRaisesRegexp(self, *args, **kwargs)
155
+
156
+ def assertRaisesRegex(self, *args, **kwargs):
157
+ """
158
+ See :obj:`unittest.TestCase.assertRaisesRegex`.
159
+ """
160
+ _builtin_unittest.TestCase.assertRaisesRegex(self, *args, **kwargs)
161
+
162
+ def assertSetEqual(self, *args, **kwargs):
163
+ """
164
+ See :obj:`unittest.TestCase.assertSetEqual`.
165
+ """
166
+ _builtin_unittest.TestCase.assertSetEqual(self, *args, **kwargs)
167
+
168
+ def assertTupleEqual(self, *args, **kwargs):
169
+ """
170
+ See :obj:`unittest.TestCase.assertTupleEqual`.
171
+ """
172
+ _builtin_unittest.TestCase.assertTupleEqual(self, *args, **kwargs)
173
+
174
+ def assertWarnsRegex(self, *args, **kwargs):
175
+ """
176
+ See :obj:`unittest.TestCase.assertWarnsRegex`.
177
+ """
178
+ _builtin_unittest.TestCase.assertWarnsRegex(self, *args, **kwargs)
179
+
180
+
181
+ if not hasattr(TestCase, "assertSequenceEqual"):
182
+ # code from python-2.7 unitest.case.TestCase
183
+ _MAX_LENGTH = 80
184
+
185
+ def safe_repr(obj, short=False):
186
+ """
187
+ Returns :func:`repr` string for :samp:`{obj}`.
188
+ """
189
+ try:
190
+ result = repr(obj)
191
+ except Exception:
192
+ result = object.__repr__(obj)
193
+ if not short or len(result) < _MAX_LENGTH:
194
+ return result
195
+ return result[:_MAX_LENGTH] + ' [truncated]...'
196
+
197
+ def strclass(cls):
198
+ """
199
+ Returns name string of :samp:`{cls}` as `<modulename>.<classname>`.
200
+ """
201
+ return "%s.%s" % (cls.__module__, cls.__name__)
202
+
203
+ def assertSequenceEqual(self, seq1, seq2, msg=None, seq_type=None):
204
+ """An equality assertion for ordered sequences (like lists and tuples).
205
+
206
+ For the purposes of this function, a valid ordered sequence type is one
207
+ which can be indexed, has a length, and has an equality operator.
208
+
209
+ :param seq1: The first sequence to compare.
210
+ :param seq2: The second sequence to compare.
211
+ :param seq_type: The expected datatype of the sequences, or None if no
212
+ datatype should be enforced.
213
+ :param msg: Optional message to use on failure instead of a list of
214
+ differences.
215
+ """
216
+
217
+ import pprint
218
+ import difflib
219
+ if seq_type is not None:
220
+ seq_type_name = seq_type.__name__
221
+ if not isinstance(seq1, seq_type):
222
+ raise self.failureException('First sequence is not a %s: %s'
223
+ % (seq_type_name, safe_repr(seq1)))
224
+ if not isinstance(seq2, seq_type):
225
+ raise self.failureException('Second sequence is not a %s: %s'
226
+ % (seq_type_name, safe_repr(seq2)))
227
+ else:
228
+ seq_type_name = "sequence"
229
+
230
+ differing = None
231
+ try:
232
+ len1 = len(seq1)
233
+ except (TypeError, NotImplementedError):
234
+ differing = 'First %s has no length. Non-sequence?' % (
235
+ seq_type_name)
236
+
237
+ if differing is None:
238
+ try:
239
+ len2 = len(seq2)
240
+ except (TypeError, NotImplementedError):
241
+ differing = 'Second %s has no length. Non-sequence?' % (
242
+ seq_type_name)
243
+
244
+ if differing is None:
245
+ if seq1 == seq2:
246
+ return
247
+
248
+ seq1_repr = safe_repr(seq1)
249
+ seq2_repr = safe_repr(seq2)
250
+
251
+ if len(seq1_repr) > 30:
252
+ seq1_repr = seq1_repr[:30] + '...'
253
+ if len(seq2_repr) > 30:
254
+ seq2_repr = seq2_repr[:30] + '...'
255
+ elements = (seq_type_name.capitalize(), seq1_repr, seq2_repr)
256
+ differing = '%ss differ: %s != %s\n' % elements
257
+
258
+ for i in range(min(len1, len2)):
259
+ try:
260
+ item1 = seq1[i]
261
+ except (TypeError, IndexError, NotImplementedError):
262
+ differing += ('\nUnable to index element %d of first %s\n' %
263
+ (i, seq_type_name))
264
+ break
265
+
266
+ try:
267
+ item2 = seq2[i]
268
+ except (TypeError, IndexError, NotImplementedError):
269
+ differing += ('\nUnable to index element %d of second %s\n' %
270
+ (i, seq_type_name))
271
+ break
272
+
273
+ if item1 != item2:
274
+ differing += ('\nFirst differing element %d:\n%s\n%s\n' %
275
+ (i, item1, item2))
276
+ break
277
+ else:
278
+ if (len1 == len2 and seq_type is None and
279
+ not isinstance(seq1, type(seq2))):
280
+ # The sequences are the same, but have differing types.
281
+ return
282
+
283
+ if len1 > len2:
284
+ differing += ('\nFirst %s contains %d additional '
285
+ 'elements.\n' % (seq_type_name, len1 - len2))
286
+ try:
287
+ differing += ('First extra element %d:\n%s\n' %
288
+ (len2, seq1[len2]))
289
+ except (TypeError, IndexError, NotImplementedError):
290
+ differing += ('Unable to index element %d '
291
+ 'of first %s\n' % (len2, seq_type_name))
292
+ elif len1 < len2:
293
+ differing += ('\nSecond %s contains %d additional '
294
+ 'elements.\n' % (seq_type_name, len2 - len1))
295
+ try:
296
+ differing += ('First extra element %d:\n%s\n' %
297
+ (len1, seq2[len1]))
298
+ except (TypeError, IndexError, NotImplementedError):
299
+ differing += ('Unable to index element %d '
300
+ 'of second %s\n' % (len1, seq_type_name))
301
+ standardMsg = differing
302
+ diffMsg = '\n' + '\n'.join(
303
+ difflib.ndiff(pprint.pformat(seq1).splitlines(),
304
+ pprint.pformat(seq2).splitlines()))
305
+ standardMsg = self._truncateMessage(standardMsg, diffMsg)
306
+ msg = self._formatMessage(msg, standardMsg)
307
+ self.fail(msg)
308
+
309
+ def _formatMessage(self, msg, standardMsg):
310
+ """Honour the longMessage attribute when generating failure messages.
311
+ If longMessage is False this means:
312
+ * Use only an explicit message if it is provided
313
+ * Otherwise use the standard message for the assert
314
+
315
+ If longMessage is True:
316
+ * Use the standard message
317
+ * If an explicit message is provided, plus ' : ' and the explicit message
318
+ """
319
+ if not self.longMessage:
320
+ return msg or standardMsg
321
+ if msg is None:
322
+ return standardMsg
323
+ try:
324
+ # don't switch to '{}' formatting in Python 2.X
325
+ # it changes the way unicode input is handled
326
+ return '%s : %s' % (standardMsg, msg)
327
+ except UnicodeDecodeError:
328
+ return '%s : %s' % (safe_repr(standardMsg), safe_repr(msg))
329
+
330
+ def _truncateMessage(self, message, diff):
331
+ DIFF_OMITTED = ('\nDiff is %s characters long. '
332
+ 'Set self.maxDiff to None to see it.')
333
+
334
+ max_diff = self.maxDiff
335
+ if max_diff is None or len(diff) <= max_diff:
336
+ return message + diff
337
+ return message + (DIFF_OMITTED % len(diff))
338
+
339
+ _maxDiff = 80 * 8
340
+ setattr(TestCase, "maxDiff", _maxDiff)
341
+ setattr(TestCase, "_truncateMessage", _truncateMessage)
342
+ setattr(TestCase, "_formatMessage", _formatMessage)
343
+ setattr(TestCase, "assertSequenceEqual", assertSequenceEqual)
344
+ else:
345
+
346
+ def assertSequenceEqual(self, *args, **kwargs):
347
+ """
348
+ See :obj:`unittest.TestCase.assertSequenceEqual`.
349
+ """
350
+ _builtin_unittest.TestCase.assertSequenceEqual(self, *args, **kwargs)
351
+
352
+ setattr(TestCase, "assertSequenceEqual", assertSequenceEqual)