Overview¶
The main interface for this library is the OpenAIMock
class. This class contains:
- all of the supported routes
- a state store for stateful routes
- a RESPX Router instance that patches the requests
The class constructor allows you to set a custom base URL and/or a custom initial state.
Modalities¶
There are serveral ways to use the OpenAIMock
class.
Decorator¶
The main way is to decorate the test function with openai_responses.mock()
which wraps the function and provides an instance of the class as a test fixture.
Context manager¶
For certain scenarios where using the decorator + Pytest fixture is not an option, you can optionally construct the instance and use the router as a context manager.
Transport¶
HTTPX clients accept a transport object. These objects are used to actually send the requests. Many people prefer to use transports and their codebase is already setup to make use of swapping different transports out for different environments.
You can create mock transport with the router object.
Routes¶
Routes are accessed following the same interface as the official Python library. For example, if you accessed the chat.completions.create
route like this in the Python library:
The mock route can be accessed like this:
Each route class contains:
- a RESPX Route instance
- a Response object
Stateful routes also contain an instance of a StateStore
for managing resources.
Stateful routes¶
While routes like chat.completions.create
are stateless, routes like those in the new Assistants API are stateful and manage resource objects for you behind the scenes.
For stateful routes, a state store is used to manage resources. Since many of the stateful routes are simple CRUD operations, you do not need to manually set the response.
Setting the response¶
You can set the value of the response for all routes by using the setter for the response
property.
The response can be set to either a partial of the OpenAI object, a full OpenAI object, an HTTPX Response, or a function that returns an HTTPX response. See more in Responses.
Call history¶
The route instances keep track of the calls to that route. That information is available to you so you can do things like assert a route was only called once, or that a route was not called at all.