1
0

TextProcessingTest.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. <?php
  2. /**
  3. * Copyright (c) 2023 Marcel Klehr <mklehr@gmx.net>
  4. * This file is licensed under the Affero General Public License version 3 or
  5. * later.
  6. * See the COPYING-README file.
  7. */
  8. namespace Test\TextProcessing;
  9. use OC\AppFramework\Bootstrap\Coordinator;
  10. use OC\AppFramework\Bootstrap\RegistrationContext;
  11. use OC\AppFramework\Bootstrap\ServiceRegistration;
  12. use OC\EventDispatcher\EventDispatcher;
  13. use OC\TextProcessing\Db\Task as DbTask;
  14. use OC\TextProcessing\Db\TaskMapper;
  15. use OC\TextProcessing\Manager;
  16. use OC\TextProcessing\RemoveOldTasksBackgroundJob;
  17. use OC\TextProcessing\TaskBackgroundJob;
  18. use OCP\AppFramework\Db\DoesNotExistException;
  19. use OCP\AppFramework\Utility\ITimeFactory;
  20. use OCP\Common\Exception\NotFoundException;
  21. use OCP\EventDispatcher\IEventDispatcher;
  22. use OCP\IServerContainer;
  23. use OCP\TextProcessing\Events\TaskFailedEvent;
  24. use OCP\TextProcessing\Events\TaskSuccessfulEvent;
  25. use OCP\TextProcessing\FreePromptTaskType;
  26. use OCP\TextProcessing\IManager;
  27. use OCP\TextProcessing\IProvider;
  28. use OCP\TextProcessing\SummaryTaskType;
  29. use OCP\PreConditionNotMetException;
  30. use OCP\TextProcessing\Task;
  31. use OCP\TextProcessing\TopicsTaskType;
  32. use PHPUnit\Framework\Constraint\IsInstanceOf;
  33. use Psr\Log\LoggerInterface;
  34. use Test\BackgroundJob\DummyJobList;
  35. class SuccessfulSummaryProvider implements IProvider {
  36. public bool $ran = false;
  37. public function getName(): string {
  38. return 'TEST Vanilla LLM Provider';
  39. }
  40. public function process(string $prompt): string {
  41. $this->ran = true;
  42. return $prompt . ' Summarize';
  43. }
  44. public function getTaskType(): string {
  45. return SummaryTaskType::class;
  46. }
  47. }
  48. class FailingSummaryProvider implements IProvider {
  49. public bool $ran = false;
  50. public function getName(): string {
  51. return 'TEST Vanilla LLM Provider';
  52. }
  53. public function process(string $prompt): string {
  54. $this->ran = true;
  55. throw new \Exception('ERROR');
  56. }
  57. public function getTaskType(): string {
  58. return SummaryTaskType::class;
  59. }
  60. }
  61. class FreePromptProvider implements IProvider {
  62. public bool $ran = false;
  63. public function getName(): string {
  64. return 'TEST Free Prompt Provider';
  65. }
  66. public function process(string $prompt): string {
  67. $this->ran = true;
  68. return $prompt . ' Free Prompt';
  69. }
  70. public function getTaskType(): string {
  71. return FreePromptTaskType::class;
  72. }
  73. }
  74. class TextProcessingTest extends \Test\TestCase {
  75. private IManager $manager;
  76. private Coordinator $coordinator;
  77. protected function setUp(): void {
  78. parent::setUp();
  79. $this->providers = [
  80. SuccessfulSummaryProvider::class => new SuccessfulSummaryProvider(),
  81. FailingSummaryProvider::class => new FailingSummaryProvider(),
  82. FreePromptProvider::class => new FreePromptProvider(),
  83. ];
  84. $this->serverContainer = $this->createMock(IServerContainer::class);
  85. $this->serverContainer->expects($this->any())->method('get')->willReturnCallback(function ($class) {
  86. return $this->providers[$class];
  87. });
  88. $this->eventDispatcher = new EventDispatcher(
  89. new \Symfony\Component\EventDispatcher\EventDispatcher(),
  90. $this->serverContainer,
  91. \OC::$server->get(LoggerInterface::class),
  92. );
  93. $this->registrationContext = $this->createMock(RegistrationContext::class);
  94. $this->coordinator = $this->createMock(Coordinator::class);
  95. $this->coordinator->expects($this->any())->method('getRegistrationContext')->willReturn($this->registrationContext);
  96. $this->currentTime = new \DateTimeImmutable('now');
  97. $this->taskMapper = $this->createMock(TaskMapper::class);
  98. $this->tasksDb = [];
  99. $this->taskMapper
  100. ->expects($this->any())
  101. ->method('insert')
  102. ->willReturnCallback(function (DbTask $task) {
  103. $task->setId(count($this->tasksDb) ? max(array_keys($this->tasksDb)) : 1);
  104. $task->setLastUpdated($this->currentTime->getTimestamp());
  105. $this->tasksDb[$task->getId()] = $task->toRow();
  106. return $task;
  107. });
  108. $this->taskMapper
  109. ->expects($this->any())
  110. ->method('update')
  111. ->willReturnCallback(function (DbTask $task) {
  112. $task->setLastUpdated($this->currentTime->getTimestamp());
  113. $this->tasksDb[$task->getId()] = $task->toRow();
  114. return $task;
  115. });
  116. $this->taskMapper
  117. ->expects($this->any())
  118. ->method('find')
  119. ->willReturnCallback(function (int $id) {
  120. if (!isset($this->tasksDb[$id])) {
  121. throw new DoesNotExistException('Could not find it');
  122. }
  123. return DbTask::fromRow($this->tasksDb[$id]);
  124. });
  125. $this->taskMapper
  126. ->expects($this->any())
  127. ->method('deleteOlderThan')
  128. ->willReturnCallback(function (int $timeout) {
  129. $this->tasksDb = array_filter($this->tasksDb, function (array $task) use ($timeout) {
  130. return $task['last_updated'] >= $this->currentTime->getTimestamp() - $timeout;
  131. });
  132. });
  133. $this->jobList = $this->createPartialMock(DummyJobList::class, ['add']);
  134. $this->jobList->expects($this->any())->method('add')->willReturnCallback(function () {
  135. });
  136. $this->manager = new Manager(
  137. $this->serverContainer,
  138. $this->coordinator,
  139. \OC::$server->get(LoggerInterface::class),
  140. $this->jobList,
  141. $this->taskMapper,
  142. );
  143. }
  144. public function testShouldNotHaveAnyProviders() {
  145. $this->registrationContext->expects($this->any())->method('getTextProcessingProviders')->willReturn([]);
  146. $this->assertCount(0, $this->manager->getAvailableTaskTypes());
  147. $this->assertFalse($this->manager->hasProviders());
  148. $this->expectException(PreConditionNotMetException::class);
  149. $this->manager->runTask(new \OCP\TextProcessing\Task(FreePromptTaskType::class, 'Hello', 'test', null));
  150. }
  151. public function testProviderShouldBeRegisteredAndRun() {
  152. $this->registrationContext->expects($this->any())->method('getTextProcessingProviders')->willReturn([
  153. new ServiceRegistration('test', SuccessfulSummaryProvider::class)
  154. ]);
  155. $this->assertCount(1, $this->manager->getAvailableTaskTypes());
  156. $this->assertTrue($this->manager->hasProviders());
  157. $this->assertEquals('Hello Summarize', $this->manager->runTask(new Task(SummaryTaskType::class, 'Hello', 'test', null)));
  158. // Summaries are not implemented by the vanilla provider, only free prompt
  159. $this->expectException(PreConditionNotMetException::class);
  160. $this->manager->runTask(new Task(FreePromptTaskType::class, 'Hello', 'test', null));
  161. }
  162. public function testProviderShouldBeRegisteredAndScheduled() {
  163. // register provider
  164. $this->registrationContext->expects($this->any())->method('getTextProcessingProviders')->willReturn([
  165. new ServiceRegistration('test', SuccessfulSummaryProvider::class)
  166. ]);
  167. $this->assertCount(1, $this->manager->getAvailableTaskTypes());
  168. $this->assertTrue($this->manager->hasProviders());
  169. // create task object
  170. $task = new Task(SummaryTaskType::class, 'Hello', 'test', null);
  171. $this->assertNull($task->getId());
  172. $this->assertNull($task->getOutput());
  173. // schedule works
  174. $this->assertEquals(Task::STATUS_UNKNOWN, $task->getStatus());
  175. $this->manager->scheduleTask($task);
  176. // Task object is up-to-date
  177. $this->assertNotNull($task->getId());
  178. $this->assertNull($task->getOutput());
  179. $this->assertEquals(Task::STATUS_SCHEDULED, $task->getStatus());
  180. // Task object retrieved from db is up-to-date
  181. $task2 = $this->manager->getTask($task->getId());
  182. $this->assertEquals($task->getId(), $task2->getId());
  183. $this->assertEquals('Hello', $task2->getInput());
  184. $this->assertNull($task2->getOutput());
  185. $this->assertEquals(Task::STATUS_SCHEDULED, $task2->getStatus());
  186. $this->eventDispatcher = $this->createMock(IEventDispatcher::class);
  187. $this->eventDispatcher->expects($this->once())->method('dispatchTyped')->with(new IsInstanceOf(TaskSuccessfulEvent::class));
  188. // run background job
  189. $bgJob = new TaskBackgroundJob(
  190. \OC::$server->get(ITimeFactory::class),
  191. $this->manager,
  192. $this->eventDispatcher,
  193. );
  194. $bgJob->setArgument(['taskId' => $task->getId()]);
  195. $bgJob->start($this->jobList);
  196. $provider = $this->providers[SuccessfulSummaryProvider::class];
  197. $this->assertTrue($provider->ran);
  198. // Task object retrieved from db is up-to-date
  199. $task3 = $this->manager->getTask($task->getId());
  200. $this->assertEquals($task->getId(), $task3->getId());
  201. $this->assertEquals('Hello', $task3->getInput());
  202. $this->assertEquals('Hello Summarize', $task3->getOutput());
  203. $this->assertEquals(Task::STATUS_SUCCESSFUL, $task3->getStatus());
  204. }
  205. public function testMultipleProvidersShouldBeRegisteredAndRunCorrectly() {
  206. $this->registrationContext->expects($this->any())->method('getTextProcessingProviders')->willReturn([
  207. new ServiceRegistration('test', SuccessfulSummaryProvider::class),
  208. new ServiceRegistration('test', FreePromptProvider::class),
  209. ]);
  210. $this->assertCount(2, $this->manager->getAvailableTaskTypes());
  211. $this->assertTrue($this->manager->hasProviders());
  212. // Try free prompt again
  213. $this->assertEquals('Hello Free Prompt', $this->manager->runTask(new Task(FreePromptTaskType::class, 'Hello', 'test', null)));
  214. // Try summary task
  215. $this->assertEquals('Hello Summarize', $this->manager->runTask(new Task(SummaryTaskType::class, 'Hello', 'test', null)));
  216. // Topics are not implemented by both the vanilla provider and the full provider
  217. $this->expectException(PreConditionNotMetException::class);
  218. $this->manager->runTask(new Task(TopicsTaskType::class, 'Hello', 'test', null));
  219. }
  220. public function testNonexistentTask() {
  221. $this->expectException(NotFoundException::class);
  222. $this->manager->getTask(98765432456);
  223. }
  224. public function testTaskFailure() {
  225. // register provider
  226. $this->registrationContext->expects($this->any())->method('getTextProcessingProviders')->willReturn([
  227. new ServiceRegistration('test', FailingSummaryProvider::class),
  228. ]);
  229. $this->assertCount(1, $this->manager->getAvailableTaskTypes());
  230. $this->assertTrue($this->manager->hasProviders());
  231. // create task object
  232. $task = new Task(SummaryTaskType::class, 'Hello', 'test', null);
  233. $this->assertNull($task->getId());
  234. $this->assertNull($task->getOutput());
  235. // schedule works
  236. $this->assertEquals(Task::STATUS_UNKNOWN, $task->getStatus());
  237. $this->manager->scheduleTask($task);
  238. // Task object is up-to-date
  239. $this->assertNotNull($task->getId());
  240. $this->assertNull($task->getOutput());
  241. $this->assertEquals(Task::STATUS_SCHEDULED, $task->getStatus());
  242. // Task object retrieved from db is up-to-date
  243. $task2 = $this->manager->getTask($task->getId());
  244. $this->assertEquals($task->getId(), $task2->getId());
  245. $this->assertEquals('Hello', $task2->getInput());
  246. $this->assertNull($task2->getOutput());
  247. $this->assertEquals(Task::STATUS_SCHEDULED, $task2->getStatus());
  248. $this->eventDispatcher = $this->createMock(IEventDispatcher::class);
  249. $this->eventDispatcher->expects($this->once())->method('dispatchTyped')->with(new IsInstanceOf(TaskFailedEvent::class));
  250. // run background job
  251. $bgJob = new TaskBackgroundJob(
  252. \OC::$server->get(ITimeFactory::class),
  253. $this->manager,
  254. $this->eventDispatcher,
  255. );
  256. $bgJob->setArgument(['taskId' => $task->getId()]);
  257. $bgJob->start($this->jobList);
  258. $provider = $this->providers[FailingSummaryProvider::class];
  259. $this->assertTrue($provider->ran);
  260. // Task object retrieved from db is up-to-date
  261. $task3 = $this->manager->getTask($task->getId());
  262. $this->assertEquals($task->getId(), $task3->getId());
  263. $this->assertEquals('Hello', $task3->getInput());
  264. $this->assertNull($task3->getOutput());
  265. $this->assertEquals(Task::STATUS_FAILED, $task3->getStatus());
  266. }
  267. public function testOldTasksShouldBeCleanedUp() {
  268. $this->registrationContext->expects($this->any())->method('getTextProcessingProviders')->willReturn([
  269. new ServiceRegistration('test', SuccessfulSummaryProvider::class)
  270. ]);
  271. $this->assertCount(1, $this->manager->getAvailableTaskTypes());
  272. $this->assertTrue($this->manager->hasProviders());
  273. $task = new Task(SummaryTaskType::class, 'Hello', 'test', null);
  274. $this->assertEquals('Hello Summarize', $this->manager->runTask($task));
  275. $this->currentTime = $this->currentTime->add(new \DateInterval('P1Y'));
  276. // run background job
  277. $bgJob = new RemoveOldTasksBackgroundJob(
  278. \OC::$server->get(ITimeFactory::class),
  279. $this->taskMapper,
  280. \OC::$server->get(LoggerInterface::class),
  281. );
  282. $bgJob->setArgument([]);
  283. $bgJob->start($this->jobList);
  284. $this->expectException(NotFoundException::class);
  285. $this->manager->getTask($task->getId());
  286. }
  287. }