Skip to content

Refactoring some code #46

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ public FileResponse createFileResponse() {
return futureFile.join();
}

@SuppressWarnings("deprecation")
public void waitUntilFileIsProcessed(String fileId) {
FileResponse fileResponse = null;
do {
Expand Down
7 changes: 2 additions & 5 deletions src/main/java/io/github/sashirestela/openai/SimpleOpenAI.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import lombok.Builder;
import lombok.Getter;
import lombok.NonNull;
import lombok.Setter;

/**
* The factory that generates implementations of the {@link OpenAI OpenAI}
Expand All @@ -29,7 +30,7 @@ public class SimpleOpenAI {
private final String organizationId;
private final String baseUrl;
private final HttpClient httpClient;

@Setter
private CleverClient cleverClient;

@Getter(AccessLevel.NONE)
Expand Down Expand Up @@ -97,10 +98,6 @@ public SimpleOpenAI(@NonNull String apiKey, String organizationId, String baseUr
.build();
}

public void setCleverClient(CleverClient cleverClient) {
this.cleverClient = cleverClient;
}

/**
* Generates an implementation of the Audios interface to handle requests.
*
Expand Down
285 changes: 114 additions & 171 deletions src/test/java/io/github/sashirestela/openai/SimpleOpenAITest.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,211 +12,154 @@
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.List;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;

import io.github.sashirestela.cleverclient.CleverClient;
import io.github.sashirestela.cleverclient.http.HttpProcessor;
import io.github.sashirestela.cleverclient.util.ReflectUtil;
import io.github.sashirestela.openai.domain.chat.ChatRequest;

class SimpleOpenAITest {

HttpClient httpClient = mock(HttpClient.class);
CleverClient cleverClient = mock(CleverClient.class);

@Nested
class StandAloneTests {
@Test
void shouldSetPropertiesToDefaultValuesWhenBuilderIsCalledWithoutThoseProperties() {
var openAI = SimpleOpenAI.builder()
.apiKey("apiKey")
.build();
assertEquals(HttpClient.Version.HTTP_2, openAI.getHttpClient().version());
assertEquals(OPENAI_BASE_URL, openAI.getBaseUrl());
assertNotNull(openAI.getCleverClient());
}

@Test
void shouldSetPropertiesToDefaultValuesWhenBuilderIsCalledWithoutThoseProperties() {
var openAI = SimpleOpenAI.builder()
.apiKey("apiKey")
.build();
assertEquals(HttpClient.Version.HTTP_2, openAI.getHttpClient().version());
assertEquals(OPENAI_BASE_URL, openAI.getBaseUrl());
assertNotNull(openAI.getCleverClient());
}
@Test
void shouldSetPropertiesWhenBuilderIsCalledWithThoseProperties() {
var otherUrl = "https://openai.com/api";
var openAI = SimpleOpenAI.builder()
.apiKey("apiKey")
.baseUrl(otherUrl)
.httpClient(httpClient)
.build();
assertEquals("apiKey", openAI.getApiKey());
assertEquals(otherUrl, openAI.getBaseUrl());
assertEquals(httpClient, openAI.getHttpClient());
}

@Test
void shouldSetPropertiesWhenBuilderIsCalledWithThoseProperties() {
var otherUrl = "https://openai.com/api";
var openAI = SimpleOpenAI.builder()
.apiKey("apiKey")
.baseUrl(otherUrl)
.httpClient(httpClient)
.build();
assertEquals("apiKey", openAI.getApiKey());
assertEquals(otherUrl, openAI.getBaseUrl());
assertEquals(httpClient, openAI.getHttpClient());
}
@Test
void shouldNotAddOrganizationToHeadersWhenBuilderIsCalledWithoutOrganizationId() {
var openAI = SimpleOpenAI.builder()
.apiKey("apiKey")
.build();
assertFalse(openAI.getCleverClient().getHeaders().containsValue(openAI.getOrganizationId()));
}

@Test
void shouldNotAddOrganizationToHeadersWhenBuilderIsCalledWithoutOrganizationId() {
var openAI = SimpleOpenAI.builder()
.apiKey("apiKey")
.build();
assertFalse(openAI.getCleverClient().getHeaders().containsValue(openAI.getOrganizationId()));
}
@Test
void shouldAddOrganizationToHeadersWhenBuilderIsCalledWithOrganizationId() {
var openAI = SimpleOpenAI.builder()
.apiKey("apiKey")
.organizationId("orgId")
.build();
assertTrue(openAI.getCleverClient().getHeaders().containsValue(openAI.getOrganizationId()));
}

@Test
void shouldAddOrganizationToHeadersWhenBuilderIsCalledWithOrganizationId() {
var openAI = SimpleOpenAI.builder()
.apiKey("apiKey")
.organizationId("orgId")
@Test
@SuppressWarnings("unchecked")
void shouldNotDuplicateContentTypeHeaderWhenCallingSimpleOpenAI() {
var chatService = SimpleOpenAI.builder()
.apiKey("apiKey")
.httpClient(httpClient)
.build()
.chatCompletions();

// When
final var NO_OF_REQUESTS = 2;
when(httpClient.sendAsync(any(), any()))
.thenReturn(completedFuture(mock(HttpResponse.class)));

repeat(NO_OF_REQUESTS, () -> {
var chatRequest = ChatRequest.builder()
.model("model")
.messages(List.of())
.build();
assertTrue(openAI.getCleverClient().getHeaders().containsValue(openAI.getOrganizationId()));
}
chatService.create(chatRequest);
});

@Test
@SuppressWarnings("unchecked")
void shouldNotDuplicateContentTypeHeaderWhenCallingSimpleOpenAI() {
var chatService = SimpleOpenAI.builder()
.apiKey("apiKey")
.httpClient(httpClient)
.build()
.chatCompletions();

// When
final var NO_OF_REQUESTS = 2;
when(httpClient.sendAsync(any(), any()))
.thenReturn(completedFuture(mock(HttpResponse.class)));

repeat(NO_OF_REQUESTS, () -> {
var chatRequest = ChatRequest.builder()
.model("model")
.messages(List.of())
.build();
chatService.create(chatRequest);
});

// Then
ArgumentCaptor<HttpRequest> requestCaptor = ArgumentCaptor.forClass(HttpRequest.class);
verify(httpClient, times(NO_OF_REQUESTS))
.sendAsync(requestCaptor.capture(), any());

var actualRequest = requestCaptor.getAllValues().get(NO_OF_REQUESTS - 1);
assertEquals(1, actualRequest.headers().allValues("Content-Type").size(),
"Contains Content-Type header exactly once");
}
// Then
ArgumentCaptor<HttpRequest> requestCaptor = ArgumentCaptor.forClass(HttpRequest.class);
verify(httpClient, times(NO_OF_REQUESTS))
.sendAsync(requestCaptor.capture(), any());

var actualRequest = requestCaptor.getAllValues().get(NO_OF_REQUESTS - 1);
assertEquals(1, actualRequest.headers().allValues("Content-Type").size(),
"Contains Content-Type header exactly once");
}

@Nested
class InitializedTests {
@Test
void shouldInstanceServiceOnlyOnceWhenItIsCalledSeverlaTimes() {
final int NUMBER_CALLINGS = 3;
final int NUMBER_INVOCATIONS = 1;

SimpleOpenAI openAI;

@BeforeEach
void init() {
openAI = SimpleOpenAI.builder()
.apiKey("apiKey")
.httpClient(httpClient)
.build();
openAI.setCleverClient(cleverClient);
}

@Test
void shouldInstanceAudioServiceOnlyOnceWhenItIsCalledSeveralTimes() {
when(cleverClient.create(any()))
.thenReturn(ReflectUtil.createProxy(
OpenAI.Audios.class,
HttpProcessor.builder().build()));
repeat(NUMBER_CALLINGS, () -> openAI.audios());
verify(cleverClient, times(NUMBER_INVOCATIONS)).create(any());
}

@Test
void shouldInstanceChatCompletionServiceOnlyOnceWhenItIsCalledSeveralTimes() {
when(cleverClient.create(any()))
.thenReturn(ReflectUtil.createProxy(
OpenAI.ChatCompletions.class,
HttpProcessor.builder().build()));
repeat(NUMBER_CALLINGS, () -> openAI.chatCompletions());
verify(cleverClient, times(NUMBER_INVOCATIONS)).create(any());
}

@Test
void shouldInstanceCompletionServiceOnlyOnceWhenItIsCalledSeveralTimes() {
SimpleOpenAI openAI = SimpleOpenAI.builder()
.apiKey("apiKey")
.httpClient(httpClient)
.build();
openAI.setCleverClient(cleverClient);

TestData[] data = {
new TestData(OpenAI.Audios.class, openAI::audios),
new TestData(OpenAI.ChatCompletions.class, openAI::chatCompletions),
new TestData(OpenAI.Completions.class, openAI::completions),
new TestData(OpenAI.Embeddings.class, openAI::embeddings),
new TestData(OpenAI.Files.class, openAI::files),
new TestData(OpenAI.FineTunings.class, openAI::fineTunings),
new TestData(OpenAI.Images.class, openAI::images),
new TestData(OpenAI.Models.class, openAI::models),
new TestData(OpenAI.Moderations.class, openAI::moderations),
new TestData(OpenAI.Assistants.class, openAI::assistants),
new TestData(OpenAI.Threads.class, openAI::threads)
};
for (TestData testData : data) {
when(cleverClient.create(any()))
.thenReturn(ReflectUtil.createProxy(
OpenAI.Completions.class,
HttpProcessor.builder().build()));
repeat(NUMBER_CALLINGS, () -> openAI.completions());
verify(cleverClient, times(NUMBER_INVOCATIONS)).create(any());
}

@Test
void shouldInstanceEmbeddingServiceOnlyOnceWhenItIsCalledSeveralTimes() {
when(cleverClient.create(any()))
.thenReturn(ReflectUtil.createProxy(
OpenAI.Embeddings.class,
HttpProcessor.builder().build()));
repeat(NUMBER_CALLINGS, () -> openAI.embeddings());
verify(cleverClient, times(NUMBER_INVOCATIONS)).create(any());
}

@Test
void shouldInstanceFilesServiceOnlyOnceWhenItIsCalledSeveralTimes() {
when(cleverClient.create(any()))
.thenReturn(ReflectUtil.createProxy(
OpenAI.Files.class,
HttpProcessor.builder().build()));
repeat(NUMBER_CALLINGS, () -> openAI.files());
verify(cleverClient, times(NUMBER_INVOCATIONS)).create(any());
}

@Test
void shouldInstanceFineTunningServiceOnlyOnceWhenItIsCalledSeveralTimes() {
when(cleverClient.create(any()))
.thenReturn(ReflectUtil.createProxy(
OpenAI.FineTunings.class,
HttpProcessor.builder().build()));
repeat(NUMBER_CALLINGS, () -> openAI.fineTunings());
verify(cleverClient, times(NUMBER_INVOCATIONS)).create(any());
.thenReturn(createProxy(testData.serviceClass));
repeat(NUMBER_CALLINGS, testData.calling);
verify(cleverClient, times(NUMBER_INVOCATIONS)).create(testData.serviceClass);
}
}

@Test
void shouldInstanceImageServiceOnlyOnceWhenItIsCalledSeveralTimes() {
when(cleverClient.create(any()))
.thenReturn(ReflectUtil.createProxy(
OpenAI.Images.class,
HttpProcessor.builder().build()));
repeat(NUMBER_CALLINGS, () -> openAI.images());
verify(cleverClient, times(NUMBER_INVOCATIONS)).create(any());
}
private static void repeat(int times, Runnable action) {
for (var i = 0; i < times; i++)
action.run();
}

@Test
void shouldInstanceModelsServiceOnlyOnceWhenItIsCalledSeveralTimes() {
when(cleverClient.create(any()))
.thenReturn(ReflectUtil.createProxy(
OpenAI.Models.class,
HttpProcessor.builder().build()));
repeat(NUMBER_CALLINGS, () -> openAI.models());
verify(cleverClient, times(NUMBER_INVOCATIONS)).create(any());
}
static class TestData {
private Class<?> serviceClass;
private Runnable calling;

@Test
void shouldInstanceModerationServiceOnlyOnceWhenItIsCalledSeveralTimes() {
when(cleverClient.create(any()))
.thenReturn(ReflectUtil.createProxy(
OpenAI.Moderations.class,
HttpProcessor.builder().build()));
repeat(NUMBER_CALLINGS, () -> openAI.moderations());
verify(cleverClient, times(NUMBER_INVOCATIONS)).create(any());
public TestData(Class<?> serviceClass, Runnable calling) {
this.serviceClass = serviceClass;
this.calling = calling;
}
}

private static void repeat(int times, Runnable action) {
for (var i = 0; i < times; i++)
action.run();
@SuppressWarnings("unchecked")
private static <T> T createProxy(Class<T> interfaceClass) {
return (T) Proxy.newProxyInstance(
interfaceClass.getClassLoader(),
new Class<?>[] { interfaceClass },
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
throw new UnsupportedOperationException("Unimplemented method 'invoke'");
}
});
}
}