Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Run tests truly programmatically #2544

Closed
santiagobasulto opened this issue Jul 3, 2017 · 2 comments
Closed

Run tests truly programmatically #2544

santiagobasulto opened this issue Jul 3, 2017 · 2 comments
Labels
type: question general question, might be closed after 2 weeks of inactivity

Comments

@santiagobasulto
Copy link

santiagobasulto commented Jul 3, 2017

Hey guys! I'm trying to execute pytest tests truly programmatically and get results from the very same python code. I see in the documentation how to "invoke pytest from Python code", but that's just executing the regular pytest command from a python interface (generating output and all that).

I'd like to invoke the underlying test runner with an arbitrary piece of code and get some sort of programmatic result. Something like:

with open('test_file.py', 'r') as fp:
    results = pytest.run_code(fp.read())
results.failed  # True/False
results.failed_tests # [TestResult, TestResult]

This is what I can do with nose for example:

suite = unittest.TestLoader().discover(abs_path)
program = TestProgram(suite=suite, exit=False, argv=sys.argv[0:1])

It's not ideal, but it's something.

@nicoddemus
Copy link
Member

nicoddemus commented Jul 3, 2017

Hi @santiagobasulto,

pytest needs to startup a lot of stuff (plugins are just one example), so your best bet would be to actually follow what's suggested in the link you posted.

To obtain the programmatic result, you can implement a custom plugin with the appropriate hooks that interest you, for example (untested):

class Plugin:
    def __init__(self):
        self.passed_tests = set()
    def pytest_runtest_logreport(self, report):
        if report.passed:
            self.passed_tests.add(report.nodeid)

plugin = Plugin()
pytest.main(['test_file.py', '-p', 'no:terminal'], plugins=[plugin])
# now plugin.passed_tests contain the list of tests that passed during the session

Here I also disabled the terminal so pytest won't write to your stdout/stderr. It might not be ideal, but I'm sure you can extract any information you need from it.

@RonnyPfannschmidt RonnyPfannschmidt added the type: question general question, might be closed after 2 weeks of inactivity label Jul 4, 2017
@santiagobasulto
Copy link
Author

Thanks very much @nicoddemus. I'll close the issue to remove noise, but I'll comment as I make progress.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
type: question general question, might be closed after 2 weeks of inactivity
Projects
None yet
Development

No branches or pull requests

3 participants