|
| 1 | +using Microsoft.Extensions.Options; |
| 2 | +using Moq; |
| 3 | +using NUnit.Framework; |
| 4 | +using OpenAI_API; |
| 5 | +using System; |
| 6 | +using System.Linq; |
| 7 | +using System.Net.Http; |
| 8 | + |
| 9 | +namespace OpenAI_Tests |
| 10 | +{ |
| 11 | + public class HttpClientResolutionTests |
| 12 | + { |
| 13 | + [Test] |
| 14 | + public void GetHttpClient_NoFactory() |
| 15 | + { |
| 16 | + var api = new OpenAIAPI(new APIAuthentication("fake-key")); |
| 17 | + var endpoint = new TestEndpoint(api); |
| 18 | + |
| 19 | + var client = endpoint.GetHttpClient(); |
| 20 | + Assert.IsNotNull(client); |
| 21 | + } |
| 22 | + |
| 23 | + [Test] |
| 24 | + public void GetHttpClient_WithFactory() |
| 25 | + { |
| 26 | + var expectedClient1 = new HttpClient(); |
| 27 | + var mockedFactory1 = Mock.Of<IHttpClientFactory>(f => f.CreateClient(Options.DefaultName) == expectedClient1); |
| 28 | + |
| 29 | + var expectedClient2 = new HttpClient(); |
| 30 | + var mockedFactory2 = Mock.Of<IHttpClientFactory>(f => f.CreateClient(Options.DefaultName) == expectedClient2); |
| 31 | + |
| 32 | + var api = new OpenAIAPI(new APIAuthentication("fake-key")); |
| 33 | + var endpoint = new TestEndpoint(api); |
| 34 | + |
| 35 | + api.HttpClientFactory = mockedFactory1; |
| 36 | + var actualClient1 = endpoint.GetHttpClient(); |
| 37 | + |
| 38 | + api.HttpClientFactory = mockedFactory2; |
| 39 | + var actualClient2 = endpoint.GetHttpClient(); |
| 40 | + |
| 41 | + Assert.AreSame(expectedClient1, actualClient1); |
| 42 | + Assert.AreSame(expectedClient2, actualClient2); |
| 43 | + |
| 44 | + api.HttpClientFactory = null; |
| 45 | + var actualClient3 = endpoint.GetHttpClient(); |
| 46 | + |
| 47 | + Assert.NotNull(actualClient3); |
| 48 | + Assert.AreNotSame(expectedClient1, actualClient3); |
| 49 | + Assert.AreNotSame(expectedClient2, actualClient3); |
| 50 | + } |
| 51 | + |
| 52 | + private class TestEndpoint : EndpointBase |
| 53 | + { |
| 54 | + public TestEndpoint(OpenAIAPI api) : base(api) |
| 55 | + { |
| 56 | + } |
| 57 | + |
| 58 | + protected override string Endpoint => throw new System.NotSupportedException(); |
| 59 | + |
| 60 | + public HttpClient GetHttpClient() |
| 61 | + { |
| 62 | + return base.GetClient(); |
| 63 | + } |
| 64 | + } |
| 65 | + } |
| 66 | +} |
0 commit comments