Skip to content

Commit fd7bfa3

Browse files
committed
Put imports on the last line unless there are other exprs
1 parent 3427d27 commit fd7bfa3

File tree

2 files changed

+14
-2
lines changed

2 files changed

+14
-2
lines changed

_pytest/assertion/rewrite.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -600,20 +600,21 @@ def run(self, mod):
600600
if doc is not None and self.is_rewrite_disabled(doc):
601601
return
602602
pos = 0
603-
lineno = 0
603+
lineno = 1
604604
for item in mod.body:
605605
if (expect_docstring and isinstance(item, ast.Expr) and
606606
isinstance(item.value, ast.Str)):
607607
doc = item.value.s
608608
if self.is_rewrite_disabled(doc):
609609
return
610-
lineno += len(doc) - 1
611610
expect_docstring = False
612611
elif (not isinstance(item, ast.ImportFrom) or item.level > 0 or
613612
item.module != "__future__"):
614613
lineno = item.lineno
615614
break
616615
pos += 1
616+
else:
617+
lineno = item.lineno
617618
imports = [ast.Import([alias], lineno=lineno, col_offset=0)
618619
for alias in aliases]
619620
mod.body[pos:pos] = imports

testing/test_assertrewrite.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,17 @@ def test_place_initial_imports(self):
8282
assert imp.lineno == 2
8383
assert imp.col_offset == 0
8484
assert isinstance(m.body[3], ast.Expr)
85+
s = """'doc string'\nfrom __future__ import with_statement"""
86+
m = rewrite(s)
87+
if sys.version_info < (3, 7):
88+
assert isinstance(m.body[0], ast.Expr)
89+
assert isinstance(m.body[0].value, ast.Str)
90+
del m.body[0]
91+
assert isinstance(m.body[0], ast.ImportFrom)
92+
for imp in m.body[1:3]:
93+
assert isinstance(imp, ast.Import)
94+
assert imp.lineno == 2
95+
assert imp.col_offset == 0
8596
s = """'doc string'\nfrom __future__ import with_statement\nother"""
8697
m = rewrite(s)
8798
if sys.version_info < (3, 7):

0 commit comments

Comments
 (0)