openai / openai-dotnet

The official .NET library for the OpenAI API
https://www.nuget.org/packages/OpenAI/AbsoluteLatest
MIT License
1.04k stars 99 forks source link

How to mock AssistantClient and FileClient responses #176

Open leon-aperstein opened 3 weeks ago

leon-aperstein commented 3 weeks ago

Confirm this is not a feature request for the underlying OpenAI API.

Confirm this is not a feature request for Azure OpenAI.

Describe the feature or improvement you're requesting

The responses provided by both FileClient and AssistantClient in the following functions: FileClient:

AssistantClinet:

Cannot be mocked or instantiated thus disabling proper unit testing. How can we write unit tests to check proper flow?

Additional context

No response

mallek commented 1 week ago

We ran into this same problem with the internal constructors and no Interfaces in the library. We used reflection to accomplish our functional tests. The Interfaces we created in our project to wrap the library.

private static T CreateInstance<T>(params object[] args)
{
    var type = typeof(T);
    var instance = type.Assembly.CreateInstance(
        type.FullName,
        false,
        BindingFlags.Instance | BindingFlags.NonPublic,
        null,
        args,
        null,
        null);

    return (T)instance;
}
var assistantClientMock = Substitute.For<IAssistantClient>();
assistantClientMock
    .CreateAssistantAsync(Arg.Any<string>(), Arg.Any<AssistantCreationOptions>())
    .ReturnsForAnyArgs(callArgs => ClientResult.FromValue(
        CreateInstance<Assistant>(
            "asst_ABCdefGHI123456",
            DateTimeOffset.UtcNow,
            callArgs.Arg<AssistantCreationOptions>().Name,
            callArgs.Arg<AssistantCreationOptions>().Description,
            callArgs.Arg<string>(),
            callArgs.Arg<AssistantCreationOptions>().Instructions,
            callArgs.Arg<AssistantCreationOptions>().Tools,
            callArgs.Arg<AssistantCreationOptions>().Metadata),
        pipelineResponseMock));