TextProcessingTest.php 12 KB

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