unittest2pytest 0.5__py3-none-any.whl

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,26 @@
1
+ #
2
+ # Copyright 2015-2019 by Hartmut Goebel <h.goebel@crazy-compilers.com>
3
+ #
4
+ # This file is part of unittest2pytest.
5
+ #
6
+ # unittest2pytest is free software: you can redistribute it and/or modify
7
+ # it under the terms of the GNU General Public License as published by
8
+ # the Free Software Foundation, either version 3 of the License, or
9
+ # (at your option) any later version.
10
+ #
11
+ # This program is distributed in the hope that it will be useful, but
12
+ # WITHOUT ANY WARRANTY; without even the implied warranty of
13
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14
+ # General Public License for more details.
15
+ #
16
+ # You should have received a copy of the GNU General Public License
17
+ # along with this program. If not, see <http://www.gnu.org/licenses/>.
18
+ #
19
+
20
+ __author__ = "Hartmut Goebel <h.goebel@crazy-compilers.com>"
21
+ __copyright__ = "Copyright 2015-2019 by Hartmut Goebel"
22
+ __licence__ = "GNU General Public License version 3 or later (GPLv3+)"
23
+
24
+
25
+ __title__ = 'unittest2pytest'
26
+ __version__ = '0.5'
@@ -0,0 +1,32 @@
1
+ #
2
+ # Copyright 2015-2019 by Hartmut Goebel <h.goebel@crazy-compilers.com>
3
+ #
4
+ # This file is part of unittest2pytest.
5
+ #
6
+ # unittest2pytest is free software: you can redistribute it and/or modify
7
+ # it under the terms of the GNU General Public License as published by
8
+ # the Free Software Foundation, either version 3 of the License, or
9
+ # (at your option) any later version.
10
+ #
11
+ # This program is distributed in the hope that it will be useful, but
12
+ # WITHOUT ANY WARRANTY; without even the implied warranty of
13
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14
+ # General Public License for more details.
15
+ #
16
+ # You should have received a copy of the GNU General Public License
17
+ # along with this program. If not, see <http://www.gnu.org/licenses/>.
18
+ #
19
+
20
+ __author__ = "Hartmut Goebel <h.goebel@crazy-compilers.com>"
21
+ __copyright__ = "Copyright 2015-2019 by Hartmut Goebel"
22
+ __licence__ = "GNU General Public License version 3 or later (GPLv3+)"
23
+
24
+
25
+ import lib2to3.main
26
+ from . import fixes
27
+
28
+ def main():
29
+ raise SystemExit(lib2to3.main.main(fixes.__name__))
30
+
31
+ if __name__ == '__main__':
32
+ main()
@@ -0,0 +1 @@
1
+ #
@@ -0,0 +1,86 @@
1
+ """
2
+ fix_remove_class - lib2to3 fix for removing "class Testxxx(TestCase):"
3
+ headers and dedenting the contained code.
4
+ """
5
+ #
6
+ # Copyright 2015-2019 by Hartmut Goebel <h.goebel@crazy-compilers.com>
7
+ #
8
+ # This file is part of unittest2pytest.
9
+ #
10
+ # unittest2pytest is free software: you can redistribute it and/or modify
11
+ # it under the terms of the GNU General Public License as published by
12
+ # the Free Software Foundation, either version 3 of the License, or
13
+ # (at your option) any later version.
14
+ #
15
+ # This program is distributed in the hope that it will be useful, but
16
+ # WITHOUT ANY WARRANTY; without even the implied warranty of
17
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18
+ # General Public License for more details.
19
+ #
20
+ # You should have received a copy of the GNU General Public License
21
+ # along with this program. If not, see <http://www.gnu.org/licenses/>.
22
+ #
23
+
24
+ __author__ = "Hartmut Goebel <h.goebel@crazy-compilers.com>"
25
+ __copyright__ = "Copyright 2015-2019 by Hartmut Goebel"
26
+ __licence__ = "GNU General Public License version 3 or later (GPLv3+)"
27
+
28
+
29
+ from lib2to3.fixer_base import BaseFix
30
+ from lib2to3.fixer_util import token, find_indentation
31
+
32
+ """
33
+ Node(classdef,
34
+ [Leaf(1, 'class'),
35
+ Leaf(1, 'TestAssertEqual'),
36
+ Leaf(7, '('),
37
+ Leaf(1, 'TestCase'),
38
+ Leaf(8, ')'),
39
+ Leaf(11, ':'),
40
+ Node(suite, [
41
+ Leaf(4, '\n'),
42
+ Leaf(5, ' '),
43
+ Node(funcdef, [
44
+ Leaf(1, 'def'),
45
+ Leaf(1, 'test_you'), ...
46
+ ]),
47
+ Leaf(6, '')])])
48
+ """
49
+
50
+ class FixRemoveClass(BaseFix):
51
+
52
+ PATTERN = """
53
+ classdef< 'class' name=any '(' 'TestCase' ')' ':'
54
+ suite=suite
55
+ >
56
+ """
57
+
58
+ def dedent(self, suite, dedent):
59
+ self.line_num = suite.get_lineno()
60
+ for kid in suite.leaves():
61
+ if kid.type in (token.INDENT, token.DEDENT):
62
+ self.line_num = kid.get_lineno()
63
+ # todo: handle tabs
64
+ kid.value = kid.value[dedent:]
65
+ self.current_indent = kid.value
66
+ elif kid.get_lineno() != self.line_num:
67
+ # todo: handle tabs
68
+ if len(kid.prefix) > len(self.current_indent):
69
+ kid.prefix = self.current_indent
70
+
71
+
72
+ def transform(self, node, results):
73
+ suite = results['suite'].clone()
74
+ # todo: handle tabs
75
+ dedent = len(find_indentation(suite)) - len(find_indentation(node))
76
+ self.dedent(suite, dedent)
77
+
78
+ # remove the first newline behind the classdef header
79
+ first = suite.children[0]
80
+ if first.type == token.NEWLINE:
81
+ if len(first.value) == 1:
82
+ del suite.children[0]
83
+ else:
84
+ first.value == first.value[1:]
85
+
86
+ return suite
@@ -0,0 +1,480 @@
1
+ """
2
+ fix_self_assert - lib2to3 fix for replacing assertXXX() method calls
3
+ by their pytest equivalent.
4
+ """
5
+ #
6
+ # Copyright 2015-2019 by Hartmut Goebel <h.goebel@crazy-compilers.com>
7
+ #
8
+ # This file is part of unittest2pytest.
9
+ #
10
+ # unittest2pytest is free software: you can redistribute it and/or modify
11
+ # it under the terms of the GNU General Public License as published by
12
+ # the Free Software Foundation, either version 3 of the License, or
13
+ # (at your option) any later version.
14
+ #
15
+ # This program is distributed in the hope that it will be useful, but
16
+ # WITHOUT ANY WARRANTY; without even the implied warranty of
17
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18
+ # General Public License for more details.
19
+ #
20
+ # You should have received a copy of the GNU General Public License
21
+ # along with this program. If not, see <http://www.gnu.org/licenses/>.
22
+ #
23
+
24
+ __author__ = "Hartmut Goebel <h.goebel@crazy-compilers.com>"
25
+ __copyright__ = "Copyright 2015-2019 by Hartmut Goebel"
26
+ __licence__ = "GNU General Public License version 3 or later (GPLv3+)"
27
+
28
+
29
+ from lib2to3.fixer_base import BaseFix
30
+ from lib2to3.fixer_util import (
31
+ Comma, Name, Call, Node, Leaf,
32
+ Newline, KeywordArg, find_indentation,
33
+ ArgList, String, Number, syms, token,
34
+ does_tree_import, is_import, parenthesize)
35
+
36
+ from functools import partial
37
+ import re
38
+ import unittest
39
+
40
+ from .. import utils
41
+
42
+
43
+ TEMPLATE_PATTERN = re.compile('[\1\2]|[^\1\2]+')
44
+
45
+ def CompOp(op, left, right, kws):
46
+ op = Name(op, prefix=" ")
47
+ left = parenthesize_expression(left)
48
+ right = parenthesize_expression(right)
49
+
50
+ left.prefix = ""
51
+ if '\n' not in right.prefix:
52
+ right.prefix = " "
53
+ return Node(syms.comparison, (left, op, right), prefix=" ")
54
+
55
+
56
+ def UnaryOp(prefix, postfix, value, kws):
57
+ if prefix or postfix:
58
+ value = parenthesize_expression(value)
59
+
60
+ kids = []
61
+ if prefix:
62
+ kids.append(Name(prefix, prefix=" "))
63
+ value.prefix = " "
64
+ kids.append(value)
65
+ if postfix:
66
+ kids.append(Name(postfix, prefix=" "))
67
+ return Node(syms.test, kids, prefix=" ")
68
+
69
+
70
+ # These symbols have lower precedence than the CompOps we use and thus
71
+ # need to be parenthesized. For datails see
72
+ # https://docs.python.org/3/reference/expressions.html#operator-precedence
73
+ _NEEDS_PARENTHESIS = [
74
+ syms.test, # if – else
75
+ syms.or_test,
76
+ syms.and_test,
77
+ syms.not_test,
78
+ syms.comparison,
79
+ ]
80
+
81
+ def parenthesize_expression(value):
82
+ if value.type in _NEEDS_PARENTHESIS:
83
+ parenthesized = parenthesize(value.clone())
84
+ parenthesized.prefix = parenthesized.children[1].prefix
85
+ parenthesized.children[1].prefix = ''
86
+ value = parenthesized
87
+ return value
88
+
89
+
90
+ def fill_template(template, *args):
91
+ parts = TEMPLATE_PATTERN.findall(template)
92
+ kids = []
93
+ for p in parts:
94
+ if p == '':
95
+ continue
96
+ elif p in '\1\2\3\4\5':
97
+ p = args[ord(p)-1]
98
+ p.prefix = ''
99
+ else:
100
+ p = Name(p)
101
+ kids.append(p.clone())
102
+ return kids
103
+
104
+ def DualOp(template, first, second, kws):
105
+ kids = fill_template(template, first, second)
106
+ return Node(syms.test, kids, prefix=" ")
107
+
108
+
109
+ def SequenceEqual(left, right, kws):
110
+ if 'seq_type' in kws:
111
+ # :todo: implement `assert isinstance(xx, seq_type)`
112
+ pass
113
+ return CompOp('==', left, right, kws)
114
+
115
+
116
+ def AlmostOp(places_op, delta_op, first, second, kws):
117
+ first.prefix = ""
118
+ second.prefix = ""
119
+ first = parenthesize_expression(first)
120
+ second = parenthesize_expression(second)
121
+ abs_op = Call(Name('abs'),
122
+ [Node(syms.factor, [first, Name('-'), second])])
123
+ if kws.get('delta', None) is not None:
124
+ # delta
125
+ return CompOp(delta_op, abs_op, kws['delta'], {})
126
+ else:
127
+ # `7` is the default in unittest.TestCase.assertAlmostEqual
128
+ places = kws['places'] or Number(7)
129
+ places.prefix = " "
130
+ round_op = Call(Name('round'), (abs_op, Comma(), places))
131
+ return CompOp(places_op, round_op, Number(0), {})
132
+
133
+
134
+ def RaisesOp(context, exceptionClass, indent, kws, arglist, node):
135
+ exceptionClass.prefix = ""
136
+ args = [exceptionClass]
137
+ # Add match keyword arg to with statement if an expected regex was provided.
138
+ if 'expected_regex' in kws:
139
+ expected_regex = kws.get('expected_regex').clone()
140
+ expected_regex.prefix = ''
141
+ args.append(String(', '))
142
+ args.append(
143
+ KeywordArg(Name('match'), expected_regex))
144
+ with_item = Call(Name(context), args)
145
+ with_item.prefix = " "
146
+ args = []
147
+ arglist = [a.clone() for a in arglist.children[4:]]
148
+ if arglist:
149
+ arglist[0].prefix=""
150
+
151
+ func = None
152
+
153
+ # :fixme: this uses hardcoded parameter names, which may change
154
+ if 'callableObj' in kws:
155
+ func = kws['callableObj']
156
+ elif 'callable_obj' in kws:
157
+ func = kws['callable_obj']
158
+ elif kws['args']: # any arguments assigned to `*args`
159
+ func = kws['args'][0]
160
+ else:
161
+ func = None
162
+
163
+ if func is None:
164
+ # Context manager
165
+ return Node(syms.with_stmt, [with_item])
166
+
167
+ if func.type == syms.lambdef:
168
+ suite = func.children[-1].clone()
169
+ else:
170
+ # TODO: Newlines within arguments are not handled yet.
171
+ # If argument prefix contains a newline, all whitespace around this
172
+ # ought to be replaced by indent plus 4+1+len(func) spaces.
173
+ suite = Call(func, arglist)
174
+
175
+ suite.prefix = indent + (4 * " ")
176
+ return Node(syms.with_stmt,
177
+ [Name('with'),
178
+ with_item,
179
+ Name(':'),
180
+ Newline(),
181
+ suite])
182
+
183
+ def RaisesRegexOp(context, designator, exceptionClass, expected_regex,
184
+ indent, kws, arglist, node):
185
+ arglist = [a.clone() for a in arglist.children]
186
+ pattern = arglist[2]
187
+ del arglist[2:4] # remove pattern and comma
188
+ arglist = Node(syms.arglist, arglist)
189
+ with_stmt = RaisesOp(context, exceptionClass, indent, kws, arglist, node)
190
+
191
+ # if this is already part of a with statement we need to insert re.search
192
+ # after the last leaf with content
193
+ if node.parent.type == syms.with_stmt:
194
+ parent_with = node.parent
195
+ for leaf in reversed(list(parent_with.leaves())):
196
+ if leaf.value.strip():
197
+ break
198
+ i = leaf.parent.children.index(leaf)
199
+ return with_stmt
200
+ else:
201
+ return Node(syms.suite, [with_stmt])
202
+
203
+ def FailOp(indent, kws, arglist, node):
204
+ new = node.clone()
205
+ new.set_child(0, Name('pytest'))
206
+ return new
207
+
208
+ def add_import(import_name, node):
209
+ suite = get_parent_of_type(node, syms.suite)
210
+ test_case = suite
211
+ while test_case.parent.type != syms.file_input:
212
+ test_case = test_case.parent
213
+ file_input = test_case.parent
214
+
215
+ if not does_tree_import(None, import_name, node):
216
+ import_stmt = Node(syms.simple_stmt,
217
+ [Node(syms.import_name, [Name('import'), Name(import_name, prefix=' ')]),
218
+ Newline(),
219
+ ])
220
+ insert_import(import_stmt, test_case, file_input)
221
+
222
+
223
+ def get_parent_of_type(node, node_type):
224
+ while node:
225
+ if node.type == node_type:
226
+ return node
227
+ node = node.parent
228
+
229
+
230
+ def insert_import(import_stmt, test_case, file_input):
231
+ """This inserts an import in a very similar way as
232
+ lib2to3.fixer_util.touch_import, but try to maintain encoding and shebang
233
+ prefixes on top of the file when there is no import"""
234
+ import_nodes = get_import_nodes(file_input)
235
+ if import_nodes:
236
+ last_import_stmt = import_nodes[-1].parent
237
+ i = file_input.children.index(last_import_stmt) + 1
238
+ # no import found, so add right before the test case
239
+ else:
240
+ i = file_input.children.index(test_case)
241
+ import_stmt.prefix = test_case.prefix
242
+ test_case.prefix = ''
243
+ file_input.insert_child(i, import_stmt)
244
+
245
+
246
+ def get_import_nodes(node):
247
+ return [
248
+ x for c in node.children
249
+ for x in c.children
250
+ if c.type == syms.simple_stmt
251
+ and is_import(x)
252
+ ]
253
+
254
+
255
+ _method_map = {
256
+ # simple ones
257
+ 'assertEqual': partial(CompOp, '=='),
258
+ 'assertNotEqual': partial(CompOp, '!='),
259
+ 'assertFalse': partial(UnaryOp, 'not', ''),
260
+ 'assertGreater': partial(CompOp, '>'),
261
+ 'assertGreaterEqual': partial(CompOp, '>='),
262
+ 'assertIn': partial(CompOp, 'in'),
263
+ 'assertIs': partial(CompOp, 'is'),
264
+ 'assertIsInstance': partial(DualOp, 'isinstance(\1, \2)'),
265
+ 'assertIsNone': partial(UnaryOp, '', 'is None'),
266
+ 'assertIsNot': partial(CompOp, 'is not'),
267
+ 'assertIsNotNone': partial(UnaryOp, '', 'is not None'),
268
+ 'assertLess': partial(CompOp, '<'),
269
+ 'assertLessEqual': partial(CompOp, '<='),
270
+ 'assertNotIn': partial(CompOp, 'not in'),
271
+ 'assertNotIsInstance': partial(DualOp, 'not isinstance(\1, \2)'),
272
+ 'assertTrue': partial(UnaryOp, '', ''),
273
+
274
+ # types ones
275
+ 'assertDictEqual': partial(CompOp, '=='),
276
+ 'assertListEqual': partial(CompOp, '=='),
277
+ 'assertMultiLineEqual': partial(CompOp, '=='),
278
+ 'assertSetEqual': partial(CompOp, '=='),
279
+ 'assertTupleEqual': partial(CompOp, '=='),
280
+ 'assertSequenceEqual': SequenceEqual,
281
+
282
+ 'assertDictContainsSubset': partial(DualOp, '{**\2, **\1} == \2'),
283
+ 'assertItemsEqual': partial(DualOp, 'sorted(\1) == sorted(\2)'),
284
+
285
+ 'assertAlmostEqual': partial(AlmostOp, "==", "<"),
286
+ 'assertNotAlmostEqual': partial(AlmostOp, "!=", ">"),
287
+
288
+ 'assertRaises': partial(RaisesOp, 'pytest.raises'),
289
+ 'assertWarns': partial(RaisesOp, 'pytest.warns'), # new Py 3.2
290
+
291
+ 'assertRegex': partial(DualOp, 're.search(\2, \1)'),
292
+ 'assertNotRegex': partial(DualOp, 'not re.search(\2, \1)'), # new Py 3.2
293
+
294
+ 'assertRaisesRegex': partial(RaisesRegexOp, 'pytest.raises', 'excinfo'),
295
+ 'assertWarnsRegex': partial(RaisesRegexOp, 'pytest.warns', 'record'),
296
+
297
+ 'fail': FailOp,
298
+
299
+ #'assertLogs': -- not to be handled here, is an context handler only
300
+ }
301
+
302
+ for newname, oldname in (
303
+ ('assertRaisesRegex', 'assertRaisesRegexp'),
304
+ ('assertRegex', 'assertRegexpMatches'),
305
+ ):
306
+ if not hasattr(unittest.TestCase, newname):
307
+ # use old name
308
+ _method_map[oldname] = _method_map[newname]
309
+ del _method_map[newname]
310
+
311
+ for m in list(_method_map.keys()):
312
+ if not hasattr(unittest.TestCase, m):
313
+ del _method_map[m]
314
+
315
+
316
+ # (Deprecated) Aliases
317
+ _method_aliases = {
318
+ 'assertEquals' : 'assertEqual',
319
+ 'assertNotEquals' : 'assertNotEqual',
320
+ 'assert_' : 'assertTrue',
321
+ 'assertAlmostEquals' : 'assertAlmostEqual',
322
+ 'assertNotAlmostEquals': 'assertNotAlmostEqual',
323
+ 'assertRegexpMatches' : 'assertRegex',
324
+ 'assertRaisesRegexp' : 'assertRaisesRegex',
325
+
326
+ 'failUnlessEqual' : 'assertEqual',
327
+ 'failIfEqual' : 'assertNotEqual',
328
+ 'failUnless' : 'assertTrue',
329
+ 'failIf' : 'assertFalse',
330
+ 'failUnlessRaises' : 'assertRaises',
331
+ 'failUnlessAlmostEqual': 'assertAlmostEqual',
332
+ 'failIfAlmostEqual' : 'assertNotAlmostEqual',
333
+ }
334
+
335
+ for a, o in list(_method_aliases.items()):
336
+ if not o in _method_map:
337
+ # if the original name is not a TestCase method, remove the alias
338
+ del _method_aliases[a]
339
+
340
+
341
+ """
342
+ Node(power,
343
+ [Leaf(1, u'self'),
344
+ Node(trailer,
345
+ [Leaf(23, u'.'),
346
+ Leaf(1, u'assertEqual')]),
347
+ Node(trailer,
348
+ [Leaf(7, u'('),
349
+ Node(arglist,
350
+ [Leaf(1, u'abc'),
351
+ Leaf(12, u','),
352
+ Leaf(3, u"'xxx'")]),
353
+ Leaf(8, u')')])])
354
+
355
+ Node(power,
356
+ [Leaf(1, u'self'),
357
+ Node(trailer,
358
+ [Leaf(23, u'.'),
359
+ Leaf(1, u'assertAlmostEqual')]),
360
+ Node(trailer,
361
+ [Leaf(7, u'('),
362
+ Node(arglist,
363
+ [Leaf(2, u'100'),
364
+ Leaf(12, u','),
365
+ Leaf(1, u'klm'),
366
+ Leaf(12, u','),
367
+ Node(argument,
368
+ [Leaf(1, u'msg'),
369
+ Leaf(22, u'='),
370
+ Leaf(3, u'"Message"')]),
371
+ Leaf(12, u','),
372
+ Node(argument,
373
+ [Leaf(1, u'places'),
374
+ Leaf(22, u'='),
375
+ Leaf(2, u'1')])]),
376
+ Leaf(8, u')')])])
377
+ """
378
+
379
+
380
+ class FixSelfAssert(BaseFix):
381
+
382
+ PATTERN = """
383
+ power< 'self'
384
+ trailer< '.' method=( %s ) >
385
+ trailer< '(' [arglist=any] ')' >
386
+ >
387
+ """ % ' | '.join(map(repr,
388
+ (set(_method_map.keys()) | set(_method_aliases.keys()))))
389
+
390
+ def transform(self, node, results):
391
+
392
+ def process_arg(arg):
393
+ if isinstance(arg, Leaf) and arg.type == token.COMMA:
394
+ return
395
+ elif (isinstance(arg, Node) and arg.type == syms.argument and
396
+ arg.children[1].type == token.EQUAL):
397
+ # keyword argument
398
+ name, equal, value = arg.children
399
+ assert name.type == token.NAME
400
+ assert equal.type == token.EQUAL
401
+ value = value.clone()
402
+ kwargs[name.value] = value
403
+ if '\n' in arg.prefix:
404
+ value.prefix = arg.prefix
405
+ else:
406
+ value.prefix = arg.prefix.strip() + " "
407
+ else:
408
+ if (isinstance(arg, Node) and arg.type == syms.argument and
409
+ arg.children[0].type == 36 and arg.children[0].value == '**'):
410
+ return
411
+ assert not kwargs, 'all positional args are assumed to come first'
412
+ if (isinstance(arg, Node) and arg.type == syms.argument and
413
+ arg.children[1].type == syms.comp_for):
414
+ # argument is a generator expression w/o
415
+ # parenthesis, add parenthesis
416
+ value = arg.clone()
417
+ value.children.insert(0, Leaf(token.LPAR, '('))
418
+ value.children.append(Leaf(token.RPAR, ')'))
419
+ posargs.append(value)
420
+ else:
421
+ posargs.append(arg.clone())
422
+
423
+ method = results['method'][0].value
424
+ # map (deprecated) aliases to original to avoid analysing
425
+ # the decorator function
426
+ method = _method_aliases.get(method, method)
427
+
428
+ posargs = []
429
+ kwargs = {}
430
+
431
+ # This is either empty, an "arglist", or a single argument
432
+ if 'arglist' not in results:
433
+ pass
434
+ elif results['arglist'].type == syms.arglist:
435
+ for arg in results['arglist'].children:
436
+ process_arg(arg)
437
+ else:
438
+ process_arg(results['arglist'])
439
+
440
+ try:
441
+ test_func = getattr(unittest.TestCase, method)
442
+ except AttributeError:
443
+ raise RuntimeError("Your unittest package does not support '%s'. "
444
+ "consider updating the package" % method)
445
+
446
+ required_args, argsdict = utils.resolve_func_args(test_func, posargs, kwargs)
447
+
448
+ if method.startswith(('assertRaises', 'assertWarns')) or method == 'fail':
449
+ n_stmt = _method_map[method](*required_args,
450
+ indent=find_indentation(node),
451
+ kws=argsdict,
452
+ arglist=results.get('arglist'),
453
+ node=node)
454
+ else:
455
+ n_stmt = Node(syms.assert_stmt,
456
+ [Name('assert'),
457
+ _method_map[method](*required_args, kws=argsdict)])
458
+ if argsdict.get('msg', None) is not None and method != 'fail':
459
+ n_stmt.children.extend((Name(','), argsdict['msg']))
460
+
461
+ def fix_line_wrapping(x):
462
+ for c in x.children:
463
+ # no need to worry about wrapping of "[", "{" and "("
464
+ if c.type in [token.LSQB, token.LBRACE, token.LPAR]:
465
+ break
466
+ if c.prefix.startswith('\n'):
467
+ c.prefix = c.prefix.replace('\n', ' \\\n')
468
+ fix_line_wrapping(c)
469
+ fix_line_wrapping(n_stmt)
470
+ # the prefix should be set only after fixing line wrapping because it can contain a '\n'
471
+ n_stmt.prefix = node.prefix
472
+
473
+ # add necessary imports
474
+ if 'Raises' in method or 'Warns' in method or method == 'fail':
475
+ add_import('pytest', node)
476
+ if ('Regex' in method and not 'Raises' in method and
477
+ not 'Warns' in method):
478
+ add_import('re', node)
479
+
480
+ return n_stmt
@@ -0,0 +1,50 @@
1
+ """
2
+ Some utility functions for unittest2pytest.
3
+ """
4
+ #
5
+ # Copyright 2015-2019 by Hartmut Goebel <h.goebel@crazy-compilers.com>
6
+ #
7
+ # This file is part of unittest2pytest.
8
+ #
9
+ # unittest2pytest is free software: you can redistribute it and/or modify
10
+ # it under the terms of the GNU General Public License as published by
11
+ # the Free Software Foundation, either version 3 of the License, or
12
+ # (at your option) any later version.
13
+ #
14
+ # This program is distributed in the hope that it will be useful, but
15
+ # WITHOUT ANY WARRANTY; without even the implied warranty of
16
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17
+ # General Public License for more details.
18
+ #
19
+ # You should have received a copy of the GNU General Public License
20
+ # along with this program. If not, see <http://www.gnu.org/licenses/>.
21
+ #
22
+
23
+ __author__ = "Hartmut Goebel <h.goebel@crazy-compilers.com>"
24
+ __copyright__ = "Copyright 2015-2019 by Hartmut Goebel"
25
+ __licence__ = "GNU General Public License version 3 or later (GPLv3+)"
26
+
27
+
28
+ import inspect
29
+ from inspect import Parameter
30
+
31
+
32
+ class SelfMarker: pass
33
+
34
+
35
+ def resolve_func_args(test_func, posargs, kwargs):
36
+ sig = inspect.signature(test_func)
37
+ assert (list(iter(sig.parameters))[0] == 'self')
38
+ posargs.insert(0, SelfMarker)
39
+ ba = sig.bind(*posargs, **kwargs)
40
+ ba.apply_defaults()
41
+ args = ba.arguments
42
+ required_args = [n for n,v in sig.parameters.items()
43
+ if (v.default is Parameter.empty and
44
+ v.kind not in (Parameter.VAR_POSITIONAL, Parameter.VAR_KEYWORD))]
45
+ assert args['self'] == SelfMarker
46
+ assert required_args[0] == 'self'
47
+ del required_args[0], args['self']
48
+ required_args = [args[n] for n in required_args]
49
+
50
+ return required_args, args