unit TestTasks; interface uses DUnitX.TestFramework, System.SysUtils, System.Classes, System.SyncObjs, Myc.Core.Tasks, Myc.Signals, // For IMycSemaphore, Signals global Myc.Core.Atomic; // If any atomic primitives are directly needed for test setup/assertion type [TestFixture] TMycTaskFactoryTests = class(TObject) private FFactory: IMycTaskFactory; procedure TestProcExecute(var executed: Boolean; signal: IMycSemaphore); public [Setup] procedure Setup; [TearDown] procedure TearDown; [Test] procedure TestFactoryCreationAndTeardown; [Test] procedure TestCreateThreadExecutesAndSignals; [Test] procedure TestRunImmediateJob; [Test] procedure TestRunDelayedJobExecutesAfterAllNotifies; [Test] procedure TestRunDelayedJobDoesNotExecutePrematurely; [Test] procedure TestWaitForAlreadySetState; [Test] procedure TestThreadInfoMethods; [Test] procedure TestExceptionPropagationFromJob; [Test] procedure TestRunJobAfterFactoryTeardown; [Test] procedure TestWaitForInWorkerThreadRaisesException; end; implementation { TMycTaskFactoryTests } procedure TMycTaskFactoryTests.Setup; begin FFactory := TMycTaskFactory.Create; // Creates the factory instance end; procedure TMycTaskFactoryTests.TearDown; begin if Assigned(FFactory) then begin FFactory.Teardown; // Explicitly teardown FFactory := nil; end; end; procedure TMycTaskFactoryTests.TestProcExecute(var executed: Boolean; signal: IMycSemaphore); begin executed := True; if Assigned(signal) then signal.Notify; end; procedure TMycTaskFactoryTests.TestFactoryCreationAndTeardown; var threadCount: Integer; begin Assert.IsNotNull(FFactory, 'Factory should be created'); threadCount := FFactory.ThreadCount; Assert.AreEqual(TThread.ProcessorCount, threadCount, 'Thread count should match processor count'); // Teardown is implicitly tested by the [TearDown] method end; procedure TMycTaskFactoryTests.TestCreateThreadExecutesAndSignals; var executed: Boolean; threadState: IMycState; procWrapper: TProc; begin executed := False; // Wrap the procedure to match TProc signature if TestProcExecute is used, // or define an anonymous procedure directly. procWrapper := procedure begin executed := True; end; threadState := FFactory.CreateThread(procWrapper); Assert.IsNotNull(threadState, 'CreateThread should return a valid state object'); FFactory.WaitFor(threadState); // Wait for the thread to complete Assert.IsTrue(executed, 'Procedure in created thread should have executed'); end; procedure TMycTaskFactoryTests.TestRunImmediateJob; var jobExecuted: Boolean; jobCompletedSignal: IMycSemaphore; begin jobExecuted := False; jobCompletedSignal := Signals.CreateSemaphore(1); // Semaphore to signal job completion FFactory.Run(0, // StartCount = 0 for immediate execution procedure begin jobExecuted := True; jobCompletedSignal.Notify; // Signal completion end); FFactory.WaitFor(jobCompletedSignal.State); // Wait for the job to complete Assert.IsTrue(jobExecuted, 'Immediate job should have executed'); end; procedure TMycTaskFactoryTests.TestRunDelayedJobExecutesAfterAllNotifies; var jobExecuted: Boolean; jobCompletedSignal: IMycSemaphore; subscriber: IMycSubscriber; startCount: Integer; begin jobExecuted := False; startCount := 2; jobCompletedSignal := Signals.CreateSemaphore(1); subscriber := FFactory.Run(startCount, procedure begin jobExecuted := True; jobCompletedSignal.Notify; end); Assert.IsNotNull(subscriber, 'Run should return a subscriber for delayed job'); // Corrected line: Assert.AreNotEqual(Signals.Null, subscriber, 'Subscriber should not be Signals.Null for StartCount > 0'); subscriber.Notify; // First notification subscriber.Notify; // Second notification, job should now be enqueued FFactory.WaitFor(jobCompletedSignal.State); // Wait for job completion Assert.IsTrue(jobExecuted, 'Delayed job should execute after all notifications'); end; procedure TMycTaskFactoryTests.TestRunDelayedJobDoesNotExecutePrematurely; var jobExecuted: Boolean; jobCompletedSignal: IMycSemaphore; // Not strictly needed here as job shouldn't run subscriber: IMycSubscriber; startCount: Integer; dummyWaitSignal: IMycSemaphore; begin jobExecuted := False; startCount := 3; jobCompletedSignal := Signals.CreateSemaphore(1); // For the job, if it were to run dummyWaitSignal := Signals.CreateSemaphore(1); subscriber := FFactory.Run(startCount, procedure begin jobExecuted := True; jobCompletedSignal.Notify; end); Assert.IsNotNull(subscriber, 'Run should return a subscriber for delayed job_P2'); subscriber.Notify; // First notification Assert.IsFalse(jobExecuted, 'Job should not execute after one notification_P2'); subscriber.Notify; // Second notification Assert.IsFalse(jobExecuted, 'Job should not execute after two notifications_P2'); // To give a very brief moment for any potential async execution attempt. // This is not foolproof for catching race conditions but can help. // A more robust way is harder without specific test hooks in the factory. FFactory.Run(0, procedure begin dummyWaitSignal.Notify; end); FFactory.WaitFor(dummyWaitSignal.State); // Ensures task queue is processed slightly Assert.IsFalse(jobExecuted, 'Job should still not have executed before third notify_P2'); end; procedure TMycTaskFactoryTests.TestWaitForAlreadySetState; var alreadySetSignal: IMycSemaphore; startTime, endTime: Cardinal; begin alreadySetSignal := Signals.CreateSemaphore(0); // Count = 0 means it's already set Assert.IsTrue(alreadySetSignal.State.IsSet, 'Signal should be initially set'); startTime := TThread.GetTickCount; FFactory.WaitFor(alreadySetSignal.State); // Should return immediately endTime := TThread.GetTickCount; // Check that WaitFor didn't block for a significant time // Allow a small delta for processing, e.g., less than 50ms Assert.IsTrue((endTime - startTime) < 50, 'WaitFor on an already set state should not block significantly'); end; procedure TMycTaskFactoryTests.TestThreadInfoMethods; var inMainThreadInJob: Boolean; inWorkerThreadInJob: Boolean; jobDoneSignal: IMycSemaphore; begin inMainThreadInJob := True; // Default to a state that would fail the assert inWorkerThreadInJob := False; // Default to a state that would fail the assert jobDoneSignal := Signals.CreateSemaphore(1); Assert.IsTrue(FFactory.InMainThread, 'Test method itself should be in main thread'); Assert.IsFalse(FFactory.InWorkerThread, 'Test method itself should not be in a factory worker thread'); FFactory.Run(0, procedure begin inMainThreadInJob := FFactory.InMainThread; inWorkerThreadInJob := FFactory.InWorkerThread; jobDoneSignal.Notify; end); FFactory.WaitFor(jobDoneSignal.State); // Wait for the job to complete and set flags Assert.IsFalse(inMainThreadInJob, 'Job executed by factory should not be in main thread'); Assert.IsTrue(inWorkerThreadInJob, 'Job executed by factory should be in a worker thread'); end; procedure TMycTaskFactoryTests.TestExceptionPropagationFromJob; var jobDoneSignal: IMycSemaphore; // To ensure job has a chance to run begin jobDoneSignal := Signals.CreateSemaphore(1); FFactory.Run(0, procedure var dummy: Integer; // To avoid hint W1035 if no other code is in the proc begin dummy := 0; // Assign to avoid compiler warning if variable is unused // Raise the specific nested exception type raise TMycTaskFactory.ETaskException.Create('Test Exception From Job'); // jobDoneSignal.Notify; // This line will not be reached end); // Give a brief moment for the job to be scheduled and potentially raise the exception. // Run another dummy job to help process the queue and ensure the exception is set. FFactory.Run(0, procedure begin jobDoneSignal.Notify; end); FFactory.WaitFor(jobDoneSignal.State); Assert.WillRaise( procedure begin (FFactory as TMycTaskFactory).HandleException; // This should re-raise the exception end, TMycTaskFactory.ETaskException, // Correctly qualified exception type 'HandleException should re-raise the exception from the job' ); // Verify FException is cleared after being handled var noExceptionRaised: Boolean := True; try (FFactory as TMycTaskFactory).HandleException; // Should not raise anything now except noExceptionRaised := False; end; Assert.IsTrue(noExceptionRaised, 'FException should be cleared after HandleException'); end; procedure TMycTaskFactoryTests.TestRunJobAfterFactoryTeardown; begin FFactory.Teardown; // Explicitly teardown the factory Assert.WillRaise( procedure begin FFactory.Run(0, procedure begin end); // Attempt to run a job end, TMycTaskFactory.ETaskException, // Expecting the factory's specific exception type 'Running a job on a torn-down factory should raise ETaskException' ); end; procedure TMycTaskFactoryTests.TestWaitForInWorkerThreadRaisesException; var exceptionCaughtInJob: Boolean; jobDoneSignal: IMycSemaphore; dummyStateToWaitFor: IMycState; begin exceptionCaughtInJob := False; jobDoneSignal := Signals.CreateSemaphore(1); dummyStateToWaitFor := Signals.CreateSemaphore(1).State; // A state that will never be set by this test logic FFactory.Run(0, procedure begin try FFactory.WaitFor(dummyStateToWaitFor); // This should raise ETaskException except on E: TMycTaskFactory.ETaskException do begin // Check message if needed: Assert.AreEqual('Waiting not allowed within tasks', E.Message); exceptionCaughtInJob := True; end; // Else: Unexpected exception, test will fail by jobDoneSignal not being set or flag remaining false end; jobDoneSignal.Notify; // Signal completion of the job's execution path end); FFactory.WaitFor(jobDoneSignal.State); // Wait for the job to finish Assert.IsTrue(exceptionCaughtInJob, 'WaitFor called within a worker thread job should raise ETaskException'); end; initialization // Register TestFixtures TDUnitX.RegisterTestFixture(TMycTaskFactoryTests); end.