2015-08-03 6 views
5

Ich habe Probleme beim Versuch, alle Ergebnisse, die von pytest angezeigt werden, in einer Datei zu speichern (txt, log, egal). Im Test Beispiel unten, würde ich erfassen möchte, was in der Konsole in einen Text/Log-Datei von einer Art angezeigt:Wie pytests Ergebnisse/Protokolle in einer Datei speichern?

import pytest 
import os 

def test_func1(): 
    assert True 


def test_func2(): 
    assert 0 == 1 

if __name__ == '__main__': 

    pytest.main(args=['-sv', os.path.abspath(__file__)]) 

Console Ausgang würde ich gerne in eine Textdatei speichern:

test-mbp:hi_world ua$ python test_out.py 
================================================= test session starts ================================================= 
platform darwin -- Python 2.7.6 -- py-1.4.28 -- pytest-2.7.1 -- /usr/bin/python 
rootdir: /Users/tester/PycharmProjects/hi_world, inifile: 
plugins: capturelog 
collected 2 items 

test_out.py::test_func1 PASSED 
test_out.py::test_func2 FAILED 

====================================================== FAILURES ======================================================= 
_____________________________________________________ test_func2 ______________________________________________________ 

    def test_func2(): 
>  assert 0 == 1 
E  assert 0 == 1 

test_out.py:9: AssertionError 
========================================= 1 failed, 1 passed in 0.01 seconds ========================================== 
test-mbp:hi_world ua$ 

Antwort

8

Es scheint, dass alle Ihren Testausgang werden stdout, so müssen Sie einfach auf Ihrem python-Aufruf der Ausgabe dort „umleiten“:

python test_out.py >myoutput.log 

Y Sie können die Ausgabe auch an mehrere Orte "abstufen". Z. B. könnten Sie sich in der Datei anmelden und die Ausgabe auf Ihrer Konsole sehen. Das obige Beispiel wird dann:

python test_out.py | tee myoutput.log 
+0

Letzter Befehl nicht unter Windows funktioniert. –

0

Die pastebin interne Plugin tut genau das, sondern sendet die Ausgabe direkt an bpaste.net. Sie können sich die Plugin-Implementierung ansehen, um zu verstehen, wie Sie sie für Ihre Bedürfnisse wiederverwenden können.

0

leite ich dies aus pastebin wie von Bruno Oliveira vorschlagen:

#!/usr/bin/env python 
# -*- coding: utf-8 -*- 

""" 
Pytest Plugin that save failure or test session information to a file pass as a command line argument to pytest. 

It put in a file exactly what pytest return to the stdout. 

To use it : 
Put this file in the root of tests/ edit your conftest and insert in the top of the file : 

    pytest_plugins = 'pytest_session_to_file' 

Then you can launch your test with the new option --session_to_file= like this : 

    py.test --session_to_file=FILENAME 
Or : 
    py.test -p pytest_session_to_file --session_to_file=FILENAME 


Inspire by _pytest.pastebin 
Ref: https://github.com/pytest-dev/pytest/blob/master/_pytest/pastebin.py 

Version : 0.1 
Date : 30 sept. 2015 11:25 
Copyright (C) 2015 Richard Vézina <ml.richard.vezinar @ gmail.com> 
Licence : Public Domain 
""" 

import pytest 
import sys 
import tempfile 


def pytest_addoption(parser): 
    group = parser.getgroup("terminal reporting") 
    group._addoption('--session_to_file', action='store', metavar='path', default='pytest_session.txt', 
        help="Save to file the pytest session information") 


@pytest.hookimpl(trylast=True) 
def pytest_configure(config): 
    tr = config.pluginmanager.getplugin('terminalreporter') 
    # if no terminal reporter plugin is present, nothing we can do here; 
    # this can happen when this function executes in a slave node 
    # when using pytest-xdist, for example 
    if tr is not None: 
     config._pytestsessionfile = tempfile.TemporaryFile('w+') 
     oldwrite = tr._tw.write 

     def tee_write(s, **kwargs): 
      oldwrite(s, **kwargs) 
      config._pytestsessionfile.write(str(s)) 
     tr._tw.write = tee_write 


def pytest_unconfigure(config): 
    if hasattr(config, '_pytestsessionfile'): 
     # get terminal contents and delete file 
     config._pytestsessionfile.seek(0) 
     sessionlog = config._pytestsessionfile.read() 
     config._pytestsessionfile.close() 
     del config._pytestsessionfile 
     # undo our patching in the terminal reporter 
     tr = config.pluginmanager.getplugin('terminalreporter') 
     del tr._tw.__dict__['write'] 
     # write summary 
     create_new_file(config=config, contents=sessionlog) 


def create_new_file(config, contents): 
    """ 
    Creates a new file with pytest session contents. 
    :contents: paste contents 
    :returns: url to the pasted contents 
    """ 
    # import _pytest.config 
    # path = _pytest.config.option.session_to_file 
    # path = 'pytest_session.txt' 
    path = config.option.session_to_file 
    with open(path, 'w') as f: 
     f.writelines(contents) 


def pytest_terminal_summary(terminalreporter): 
    import _pytest.config 
    tr = terminalreporter 
    if 'failed' in tr.stats: 
     for rep in terminalreporter.stats.get('failed'): 
      try: 
       msg = rep.longrepr.reprtraceback.reprentries[-1].reprfileloc 
      except AttributeError: 
       msg = tr._getfailureheadline(rep) 
      tw = _pytest.config.create_terminal_writer(terminalreporter.config, stringio=True) 
      rep.toterminal(tw) 
      s = tw.stringio.getvalue() 
      assert len(s) 
      create_new_file(config=_pytest.config, contents=s) 
+0

Eigentlich war ich dabei, dieses pytest-Plugin zu paketieren und fand schließlich die Liste der Plugins von Drittanbietern (https://pytest.org/latest/plugins_index/index.html) und ich bin mir nicht sicher, was ich getan habe nicht das selbe von pytest-capturelog oder pytest-catchlog, die Ausgabe des Plugins ist sicherlich nicht die selbe, obwohl es die gleichen Informationen liefern könnte. Wenn jemand, der diese Plugins kennt, bestätigen kann ... Wenn ja, kann ich besser nur die Fähigkeit hinzufügen, die gleiche Ausgabe von diesen Plugins zu erhalten, dann die obige ... – Richard

+0

Hier das Pypi-Paket: https: //pypi.python. org/pypi/pytest-session_to_file/0.1.0 – Richard

+0

Endlich ein funktionierendes Pypi-Paket hier: https://pypi.python.org/pypi/pytest-session2file/0.1.5 – Richard

Verwandte Themen