pytest에서 콘솔에 인쇄하는 방법
Development와 TDD(Test-Driven Development)를 함께 pytest
pytest
않다print
합니다.print
.
하고 .pytest my_tests.py
실행할 수 있습니다.
documentation
디폴트로는 동작한다고 하는 것 같습니다.http://pytest.org/latest/capture.html
단,
import myapplication as tum
class TestBlogger:
@classmethod
def setup_class(self):
self.user = "alice"
self.b = tum.Blogger(self.user)
print "This should be printed, but it won't be!"
def test_inherit(self):
assert issubclass(tum.Blogger, tum.Site)
links = self.b.get_links(posts)
print len(links) # This won't print either.
표준 출력 콘솔에는 아무것도 인쇄되지 않습니다(정상적인 진행 상황과 합격/실패한 테스트 수).
테스트 중인 스크립트에는 다음과 같은 인쇄가 포함되어 있습니다.
class Blogger(Site):
get_links(self, posts):
print len(posts) # It won't get printed in the test.
»unittest
듈,, 모모모모 모로로로인인인 을 사용법저는 만, 용, 사, 사를 쓰고 싶어요.pytest
른른른른른른른
인쇄 명세서를 어떻게 보여주는지 아는 사람 있나요?
" " " 입니다.py.test
는 표준 출력 결과를 캡처하여 출력 방법을 제어할 수 있도록 합니다.이렇게 하지 않으면 어떤 테스트에서 해당 텍스트를 출력했는지 알 수 없는 많은 텍스트가 출력됩니다.
그러나 테스트가 실패하면 결과 보고서에 해당 테스트에서 표준으로 출력된 내용을 보여주는 섹션이 포함됩니다.
예를들면,
def test_good():
for i in range(1000):
print(i)
def test_bad():
print('this should fail!')
assert False
결과는 다음과 같습니다.
>>> py.test tmp.py
============================= test session starts ==============================
platform darwin -- Python 2.7.6 -- py-1.4.20 -- pytest-2.5.2
plugins: cache, cov, pep8, xdist
collected 2 items
tmp.py .F
=================================== FAILURES ===================================
___________________________________ test_bad ___________________________________
def test_bad():
print('this should fail!')
> assert False
E assert False
tmp.py:7: AssertionError
------------------------------- Captured stdout --------------------------------
this should fail!
====================== 1 failed, 1 passed in 0.04 seconds ======================
해 주세요.Captured stdout
★★★★★★ 。
print
되면, 「」, 「이러다」를 수 .-s
을 들다py.test
다만, 이것은 해석하기 어려운 경우가 있습니다.
>>> py.test tmp.py -s
============================= test session starts ==============================
platform darwin -- Python 2.7.6 -- py-1.4.20 -- pytest-2.5.2
plugins: cache, cov, pep8, xdist
collected 2 items
tmp.py 0
1
2
3
... and so on ...
997
998
999
.this should fail!
F
=================================== FAILURES ===================================
___________________________________ test_bad ___________________________________
def test_bad():
print('this should fail!')
> assert False
E assert False
tmp.py:7: AssertionError
====================== 1 failed, 1 passed in 0.02 seconds ======================
단답
하다를 사용하세요.-s
★★★★
pytest -s
상세 답변
문서에서:
테스트 실행 중 stdout 및 stderr로 전송된 모든 출력이 캡처됩니다.테스트 또는 셋업 방법이 실패하면 일반적으로 캡처된 출력이 실패 트레이스백과 함께 표시됩니다.
pytest
에는, 「」이 .--capture=method
method
방식으로,중 가 될 수 .fd
,sys
★★★★★★★★★★★★★★★★★」no
pytest
.-s
이 방법이 지름길이다--capture=no
콘솔에서 인쇄문을 표시할 수 있는 옵션입니다.
pytest --capture=no # show print statements in console
pytest -s # equivalent to previous command
캡처 방법 설정 또는 캡처 비활성화
방법이 .pytest
캡처를 할 수 .
파일 기술자(FD) 수준 캡처(기본값):operating system 파일 기술자1 및 2 에의 기입이 모두 캡쳐 됩니다.
sys 레벨 캡처:Python 파일 sys.stdout 및 sys.stderr에 대한 쓰기만 캡처됩니다.파일 설명자에 대한 쓰기 캡처는 수행되지 않습니다.
pytest -s # disable all capturing
pytest --capture=sys # replace sys.stdout/stderr with in-mem files
pytest --capture=fd # also point filedescriptors 1 and 2 to temp file
「」를 사용합니다.-s
옵션을 선택하면 모든 기능의 출력이 출력됩니다.을 사용하다
특정 출력이 필요한 경우, 말씀하신 문서 페이지에서 몇 가지 권장 사항을 제시합니다.
★★
assert False, "dumb assert to make PyTest print my stuff"
기능 종료 시 테스트 실패로 인한 출력이 표시됩니다.PyTest에 의해 전달된 특별한 오브젝트가 있습니다.이러한 오브젝트는 나중에 검사하기 위해 파일에 출력을 쓸 수 있습니다.
def test_good1(capsys): for i in range(5): print i out, err = capsys.readouterr() open("err.txt", "w").write(err) open("out.txt", "w").write(out)
열 수 요.
out
★★★★★★★★★★★★★★★★★」err
고치거나 새로 작업을 합니다.py.test; cat out.txt
포탄
이것은 꽤 해킹적인 방법이지만, 필요한 것일 수도 있습니다.결국, TDD는 물건을 엉망으로 만들고, 준비가 되면 깨끗하고 조용하게 놔두는 것을 의미합니다. :-)
있는 가장 으로 단일 스테이트먼트를 입니다.sys.stdout
(하거나 를 하게 하지 않고)-s
option) - 그 은 표시되지 않습니다.
- 파라미터 " " " 를 합니다.
capsys
이 은 (이렇게 하다)를 예요.capsys
예를 들어 파라미터 목록으로 이동합니다.
def test_function(existing_parameters, capsys):
- 코드에는 다음 내용을 삽입하기만 하면 됩니다.
with capsys.disabled():
print("this output will not be captured and go straight to sys.stdout")
https://buildmedia.readthedocs.org/media/pdf/pytest/latest/pytest.pdf (2.11 Stdout/stderr 출력을 캡처하는 방법)을 참조해 주세요.
에 대한 PyTest
말 그대로 모든 걸 잠잠하게 했어요
신호를 보내는 테스트에 실패하기 싫어서 다음과 같이 해킹을 했습니다.
def test_2_YellAboutBrokenAndMutedTests():
import atexit
def report():
print C_patch.tidy_text("""
In silent mode PyTest breaks low level stream structure I work with, so
I cannot test if my functionality work fine. I skipped corresponding tests.
Run `py.test -s` to make sure everything is tested.""")
if sys.stdout != sys.__stdout__:
atexit.register(report)
atexit
module을 사용하면 다음 시간 이후에 인쇄가 가능합니다. PyTest
에 의해 출력 스트림이 해방되었습니다.을 사용하다
============================= test session starts ==============================
platform linux2 -- Python 2.7.3, pytest-2.9.2, py-1.4.31, pluggy-0.3.1
rootdir: /media/Storage/henaro/smyth/Alchemist2-git/sources/C_patch, inifile:
collected 15 items
test_C_patch.py .....ssss....s.
===================== 10 passed, 5 skipped in 0.15 seconds =====================
In silent mode PyTest breaks low level stream structure I work with, so
I cannot test if my functionality work fine. I skipped corresponding tests.
Run `py.test -s` to make sure everything is tested.
~/.../sources/C_patch$
는, 「메시지」는, 「메시지」가 됩니다.PyTest
자동 모드이며, 로 작업을 실행하면 인쇄되지 않습니다.py.test -s
모든 것이 이미 잘 테스트되어 있습니다.
검사 자료에 따르면pytest --capture=sys
작동해야 합니다.테스트 내부에서 표준을 캡처하려면 Capsys 고정 장치를 참조하십시오.
는 원래 ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★PyTest
VSCode 콘솔에서 유닛 테스트를 실행/디버깅하면서 인쇄합니다. 할 수 .launch.json
★★★★★★★★★★..venv
가상 환경 폴더.
"version": "0.2.0",
"configurations": [
{
"name": "PyTest",
"type": "python",
"request": "launch",
"stopOnEntry": false,
"pythonPath": "${config:python.pythonPath}",
"module": "pytest",
"args": [
"-sv"
],
"cwd": "${workspaceRoot}",
"env": {},
"envFile": "${workspaceRoot}/.venv",
"debugOptions": [
"WaitOnAbnormalExit",
"WaitOnNormalExit",
"RedirectOutput"
]
}
]
}
GUI 를 할 수 .Pycharm GUI 로 합니다.Run > Edit Configurations
하게 하는 하고, 「인쇄 스테이트먼트」를 추가합니다-s
Additional Arguments
syslog.syslog.syslog.
Pycharm 디버거를 주로 사용하여 (GUI를 통해) pytest 기능을 디버깅하는 동안 특정 사용 사례에서 코드 다른 곳에서 무슨 일이 일어나고 있는지 알아야 하고 인쇄 문장이 도움이 되기 때문입니다.
일반적으로 다음 명령을 사용합니다.
pytest -v -rs --html=report.html --self-contained-html test_Suite.py -s
또한 위의 명령어는 모든 인쇄문이 캡처되어 저장되는 report.disc 파일을 생성합니다.그리고 그-s
마지막으로 인쇄문을 단말기에 표시합니다.
이미 많은 좋은 답변이 있지만 실행 시 로그를 얻을 수 없었던 이유를 공유하겠습니다.pytest
.
한 가지 중요한 점은 각 테스트 케이스는test_
함수를 쓸 때 접두사를 사용합니다.않으면 렇렇않 without without without without without without without without without without without without without without without without without without without without without without without without without without without without without without 를 사용할 때 인쇄문이 없습니다.pytest
.
커맨드에 대해서는, 다음의 커맨드를 사용하고, 매우 포괄적인 로그를 취득합니다.
python -m pytest -v -rs <particular_file.py> -s -o log_cli-level=DEBUG
올바른 기능명이 있는지 확인하고 명령어를 사용하면 콘솔로그를 확실하게 표시할 수 있습니다.
pytest.ini를 사용하는 경우 다음 사용을 고려하십시오.
[pytest]
...
addopts = --capture=no
...
이것은, 테스트에 근거하는 IDE 확장으로부터 테스트를 실행하고 있는 경우에 유효하게 동작합니다.ini
언급URL : https://stackoverflow.com/questions/24617397/how-to-print-to-console-in-pytest
'programing' 카테고리의 다른 글
MySQL 대소문자를 구분하는 쿼리 (0) | 2023.01.12 |
---|---|
자동 증가가 mysql에서 생성할 수 있는 가장 큰 ID 번호는 무엇입니까? (0) | 2023.01.12 |
Java 8에서 문자열 목록으로 열거 값 가져오기 (0) | 2023.01.12 |
MariaDB 10에서 대용량 인덱스를 활성화하려면 어떻게 해야 합니까? (0) | 2023.01.12 |
어레이에 개체를 추가하는 방법 (0) | 2023.01.12 |