From fc93ad5d29a912ce8014738b9da1691720b6c9d2 Mon Sep 17 00:00:00 2001 From: mulla028 Date: Mon, 11 Nov 2024 19:04:48 -0500 Subject: [PATCH] Unit tests added --- pom.xml | 16 ++- src/main/java/org/example/CohereApi.java | 2 +- src/main/java/org/example/Config.java | 4 +- src/test/java/org/example/ApiTest.java | 116 ++++++++++++++++ src/test/java/org/example/ColorsTest.java | 32 +++++ src/test/java/org/example/ConfigTest.java | 132 +++++++++++++++++++ src/test/resources/.polyglotcode-config.toml | 7 + src/test/resources/response.json | 16 +++ 8 files changed, 318 insertions(+), 7 deletions(-) create mode 100644 src/test/java/org/example/ApiTest.java create mode 100644 src/test/java/org/example/ColorsTest.java create mode 100644 src/test/java/org/example/ConfigTest.java create mode 100644 src/test/resources/.polyglotcode-config.toml create mode 100644 src/test/resources/response.json diff --git a/pom.xml b/pom.xml index 4ff64d8..f26dd0d 100644 --- a/pom.xml +++ b/pom.xml @@ -35,12 +35,21 @@ toml 3.8.1 + + org.junit.jupiter + junit-jupiter-engine + 5.11.3 + test + + + org.wiremock + wiremock + 3.9.2 + test + - - - @@ -114,7 +123,6 @@ - diff --git a/src/main/java/org/example/CohereApi.java b/src/main/java/org/example/CohereApi.java index 6212654..74ebb41 100644 --- a/src/main/java/org/example/CohereApi.java +++ b/src/main/java/org/example/CohereApi.java @@ -130,7 +130,7 @@ public static JSONObject callApi( } // getMsg method, completes and returns json request - static String getMsg(String language, String fileContent) { + public static String getMsg(String language, String fileContent) { String comments = ""; return "{ \"message\": \"" + comments diff --git a/src/main/java/org/example/Config.java b/src/main/java/org/example/Config.java index d39da61..8b7bb42 100644 --- a/src/main/java/org/example/Config.java +++ b/src/main/java/org/example/Config.java @@ -8,8 +8,8 @@ public class Config { FileConfig config; Config() { - File conigFile = new File(System.getProperty("user.home"), ".polyglotcode-config.toml"); - FileConfigBuilder builder = (FileConfigBuilder) FileConfig.builder(conigFile).sync(); + File configFile = new File(System.getProperty("user.home"), ".polyglotcode-config.toml"); + FileConfigBuilder builder = (FileConfigBuilder) FileConfig.builder(configFile).sync(); config = builder.build(); try { diff --git a/src/test/java/org/example/ApiTest.java b/src/test/java/org/example/ApiTest.java new file mode 100644 index 0000000..feb7b16 --- /dev/null +++ b/src/test/java/org/example/ApiTest.java @@ -0,0 +1,116 @@ +package org.example; + +import com.github.tomakehurst.wiremock.WireMockServer; +import com.github.tomakehurst.wiremock.client.WireMock; +import org.json.JSONObject; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + + +import java.io.File; +import java.io.IOException; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.file.Files; + +import static com.github.tomakehurst.wiremock.client.WireMock.*; +import static org.junit.jupiter.api.Assertions.*; + +public class ApiTest { + + private WireMockServer wireMockServer; + + private File fileName = new File("src/test/resources", "response.json"); + + + @Test + @Tag("api") + public void exampleTest() throws Exception { + // Setup the WireMock mapping stub for the test + wireMockServer = new WireMockServer(8080); + wireMockServer.start(); + String body = Files.readString(fileName.toPath()); + JSONObject jsonObject = new JSONObject(body); + + // Configure WireMock to use the started server + WireMock.configureFor("127.0.0.1", 8080); + + // Stub an API endpoint for testing + stubFor(post(urlEqualTo("/server-response")) + .willReturn(ok() + .withHeader("Content-Type", "application/json") + .withBody(body))); + + // Setup HTTP POST request (with HTTP Client embedded in Java 11+) + String bodyURL = "http://127.0.0.1:8080/server-response"; + JSONObject response; + response = CohereApi.callApi("", "", "", bodyURL, false); + + assertEquals(jsonObject.toString(), response.toString()); + + wireMockServer.stop(); + } + + + @Test + @Tag("unit") + public void testGetMsg() { + String language = "French"; + String fileContent = "Hello World!"; + String expectedMessage = "{ \"message\": \"Translate this code in French\\Hello World!"; + String actualMessage = CohereApi.getMsg(language, fileContent); + assertEquals(expectedMessage, actualMessage, "The JSON request message should match the expected format."); + } + + + @Test + @Tag("unit") + public void testGetErr400() { + assertEquals("Bad Request. The request was invalid or cannot be otherwise served.", CohereApi.getErr(400)); + } + + @Test + @Tag("unit") + public void testGetErr401() { + assertEquals("Unauthorized. Authentication failed or API key is invalid.", CohereApi.getErr(401)); + } + + @Test + @Tag("unit") + public void testGetErr403() { + assertEquals("Forbidden. The request is understood, but it has been refused.", CohereApi.getErr(403)); + } + + @Test + @Tag("unit") + public void testGetErr404() { + assertEquals("Not Found. The requested resource could not be found.", CohereApi.getErr(404)); + } + + @Test + @Tag("unit") + public void testGetErr429() { + assertEquals("Too Many Requests. Rate limit exceeded.", CohereApi.getErr(429)); + } + + @Test + @Tag("unit") + public void testGetErr500() { + assertEquals("Internal Server Error. An error occurred on the server.", CohereApi.getErr(500)); + } + + @Test + @Tag("unit") + public void testGetErr503() { + assertEquals("Service Unavailable. The service is temporarily unavailable.", CohereApi.getErr(503)); + } + + @Test + @Tag("unit") + public void testGetErrUnknown() { + assertEquals("An unexpected error occurred.", CohereApi.getErr(999)); + } +} diff --git a/src/test/java/org/example/ColorsTest.java b/src/test/java/org/example/ColorsTest.java new file mode 100644 index 0000000..6d0959a --- /dev/null +++ b/src/test/java/org/example/ColorsTest.java @@ -0,0 +1,32 @@ +package org.example; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + +public class ColorsTest { + + @Test + @Tag("unit") + void testSetGreen() { + String expected = "\u001B[32m"; + String actual = Colors.setGreen(); + assertEquals(expected, actual, "setGreen() should return the ANSI code for green color"); + } + + @Test + @Tag("unit") + void testSetRed() { + String expected = "\u001B[31m"; + String actual = Colors.setRed(); + assertEquals(expected, actual, "setRed() should return the ANSI code for red color"); + } + + @Test + @Tag("unit") + void testResetColor() { + String expected = "\u001B[0m"; + String actual = Colors.resetColor(); + assertEquals(expected, actual, "resetColor() should return the ANSI code to reset color"); + } +} diff --git a/src/test/java/org/example/ConfigTest.java b/src/test/java/org/example/ConfigTest.java new file mode 100644 index 0000000..9ab1770 --- /dev/null +++ b/src/test/java/org/example/ConfigTest.java @@ -0,0 +1,132 @@ +package org.example; + +import com.electronwill.nightconfig.core.file.FileConfig; +import org.junit.jupiter.api.*; +import static org.junit.jupiter.api.Assertions.*; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; + +public class ConfigTest { + + private String originalUserHome; + + @BeforeEach + void setUp() { + // Save the original user.home property + originalUserHome = System.getProperty("user.home"); + } + + @AfterEach + void tearDown() { + // Restore the original user.home property + System.setProperty("user.home", originalUserHome); + } + + @Test + @Tag("unit") + void testConfigLoadsDefaultsWhenFileIsEmpty() throws IOException { + // Create a temporary directory to act as the user's home directory + File tempDir = Files.createTempDirectory("tempHomeDir").toFile(); + + // Set the user.home property to the temporary directory + System.setProperty("user.home", tempDir.getAbsolutePath()); + + // Ensure the config file does not exist + File configFile = new File(tempDir, ".polyglotcode-.polyglotcode-config.toml"); + if (configFile.exists()) { + configFile.delete(); + } + + // Create an empty config file + configFile.createNewFile(); + + // Create the Config object + Config config = new Config(); + + // Test that defaults are loaded + assertEquals("", config.getApiKey()); + assertEquals("https://api.cohere.ai/v1/chat", config.getBaseUrl()); + assertFalse(config.displayToken()); + assertFalse(config.streamResponse()); + + // Clean up + configFile.delete(); + tempDir.delete(); + } + + @Test + @Tag("conf") + void testConfigLoadsValuesFromFile() throws IOException { + File file = new File("src/test/resources"); + + // Set the user.home property to the temporary directory + System.setProperty("user.home", file.getAbsolutePath()); + + // Create the Config object + Config config = new Config(); + + // Test that values are loaded from the file + assertEquals("test-api-key", config.getApiKey()); + assertEquals("https://api.cohere.ai/v1/chat", config.getBaseUrl()); + assertFalse(config.displayToken()); + assertFalse(config.streamResponse()); + + } + + @Test + @Tag("unit") + void testConfigThrowsExceptionWhenFileIsInvalid() throws IOException { + // Create a temporary directory to act as the user's home directory + File tempDir = Files.createTempDirectory("tempHomeDir").toFile(); + + // Set the user.home property to the temporary directory + System.setProperty("user.home", tempDir.getAbsolutePath()); + + // Create the config file with invalid content + File configFile = new File(tempDir, ".polyglotcode-config.toml"); + Files.write(configFile.toPath(), "invalid content".getBytes()); + + // Expect a RuntimeException when creating the Config object + Exception exception = assertThrows(RuntimeException.class, Config::new); + + assertEquals("Config file is not valid.", exception.getMessage()); + + // Clean up + configFile.delete(); + tempDir.delete(); + } + + @Test + @Tag("unit") + void testConfigCreatesDefaultConfigWhenFileDoesNotExist() throws IOException { + // Create a temporary directory to act as the user's home directory + File tempDir = Files.createTempDirectory("tempHomeDir").toFile(); + + // Set the user.home property to the temporary directory + System.setProperty("user.home", tempDir.getAbsolutePath()); + + // Ensure the config file does not exist + File configFile = new File(tempDir, ".polyglotcode-config.toml"); + if (configFile.exists()) { + configFile.delete(); + } + + // Create the Config object + Config config = new Config(); + + // Test that defaults are loaded + assertEquals("", config.getApiKey()); + assertEquals("https://api.cohere.ai/v1/chat", config.getBaseUrl()); + assertFalse(config.displayToken()); + assertFalse(config.streamResponse()); + + // Verify that the config file is created + assertTrue(configFile.exists()); + + // Clean up + configFile.delete(); + tempDir.delete(); + } +} diff --git a/src/test/resources/.polyglotcode-config.toml b/src/test/resources/.polyglotcode-config.toml new file mode 100644 index 0000000..1618904 --- /dev/null +++ b/src/test/resources/.polyglotcode-config.toml @@ -0,0 +1,7 @@ +[output] +display_token = false +stream_response = false + +[api] +api_key = "test-api-key" +base_url = "https://api.cohere.ai/v1/chat" \ No newline at end of file diff --git a/src/test/resources/response.json b/src/test/resources/response.json new file mode 100644 index 0000000..eda2649 --- /dev/null +++ b/src/test/resources/response.json @@ -0,0 +1,16 @@ +{ + "meta": { + "billed_units": { + "output_tokens": 73, + "input_tokens": 86 + }, + "tokens": { + "output_tokens": 73, + "input_tokens": 152 + }, + "api_version": { + "version": "1" + } + }, + "text": "```java\npublic class Main {\n public static void main(String[] args) {\n int a = 5;\n int b = 10;\n int sum = a + b;\n\n System.out.println(\"The sum of \" + a + \" and \" + b + \" is: \" + sum);\n }\n}```" +} \ No newline at end of file