]> granicus.if.org Git - python/commitdiff
pdb: modernize find_function() and add tests for it.
authorGeorg Brandl <georg@python.org>
Sun, 13 Oct 2013 18:51:47 +0000 (20:51 +0200)
committerGeorg Brandl <georg@python.org>
Sun, 13 Oct 2013 18:51:47 +0000 (20:51 +0200)
Closes #18714.

Lib/pdb.py
Lib/test/test_pdb.py
Misc/NEWS

index 1ec83daf439a901deba178bbcf42da66475e040f..143b9252e5bcef3e3cd6ce92597f86303d9f551f 100755 (executable)
@@ -95,18 +95,11 @@ def find_function(funcname, filename):
     except OSError:
         return None
     # consumer of this info expects the first line to be 1
-    lineno = 1
-    answer = None
-    while True:
-        line = fp.readline()
-        if line == '':
-            break
-        if cre.match(line):
-            answer = funcname, filename, lineno
-            break
-        lineno += 1
-    fp.close()
-    return answer
+    with fp:
+        for lineno, line in enumerate(fp, start=1):
+            if cre.match(line):
+                return funcname, filename, lineno
+    return None
 
 def getsourcelines(obj):
     lines, lineno = inspect.findsource(obj)
index e17f933d80e5f0a91af725bef91fd2c8b3f89f92..7993d02ba1e8e37529674375471e0613f9697925 100644 (file)
@@ -620,6 +620,36 @@ class PdbTestCase(unittest.TestCase):
         stderr = stderr and bytes.decode(stderr)
         return stdout, stderr
 
+    def _assert_find_function(self, file_content, func_name, expected):
+        file_content = textwrap.dedent(file_content)
+
+        with open(support.TESTFN, 'w') as f:
+            f.write(file_content)
+
+        expected = None if not expected else (
+            expected[0], support.TESTFN, expected[1])
+        self.assertEqual(
+            expected, pdb.find_function(func_name, support.TESTFN))
+
+    def test_find_function_empty_file(self):
+        self._assert_find_function('', 'foo', None)
+
+    def test_find_function_found(self):
+        self._assert_find_function(
+            """\
+            def foo():
+                pass
+
+            def bar():
+                pass
+
+            def quux():
+                pass
+            """,
+            'bar',
+            ('bar', 4),
+        )
+
     def test_issue7964(self):
         # open the file as binary so we can force \r\n newline
         with open(support.TESTFN, 'wb') as f:
index 3ff145f6a92ff5346c1e04b594af16427ba1da3b..f185b17db4fde0c5bd22105b01c9f1c6484d82de 100644 (file)
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -114,6 +114,8 @@ Tests
 - Issue #18919: Unified and extended tests for audio modules: aifc, sunau and
   wave.
 
+- Issue #18714: Added tests for ``pdb.find_function()``.
+
 Documentation
 -------------