Skip to content

Instantly share code, notes, and snippets.

@genadyp
Last active June 29, 2021 12:27
Show Gist options
  • Save genadyp/9b6113f4b8f5bfe949b7e39516e72973 to your computer and use it in GitHub Desktop.
Save genadyp/9b6113f4b8f5bfe949b7e39516e72973 to your computer and use it in GitHub Desktop.
pytest

How to share global variables between tests?

Option 1

# contents of conftest.py

import pytest


def pytest_addoption(parser):
    parser.addoption("--api_version", action="store", default="v25", help="By default: v25")


@pytest.fixture(scope='session')
def api_url(pytestconfig):
    api_version = pytestconfig.getoption("--api_version").lower()
    if api_version in ['v24', 'v25', 'v26', 'v27']:
        return 'http://www.foobar.com/' + api_version
    else:
        raise ValueError('Unknown api version: ' + api_version)
contents of test_foo.py

import pytest
import requests


@pytest.fixture
def data(api_url):  # probably a good idea to rename your fixture to a api_response or change what fixture returns.
    return requests.get(api_url)


def test_bar(data):
    print(data.text)
    # below you are not testing data, but merely checking that response object is not None
    assert data is not None  # this will always pass

    # you probably want to test status code and response content
    assert data.status_code == 200
    assert data.json()
# Run the tests: 
pytest -vvv --api_version v24 test_foo.py

Option 2

# in conftest.py

api_url_by_option = None

def pytest_addoption(parser):
    parser.addoption("--api_version", action="store", default="v25", help="By default: v25")

@pytest.fixture(autouse=True, scope='session')
def cmd_param(pytestconfig):
    api_version = pytestconfig.getoption("--mobile_api_ver").lower()
    global api_url_by_option
    if api_version in ['v24', 'v25', 'v26', 'v27']:
        api_url_by_option = 'http://www.foobar.com/' + api_version
    else:
        raise ValueError('Unknown api version: ' + api_version)

@pytest.fixture:
def api_url():
    return api_url_by_option
# In test_foo.py you don't need to import api_url. 
# Please notice that the api_url fixture from conftest.py is used in fixture data.

import requests

@pytest.fixture
def data(api_url):
    return requests.request("GET", api_url)

test_bar(data):
    assert data is not None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment