Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 8

@Test

void testOrganizationMismatchExceptionWhenDownloadFile() throws Exception {


Map<String, Object> loggedInUserOrganization = new HashMap<>();
loggedInUserOrganization.put("id", "123");
UserContext.setLoggedInUserOrganization(loggedInUserOrganization);
UserContext.setLoggedInUserEmail("test@gmail.com");
File file = new File();
file.setOrganizationId("1234");
UserContext.setLoggedInUserEmail("null");
UserContext.setLoggedInUserPermissions(Collections.singleton("null"));
when(fileRepository.findById(anyString())).thenReturn(Optional.of(file));
Exception exception = assertThrows(Exception.class,()->{
fileServiceImpl.downloadFile("file");
});
System.out.println("exception "+exception.getMessage());
assertEquals(UNAUTHORISED_ACCESS_ERROR+ ":
OrgMisMatch",exception.getMessage());
}

package com.tac.filemanagement.serviceImpl;

import com.google.cloud.storage.Blob;
import com.google.cloud.storage.BlobInfo;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageException;
import com.mongodb.DuplicateKeyException;
import com.mongodb.MongoWriteException;
import com.mongodb.WriteError;
import com.tac.filemanagement.config.properties.AllowedContentTypes;
import com.tac.filemanagement.config.properties.GCSProperties;
import com.tac.filemanagement.exceptions.FileTypeMismatchException;
import com.tac.filemanagement.exceptions.GCSFileAccessException;
import com.tac.filemanagement.exceptions.MongoFileUploadException;
import com.tac.filemanagement.model.File;
import com.tac.filemanagement.repository.FileRepository;
import com.tac.filemanagement.requests.FileUploadRequest;
import com.tac.filemanagement.utils.UserContext;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.EnableLoadTimeWeaving;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;

import java.util.*;

import static com.tac.filemanagement.utils.Constants.*;


import static
com.tac.filemanagement.utils.helpers.GCSPathGenerator.generateGCSPath;
import static org.mockito.Mockito.*;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

@ContextConfiguration(classes = {FileServiceImpl.class, AllowedContentTypes.class,


GCSProperties.class})
@ExtendWith(SpringExtension.class)
public class FileServiceImplTest {

private static final String MONGO_FILE_DELETE_ERROR = "Something went wrong in


our system";
private static final String GCS_FILE_DELETE_ERROR = "Something went wrong in
our system";
@Autowired
private AllowedContentTypes allowedContentTypes;
@MockBean
private FileRepository fileRepository;
@Autowired
private FileServiceImpl fileServiceImpl;
@Autowired
private GCSProperties gcsProperties;
@MockBean
private Storage storage;

@Test
public void testFileTypeMismatchException() {
// Prepare a file with a content type that doesn't match the allowed types
MockMultipartFile mockFile = new MockMultipartFile(
"file",
"filename.txt",
"invalid/type",
"content".getBytes()
);
FileUploadRequest fileUploadRequest = new FileUploadRequest();
fileUploadRequest.setFile(mockFile);
String[] allowedTypes = {"valid/type"};
allowedContentTypes.setAllowedTypes(allowedTypes);
FileTypeMismatchException exception =
assertThrows(FileTypeMismatchException.class, () -> {
fileServiceImpl.uploadFile(fileUploadRequest);
});
assertEquals(exception.getMessage(),INVALID_FILE_FORMATS+ " "+
SUPPORTED_FILE_TYPES);
}

@Test
public void testServerDownException() {
MockMultipartFile mockFile = new MockMultipartFile(
"file",
"filename.txt",
"invalid/type", // Set an invalid content type here
"content".getBytes()
);
FileUploadRequest fileUploadRequest = new FileUploadRequest();
fileUploadRequest.setFile(mockFile);
Exception exception = assertThrows(Exception.class, () -> {
fileServiceImpl.uploadFile(fileUploadRequest);
});
assertEquals(exception.getMessage(),SERVICE_DOWN_ERROR);
}
@Test
public void testMongoDBException() throws Exception {
MockMultipartFile mockFile = new MockMultipartFile(
"file",
"filename.txt",
"valid/type",
"content".getBytes()
);
FileUploadRequest fileUploadRequest = new FileUploadRequest();
fileUploadRequest.setFile(mockFile);
fileUploadRequest.setDescription("");
fileUploadRequest.setEntityId("id");
String[] allowedTypes = {"valid/type"};
allowedContentTypes.setAllowedTypes(allowedTypes);
Set<String> stringSet = new HashSet<>();
stringSet.add(READ_EMPLOYEE);
stringSet.add("Test");
UserContext.setLoggedInUserPermissions(stringSet);
Map<String, Object> loggedInUserOrganization = new HashMap<>();
loggedInUserOrganization.put("id", 123);
UserContext.setLoggedInUserOrganization(loggedInUserOrganization);
File file = new File();

Mockito.when(fileRepository.save(Mockito.any(File.class))).thenThrow(MongoWriteExce
ption.class);
Exception writeException = assertThrows(Exception.class, () -> {
fileServiceImpl.uploadFile(fileUploadRequest);
});
assertEquals(writeException.getMessage(),MONGO_UPLOAD_FAILED);
}

@Test
public void testGCSException() throws Exception {
MockMultipartFile mockFile = new MockMultipartFile(
"file",
"filename.txt",
"valid/type",
"content".getBytes()
);
FileUploadRequest fileUploadRequest = new FileUploadRequest();
fileUploadRequest.setFile(mockFile);
fileUploadRequest.setDescription("");
fileUploadRequest.setEntityId("id");
String[] allowedTypes = {"valid/type"};
allowedContentTypes.setAllowedTypes(allowedTypes);
Set<String> stringSet = new HashSet<>();
stringSet.add(READ_EMPLOYEE);
UserContext.setLoggedInUserPermissions(stringSet);
Map<String, Object> loggedInUserOrganization = new HashMap<>();
loggedInUserOrganization.put("id", 123);
UserContext.setLoggedInUserOrganization(loggedInUserOrganization);
File fileEntity = new File();
fileEntity.setName("SampleFile.txt");
fileEntity.setFileType("Text");
fileEntity.setFileFormat("TXT");
fileEntity.setId("id");
fileEntity.setFileSize("Size");
fileEntity.setEntityId("testId");
fileEntity.setEntityType("dummyType");
fileEntity.setDescription("test description");

Mockito.when(fileRepository.save(Mockito.any(File.class))).thenReturn(fileEntity);
GCSProperties.Bucket bucket = new GCSProperties.Bucket();
bucket.setName("Test");
gcsProperties.setBucket(bucket);
doThrow(StorageException.class).when(storage).create(any(BlobInfo.class),
any(byte[].class));
Exception writeException = assertThrows(Exception.class, () -> {
fileServiceImpl.uploadFile(fileUploadRequest);
});
System.out.println("Exception "+writeException.getMessage());
assertEquals(writeException.getMessage(),GCS_UPLOAD_FAILED);
}

@Test
void testOrganizationMismatchExceptionWhenListOfFileByEntityId(){
Map<String, Object> loggedInUserOrganization = new HashMap<>();
loggedInUserOrganization.put("id", 123);
UserContext.setLoggedInUserOrganization(loggedInUserOrganization);
UserContext.setLoggedInEmployeeId("id");
List<File> files = new ArrayList<>();
File file = new File();
file.setOrganizationId("id");
files.add(file);
when(fileRepository.findByEntityId("id")).thenReturn(files);
Exception exception = assertThrows(Exception.class,() -> {
fileServiceImpl.listofFileByEntityId("id");
});
System.out.println(exception.getMessage());
assertEquals(UNAUTHORISED_ACCESS_ERROR + ":
OrgMisMatch",exception.getMessage());
}
@Test
void testReturnWhenListOfFileByEntityId() throws Exception {
Map<String, Object> loggedInUserOrganization = new HashMap<>();
loggedInUserOrganization.put("id", 123);
UserContext.setLoggedInUserOrganization(loggedInUserOrganization);
UserContext.setLoggedInEmployeeId("id");
List<File> files = new ArrayList<>();
when(fileRepository.findByEntityId("id")).thenReturn(files);
List<File> result = fileServiceImpl.listofFileByEntityId("id");
assertEquals(result,files);
}

@Test
void testUnAuthorisedExceptionWhenListOfFileByEntityId(){
Map<String, Object> loggedInUserOrganization = new HashMap<>();
loggedInUserOrganization.put("id", 123);
UserContext.setLoggedInUserOrganization(loggedInUserOrganization);
Set<String> stringSet = new HashSet<>();
stringSet.add(READ_EMPLOYEE);
stringSet.add("Test");
UserContext.setLoggedInUserPermissions(stringSet);
UserContext.setLoggedInEmployeeId("id");
List<File> files = new ArrayList<>();
File file = new File();
file.setOrganizationId("id");
files.add(file);
when(fileRepository.findByEntityId("id")).thenReturn(files);
Exception exception = assertThrows(Exception.class,() -> {
fileServiceImpl.listofFileByEntityId("idd");
});
System.out.println(exception.getMessage());
assertEquals(UNAUTHORISED_ACCESS_ERROR,exception.getMessage());
}

@Test
void testExceptionWhenListOfFileByEntityId(){
UserContext.setLoggedInUserPermissions(null);
Exception exception = assertThrows(Exception.class,() -> {
fileServiceImpl.listofFileByEntityId("");
});
assertEquals(SERVICE_DOWN_ERROR,exception.getMessage());
}

@Test
void testReturnByteArrayResourceWhenDownloadFile() throws Exception {
Map<String, Object> loggedInUserOrganization = new HashMap<>();
loggedInUserOrganization.put("id", "123");
UserContext.setLoggedInUserOrganization(loggedInUserOrganization);
File file = new File();
file.setOrganizationId("123");
file.setCreatedBy("test-employee");
file.setId("id");
file.setEntityId("id");
file.setEntityType("type");
file.setFileType("fieldType");
UserContext.setLoggedInUserEmail("test-employee");
when(fileRepository.findById(anyString())).thenReturn(Optional.of(file));
GCSProperties.Bucket bucket = new GCSProperties.Bucket();
bucket.setName("Test");
gcsProperties.setBucket(bucket);
Blob mockBlob = mock(Blob.class);
File mockFile = new File();
mockFile.setId("id");
byte[] mockContent = "Sample content".getBytes();
when(mockBlob.getContent()).thenReturn(mockContent);
when(storage.get(anyString(), anyString())).thenReturn(mockBlob);
ByteArrayResource result = fileServiceImpl.downloadFile("fileId");
result.getFilename();
assertEquals("Sample content", new String(result.getByteArray()));
}

@Test
void testUnAuthorisedExceptionWhenDownloadFile() throws Exception {
Map<String, Object> loggedInUserOrganization = new HashMap<>();
loggedInUserOrganization.put("id", "123");
UserContext.setLoggedInUserOrganization(loggedInUserOrganization);
UserContext.setLoggedInUserEmail("test@gmail.com");
File file = new File();
file.setOrganizationId("123");
UserContext.setLoggedInUserEmail("null");
UserContext.setLoggedInUserPermissions(Collections.singleton("null"));
when(fileRepository.findById(anyString())).thenReturn(Optional.of(file));
Exception exception = assertThrows(Exception.class,()->{
fileServiceImpl.downloadFile("file");
});
System.out.println("exception "+exception.getMessage());
assertEquals(UNAUTHORISED_ACCESS_ERROR,exception.getMessage());
}
@Test
void testGeneralExceptionWhenDownloadFile() throws Exception {
when(fileRepository.findById(anyString())).thenReturn(Optional.empty());
Exception exception = assertThrows(Exception.class,()->{
fileServiceImpl.downloadFile("file");
});
System.out.println("exception "+exception.getMessage());
assertEquals(SERVICE_DOWN_ERROR,exception.getMessage());
}

@Test
void testGeneralExceptionWhenDeleteFile(){
when(fileRepository.findById(anyString())).thenReturn(Optional.empty());
Exception exception = assertThrows(Exception.class,()->{
fileServiceImpl.deleteFile("file");
});
System.out.println("exception "+exception.getMessage());
assertEquals(SERVICE_DOWN_ERROR,exception.getMessage());
}

@Test
void testGCSFileAccessExceptionWhenDeleteFile() throws Exception {
Map<String, Object> loggedInUserOrganization = new HashMap<>();
loggedInUserOrganization.put("id", "123");
UserContext.setLoggedInUserOrganization(loggedInUserOrganization);
File file = new File();
file.setOrganizationId("123");
file.setCreatedBy("test-employee@gmail.com");
file.setId("id");
file.setEntityId("id");
file.setEntityType("type");
file.setFileType("fieldType");
UserContext.setLoggedInUserEmail("test-employee@gmail.com");
when(fileRepository.findById(anyString())).thenReturn(Optional.of(file));
GCSProperties.Bucket bucket = new GCSProperties.Bucket();
bucket.setName("Test");
gcsProperties.setBucket(bucket);
Blob mockBlob = mock(Blob.class);
when(storage.get(anyString(), anyString())).thenReturn(mockBlob);
doThrow(new
GCSFileAccessException(GCS_FILE_DELETE_ERROR)).when(mockBlob).delete();
Exception exception = assertThrows(Exception.class,()->{
fileServiceImpl.deleteFile("file");
});
assertEquals(SERVICE_DOWN_ERROR,exception.getMessage());
}

@Test
void testMongoFileUploadExceptionWhenDeleteFile() throws Exception {
Map<String, Object> loggedInUserOrganization = new HashMap<>();
loggedInUserOrganization.put("id", "123");
UserContext.setLoggedInUserOrganization(loggedInUserOrganization);
File file = new File();
file.setOrganizationId("123");
file.setCreatedBy("test-employee@gmail.com");
file.setId("id");
file.setEntityId("id");
file.setEntityType("type");
file.setFileType("fieldType");
UserContext.setLoggedInUserEmail("test-employee@gmail.com");
when(fileRepository.findById(anyString())).thenReturn(Optional.of(file));
GCSProperties.Bucket bucket = new GCSProperties.Bucket();
bucket.setName("Test");
gcsProperties.setBucket(bucket);
Blob mockBlob = mock(Blob.class);
when(storage.get(anyString(), anyString())).thenReturn(mockBlob);
doThrow(new
MongoFileUploadException(MONGO_FILE_DELETE_ERROR)).when(fileRepository).delete(any(
));
Exception exception = assertThrows(Exception.class,()->{
fileServiceImpl.deleteFile("file");
});
assertEquals(SERVICE_DOWN_ERROR,exception.getMessage());
}

@Test
void testReturnWhenDeleteFile() throws Exception {
Map<String, Object> loggedInUserOrganization = new HashMap<>();
loggedInUserOrganization.put("id", "123");
UserContext.setLoggedInUserOrganization(loggedInUserOrganization);
File file = new File();
file.setOrganizationId("123");
file.setCreatedBy("test-employee@gmail.com");
file.setId("id");
file.setEntityId("id");
file.setEntityType("type");
file.setFileType("fieldType");
UserContext.setLoggedInUserEmail("test-employee@gmail.com");
when(fileRepository.findById(anyString())).thenReturn(Optional.of(file));
GCSProperties.Bucket bucket = new GCSProperties.Bucket();
bucket.setName("Test");
gcsProperties.setBucket(bucket);
Blob mockBlob = mock(Blob.class);
when(storage.get(anyString(), anyString())).thenReturn(mockBlob);
File result = fileServiceImpl.deleteFile("file");
assertEquals(file,result);
}

@Test
void testUnAuthorisedExceptionWhenDeleteFile() throws Exception {
Map<String, Object> loggedInUserOrganization = new HashMap<>();
loggedInUserOrganization.put("id", "123");
UserContext.setLoggedInUserOrganization(loggedInUserOrganization);
Set<String> stringSet = new HashSet<>();
UserContext.setLoggedInUserPermissions(stringSet);
File file = new File();
file.setOrganizationId("123");
file.setCreatedBy("test-employee@gmail.com");
UserContext.setLoggedInUserEmail("test-employee2@gmail.com");
when(fileRepository.findById(anyString())).thenReturn(Optional.of(file));
Exception exception = assertThrows(Exception.class,()->{
fileServiceImpl.deleteFile("file");
});
assertEquals(UNAUTHORISED_ACCESS_ERROR,exception.getMessage());
}
// @Test
// void testOrganizationMismatchExceptionWhenDeleteFile() throws Exception {
// Map<String, Object> loggedInUserOrganization = new HashMap<>();
// loggedInUserOrganization.put("id", "1");
// UserContext.setLoggedInUserOrganization(loggedInUserOrganization);
// Set<String> stringSet = new HashSet<>();
// UserContext.setLoggedInUserPermissions(stringSet);
// File file = new File();
// file.setOrganizationId("2");
// when(fileRepository.findById(anyString())).thenReturn(Optional.of(file));
// Exception exception = assertThrows(Exception.class,()->{
// fileServiceImpl.deleteFile("file");
// });
// assertEquals(UNAUTHORISED_ACCESS_ERROR+ ":
OrgMisMatch",exception.getMessage());
// }
}

You might also like