pytest-dev / unittest2pytest

helps rewriting Python `unittest` test-cases into `pytest` test-cases
GNU General Public License v3.0
128 stars 27 forks source link

Fixed bug converting asserts that use a regex. #24

Closed boralyl closed 6 years ago

boralyl commented 6 years ago

Also changed the conversion to pass a kwarg to match instead of capturing the exception with the context manager and doing a re.search against it for asserting the exception message.

Fixes #23

unittest2pytest -f self_assert test.py
RefactoringTool: Refactored test.py
--- test.py (original)
+++ test.py (refactored)
@@ -1,17 +1,18 @@
 import warnings
 from unittest import TestCase
+import pytest

 class FooTestCase(TestCase):

     def test_raisesregexp(self):
-        with self.assertRaisesRegexp(ValueError, 'Foo'):
+        with pytest.raises(ValueError, match='Foo'):
             raise ValueError('Foo')

     def test_raisesregex(self):
-        with self.assertRaisesRegex(ValueError, 'Bar'):
+        with pytest.raises(ValueError, match='Bar'):
             raise ValueError('Bar')

     def test_warnsregex(self):
-        with self.assertWarnsRegex(DeprecationWarning, 'Foobar'):
+        with pytest.warns(DeprecationWarning, match='Foobar'):
             warnings.warn('Foobar yada yada', DeprecationWarning)
RefactoringTool: Files that need to be modified:
RefactoringTool: test.py
boralyl commented 6 years ago

I realized after posting this that this will require a minimum version of pytest that supports the match kwarg. This also doesn't handle any existing test that uses that stores the context manager as a variable, e.g.

with self.assertRaisesRegexp(ValueError, 'foo') as cm:
   raise ValueError('foo')

However, this appears broken at the moment based on #18

nicoddemus commented 6 years ago

Thanks @boralyl, let's wait to hear from @htgoebel about the min pytest version issue.

htgoebel commented 6 years ago

IMO it is no issue to require a minimum version of pytest. I some project is about to convert old test-code to pytest, then it either is not yet using pytest at all (thus any version of pytest is okay), or wants to improve its test-suite (which, well, then meanss using a newer version of pytest).

We only need to take care to have the minimum version installed in our test-suite :-)

Regarding the merge, I suggest to use a squash-merge.

nicoddemus commented 6 years ago

The test suite installs the latest pytest given the requirement pytest >=2.7.2, so I guess we are OK here. 👍

Want to do the honors of merging @htgoebel? 😁