openai/openai-python
Publicmirrored from https://github.com/openai/openai-pythonAvailable
tests/conftest.py
51lines · modeblame
98d779fbStainless Bot2 years ago | 1 | from __future__ import annotations |
| 2 | | |
| 3 | import os | |
08b8179aDavid Schnurr2 years ago | 4 | import logging |
98d779fbStainless Bot2 years ago | 5 | from typing import TYPE_CHECKING, Iterator, AsyncIterator |
08b8179aDavid Schnurr2 years ago | 6 | |
| 7 | import pytest | |
44ac1cefStainless Bot1 years ago | 8 | from pytest_asyncio import is_async_test |
08b8179aDavid Schnurr2 years ago | 9 | |
98d779fbStainless Bot2 years ago | 10 | from openai import OpenAI, AsyncOpenAI |
| 11 | | |
| 12 | if TYPE_CHECKING: | |
| 13 | from _pytest.fixtures import FixtureRequest | |
| 14 | | |
08b8179aDavid Schnurr2 years ago | 15 | pytest.register_assert_rewrite("tests.utils") |
| 16 | | |
| 17 | logging.getLogger("openai").setLevel(logging.DEBUG) | |
| 18 | | |
| 19 | | |
44ac1cefStainless Bot1 years ago | 20 | # automatically add `pytest.mark.asyncio()` to all of our async tests |
| 21 | # so we don't have to add that boilerplate everywhere | |
| 22 | def pytest_collection_modifyitems(items: list[pytest.Function]) -> None: | |
| 23 | pytest_asyncio_tests = (item for item in items if is_async_test(item)) | |
| 24 | session_scope_marker = pytest.mark.asyncio(loop_scope="session") | |
| 25 | for async_test in pytest_asyncio_tests: | |
| 26 | async_test.add_marker(session_scope_marker, append=False) | |
98d779fbStainless Bot2 years ago | 27 | |
| 28 | | |
| 29 | base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010") | |
| 30 | | |
| 31 | api_key = "My API Key" | |
| 32 | | |
| 33 | | |
| 34 | @pytest.fixture(scope="session") | |
| 35 | def client(request: FixtureRequest) -> Iterator[OpenAI]: | |
| 36 | strict = getattr(request, "param", True) | |
| 37 | if not isinstance(strict, bool): | |
| 38 | raise TypeError(f"Unexpected fixture parameter type {type(strict)}, expected {bool}") | |
| 39 | | |
| 40 | with OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=strict) as client: | |
| 41 | yield client | |
| 42 | | |
| 43 | | |
| 44 | @pytest.fixture(scope="session") | |
| 45 | async def async_client(request: FixtureRequest) -> AsyncIterator[AsyncOpenAI]: | |
| 46 | strict = getattr(request, "param", True) | |
| 47 | if not isinstance(strict, bool): | |
| 48 | raise TypeError(f"Unexpected fixture parameter type {type(strict)}, expected {bool}") | |
| 49 | | |
| 50 | async with AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=strict) as client: | |
| 51 | yield client |