1
0

TextProcessingTest.php 13 KB

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