Skip to content

Commit

Permalink
[REFACTOR]added more tests, trying to integrate sonar cloud again
Browse files Browse the repository at this point in the history
  • Loading branch information
pesolosep committed May 26, 2024
1 parent 07b81ee commit 208b92c
Show file tree
Hide file tree
Showing 16 changed files with 527 additions and 39 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/scorecard.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ on:
schedule:
- cron: "40 19 * * 5"
push:
branches: ["master", "subbox-management"]
branches: ["master"]

# Declare default permissions as read only.
permissions: read-all
Expand Down
6 changes: 3 additions & 3 deletions build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ val springBootVersion = "2.5.0"
val micrometerVersion = "1.12.5"
val dotenvVersion = "4.0.0"
val jwtVersion = "0.12.5"
val junitJupiterVersion = "5.9.1"

dependencies {
implementation("org.springframework.boot:spring-boot-starter-logging")
Expand All @@ -57,6 +58,8 @@ dependencies {
testImplementation("org.springframework.boot:spring-boot-starter-test")
runtimeOnly("io.micrometer:micrometer-registry-prometheus")
implementation("org.springframework.boot:spring-boot-starter-actuator")
testImplementation ("org.springframework.boot:spring-boot-starter-test")
testImplementation ("org.springframework.security:spring-security-test")
}


Expand Down Expand Up @@ -91,9 +94,6 @@ tasks.test{
}

tasks.jacocoTestReport {
classDirectories.setFrom(files(classDirectories.files.map {
fileTree(it) { exclude("**/*Application**") }
}))
dependsOn(tasks.test) // tests are required to run before generating the report
reports {
xml.required.set(true)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package id.ac.ui.cs.advprog.snackscription_subscriptionbox.config;


import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {

@Override
public AsyncTaskExecutor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5);
executor.setMaxPoolSize(10);
executor.setQueueCapacity(100);
executor.setThreadNamePrefix("Async-Executor-");
executor.initialize();
return executor;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ public SubscriptionBoxController(SubscriptionBoxService subscriptionBoxService,
this.jwtUtils = jwtUtils;
}

// Being kept for debugging purposes
private static final Logger logger = LoggerFactory.getLogger(SubscriptionBoxController.class);

private void validateToken(String token) throws IllegalAccessException {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@ public static SubscriptionBox convertDTOtoModel(SubscriptionBoxDTO subscriptionB
).orElse(null);

return new SubscriptionBoxFactory().create(
subscriptionBoxDTO.getId(),
subscriptionBoxDTO.getName(),
subscriptionBoxDTO.getType(),
subscriptionBoxDTO.getPrice(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,5 @@
public interface Factory <T> {
T create();

T create(String id, String name, String type, int price, List<Item> items , String description);
T create( String name, String type, int price, List<Item> items , String description);
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ public SubscriptionBox create(){
return new SubscriptionBox();
}

public SubscriptionBox create(String id, String name, String type, int price, List<Item> items, String description){
public SubscriptionBox create(String name, String type, int price, List<Item> items, String description){
return new SubscriptionBox( name, type, price, items, description);
}


}
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@ public SubscriptionBox( String name, String type, int price, List<Item> items, S
this.description = description;
}



public void setType(String type) {
if (type.equalsIgnoreCase("monthly") |
type.equalsIgnoreCase("quarterly") |
Expand Down Expand Up @@ -86,4 +88,4 @@ public void setPrice(int price) {

}
}
;

Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package id.ac.ui.cs.advprog.snackscription_subscriptionbox.config;

import org.junit.jupiter.api.Test;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;


class AsyncConfigTest {

@Test
void testAsyncExecutor() {

AsyncConfig asyncConfig = new AsyncConfig();

AsyncTaskExecutor executor = asyncConfig.getAsyncExecutor();

assertNotNull(executor);

assertEquals(5, ((ThreadPoolTaskExecutor) executor).getCorePoolSize());
assertEquals(10, ((ThreadPoolTaskExecutor) executor).getMaxPoolSize());
assertEquals(100, ((ThreadPoolTaskExecutor) executor).getQueueCapacity());
assertEquals("Async-Executor-", ((ThreadPoolTaskExecutor) executor).getThreadNamePrefix());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
package id.ac.ui.cs.advprog.snackscription_subscriptionbox.config;


import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.security.core.context.SecurityContextHolder;
import id.ac.ui.cs.advprog.snackscription_subscriptionbox.utils.JWTUtils;

import java.io.IOException;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.Mockito.*;

class JWTAuthFilterTest {

@Mock
private JWTUtils jwtUtils;

@Mock
private HttpServletRequest request;

@Mock
private HttpServletResponse response;

@Mock
private FilterChain filterChain;

@InjectMocks
private JWTAuthFilter jwtAuthFilter;

@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
SecurityContextHolder.clearContext();
}

@Test
void doFilterInternal_MissingAuthHeader() throws ServletException, IOException {
when(request.getHeader("Authorization")).thenReturn(null);

jwtAuthFilter.doFilterInternal(request, response, filterChain);

verify(filterChain, times(1)).doFilter(request, response);
assertNull(SecurityContextHolder.getContext().getAuthentication());
}

@Test
void doFilterInternal_BlankAuthHeader() throws ServletException, IOException {
when(request.getHeader("Authorization")).thenReturn("");

jwtAuthFilter.doFilterInternal(request, response, filterChain);

verify(filterChain, times(1)).doFilter(request, response);
assertNull(SecurityContextHolder.getContext().getAuthentication());
}

@Test
void doFilterInternal_InvalidToken() throws ServletException, IOException {
String invalidToken = "Bearer invalidToken";
when(request.getHeader("Authorization")).thenReturn(invalidToken);
when(jwtUtils.isTokenValid(anyString())).thenReturn(false);

jwtAuthFilter.doFilterInternal(request, response, filterChain);

verify(filterChain, times(1)).doFilter(request, response);
assertNull(SecurityContextHolder.getContext().getAuthentication());
}

@Test
void doFilterInternal_ValidToken() throws ServletException, IOException {
String validToken = "Bearer validToken";
when(request.getHeader("Authorization")).thenReturn(validToken);
when(jwtUtils.isTokenValid("validToken")).thenReturn(true);
when(jwtUtils.extractRole("validToken")).thenReturn("USER");

jwtAuthFilter.doFilterInternal(request, response, filterChain);

verify(filterChain, times(1)).doFilter(request, response);
assertEquals("USER", SecurityContextHolder.getContext().getAuthentication().getAuthorities().iterator().next().getAuthority());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
package id.ac.ui.cs.advprog.snackscription_subscriptionbox.dto;

import id.ac.ui.cs.advprog.snackscription_subscriptionbox.model.Item;
import id.ac.ui.cs.advprog.snackscription_subscriptionbox.model.SubscriptionBox;
import id.ac.ui.cs.advprog.snackscription_subscriptionbox.factory.SubscriptionBoxFactory;
import org.junit.jupiter.api.Test;

import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;

class DTOMapperTest {

@Test
void testConvertModelToDto() {
Item item1 = new Item("1", "Item 1", 10);
Item item2 = new Item("2", "Item 2", 20);
List<Item> items = List.of(item1, item2);

SubscriptionBox model = new SubscriptionBox( "Basic", "Monthly", 100, items, "Description");
SubscriptionBoxDTO dto = DTOMapper.convertModelToDto(model);

assertThat(dto.getId()).isEqualTo(model.getId());
assertThat(dto.getName()).isEqualTo("Basic");
assertThat(dto.getType()).isEqualTo("MONTHLY");
assertThat(dto.getPrice()).isEqualTo(100);
assertThat(dto.getItems()).hasSize(2);
assertThat(dto.getDescription()).isEqualTo("Description");
}

@Test
void testConvertDTOtoModel() {
ItemDTO item1 = new ItemDTO("1", "Item 1", 10);
ItemDTO item2 = new ItemDTO("2", "Item 2", 20);
List<ItemDTO> items = List.of(item1, item2);

SubscriptionBoxDTO dto = new SubscriptionBoxDTO("1","Basic", "Monthly", 100, items, "Description");
SubscriptionBox model = DTOMapper.convertDTOtoModel(dto);
assertThat(model.getName()).isEqualTo("Basic");
assertThat(model.getType()).isEqualTo("MONTHLY");
assertThat(model.getPrice()).isEqualTo(100);
assertThat(model.getItems()).hasSize(2);
assertThat(model.getDescription()).isEqualTo("Description");
}

@Test
void testUpdateSubscriptionBox() {
SubscriptionBox model = new SubscriptionBox("1", "Monthly", 100, null, "Old Description");
ItemDTO item1 = new ItemDTO("1", "Item 1", 10);
List<ItemDTO> items = List.of(item1);

SubscriptionBoxDTO dto = new SubscriptionBoxDTO("1", "Basic", "Monthly", 150, items, "New Description");
SubscriptionBox updatedModel = DTOMapper.updateSubscriptionBox(model, dto);

assertThat(updatedModel.getPrice()).isEqualTo(150);
assertThat(updatedModel.getDescription()).isEqualTo("New Description");
assertThat(updatedModel.getItems()).hasSize(1);
}

@Test
void testConvertItemToDto() {
Item item = new Item("1", "Item 1", 10);
ItemDTO dto = DTOMapper.convertItemToDto(item);

assertThat(dto.getId()).isEqualTo("1");
assertThat(dto.getName()).isEqualTo("Item 1");
assertThat(dto.getQuantity()).isEqualTo(10);
}

@Test
void testConvertDtoToItem() {
ItemDTO dto = new ItemDTO("1", "Item 1", 10);
Item item = DTOMapper.convertDtoToItem(dto);

assertThat(item.getId()).isEqualTo("1");
assertThat(item.getName()).isEqualTo("Item 1");
assertThat(item.getQuantity()).isEqualTo(10);
}

@Test
void testUpdateItem() {
Item item = new Item("1", "Old Item", 5);
ItemDTO dto = new ItemDTO("1", "New Item", 10);
Item updatedItem = DTOMapper.updateItem(item, dto);

assertThat(updatedItem.getName()).isEqualTo("New Item");
assertThat(updatedItem.getQuantity()).isEqualTo(10);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package id.ac.ui.cs.advprog.snackscription_subscriptionbox.dto;

import org.junit.jupiter.api.Test;

import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;

class SubscriptionBoxDTOTest {

@Test
void testNoArgsConstructor() {
SubscriptionBoxDTO dto = new SubscriptionBoxDTO();
assertThat(dto).isNotNull();
}

@Test
void testAllArgsConstructor() {
ItemDTO item1 = new ItemDTO("1", "Item 1", 10);
ItemDTO item2 = new ItemDTO("2", "Item 2", 20);
List<ItemDTO> items = List.of(item1, item2);

SubscriptionBoxDTO dto = new SubscriptionBoxDTO("1", "Basic", "Monthly", 100, items, "Description");

assertThat(dto.getId()).isEqualTo("1");
assertThat(dto.getName()).isEqualTo("Basic");
assertThat(dto.getType()).isEqualTo("Monthly");
assertThat(dto.getPrice()).isEqualTo(100);
assertThat(dto.getItems()).isEqualTo(items);
assertThat(dto.getDescription()).isEqualTo("Description");
}

@Test
void testSettersAndGetters() {
SubscriptionBoxDTO dto = new SubscriptionBoxDTO();

dto.setId("1");
dto.setName("Basic");
dto.setType("Monthly");
dto.setPrice(100);
ItemDTO item = new ItemDTO("1", "Item 1", 10);
dto.setItems(List.of(item));
dto.setDescription("Description");

assertThat(dto.getId()).isEqualTo("1");
assertThat(dto.getName()).isEqualTo("Basic");
assertThat(dto.getType()).isEqualTo("Monthly");
assertThat(dto.getPrice()).isEqualTo(100);
assertThat(dto.getItems()).containsExactly(item);
assertThat(dto.getDescription()).isEqualTo("Description");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ void testCreateSubscriptionBoxWithParameters() {
items.add(new Item()); // Assuming you have a constructor in Item class like this
items.add(new Item());

SubscriptionBox subscriptionBox = subscriptionBoxFactory.create("1", "Deluxe Box", "MONTHLY", 150, items, "this is good yas");
SubscriptionBox subscriptionBox = subscriptionBoxFactory.create("Deluxe Box", "MONTHLY", 150, items, "this is good yas");

assertEquals("Deluxe Box", subscriptionBox.getName());
assertEquals("MONTHLY", subscriptionBox.getType());
Expand Down
Loading

0 comments on commit 208b92c

Please sign in to comment.