🤖 format everything with pre-commit by stirlingbot (#3804)

Auto-generated by [create-pull-request][1] with **stirlingbot**

[1]: https://github.com/peter-evans/create-pull-request

Signed-off-by: stirlingbot[bot] <stirlingbot[bot]@users.noreply.github.com>
Co-authored-by: stirlingbot[bot] <195170888+stirlingbot[bot]@users.noreply.github.com>
This commit is contained in:
stirlingbot[bot] 2025-07-01 15:41:23 +01:00 committed by GitHub
parent 9eb534a6d2
commit 14d4fbb2a3
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
10 changed files with 142 additions and 142 deletions

View File

@ -126,7 +126,7 @@ class AutoJobPostMappingIntegrationTest {
verify(jobExecutorService).runJobGeneric(
asyncCaptor.capture(),
workCaptor.capture(),
workCaptor.capture(),
timeoutCaptor.capture(),
queueableCaptor.capture(),
resourceWeightCaptor.capture());
@ -197,7 +197,7 @@ class AutoJobPostMappingIntegrationTest {
autoJobAspect.wrapWithJobExecution(joinPoint, autoJobPostMapping);
// Then
assertEquals("stored-file-id", pdfFile.getFileId(),
assertEquals("stored-file-id", pdfFile.getFileId(),
"FileId should be set to the stored file id");
assertNotNull(pdfFile.getFileInput(), "FileInput should be replaced with persistent file");

View File

@ -187,4 +187,4 @@ class FileStorageTest {
// Assert
assertFalse(result);
}
}
}

View File

@ -64,8 +64,8 @@ class JobExecutorServiceTest {
void setUp() {
// Initialize the service manually with all its dependencies
jobExecutorService = new JobExecutorService(
taskManager,
fileStorage,
taskManager,
fileStorage,
request,
resourceMonitor,
jobQueue,
@ -199,4 +199,4 @@ class JobExecutorServiceTest {
assertTrue(e.getCause() instanceof TimeoutException);
}
}
}
}

View File

@ -36,7 +36,7 @@ class JobQueueTest {
// Mark stubbing as lenient to avoid UnnecessaryStubbingException
lenient().when(resourceMonitor.calculateDynamicQueueCapacity(anyInt(), anyInt())).thenReturn(10);
lenient().when(resourceMonitor.getCurrentStatus()).thenReturn(statusRef);
// Initialize JobQueue with mocked ResourceMonitor
jobQueue = new JobQueue(resourceMonitor);
}
@ -99,4 +99,4 @@ class JobQueueTest {
assertTrue(jobQueue.isJobQueued(jobId));
assertFalse(jobQueue.isJobQueued("nonexistent"));
}
}
}

View File

@ -117,7 +117,7 @@ class ResourceMonitorTest {
// Then
assertEquals(shouldQueue, result,
String.format("For weight %d and status %s, shouldQueue should be %s",
String.format("For weight %d and status %s, shouldQueue should be %s",
weight, status, shouldQueue));
}
@ -134,4 +134,4 @@ class ResourceMonitorTest {
assertTrue(staleMetrics.isStale(5000), "Metrics from 6 seconds ago should be stale with 5s threshold");
assertFalse(freshMetrics.isStale(5000), "Fresh metrics should not be stale");
}
}
}

View File

@ -252,17 +252,17 @@ class TaskManagerTest {
// Verify the executor service is shutdown
// This is difficult to test directly, but we can verify it doesn't throw exceptions
}
@Test
void testAddNote() {
// Arrange
String jobId = UUID.randomUUID().toString();
taskManager.createTask(jobId);
String note = "Test note";
// Act
boolean result = taskManager.addNote(jobId, note);
// Assert
assertTrue(result);
JobResult jobResult = taskManager.getJobResult(jobId);
@ -271,16 +271,16 @@ class TaskManagerTest {
assertEquals(1, jobResult.getNotes().size());
assertEquals(note, jobResult.getNotes().get(0));
}
@Test
void testAddNote_NonExistentJob() {
// Arrange
String jobId = "non-existent-job";
String note = "Test note";
// Act
boolean result = taskManager.addNote(jobId, note);
// Assert
assertFalse(result);
}

View File

@ -82,10 +82,10 @@ public class TempFileCleanupServiceTest {
when(tempFileManagement.isStartupCleanup()).thenReturn(false);
when(tempFileManagement.isCleanupSystemTemp()).thenReturn(false);
when(tempFileManagement.getCleanupIntervalMinutes()).thenReturn(30L);
// Set machineType using reflection (still needed for this field)
ReflectionTestUtils.setField(cleanupService, "machineType", "Standard");
when(tempFileManager.getMaxAgeMillis()).thenReturn(3600000L); // 1 hour
}
@ -113,30 +113,30 @@ public class TempFileCleanupServiceTest {
Path ourTempFile3 = Files.createFile(customTempDir.resolve("stirling-pdf-789.tmp"));
Path ourTempFile4 = Files.createFile(customTempDir.resolve("pdf-save-123-456.tmp"));
Path ourTempFile5 = Files.createFile(libreOfficeTempDir.resolve("input_file.pdf"));
// Old temporary files
Path oldTempFile = Files.createFile(systemTempDir.resolve("output_old.pdf"));
// System temp files that should be cleaned in container mode
Path sysTempFile1 = Files.createFile(systemTempDir.resolve("lu123abc.tmp"));
Path sysTempFile2 = Files.createFile(customTempDir.resolve("ocr_process123"));
Path sysTempFile3 = Files.createFile(customTempDir.resolve("tmp_upload.tmp"));
// Files that should be preserved
Path jettyFile1 = Files.createFile(systemTempDir.resolve("jetty-123.tmp"));
Path jettyFile2 = Files.createFile(systemTempDir.resolve("something-with-jetty-inside.tmp"));
Path regularFile = Files.createFile(systemTempDir.resolve("important.txt"));
// Create a nested directory with temp files
Path nestedDir = Files.createDirectories(systemTempDir.resolve("nested"));
Path nestedTempFile = Files.createFile(nestedDir.resolve("output_nested.pdf"));
// Empty file (special case)
Path emptyFile = Files.createFile(systemTempDir.resolve("empty.tmp"));
// Configure mock registry to say these files aren't registered
when(registry.contains(any(File.class))).thenReturn(false);
// The set of files that will be deleted in our test
Set<Path> deletedFiles = new HashSet<>();
@ -145,31 +145,31 @@ public class TempFileCleanupServiceTest {
// Mock Files.list for each directory we'll process
mockedFiles.when(() -> Files.list(eq(systemTempDir)))
.thenReturn(Stream.of(
ourTempFile1, ourTempFile2, oldTempFile, sysTempFile1,
ourTempFile1, ourTempFile2, oldTempFile, sysTempFile1,
jettyFile1, jettyFile2, regularFile, emptyFile, nestedDir));
mockedFiles.when(() -> Files.list(eq(customTempDir)))
.thenReturn(Stream.of(ourTempFile3, ourTempFile4, sysTempFile2, sysTempFile3));
mockedFiles.when(() -> Files.list(eq(libreOfficeTempDir)))
.thenReturn(Stream.of(ourTempFile5));
mockedFiles.when(() -> Files.list(eq(nestedDir)))
.thenReturn(Stream.of(nestedTempFile));
// Configure Files.isDirectory for each path
mockedFiles.when(() -> Files.isDirectory(eq(nestedDir))).thenReturn(true);
mockedFiles.when(() -> Files.isDirectory(any(Path.class))).thenReturn(false);
// Configure Files.exists to return true for all paths
mockedFiles.when(() -> Files.exists(any(Path.class))).thenReturn(true);
// Configure Files.getLastModifiedTime to return different times based on file names
mockedFiles.when(() -> Files.getLastModifiedTime(any(Path.class)))
.thenAnswer(invocation -> {
Path path = invocation.getArgument(0);
String fileName = path.getFileName().toString();
// For files with "old" in the name, return a timestamp older than maxAgeMillis
if (fileName.contains("old")) {
return FileTime.fromMillis(System.currentTimeMillis() - 5000000);
@ -183,13 +183,13 @@ public class TempFileCleanupServiceTest {
return FileTime.fromMillis(System.currentTimeMillis() - 60000); // 1 minute ago
}
});
// Configure Files.size to return different sizes based on file names
mockedFiles.when(() -> Files.size(any(Path.class)))
.thenAnswer(invocation -> {
Path path = invocation.getArgument(0);
String fileName = path.getFileName().toString();
// Return 0 bytes for the empty file
if (fileName.equals("empty.tmp")) {
return 0L;
@ -199,7 +199,7 @@ public class TempFileCleanupServiceTest {
return 1024L; // 1 KB
}
});
// For deleteIfExists, track which files would be deleted
mockedFiles.when(() -> Files.deleteIfExists(any(Path.class)))
.thenAnswer(invocation -> {
@ -207,28 +207,28 @@ public class TempFileCleanupServiceTest {
deletedFiles.add(path);
return true;
});
// Act - set containerMode to false for this test
invokeCleanupDirectoryStreaming(systemTempDir, false, 0, 3600000);
invokeCleanupDirectoryStreaming(customTempDir, false, 0, 3600000);
invokeCleanupDirectoryStreaming(libreOfficeTempDir, false, 0, 3600000);
// Assert - Only old temp files and empty files should be deleted
assertTrue(deletedFiles.contains(oldTempFile), "Old temp file should be deleted");
assertTrue(deletedFiles.contains(emptyFile), "Empty file should be deleted");
// Regular temp files should not be deleted because they're too new
assertFalse(deletedFiles.contains(ourTempFile1), "Recent temp file should be preserved");
assertFalse(deletedFiles.contains(ourTempFile2), "Recent temp file should be preserved");
assertFalse(deletedFiles.contains(ourTempFile3), "Recent temp file should be preserved");
assertFalse(deletedFiles.contains(ourTempFile4), "Recent temp file should be preserved");
assertFalse(deletedFiles.contains(ourTempFile5), "Recent temp file should be preserved");
// System temp files should not be deleted in non-container mode
assertFalse(deletedFiles.contains(sysTempFile1), "System temp file should be preserved in non-container mode");
assertFalse(deletedFiles.contains(sysTempFile2), "System temp file should be preserved in non-container mode");
assertFalse(deletedFiles.contains(sysTempFile3), "System temp file should be preserved in non-container mode");
// Jetty files and regular files should never be deleted
assertFalse(deletedFiles.contains(jettyFile1), "Jetty file should be preserved");
assertFalse(deletedFiles.contains(jettyFile2), "File with jetty in name should be preserved");
@ -242,10 +242,10 @@ public class TempFileCleanupServiceTest {
Path ourTempFile = Files.createFile(systemTempDir.resolve("output_123.pdf"));
Path sysTempFile = Files.createFile(systemTempDir.resolve("lu123abc.tmp"));
Path regularFile = Files.createFile(systemTempDir.resolve("important.txt"));
// Configure mock registry to say these files aren't registered
when(registry.contains(any(File.class))).thenReturn(false);
// The set of files that will be deleted in our test
Set<Path> deletedFiles = new HashSet<>();
@ -254,21 +254,21 @@ public class TempFileCleanupServiceTest {
// Mock Files.list for systemTempDir
mockedFiles.when(() -> Files.list(eq(systemTempDir)))
.thenReturn(Stream.of(ourTempFile, sysTempFile, regularFile));
// Configure Files.isDirectory
mockedFiles.when(() -> Files.isDirectory(any(Path.class))).thenReturn(false);
// Configure Files.exists
mockedFiles.when(() -> Files.exists(any(Path.class))).thenReturn(true);
// Configure Files.getLastModifiedTime to return recent timestamps
mockedFiles.when(() -> Files.getLastModifiedTime(any(Path.class)))
.thenReturn(FileTime.fromMillis(System.currentTimeMillis() - 60000)); // 1 minute ago
// Configure Files.size to return normal size
mockedFiles.when(() -> Files.size(any(Path.class)))
.thenReturn(1024L); // 1 KB
// For deleteIfExists, track which files would be deleted
mockedFiles.when(() -> Files.deleteIfExists(any(Path.class)))
.thenAnswer(invocation -> {
@ -276,10 +276,10 @@ public class TempFileCleanupServiceTest {
deletedFiles.add(path);
return true;
});
// Act - set containerMode to true and maxAgeMillis to 0 for container startup cleanup
invokeCleanupDirectoryStreaming(systemTempDir, true, 0, 0);
// Assert - In container mode, both our temp files and system temp files should be deleted
// regardless of age (when maxAgeMillis is 0)
assertTrue(deletedFiles.contains(ourTempFile), "Our temp file should be deleted in container mode");
@ -293,10 +293,10 @@ public class TempFileCleanupServiceTest {
// Arrange - Create an empty file
Path emptyFile = Files.createFile(systemTempDir.resolve("empty.tmp"));
Path recentEmptyFile = Files.createFile(systemTempDir.resolve("recent_empty.tmp"));
// Configure mock registry to say these files aren't registered
when(registry.contains(any(File.class))).thenReturn(false);
// The set of files that will be deleted in our test
Set<Path> deletedFiles = new HashSet<>();
@ -305,19 +305,19 @@ public class TempFileCleanupServiceTest {
// Mock Files.list for systemTempDir
mockedFiles.when(() -> Files.list(eq(systemTempDir)))
.thenReturn(Stream.of(emptyFile, recentEmptyFile));
// Configure Files.isDirectory
mockedFiles.when(() -> Files.isDirectory(any(Path.class))).thenReturn(false);
// Configure Files.exists
mockedFiles.when(() -> Files.exists(any(Path.class))).thenReturn(true);
// Configure Files.getLastModifiedTime to return different times based on file names
mockedFiles.when(() -> Files.getLastModifiedTime(any(Path.class)))
.thenAnswer(invocation -> {
Path path = invocation.getArgument(0);
String fileName = path.getFileName().toString();
if (fileName.equals("empty.tmp")) {
// More than 5 minutes old
return FileTime.fromMillis(System.currentTimeMillis() - 6 * 60 * 1000);
@ -326,11 +326,11 @@ public class TempFileCleanupServiceTest {
return FileTime.fromMillis(System.currentTimeMillis() - 2 * 60 * 1000);
}
});
// Configure Files.size to return 0 for empty files
mockedFiles.when(() -> Files.size(any(Path.class)))
.thenReturn(0L);
// For deleteIfExists, track which files would be deleted
mockedFiles.when(() -> Files.deleteIfExists(any(Path.class)))
.thenAnswer(invocation -> {
@ -338,14 +338,14 @@ public class TempFileCleanupServiceTest {
deletedFiles.add(path);
return true;
});
// Act
invokeCleanupDirectoryStreaming(systemTempDir, false, 0, 3600000);
// Assert
assertTrue(deletedFiles.contains(emptyFile),
assertTrue(deletedFiles.contains(emptyFile),
"Empty file older than 5 minutes should be deleted");
assertFalse(deletedFiles.contains(recentEmptyFile),
assertFalse(deletedFiles.contains(recentEmptyFile),
"Empty file newer than 5 minutes should not be deleted");
}
}
@ -356,14 +356,14 @@ public class TempFileCleanupServiceTest {
Path dir1 = Files.createDirectories(systemTempDir.resolve("dir1"));
Path dir2 = Files.createDirectories(dir1.resolve("dir2"));
Path dir3 = Files.createDirectories(dir2.resolve("dir3"));
Path tempFile1 = Files.createFile(dir1.resolve("output_1.pdf"));
Path tempFile2 = Files.createFile(dir2.resolve("output_2.pdf"));
Path tempFile3 = Files.createFile(dir3.resolve("output_old_3.pdf"));
// Configure mock registry to say these files aren't registered
when(registry.contains(any(File.class))).thenReturn(false);
// The set of files that will be deleted in our test
Set<Path> deletedFiles = new HashSet<>();
@ -372,16 +372,16 @@ public class TempFileCleanupServiceTest {
// Mock Files.list for each directory
mockedFiles.when(() -> Files.list(eq(systemTempDir)))
.thenReturn(Stream.of(dir1));
mockedFiles.when(() -> Files.list(eq(dir1)))
.thenReturn(Stream.of(tempFile1, dir2));
mockedFiles.when(() -> Files.list(eq(dir2)))
.thenReturn(Stream.of(tempFile2, dir3));
mockedFiles.when(() -> Files.list(eq(dir3)))
.thenReturn(Stream.of(tempFile3));
// Configure Files.isDirectory for each path
mockedFiles.when(() -> Files.isDirectory(eq(dir1))).thenReturn(true);
mockedFiles.when(() -> Files.isDirectory(eq(dir2))).thenReturn(true);
@ -389,16 +389,16 @@ public class TempFileCleanupServiceTest {
mockedFiles.when(() -> Files.isDirectory(eq(tempFile1))).thenReturn(false);
mockedFiles.when(() -> Files.isDirectory(eq(tempFile2))).thenReturn(false);
mockedFiles.when(() -> Files.isDirectory(eq(tempFile3))).thenReturn(false);
// Configure Files.exists to return true for all paths
mockedFiles.when(() -> Files.exists(any(Path.class))).thenReturn(true);
// Configure Files.getLastModifiedTime to return different times based on file names
mockedFiles.when(() -> Files.getLastModifiedTime(any(Path.class)))
.thenAnswer(invocation -> {
Path path = invocation.getArgument(0);
String fileName = path.getFileName().toString();
if (fileName.contains("old")) {
// Old file
return FileTime.fromMillis(System.currentTimeMillis() - 5000000);
@ -407,11 +407,11 @@ public class TempFileCleanupServiceTest {
return FileTime.fromMillis(System.currentTimeMillis() - 60000);
}
});
// Configure Files.size to return normal size
mockedFiles.when(() -> Files.size(any(Path.class)))
.thenReturn(1024L);
// For deleteIfExists, track which files would be deleted
mockedFiles.when(() -> Files.deleteIfExists(any(Path.class)))
.thenAnswer(invocation -> {
@ -419,14 +419,14 @@ public class TempFileCleanupServiceTest {
deletedFiles.add(path);
return true;
});
// Act
invokeCleanupDirectoryStreaming(systemTempDir, false, 0, 3600000);
// Debug - print what was deleted
System.out.println("Deleted files: " + deletedFiles);
System.out.println("Looking for: " + tempFile3);
// Assert
assertFalse(deletedFiles.contains(tempFile1), "Recent temp file should be preserved");
assertFalse(deletedFiles.contains(tempFile2), "Recent temp file should be preserved");
@ -437,28 +437,28 @@ public class TempFileCleanupServiceTest {
/**
* Helper method to invoke the private cleanupDirectoryStreaming method using reflection
*/
private void invokeCleanupDirectoryStreaming(Path directory, boolean containerMode, int depth, long maxAgeMillis)
private void invokeCleanupDirectoryStreaming(Path directory, boolean containerMode, int depth, long maxAgeMillis)
throws IOException {
try {
// Create a consumer that tracks deleted files
AtomicInteger deleteCount = new AtomicInteger(0);
Consumer<Path> deleteCallback = path -> deleteCount.incrementAndGet();
// Get the method with updated signature
var method = TempFileCleanupService.class.getDeclaredMethod(
"cleanupDirectoryStreaming",
"cleanupDirectoryStreaming",
Path.class, boolean.class, int.class, long.class, boolean.class, Consumer.class);
method.setAccessible(true);
// Invoke the method with appropriate parameters
method.invoke(cleanupService, directory, containerMode, depth, maxAgeMillis, false, deleteCallback);
} catch (Exception e) {
throw new RuntimeException("Error invoking cleanupDirectoryStreaming", e);
}
}
// Matcher for exact path equality
private static Path eq(Path path) {
return argThat(arg -> arg != null && arg.equals(path));
}
}
}

View File

@ -27,7 +27,7 @@ public class FileToPdfTest {
String fileName = "test.html"; // Sample file name indicating an HTML file
boolean disableSanitize = false; // Flag to control sanitization
TempFileManager tempFileManager = mock(TempFileManager.class); // Mock TempFileManager
// Mock the temp file creation to return real temp files
try {
when(tempFileManager.createTempFile(anyString()))

View File

@ -22,7 +22,7 @@ class SpringContextHolderTest {
void testSetApplicationContext() {
// Act
contextHolder.setApplicationContext(mockApplicationContext);
// Assert
assertTrue(SpringContextHolder.isInitialized());
}
@ -33,10 +33,10 @@ class SpringContextHolderTest {
contextHolder.setApplicationContext(mockApplicationContext);
TestBean expectedBean = new TestBean();
when(mockApplicationContext.getBean(TestBean.class)).thenReturn(expectedBean);
// Act
TestBean result = SpringContextHolder.getBean(TestBean.class);
// Assert
assertSame(expectedBean, result);
verify(mockApplicationContext).getBean(TestBean.class);
@ -46,10 +46,10 @@ class SpringContextHolderTest {
@Test
void testGetBean_ApplicationContextNotSet() {
// Don't set application context
// Act
TestBean result = SpringContextHolder.getBean(TestBean.class);
// Assert
assertNull(result);
}
@ -59,10 +59,10 @@ class SpringContextHolderTest {
// Arrange
contextHolder.setApplicationContext(mockApplicationContext);
when(mockApplicationContext.getBean(TestBean.class)).thenThrow(new org.springframework.beans.BeansException("Bean not found") {});
// Act
TestBean result = SpringContextHolder.getBean(TestBean.class);
// Assert
assertNull(result);
}
@ -70,4 +70,4 @@ class SpringContextHolderTest {
// Simple test class
private static class TestBean {
}
}
}

View File

@ -30,13 +30,13 @@ class JobControllerTest {
@Mock
private FileStorage fileStorage;
@Mock
private JobQueue jobQueue;
@Mock
private HttpServletRequest request;
private MockHttpSession session;
@InjectMocks
@ -45,7 +45,7 @@ class JobControllerTest {
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
// Setup mock session for tests
session = new MockHttpSession();
when(request.getSession()).thenReturn(session);
@ -66,7 +66,7 @@ class JobControllerTest {
assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals(mockResult, response.getBody());
}
@Test
void testGetJobStatus_ExistingJobInQueue() {
// Arrange
@ -83,11 +83,11 @@ class JobControllerTest {
// Assert
assertEquals(HttpStatus.OK, response.getStatusCode());
@SuppressWarnings("unchecked")
Map<String, Object> responseBody = (Map<String, Object>) response.getBody();
assertEquals(mockResult, responseBody.get("jobResult"));
@SuppressWarnings("unchecked")
Map<String, Object> queueInfo = (Map<String, Object>) responseBody.get("queueInfo");
assertTrue((Boolean) queueInfo.get("inQueue"));
@ -231,38 +231,38 @@ class JobControllerTest {
/*
* @Test void testGetJobStats() { // Arrange JobStats mockStats =
* JobStats.builder() .totalJobs(10) .activeJobs(3) .completedJobs(7) .build();
*
*
* when(taskManager.getJobStats()).thenReturn(mockStats);
*
*
* // Act ResponseEntity<?> response = controller.getJobStats();
*
*
* // Assert assertEquals(HttpStatus.OK, response.getStatusCode());
* assertEquals(mockStats, response.getBody()); }
*
*
* @Test void testCleanupOldJobs() { // Arrange when(taskManager.getJobStats())
* .thenReturn(JobStats.builder().totalJobs(10).build())
* .thenReturn(JobStats.builder().totalJobs(7).build());
*
*
* // Act ResponseEntity<?> response = controller.cleanupOldJobs();
*
*
* // Assert assertEquals(HttpStatus.OK, response.getStatusCode());
*
*
* @SuppressWarnings("unchecked") Map<String, Object> responseBody =
* (Map<String, Object>) response.getBody(); assertEquals("Cleanup complete",
* responseBody.get("message")); assertEquals(3,
* responseBody.get("removedJobs")); assertEquals(7,
* responseBody.get("remainingJobs"));
*
*
* verify(taskManager).cleanupOldJobs(); }
*
*
* @Test void testGetQueueStats() { // Arrange Map<String, Object>
* mockQueueStats = Map.of( "queuedJobs", 5, "queueCapacity", 10,
* "resourceStatus", "OK" );
*
*
* when(jobQueue.getQueueStats()).thenReturn(mockQueueStats);
*
*
* // Act ResponseEntity<?> response = controller.getQueueStats();
*
*
* // Assert assertEquals(HttpStatus.OK, response.getStatusCode());
* assertEquals(mockQueueStats, response.getBody());
* verify(jobQueue).getQueueStats(); }
@ -271,32 +271,32 @@ class JobControllerTest {
void testCancelJob_InQueue() {
// Arrange
String jobId = "job-in-queue";
// Setup user session with job authorization
java.util.Set<String> userJobIds = new java.util.HashSet<>();
userJobIds.add(jobId);
session.setAttribute("userJobIds", userJobIds);
when(jobQueue.isJobQueued(jobId)).thenReturn(true);
when(jobQueue.getJobPosition(jobId)).thenReturn(2);
when(jobQueue.cancelJob(jobId)).thenReturn(true);
// Act
ResponseEntity<?> response = controller.cancelJob(jobId);
// Assert
assertEquals(HttpStatus.OK, response.getStatusCode());
@SuppressWarnings("unchecked")
Map<String, Object> responseBody = (Map<String, Object>) response.getBody();
assertEquals("Job cancelled successfully", responseBody.get("message"));
assertTrue((Boolean) responseBody.get("wasQueued"));
assertEquals(2, responseBody.get("queuePosition"));
verify(jobQueue).cancelJob(jobId);
verify(taskManager, never()).setError(anyString(), anyString());
}
@Test
void testCancelJob_Running() {
// Arrange
@ -304,51 +304,51 @@ class JobControllerTest {
JobResult jobResult = new JobResult();
jobResult.setJobId(jobId);
jobResult.setComplete(false);
// Setup user session with job authorization
java.util.Set<String> userJobIds = new java.util.HashSet<>();
userJobIds.add(jobId);
session.setAttribute("userJobIds", userJobIds);
when(jobQueue.isJobQueued(jobId)).thenReturn(false);
when(taskManager.getJobResult(jobId)).thenReturn(jobResult);
// Act
ResponseEntity<?> response = controller.cancelJob(jobId);
// Assert
assertEquals(HttpStatus.OK, response.getStatusCode());
@SuppressWarnings("unchecked")
Map<String, Object> responseBody = (Map<String, Object>) response.getBody();
assertEquals("Job cancelled successfully", responseBody.get("message"));
assertFalse((Boolean) responseBody.get("wasQueued"));
assertEquals("n/a", responseBody.get("queuePosition"));
verify(jobQueue, never()).cancelJob(jobId);
verify(taskManager).setError(jobId, "Job was cancelled by user");
}
@Test
void testCancelJob_NotFound() {
// Arrange
String jobId = "non-existent-job";
// Setup user session with job authorization
java.util.Set<String> userJobIds = new java.util.HashSet<>();
userJobIds.add(jobId);
session.setAttribute("userJobIds", userJobIds);
when(jobQueue.isJobQueued(jobId)).thenReturn(false);
when(taskManager.getJobResult(jobId)).thenReturn(null);
// Act
ResponseEntity<?> response = controller.cancelJob(jobId);
// Assert
assertEquals(HttpStatus.NOT_FOUND, response.getStatusCode());
}
@Test
void testCancelJob_AlreadyComplete() {
// Arrange
@ -356,51 +356,51 @@ class JobControllerTest {
JobResult jobResult = new JobResult();
jobResult.setJobId(jobId);
jobResult.setComplete(true);
// Setup user session with job authorization
java.util.Set<String> userJobIds = new java.util.HashSet<>();
userJobIds.add(jobId);
session.setAttribute("userJobIds", userJobIds);
when(jobQueue.isJobQueued(jobId)).thenReturn(false);
when(taskManager.getJobResult(jobId)).thenReturn(jobResult);
// Act
ResponseEntity<?> response = controller.cancelJob(jobId);
// Assert
assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode());
@SuppressWarnings("unchecked")
Map<String, Object> responseBody = (Map<String, Object>) response.getBody();
assertEquals("Cannot cancel job that is already complete", responseBody.get("message"));
}
@Test
void testCancelJob_Unauthorized() {
// Arrange
String jobId = "unauthorized-job";
// Setup user session with other job IDs but not this one
java.util.Set<String> userJobIds = new java.util.HashSet<>();
userJobIds.add("other-job-1");
userJobIds.add("other-job-2");
session.setAttribute("userJobIds", userJobIds);
// Act
ResponseEntity<?> response = controller.cancelJob(jobId);
// Assert
assertEquals(HttpStatus.FORBIDDEN, response.getStatusCode());
@SuppressWarnings("unchecked")
Map<String, Object> responseBody = (Map<String, Object>) response.getBody();
assertEquals("You are not authorized to cancel this job", responseBody.get("message"));
// Verify no cancellation attempts were made
verify(jobQueue, never()).isJobQueued(anyString());
verify(jobQueue, never()).cancelJob(anyString());
verify(taskManager, never()).getJobResult(anyString());
verify(taskManager, never()).setError(anyString(), anyString());
}
}
}