How to share global variables between tests?

I wouldn't mess with global variables. Just define your fixture to return a value and use that fixture in your tests: Similar to what @milo posted but a lot simpler.

Also you had defined --api_version CLI option but accessing --mobile_api_ver option in your fixture. Additionally your test is just checking that a response object is not None which will never be None, so assert statement will always pass even if response is 404 status, see inline comments.

Here is some code that will work:

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


Note: pytest_namespace is deprecated now

pytest provides a way to use some global variables within the session. These variables can be used by fixtures as well.

These variables are controlled via pytest hooks.

import pytest

def pytest_namespace():
    return {'my_global_variable': 0}

@pytest.fixture
def data():
    pytest.my_global_variable = 100

def test(data):
    print pytest.my_global_variable

According to docs, pytest_namespace has been removed in version 4.0:

One can use pytest_configure to share global variables.

Example:

import pytest

def pytest_configure():
    pytest.my_symbol = MySymbol()

You can currently use the pytest object directly as stated in the Docs but only as a stopgap measure:

import pytest


def pytest_configure():
    pytest.my_symbol = MySymbol()

But beware if using the pytest_namespace version as it's deprecated:

old version using the namespace:

class MySymbol:
    ...


def pytest_namespace():
    return {"my_symbol": MySymbol()}

Tags:

Python

Pytest