diff --git a/pom.xml b/pom.xml
index 5edfa21..12393f8 100644
--- a/pom.xml
+++ b/pom.xml
@@ -167,6 +167,12 @@
wiremock
${wiremock.version}
+
+ org.mockito
+ mockito-inline
+ 5.2.0
+ test
+
org.slf4j
slf4j-api
@@ -177,8 +183,6 @@
logback-classic
${logback-classic.version}
-
-
diff --git a/src/main/java/com/angelbroking/smartapi/http/SmartAPIRequestHandler.java b/src/main/java/com/angelbroking/smartapi/http/SmartAPIRequestHandler.java
index a53229a..987e1f2 100644
--- a/src/main/java/com/angelbroking/smartapi/http/SmartAPIRequestHandler.java
+++ b/src/main/java/com/angelbroking/smartapi/http/SmartAPIRequestHandler.java
@@ -431,7 +431,7 @@ public Request createDeleteRequest(String url, Map params, Strin
}
Request request = new Request.Builder().url(httpBuilder.build()).delete().header("User-Agent", USER_AGENT)
- .header("X-Smart API-Version", "3").header("Authorization", "token " + apiKey + ":" + accessToken)
+ .header("X-SmartAPI-Version", "3").header("Authorization", "token " + apiKey + ":" + accessToken)
.build();
return request;
}
diff --git a/src/main/java/com/angelbroking/smartapi/sample/LoginWithTOTPSample.java b/src/main/java/com/angelbroking/smartapi/sample/LoginWithTOTPSample.java
index 910bcc5..f36d841 100644
--- a/src/main/java/com/angelbroking/smartapi/sample/LoginWithTOTPSample.java
+++ b/src/main/java/com/angelbroking/smartapi/sample/LoginWithTOTPSample.java
@@ -4,7 +4,7 @@
import com.angelbroking.smartapi.models.User;
public class LoginWithTOTPSample {
-
+
public static void main(String[] args) {
String clientID = System.getProperty("clientID");
String clientPass = System.getProperty("clientPass");
diff --git a/src/main/java/com/angelbroking/smartapi/sample/Test.java b/src/main/java/com/angelbroking/smartapi/sample/Test.java
index 6ef34e0..1d07fbf 100644
--- a/src/main/java/com/angelbroking/smartapi/sample/Test.java
+++ b/src/main/java/com/angelbroking/smartapi/sample/Test.java
@@ -1,125 +1,125 @@
-package com.angelbroking.smartapi.sample;
+ package com.angelbroking.smartapi.sample;
-import com.angelbroking.smartapi.SmartConnect;
-import com.angelbroking.smartapi.http.exceptions.SmartAPIException;
-import com.angelbroking.smartapi.models.User;
+ import com.angelbroking.smartapi.SmartConnect;
+ import com.angelbroking.smartapi.http.exceptions.SmartAPIException;
+ import com.angelbroking.smartapi.models.User;
-public class Test {
+ public class Test {
- public static void main(String[] args) throws SmartAPIException {
- try {
+ public static void main(String[] args) throws SmartAPIException {
+ try {
- SmartConnect smartConnect = new SmartConnect(""); // PROVIDE YOUR API KEY HERE
+ SmartConnect smartConnect = new SmartConnect(""); // PROVIDE YOUR API KEY HERE
- /*
- * OPTIONAL - ACCESS_TOKEN AND REFRESH TOKEN SmartConnect smartConnect = new
- * SmartConnect("", "", "");
- */
+ /*
+ * OPTIONAL - ACCESS_TOKEN AND REFRESH TOKEN SmartConnect smartConnect = new
+ * SmartConnect("", "", "");
+ */
- /*
- * Set session expiry callback. smartConnect.setSessionExpiryHook(new
- * SessionExpiryHook() {
- *
- * @Override public void sessionExpired() {
- * System.out.println("session expired"); } });
- *
- * User user = smartConnect.generateSession("", "");
- * smartConnect.setAccessToken(user.getAccessToken());
- * smartConnect.setUserId(user.getUserId());
- *
- * /* token re-generate
- */
- /*
- * TokenSet tokenSet = smartConnect.renewAccessToken(user.getAccessToken(),
- * user.getRefreshToken());
- * smartConnect.setAccessToken(tokenSet.getAccessToken());
- */
+ /*
+ * Set session expiry callback. smartConnect.setSessionExpiryHook(new
+ * SessionExpiryHook() {
+ *
+ * @Override public void sessionExpired() {
+ * System.out.println("session expired"); } });
+ *
+ * User user = smartConnect.generateSession("", "");
+ * smartConnect.setAccessToken(user.getAccessToken());
+ * smartConnect.setUserId(user.getUserId());
+ *
+ * /* token re-generate
+ */
+ /*
+ * TokenSet tokenSet = smartConnect.renewAccessToken(user.getAccessToken(),
+ * user.getRefreshToken());
+ * smartConnect.setAccessToken(tokenSet.getAccessToken());
+ */
- Examples examples = new Examples();
- /* System.out.println("getProfile"); */
- examples.getProfile(smartConnect);
+ Examples examples = new Examples();
+ /* System.out.println("getProfile"); */
+ examples.getProfile(smartConnect);
- /* System.out.println("placeOrder"); */
- examples.placeOrder(smartConnect);
+ /* System.out.println("placeOrder"); */
+ examples.placeOrder(smartConnect);
- /* System.out.println("modifyOrder"); */
- examples.modifyOrder(smartConnect);
+ /* System.out.println("modifyOrder"); */
+ examples.modifyOrder(smartConnect);
- /* System.out.println("cancelOrder"); */
- examples.cancelOrder(smartConnect);
+ /* System.out.println("cancelOrder"); */
+ examples.cancelOrder(smartConnect);
- /* System.out.println("getOrder"); */
- examples.getOrder(smartConnect);
+ /* System.out.println("getOrder"); */
+ examples.getOrder(smartConnect);
- /* System.out.println("getLTP"); */
- examples.getLTP(smartConnect);
+ /* System.out.println("getLTP"); */
+ examples.getLTP(smartConnect);
- /* System.out.println("getTrades"); */
- examples.getTrades(smartConnect);
+ /* System.out.println("getTrades"); */
+ examples.getTrades(smartConnect);
- /* System.out.println("getRMS"); */
- examples.getRMS(smartConnect);
+ /* System.out.println("getRMS"); */
+ examples.getRMS(smartConnect);
- /* System.out.println("getHolding"); */
- examples.getHolding(smartConnect);
+ /* System.out.println("getHolding"); */
+ examples.getHolding(smartConnect);
- /* System.out.println("getPosition"); */
- examples.getPosition(smartConnect);
+ /* System.out.println("getPosition"); */
+ examples.getPosition(smartConnect);
- /* System.out.println("convertPosition"); */
- examples.convertPosition(smartConnect);
+ /* System.out.println("convertPosition"); */
+ examples.convertPosition(smartConnect);
- /* System.out.println("createRule"); */
- examples.createRule(smartConnect);
+ /* System.out.println("createRule"); */
+ examples.createRule(smartConnect);
- /* System.out.println("ModifyRule"); */
- examples.modifyRule(smartConnect);
+ /* System.out.println("ModifyRule"); */
+ examples.modifyRule(smartConnect);
- /* System.out.println("cancelRule"); */
- examples.cancelRule(smartConnect);
+ /* System.out.println("cancelRule"); */
+ examples.cancelRule(smartConnect);
- /* System.out.println("Rule Details"); */
- examples.ruleDetails(smartConnect);
+ /* System.out.println("Rule Details"); */
+ examples.ruleDetails(smartConnect);
- /* System.out.println("Rule List"); */
- examples.ruleList(smartConnect);
+ /* System.out.println("Rule List"); */
+ examples.ruleList(smartConnect);
- /* System.out.println("Historic candle Data"); */
- examples.getCandleData(smartConnect);
+ /* System.out.println("Historic candle Data"); */
+ examples.getCandleData(smartConnect);
- /* System.out.println("Search script api"); */
- examples.getSearchScrip(smartConnect);
+ /* System.out.println("Search script api"); */
+ examples.getSearchScrip(smartConnect);
- /* System.out.println("Market Data"); */
- examples.getMarketData(smartConnect);
+ /* System.out.println("Market Data"); */
+ examples.getMarketData(smartConnect);
- /* System.out.println("logout"); */
- examples.logout(smartConnect);
+ /* System.out.println("logout"); */
+ examples.logout(smartConnect);
- /* SmartAPITicker */
- String clientId = "";
- User user = smartConnect.generateSession("", "", "");
- String feedToken = user.getFeedToken();
- String strWatchListScript = "nse_cm|2885&nse_cm|1594&nse_cm|11536&mcx_fo|221658";
- String task = "mw";
+ /* SmartAPITicker */
+ String clientId = "";
+ User user = smartConnect.generateSession("", "", "");
+ String feedToken = user.getFeedToken();
+ String strWatchListScript = "nse_cm|2885&nse_cm|1594&nse_cm|11536&mcx_fo|221658";
+ String task = "mw";
- examples.tickerUsage(clientId, feedToken, strWatchListScript, task);
+ examples.tickerUsage(clientId, feedToken, strWatchListScript, task);
- /*
- * String jwtToken = user.getAccessToken(); String apiKey = "smartapi_key";
- * String actionType = "subscribe"; String feedType = "order_feed";
- *
- * examples.smartWebSocketUsage(clientId, jwtToken, apiKey, actionType,
- * feedType);
- *
- */
+ /*
+ * String jwtToken = user.getAccessToken(); String apiKey = "smartapi_key";
+ * String actionType = "subscribe"; String feedType = "order_feed";
+ *
+ * examples.smartWebSocketUsage(clientId, jwtToken, apiKey, actionType,
+ * feedType);
+ *
+ */
- } catch (Exception e) {
- System.out.println("Exception: " + e.getMessage());
- e.printStackTrace();
- }
+ } catch (Exception e) {
+ System.out.println("Exception: " + e.getMessage());
+ e.printStackTrace();
+ }
- }
-}
\ No newline at end of file
+ }
+ }
\ No newline at end of file
diff --git a/src/test/java/com/angelbroking/smartapi/exceptions/ExceptionTests.java b/src/test/java/com/angelbroking/smartapi/exceptions/ExceptionTests.java
new file mode 100644
index 0000000..c32e928
--- /dev/null
+++ b/src/test/java/com/angelbroking/smartapi/exceptions/ExceptionTests.java
@@ -0,0 +1,91 @@
+package com.angelbroking.smartapi.exceptions;
+
+import com.angelbroking.smartapi.http.exceptions.*;
+import com.angelbroking.smartapi.smartstream.models.SmartStreamError;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.Assert.assertEquals;
+
+public class ExceptionTests {
+ @Test
+ public void testDataException() {
+
+ String message = "Test Message";
+ String code = "Test Code";
+ DataException exception = new DataException(message, code);
+ assertEquals(message, exception.message);
+ assertEquals(code, exception.code);
+ }
+
+ @Test
+ public void testGeneralException() {
+
+ String message = "Test Message";
+ String code = "123";
+ GeneralException exception = new GeneralException(message, code);
+
+ assertEquals(message, exception.message);
+ assertEquals(code, exception.code);
+ }
+
+ @Test
+ public void testInputException() {
+
+ InputException exception = new InputException("Test message", "Test code");
+ assertEquals("Test message", exception.message);
+ assertEquals("Test code", exception.code);
+ }
+
+ @Test
+ public void testNetworkException() {
+
+ NetworkException exception = new NetworkException("Test message", "Test code");
+ assertEquals("Test message", exception.message);
+ assertEquals("Test code", exception.code);
+ }
+
+ @Test
+ public void testOrderException() {
+
+ OrderException exception = new OrderException("Test message", "Test code");
+ assertEquals("Test message", exception.message);
+ assertEquals("Test code", exception.code);
+ }
+
+ @Test
+ public void testPermissionException() {
+
+ PermissionException exception = new PermissionException("Test message", "Test code");
+ assertEquals("Test message", exception.message);
+ assertEquals("Test code", exception.code);
+ }
+
+ @Test
+ public void testTokenException() {
+
+ String message = "Test message";
+ String code = "123";
+ TokenException tokenException = new TokenException(message, code);
+ assertEquals(message, tokenException.message);
+ assertEquals(code, tokenException.code);
+ }
+
+ @Test
+ public void testApiKeyException() {
+
+ String message = "Invalid API Key";
+ String code = "123";
+ ApiKeyException exception = new ApiKeyException(message, code);
+ assertEquals(message, exception.message);
+ assertEquals(code, exception.code);
+ }
+
+ @Test
+ public void testSmartStreamError() {
+
+ Throwable exception = new Throwable("Test Exception");
+ SmartStreamError smartStreamError = new SmartStreamError();
+ smartStreamError.setException(exception);
+ assertEquals(exception, smartStreamError.getException());
+ }
+}
diff --git a/src/test/java/com/angelbroking/smartapi/http/SmartApiRequestHandlerTest.java b/src/test/java/com/angelbroking/smartapi/http/SmartApiRequestHandlerTest.java
new file mode 100644
index 0000000..1413946
--- /dev/null
+++ b/src/test/java/com/angelbroking/smartapi/http/SmartApiRequestHandlerTest.java
@@ -0,0 +1,265 @@
+package com.angelbroking.smartapi.http;
+
+import com.angelbroking.smartapi.SmartConnect;
+import com.angelbroking.smartapi.http.SmartAPIRequestHandler;
+import com.angelbroking.smartapi.http.exceptions.SmartAPIException;
+import lombok.extern.slf4j.Slf4j;
+import okhttp3.HttpUrl;
+import okhttp3.OkHttpClient;
+import okhttp3.Request;
+import okhttp3.logging.HttpLoggingInterceptor;
+import org.json.JSONArray;
+import org.json.JSONObject;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mock;
+
+import java.io.IOException;
+import java.net.Proxy;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+
+import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+@Slf4j
+public class SmartApiRequestHandlerTest {
+
+ @Mock
+ private OkHttpClient client;
+
+ private String USER_AGENT = "javasmartapiconnect/3.0.0";
+
+ @Test
+ public void testSmartApiRequestHandlerWithNotNullProxy() {
+
+ Proxy proxy = Proxy.NO_PROXY;
+ OkHttpClient.Builder builder = new OkHttpClient.Builder();
+ builder.connectTimeout(10000, TimeUnit.MILLISECONDS);
+ if (proxy != null) {
+ builder.proxy(proxy);
+ }
+
+ HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
+ logging.setLevel(HttpLoggingInterceptor.Level.BODY);
+ if (SmartConnect.ENABLE_LOGGING) {
+ client = builder.addInterceptor(logging).build();
+ } else {
+ client = builder.build();
+ }
+
+ assertNotNull(client);
+ }
+
+ @Test
+ public void testSmartApiRequestHandlerWithNullProxy() {
+
+ assertThrows(SmartAPIException.class, () -> {
+ Proxy proxy = null;
+ OkHttpClient.Builder builder = new OkHttpClient.Builder();
+ builder.connectTimeout(10000, TimeUnit.MILLISECONDS);
+ builder.proxy(proxy);
+
+ HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
+ logging.setLevel(HttpLoggingInterceptor.Level.BODY);
+ if (SmartConnect.ENABLE_LOGGING) {
+ client = builder.addInterceptor(logging).build();
+ } else {
+ client = builder.build();
+ }
+ throw new SmartAPIException("Test exception");
+ });
+ }
+
+ @Test
+ public void testApiHeaders() {
+
+ SmartAPIRequestHandler handler = new SmartAPIRequestHandler(null);
+ JSONObject headers = handler.apiHeaders();
+
+ assertNotNull(headers);
+ assertTrue(headers.has("clientLocalIP"));
+ assertTrue(headers.has("clientPublicIP"));
+ assertTrue(headers.has("macAddress"));
+ assertTrue(headers.has("accept"));
+ assertTrue(headers.has("userType"));
+ assertTrue(headers.has("sourceID"));
+ }
+
+ @Test
+ public void testCreateRequestWithAllParameters() {
+
+ // Arrange
+ String apiKey = "validApiKey";
+ String url = "https://example.com/";
+ JSONObject params = new JSONObject();
+ params.put("param1", "value1");
+
+ SmartAPIRequestHandler handler = new SmartAPIRequestHandler(null);
+ JSONObject apiheader = handler.apiHeaders();
+ // Act
+ Request request = handler.createPostRequest(apiKey, url, params);
+
+ log.info("url {}", request.url());
+ log.info("content type {}", request.header("Content-Type"));
+ // Assert
+ assertNotNull(request);
+ assertEquals(url, request.url().toString());
+ assertEquals("POST", request.method());
+ assertEquals("application/json", request.header("Content-Type"));
+ assertEquals(apiKey, request.header("X-PrivateKey"));
+ assertEquals(apiheader.getString("clientLocalIP"), request.header("X-ClientLocalIP"));
+ assertEquals(apiheader.getString("clientPublicIP"), request.header("X-ClientPublicIP"));
+ assertEquals(apiheader.getString("macAddress"), request.header("X-MACAddress"));
+ assertEquals(apiheader.getString("accept"), request.header("Accept"));
+ assertEquals(apiheader.getString("userType"), request.header("X-UserType"));
+ assertEquals(apiheader.getString("sourceID"), request.header("X-SourceID"));
+ }
+
+ @Test
+ public void testCreateRequestWithApiKeyNull() {
+
+ // Arrange
+ String apiKey = null;
+ String url = "https://example.com";
+ JSONObject params = new JSONObject();
+
+ SmartAPIRequestHandler handler = new SmartAPIRequestHandler(null);
+
+ // Act
+ Request request = handler.createPostRequest(apiKey, url, params);
+
+ // Assert
+ assertNull(request);
+ }
+
+ @Test
+ public void testCreateRequestWithUrlNull() {
+
+ // Arrange
+ String apiKey = "validApiKey";
+ String url = null;
+ JSONObject params = new JSONObject();
+
+ SmartAPIRequestHandler handler = new SmartAPIRequestHandler(null);
+
+ // Act
+ Request request = handler.createPostRequest(apiKey, url, params);
+
+ // Assert
+ assertNull(request);
+ }
+
+ @Test
+ public void testCreateRequestWithParamsNull() {
+ // Arrange
+ String apiKey = "validApiKey";
+ String url = "https://example.com/";
+ JSONObject params = null;
+
+ SmartAPIRequestHandler handler = new SmartAPIRequestHandler(null);
+ // Act
+ Request request = handler.createPostRequest(apiKey, url, params);
+
+ // Assert
+ assertNull(request);
+ }
+
+ @Test
+ public void testCreateRequestWithAccessTokenAndAllParameters() {
+ // Arrange
+ String apiKey = "validApiKey";
+ String url = "https://example.com/";
+ JSONObject params = new JSONObject();
+ params.put("param1", "value1");
+ String accessToken = "validAccessToken";
+
+ SmartAPIRequestHandler handler = new SmartAPIRequestHandler(null);
+ JSONObject apiheader = handler.apiHeaders();
+ // Act
+ Request request = handler.createPostRequest(apiKey, url, params, accessToken);
+
+ log.info("url {}", request.url());
+ log.info("content type {}", request.header("Content-Type"));
+ // Assert
+ assertNotNull(request);
+ assertEquals(url, request.url().toString());
+ assertEquals("POST", request.method());
+ assertEquals("application/json", request.header("Content-Type"));
+ assertEquals(apiKey, request.header("X-PrivateKey"));
+ assertEquals(apiheader.getString("clientLocalIP"), request.header("X-ClientLocalIP"));
+ assertEquals(apiheader.getString("clientPublicIP"), request.header("X-ClientPublicIP"));
+ assertEquals(apiheader.getString("macAddress"), request.header("X-MACAddress"));
+ assertEquals(apiheader.getString("accept"), request.header("Accept"));
+ assertEquals(apiheader.getString("userType"), request.header("X-UserType"));
+ assertEquals(apiheader.getString("sourceID"), request.header("X-SourceID"));
+
+ }
+
+
+ @Test
+ public void test_valid_apiKey_url_accessToken() throws IOException {
+
+ String apiKey = "validApiKey";
+ String url = "https://example.com/api";
+ String accessToken = "validAccessToken";
+
+ SmartAPIRequestHandler handler = new SmartAPIRequestHandler(null);
+ JSONObject apiheader = handler.apiHeaders();
+
+ Request request = handler.createGetRequest(apiKey, url, accessToken);
+
+ assertEquals(url, request.url().toString());
+ assertEquals("Bearer " + accessToken, request.header("Authorization"));
+ assertEquals(apiKey, request.header("X-PrivateKey"));
+ assertEquals(apiheader.getString("clientLocalIP"), request.header("X-ClientLocalIP"));
+ assertEquals(apiheader.getString("clientPublicIP"), request.header("X-ClientPublicIP"));
+ assertEquals(apiheader.getString("macAddress"), request.header("X-MACAddress"));
+ assertEquals(apiheader.getString("accept"), request.header("Accept"));
+ assertEquals(apiheader.getString("userType"), request.header("X-UserType"));
+ assertEquals(apiheader.getString("sourceID"), request.header("X-SourceID"));
+ }
+
+ @Test
+ public void testApiHeadersWithValidValues() {
+
+ SmartAPIRequestHandler handler = new SmartAPIRequestHandler(null);
+ JSONObject headers = handler.apiHeaders();
+
+ assertNotNull(headers);
+ assertEquals("127.0.1.1", headers.getString("clientLocalIP")); // chnage according to each machine
+ assertEquals("103.59.212.254", headers.getString("clientPublicIP")); // chnage according to each machine
+ assertEquals("02-42-54-06-EC-5D", headers.getString("macAddress")); // chnage according to each machine
+ assertEquals("application/json", headers.getString("accept"));
+ assertEquals("USER", headers.getString("userType"));
+ assertEquals("WEB", headers.getString("sourceID"));
+ }
+
+ @Test
+ public void test_createDeleteRequest_withUrlAndParams() {
+
+ SmartAPIRequestHandler handler = new SmartAPIRequestHandler(null);
+ String url = "https://example.com/api";
+ Map params = new HashMap<>();
+ params.put("param1", "value1");
+ params.put("param2", "value2");
+ String apiKey = "API_KEY";
+ String accessToken = "ACCESS_TOKEN";
+
+ Request request = handler.createDeleteRequest(url, params, apiKey, accessToken);
+
+ assertNotNull(request);
+ assertEquals("DELETE", request.method());
+ assertEquals(url+"?param1=value1¶m2=value2", request.url().toString());
+ assertEquals(USER_AGENT, request.header("User-Agent"));
+ assertEquals("3", request.header("X-SmartAPI-Version"));
+ assertEquals("token " + apiKey + ":" + accessToken, request.header("Authorization"));
+
+ HttpUrl.Builder httpBuilder = HttpUrl.parse(url).newBuilder();
+ for (Map.Entry entry : params.entrySet()) {
+ httpBuilder.addQueryParameter(entry.getKey(), entry.getValue().toString());
+ }
+ assertEquals(httpBuilder.build(), request.url());
+ }
+}
+
diff --git a/src/test/java/com/angelbroking/smartapi/http/SmartApiResponseHandlerTest.java b/src/test/java/com/angelbroking/smartapi/http/SmartApiResponseHandlerTest.java
new file mode 100644
index 0000000..bea2ed2
--- /dev/null
+++ b/src/test/java/com/angelbroking/smartapi/http/SmartApiResponseHandlerTest.java
@@ -0,0 +1,91 @@
+package com.angelbroking.smartapi.http;
+
+import com.angelbroking.smartapi.http.SmartAPIResponseHandler;
+import com.angelbroking.smartapi.http.exceptions.SmartAPIException;
+import okhttp3.Response;
+import org.json.JSONObject;
+import org.junit.jupiter.api.Test;
+
+import java.io.IOException;
+
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+public class SmartApiResponseHandlerTest {
+
+
+
+ @Test
+ public void testSmartApiResponseHandlerResponse() {
+
+ Response response = mock(Response.class);
+ when(response.header("Content-Type")).thenReturn("application/json");
+
+ JSONObject jsonObject = new JSONObject();
+ jsonObject.put("status", "success");
+
+ try {
+ SmartAPIResponseHandler smartAPIResponseHandler = new SmartAPIResponseHandler();
+ JSONObject result = smartAPIResponseHandler.handle(response, jsonObject.toString());
+ assertNotNull(result);
+ } catch (SmartAPIException e) {
+ throw new RuntimeException(e);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+
+ @Test
+ public void testHandlerForOkStatusCode() throws SmartAPIException, IOException {
+
+ // Arrange
+ Response response = mock(Response.class);
+ when(response.code()).thenReturn(200);
+ String body = "{\"status\": true, \"data\": [{\"exchange\": \"NSE\", \"tradingsymbol\": \"INFY\", \"symboltoken\": \"12345\"}]}";
+
+ SmartAPIResponseHandler handler = new SmartAPIResponseHandler();
+
+ // Act
+ String result = handler.handler(response, body);
+
+ // Assert
+ assertEquals("Search successful. Found 1 trading symbols for the given query:\n1. exchange: NSE, tradingsymbol: INFY, symboltoken: 12345\n", result);
+ }
+
+ @Test
+ public void testHandlerMethodForBadRequestStatusResponse() throws SmartAPIException, IOException {
+
+ // Arrange
+ Response response = mock(Response.class);
+ when(response.code()).thenReturn(400);
+
+ SmartAPIResponseHandler handler = new SmartAPIResponseHandler();
+
+ // Act
+ String result = handler.handler(response, "");
+
+ // Assert
+ assertEquals("Bad request. Please provide valid input", result);
+ }
+
+ @Test
+ public void testHandlerMethodForIllegalArgumentException() {
+
+ // Arrange
+ Response response = mock(Response.class);
+ when(response.code()).thenReturn(500);
+
+ SmartAPIResponseHandler handler = new SmartAPIResponseHandler();
+
+ // Act & Assert
+ assertThrows(IllegalArgumentException.class, () -> {
+ handler.handler(response, "");
+ });
+
+ }
+}
diff --git a/src/test/java/com/angelbroking/smartapi/models/ModelTests.java b/src/test/java/com/angelbroking/smartapi/models/ModelTests.java
new file mode 100644
index 0000000..fd9aff1
--- /dev/null
+++ b/src/test/java/com/angelbroking/smartapi/models/ModelTests.java
@@ -0,0 +1,706 @@
+package com.angelbroking.smartapi.models;
+
+import com.angelbroking.smartapi.models.*;
+import com.angelbroking.smartapi.smartstream.models.BestTwentyData;
+import com.angelbroking.smartapi.smartstream.models.ExchangeType;
+import com.angelbroking.smartapi.smartstream.models.LTP;
+import com.angelbroking.smartapi.utils.Constants;
+import com.google.gson.annotations.SerializedName;
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+import org.junit.jupiter.api.Test;
+
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+
+import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+public class ModelTests {
+
+ /* ---------------- Profile Model Tests------------------------- */
+ @Test
+ public void testProfileModelWithAllValues() {
+
+ Profile profile = new Profile();
+ profile.setEmail("test@example.com");
+ profile.setUserName("John Doe");
+ profile.setBroker("ABC Broker");
+ profile.setExchanges(new String[]{"Exchange1", "Exchange2"});
+ profile.setProducts(new String[]{"Product1", "Product2"});
+
+ assertEquals("test@example.com", profile.getEmail());
+ assertEquals("John Doe", profile.getUserName());
+ assertEquals("ABC Broker", profile.getBroker());
+ assertArrayEquals(new String[]{"Exchange1", "Exchange2"}, profile.getExchanges());
+ assertArrayEquals(new String[]{"Product1", "Product2"}, profile.getProducts());
+ }
+
+ @Test
+ public void testGetEmailForProfileModel() {
+
+ Profile profile = new Profile();
+ profile.setEmail("test@example.com");
+
+ assertEquals("test@example.com", profile.getEmail());
+ }
+
+ @Test
+ public void testGetUserNameForProfileModel() {
+
+ Profile profile = new Profile();
+ profile.setUserName("John Doe");
+
+ assertEquals("John Doe", profile.getUserName());
+ }
+
+ @Test
+ public void testCreateProfileWithEmptyArrays() {
+
+ Profile profile = new Profile();
+ profile.setEmail("test@example.com");
+ profile.setUserName("John Doe");
+ profile.setBroker("ABC Broker");
+ profile.setExchanges(new String[]{});
+ profile.setProducts(new String[]{});
+
+ assertEquals("test@example.com", profile.getEmail());
+ assertEquals("John Doe", profile.getUserName());
+ assertEquals("ABC Broker", profile.getBroker());
+ assertArrayEquals(new String[]{}, profile.getExchanges());
+ assertArrayEquals(new String[]{}, profile.getProducts());
+ }
+
+ @Test
+ public void testCreateProfileWithNullArrays() {
+
+ Profile profile = new Profile();
+ profile.setEmail("test@example.com");
+ profile.setUserName("John Doe");
+ profile.setBroker("ABC Broker");
+ profile.setExchanges(null);
+ profile.setProducts(null);
+
+ assertEquals("test@example.com", profile.getEmail());
+ assertEquals("John Doe", profile.getUserName());
+ assertEquals("ABC Broker", profile.getBroker());
+ assertNull(profile.getExchanges());
+ assertNull(profile.getProducts());
+ }
+
+ @Test
+ public void testSetEmailToNull() {
+
+ Profile profile = new Profile();
+ profile.setEmail("test@example.com");
+ profile.setUserName("John Doe");
+ profile.setBroker("ABC Broker");
+
+ profile.setEmail(null);
+
+ assertNull(profile.getEmail());
+ }
+
+ @Test
+ public void testGetBroker() {
+
+ Profile profile = new Profile();
+ profile.setBroker("ABC Broker");
+
+ assertEquals("ABC Broker", profile.getBroker());
+ }
+
+ @Test
+ public void testGetExchanges() {
+
+ Profile profile = new Profile();
+ profile.setExchanges(new String[]{"Exchange1", "Exchange2"});
+
+ assertArrayEquals(new String[]{"Exchange1", "Exchange2"}, profile.getExchanges());
+ }
+
+ @Test
+ public void testGetProducts() {
+
+ Profile profile = new Profile();
+ profile.setProducts(new String[]{"Product1", "Product2"});
+
+ assertArrayEquals(new String[]{"Product1", "Product2"}, profile.getProducts());
+ }
+
+ /* ---------------- TokenSet Model Tests------------------------- */
+
+
+ @Test
+ public void testTokenSetModelWithAllValues() {
+
+ TokenSet tokenSet = new TokenSet();
+ tokenSet.setUserId("12345");
+ assertEquals("12345", tokenSet.getUserId());
+ }
+
+ @Test
+ public void testGetAccessTokenForTokenSetModel() {
+
+ TokenSet tokenSet = new TokenSet();
+ tokenSet.setAccessToken("abc123");
+ assertEquals("abc123", tokenSet.getAccessToken());
+ }
+
+ @Test
+ public void testGetRefreshTokenForTokenSetModel() {
+
+ TokenSet tokenSet = new TokenSet();
+ tokenSet.setRefreshToken("xyz789");
+ assertEquals("xyz789", tokenSet.getRefreshToken());
+ }
+
+ @Test
+ public void testNullUserIdForTokenSetModel() {
+
+ TokenSet tokenSet = new TokenSet();
+ assertNull(tokenSet.getUserId());
+ }
+
+ @Test
+ public void testNullAccessToken() {
+
+ TokenSet tokenSet = new TokenSet();
+ assertNull(tokenSet.getAccessToken());
+ }
+
+ @Test
+ public void testNullRefreshToken() {
+
+ TokenSet tokenSet = new TokenSet();
+ assertNull(tokenSet.getRefreshToken());
+ }
+
+ @Test
+ public void testUserModelWithAllValues() {
+
+ User user = new User();
+ user.setUserName("John Doe");
+ user.setUserId("123456");
+ user.setMobileNo("9876543210");
+ user.setBrokerName("Angel Broking");
+ user.setEmail("john.doe@example.com");
+ Date lastLoginTime = new Date();
+ user.setLastLoginTime(lastLoginTime);
+ user.setAccessToken("access_token");
+ user.setRefreshToken("refresh_token");
+ String[] products = {"Product 1", "Product 2"};
+ user.setProducts(products);
+ String[] exchanges = {"Exchange 1", "Exchange 2"};
+ user.setExchanges(exchanges);
+ user.setFeedToken("feed_token");
+
+ assertEquals("John Doe", user.getUserName());
+ assertEquals("123456", user.getUserId());
+ assertEquals("9876543210", user.getMobileNo());
+ assertEquals("Angel Broking", user.getBrokerName());
+ assertEquals("john.doe@example.com", user.getEmail());
+ assertEquals(lastLoginTime, user.getLastLoginTime());
+ assertEquals("access_token", user.getAccessToken());
+ assertEquals("refresh_token", user.getRefreshToken());
+ assertArrayEquals(products, user.getProducts());
+ assertArrayEquals(exchanges, user.getExchanges());
+ assertEquals("feed_token", user.getFeedToken());
+ }
+
+ @Test
+ public void testUserModelParseResponse() throws JSONException, ParseException {
+
+ JSONObject response = new JSONObject();
+ JSONObject data = new JSONObject();
+ data.put("name", "John Doe");
+ data.put("clientcode", "123456");
+ data.put("mobileno", "9876543210");
+ data.put("broker", "Angel Broking");
+ data.put("email", "john.doe@example.com");
+ data.put("lastlogintime", "2022-01-01 10:00:00");
+ data.put("accessToken", "access_token");
+ data.put("refreshToken", "refresh_token");
+ JSONArray products = new JSONArray();
+ products.put("Product 1");
+ products.put("Product 2");
+ data.put("products", products);
+ JSONArray exchanges = new JSONArray();
+ exchanges.put("Exchange 1");
+ exchanges.put("Exchange 2");
+ data.put("exchanges", exchanges);
+ data.put("feedToken", "feed_token");
+ response.put("data", data);
+
+ User user = new User();
+ user = user.parseResponse(response);
+
+ System.out.println(user.getUserName());
+ assertEquals("John Doe", user.getUserName());
+ assertEquals("123456", user.getUserId());
+ assertEquals("9876543210", user.getMobileNo());
+ assertEquals("Angel Broking", user.getBrokerName());
+ assertEquals("john.doe@example.com", user.getEmail());
+ SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+ Date lastLoginTime = format.parse("2022-01-01 10:00:00");
+ assertEquals(lastLoginTime, user.getLastLoginTime());
+ assertEquals("access_token", user.getAccessToken());
+ assertEquals("refresh_token", user.getRefreshToken());
+ assertArrayEquals(new String[]{"Product 1", "Product 2"}, user.getProducts());
+ assertArrayEquals(new String[]{"Exchange 1", "Exchange 2"}, user.getExchanges());
+ assertEquals("feed_token", user.getFeedToken());
+ }
+
+ @Test
+ public void testUserModelSetters() {
+
+ User user = new User();
+ user.setUserName("John Doe");
+ user.setUserId("123456");
+ user.setMobileNo("9876543210");
+ user.setBrokerName("Angel Broking");
+ user.setEmail("john.doe@example.com");
+ Date lastLoginTime = new Date();
+ user.setLastLoginTime(lastLoginTime);
+ user.setAccessToken("access_token");
+ user.setRefreshToken("refresh_token");
+ String[] products = {"Product 1", "Product 2"};
+ user.setProducts(products);
+ String[] exchanges = {"Exchange 1", "Exchange 2"};
+ user.setExchanges(exchanges);
+ user.setFeedToken("feed_token");
+
+ assertEquals("John Doe", user.getUserName());
+ assertEquals("123456", user.getUserId());
+ assertEquals("9876543210", user.getMobileNo());
+ assertEquals("Angel Broking", user.getBrokerName());
+ assertEquals("john.doe@example.com", user.getEmail());
+ assertEquals(lastLoginTime, user.getLastLoginTime());
+ assertEquals("access_token", user.getAccessToken());
+ assertEquals("refresh_token", user.getRefreshToken());
+ assertArrayEquals(products, user.getProducts());
+ assertArrayEquals(exchanges, user.getExchanges());
+ assertEquals("feed_token", user.getFeedToken());
+
+ // Update fields
+ user.setUserName("Jane Smith");
+ user.setUserId("654321");
+ user.setMobileNo("0123456789");
+ user.setBrokerName("XYZ Broking");
+ user.setEmail("jane.smith@example.com");
+ Date newLastLoginTime = new Date();
+ user.setLastLoginTime(newLastLoginTime);
+ user.setAccessToken("new_access_token");
+ user.setRefreshToken("new_refresh_token");
+ String[] newProducts = {"Product 3", "Product 4"};
+ user.setProducts(newProducts);
+ String[] newExchanges = {"Exchange 3", "Exchange 4"};
+ user.setExchanges(newExchanges);
+ user.setFeedToken("new_feed_token");
+
+ assertEquals("Jane Smith", user.getUserName());
+ assertEquals("654321", user.getUserId());
+ assertEquals("0123456789", user.getMobileNo());
+ assertEquals("XYZ Broking", user.getBrokerName());
+ assertEquals("jane.smith@example.com", user.getEmail());
+ assertEquals(newLastLoginTime, user.getLastLoginTime());
+ assertEquals("new_access_token", user.getAccessToken());
+ assertEquals("new_refresh_token", user.getRefreshToken());
+ assertArrayEquals(newProducts, user.getProducts());
+ assertArrayEquals(newExchanges, user.getExchanges());
+ assertEquals("new_feed_token", user.getFeedToken());
+ }
+
+ @Test
+ public void testUserWithNullResponse() throws JSONException {
+
+ JSONObject response = null;
+ JSONObject finalResponse = response;
+
+ User user = new User();
+ assertThrows(NullPointerException.class, () -> {
+ user.parseResponse(finalResponse);
+ });
+
+ response = new JSONObject();
+ assertThrows(NullPointerException.class, () -> {
+ user.parseResponse(finalResponse);
+ });
+
+ JSONObject data = new JSONObject();
+ response.put("data", data);
+ assertThrows(NullPointerException.class, () -> {
+ user.parseResponse(finalResponse);
+ });
+
+ data.put("name", "John Doe");
+ assertThrows(NullPointerException.class, () -> {
+ user.parseResponse(finalResponse);
+ });
+ }
+
+ @Test
+ public void testTradeModelWithAllFields() {
+
+ Trade trade = new Trade();
+ trade.tradeId = "123";
+ trade.orderId = "456";
+ trade.exchangeOrderId = "789";
+ trade.tradingSymbol = "AAPL";
+ trade.exchange = "NASDAQ";
+ trade.instrumentToken = "12345";
+ trade.product = "Equity";
+ trade.averagePrice = "100.50";
+ trade.quantity = "10";
+ trade.fillTimestamp = new Date();
+ trade.exchangeTimestamp = new Date();
+ trade.transactionType = "BUY";
+
+ assertNotNull(trade);
+ assertEquals("123", trade.tradeId);
+ assertEquals("456", trade.orderId);
+ assertEquals("789", trade.exchangeOrderId);
+ assertEquals("AAPL", trade.tradingSymbol);
+ assertEquals("NASDAQ", trade.exchange);
+ assertEquals("12345", trade.instrumentToken);
+ assertEquals("Equity", trade.product);
+ assertEquals("100.50", trade.averagePrice);
+ assertEquals("10", trade.quantity);
+ assertNotNull(trade.fillTimestamp);
+ assertNotNull(trade.exchangeTimestamp);
+ assertEquals("BUY", trade.transactionType);
+ }
+
+ @Test
+ public void testTradeModelSerializedNameAnnotationsMappedCorrectly() throws NoSuchFieldException {
+
+ Trade trade = new Trade();
+
+ assertNotNull(trade.getClass().getDeclaredField("tradeId").getAnnotation(SerializedName.class));
+ assertNotNull(trade.getClass().getDeclaredField("orderId").getAnnotation(SerializedName.class));
+ assertNotNull(trade.getClass().getDeclaredField("exchangeOrderId").getAnnotation(SerializedName.class));
+ assertNotNull(trade.getClass().getDeclaredField("tradingSymbol").getAnnotation(SerializedName.class));
+ assertNotNull(trade.getClass().getDeclaredField("exchange").getAnnotation(SerializedName.class));
+ assertNotNull(trade.getClass().getDeclaredField("instrumentToken").getAnnotation(SerializedName.class));
+ assertNotNull(trade.getClass().getDeclaredField("product").getAnnotation(SerializedName.class));
+ assertNotNull(trade.getClass().getDeclaredField("averagePrice").getAnnotation(SerializedName.class));
+ assertNotNull(trade.getClass().getDeclaredField("quantity").getAnnotation(SerializedName.class));
+ assertNotNull(trade.getClass().getDeclaredField("fillTimestamp").getAnnotation(SerializedName.class));
+ assertNotNull(trade.getClass().getDeclaredField("exchangeTimestamp").getAnnotation(SerializedName.class));
+ assertNotNull(trade.getClass().getDeclaredField("transactionType").getAnnotation(SerializedName.class));
+ }
+
+ @Test
+ public void testTradeModelDateFieldsParsedAndStoredCorrectly() {
+
+ Trade trade = new Trade();
+ Date fillTimestamp = new Date();
+ Date exchangeTimestamp = new Date();
+
+ trade.fillTimestamp = fillTimestamp;
+ trade.exchangeTimestamp = exchangeTimestamp;
+
+ assertEquals(fillTimestamp, trade.fillTimestamp);
+ assertEquals(exchangeTimestamp, trade.exchangeTimestamp);
+ }
+
+ @Test
+ public void testTradeModelCreatedWithNullValues() {
+
+ Trade trade = new Trade();
+
+ assertNull(trade.tradeId);
+ assertNull(trade.orderId);
+ assertNull(trade.exchangeOrderId);
+ assertNull(trade.tradingSymbol);
+ assertNull(trade.exchange);
+ assertNull(trade.instrumentToken);
+ assertNull(trade.product);
+ assertNull(trade.averagePrice);
+ assertNull(trade.quantity);
+ assertNull(trade.fillTimestamp);
+ assertNull(trade.exchangeTimestamp);
+ assertNull(trade.transactionType);
+ }
+
+ @Test
+ public void testTradeModelCreatedWithInvalidDateFormats() {
+
+ Trade trade = new Trade();
+ String invalidDateFormat = "2021-13-01";
+ try {
+ trade.fillTimestamp = new Date(invalidDateFormat);
+ trade.exchangeTimestamp = new Date(invalidDateFormat);
+ } catch (Exception e) {
+ assertNull(trade.fillTimestamp);
+ assertNull(trade.exchangeTimestamp);
+ }
+ }
+
+ @Test
+ public void testOrderModelWithAllFields() {
+
+ Order order = new Order();
+ order.disclosedQuantity = "10";
+ order.duration = "DAY";
+ order.tradingSymbol = "AAPL";
+ order.variety = "NORMAL";
+ order.orderType = "LIMIT";
+ order.triggerPrice = "100.00";
+ order.text = "Sample order";
+ order.price = "99.50";
+ order.status = "OPEN";
+ order.productType = "CNC";
+ order.exchange = "NSE";
+ order.orderId = "12345";
+ order.symbol = "AAPL";
+ order.updateTime = "2021-01-01 10:00:00";
+ order.exchangeTimestamp = "2021-01-01 10:00:00";
+ order.exchangeUpdateTimestamp = "2021-01-01 10:00:00";
+ order.averagePrice = "99.75";
+ order.transactionType = "BUY";
+ order.quantity = "100";
+ order.squareOff = "0";
+ order.stopLoss = "0";
+ order.trailingStopLoss = "0";
+ order.symbolToken = "123456";
+ order.instrumentType = "EQ";
+ order.strikePrice = "0.00";
+ order.optionType = "";
+ order.expiryDate = "";
+ order.lotSize = "";
+ order.cancelSize = "";
+ order.filledShares = "";
+ order.orderStatus = "";
+ order.unfilledShares = "";
+ order.fillId = "";
+ order.fillTime = "";
+
+ assertEquals("10", order.disclosedQuantity);
+ assertEquals("DAY", order.duration);
+ assertEquals("AAPL", order.tradingSymbol);
+ assertEquals("NORMAL", order.variety);
+ assertEquals("LIMIT", order.orderType);
+ assertEquals("100.00", order.triggerPrice);
+ assertEquals("Sample order", order.text);
+ assertEquals("99.50", order.price);
+ assertEquals("OPEN", order.status);
+ assertEquals("CNC", order.productType);
+ assertEquals("NSE", order.exchange);
+ assertEquals("12345", order.orderId);
+ assertEquals("AAPL", order.symbol);
+ assertEquals("2021-01-01 10:00:00", order.updateTime);
+ assertEquals("2021-01-01 10:00:00", order.exchangeTimestamp);
+ assertEquals("2021-01-01 10:00:00", order.exchangeUpdateTimestamp);
+ assertEquals("99.75", order.averagePrice);
+ assertEquals("BUY", order.transactionType);
+ assertEquals("100", order.quantity);
+ assertEquals("0", order.squareOff);
+ assertEquals("0", order.stopLoss);
+ assertEquals("0", order.trailingStopLoss);
+ assertEquals("123456", order.symbolToken);
+ assertEquals("EQ", order.instrumentType);
+ assertEquals("0.00", order.strikePrice);
+ assertEquals("", order.optionType);
+ assertEquals("", order.expiryDate);
+ assertEquals("", order.lotSize);
+ assertEquals("", order.cancelSize);
+ assertEquals("", order.filledShares);
+ assertEquals("", order.orderStatus);
+ assertEquals("", order.unfilledShares);
+ assertEquals("", order.fillId);
+ assertEquals("", order.fillTime);
+ }
+
+ @Test
+ public void testGttModelWithAllFields() {
+
+ Gtt gtt = new Gtt();
+ gtt.id = 123;
+ gtt.tradingSymbol = "AAPL";
+ gtt.symbolToken = "1111";
+ gtt.exchange = "NCE";
+ gtt.transactionType = "BUY";
+ gtt.productType = "Equity";
+ gtt.price = 100;
+ gtt.quantity = 10;
+ gtt.triggerPrice = 100;
+ gtt.disclosedQty = 10;
+ gtt.timePeriod = 10;
+
+ assertNotNull(gtt);
+ assertEquals(123, (int) gtt.id);
+ assertEquals("AAPL", gtt.tradingSymbol);
+ assertEquals("1111", gtt.symbolToken);
+ assertEquals("NCE", gtt.exchange);
+ assertEquals("BUY", gtt.transactionType);
+ assertEquals("Equity", gtt.productType);
+ assertEquals(100, (int) gtt.price);
+ assertEquals(10, (int) gtt.quantity);
+ assertEquals(100,(int) gtt.triggerPrice);
+ assertEquals(10, (int) gtt.disclosedQty);
+ assertEquals(10, (int) gtt.timePeriod);
+ }
+
+ @Test
+ public void testConstantsFields() {
+
+ assertFalse(Constants.PRODUCT_DELIVERY.isEmpty());
+ assertFalse(Constants.PRODUCT_INTRADAY.isEmpty());
+ assertFalse(Constants.PRODUCT_MARGIN.isEmpty());
+ assertFalse(Constants.PRODUCT_BO.isEmpty());
+ assertFalse(Constants.PRODUCT_CARRYFORWARD.isEmpty());
+
+ assertFalse(Constants.ORDER_TYPE_MARKET.isEmpty());
+ assertFalse(Constants.ORDER_TYPE_LIMIT.isEmpty());
+ assertFalse(Constants.ORDER_TYPE_STOPLOSS_LIMIT.isEmpty());
+ assertFalse(Constants.ORDER_TYPE_STOPLOSS_MARKET.isEmpty());
+
+ assertFalse(Constants.VARIETY_NORMAL.isEmpty());
+ assertFalse(Constants.VARIETY_AMO.isEmpty());
+ assertFalse(Constants.VARIETY_STOPLOSS.isEmpty());
+ assertFalse(Constants.VARIETY_ROBO.isEmpty());
+
+ assertFalse(Constants.TRANSACTION_TYPE_BUY.isEmpty());
+ assertFalse(Constants.TRANSACTION_TYPE_SELL.isEmpty());
+
+ assertFalse(Constants.DURATION_DAY.isEmpty());
+ assertFalse(Constants.DURATION_IOC.isEmpty());
+
+ assertFalse(Constants.EXCHANGE_NSE.isEmpty());
+ assertFalse(Constants.EXCHANGE_BSE.isEmpty());
+ assertFalse(Constants.EXCHANGE_NFO.isEmpty());
+ assertFalse(Constants.EXCHANGE_CDS.isEmpty());
+ assertFalse(Constants.EXCHANGE_NCDEX.isEmpty());
+ assertFalse(Constants.EXCHANGE_MCX.isEmpty());
+ }
+
+ @Test
+ public void testOrderParamsWithAllFields() {
+
+ OrderParams orderParams = new OrderParams();
+ orderParams.orderid = "12345";
+ orderParams.exchange = "NSE";
+ orderParams.symboltoken = "123";
+ orderParams.transactiontype = "BUY";
+ orderParams.quantity = 100;
+ orderParams.price = 100.0;
+ orderParams.producttype = "NRML";
+ orderParams.ordertype = "LIMIT";
+ orderParams.duration = "DAY";
+ orderParams.variety = "NORMAL";
+ orderParams.tradingsymbol = "AAPL";
+ orderParams.triggerprice = "150.0";
+ orderParams.squareoff = "160.0";
+ orderParams.stoploss = "140.0";
+ assertNotNull(orderParams);
+ }
+
+ @Test
+ public void testGttParamsWithNullValues() {
+
+ GttParams gttParams = new GttParams();
+ assertNotNull(gttParams);
+ assertNull(gttParams.id);
+ assertNull(gttParams.tradingsymbol);
+ assertNull(gttParams.exchange);
+ assertNull(gttParams.transactiontype);
+ assertNull(gttParams.producttype);
+ assertNull(gttParams.price);
+ assertNull(gttParams.qty);
+ assertNull(gttParams.triggerprice);
+ assertNull(gttParams.disclosedqty);
+ assertNull(gttParams.timeperiod);
+ assertNull(gttParams.symboltoken);
+ }
+
+ @Test
+ public void testSearchScripResponse() {
+
+ SearchScripResponseDTO responseDTO = new SearchScripResponseDTO();
+ responseDTO.setTradingSymbol("ABC");
+ responseDTO.setExchange("NYSE");
+ responseDTO.setSymbolToken("12345");
+
+ assertEquals("ABC", responseDTO.getTradingSymbol());
+ assertEquals("NYSE", responseDTO.getExchange());
+ assertEquals("12345", responseDTO.getSymbolToken());
+ }
+
+ @Test
+ public void testOrderModelResponse() {
+
+ Order order = new Order();
+ order.disclosedQuantity = "10";
+ order.duration = "DAY";
+ order.tradingSymbol = "AAPL";
+ order.variety = "NORMAL";
+ order.orderType = "LIMIT";
+ order.triggerPrice = "100.0";
+ order.text = "Sample order";
+ order.price = "99.0";
+ order.status = "OPEN";
+ order.productType = "CNC";
+ order.exchange = "NSE";
+ order.orderId = "12345";
+ order.symbol = "AAPL";
+ order.updateTime = "2021-01-01 10:00:00";
+ order.exchangeTimestamp = "2021-01-01 10:00:00";
+ order.exchangeUpdateTimestamp = "2021-01-01 10:00:00";
+ order.averagePrice = "98.0";
+ order.transactionType = "BUY";
+ order.quantity = "5";
+ order.squareOff = "100.0";
+ order.stopLoss = "95.0";
+ order.trailingStopLoss = "90.0";
+ order.symbolToken = "AAPL";
+ order.instrumentType = "EQUITY";
+ order.strikePrice = "0.0";
+ order.optionType = "";
+ order.expiryDate = "";
+ order.lotSize = "";
+ order.cancelSize = "";
+ order.filledShares = "";
+ order.orderStatus = "";
+ order.unfilledShares = "";
+ order.fillId = "";
+ order.fillTime = "";
+
+ String expected = "Order [disclosedQuantity=10, duration=DAY, tradingSymbol=AAPL, variety=NORMAL, orderType=LIMIT, triggerPrice=100.0, text=Sample order, price=99.0, status=OPEN, productType=CNC, exchange=NSE, orderId=12345, symbol=AAPL, updateTime=2021-01-01 10:00:00, exchangeTimestamp=2021-01-01 10:00:00, exchangeUpdateTimestamp=2021-01-01 10:00:00, averagePrice=98.0, transactionType=BUY, quantity=5, squareOff=100.0, stopLoss=95.0, trailingStopLoss=90.0, symbolToken=AAPL, instrumentType=EQUITY, strikePrice=0.0, optionType=, expiryDate=, lotSize=, cancelSize=, filledShares=, orderStatus=, unfilledShares=, fillId=, fillTime=]";
+
+ assertEquals(expected, order.toString());
+ }
+
+ @Test
+ public void testBESTTwentyData() {
+
+ BestTwentyData data = new BestTwentyData(10, 20, (short) 5);
+ assertEquals(10, data.getQuantity());
+ assertEquals(20, data.getPrice());
+ assertEquals(5, data.getNumberOfOrders());
+ }
+
+ @Test
+ public void testGettersAndSettersMethodOfBestTwentyDataModel() {
+
+ BestTwentyData data = new BestTwentyData();
+ data.setQuantity(10);
+ data.setPrice(20);
+ data.setNumberOfOrders((short) 5);
+ assertEquals(10, data.getQuantity());
+ assertEquals(20, data.getPrice());
+ assertEquals(5, data.getNumberOfOrders());
+ }
+
+ @Test
+ public void testToStringMethodOfBestTwentyData() {
+
+ BestTwentyData data = new BestTwentyData(10, 20, (short) 5);
+ String expected = "BestTwentyData(quantity=10, price=20, numberOfOrders=5)";
+ assertEquals(expected, data.toString());
+ }
+}
diff --git a/src/test/java/com/angelbroking/smartapi/SmartConnectTest.java b/src/test/java/com/angelbroking/smartapi/smartconnet/SmartConnectTest.java
similarity index 83%
rename from src/test/java/com/angelbroking/smartapi/SmartConnectTest.java
rename to src/test/java/com/angelbroking/smartapi/smartconnet/SmartConnectTest.java
index 14c4b9e..2d8bf7f 100644
--- a/src/test/java/com/angelbroking/smartapi/SmartConnectTest.java
+++ b/src/test/java/com/angelbroking/smartapi/smartconnet/SmartConnectTest.java
@@ -1,8 +1,16 @@
-package com.angelbroking.smartapi;
+package com.angelbroking.smartapi.smartconnet;
+import com.angelbroking.smartapi.Routes;
+import com.angelbroking.smartapi.SmartConnect;
import com.angelbroking.smartapi.http.SmartAPIRequestHandler;
import com.angelbroking.smartapi.http.exceptions.DataException;
import com.angelbroking.smartapi.http.exceptions.SmartAPIException;
+import com.angelbroking.smartapi.models.Order;
+import com.angelbroking.smartapi.models.OrderParams;
+import com.angelbroking.smartapi.models.User;
+import com.angelbroking.smartapi.smartstream.models.SmartStreamError;
+import com.angelbroking.smartapi.utils.Constants;
+import com.warrenstrange.googleauth.GoogleAuthenticator;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONArray;
import org.json.JSONException;
@@ -28,7 +36,10 @@
import static com.angelbroking.smartapi.utils.Constants.JSON_EXCEPTION_OCCURRED;
import static com.angelbroking.smartapi.utils.Constants.SMART_API_EXCEPTION_ERROR_MSG;
import static com.angelbroking.smartapi.utils.Constants.SMART_API_EXCEPTION_OCCURRED;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;
@@ -36,6 +47,7 @@
@RunWith(MockitoJUnitRunner.Silent.class)
@Slf4j
public class SmartConnectTest {
+
@Mock
private SmartAPIRequestHandler smartAPIRequestHandler;
@@ -309,6 +321,7 @@ public void testMarketDataOHLC_Failure() throws SmartAPIException, IOException {
}
private JSONObject getMarketDataRequest(String mode) {
+
JSONObject payload = new JSONObject();
payload.put("mode", mode);
JSONObject exchangeTokens = new JSONObject();
@@ -319,5 +332,72 @@ private JSONObject getMarketDataRequest(String mode) {
return payload;
}
+
+ @Test
+ public void testSmartConnectObjectWithApiKey() {
+
+ SmartConnect smartConnect = new SmartConnect("API_KEY");
+ assertNotNull(smartConnect);
+ }
+
+ @Test
+ public void testSmartConnectObjectWithApiKeyAccessTokenRefreshToken() {
+
+ SmartConnect smartConnect = new SmartConnect("apiKey", "accessToken", "refreshToken");
+ assertNotNull(smartConnect);
+ assertEquals("apiKey", smartConnect.getApiKey());
+ assertEquals("accessToken", smartConnect.getAccessToken());
+ assertEquals("refreshToken", smartConnect.getPublicToken());
+ }
+ @Test
+ public void testSetApiKeyOfSmartConnect() {
+
+ SmartConnect smartConnect = new SmartConnect();
+ smartConnect.setApiKey("apiKey");
+ smartConnect.setAccessToken("accessToken");
+ smartConnect.setRefreshToken("refreshToken");
+ assertEquals("apiKey", smartConnect.getApiKey());
+ assertEquals("accessToken", smartConnect.getAccessToken());
+ assertEquals("refreshToken", smartConnect.getPublicToken());
+ }
+
+ @Test
+ public void testSmartConnectWithNullValues() {
+
+ SmartConnect smartConnect = new SmartConnect();
+ smartConnect.setApiKey(null);
+ smartConnect.setAccessToken(null);
+ smartConnect.setRefreshToken(null);
+ assertThrows(NullPointerException.class, () -> smartConnect.getApiKey());
+ assertThrows(NullPointerException.class, () -> smartConnect.getAccessToken());
+ assertThrows(NullPointerException.class, () -> smartConnect.getUserId());
+ assertThrows(NullPointerException.class, () -> smartConnect.getPublicToken());
+ }
+
+ @Test
+ public void testGenerateSession() {
+
+ SmartConnect smartConnect = new SmartConnect("apiKey", "accessToken", "refreshToken");
+ assertNull(smartConnect.generateSession("invalidClientCode", "password", "totp"));
+ }
+
+ @Test
+ public void testReturnApiKeyIfNotNull() {
+
+ SmartConnect smartConnect = new SmartConnect("apiKey");
+ String result = smartConnect.getApiKey();
+ assertEquals("apiKey", result);
+ }
+
+ @Test
+ public void testThrowsNullPointerExceptionIfApiKeyIsNull() {
+
+ SmartConnect smartConnect = new SmartConnect();
+ assertThrows(NullPointerException.class, () -> {
+ smartConnect.getApiKey();
+ });
+ }
+
}
+
diff --git a/src/test/java/com/angelbroking/smartapi/smartticker/SmartWebSocketTest.java b/src/test/java/com/angelbroking/smartapi/smartticker/SmartWebSocketTest.java
new file mode 100644
index 0000000..d349e8d
--- /dev/null
+++ b/src/test/java/com/angelbroking/smartapi/smartticker/SmartWebSocketTest.java
@@ -0,0 +1,170 @@
+package com.angelbroking.smartapi.smartticker;
+
+import com.angelbroking.smartapi.http.exceptions.SmartAPIException;
+import com.angelbroking.smartapi.smartTicker.*;
+import com.neovisionaries.ws.client.WebSocket;
+import com.neovisionaries.ws.client.WebSocketAdapter;
+import org.json.JSONArray;
+import org.junit.jupiter.api.Test;
+
+import java.io.IOException;
+import java.lang.reflect.Field;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+import static org.mockito.Mockito.*;
+
+public class SmartWebSocketTest {
+
+ @Test
+ public void testWebSocketWithAllFields() {
+ // Arrange
+ String clientId = "123";
+ String jwtToken = "token";
+ String apiKey = "key";
+ String actionType = "action";
+ String feedType = "feed";
+
+ // Act
+ SmartWebsocket websocket = new SmartWebsocket(clientId, jwtToken, apiKey, actionType, feedType);
+
+ // Assert
+ assertNotNull(websocket);
+ }
+
+ @Test
+ public void testSetListener() {
+ // Arrange
+ SmartWebsocket websocket = new SmartWebsocket("123", "token", "key", "action", "feed");
+
+ // Act
+ websocket.setOnErrorListener(new SmartWSOnError() {
+ @Override
+ public void onError(Exception exception) {}
+
+ @Override
+ public void onError(SmartAPIException smartAPIException) {}
+
+ @Override
+ public void onError(String error) {}
+ });
+
+ websocket.setOnTickerArrivalListener(new SmartWSOnTicks() {
+ @Override
+ public void onTicks(JSONArray ticks) {}
+ });
+
+ websocket.setOnConnectedListener(new SmartWSOnConnect() {
+ @Override
+ public void onConnected() {}
+ });
+
+ websocket.setOnDisconnectedListener(new SmartWSOnDisconnect() {
+ @Override
+ public void onDisconnected() {}
+ });
+
+ // Assert
+ assertNotNull(websocket);
+ }
+
+ @Test
+ public void testSetOnErrorListener_success() throws NoSuchFieldException, IllegalAccessException {
+ SmartWebsocket websocket = new SmartWebsocket("clientId", "jwtToken", "apiKey", "actionType", "feedType");
+ SmartWSOnError listener = new SmartWSOnError() {
+ @Override
+ public void onError(Exception exception) {}
+
+ @Override
+ public void onError(SmartAPIException smartAPIException) {}
+
+ @Override
+ public void onError(String error) {}
+ };
+
+ // Use reflection to access the private field onErrorListener
+ Field onErrorListenerField = SmartWebsocket.class.getDeclaredField("onErrorListener");
+ onErrorListenerField.setAccessible(true); // Make it accessible
+ onErrorListenerField.set(websocket, listener); // Set the private field with the listener
+
+ SmartWSOnError actualListener = (SmartWSOnError) onErrorListenerField.get(websocket);
+
+ assertEquals(listener, actualListener);
+ }
+
+
+
+ @Test
+ public void test_setOnTickerArrivalListener_validListener() throws NoSuchFieldException, IllegalAccessException {
+ // Initialize the SmartWebsocket object
+ SmartWebsocket websocket = new SmartWebsocket("clientId", "jwtToken", "apiKey", "actionType", "feedType");
+
+ // Create a valid SmartWSOnTicks listener
+ SmartWSOnTicks listener = new SmartWSOnTicks() {
+ @Override
+ public void onTicks(JSONArray ticks) {
+ // Listener implementation
+ }
+ };
+
+ // Use reflection to access the private field onTickerArrivalListener
+ Field onTickerArrivalListenerField = SmartWebsocket.class.getDeclaredField("onTickerArrivalListener");
+ onTickerArrivalListenerField.setAccessible(true); // Make it accessible
+ onTickerArrivalListenerField.set(websocket, listener); // Set the private field with the listener
+
+ SmartWSOnTicks actualListener = (SmartWSOnTicks) onTickerArrivalListenerField.get(websocket);
+
+ assertEquals(listener, actualListener);
+ }
+
+ @Test
+ public void test_setOnConnectedListener_success() throws NoSuchFieldException, IllegalAccessException {
+ // Initialize the SmartWebsocket object
+ SmartWebsocket websocket = new SmartWebsocket("clientId", "jwtToken", "apiKey", "actionType", "feedType");
+
+ // Create a valid SmartWSOnConnect listener
+ SmartWSOnConnect listener = new SmartWSOnConnect() {
+ @Override
+ public void onConnected() {
+ // Listener implementation
+ }
+ };
+
+ // Use reflection to access the private field onConnectedListener
+ Field onConnectedListenerField = SmartWebsocket.class.getDeclaredField("onConnectedListener");
+ onConnectedListenerField.setAccessible(true); // Make it accessible
+ onConnectedListenerField.set(websocket, listener); // Set the private field with the listener
+
+ SmartWSOnConnect actualListener = (SmartWSOnConnect) onConnectedListenerField.get(websocket);
+
+ assertEquals(listener, actualListener);
+ }
+
+ @Test
+ public void test_on_connected_listener_called() {
+ SmartWebsocket websocket = new SmartWebsocket("clientId", "jwtToken", "apiKey", "actionType", "feedType");
+ WebSocketAdapter adapter = websocket.getWebsocketAdapter();
+
+ WebSocket websocketMock = mock(WebSocket.class);
+ Map> headers = new HashMap<>();
+
+ SmartWSOnConnect onConnectedListenerMock = mock(SmartWSOnConnect.class);
+ websocket.setOnConnectedListener(onConnectedListenerMock);
+
+ assertDoesNotThrow(() -> adapter.onConnected(websocketMock, headers));
+ verify(onConnectedListenerMock, times(1)).onConnected();
+ }
+
+ @Test
+ public void test_decompressMethod() throws IOException {
+ byte[] compressedTxt = {120, -100, 75, 44, 73, 45, 46, 1, 0, 0, -1, -1};
+ byte[] expected = {97, 116, 101, 115, 116};
+
+ byte[] result = SmartWebsocket.decompress(compressedTxt);
+
+ assertArrayEquals(expected, result);
+ }
+}
diff --git a/src/test/java/com/angelbroking/smartapi/ticker/SmartApiTickerTest.java b/src/test/java/com/angelbroking/smartapi/ticker/SmartApiTickerTest.java
new file mode 100644
index 0000000..d5bd5ac
--- /dev/null
+++ b/src/test/java/com/angelbroking/smartapi/ticker/SmartApiTickerTest.java
@@ -0,0 +1,121 @@
+package com.angelbroking.smartapi.ticker;
+
+import com.angelbroking.smartapi.smartstream.models.BestTwentyData;
+import com.angelbroking.smartapi.ticker.OnConnect;
+import com.angelbroking.smartapi.ticker.OnTicks;
+import com.angelbroking.smartapi.ticker.SmartAPITicker;
+import com.angelbroking.smartapi.utils.ByteUtils;
+import org.json.JSONArray;
+import org.junit.jupiter.api.Test;
+
+import java.lang.reflect.Field;
+import java.nio.ByteBuffer;
+
+import static com.angelbroking.smartapi.utils.Constants.*;
+import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+public class SmartApiTickerTest {
+
+ @Test
+ public void testSmartApiTickerWithAllFields() {
+
+ // Arrange
+ String clientId = "client_id";
+ String feedToken = "feed_token";
+ String script = "script";
+ String task = "task";
+
+ // Act
+ SmartAPITicker ticker = new SmartAPITicker(clientId, feedToken, script, task);
+
+ // Assert
+ assertNotNull(ticker);
+ }
+
+ @Test
+ public void testSetListenerOfSmartAPITicker() {
+
+ // Arrange
+ String clientId = "client_id";
+ String feedToken = "feed_token";
+ String script = "script";
+ String task = "task";
+
+ SmartAPITicker ticker = new SmartAPITicker(clientId, feedToken, script, task);
+
+ // Act
+ ticker.setOnTickerArrivalListener(new OnTicks() {
+ @Override
+ public void onTicks(JSONArray ticks) {
+ // Test implementation
+ }
+ });
+
+ ticker.setOnConnectedListener(new OnConnect() {
+ @Override
+ public void onConnected() {
+ // Test implementation
+ }
+ });
+
+ // Assert
+ assertNotNull(ticker);
+ }
+
+
+ @Test
+ public void testUnableToCloseWebSocketConnectionOfSmartAPITicker() {
+
+ // Arrange
+ String clientId = "client_id";
+ String feedToken = "feed_token";
+ String script = "script";
+ String task = "task";
+
+ SmartAPITicker ticker = new SmartAPITicker(clientId, feedToken, script, task);
+
+ // Act
+ ticker.disconnect();
+
+ // Assert
+ assertFalse(ticker.isConnectionOpen());
+ }
+
+
+ @Test
+ public void testBestTwentyDataMethod() {
+
+ ByteBuffer buffer = ByteBuffer.allocate(100000); // for testing
+ for (int i = 0; i < NUM_PACKETS_FOR_DEPTH; i++) {
+ int offset = BEST_TWENTY_BUY_DATA_POSITION + (i * PACKET_SIZE_FOR_DEPTH20);
+ buffer.putInt(offset + QUANTITY_OFFSET_FOR_DEPTH20, 100);
+ buffer.putInt(offset + PRICE_OFFSET_FOR_DEPTH20, 200);
+ buffer.putShort(offset + NUMBER_OF_ORDERS_OFFSET_FOR_DEPTH20, (short) 5);
+ }
+
+ BestTwentyData[] result = ByteUtils.getBestTwentyBuyData(buffer);
+
+ assertEquals(NUM_PACKETS_FOR_DEPTH, result.length);
+ for (BestTwentyData data : result) {
+ assertEquals(100, data.getQuantity());
+ assertEquals(200, data.getPrice());
+ assertEquals(5, data.getNumberOfOrders());
+ }
+ }
+
+ @Test
+ public void testBestTwentyDataWithNoValues() {
+
+ ByteBuffer buffer = ByteBuffer.allocate(10000);
+
+ BestTwentyData[] result = ByteUtils.getBestTwentyBuyData(buffer);
+
+ assertEquals(NUM_PACKETS_FOR_DEPTH, result.length);
+ for (BestTwentyData data : result) {
+ assertEquals(0, data.getQuantity());
+ assertEquals(0, data.getPrice());
+ assertEquals(0, data.getNumberOfOrders());
+ }
+ }
+}