← Back to team overview

launchpad-reviewers team mailing list archive

[Merge] ~cjwatson/launchpad:eliminate-hardcoded-line-number into launchpad:master

 

Colin Watson has proposed merging ~cjwatson/launchpad:eliminate-hardcoded-line-number into launchpad:master.

Commit message:
Eliminate hardcoded line number in test_stacktrace

Requested reviews:
  Launchpad code reviewers (launchpad-reviewers)

For more details, see:
https://code.launchpad.net/~cjwatson/launchpad/+git/launchpad/+merge/424573

The hardcoded line number in `lp.services.tests.test_stacktrace` that must match the source line number on which it appears has bitten me twice in the past while refactoring, and it's an obstacle to being able to run source code reformatting tools reliably.  Use `ast` to detect that line number dynamically instead.
-- 
Your team Launchpad code reviewers is requested to review the proposed merge of ~cjwatson/launchpad:eliminate-hardcoded-line-number into launchpad:master.
diff --git a/lib/lp/services/tests/test_stacktrace.py b/lib/lp/services/tests/test_stacktrace.py
index aa76758..533718a 100644
--- a/lib/lp/services/tests/test_stacktrace.py
+++ b/lib/lp/services/tests/test_stacktrace.py
@@ -3,6 +3,7 @@
 
 """Test the stacktrace module."""
 
+import ast
 import io
 import sys
 
@@ -13,9 +14,17 @@ from lp.testing import TestCase
 from lp.testing.layers import BaseLayer
 
 
-# This constant must always be equal to the line number on which it lives for
-# the tests to pass.
-MY_LINE_NUMBER = 18
+def find_assignment_line_number(name):
+    """Find the first line number containing an assignment to `name`."""
+    with open(__file__) as f:
+        for node in ast.walk(ast.parse(f.read())):
+            if isinstance(node, ast.Assign):
+                for target in node.targets:
+                    if isinstance(target, ast.Name) and target.id == name:
+                        return target.lineno
+
+
+MY_LINE_NUMBER = find_assignment_line_number("MY_LINE_NUMBER")
 
 MY_FILE_NAME = __file__[:__file__.rindex('.py')] + '.py'