Add initial Plenario live polling app
CI / Deploy / test (push) Successful in 49s
CI / Deploy / deploy (push) Failing after 5s

CakePHP 5.4 app for live polls: create via email without login, manage
via secret admin link, join via code. Includes slide types (choice,
wordcloud, open, scale, content), presenter mode, CSV export, captcha,
throttling, tests and Gitea CI/deploy workflow.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
gnilebeinandClaude Opus 5.5 committed 2026-11-07 13:24:29 +01:00
commit eb319f8c1e
120 files changed
+15572

No files matched your search

+88
View File
@@ -0,0 +1,88 @@
<?php
declare(strict_types=1);
/**
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
* @link https://cakephp.org CakePHP(tm) Project
* @since 3.3.0
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
namespace App\Test\TestCase;
use App\Application;
use App\Middleware\HostHeaderMiddleware;
use Cake\Core\Configure;
use Cake\Error\Middleware\ErrorHandlerMiddleware;
use Cake\Http\MiddlewareQueue;
use Cake\Routing\Middleware\AssetMiddleware;
use Cake\Routing\Middleware\RoutingMiddleware;
use Cake\TestSuite\IntegrationTestTrait;
use Cake\TestSuite\TestCase;
/**
* ApplicationTest class
*/
class ApplicationTest extends TestCase
{
use IntegrationTestTrait;
/**
* Test bootstrap in production.
*
* @return void
*/
public function testBootstrap()
{
Configure::write('debug', false);
$app = new Application(dirname(__DIR__, 2) . '/config');
$app->bootstrap();
$plugins = $app->getPlugins();
$this->assertTrue($plugins->has('Bake'), 'plugins has Bake?');
$this->assertFalse($plugins->has('DebugKit'), 'plugins has DebugKit?');
$this->assertTrue($plugins->has('Migrations'), 'plugins has Migrations?');
}
/**
* Test bootstrap add DebugKit plugin in debug mode.
*
* @return void
*/
public function testBootstrapInDebug()
{
Configure::write('debug', true);
$app = new Application(dirname(__DIR__, 2) . '/config');
$app->bootstrap();
$plugins = $app->getPlugins();
$this->assertTrue($plugins->has('DebugKit'), 'plugins has DebugKit?');
}
/**
* testMiddleware
*
* @return void
*/
public function testMiddleware()
{
$app = new Application(dirname(__DIR__, 2) . '/config');
$middleware = new MiddlewareQueue();
$middleware = $app->middleware($middleware);
$this->assertInstanceOf(ErrorHandlerMiddleware::class, $middleware->current());
$middleware->seek(1);
$this->assertInstanceOf(HostHeaderMiddleware::class, $middleware->current());
$middleware->seek(2);
$this->assertInstanceOf(AssetMiddleware::class, $middleware->current());
$middleware->seek(3);
$this->assertInstanceOf(RoutingMiddleware::class, $middleware->current());
}
}
+79
View File
@@ -0,0 +1,79 @@
<?php
declare(strict_types=1);
namespace App\Test\TestCase\Captcha;
use App\Captcha\CaptchaFactory;
use App\Captcha\MathCaptcha;
use App\Captcha\NoCaptcha;
use App\Captcha\RecaptchaCaptcha;
use Cake\Http\Client;
use Cake\Http\Client\Response as ClientResponse;
use Cake\Http\ServerRequest;
use Cake\Http\Session;
use Cake\TestSuite\TestCase;
use InvalidArgumentException;
/**
* Captcha implementations.
*/
class CaptchaTest extends TestCase
{
public function testFactory(): void
{
$this->assertInstanceOf(NoCaptcha::class, CaptchaFactory::create('x', 'none'));
$this->assertInstanceOf(MathCaptcha::class, CaptchaFactory::create('x', 'math'));
$this->assertInstanceOf(RecaptchaCaptcha::class, CaptchaFactory::create('x', 'recaptcha'));
$this->expectException(InvalidArgumentException::class);
CaptchaFactory::create('x', 'unknown');
}
public function testMathCaptchaIsSingleUse(): void
{
$session = new Session();
$request = new ServerRequest(['session' => $session]);
$captcha = new MathCaptcha('create');
$challenge = $captcha->challenge($request);
$this->assertSame('math', $challenge['type']);
$answer = (string)$session->read('Captcha.math.create');
$submit = (new ServerRequest(['session' => $session]))->withData('captcha_answer', $answer);
$this->assertTrue($captcha->verify($submit));
$this->assertFalse($captcha->verify($submit), 'second verification must fail');
}
public function testMathCaptchaScopesAreIndependent(): void
{
$session = new Session();
$request = new ServerRequest(['session' => $session]);
(new MathCaptcha('create'))->challenge($request);
$answer = (string)$session->read('Captcha.math.create');
$submit = (new ServerRequest(['session' => $session]))->withData('captcha_answer', $answer);
$this->assertFalse((new MathCaptcha('recover'))->verify($submit));
}
public function testRecaptchaVerifiesWithGoogle(): void
{
$client = $this->createMock(Client::class);
$client->expects($this->once())
->method('post')
->with(RecaptchaCaptcha::VERIFY_URL, $this->callback(fn($data) => $data['secret'] === 'secret' && $data['response'] === 'tok'))
->willReturn(new ClientResponse(['HTTP/1.1 200 OK', 'Content-Type: application/json'], '{"success": true}'));
$captcha = new RecaptchaCaptcha('site', 'secret', $client);
$request = (new ServerRequest())->withData('g-recaptcha-response', 'tok');
$this->assertTrue($captcha->verify($request));
}
public function testRecaptchaFailsClosed(): void
{
$client = $this->createStub(Client::class);
$client->method('post')->willReturn(new ClientResponse(['HTTP/1.1 200 OK'], '{"success": false}'));
$request = (new ServerRequest())->withData('g-recaptcha-response', 'tok');
$this->assertFalse((new RecaptchaCaptcha('site', 'secret', $client))->verify($request));
$this->assertFalse((new RecaptchaCaptcha('', '', $client))->verify($request), 'missing keys');
$this->assertFalse((new RecaptchaCaptcha('site', 'secret', $client))->verify(new ServerRequest()), 'missing token');
}
}
@@ -0,0 +1,186 @@
<?php
declare(strict_types=1);
namespace App\Test\TestCase\Controller;
use App\Model\Entity\Slide;
use App\Model\Table\PollsTable;
use App\Test\TestCase\PlenarioTestTrait;
use Cake\TestSuite\EmailTrait;
use Cake\TestSuite\IntegrationTestTrait;
use Cake\TestSuite\TestCase;
/**
* Admin area behind the secret token: dashboard, slides, presenter controls.
*/
class AdminControllerTest extends TestCase
{
use EmailTrait;
use IntegrationTestTrait;
use PlenarioTestTrait;
/**
* @var list<string>
*/
protected array $fixtures = ['app.Polls', 'app.Slides', 'app.SlideOptions', 'app.Responses'];
protected function setUp(): void
{
parent::setUp();
$this->enableCsrfToken();
}
public function testInvalidTokenIs404(): void
{
$this->createPoll();
$this->get('/admin/' . str_repeat('x', 43));
$this->assertResponseCode(404);
}
public function testDashboardSendsPrivacyHeaders(): void
{
[$poll, $token] = $this->createPoll('Meine <Umfrage>');
$this->get("/admin/$token");
$this->assertResponseOk();
$this->assertResponseContains('Meine &lt;Umfrage&gt;');
$this->assertResponseContains($poll->formattedJoinCode());
$this->assertHeader('Referrer-Policy', 'no-referrer');
$this->assertHeaderContains('X-Robots-Tag', 'noindex');
}
public function testTokenOfOtherPollCannotAccessSlides(): void
{
[$pollA] = $this->createPoll('A');
[, $tokenB] = $this->createPoll('B');
$slide = $this->createSlide($pollA);
$this->get("/admin/$tokenB/slides/{$slide->id}/edit");
$this->assertResponseCode(404);
}
public function testAddChoiceSlide(): void
{
[$poll, $token] = $this->createPoll();
$this->post("/admin/$token/slides/add?type=choice", [
'type' => 'choice',
'question' => 'Pizza oder Pasta?',
'options_text' => "Pizza\n\nPasta\nPizza\n",
'settings' => ['multiple' => '1', 'evil' => 'x'],
]);
$this->assertRedirect(['_name' => 'admin', 'token' => $token]);
$slide = $this->slidesTable()->find()->contain(['SlideOptions'])->firstOrFail();
$this->assertSame($poll->id, $slide->poll_id);
$this->assertSame(['Pizza', 'Pasta'], array_map(fn($o) => $o->label, $slide->slide_options));
$this->assertSame(['multiple' => true], $slide->settings);
$this->assertSame(1, $slide->position);
}
public function testEditKeepsVotesOfUnchangedOptions(): void
{
[$poll, $token] = $this->createPoll();
$slide = $this->createSlide($poll, Slide::TYPE_CHOICE, [], ['A', 'B']);
$optionA = $slide->slide_options[0];
$this->post("/admin/$token/slides/{$slide->id}/edit", [
'question' => 'Neu',
'options_text' => "C\nA",
]);
$this->assertRedirect();
$slide = $this->slidesTable()->get($slide->id, contain: ['SlideOptions']);
$this->assertSame('Neu', $slide->question);
$this->assertSame(['C', 'A'], array_map(fn($o) => $o->label, $slide->slide_options));
$this->assertSame($optionA->id, $slide->slide_options[1]->id);
}
public function testMoveAndDeleteSlides(): void
{
[$poll, $token] = $this->createPoll();
$first = $this->createSlide($poll, Slide::TYPE_OPEN);
$second = $this->createSlide($poll, Slide::TYPE_SCALE);
$this->post("/admin/$token/slides/{$second->id}/move/up");
$this->assertSame(1, $this->slidesTable()->get($second->id)->position);
$this->assertSame(2, $this->slidesTable()->get($first->id)->position);
$this->post("/admin/$token/slides/{$second->id}/delete");
$this->assertFalse($this->slidesTable()->exists(['id' => $second->id]));
$this->assertSame(1, $this->slidesTable()->get($first->id)->position);
}
public function testPresentStartsWithFirstSlideAndControlNavigates(): void
{
[$poll, $token] = $this->createPoll();
$first = $this->createSlide($poll, Slide::TYPE_CHOICE);
$second = $this->createSlide($poll, Slide::TYPE_WORDCLOUD);
$this->get("/admin/$token/present");
$this->assertResponseOk();
$this->assertSame($first->id, $this->pollsTable()->get($poll->id)->current_slide_id);
$this->configRequest(['headers' => ['Accept' => 'application/json']]);
$this->post("/admin/$token/control", ['action' => 'next']);
$this->assertResponseOk();
$state = json_decode((string)$this->_response->getBody(), true);
$this->assertSame($second->id, $state['slide']['id']);
$this->assertSame(1, $state['index']);
$this->assertArrayNotHasKey('email', $state['poll']);
$this->configRequest(['headers' => ['Accept' => 'application/json']]);
$this->post("/admin/$token/control", ['action' => 'toggle']);
$this->assertFalse($this->slidesTable()->get($second->id)->is_voting_open);
$this->configRequest(['headers' => ['Accept' => 'application/json']]);
$this->post("/admin/$token/control", ['action' => 'next']);
$this->assertSame($second->id, $this->pollsTable()->get($poll->id)->current_slide_id, 'stays on last slide');
}
public function testControlRejectsSlideOfOtherPoll(): void
{
[, $token] = $this->createPoll('A');
[$other] = $this->createPoll('B');
$foreign = $this->createSlide($other);
$this->post("/admin/$token/control", ['action' => 'goto', 'slide_id' => $foreign->id]);
$this->assertResponseCode(400);
}
public function testRotateTokenInvalidatesOldLink(): void
{
[$poll, $token] = $this->createPoll();
$this->post("/admin/$token/rotate-token");
$this->assertRedirect();
$this->assertMailSentTo('owner@example.org');
$fresh = $this->pollsTable()->get($poll->id);
$this->assertNotSame(PollsTable::hashToken($token), $fresh->admin_token_hash);
$this->get("/admin/$token");
$this->assertResponseCode(404);
}
public function testDeleteRequiresJoinCode(): void
{
[$poll, $token] = $this->createPoll();
$this->post("/admin/$token/delete", ['confirm_code' => 'WRONG']);
$this->assertTrue($this->pollsTable()->exists(['id' => $poll->id]));
$this->post("/admin/$token/delete", ['confirm_code' => strtolower($poll->join_code)]);
$this->assertRedirect(['_name' => 'home']);
$this->assertFalse($this->pollsTable()->exists(['id' => $poll->id]));
}
public function testQrAndExport(): void
{
[, $token] = $this->createPoll();
$this->get("/admin/$token/qr.svg");
$this->assertResponseOk();
$this->assertContentType('image/svg+xml');
$this->get("/admin/$token/export.csv");
$this->assertResponseOk();
$this->assertHeaderContains('Content-Disposition', 'attachment');
}
}
Whitespace-only changes.
@@ -0,0 +1,149 @@
<?php
declare(strict_types=1);
namespace App\Test\TestCase\Controller;
use App\Test\TestCase\PlenarioTestTrait;
use Cake\Cache\Cache;
use Cake\Core\Configure;
use Cake\TestSuite\EmailTrait;
use Cake\TestSuite\IntegrationTestTrait;
use Cake\TestSuite\TestCase;
/**
* Poll creation, captcha handling, join and recovery.
*/
class HomeControllerTest extends TestCase
{
use EmailTrait;
use IntegrationTestTrait;
use PlenarioTestTrait;
/**
* @var list<string>
*/
protected array $fixtures = ['app.Polls', 'app.Slides', 'app.SlideOptions', 'app.Responses'];
protected function setUp(): void
{
parent::setUp();
$this->enableCsrfToken();
Configure::write('Plenario.captcha.type', 'math');
Configure::write('Plenario.showAdminLinkAfterCreate', false);
Cache::clear('throttle');
}
public function testIndexRendersBothForms(): void
{
$this->get('/');
$this->assertResponseOk();
$this->assertResponseContains('Neue Umfrage erstellen');
$this->assertResponseContains('Sicherheitsfrage: Was ist');
$this->assertResponseContains('Teilnahme-Code');
}
public function testCreateWithValidMathCaptchaSendsAdminMail(): void
{
$this->session(['Captcha.math.create' => 7]);
$this->post('/create', ['title' => 'Retro', 'email' => 'Owner@Example.org', 'captcha_answer' => '7']);
$this->assertRedirect(['_name' => 'created']);
$poll = $this->pollsTable()->find()->firstOrFail();
$this->assertSame('owner@example.org', $poll->email);
$this->assertMatchesRegularExpression('/^[A-Z2-9]{6}$/', $poll->join_code);
$this->assertMailSentTo('owner@example.org');
$this->assertMailContains('/admin/');
$this->session(['Plenario.created' => $_SESSION['Plenario']['created'] ?? null]);
$this->get('/created');
$this->assertResponseContains('Fast geschafft');
$this->assertResponseNotContains('/admin/', 'Admin link must not be shown when disabled');
}
public function testCreateRejectsWrongCaptcha(): void
{
$this->session(['Captcha.math.create' => 7]);
$this->post('/create', ['title' => 'Retro', 'email' => 'owner@example.org', 'captcha_answer' => '8']);
$this->assertResponseOk();
$this->assertResponseContains('Sicherheitsabfrage war nicht korrekt');
$this->assertSame(0, $this->pollsTable()->find()->count());
$this->assertNoMailSent();
}
public function testCreateRejectsMissingCaptchaSession(): void
{
$this->post('/create', ['title' => 'Retro', 'email' => 'owner@example.org', 'captcha_answer' => '0']);
$this->assertSame(0, $this->pollsTable()->find()->count());
}
public function testCreateWithoutCaptchaAndInvalidEmail(): void
{
Configure::write('Plenario.captcha.type', 'none');
$this->post('/create', ['title' => 'Retro', 'email' => 'kein-mail']);
$this->assertResponseOk();
$this->assertResponseContains('gültige E-Mail-Adresse');
$this->assertSame(0, $this->pollsTable()->find()->count());
}
public function testCreateShowsAdminLinkInDevMode(): void
{
Configure::write('Plenario.captcha.type', 'none');
Configure::write('Plenario.showAdminLinkAfterCreate', true);
$this->post('/create', ['title' => 'Retro', 'email' => 'owner@example.org']);
$this->session(['Plenario.created' => $_SESSION['Plenario']['created'] ?? null]);
$this->get('/created');
$this->assertResponseContains('/admin/');
}
public function testCreateIsThrottled(): void
{
Configure::write('Plenario.captcha.type', 'none');
Configure::write('Plenario.throttle.createPerHour', 2);
for ($i = 0; $i < 3; $i++) {
$this->post('/create', ['title' => 'Retro ' . $i, 'email' => 'owner@example.org']);
}
$this->assertResponseContains('Zu viele Umfragen');
$this->assertSame(2, $this->pollsTable()->find()->count());
}
public function testJoinNormalisesCode(): void
{
[$poll] = $this->createPoll();
$code = strtolower(substr($poll->join_code, 0, 3) . ' - ' . substr($poll->join_code, 3));
$this->get('/join?code=' . urlencode($code));
$this->assertRedirect(['_name' => 'participate', 'code' => $poll->join_code]);
}
public function testJoinUnknownCode(): void
{
$this->get('/join?code=ZZZZZZ');
$this->assertResponseOk();
$this->assertResponseContains('keine Umfrage gefunden');
}
public function testRecoverResendsExistingLinks(): void
{
Configure::write('Plenario.captcha.type', 'none');
[, $token] = $this->createPoll('Eins', 'owner@example.org');
$this->createPoll('Fremd', 'other@example.org');
$this->post('/recover', ['email' => 'OWNER@example.org']);
$this->assertRedirect(['_name' => 'recover']);
$this->assertMailCount(1);
$this->assertMailSentTo('owner@example.org');
$this->assertMailContains('/admin/' . $token);
$this->assertMailContainsText('Eins');
}
public function testRecoverUnknownAddressSendsNothingButSameMessage(): void
{
Configure::write('Plenario.captcha.type', 'none');
$this->post('/recover', ['email' => 'nobody@example.org']);
$this->assertRedirect(['_name' => 'recover']);
$this->assertFlashMessage('Falls zu nobody@example.org Umfragen existieren, haben wir dir die Admin-Links per E-Mail geschickt.');
$this->assertNoMailSent();
}
}
@@ -0,0 +1,157 @@
<?php
declare(strict_types=1);
namespace App\Test\TestCase\Controller;
use App\Model\Entity\Slide;
use App\Test\TestCase\PlenarioTestTrait;
use Cake\ORM\TableRegistry;
use Cake\TestSuite\IntegrationTestTrait;
use Cake\TestSuite\TestCase;
/**
* Participant view, state endpoint and voting.
*/
class ParticipateControllerTest extends TestCase
{
use IntegrationTestTrait;
use PlenarioTestTrait;
/**
* @var list<string>
*/
protected array $fixtures = ['app.Polls', 'app.Slides', 'app.SlideOptions', 'app.Responses'];
protected const PID = '0123456789abcdef0123456789abcdef';
protected function setUp(): void
{
parent::setUp();
$this->enableCsrfToken();
}
public function testUnknownCodeIs404(): void
{
$this->get('/p/ZZZZZZ');
$this->assertResponseCode(404);
}
public function testWaitingScreenAndCookie(): void
{
[$poll] = $this->createPoll();
$this->get('/p/' . $poll->join_code);
$this->assertResponseOk();
$this->assertResponseContains('Gleich geht');
$this->assertCookieIsSet('plenario_pid');
}
public function testVoteOnceOnly(): void
{
[$poll] = $this->createPoll();
$slide = $this->createSlide($poll, Slide::TYPE_CHOICE);
$this->goLive($poll, $slide);
$optionId = $slide->slide_options[0]->id;
$this->cookie('plenario_pid', self::PID);
$this->post("/p/{$poll->join_code}/vote", ['slide_id' => $slide->id, 'option_id' => $optionId]);
$this->assertRedirect(['_name' => 'participate', 'code' => $poll->join_code]);
$this->assertFlashMessage('Danke für deine Antwort!');
$this->cookie('plenario_pid', self::PID);
$this->post("/p/{$poll->join_code}/vote", ['slide_id' => $slide->id, 'option_id' => $optionId]);
$this->assertFlashMessage('Du hast bereits abgestimmt.');
$this->assertSame(1, TableRegistry::getTableLocator()->get('Responses')->find()->count());
}
public function testVoteForInactiveSlideIsRejected(): void
{
[$poll] = $this->createPoll();
$live = $this->createSlide($poll, Slide::TYPE_OPEN);
$other = $this->createSlide($poll, Slide::TYPE_OPEN);
$this->goLive($poll, $live);
$this->post("/p/{$poll->join_code}/vote", ['slide_id' => $other->id, 'text' => 'Hallo']);
$this->assertFlashMessage('Diese Frage ist nicht mehr aktiv.');
$this->assertSame(0, TableRegistry::getTableLocator()->get('Responses')->find()->count());
}
public function testStateHidesResultsUntilAnswered(): void
{
[$poll] = $this->createPoll();
$slide = $this->createSlide($poll, Slide::TYPE_SCALE);
$this->goLive($poll, $slide);
$this->cookie('plenario_pid', self::PID);
$this->get("/p/{$poll->join_code}/state");
$state = json_decode((string)$this->_response->getBody(), true);
$this->assertSame($slide->id, $state['slideId']);
$this->assertFalse($state['hasResponded']);
$this->assertNull($state['results']);
$this->cookie('plenario_pid', self::PID);
$this->post("/p/{$poll->join_code}/vote", ['slide_id' => $slide->id, 'value' => 4]);
$this->cookie('plenario_pid', self::PID);
$this->get("/p/{$poll->join_code}/state");
$state = json_decode((string)$this->_response->getBody(), true);
$this->assertTrue($state['hasResponded']);
$this->assertEqualsWithDelta(4.0, $state['results']['average'], 0.001);
}
public function testWordcloudAjaxVoteReturnsStateWithUpvoteCloud(): void
{
[$poll] = $this->createPoll();
$poll->show_results_to_participants = false;
$this->pollsTable()->saveOrFail($poll);
$slide = $this->createSlide($poll, Slide::TYPE_WORDCLOUD, ['settings' => ['max_words' => 0, 'allow_upvotes' => true]]);
$this->goLive($poll, $slide);
$this->cookie('plenario_pid', self::PID);
$this->configRequest(['headers' => ['X-Requested-With' => 'XMLHttpRequest', 'Accept' => 'application/json']]);
$this->post("/p/{$poll->join_code}/vote", ['slide_id' => $slide->id, 'word' => 'Kaffee']);
$this->assertResponseOk();
$body = json_decode((string)$this->_response->getBody(), true);
$this->assertTrue($body['ok']);
$this->assertSame(['kaffee'], $body['state']['words']['mine']);
$this->assertNull($body['state']['words']['remaining']);
// Cloud is visible despite show_results_to_participants=false, because upvotes are on.
$this->assertSame('Kaffee', $body['state']['results']['words'][0]['text']);
$this->cookie('plenario_pid', self::PID);
$this->configRequest(['headers' => ['X-Requested-With' => 'XMLHttpRequest', 'Accept' => 'application/json']]);
$this->post("/p/{$poll->join_code}/vote", ['slide_id' => $slide->id, 'word' => 'kaffee']);
$body = json_decode((string)$this->_response->getBody(), true);
$this->assertFalse($body['ok']);
$this->assertSame('Diesen Begriff hast du schon genannt.', $body['message']);
}
public function testWordcloudWithoutUpvotesHidesCloudBeforeAnswer(): void
{
[$poll] = $this->createPoll();
$slide = $this->createSlide($poll, Slide::TYPE_WORDCLOUD, ['settings' => ['allow_upvotes' => false]]);
$this->goLive($poll, $slide);
$this->cookie('plenario_pid', self::PID);
$this->get('/p/' . $poll->join_code);
$this->assertResponseOk();
$this->assertResponseContains('data-word-input');
$this->assertResponseNotContains('data-upvote-hint');
$this->cookie('plenario_pid', self::PID);
$this->get("/p/{$poll->join_code}/state");
$state = json_decode((string)$this->_response->getBody(), true);
$this->assertNull($state['results']);
$this->assertFalse($state['words']['allowUpvotes']);
}
public function testClosedPoll(): void
{
[$poll] = $this->createPoll();
$poll->is_active = false;
$this->pollsTable()->saveOrFail($poll);
$this->get('/p/' . $poll->join_code);
$this->assertResponseContains('Diese Umfrage ist geschlossen');
}
}
Whitespace-only changes.
+83
View File
@@ -0,0 +1,83 @@
<?php
declare(strict_types=1);
namespace App\Test\TestCase;
use App\Model\Entity\Poll;
use App\Model\Entity\Slide;
use App\Model\Table\PollsTable;
use App\Model\Table\SlidesTable;
use Cake\ORM\TableRegistry;
/**
* Helpers to create test data. Use together with the fixtures
* app.Polls, app.Slides, app.SlideOptions, app.Responses.
*/
trait PlenarioTestTrait
{
/**
* @return array{0: \App\Model\Entity\Poll, 1: string} Poll and plain admin token
*/
protected function createPoll(string $title = 'Testumfrage', string $email = 'owner@example.org'): array
{
/** @var \App\Model\Table\PollsTable $polls */
$polls = TableRegistry::getTableLocator()->get('Polls');
[$poll, $token] = $polls->createPoll(['title' => $title, 'email' => $email]);
$this->assertNotNull($token, 'Poll could not be created: ' . json_encode($poll->getErrors()));
return [$poll, (string)$token];
}
/**
* @param \App\Model\Entity\Poll $poll Poll
* @param string $type Slide type
* @param array<string, mixed> $data Extra slide data
* @param list<string> $options Option labels (choice)
* @return \App\Model\Entity\Slide Slide incl. slide_options
*/
protected function createSlide(Poll $poll, string $type = Slide::TYPE_CHOICE, array $data = [], array $options = ['Ja', 'Nein']): Slide
{
/** @var \App\Model\Table\SlidesTable $slides */
$slides = TableRegistry::getTableLocator()->get('Slides');
$slide = $slides->newEntity($data + [
'type' => $type,
'question' => 'Frage ' . $type,
'settings' => Slide::DEFAULT_SETTINGS[$type] ?? [],
]);
$slide->poll_id = $poll->id;
$slides->saveOrFail($slide);
if ($type === Slide::TYPE_CHOICE) {
$slides->syncOptions($slide, $options);
}
return $slides->get($slide->id, contain: ['SlideOptions']);
}
/**
* Makes the slide the poll's current slide.
*/
protected function goLive(Poll $poll, Slide $slide): Poll
{
$polls = $this->pollsTable();
$poll->current_slide_id = $slide->id;
$polls->saveOrFail($poll);
return $polls->get($poll->id);
}
protected function pollsTable(): PollsTable
{
/** @var \App\Model\Table\PollsTable $table */
$table = TableRegistry::getTableLocator()->get('Polls');
return $table;
}
protected function slidesTable(): SlidesTable
{
/** @var \App\Model\Table\SlidesTable $table */
$table = TableRegistry::getTableLocator()->get('Slides');
return $table;
}
}
+233
View File
@@ -0,0 +1,233 @@
<?php
declare(strict_types=1);
namespace App\Test\TestCase\Service;
use App\Model\Entity\Slide;
use App\Model\Table\SlidesTable;
use App\Service\PollStateService;
use App\Service\ResultsService;
use App\Service\VoteException;
use App\Service\VoteService;
use App\Test\TestCase\PlenarioTestTrait;
use Cake\TestSuite\TestCase;
/**
* Validation rules of VoteService and aggregation of ResultsService.
*/
class VoteServiceTest extends TestCase
{
use PlenarioTestTrait;
/**
* @var list<string>
*/
protected array $fixtures = ['app.Polls', 'app.Slides', 'app.SlideOptions', 'app.Responses'];
public function testParticipantHashIsScopedPerPoll(): void
{
$this->assertNotSame(VoteService::participantHash('abc', 1), VoteService::participantHash('abc', 2));
$this->assertSame(VoteService::participantHash('abc', 1), VoteService::participantHash('abc', 1));
}
public function testSingleChoiceRejectsMultipleOptions(): void
{
[$poll] = $this->createPoll();
$slide = $this->createSlide($poll, Slide::TYPE_CHOICE, [], ['A', 'B']);
$poll = $this->goLive($poll, $slide);
$ids = array_map(fn($o) => $o->id, $slide->slide_options);
$this->expectException(VoteException::class);
(new VoteService())->submit($poll, $slide, 'p1', ['option_ids' => $ids]);
}
public function testChoiceIgnoresForeignOptionIds(): void
{
[$poll] = $this->createPoll();
$slide = $this->createSlide($poll, Slide::TYPE_CHOICE);
$poll = $this->goLive($poll, $slide);
$this->expectExceptionMessage('Bitte wähle eine Antwort aus.');
(new VoteService())->submit($poll, $slide, 'p1', ['option_id' => 999999]);
}
public function testClosedVotingIsRejected(): void
{
[$poll] = $this->createPoll();
$slide = $this->createSlide($poll, Slide::TYPE_OPEN, ['is_voting_open' => false]);
$poll = $this->goLive($poll, $slide);
$this->expectExceptionMessage('geschlossen');
(new VoteService())->submit($poll, $slide, 'p1', ['text' => 'Hallo']);
}
public function testScaleRange(): void
{
[$poll] = $this->createPoll();
$slide = $this->createSlide($poll, Slide::TYPE_SCALE, ['settings' => ['scale_min' => 1, 'scale_max' => 3]]);
$poll = $this->goLive($poll, $slide);
$this->expectExceptionMessage('zwischen 1 und 3');
(new VoteService())->submit($poll, $slide, 'p1', ['value' => '4']);
}
public function testMultipleChoiceResults(): void
{
[$poll] = $this->createPoll();
$slide = $this->createSlide($poll, Slide::TYPE_CHOICE, ['settings' => ['multiple' => true]], ['A', 'B', 'C']);
$poll = $this->goLive($poll, $slide);
[$a, $b] = array_map(fn($o) => $o->id, $slide->slide_options);
$service = new VoteService();
$service->submit($poll, $slide, 'p1', ['option_ids' => [$a, $b]]);
$service->submit($poll, $slide, 'p2', ['option_ids' => [$a]]);
$results = (new ResultsService())->forSlide($slide);
$this->assertSame(2, $results['participants']);
$this->assertSame(3, $results['votes']);
$this->assertSame([2, 1, 0], array_column($results['options'], 'count'));
$this->assertEqualsWithDelta(66.7, $results['options'][0]['percent'], 0.01);
}
public function testWordcloudGroupsCaseInsensitivelyAndLimitsWords(): void
{
[$poll] = $this->createPoll();
$slide = $this->createSlide($poll, Slide::TYPE_WORDCLOUD, ['settings' => ['max_words' => 2]]);
$poll = $this->goLive($poll, $slide);
$service = new VoteService();
$service->submit($poll, $slide, 'p1', ['words' => ['Kaffee', ' tee ', 'Wasser']]);
$service->submit($poll, $slide, 'p2', ['words' => ['kaffee', '', 'KAFFEE']]);
$results = (new ResultsService())->forSlide($slide);
$this->assertSame(['Kaffee', 'tee'], array_column($results['words'], 'text'));
$this->assertSame(['kaffee', 'tee'], array_column($results['words'], 'key'));
$this->assertSame([2, 1], array_column($results['words'], 'count'));
$this->assertEquals(1, $results['words'][0]['weight']);
}
public function testWordcloudAcceptsWordsOneByOneAndCountsRepeatsAsUpvote(): void
{
[$poll] = $this->createPoll();
$slide = $this->createSlide($poll, Slide::TYPE_WORDCLOUD, ['settings' => ['max_words' => 0]]);
$poll = $this->goLive($poll, $slide);
$service = new VoteService();
$service->submit($poll, $slide, 'p1', ['word' => 'Kaffee']);
$service->submit($poll, $slide, 'p1', ['word' => 'Tee']);
$service->submit($poll, $slide, 'p1', ['word' => 'Wasser']);
$service->submit($poll, $slide, 'p1', ['word' => 'Saft']);
// Entering an existing word of someone else = upvote.
$service->submit($poll, $slide, 'p2', ['word' => 'kaffee ']);
$results = (new ResultsService())->forSlide($slide);
$this->assertSame(2, $results['participants']);
$this->assertSame('Kaffee', $results['words'][0]['text']);
$this->assertSame(2, $results['words'][0]['count']);
$this->assertCount(4, $results['words']);
}
public function testWordcloudRejectsOwnDuplicate(): void
{
[$poll] = $this->createPoll();
$slide = $this->createSlide($poll, Slide::TYPE_WORDCLOUD);
$poll = $this->goLive($poll, $slide);
$service = new VoteService();
$service->submit($poll, $slide, 'p1', ['word' => 'Kaffee']);
$this->expectExceptionMessage('Diesen Begriff hast du schon genannt.');
$service->submit($poll, $slide, 'p1', ['word' => 'KAFFEE']);
}
public function testWordcloudLimitCountsAcrossSubmits(): void
{
[$poll] = $this->createPoll();
$slide = $this->createSlide($poll, Slide::TYPE_WORDCLOUD, ['settings' => ['max_words' => 2]]);
$poll = $this->goLive($poll, $slide);
$service = new VoteService();
$service->submit($poll, $slide, 'p1', ['word' => 'Kaffee']);
$service->submit($poll, $slide, 'p1', ['word' => 'Tee']);
$state = (new PollStateService())->wordState($slide, 'p1');
$this->assertSame(['kaffee', 'tee'], $state['mine']);
$this->assertSame(0, $state['remaining']);
$this->assertTrue($state['limitReached']);
$this->expectExceptionMessage('Du hast bereits alle 2 Begriffe abgegeben.');
$service->submit($poll, $slide, 'p1', ['word' => 'Wasser']);
}
public function testWordcloudSettingsSanitizing(): void
{
$settings = SlidesTable::sanitizeSettings(Slide::TYPE_WORDCLOUD, ['max_words' => '-3', 'allow_upvotes' => '0']);
$this->assertSame(['max_words' => 0, 'allow_upvotes' => false, 'allow_downvotes' => true], $settings);
$settings = SlidesTable::sanitizeSettings(Slide::TYPE_WORDCLOUD, ['max_words' => '999', 'allow_downvotes' => '0']);
$this->assertSame(['max_words' => 50, 'allow_upvotes' => true, 'allow_downvotes' => false], $settings);
}
public function testWordcloudDownvotes(): void
{
[$poll] = $this->createPoll();
$slide = $this->createSlide($poll, Slide::TYPE_WORDCLOUD, ['settings' => ['max_words' => 1]]);
$poll = $this->goLive($poll, $slide);
$service = new VoteService();
$service->submit($poll, $slide, 'p1', ['word' => 'Kaffee']);
$service->submit($poll, $slide, 'p2', ['word' => 'kaffee']);
$service->submit($poll, $slide, 'p3', ['word' => 'Kaffee', 'vote' => 'down']);
// Downvotes do not count towards max_words.
$service->submit($poll, $slide, 'p3', ['word' => 'Tee']);
$results = (new ResultsService())->forSlide($slide);
$this->assertSame(3, $results['participants']);
$this->assertSame(['Kaffee', 'Tee'], array_column($results['words'], 'text'));
$this->assertSame([2, 1], array_column($results['words'], 'count'));
$this->assertSame([1, 0], array_column($results['words'], 'down'));
$state = (new PollStateService())->wordState($slide, 'p3');
$this->assertSame(['tee'], $state['mine']);
$this->assertSame(['kaffee'], $state['down']);
$this->assertTrue($state['allowDownvotes']);
}
public function testWordcloudDownvoteRules(): void
{
[$poll] = $this->createPoll();
$slide = $this->createSlide($poll, Slide::TYPE_WORDCLOUD);
$poll = $this->goLive($poll, $slide);
$service = new VoteService();
$service->submit($poll, $slide, 'p1', ['word' => 'Kaffee']);
$cases = [
['p1', 'Kaffee', 'Du hast diesen Begriff selbst genannt.'],
['p2', 'Wasser', 'Diesen Begriff gibt es nicht in der Wortwolke.'],
];
foreach ($cases as [$participant, $word, $expected]) {
try {
$service->submit($poll, $slide, $participant, ['word' => $word, 'vote' => 'down']);
$this->fail('VoteException expected for ' . $word);
} catch (VoteException $e) {
$this->assertSame($expected, $e->getMessage());
}
}
$service->submit($poll, $slide, 'p2', ['word' => 'Kaffee', 'vote' => 'down']);
$this->expectExceptionMessage('Diesen Begriff hast du bereits abgelehnt.');
// Upvoting after a downvote is not possible.
$service->submit($poll, $slide, 'p2', ['word' => 'Kaffee']);
}
public function testWordcloudDownvotesCanBeDisabled(): void
{
[$poll] = $this->createPoll();
$slide = $this->createSlide($poll, Slide::TYPE_WORDCLOUD, ['settings' => ['allow_downvotes' => false]]);
$poll = $this->goLive($poll, $slide);
$service = new VoteService();
$service->submit($poll, $slide, 'p1', ['word' => 'Kaffee']);
$this->expectExceptionMessage('Downvotes sind bei dieser Frage nicht möglich.');
$service->submit($poll, $slide, 'p2', ['word' => 'Kaffee', 'vote' => 'down']);
}
}
View File
Whitespace-only changes.