Patchwork [5,of,8] tests: use context manager form of assertRaises

login
register
mail settings
Submitter Gregory Szorc
Date May 13, 2017, 7:54 p.m.
Message ID <20054f6926cca44d7efb.1494705277@ubuntu-vm-main>
Download mbox | patch
Permalink /patch/20609/
State Accepted
Headers show

Comments

Gregory Szorc - May 13, 2017, 7:54 p.m.
# HG changeset patch
# User Gregory Szorc <gregory.szorc@gmail.com>
# Date 1494701564 25200
#      Sat May 13 11:52:44 2017 -0700
# Node ID 20054f6926cca44d7efb13be3122f0f76bfa4e8c
# Parent  e367d7c1b2c46a78056a3093c43d6c9bee8e5bbf
tests: use context manager form of assertRaises

Support for using unittest.TestCase.assertRaises as a context
manager was added in Python 2.7. This form is more readable,
especially for complex tests.

While I was here, I also restored the use of assertRaisesRegexp,
which was removed in c6921568cd20 for Python 2.6 compatibility.

Patch

diff --git a/tests/test-atomictempfile.py b/tests/test-atomictempfile.py
--- a/tests/test-atomictempfile.py
+++ b/tests/test-atomictempfile.py
@@ -47,7 +47,8 @@  class testatomictempfile(unittest.TestCa
     # if a programmer screws up and passes bad args to atomictempfile, they
     # get a plain ordinary TypeError, not infinite recursion
     def testoops(self):
-        self.assertRaises(TypeError, atomictempfile)
+        with self.assertRaises(TypeError):
+            atomictempfile()
 
     # checkambig=True avoids ambiguity of timestamp
     def testcheckambig(self):
diff --git a/tests/test-ctxmanager.py b/tests/test-ctxmanager.py
--- a/tests/test-ctxmanager.py
+++ b/tests/test-ctxmanager.py
@@ -55,23 +55,21 @@  class test_ctxmanager(unittest.TestCase)
     def test_raise_on_enter(self):
         trace = []
         addtrace = trace.append
-        def go():
+        with self.assertRaises(ctxerror):
             with util.ctxmanager(ctxmgr('a', addtrace),
                                  lambda: raise_on_enter('b', addtrace)) as c:
                 c.enter()
                 addtrace('unreachable')
-        self.assertRaises(ctxerror, go)
         self.assertEqual(trace, [('enter', 'a'), ('raise', 'b'), ('exit', 'a')])
 
     def test_raise_on_exit(self):
         trace = []
         addtrace = trace.append
-        def go():
+        with self.assertRaises(ctxerror):
             with util.ctxmanager(ctxmgr('a', addtrace),
                                  lambda: raise_on_exit('b', addtrace)) as c:
                 c.enter()
                 addtrace('running')
-        self.assertRaises(ctxerror, go)
         self.assertEqual(trace, [('enter', 'a'), ('enter', 'b'), 'running',
                                  ('raise', 'b'), ('exit', 'a')])
 
diff --git a/tests/test-lock.py b/tests/test-lock.py
--- a/tests/test-lock.py
+++ b/tests/test-lock.py
@@ -260,12 +260,10 @@  class testlock(unittest.TestCase):
         lock = state.makelock(inheritchecker=check)
         state.assertacquirecalled(True)
 
-        def tryinherit():
+        with self.assertRaises(error.LockInheritanceContractViolation):
             with lock.inherit():
                 pass
 
-        self.assertRaises(error.LockInheritanceContractViolation, tryinherit)
-
         lock.release()
 
     def testfrequentlockunlock(self):
diff --git a/tests/test-manifest.py b/tests/test-manifest.py
--- a/tests/test-manifest.py
+++ b/tests/test-manifest.py
@@ -128,7 +128,8 @@  class basemanifesttests(object):
         self.assertEqual('l', m.flags('bar/baz/qux.py'))
         self.assertEqual(BIN_HASH_1, m['foo'])
         self.assertEqual('', m.flags('foo'))
-        self.assertRaises(KeyError, lambda : m['wat'])
+        with self.assertRaises(KeyError):
+            m['wat']
 
     def testParseManifestV2(self):
         m1 = self.parsemanifest(A_SHORT_MANIFEST)
@@ -213,7 +214,8 @@  class basemanifesttests(object):
         self.assertEqual('', m.flags('alpha'))
         self.assertEqual('l', m.flags('bar/baz/qux.py'))
         self.assertEqual('', m.flags('beta'))
-        self.assertRaises(KeyError, lambda : m['foo'])
+        with self.assertRaises(KeyError):
+            m['foo']
 
     def testSetGetNodeSuffix(self):
         clean = self.parsemanifest(A_SHORT_MANIFEST)
@@ -255,12 +257,14 @@  class basemanifesttests(object):
                 assert False
             return True
         match.matchfn = filt
-        self.assertRaises(AssertionError, m.matches, match)
+        with self.assertRaises(AssertionError):
+            m.matches(match)
 
     def testRemoveItem(self):
         m = self.parsemanifest(A_SHORT_MANIFEST)
         del m['foo']
-        self.assertRaises(KeyError, lambda : m['foo'])
+        with self.assertRaises(KeyError):
+            m['foo']
         self.assertEqual(1, len(m))
         self.assertEqual(1, len(list(m)))
         # now restore and make sure everything works right
diff --git a/tests/test-simplekeyvaluefile.py b/tests/test-simplekeyvaluefile.py
--- a/tests/test-simplekeyvaluefile.py
+++ b/tests/test-simplekeyvaluefile.py
@@ -53,24 +53,24 @@  class testsimplekeyvaluefile(unittest.Te
 
     def testinvalidkeys(self):
         d = {'0key1': 'value1', 'Key2': 'value2'}
-        self.assertRaises(error.ProgrammingError,
-                          scmutil.simplekeyvaluefile(self.vfs, 'kvfile').write,
-                          d)
+        with self.assertRaisesRegexp(error.ProgrammingError,
+                                     'keys must start with a letter.*'):
+            scmutil.simplekeyvaluefile(self.vfs, 'kvfile').write(d)
+
         d = {'key1@': 'value1', 'Key2': 'value2'}
-        self.assertRaises(error.ProgrammingError,
-                          scmutil.simplekeyvaluefile(self.vfs, 'kvfile').write,
-                          d)
+        with self.assertRaisesRegexp(error.ProgrammingError, 'invalid key.*'):
+            scmutil.simplekeyvaluefile(self.vfs, 'kvfile').write(d)
 
     def testinvalidvalues(self):
         d = {'key1': 'value1', 'Key2': 'value2\n'}
-        self.assertRaises(error.ProgrammingError,
-                          scmutil.simplekeyvaluefile(self.vfs, 'kvfile').write,
-                          d)
+        with self.assertRaisesRegexp(error.ProgrammingError,  'invalid val.*'):
+            scmutil.simplekeyvaluefile(self.vfs, 'kvfile').write(d)
 
     def testcorruptedfile(self):
         self.vfs.contents['badfile'] = 'ababagalamaga\n'
-        self.assertRaises(error.CorruptedState,
-                          scmutil.simplekeyvaluefile(self.vfs, 'badfile').read)
+        with self.assertRaisesRegexp(error.CorruptedState,
+                                     'dictionary.*element.*'):
+            scmutil.simplekeyvaluefile(self.vfs, 'badfile').read()
 
     def testfirstline(self):
         dw = {'key1': 'value1'}
diff --git a/tests/test-simplemerge.py b/tests/test-simplemerge.py
--- a/tests/test-simplemerge.py
+++ b/tests/test-simplemerge.py
@@ -326,7 +326,8 @@  bbb
         self.assertEquals(ml, MERGED_RESULT)
 
     def test_binary(self):
-        self.assertRaises(error.Abort, Merge3, ['\x00'], ['a'], ['b'])
+        with self.assertRaises(error.Abort):
+            Merge3(['\x00'], ['a'], ['b'])
 
     def test_dos_text(self):
         base_text = 'a\r\n'