当测试失败时,会有一个输出指示测试的上下文,例如
=================================== FAILURES ===================================
______________________________ Test.test_sum_even ______________________________
numbers = [2, 4, 6]
@staticmethod
def test_sum_even(numbers):
assert sum(numbers) % 2 == 0
> assert False
E assert False
test_preprocessing.py:52: AssertionError
如果我也希望通过测试同样的事情怎么办?这样我可以快速检查传递给测试的参数是否正确?
我尝试过命令行选项行--full-trace
,-l
,--tb long
和-rpP
,但都没有。
有什么想法吗?
答案 0 :(得分:2)
使用 '''
encrypt pdf files
'''
import PyPDF2 as p
import os
from tkinter import *
from tkinter import ttk
from tkinter.filedialog import askopenfilename, askdirectory
from tkinter.messagebox import showerror
class MainWindow(Frame):
def __init__(self):
Frame.__init__(self)
self.choice = 'Choose a file or a folder'
self.processing = 'Encrypting file(s)'
self.master.title('Viktor PDF titkositoja :)')
self.master.rowconfigure(5, weight=1)
self.master.columnconfigure(5, weight=1)
self.grid(sticky=W+E+N+S)
self.button = Button(self, text='File', command=self.enc_file, width=30)
self.button.grid(row=1, column=0, sticky=W+E, padx=15, pady=6)
self.button = Button(self, text='Folder', command=self.enc_folder, width=30)
self.button.grid(row=1, column=1, sticky=W+E, padx=15, pady=6)
self.labelText = StringVar()
self.label = Label(self, textvariable=self.labelText)
self.labelText.set(self.choice)
self.label.grid(row=2, column=0, columnspan=2, sticky=W+E, padx=3, pady=10)
self.row = 2
self.copy_to = os.path.join('/home', 'zaturek', 'Documents')
def reset_labels(self):
list = self.grid_slaves()
for l in list[:-3]:
l.destroy()
self.labelText.set(self.choice)
def enc_file(self):
self.reset_labels()
fname = askopenfilename(filetypes=(('PDF files', '.pdf'),
('All files', '*.*') ))
if fname:
try:
self.labelText.set(self.processing + '\n' + fname)
self.enc(fname)
except Exception as e:
showerror(title='Error', message=e)
def enc_folder(self):
self.reset_labels()
dname = askdirectory()
if dname:
# self.labelText.set('Fajlok titkositasa a mappaban: ' + '\n' + dname)
for f in os.listdir():
if os.path.isfile(f) and '.pdf' in f:
try:
self.labelText.set(self.processing + '\n' + f)
self.enc(f)
except Exception as e:
showerror(title='error', message=e)
print(f)
def enc(self, f):
#self.label.config(text='Fajl(ok) titkositasa folyamatban' + '\n' + f)
read_pdf = p.PdfFileReader(f)
write_pdf = p.PdfFileWriter()
if read_pdf.isEncrypted == False:
try:
for i in range(0, read_pdf.getNumPages()):
write_pdf.addPage(read_pdf.getPage(i))
write_pdf.encrypt('1234')
with open(self.new_fname(f), 'wb') as out:
write_pdf.write(out)
#print('itt')
self.nlabel2 = Label(self, text=f + ' - kesz.')
self.nlabel2.grid(row=self.row+1, column=0, columnspan=2, sticky=W+E)
self.row += 1
except Exception as e:
m = 'Valami nem stimmelt. Ellenorizd es probald ujra. Ha akkor sem megy, hivj fel!'
showerror(title='error', message=f + '\n' + e)
print(e)
else:
self.nlabel3 = Label(self, text=f + ' - mar kodolva volt.')
self.nlabel3.grid(row=self.row+1, column=0, columnspan=2, sticky=W+E)
self.row += 1
def new_fname(self, f):
t = os.path.split(f)[1].split('.')
#print(t[0])
t[0] = t[0] + '_e'
nf = str.join('.', (t[0], t[1]))
#print(os.path.join(self.copy_to, nf))
return os.path.join(self.copy_to, nf)
if __name__ == '__main__':
MainWindow().mainloop()
标志执行pytest将导致它在执行时列出每个测试的完全限定名称,例如:
--verbose
答案 1 :(得分:1)
如果您只是要求传递测试用例的标准输出,那么您需要将-s
选项传递给pytest
以防止捕获标准输出。有关标准输出抑制的更多信息,请参见pytest docs。
答案 2 :(得分:0)
pytest
没有此功能。它的工作是向您显示断言失败时来自异常的错误。
一种解决方法是使用python的logging模块,然后使用pytest
中的caplog装置,明确包含要通过测试的信息。
例如func.py
的一个版本可能是:
import logging
logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger('my-even-logger')
def is_even(numbers):
res = sum(numbers) % 2 == 0
if res is True:
log.warning('Sum is Even')
else:
log.warning('Sum is Odd')
#... do stuff ...
,然后是test_func.py
:
import pytest
from func import is_even
@pytest.fixture
def my_list():
numbers = [2, 4, 6]
return numbers
def test_is_even(caplog, my_list):
with caplog.at_level(logging.DEBUG, logger='my-even-logger'):
is_even(my_list)
assert 'Even' in caplog.text
如果您运行pytest -s test_even.py
并且由于测试通过,则记录器将向您显示以下消息:
test_even.py WARNING:my-sum-logger:Sum is Even