Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions tests/Unit/Controller/SwControllerTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

declare(strict_types=1);

namespace OCA\ExeLearning\Tests\Unit\Controller;

use OCA\ExeLearning\Controller\SwController;
use OCP\AppFramework\Http;
use OCP\IRequest;
use PHPUnit\Framework\TestCase;

final class SwControllerTest extends TestCase {
public function testServesServiceWorkerWithRequiredHeaders(): void {
$controller = new SwController('exelearning', $this->createMock(IRequest::class));

$response = $controller->index();

self::assertSame(Http::STATUS_OK, $response->getStatus());
self::assertIsString($response->getData());
self::assertStringContainsString('addEventListener', $response->getData());
self::assertSame('text/javascript; charset=utf-8', $response->getHeaders()['Content-Type']);
self::assertSame('/apps/exelearning/', $response->getHeaders()['Service-Worker-Allowed']);
self::assertSame('public, max-age=300', $response->getHeaders()['Cache-Control']);
self::assertSame('nosniff', $response->getHeaders()['X-Content-Type-Options']);
}
}
48 changes: 48 additions & 0 deletions tests/Unit/Controller/TemplateControllerTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<?php

declare(strict_types=1);

namespace OCA\ExeLearning\Tests\Unit\Controller;

use OCA\ExeLearning\Controller\TemplateController;
use OCP\AppFramework\Http;
use OCP\IRequest;
use OCP\IUser;
use OCP\IUserSession;
use PHPUnit\Framework\TestCase;

final class TemplateControllerTest extends TestCase {
public function testRequiresAuthentication(): void {
$session = $this->createMock(IUserSession::class);
$session->method('getUser')->willReturn(null);
$controller = new TemplateController(
'exelearning',
$this->createMock(IRequest::class),
$session,
);

$response = $controller->blank();

self::assertSame(Http::STATUS_UNAUTHORIZED, $response->getStatus());
self::assertSame(['error' => 'Not authenticated'], $response->getData());
}

public function testStreamsBundledBlankPackage(): void {
$session = $this->createMock(IUserSession::class);
$session->method('getUser')->willReturn($this->createMock(IUser::class));
$controller = new TemplateController(
'exelearning',
$this->createMock(IRequest::class),
$session,
);

$response = $controller->blank();

self::assertSame(Http::STATUS_OK, $response->getStatus());
self::assertIsResource($response->getStream());
self::assertSame('application/vnd.exelearning.elpx', $response->getHeaders()['Content-Type']);
self::assertGreaterThan(0, (int)$response->getHeaders()['Content-Length']);
self::assertSame('nosniff', $response->getHeaders()['X-Content-Type-Options']);
self::assertSame('private, max-age=300', $response->getHeaders()['Cache-Control']);
}
}
162 changes: 162 additions & 0 deletions tests/Unit/Controller/ViewControllerTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
<?php

declare(strict_types=1);

namespace OCA\ExeLearning\Tests\Unit\Controller;

use OCA\ExeLearning\AppInfo\Application;
use OCA\ExeLearning\Controller\ViewController;
use OCA\ExeLearning\Service\ElpxPackageService;
use OCP\AppFramework\Http;
use OCP\AppFramework\Services\IInitialState;
use OCP\Files\File;
use OCP\Files\NotFoundException;
use OCP\Files\NotPermittedException;
use OCP\IRequest;
use OCP\IURLGenerator;
use OCP\IUser;
use OCP\IUserSession;
use OCP\Util;
use PHPUnit\Framework\TestCase;

final class ViewControllerTest extends TestCase {
private IUserSession $session;
private ElpxPackageService $packages;
private InitialStateRecorder $initialState;
private IURLGenerator $urlGenerator;
private ViewController $controller;

protected function setUp(): void {
Util::reset();
$this->session = $this->createMock(IUserSession::class);
$this->packages = $this->createMock(ElpxPackageService::class);
$this->initialState = new InitialStateRecorder();
$this->urlGenerator = $this->createMock(IURLGenerator::class);
$this->urlGenerator->method('linkToRoute')
->willReturn('/apps/exelearning/editor/iframe');
$this->controller = new ViewController(
'exelearning',
$this->createMock(IRequest::class),
$this->session,
$this->packages,
$this->initialState,
$this->urlGenerator,
);
}

public function testRequiresAuthentication(): void {
$this->session->method('getUser')->willReturn(null);

$response = $this->controller->index(fileId: 42);

self::assertSame(Http::STATUS_UNAUTHORIZED, $response->getStatus());
self::assertSame(['error' => 'Not authenticated'], $response->getData());
}

public function testProvidesFileStateWhenResolvedById(): void {
$this->authenticate();
$file = $this->packageFile();
$this->packages->expects(self::once())
->method('getForUserById')
->with('alice', 42)
->willReturn($file);

$response = $this->controller->index(fileId: 42);

self::assertSame([
'id' => 42,
'name' => 'lesson.elpx',
'path' => '/Lessons/lesson.elpx',
'mtime' => 123456,
'etag' => 'etag-1',
'writable' => true,
], $this->initialState->states['file']);
$this->assertPageStateAndPolicy($response, 'preview');
}

public function testProvidesFileStateWhenResolvedByPathAndEditorMode(): void {
$this->authenticate();
$file = $this->packageFile();
$this->packages->expects(self::once())
->method('getForUserByPath')
->with('alice', 'Lessons/lesson.elpx')
->willReturn($file);

$response = $this->controller->index(path: 'Lessons/lesson.elpx', mode: 'editor');

self::assertSame(42, $this->initialState->states['file']['id']);
$this->assertPageStateAndPolicy($response, 'editor');
}

public function testLookupErrorsStillRenderPageWithoutFileState(): void {
$this->authenticate();
$this->packages->expects(self::exactly(2))
->method('getForUserById')
->willReturnOnConsecutiveCalls(
self::throwException(new NotFoundException('missing')),
self::throwException(new NotPermittedException('denied')),
);

$missing = $this->controller->index(fileId: 42);
$denied = $this->controller->index(fileId: 43);

self::assertSame(Http::STATUS_OK, $missing->getStatus());
self::assertSame(Http::STATUS_OK, $denied->getStatus());
self::assertArrayNotHasKey('file', $this->initialState->states);
}

public function testPathLookupErrorAndEmptySelectionRenderPreview(): void {
$this->authenticate();
$this->packages->method('getForUserByPath')->willThrowException(new NotFoundException('missing'));

$failed = $this->controller->index(path: 'missing.elpx');
self::assertSame(Http::STATUS_OK, $failed->getStatus());
self::assertArrayNotHasKey('file', $this->initialState->states);

$this->initialState->states = [];
Util::reset();
$empty = $this->controller->index(path: '');
$this->assertPageStateAndPolicy($empty, 'preview');
}

private function authenticate(): void {
$user = $this->createMock(IUser::class);
$user->method('getUID')->willReturn('alice');
$this->session->method('getUser')->willReturn($user);
}

private function packageFile(): File {
$file = $this->createMock(File::class);
$file->method('getId')->willReturn(42);
$file->method('getName')->willReturn('lesson.elpx');
$file->method('getPath')->willReturn('/Lessons/lesson.elpx');
$file->method('getMTime')->willReturn(123456);
$file->method('getEtag')->willReturn('etag-1');
$file->method('isUpdateable')->willReturn(true);
return $file;
}

private function assertPageStateAndPolicy(object $response, string $mode): void {
self::assertSame(Http::STATUS_OK, $response->getStatus());
self::assertSame(false, $this->initialState->states['editorAvailable']);
self::assertSame('/apps/exelearning/editor/iframe', $this->initialState->states['editorIframeUrl']);
self::assertSame($mode, $this->initialState->states['initialMode']);
self::assertSame([[Application::APP_ID, 'exelearning-view']], Util::$scripts);

$policy = $response->getContentSecurityPolicy();
self::assertNotNull($policy);
self::assertSame(["'self'"], $policy->workerSrc);
self::assertSame(["'self'"], $policy->scriptDomains);
self::assertSame(["'self'"], $policy->connectDomains);
self::assertSame(["'self'"], $policy->frameDomains);
}
}

final class InitialStateRecorder implements IInitialState {
/** @var array<string, mixed> */
public array $states = [];

public function provideInitialState(string $key, mixed $value): void {
$this->states[$key] = $value;
}
}
49 changes: 49 additions & 0 deletions tests/bootstrap-standalone.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,23 @@ public function boot(IBootContext $context): void;
if (!interface_exists('OCP\\IUserSession', false)) {
eval('namespace OCP; interface IUserSession { public function getUser(); }');
}
if (!interface_exists('OCP\\IURLGenerator', false)) {
eval('
namespace OCP;
interface IURLGenerator {
public function linkTo(string $app, string $file);
public function linkToRoute(string $routeName, array $arguments = []);
}
');
}
if (!interface_exists('OCP\\AppFramework\\Services\\IInitialState', false)) {
eval('
namespace OCP\\AppFramework\\Services;
interface IInitialState {
public function provideInitialState(string $key, mixed $value): void;
}
');
}
if (!class_exists('OCP\\AppFramework\\Controller', false)) {
eval('
namespace OCP\\AppFramework;
Expand All @@ -77,6 +94,21 @@ class Http {
}
');
}
if (!class_exists('OCP\\AppFramework\\Http\\ContentSecurityPolicy', false)) {
eval('
namespace OCP\\AppFramework\\Http;
class ContentSecurityPolicy {
public array $workerSrc = [];
public array $scriptDomains = [];
public array $connectDomains = [];
public array $frameDomains = [];
public function addAllowedWorkerSrcDomain(string $domain): void { $this->workerSrc[] = $domain; }
public function addAllowedScriptDomain(string $domain): void { $this->scriptDomains[] = $domain; }
public function addAllowedConnectDomain(string $domain): void { $this->connectDomains[] = $domain; }
public function addAllowedFrameDomain(string $domain): void { $this->frameDomains[] = $domain; }
}
');
}
if (!class_exists('OCP\\AppFramework\\Http\\DataResponse', false)) {
eval('
namespace OCP\\AppFramework\\Http;
Expand All @@ -93,6 +125,18 @@ public function addHeader(string $name, string $value): void { $this->headers[$n
public function getHeaders(): array { return $this->headers; }
}
class DataDisplayResponse extends DataResponse {}
class TemplateResponse extends DataResponse {
public const RENDER_AS_USER = "user";
public ?ContentSecurityPolicy $contentSecurityPolicy = null;
public function __construct(
public string $appName,
public string $templateName,
array $params = [],
public string $renderAs = self::RENDER_AS_USER,
) { parent::__construct($params, 200); }
public function setContentSecurityPolicy(ContentSecurityPolicy $policy): void { $this->contentSecurityPolicy = $policy; }
public function getContentSecurityPolicy(): ?ContentSecurityPolicy { return $this->contentSecurityPolicy; }
}
class StreamResponse extends DataResponse {
public function __construct($stream) { parent::__construct($stream, 200); }
public function getStream() { return $this->data; }
Expand Down Expand Up @@ -130,6 +174,11 @@ public function getStorage();
public function getInternalPath();
public function fopen($mode);
public function getSize();
public function getId();
public function getPath();
public function getMTime();
public function getEtag();
public function isUpdateable();
}
');
}
Expand Down
3 changes: 3 additions & 0 deletions tests/phpunit.xml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,10 @@
<directory>../lib/AppInfo</directory>
<file>../lib/Controller/AssetController.php</file>
<file>../lib/Controller/PackageController.php</file>
<file>../lib/Controller/SwController.php</file>
<file>../lib/Controller/TemplateController.php</file>
<file>../lib/Controller/ThumbnailController.php</file>
<file>../lib/Controller/ViewController.php</file>
<directory>../lib/Preview</directory>
<directory>../lib/Service</directory>
</include>
Expand Down
Loading