Skip to content

Commit

Permalink
Unit tests added
Browse files Browse the repository at this point in the history
  • Loading branch information
mulla028 committed Nov 12, 2024
1 parent bf819af commit fc93ad5
Show file tree
Hide file tree
Showing 8 changed files with 318 additions and 7 deletions.
16 changes: 12 additions & 4 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,21 @@
<artifactId>toml</artifactId>
<version>3.8.1</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.11.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.wiremock</groupId>
<artifactId>wiremock</artifactId>
<version>3.9.2</version>
<scope>test</scope>
</dependency>

</dependencies>




<build>
<plugins>

Expand Down Expand Up @@ -114,7 +123,6 @@
</plugin>



</plugins>
</build>

Expand Down
2 changes: 1 addition & 1 deletion src/main/java/org/example/CohereApi.java
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/org/example/Config.java
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
116 changes: 116 additions & 0 deletions src/test/java/org/example/ApiTest.java
Original file line number Diff line number Diff line change
@@ -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));
}
}
32 changes: 32 additions & 0 deletions src/test/java/org/example/ColorsTest.java
Original file line number Diff line number Diff line change
@@ -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");
}
}
132 changes: 132 additions & 0 deletions src/test/java/org/example/ConfigTest.java
Original file line number Diff line number Diff line change
@@ -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();
}
}
7 changes: 7 additions & 0 deletions src/test/resources/.polyglotcode-config.toml
Original file line number Diff line number Diff line change
@@ -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"
16 changes: 16 additions & 0 deletions src/test/resources/response.json
Original file line number Diff line number Diff line change
@@ -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}```"
}

0 comments on commit fc93ad5

Please sign in to comment.