test 2

 import static org.mockito.ArgumentMatchers.any;

import static org.mockito.ArgumentMatchers.anyString;

import static org.mockito.ArgumentMatchers.eq;

import static org.mockito.Mockito.doNothing;

import static org.mockito.Mockito.doThrow;

import static org.mockito.Mockito.never;

import static org.mockito.Mockito.times;

import static org.mockito.Mockito.verify;

import static org.mockito.Mockito.when;


import java.io.IOException;

import java.util.List;

import java.util.Optional;


import org.junit.jupiter.api.BeforeEach;

import org.junit.jupiter.api.Test;

import org.junit.jupiter.api.extension.ExtendWith;

import org.mockito.InjectMocks;

import org.mockito.Mock;

import org.mockito.junit.jupiter.MockitoExtension;

import org.springframework.test.context.junit.jupiter.SpringExtension;


@ExtendWith({SpringExtension.class, MockitoExtension.class})

public class YourServiceTest {


    private static final String PERIMETER = "test-perimeter";

    private static final String REPO_ID = "repo-123";

    private static final String DUMPSET_NAME = "test-dump";

    private static final String ENVIRONMENT = "dev";

    private static final String DB_USERNAME = "testuser";

    private static final String DB_NAME = "testdb";


    @Mock

    private AlmRepositoryDao almRepositoryDao;

    

    @Mock

    private AlmRepositoryMapper almRepositoryMapper;

    

    @Mock

    private DumpAvailabilityDao dumpAvailabilityDao;

    

    @Mock

    private DumpDao dumpDao;

    

    @Mock

    private DumpInformationMapper dumpInformationMapper;

    

    @Mock

    private DumpHelper dumpHelper;

    

    @Mock

    private GarliqOcpmService garliqOcpmService;

    

    @Mock

    private TaskService taskService;

    

    @Mock

    private AlmRepositoryService almRepositoryService;


    @InjectMocks

    private YourService yourService;


    private SuperTask superTask;

    private Dump dump;

    private AlmRepository almRepository;

    private DumpAvailabilityEntity dumpAvailabilityEntity;

    private DumpSetDto dumpSetDto;


    @BeforeEach

    void setUp() {

        superTask = givenSuperTask();

        dump = givenDump();

        almRepository = givenAlmRepository();

        dumpAvailabilityEntity = givenDumpAvailabilityEntity();

        dumpSetDto = givenDumpSetDto();

    }


    @Test

    void should_download_dump_when_dump_availability_not_present() throws Exception {

        // Given

        ImportDataEvent event = new ImportDataEvent(

            this, almRepository, DUMPSET_NAME, ENVIRONMENT, superTask, dump

        );

        

        when(dumpAvailabilityDao.findByPerimeterAndNameAndDatabase(

            almRepository.getPerimeter(), DUMPSET_NAME, almRepository.getDbName()))

            .thenReturn(Optional.empty());

            

        when(dumpDao.findByPerimeterAndNameAndEnvironment(

            almRepository.getPerimeter(), DUMPSET_NAME, ENVIRONMENT))

            .thenReturn(Optional.of(givenDumpEntity()));

            

        List<String> fileList = List.of("file1.sql", "file2.sql");

        when(dumpHelper.getListOfDumpFiles(any(DumpSetDto.class))).thenReturn(fileList);

        

        when(JsonHelper.toObject(eq(DumpSetDto.class), anyString())).thenReturn(dumpSetDto);

        

        when(garliqOcpmService.transferDumpToS3(

            any(), anyString(), any(), any(), any()))

            .thenReturn(JobStatus.OK);


        // When

        yourService.handleImportDataEvent(event);


        // Then

        verify(dumpAvailabilityDao).findByPerimeterAndNameAndDatabase(

            almRepository.getPerimeter(), DUMPSET_NAME, almRepository.getDbName());

        verify(dumpDao).findByPerimeterAndNameAndEnvironment(

            almRepository.getPerimeter(), DUMPSET_NAME, ENVIRONMENT);

        verify(dumpHelper).getListOfDumpFiles(any(DumpSetDto.class));

        verify(garliqOcpmService, times(fileList.size())).transferDumpToS3(

            any(), eq(almRepository.getDbUsername()), any(), eq(superTask), eq(TaskType.DOWNLOAD_DUMP));

        

        // Verify DumpState was updated to READY after successful download

        verify(almRepositoryDao).findByDbUsername(almRepository.getDbUsername());

        verify(dumpAvailabilityDao).save(any(DumpAvailabilityEntity.class));

    }


    @Test

    void should_handle_job_status_ko_during_dump_download() throws Exception {

        // Given

        ImportDataEvent event = new ImportDataEvent(

            this, almRepository, DUMPSET_NAME, ENVIRONMENT, superTask, dump

        );

        

        when(dumpAvailabilityDao.findByPerimeterAndNameAndDatabase(

            almRepository.getPerimeter(), DUMPSET_NAME, almRepository.getDbName()))

            .thenReturn(Optional.empty());

            

        when(dumpDao.findByPerimeterAndNameAndEnvironment(

            almRepository.getPerimeter(), DUMPSET_NAME, ENVIRONMENT))

            .thenReturn(Optional.of(givenDumpEntity()));

            

        List<String> fileList = List.of("file1.sql", "file2.sql");

        when(dumpHelper.getListOfDumpFiles(any(DumpSetDto.class))).thenReturn(fileList);

        

        when(JsonHelper.toObject(eq(DumpSetDto.class), anyString())).thenReturn(dumpSetDto);

        

        // First file succeeds, second file fails

        when(garliqOcpmService.transferDumpToS3(

            any(), anyString(), any(), any(), any()))

            .thenReturn(JobStatus.OK, JobStatus.KO);

            

        when(almRepositoryDao.findByDbUsername(anyString()))

            .thenReturn(Optional.of(givenRepositoryEntity()));

            

        when(almRepositoryMapper.toAlmRepository(any()))

            .thenReturn(almRepository);

            

        when(dumpAvailabilityDao.findByPerimeterAndNameAndDatabase(

            almRepository.getPerimeter(), dumpSetDto.getName(), almRepository.getDbName()))

            .thenReturn(Optional.of(dumpAvailabilityEntity));


        // When

        yourService.handleImportDataEvent(event);


        // Then

        verify(taskService).createFailedTask(

            eq(superTask), 

            eq(almRepository.getDbUsername()), 

            eq(TaskType.DOWNLOAD_DUMP), 

            anyString()

        );

        verify(almRepositoryService).updateStateToFailure(almRepository.getDbUsername());

        

        // Verify DumpState was updated to INCOMPLETE

        verify(dumpAvailabilityDao).save(any(DumpAvailabilityEntity.class));

        verify(dumpAvailabilityEntity).setState(DumpState.INCOMPLETE);

        

        // Verify importDumpFromOcpm was never called

        verify(yourService, never()).importDumpFromOcpm(any(), any(), any(), any(), any());

    }


    @Test

    void should_import_dump_when_dump_is_already_available() throws Exception {

        // Given

        ImportDataEvent event = new ImportDataEvent(

            this, almRepository, DUMPSET_NAME, ENVIRONMENT, superTask, dump

        );

        

        dumpAvailabilityEntity.setState(DumpState.READY);

        when(dumpAvailabilityDao.findByPerimeterAndNameAndDatabase(

            almRepository.getPerimeter(), DUMPSET_NAME, almRepository.getDbName()))

            .thenReturn(Optional.of(dumpAvailabilityEntity));


        // When

        yourService.handleImportDataEvent(event);


        // Then

        verify(dumpAvailabilityDao).findByPerimeterAndNameAndDatabase(

            almRepository.getPerimeter(), DUMPSET_NAME, almRepository.getDbName());

        verify(yourService).importDumpFromOcpm(

            superTask, 

            almRepository.getPerimeter(), 

            almRepository.getId(), 

            ENVIRONMENT, 

            dump

        );

        // Verify no download was attempted

        verify(dumpHelper, never()).getListOfDumpFiles(any());

    }


    @Test

    void should_handle_exception_when_dump_not_ready() throws Exception {

        // Given

        ImportDataEvent event = new ImportDataEvent(

            this, almRepository, DUMPSET_NAME, ENVIRONMENT, superTask, dump

        );

        

        dumpAvailabilityEntity.setState(DumpState.DOWNLOADING);

        when(dumpAvailabilityDao.findByPerimeterAndNameAndDatabase(

            almRepository.getPerimeter(), DUMPSET_NAME, almRepository.getDbName()))

            .thenReturn(Optional.of(dumpAvailabilityEntity));


        // When

        yourService.handleImportDataEvent(event);


        // Then

        verify(taskService).createFailedTask(

            eq(superTask), 

            eq(almRepository.getDbUsername()), 

            eq(TaskType.IMPORT_DATA), 

            anyString()

        );

        // Verify no import or download was attempted

        verify(yourService, never()).importDumpFromOcpm(any(), any(), any(), any(), any());

        verify(dumpHelper, never()).getListOfDumpFiles(any());

    }


    @Test

    void should_update_dump_availability_to_ready_after_successful_download() throws Exception {

        // Given

        ImportDataEvent event = new ImportDataEvent(

            this, almRepository, DUMPSET_NAME, ENVIRONMENT, superTask, dump

        );

        

        when(dumpAvailabilityDao.findByPerimeterAndNameAndDatabase(

            almRepository.getPerimeter(), DUMPSET_NAME, almRepository.getDbName()))

            .thenReturn(Optional.empty());

            

        when(dumpDao.findByPerimeterAndNameAndEnvironment(

            almRepository.getPerimeter(), DUMPSET_NAME, ENVIRONMENT))

            .thenReturn(Optional.of(givenDumpEntity()));

            

        List<String> fileList = List.of("file1.sql");

        when(dumpHelper.getListOfDumpFiles(any(DumpSetDto.class))).thenReturn(fileList);

        

        when(JsonHelper.toObject(eq(DumpSetDto.class), anyString())).thenReturn(dumpSetDto);

        

        when(garliqOcpmService.transferDumpToS3(

            any(), anyString(), any(), any(), any()))

            .thenReturn(JobStatus.OK);

            

        when(almRepositoryDao.findByDbUsername(anyString()))

            .thenReturn(Optional.of(givenRepositoryEntity()));

            

        when(almRepositoryMapper.toAlmRepository(any()))

            .thenReturn(almRepository);

            

        when(dumpAvailabilityDao.findByPerimeterAndNameAndDatabase(

            almRepository.getPerimeter(), dumpSetDto.getName(), almRepository.getDbName()))

            .thenReturn(Optional.of(dumpAvailabilityEntity));

            

        doNothing().when(yourService).importDumpFromOcpm(any(), any(), any(), any(), any());


        // When

        yourService.handleImportDataEvent(event);


        // Then

        // Verify DumpState was updated to READY

        verify(dumpAvailabilityEntity).setState(DumpState.READY);

        verify(dumpAvailabilityDao).save(dumpAvailabilityEntity);

        

        // Verify importDumpFromOcpm was called after successful download

        verify(yourService).importDumpFromOcpm(

            superTask, 

            almRepository.getPerimeter(), 

            almRepository.getId(), 

            ENVIRONMENT, 

            dump

        );

    }


    @Test

    void should_handle_exception_during_download_dump() throws Exception {

        // Given

        ImportDataEvent event = new ImportDataEvent(

            this, almRepository, DUMPSET_NAME, ENVIRONMENT, superTask, dump

        );

        

        when(dumpAvailabilityDao.findByPerimeterAndNameAndDatabase(

            almRepository.getPerimeter(), DUMPSET_NAME, almRepository.getDbName()))

            .thenReturn(Optional.empty());

            

        when(dumpDao.findByPerimeterAndNameAndEnvironment(

            almRepository.getPerimeter(), DUMPSET_NAME, ENVIRONMENT))

            .thenReturn(Optional.of(givenDumpEntity()));

            

        // Throw IOException during download process

        when(dumpHelper.getListOfDumpFiles(any(DumpSetDto.class)))

            .thenThrow(new IOException("Network error"));


        // When

        yourService.handleImportDataEvent(event);


        // Then

        verify(taskService).createFailedTask(

            eq(superTask), 

            eq(almRepository.getDbUsername()), 

            eq(TaskType.DOWNLOAD_DUMP), 

            anyString()

        );

        // Verify no import was attempted

        verify(yourService, never()).importDumpFromOcpm(any(), any(), any(), any(), any());

    }

    

    // Helper methods to create test objects (you would need to implement these)

    private SuperTask givenSuperTask() {

        SuperTask superTask = new SuperTask();

        superTask.setId(1L);

        return superTask;

    }

    

    private Dump givenDump() {

        Dump dump = new Dump();

        dump.setId(1L);

        dump.setName(DUMPSET_NAME);

        dump.setEnvironment(ENVIRONMENT);

        dump.setDescription("{\"name\":\"" + DUMPSET_NAME + "\",\"files\":[\"file1.sql\",\"file2.sql\"]}");

        dump.setCoherence("COHERENT");

        return dump;

    }

    

    private AlmRepository givenAlmRepository() {

        AlmRepository repo = new AlmRepository();

        repo.setId(REPO_ID);

        repo.setPerimeter(PERIMETER);

        repo.setDbName(DB_NAME);

        repo.setDbUsername(DB_USERNAME);

        return repo;

    }

    

    private DumpEntity givenDumpEntity() {

        DumpEntity entity = new DumpEntity();

        entity.setId(1L);

        entity.setName(DUMPSET_NAME);

        entity.setEnvironment(ENVIRONMENT);

        entity.setPerimeter(PERIMETER);

        entity.setDescription(givenDump().getDescription());

        return entity;

    }

    

    private RepositoryEntity givenRepositoryEntity() {

        RepositoryEntity entity = new RepositoryEntity();

        entity.setId(REPO_ID);

        entity.setPerimeter(PERIMETER);

        entity.setDbName(DB_NAME);

        entity.setDbUsername(DB_USERNAME);

        return entity;

    }

    

    private DumpAvailabilityEntity givenDumpAvailabilityEntity() {

        DumpAvailabilityEntity entity = new DumpAvailabilityEntity();

        entity.setId(1L);

        entity.setPerimeter(PERIMETER);

        entity.setName(DUMPSET_NAME);

        entity.setDatabase(DB_NAME);

        entity.setState(DumpState.DOWNLOADING);

        return entity;

    }

    

    private DumpSetDto givenDumpSetDto() {

        DumpSetDto dto = new DumpSetDto();

        dto.setName(DUMPSET_NAME);

        dto.setFiles(List.of("file1.sql", "file2.sql"));

        return dto;

    }

}

Comments

Popular posts from this blog

Unit Tests in Spring Boot