ycliper

Популярное

Музыка Кино и Анимация Автомобили Животные Спорт Путешествия Игры Юмор

Интересные видео

2025 Сериалы Трейлеры Новости Как сделать Видеоуроки Diy своими руками

Топ запросов

смотреть а4 schoolboy runaway турецкий сериал смотреть мультфильмы эдисон
Скачать

PYTEST CHEAT SHEET | PART 3 | QA SDET

Автор: Viplove QA - SDET

Загружено: 2025-05-14

Просмотров: 316

Описание: Basic Test Structure

Pytest test functions must start with test_.

To run all tests: pytest

Run a specific file: pytest test_login.py

Run a specific test by keyword: pytest -k "test_login"

Use -v for verbose, -s to show print statements, and -x to stop at first failure.

Use --maxfail=2 to stop after 2 failures.



---

🧪 Assertions

Pytest uses plain assert for validations: assert a == b, assert "text" in str.

For exception handling, use:

with pytest.raises(ZeroDivisionError):
1 / 0



---

🔁 Parametrization

Run one test with multiple inputs using @pytest.mark.parametrize:

@pytest.mark.parametrize("x, y", [(1, 2), (3, 4)])
def test_add(x, y):
assert x y



---

🧩 Fixtures

Fixtures are reusable setup/teardown logic:

@pytest.fixture
def setup_data():
return "some data"

Use yield in fixtures to define teardown steps:

@pytest.fixture
def browser():
driver = webdriver.Chrome()
yield driver
driver.quit()

Fixture scopes: function (default), class, module, session

Set autouse=True to run a fixture for every test automatically.



---

🚫 Skipping & xfail

To skip a test:

@pytest.mark.skip(reason="Not implemented yet")

Conditionally skip:

@pytest.mark.skipif(sys.platform == "win32", reason="Skip on Windows")

Expected failure (does not fail build):

@pytest.mark.xfail(reason="Known issue")



---

🧷 Test Organization

Test discovery looks for files named test_*.py or *_test.py.

Functions must begin with test_.

You can also use setup_module(), setup_class(), and setup_function() for old-style setup, but fixtures are recommended.



---

🛠️ Command Line Tools

Run only failed tests: pytest --lf

Rerun failed tests: pytest --reruns 3 (requires pytest-rerunfailures)

Generate HTML reports: pytest --html=report.html (requires pytest-html)

Use --tb=short for a shorter traceback display.



---

🧪 Selenium with Pytest

Create a WebDriver fixture in conftest.py:

@pytest.fixture
def browser():
driver = webdriver.Chrome()
driver.maximize_window()
yield driver
driver.quit()

Use WebDriverWait and expected_conditions for stable waits:

WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "username")))

For headless testing:

options = Options()
options.add_argument("--headless")



---

🌐 API Testing with Requests

Install: pip install requests

Example GET request:

import requests
def test_api():
res = requests.get("https://reqres.in/api/users/2")
assert res.status_code == 200

Use @pytest.mark.parametrize to test multiple inputs:

@pytest.mark.parametrize("user_id", [1, 2, 3])
def test_user_api(user_id):
response = requests.get(f"https://reqres.in/api/users/{user_id}")
assert response.status_code == 200



---

🏷️ Markers

Use markers to tag tests:

@pytest.mark.smoke
def test_something():
...

Run specific marker: pytest -m smoke

Register custom markers in pytest.ini:

[pytest]
markers =
smoke: Smoke tests
regression: Regression tests



---

🔌 Useful Plugins

pytest-html: Generate HTML reports.

pytest-xdist: Run tests in parallel (pytest -n 4).

pytest-rerunfailures: Automatically retry failed tests.

Не удается загрузить Youtube-плеер. Проверьте блокировку Youtube в вашей сети.
Повторяем попытку...
PYTEST CHEAT SHEET | PART 3 | QA SDET

Поделиться в:

Доступные форматы для скачивания:

Скачать видео

  • Информация по загрузке:

Скачать аудио

Похожие видео

Трамп объявил о прекращении огня / Конец российского наступления?

Трамп объявил о прекращении огня / Конец российского наступления?

7 Дней в САМЫХ СЕКРЕТНЫХ МЕСТАХ КИТАЯ! Такого мы не ожидали..

7 Дней в САМЫХ СЕКРЕТНЫХ МЕСТАХ КИТАЯ! Такого мы не ожидали..

Ultimate DevOps Mock Interview

Ultimate DevOps Mock Interview

Я Добыл Самое Сильное Оружие в Майнкрафте

Я Добыл Самое Сильное Оружие в Майнкрафте

First Week, First Month, First Year Retention

First Week, First Month, First Year Retention

ФЕЙК! Дуров мстит мне. Алко треш Успенской. Бондарчук. любовь Миронова и Астахова. Шура ищет жену

ФЕЙК! Дуров мстит мне. Алко треш Успенской. Бондарчук. любовь Миронова и Астахова. Шура ищет жену

Я ПРОВЁЛ 3 ДНЯ с ПОПУЛЯРНЫМ FPV ДРОНОМ и ВОТ ЧТО СЛУЧИЛОСЬ!

Я ПРОВЁЛ 3 ДНЯ с ПОПУЛЯРНЫМ FPV ДРОНОМ и ВОТ ЧТО СЛУЧИЛОСЬ!

Азербайджан и Россия — дальше будет хуже | Рейды в Екатеринбурге, задержания в Баку

Азербайджан и Россия — дальше будет хуже | Рейды в Екатеринбурге, задержания в Баку

C++ 26 is Complete!

C++ 26 is Complete!

⚡Путин, введи войска! Азербайджан наносит удар.

⚡Путин, введи войска! Азербайджан наносит удар.

© 2025 ycliper. Все права защищены.



  • Контакты
  • О нас
  • Политика конфиденциальности



Контакты для правообладателей: [email protected]