What is PyTest Fixture?

 If you want to execute set of code before or after your test you can use PyTest Fixture. 

The purpose of test fixtures is to provide a fixed baseline upon which tests can reliably and repeatedly execute. pytest fixtures offer dramatic improvements over the classic xUnit style of setup/teardown functions:

  • fixtures have explicit names and are activated by declaring their use from test functions, modules, classes or whole projects.
  • fixtures are implemented in a modular manner, as each fixture name triggers a fixture function which can itself use other fixtures.
  • fixture management scales from simple unit to complex functional testing, allowing to parametrize fixtures and tests according to configuration and component options, or to re-use fixtures across class, module or whole test session scopes.

Example:

from selenium.webdriver import Chrome
import pytest

@pytest.fixture()
def fix_method()
    global driver
    path = ""
    driver = Chrome(executable_path = path)
    driver.get("");
    yield
    driver.close()

def test_1(fix_method):
	...
	...

def test_2(fix_method):
	...
	...

def test_3(fix_method):
	...
	...

In above scenario, code in fix_method will be executed before all 3 Test cases except the one line after yield. Code after yield will execute after every test case. Don't forget you need to include fix_method name as a parameter in all test.

If you want to execute fixture code only once in module, you can specify its scope.

@pytest.fixture(scope="module")
def fix_method()
    global driver