· 7 years ago · Aug 23, 2018, 11:44 PM
1import pytest
2import os
3
4def test_func1():
5 assert True
6
7
8def test_func2():
9 assert 0 == 1
10
11if __name__ == '__main__':
12
13 pytest.main(args=['-sv', os.path.abspath(__file__)])
14
15test-mbp:hi_world ua$ python test_out.py
16================================================= test session starts =================================================
17platform darwin -- Python 2.7.6 -- py-1.4.28 -- pytest-2.7.1 -- /usr/bin/python
18rootdir: /Users/tester/PycharmProjects/hi_world, inifile:
19plugins: capturelog
20collected 2 items
21
22test_out.py::test_func1 PASSED
23test_out.py::test_func2 FAILED
24
25====================================================== FAILURES =======================================================
26_____________________________________________________ test_func2 ______________________________________________________
27
28 def test_func2():
29> assert 0 == 1
30E assert 0 == 1
31
32test_out.py:9: AssertionError
33========================================= 1 failed, 1 passed in 0.01 seconds ==========================================
34test-mbp:hi_world ua$
35
36python test_out.py >myoutput.log
37
38python test_out.py | tee myoutput.log
39
40#!/usr/bin/env python
41# -*- coding: utf-8 -*-
42
43"""
44Pytest Plugin that save failure or test session information to a file pass as a command line argument to pytest.
45
46It put in a file exactly what pytest return to the stdout.
47
48To use it :
49Put this file in the root of tests/ edit your conftest and insert in the top of the file :
50
51 pytest_plugins = 'pytest_session_to_file'
52
53Then you can launch your test with the new option --session_to_file= like this :
54
55 py.test --session_to_file=FILENAME
56Or :
57 py.test -p pytest_session_to_file --session_to_file=FILENAME
58
59
60Inspire by _pytest.pastebin
61Ref: https://github.com/pytest-dev/pytest/blob/master/_pytest/pastebin.py
62
63Version : 0.1
64Date : 30 sept. 2015 11:25
65Copyright (C) 2015 Richard Vézina <ml.richard.vezinar @ gmail.com>
66Licence : Public Domain
67"""
68
69import pytest
70import sys
71import tempfile
72
73
74def pytest_addoption(parser):
75 group = parser.getgroup("terminal reporting")
76 group._addoption('--session_to_file', action='store', metavar='path', default='pytest_session.txt',
77 help="Save to file the pytest session information")
78
79
80@pytest.hookimpl(trylast=True)
81def pytest_configure(config):
82 tr = config.pluginmanager.getplugin('terminalreporter')
83 # if no terminal reporter plugin is present, nothing we can do here;
84 # this can happen when this function executes in a slave node
85 # when using pytest-xdist, for example
86 if tr is not None:
87 config._pytestsessionfile = tempfile.TemporaryFile('w+')
88 oldwrite = tr._tw.write
89
90 def tee_write(s, **kwargs):
91 oldwrite(s, **kwargs)
92 config._pytestsessionfile.write(str(s))
93 tr._tw.write = tee_write
94
95
96def pytest_unconfigure(config):
97 if hasattr(config, '_pytestsessionfile'):
98 # get terminal contents and delete file
99 config._pytestsessionfile.seek(0)
100 sessionlog = config._pytestsessionfile.read()
101 config._pytestsessionfile.close()
102 del config._pytestsessionfile
103 # undo our patching in the terminal reporter
104 tr = config.pluginmanager.getplugin('terminalreporter')
105 del tr._tw.__dict__['write']
106 # write summary
107 create_new_file(config=config, contents=sessionlog)
108
109
110def create_new_file(config, contents):
111 """
112 Creates a new file with pytest session contents.
113 :contents: paste contents
114 :returns: url to the pasted contents
115 """
116 # import _pytest.config
117 # path = _pytest.config.option.session_to_file
118 # path = 'pytest_session.txt'
119 path = config.option.session_to_file
120 with open(path, 'w') as f:
121 f.writelines(contents)
122
123
124def pytest_terminal_summary(terminalreporter):
125 import _pytest.config
126 tr = terminalreporter
127 if 'failed' in tr.stats:
128 for rep in terminalreporter.stats.get('failed'):
129 try:
130 msg = rep.longrepr.reprtraceback.reprentries[-1].reprfileloc
131 except AttributeError:
132 msg = tr._getfailureheadline(rep)
133 tw = _pytest.config.create_terminal_writer(terminalreporter.config, stringio=True)
134 rep.toterminal(tw)
135 s = tw.stringio.getvalue()
136 assert len(s)
137 create_new_file(config=_pytest.config, contents=s)
138
139from _pytest.cacheprovider import Cache
140from collections import defaultdict
141
142import _pytest.cacheprovider
143import pytest
144
145@pytest.hookimpl(tryfirst=True)
146def pytest_configure(config):
147 config.cache = Cache(config)
148 config.cache.set('record_s', defaultdict(list))
149
150@pytest.fixture(autouse=True)
151def record(request):
152 cache = request.config.cache
153 record_s = cache.get('record_s', {})
154 testname = request.node.name
155 # Tried to avoid the initialization, but it throws errors.
156 record_s[testname] = []
157 yield record_s[testname]
158 cache.set('record_s', record_s)
159
160@pytest.hookimpl(trylast=True)
161def pytest_unconfigure(config):
162 print("====================================================================n")
163 print("ttTerminal Test Report Summary: n")
164 print("====================================================================n")
165 r_cache = config.cache.get('record_s',{})
166 print str(r_cache)
167
168def test_foo(record):
169 record.append(('PASS', "reason", { "some": "other_stuff" }))
170
171====================================================================
172
173 Terminal Test Report Summary:
174
175====================================================================
176
177{u'test_foo': [[u'PASS',u'reason', { u'some': u'other_stuff' } ]]}