Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions src/_pytest/pytester.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

import codecs
import gc
import inspect
import os
import platform
import re
Expand Down Expand Up @@ -584,6 +585,19 @@ def makepyfile(self, *args, **kwargs):
"""Shortcut for .makefile() with a .py extension."""
return self._makefile(".py", args, kwargs)

def makepyfilefunc(self, func, *args, **kwargs):
"""Make Python file from function"""
source = inspect.getsourcelines(func)[0][1:]
# Calculate whitespace from function and remove it.
pad = 0
for c in source[0]:
if c == ' ':
pad += 1
else:
break
unpadded_source = ''.join([line[pad:] for line in source])
return self.makepyfile(unpadded_source)

def maketxtfile(self, *args, **kwargs):
"""Shortcut for .makefile() with a .txt extension."""
return self._makefile(".txt", args, kwargs)
Expand Down
11 changes: 11 additions & 0 deletions testing/test_pytester.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,17 @@ def setup_function(function):
assert u"mixed_encoding = u'São Paulo'".encode("utf-8") in p.read("rb")


def test_makepyfilefunc(testdir):
"""Test makepyfilefunc against an inline function declaration"""
def tests():
def test_foo():
assert True

test_mod = testdir.makepyfilefunc(tests)
result = testdir.inline_run(str(test_mod))
assert result.ret == EXIT_OK


class TestInlineRunModulesCleanup(object):
def test_inline_run_test_module_not_cleaned_up(self, testdir):
test_mod = testdir.makepyfile("def test_foo(): assert True")
Expand Down