diff --git a/src/_pytest/pytester.py b/src/_pytest/pytester.py index ce1c8ea1ce3..f2d091b5d3c 100644 --- a/src/_pytest/pytester.py +++ b/src/_pytest/pytester.py @@ -3,6 +3,7 @@ import codecs import gc +import inspect import os import platform import re @@ -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) diff --git a/testing/test_pytester.py b/testing/test_pytester.py index 195f2c7f181..ad394a63049 100644 --- a/testing/test_pytester.py +++ b/testing/test_pytester.py @@ -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")