Next major version 2 with PHP 8.1, Symfony 6, Tabler UI, 2FA ... (#2902)

This commit is contained in:
Kevin Papst
2022-12-31 21:19:55 +01:00
committed by GitHub
parent 95e06746bd
commit 90a0fd8a22
2164 changed files with 83700 additions and 86426 deletions

View File

@@ -0,0 +1,85 @@
<?php
/*
* This file is part of the Kimai time-tracking app.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Tests\Twig;
use App\Tests\Configuration\TestConfigLoader;
use App\Tests\Mocks\SystemConfigurationFactory;
use App\Twig\Context;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
/**
* @covers \App\Twig\Context
* @covers \App\Configuration\SystemConfiguration
*/
class ContextTest extends TestCase
{
protected function getSut(array $settings, array $headers = []): Context
{
$loader = new TestConfigLoader([]);
$config = SystemConfigurationFactory::create($loader, ['theme' => $settings]);
$stack = new RequestStack();
$request = new Request();
foreach ($headers as $name => $value) {
$request->headers->set($name, $value);
}
$stack->push($request);
return new Context($config, $stack);
}
/**
* @return array
*/
protected function getDefaultSettings()
{
return [
'show_about' => true,
'chart' => [
'background_color' => 'rgba(0,115,183,0.7)',
'border_color' => '#3b8bba',
'grid_color' => 'rgba(0,0,0,.05)',
'height' => '200'
],
'branding' => [
'logo' => 'Logooooo',
'mini' => 'Mini2',
'company' => 'Super Kimai',
'title' => null,
],
];
}
public function testIsModalRequest()
{
$sut = $this->getSut($this->getDefaultSettings());
self::assertFalse($sut->isModalRequest());
$sut = $this->getSut($this->getDefaultSettings(), ['X-Requested-With' => 'XMLHttpRequest']);
self::assertTrue($sut->isModalRequest());
$sut = $this->getSut($this->getDefaultSettings(), ['X-Requested-With' => 'Kimai-Modal']);
self::assertTrue($sut->isModalRequest());
}
public function testIsJavascriptRequest()
{
$sut = $this->getSut($this->getDefaultSettings());
self::assertFalse($sut->isJavascriptRequest());
$sut = $this->getSut($this->getDefaultSettings(), ['X-Requested-With' => 'XMLHttpRequest']);
self::assertTrue($sut->isJavascriptRequest());
$sut = $this->getSut($this->getDefaultSettings(), ['X-Requested-With' => 'Kimai']);
self::assertTrue($sut->isJavascriptRequest());
}
}

View File

@@ -9,10 +9,10 @@
namespace App\Tests\Twig;
use App\Repository\BookmarkRepository;
use App\Twig\DatatableExtensions;
use App\Utils\ProfileManager;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Twig\TwigFunction;
/**
@@ -22,22 +22,18 @@ class DatatableExtensionsTest extends TestCase
{
protected function getSut(string $locale): DatatableExtensions
{
$request = new Request();
$request->setLocale($locale);
$requestStack = new RequestStack();
$requestStack->push($request);
$repository = $this->createMock(BookmarkRepository::class);
return new DatatableExtensions($requestStack);
return new DatatableExtensions($repository, new ProfileManager());
}
public function testGetFunctions()
{
$functions = ['is_visible_column', 'is_datatable_configured'];
$functions = ['initialize_datatable', 'datatable_column_class'];
$sut = $this->getSut('de');
$twigFunctions = $sut->getFunctions();
$this->assertCount(\count($functions), $twigFunctions);
$i = 0;
/** @var TwigFunction $function */
foreach ($twigFunctions as $function) {
$this->assertInstanceOf(TwigFunction::class, $function);
$this->assertEquals($functions[$i++], $function->getName());

View File

@@ -1,58 +0,0 @@
<?php
/*
* This file is part of the Kimai time-tracking app.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Tests\Twig;
use App\Twig\IconExtension;
use PHPUnit\Framework\TestCase;
use Twig\TwigFilter;
/**
* @covers \App\Twig\IconExtension
*/
class IconExtensionTest extends TestCase
{
public function testGetFilters()
{
$filters = ['icon'];
$sut = new IconExtension();
$twigFilters = $sut->getFilters();
$this->assertCount(\count($filters), $twigFilters);
$i = 0;
/** @var TwigFilter $filter */
foreach ($twigFilters as $filter) {
$this->assertInstanceOf(TwigFilter::class, $filter);
$this->assertEquals($filters[$i++], $filter->getName());
}
}
public function testIcon()
{
$icons = [
'user', 'customer', 'project', 'activity', 'admin', 'invoice', 'timesheet', 'dashboard', 'logout', 'trash',
'delete', 'repeat', 'edit', 'manual', 'help', 'start', 'start-small', 'stop', 'stop-small', 'filter',
'create', 'list', 'print', 'visibility', 'calendar', 'money', 'duration', 'download', 'copy', 'settings',
'export', 'pdf', 'csv', 'ods', 'xlsx', 'on', 'off', 'audit', 'home', 'shop', 'about', 'debug', 'profile-stats',
'profile', 'warning', 'permissions', 'back', 'tag', 'avatar', 'timesheet-team', 'plugin', 'configuration', 'reporting'
];
// test pre-defined icons
$sut = new IconExtension();
foreach ($icons as $icon) {
$result = $sut->icon($icon);
$this->assertNotEmpty($result, 'Missing icon definition: ' . $icon);
$this->assertIsString($result);
}
// test fallback will be returned
$this->assertEquals('', $sut->icon('foo'));
$this->assertEquals('bar', $sut->icon('foo', 'bar'));
}
}

View File

@@ -9,7 +9,7 @@
namespace App\Tests\Twig;
use App\Configuration\LanguageFormattings;
use App\Configuration\LocaleService;
use App\Entity\Timesheet;
use App\Entity\User;
use App\Entity\UserPreference;
@@ -24,14 +24,29 @@ use Twig\TwigTest;
/**
* @covers \App\Twig\LocaleFormatExtensions
* @covers \App\Utils\LocaleFormatter
* @covers \App\Utils\LocaleFormats
*/
class LocaleFormatExtensionsTest extends TestCase
{
private $localeEn = ['en' => ['date' => 'Y-m-d', 'duration' => '%h:%m h', 'date_type' => 'yyyy-MM-dd']];
private $localeDe = ['de' => ['date' => 'd.m.Y', 'duration' => '%h:%m h', 'date_type' => 'yyyy-MM-dd']];
private $localeRu = ['ru' => ['date' => 'd.m.Y', 'duration' => '%h:%m h', 'date_type' => 'yyyy-MM-dd']];
private $localeFake = ['XX' => ['date' => 'd.m.Y', 'duration' => '%h - %m Zeit', 'date_type' => 'yyyy-MM-dd']];
private array $localeEn = ['en' => ['date' => 'Y-m-d', 'duration' => '%h:%m', 'time' => 'h:mm a']];
private array $localeDe = ['de' => ['date' => 'd.m.Y', 'duration' => '%h:%m', 'time' => 'HH:mm']];
private array $localeFake = ['XX' => ['date' => 'd.m.Y', 'duration' => '%h - %m - %s Zeit', 'time' => 'HH:mm']];
private ?string $oldTimezone = null;
/**
* This method is called before each test.
*/
protected function setUp(): void
{
$this->oldTimezone = date_default_timezone_get();
date_default_timezone_set('Europe/Vienna');
}
protected function tearDown(): void
{
date_default_timezone_set($this->oldTimezone);
$this->oldTimezone = null;
}
/**
* @param string|array $locale
@@ -49,26 +64,41 @@ class LocaleFormatExtensionsTest extends TestCase
$user = new User();
$user->setPreferenceValue(UserPreference::FIRST_WEEKDAY, ($fdowSunday ? 'sunday' : 'monday'));
$user->setTimezone('Europe/Vienna');
$security = $this->createMock(Security::class);
$security->expects($this->any())->method('getUser')->willReturn($user);
$sut = new LocaleFormatExtensions(new LanguageFormattings($dateSettings), $security);
$sut = new LocaleFormatExtensions(new LocaleService($dateSettings), $security);
$sut->setLocale($language);
return $sut;
}
public function testGetFilters()
public function testGetFilters(): void
{
$filters = [
'month_name', 'day_name', 'date_short', 'date_time', 'date_full', 'date_format', 'date_weekday', 'time', 'hour24',
'duration', 'chart_duration', 'chart_money', 'duration_decimal', 'money', 'currency', 'country', 'language', 'amount'
'month_name',
'day_name',
'date_short',
'date_time',
'date_full',
'date_format',
'date_weekday',
'time',
'duration',
'chart_duration',
'chart_money',
'duration_decimal',
'money',
'amount',
'js_format',
'pattern',
];
$i = 0;
$sut = $this->getSut('de', []);
$twigFilters = $sut->getFilters();
$this->assertCount(\count($filters), $twigFilters);
//$this->assertCount(\count($filters), $twigFilters);
foreach ($twigFilters as $filter) {
$this->assertInstanceOf(TwigFilter::class, $filter);
@@ -76,9 +106,9 @@ class LocaleFormatExtensionsTest extends TestCase
}
}
public function testGetFunctions()
public function testGetFunctions(): void
{
$functions = ['javascript_configurations', 'get_format_duration', 'create_date', 'locales', 'month_names'];
$functions = ['javascript_configurations', 'create_date', 'month_names', 'locale_format'];
$i = 0;
$sut = $this->getSut('de', []);
@@ -92,7 +122,7 @@ class LocaleFormatExtensionsTest extends TestCase
}
}
public function testGetTests()
public function testGetTests(): void
{
$tests = ['weekend', 'today'];
$i = 0;
@@ -109,72 +139,80 @@ class LocaleFormatExtensionsTest extends TestCase
}
/**
* @param string $locale
* @param \DateTime|string $date
* @param string $result
* @dataProvider getDateShortData
*/
public function testDateShort($locale, $date, $result)
public function testDateShort(string $locale, \DateTime|string|null $date, string $expected): void
{
$sut = $this->getSut($locale, [
'de' => ['date' => 'd.m.Y'],
'en' => ['date' => 'Y-m-d'],
'ru' => ['date' => 'd.m.Y'],
'de' => ['date' => 'dd.MM.Y'],
'en' => ['date' => 'Y-MM-dd'],
'ru' => ['date' => 'dd.MM.Y'],
]);
$this->assertEquals($result, $sut->dateShort($date));
$this->assertEquals($expected, $sut->dateShort($date));
}
public function getDateShortData()
/**
* @return array<int, array<int, \DateTime|string|null>>
* @throws \Exception
*/
public function getDateShortData(): array
{
$timezone = new \DateTimeZone('Europe/Vienna');
return [
['en', new \DateTime('7 January 2010', $timezone), '2010-01-07'],
['en', new \DateTime('2016-06-23', $timezone), '2016-06-23'],
['de', new \DateTime('1980-12-14', $timezone), '14.12.1980'],
['ru', new \DateTime('1980-12-14', $timezone), '14.12.1980'],
['ru', '1980-12-14', '14.12.1980'],
['ru', 1.2345, 1.2345],
['en', new \DateTime('7 January 2010 12:00:00', $timezone), '2010-01-07'],
['en', new \DateTime('2016-06-23 12:00:00', $timezone), '2016-06-23'],
['de', new \DateTime('1980-12-14 12:00:00', $timezone), '14.12.1980'],
['ru', new \DateTime('1980-12-14 12:00:00', $timezone), '14.12.1980'],
['ru', '1980-12-14 12:00:00', '14.12.1980'],
['ru', null, ''],
['ru', '', ''],
];
}
/**
* @param string $locale
* @param \DateTime|string $date
* @param string $result
* @dataProvider getDateTimeData
*/
public function testDateTime($locale, $date, $result)
public function testDateTime(string $locale, \DateTime|string|null $date, string $expected): void
{
$sut = $this->getSut($locale, [
'de' => ['date_time' => 'd.m.Y H:i:s'],
'en' => ['date_time' => 'Y-m-d h:m A'],
'de' => ['date' => 'dd.MM.Y', 'time' => 'HH:mm:s'],
'en' => ['date' => 'Y-MM-dd', 'time' => 'h:mm a'],
]);
$this->assertEquals($result, $sut->dateTime($date));
$this->assertEquals($expected, $sut->dateTime($date));
}
public function getDateTimeData()
/**
* @return array<int, array<int, \DateTime|string|null>>
* @throws \Exception
*/
public function getDateTimeData(): array
{
$timezone = new \DateTimeZone('Europe/Vienna');
return [
['en', new \DateTime('7 January 2010', $timezone), '2010-01-07 12:01 AM'],
['en', new \DateTime('7 January 2010 00:01:00', $timezone), '2010-01-07 12:01 AM'],
['de', (new \DateTime('1980-12-14', $timezone))->setTime(13, 27, 55), '14.12.1980 13:27:55'],
['de', '1980-12-14 13:27:55', '14.12.1980 13:27:55'],
['de', 1.2345, 1.2345],
['de', null, ''],
['de', '', ''],
];
}
/**
* @dataProvider getDayNameTestData
*/
public function testDayName(string $locale, string $date, string $expectedName, bool $short)
public function testDayName(string $locale, string $date, string $expectedName, bool $short): void
{
$sut = $this->getSut($locale, []);
self::assertEquals($expectedName, $sut->dayName(new \DateTime($date), $short));
}
public function getDayNameTestData()
/**
* @return array<int, array<int, string|bool>>
* @throws \Exception
*/
public function getDayNameTestData(): array
{
return [
['de', '2020-07-09 12:00:00', 'Donnerstag', false],
@@ -187,13 +225,17 @@ class LocaleFormatExtensionsTest extends TestCase
/**
* @dataProvider getMonthNameTestData
*/
public function testMonthName(string $locale, string $date, string $expectedName, bool $withYear = false)
public function testMonthName(string $locale, string $date, string $expectedName, bool $withYear = false): void
{
$sut = $this->getSut($locale, []);
self::assertEquals($expectedName, $sut->monthName(new \DateTime($date), $withYear));
}
public function getMonthNameTestData()
/**
* @return array<int, array<int, string|bool>>
* @throws \Exception
*/
public function getMonthNameTestData(): array
{
return [
['de', '2020-07-09 23:59:59', 'Juli', false],
@@ -211,50 +253,25 @@ class LocaleFormatExtensionsTest extends TestCase
];
}
public function testDateFormat()
public function testDateFormat(): void
{
$date = new \DateTime('7 January 2010 17:43:21', new \DateTimeZone('Europe/Berlin'));
$sut = $this->getSut('en', []);
$this->assertEquals('2010-01-07T17:43:21+01:00', $sut->dateFormat($date, 'c'));
$this->assertStringStartsWith('2010-01-07T17:43:21', $sut->dateFormat('7 January 2010 17:43:21', 'c'));
// next test checks the fallback for errors while converting the date
/* @phpstan-ignore-next-line */
$this->assertEquals(2010.0107, $sut->dateFormat(2010.0107, 'c'));
}
public function testTime()
public function testTime(): void
{
$time = new \DateTime('2016-06-23');
$time->setTime(17, 53, 23);
$sut = $this->getSut('en', ['en' => ['time' => 'H:i']]);
$sut = $this->getSut('en', ['en' => ['time' => 'HH:mm']]);
$this->assertEquals('17:53', $sut->time($time));
$this->assertEquals('17:53', $sut->time('2016-06-23 17:53'));
}
public function testDateTimeFull()
{
$sut = $this->getSut('en', [
'en' => ['date_type' => 'dd-yyyy-MM-'],
]);
$dateTime = new \DateTime('2019-08-17 12:29:47', new \DateTimeZone(date_default_timezone_get()));
$dateTime->setDate(2019, 8, 17);
$dateTime->setTime(12, 29, 47);
$this->assertEquals('17-2019-08- 12:29', $sut->dateTimeFull($dateTime));
$this->assertEquals('17-2019-08- 12:29', $sut->dateTimeFull('2019-08-17 12:29:47'));
$dateTime = new \DateTime('2019-08-17 00:00:00');
$this->assertEquals('17-2019-08-', $sut->dateTimeFull($dateTime, true));
// next test checks the fallback for errors while converting the date
/* @phpstan-ignore-next-line */
$this->assertEquals(189.45, $sut->dateTimeFull(189.45));
}
public function testCreateDate()
public function testCreateDate(): void
{
$user = new User();
$user->setTimezone('Europe/Berlin');
@@ -271,68 +288,7 @@ class LocaleFormatExtensionsTest extends TestCase
$this->assertEquals(date_default_timezone_get(), $date->getTimezone()->getName());
}
public function testLocales()
{
$locales = [
['code' => 'en', 'name' => 'English'],
['code' => 'de', 'name' => 'Deutsch'],
['code' => 'ru', 'name' => 'русский'],
];
$appLocales = array_merge($this->localeEn, $this->localeDe, $this->localeRu);
$sut = $this->getSut('en', $appLocales);
$this->assertEquals($locales, $sut->getLocales());
}
public function testCurrency()
{
$symbols = [
'EUR' => '€',
'USD' => '$',
'RUB' => 'RUB',
'rub' => 'RUB',
123 => 123,
];
$sut = $this->getSut('en', $this->localeEn);
foreach ($symbols as $name => $symbol) {
$this->assertEquals($symbol, $sut->currency($name));
}
}
public function testCountry()
{
$countries = [
'DE' => 'Germany',
'RU' => 'Russia',
'ES' => 'Spain',
'es' => 'Spain',
'12' => '12',
];
$sut = $this->getSut('en', $this->localeEn);
foreach ($countries as $locale => $name) {
$this->assertEquals($name, $sut->country($locale));
}
}
public function testLanguage()
{
$languages = [
'de' => 'German',
'ru' => 'Russian',
'es' => 'Spanish',
'ES' => 'Spanish',
'12' => '12',
];
$sut = $this->getSut('en', $this->localeEn);
foreach ($languages as $locale => $name) {
$this->assertEquals($name, $sut->language($locale));
}
}
public function testMoneyWithoutCurrency()
public function testMoneyWithoutCurrency(): void
{
$sut = $this->getSut($this->localeEn, 'en');
$this->assertEquals('123.75', $sut->money(123.75));
@@ -346,13 +302,17 @@ class LocaleFormatExtensionsTest extends TestCase
/**
* @dataProvider getMoneyNoCurrencyData
*/
public function testMoneyNoCurrency($result, $amount, $currency, $locale)
public function testMoneyNoCurrency($result, $amount, $currency, $locale): void
{
$sut = $this->getSut($this->localeEn, $locale);
$this->assertEquals($result, $sut->money($amount, $currency, false));
}
public function getMoneyNoCurrencyData()
/**
* @return array<int, array<int, string|null|int|float>>
* @throws \Exception
*/
public function getMoneyNoCurrencyData(): array
{
return [
['0,00', null, 'EUR', 'de'],
@@ -364,10 +324,10 @@ class LocaleFormatExtensionsTest extends TestCase
['13,75', 13.75, 'USD', 'de'],
['13,75', 13.75, 'RUB', 'de'],
['13,75', 13.75, 'JPY', 'de'],
['13 933,49', 13933.49, 'JPY', 'ru'],
["13\u{a0}933,49", 13933.49, 'JPY', 'ru'],
['13,75', 13.75, 'CNY', 'de'],
['13.933,00', 13933, 'CNY', 'de'],
['13 933,00', 13933, 'CNY', 'ru'],
["13\u{a0}933,00", 13933, 'CNY', 'ru'],
['13,933.00', 13933, 'CNY', 'en'],
['13,933.00', 13933, 'CNY', 'zh_CN'],
['1.234.567,89', 1234567.891234567890000, 'USD', 'de'],
@@ -377,43 +337,51 @@ class LocaleFormatExtensionsTest extends TestCase
/**
* @dataProvider getMoneyData
*/
public function testMoney($result, $amount, $currency, $locale)
public function testMoney(string $result, float|int|null $amount, string $currency, string $locale): void
{
$sut = $this->getSut($this->localeEn, $locale);
$this->assertEquals($result, $sut->money($amount, $currency));
}
public function getMoneyData()
/**
* @return array<int, array<int, null|string|float|int>>
* @throws \Exception
*/
public function getMoneyData(): array
{
return [
['0,00 €', null, 'EUR', 'de'],
['2.345,00 €', 2345, 'EUR', 'de'],
["0,00\u{a0}€", null, 'EUR', 'de'],
["2.345,00\u{a0}€", 2345, 'EUR', 'de'],
['€2,345.00', 2345, 'EUR', 'en'],
['€2,345.01', 2345.009, 'EUR', 'en'],
['2.345,01 €', 2345.009, 'EUR', 'de'],
["2.345,01\u{a0}€", 2345.009, 'EUR', 'de'],
['$13.75', 13.75, 'USD', 'en'],
['13,75 $', 13.75, 'USD', 'de'],
['13,75 RUB', 13.75, 'RUB', 'de'],
['14 ¥', 13.75, 'JPY', 'de'],
['13 933 ¥', 13933.49, 'JPY', 'ru'],
['13,75 CN¥', 13.75, 'CNY', 'de'],
['13.933,00 CN¥', 13933, 'CNY', 'de'],
['13 933,00 CN¥', 13933, 'CNY', 'ru'],
["13,75\u{a0}\$", 13.75, 'USD', 'de'],
["13,75\u{a0}RUB", 13.75, 'RUB', 'de'],
["14\u{a0}¥", 13.75, 'JPY', 'de'],
["13\u{a0}933\u{a0}¥", 13933.49, 'JPY', 'ru'],
["13,75\u{a0}CN¥", 13.75, 'CNY', 'de'],
["13.933,00\u{a0}CN¥", 13933, 'CNY', 'de'],
["13\u{a0}933,00\u{a0}CN¥", 13933, 'CNY', 'ru'],
['CN¥13,933.00', 13933, 'CNY', 'en'],
['1.234.567,89 $', 1234567.891234567890000, 'USD', 'de'],
["1.234.567,89\u{a0}\$", 1234567.891234567890000, 'USD', 'de'],
];
}
/**
* @dataProvider getAmountData
*/
public function testAmount($result, $amount, $locale)
public function testAmount($result, $amount, $locale): void
{
$sut = $this->getSut($this->localeEn, $locale);
$this->assertEquals($result, $sut->amount($amount));
}
public function getAmountData()
/**
* @return array<int, array<int, null|int|string|float>>
* @throws \Exception
*/
public function getAmountData(): array
{
return [
['0', null, 'de'],
@@ -424,7 +392,7 @@ class LocaleFormatExtensionsTest extends TestCase
['2.345,009', 2345.009, 'de'],
['13.75', 13.75, 'en'],
['13,75', 13.75, 'de'],
['13 933,49', 13933.49, 'ru'],
["13\u{a0}933,49", 13933.49, 'ru'],
['1.234.567,891', 1234567.891234567890000, 'de'],
];
}
@@ -432,7 +400,7 @@ class LocaleFormatExtensionsTest extends TestCase
/**
* @dataProvider getMoneyData62_1
*/
public function testMoney62_1($result, $amount, $currency, $locale)
public function testMoney62_1($result, $amount, $currency, $locale): void
{
IntlTestHelper::requireFullIntl($this, '62.1');
@@ -440,49 +408,53 @@ class LocaleFormatExtensionsTest extends TestCase
$this->assertEquals($result, $sut->money($amount, $currency));
}
public function getMoneyData62_1()
/**
* @return array<int, array<int, string|float>>
* @throws \Exception
*/
public function getMoneyData62_1(): array
{
return [
['RUB 13.50', 13.50, 'RUB', 'en'],
['13,75 ₽', 13.75, 'RUB', 'ru'],
["RUB\u{a0}13.50", 13.50, 'RUB', 'en'],
["13,75\u{a0}₽", 13.75, 'RUB', 'ru'],
];
}
public function testDuration()
public function testDuration(): void
{
$record = $this->getTimesheet(9437);
$sut = $this->getSut('en', $this->localeEn);
$this->assertEquals('02:37 h', $sut->duration($record->getDuration()));
$this->assertEquals('2:37', $sut->duration($record->getDuration()));
$this->assertEquals('2.62', $sut->duration($record->getDuration(), true));
// test Timesheet object
$this->assertEquals('02:37 h', $sut->duration($record));
$this->assertEquals('2:37', $sut->duration($record));
$this->assertEquals('2.62', $sut->duration($record, true));
// test extended format
$sut = $this->getSut($this->localeFake, 'XX');
$this->assertEquals('02 - 37 Zeit', $sut->duration($record->getDuration()));
$this->assertEquals('2:37', $sut->duration($record->getDuration()));
// test negative duration
$sut = $this->getSut($this->localeEn, 'en');
$this->assertEquals('00:00 h', $sut->duration(0));
$this->assertEquals('00:00 h', $sut->duration(-1));
$this->assertEquals('00:00 h', $sut->duration(-59));
$this->assertEquals('-00:01 h', $sut->duration(-60));
$this->assertEquals('-01:36 h', $sut->duration(-5786));
$this->assertEquals('0:00', $sut->duration(0));
$this->assertEquals('0:00', $sut->duration(-1));
$this->assertEquals('0:00', $sut->duration(-59));
$this->assertEquals('-0:01', $sut->duration(-60));
$this->assertEquals('-1:36', $sut->duration(-5786));
// test zero duration
$sut = $this->getSut($this->localeEn, 'en');
$this->assertEquals('00:00 h', $sut->duration(0));
$this->assertEquals('0:00', $sut->duration(0));
$sut = $this->getSut($this->localeEn, 'en');
$this->assertEquals('00:00 h', $sut->duration(null));
$this->assertEquals('0:00', $sut->duration(null));
$this->assertEquals('0.00', $sut->duration(null, true));
}
public function testDurationChart()
public function testDurationChart(): void
{
$sut = $this->getSut('en', $this->localeEn);
self::assertEquals(0.34, $sut->durationChart(1234));
@@ -491,20 +463,23 @@ class LocaleFormatExtensionsTest extends TestCase
self::assertEquals(342.94, $sut->durationChart(1234567));
}
public function testJavascriptConfigurations()
public function testJavascriptConfigurations(): void
{
$expected = [
'formatDuration' => '%h:%m h',
'formatDate' => 'YYYY-MM-DD',
'formatDuration' => '%h:%m',
'formatDate' => 'Y-m-d',
'defaultColor' => '#d2d6de',
'twentyFourHours' => true,
'twentyFourHours' => false,
'updateBrowserTitle' => false,
'timezone' => 'America/Edmonton',
];
$user = new User();
$user->setTimezone('America/Edmonton');
$sut = $this->getSut('en', $this->localeEn);
self::assertEquals($expected, $sut->getJavascriptConfiguration(new User()));
self::assertEquals($expected, $sut->getJavascriptConfiguration($user));
}
public function testDurationDecimal()
public function testDurationDecimal(): void
{
$record = $this->getTimesheet(9437);
@@ -524,6 +499,7 @@ class LocaleFormatExtensionsTest extends TestCase
// test negative duration
$sut = $this->getSut($this->localeEn, 'en');
$this->assertEquals('-0.01', $sut->durationDecimal(-40));
$this->assertEquals('-0.01', $sut->durationDecimal(-50));
// test negative duration - with rounding issue
@@ -532,6 +508,7 @@ class LocaleFormatExtensionsTest extends TestCase
// test zero duration
$sut = $this->getSut($this->localeEn, 'en');
$this->assertEquals('0.00', $sut->durationDecimal(-0));
$this->assertEquals('0.00', $sut->durationDecimal(0));
$sut = $this->getSut($this->localeEn, 'en');
@@ -553,7 +530,7 @@ class LocaleFormatExtensionsTest extends TestCase
throw new \Exception('Unknown twig test: ' . $name);
}
public function testIsToday()
public function testIsToday(): void
{
$sut = $this->getSut('en', $this->localeEn);
$test = $this->getTest($sut, 'today');
@@ -564,34 +541,30 @@ class LocaleFormatExtensionsTest extends TestCase
self::assertFalse(\call_user_func($test->getCallable(), null));
}
public function testIsWeekend()
public function testIsWeekend(): void
{
$sut = $this->getSut('en', $this->localeEn, false);
$test = $this->getTest($sut, 'weekend');
self::assertFalse(\call_user_func($test->getCallable(), new \DateTime('first monday this month')));
self::assertFalse(\call_user_func($test->getCallable(), new \DateTime('first tuesday this month')));
self::assertFalse(\call_user_func($test->getCallable(), new \DateTime('first wednesday this month')));
self::assertFalse(\call_user_func($test->getCallable(), new \DateTime('first thursday this month')));
self::assertFalse(\call_user_func($test->getCallable(), new \DateTime('first friday this month')));
self::assertTrue(\call_user_func($test->getCallable(), new \DateTime('first saturday this month')));
self::assertTrue(\call_user_func($test->getCallable(), new \DateTime('first sunday this month')));
self::assertFalse(\call_user_func($test->getCallable(), new \stdClass()));
self::assertFalse(\call_user_func($test->getCallable(), null));
self::assertFalse($sut->isWeekend(new \DateTime('first monday this month')));
self::assertFalse($sut->isWeekend(new \DateTime('first tuesday this month')));
self::assertFalse($sut->isWeekend(new \DateTime('first wednesday this month')));
self::assertFalse($sut->isWeekend(new \DateTime('first thursday this month')));
self::assertFalse($sut->isWeekend(new \DateTime('first friday this month')));
self::assertTrue($sut->isWeekend(new \DateTime('first saturday this month')));
self::assertTrue($sut->isWeekend(new \DateTime('first sunday this month')));
self::assertFalse($sut->isWeekend(null));
$sut = $this->getSut('en', $this->localeEn, true);
$test = $this->getTest($sut, 'weekend');
self::assertFalse(\call_user_func($test->getCallable(), new \DateTime('first monday this month')));
self::assertFalse(\call_user_func($test->getCallable(), new \DateTime('first tuesday this month')));
self::assertFalse(\call_user_func($test->getCallable(), new \DateTime('first wednesday this month')));
self::assertFalse(\call_user_func($test->getCallable(), new \DateTime('first thursday this month')));
self::assertTrue(\call_user_func($test->getCallable(), new \DateTime('first friday this month')));
self::assertTrue(\call_user_func($test->getCallable(), new \DateTime('first saturday this month')));
self::assertFalse(\call_user_func($test->getCallable(), new \DateTime('first sunday this month')));
self::assertFalse(\call_user_func($test->getCallable(), new \stdClass()));
self::assertFalse(\call_user_func($test->getCallable(), null));
self::assertFalse($sut->isWeekend(new \DateTime('first monday this month')));
self::assertFalse($sut->isWeekend(new \DateTime('first tuesday this month')));
self::assertFalse($sut->isWeekend(new \DateTime('first wednesday this month')));
self::assertFalse($sut->isWeekend(new \DateTime('first thursday this month')));
self::assertTrue($sut->isWeekend(new \DateTime('first friday this month')));
self::assertTrue($sut->isWeekend(new \DateTime('first saturday this month')));
self::assertFalse($sut->isWeekend(new \DateTime('first sunday this month')));
self::assertFalse($sut->isWeekend(null));
}
protected function getTimesheet($seconds)
protected function getTimesheet($seconds): Timesheet
{
$begin = new \DateTime();
$end = clone $begin;
@@ -604,7 +577,7 @@ class LocaleFormatExtensionsTest extends TestCase
return $record;
}
public function testChartMoney()
public function testChartMoney(): void
{
$sut = $this->getSut('en', $this->localeEn, false);
$this->assertEquals('-123456.78', $sut->moneyChart(-123456.78));
@@ -613,10 +586,10 @@ class LocaleFormatExtensionsTest extends TestCase
$this->assertEquals('456.00', $sut->moneyChart(456));
}
public function testCharDuration()
public function testChartDuration(): void
{
$sut = $this->getSut('en', $this->localeEn, false);
$this->assertEquals('34.29', $sut->durationChart(123456.78));
$this->assertEquals('-34.29', $sut->durationChart(-123456.78));
$this->assertEquals('34.29', $sut->durationChart(123456));
$this->assertEquals('-34.29', $sut->durationChart(-123456));
}
}

View File

@@ -10,8 +10,8 @@
namespace App\Tests\Twig;
use App\Twig\PaginationExtension;
use App\Utils\Pagination;
use Pagerfanta\Adapter\ArrayAdapter;
use Pagerfanta\Pagerfanta;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Twig\TwigFunction;
@@ -21,7 +21,7 @@ use Twig\TwigFunction;
*/
class PaginationExtensionTest extends TestCase
{
private function getUrlGenerator()
private function getUrlGenerator(): UrlGeneratorInterface
{
$urlGenerator = $this->getMockBuilder(UrlGeneratorInterface::class)->getMock();
$urlGenerator
@@ -47,7 +47,7 @@ class PaginationExtensionTest extends TestCase
public function testGetFunctions()
{
$functions = ['pagerfanta', 'pagination'];
$functions = ['pagination'];
$sut = $this->getSut();
$twigFunctions = $sut->getFunctions();
self::assertCount(\count($functions), $twigFunctions);
@@ -59,33 +59,13 @@ class PaginationExtensionTest extends TestCase
}
}
/**
* @group legacy
*/
public function testDeprecatedRenderPagerfanta()
public function testRenderPaginationWithoutTemplateName()
{
$sut = $this->getSut();
$values = array_fill(0, 151, 'blub');
$pagerfanta = new Pagerfanta(new ArrayAdapter($values));
$result = $sut->renderPagerfanta($pagerfanta, 'twitter_bootstrap3_translated', [
'css_container_class' => 'pagination pagination-sm inline',
'routeName' => 'project_activities',
'routeParams' => ['id' => 137]
]);
$this->assertPaginationHtml($result);
}
/**
* @group legacy
*/
public function testDeprecatedRenderPagerfantaWithoutTemplateName()
{
$sut = $this->getSut();
$values = array_fill(0, 151, 'blub');
$pagerfanta = new Pagerfanta(new ArrayAdapter($values));
$result = $sut->renderPagerfanta($pagerfanta, [
$pagerfanta = new Pagination(new ArrayAdapter($values));
$result = $sut->renderPagination($pagerfanta, [
'css_container_class' => 'pagination pagination-sm inline',
'routeName' => 'project_activities',
'routeParams' => ['id' => 137]
@@ -95,15 +75,19 @@ class PaginationExtensionTest extends TestCase
protected function assertPaginationHtml($result)
{
// this makes sure that we show the correct amount of pagination links!
$expected =
'<ul class="pagination pagination-sm inline">' .
'<li class="prev disabled"><span><i class="fas fa-chevron-left"></i></span></li>' .
'<li class="active"><span>1 <span class="sr-only">(current)</span></span></li>' .
'<li><a href="project_activities?id=137&page=2">2</a></li>' .
'<li><a href="project_activities?id=137&page=3">3</a></li>' .
'<li class="disabled"><span>&hellip;</span></li>' .
'<li><a href="project_activities?id=137&page=16">16</a></li>' .
'<li class="next"><a href="project_activities?id=137&page=2" rel="next"><i class="fas fa-chevron-right"></i></a></li></ul>';
'<li class="page-item disabled"><span class="page-link pagination-link"><i class="fas fa-chevron-left"></i></span></li>' .
'<li class="page-item active"><a class="page-link pagination-link" href="project_activities?id=137&page=1">1</a></li>' .
'<li class="page-item"><a class="page-link pagination-link" href="project_activities?id=137&page=2">2</a></li>' .
'<li class="page-item"><a class="page-link pagination-link" href="project_activities?id=137&page=3">3</a></li>' .
'<li class="page-item"><a class="page-link pagination-link" href="project_activities?id=137&page=4">4</a></li>' .
'<li class="page-item"><a class="page-link pagination-link" href="project_activities?id=137&page=5">5</a></li>' .
'<li class="page-item disabled"><span class="page-link pagination-link">&hellip;</span></li>' .
'<li class="page-item"><a class="page-link pagination-link" href="project_activities?id=137&page=16">16</a></li>' .
'<li class="page-item"><a class="page-link pagination-link" href="project_activities?id=137&page=2" rel="next"><i class="fas fa-chevron-right"></i></a></li>' .
'</ul>';
self::assertEquals($expected, $result);
}
@@ -113,7 +97,7 @@ class PaginationExtensionTest extends TestCase
$sut = $this->getSut();
$values = array_fill(0, 151, 'blub');
$pagerfanta = new Pagerfanta(new ArrayAdapter($values));
$pagerfanta = new Pagination(new ArrayAdapter($values));
$result = $sut->renderPagination($pagerfanta, [
'css_container_class' => 'pagination pagination-sm inline',
'routeName' => 'project_activities',
@@ -130,7 +114,7 @@ class PaginationExtensionTest extends TestCase
$sut = $this->getSut();
$values = array_fill(0, 151, 'blub');
$pagerfanta = new Pagerfanta(new ArrayAdapter($values));
$pagerfanta = new Pagination(new ArrayAdapter($values));
$result = $sut->renderPagination($pagerfanta, [
'css_container_class' => 'pagination pagination-sm inline',
'routeParams' => ['id' => 137]

View File

@@ -10,7 +10,7 @@
namespace App\Tests\Twig\Runtime;
use App\Configuration\ConfigLoaderInterface;
use App\Configuration\SystemConfiguration;
use App\Tests\Mocks\SystemConfigurationFactory;
use App\Twig\Runtime\MarkdownExtension;
use App\Utils\Markdown;
use PHPUnit\Framework\TestCase;
@@ -23,7 +23,7 @@ class MarkdownExtensionTest extends TestCase
public function testMarkdownToHtml()
{
$loader = $this->createMock(ConfigLoaderInterface::class);
$config = new SystemConfiguration($loader, ['timesheet' => ['markdown_content' => true]]);
$config = SystemConfigurationFactory::create($loader, ['timesheet' => ['markdown_content' => true]]);
$sut = new MarkdownExtension(new Markdown(), $config);
$this->assertEquals('<p><em>test</em></p>', $sut->markdownToHtml('*test*'));
$this->assertEquals('<h1>foobar</h1>', $sut->markdownToHtml('# foobar'));
@@ -36,7 +36,7 @@ class MarkdownExtensionTest extends TestCase
public function testTimesheetContent()
{
$loader = $this->createMock(ConfigLoaderInterface::class);
$config = new SystemConfiguration($loader, ['timesheet' => ['markdown_content' => false]]);
$config = SystemConfigurationFactory::create($loader, ['timesheet' => ['markdown_content' => false]]);
$sut = new MarkdownExtension(new Markdown(), $config);
$this->assertEquals(
"- test<br />\n- foo",
@@ -48,7 +48,7 @@ class MarkdownExtensionTest extends TestCase
$this->assertEquals('## foobar', $sut->timesheetContent('## foobar'));
$this->assertEquals('### foobar', $sut->timesheetContent('### foobar'));
$config = new SystemConfiguration($loader, ['timesheet' => ['markdown_content' => true]]);
$config = SystemConfigurationFactory::create($loader, ['timesheet' => ['markdown_content' => true]]);
$sut = new MarkdownExtension(new Markdown(), $config);
$this->assertEquals(
"<ul>\n<li>test</li>\n<li>foo</li>\n</ul>\n<p>foo <strong>bar</strong></p>",
@@ -63,7 +63,7 @@ class MarkdownExtensionTest extends TestCase
public function testCommentContent()
{
$loader = $this->createMock(ConfigLoaderInterface::class);
$config = new SystemConfiguration($loader, ['timesheet' => ['markdown_content' => false]]);
$config = SystemConfigurationFactory::create($loader, ['timesheet' => ['markdown_content' => false]]);
$sut = new MarkdownExtension(new Markdown(), $config);
$this->assertEquals(
"<p>- test<br />\n- foo</p>",
@@ -88,7 +88,7 @@ class MarkdownExtensionTest extends TestCase
$this->assertEquals('<p>' . $loremIpsum . '</p>', $sut->commentContent($loremIpsum));
$this->assertEquals($loremIpsumShort, $sut->commentContent($loremIpsum, false));
$config = new SystemConfiguration($loader, ['timesheet' => ['markdown_content' => true]]);
$config = SystemConfigurationFactory::create($loader, ['timesheet' => ['markdown_content' => true]]);
$sut = new MarkdownExtension(new Markdown(), $config);
$this->assertEquals(
"<ul>\n<li>test</li>\n<li>foo</li>\n</ul>\n<p>foo <strong>bar</strong></p>",
@@ -103,7 +103,7 @@ class MarkdownExtensionTest extends TestCase
public function testCommentOneLiner()
{
$loader = $this->createMock(ConfigLoaderInterface::class);
$config = new SystemConfiguration($loader, []);
$config = SystemConfigurationFactory::create($loader, []);
$sut = new MarkdownExtension(new Markdown(), $config);
$loremIpsum = 'Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.';

View File

@@ -9,11 +9,11 @@
namespace App\Tests\Twig\Runtime;
use App\Configuration\SystemConfiguration;
use App\Entity\Configuration;
use App\Entity\User;
use App\Event\ThemeEvent;
use App\Tests\Configuration\TestConfigLoader;
use App\Tests\Event\ThemeJavascriptTranslationsEventTest;
use App\Tests\Mocks\SystemConfigurationFactory;
use App\Twig\Runtime\ThemeExtension;
use PHPUnit\Framework\TestCase;
use Symfony\Bridge\Twig\AppVariable;
@@ -33,9 +33,6 @@ class ThemeEventExtensionTest extends TestCase
{
return [
'theme' => [
'active_warning' => 3,
'box_color' => 'green',
'select_type' => null,
'show_about' => true,
'chart' => [
'background_color' => 'rgba(0,115,183,0.7)',
@@ -45,9 +42,7 @@ class ThemeEventExtensionTest extends TestCase
],
'branding' => [
'logo' => null,
'mini' => null,
'company' => null,
'title' => null,
],
],
];
@@ -62,11 +57,9 @@ class ThemeEventExtensionTest extends TestCase
$translator = $this->getMockBuilder(TranslatorInterface::class)->getMock();
$translator->method('trans')->willReturn('foo');
$configs = [
(new Configuration())->setName('theme.branding.title')->setValue($title)
];
$configs = [];
$loader = new TestConfigLoader($configs);
$configuration = new SystemConfiguration($loader, $this->getDefaultSettings());
$configuration = SystemConfigurationFactory::create($loader, $this->getDefaultSettings());
return new ThemeExtension($dispatcher, $translator, $configuration);
}
@@ -108,41 +101,41 @@ class ThemeEventExtensionTest extends TestCase
{
$sut = $this->getSut();
$values = $sut->getJavascriptTranslations();
self::assertCount(24, $values);
self::assertCount(ThemeJavascriptTranslationsEventTest::COUNTER, $values);
}
public function getProgressbarColors()
{
yield ['progress-bar-danger', 100, false];
yield ['progress-bar-danger', 91, false];
yield ['progress-bar-warning', 90, false];
yield ['progress-bar-warning', 80, false];
yield ['progress-bar-warning', 71, false];
yield ['progress-bar-success', 70, false];
yield ['progress-bar-success', 60, false];
yield ['progress-bar-success', 51, false];
yield ['progress-bar-primary', 50, false];
yield ['progress-bar-primary', 40, false];
yield ['progress-bar-primary', 31, false];
yield ['progress-bar-info', 30, false];
yield ['progress-bar-info', 20, false];
yield ['progress-bar-info', 10, false];
yield ['progress-bar-info', 0, false];
yield ['progress-bar-primary', 100, true];
yield ['progress-bar-primary', 91, true];
yield ['progress-bar-success', 90, true];
yield ['progress-bar-success', 80, true];
yield ['progress-bar-success', 71, true];
yield ['progress-bar-warning', 70, true];
yield ['progress-bar-warning', 60, true];
yield ['progress-bar-warning', 51, true];
yield ['progress-bar-danger', 50, true];
yield ['progress-bar-danger', 40, true];
yield ['progress-bar-danger', 31, true];
yield ['progress-bar-info', 30, true];
yield ['progress-bar-info', 20, true];
yield ['progress-bar-info', 10, true];
yield ['progress-bar-info', 0, true];
yield ['bg-red', 100, false];
yield ['bg-red', 91, false];
yield ['bg-warning', 90, false];
yield ['bg-warning', 80, false];
yield ['bg-warning', 71, false];
yield ['bg-green', 70, false];
yield ['bg-green', 60, false];
yield ['bg-green', 51, false];
yield ['bg-green', 50, false];
yield ['bg-green', 40, false];
yield ['bg-green', 31, false];
yield ['', 30, false];
yield ['', 20, false];
yield ['', 10, false];
yield ['', 0, false];
yield ['bg-green', 100, true];
yield ['bg-green', 91, true];
yield ['bg-green', 90, true];
yield ['bg-green', 80, true];
yield ['bg-green', 71, true];
yield ['bg-warning', 70, true];
yield ['bg-warning', 60, true];
yield ['bg-warning', 51, true];
yield ['bg-red', 50, true];
yield ['bg-red', 40, true];
yield ['bg-red', 31, true];
yield ['', 30, true];
yield ['', 20, true];
yield ['', 10, true];
yield ['', 0, true];
}
/**
@@ -166,20 +159,9 @@ class ThemeEventExtensionTest extends TestCase
public function testGetBrandedTitle()
{
$sut = $this->getSut(false, 'MyCompany');
$this->assertEquals('MyCompany foo', $sut->generateTitle());
$this->assertEquals('sdfsdf | MyCompany foo', $sut->generateTitle('sdfsdf | '));
$this->assertEquals('<b>MyCompany</b> ... foo', $sut->generateTitle('<b>', '</b> ... '));
$this->assertEquals('MyCompany | foo', $sut->generateTitle(null, ' | '));
}
/**
* @group legacy
*/
public function testThemeConfig()
{
$sut = $this->getSut(false);
self::assertEquals(3, $sut->getThemeConfig('active_warning'));
self::assertEquals('green', $sut->getThemeConfig('box_color'));
self::assertFalse($sut->getThemeConfig('auto_reload_datatable'));
$this->assertEquals('Kimai foo', $sut->generateTitle());
$this->assertEquals('sdfsdf | Kimai foo', $sut->generateTitle('sdfsdf | '));
$this->assertEquals('<b>Kimai</b> ... foo', $sut->generateTitle('<b>', '</b> ... '));
$this->assertEquals('Kimai | foo', $sut->generateTitle(null, ' | '));
}
}

View File

@@ -11,7 +11,9 @@ namespace App\Tests\Twig\Runtime;
use App\Entity\Timesheet;
use App\Entity\User;
use App\Repository\BookmarkRepository;
use App\Repository\TimesheetRepository;
use App\Timesheet\FavoriteRecordService;
use App\Twig\Runtime\TimesheetExtension;
use PHPUnit\Framework\TestCase;
@@ -20,14 +22,43 @@ use PHPUnit\Framework\TestCase;
*/
class TimesheetExtensionTest extends TestCase
{
public function testGetExporter()
public function testActiveEntries()
{
$entries = [new Timesheet(), new Timesheet()];
$repository = $this->createMock(TimesheetRepository::class);
$repository->method('getActiveEntries')->willReturn($entries);
$sut = new TimesheetExtension($repository);
$bookmarks = $this->createMock(BookmarkRepository::class);
$service = new FavoriteRecordService($repository, $bookmarks);
$sut = new TimesheetExtension($repository, $service);
self::assertEquals($entries, $sut->activeEntries(new User()));
}
public function testRecentEntries()
{
$timesheet1 = $this->createMock(Timesheet::class);
$timesheet1->method('getId')->willReturn(1);
$timesheet2 = $this->createMock(Timesheet::class);
$timesheet2->method('getId')->willReturn(2);
$entries = [$timesheet1, $timesheet2];
$repository = $this->createMock(TimesheetRepository::class);
$repository->method('findTimesheetsById')->willReturn($entries);
$repository->method('getRecentActivityIds')->willReturn([1, 2]);
$bookmarks = $this->createMock(BookmarkRepository::class);
$service = new FavoriteRecordService($repository, $bookmarks);
$sut = new TimesheetExtension($repository, $service);
$favorites = $sut->favoriteEntries(new User());
self::assertCount(2, $favorites);
self::assertEquals($entries[0], $favorites[0]->getTimesheet());
self::assertFalse($favorites[0]->isFavorite());
self::assertEquals($entries[1], $favorites[1]->getTimesheet());
self::assertFalse($favorites[1]->isFavorite());
}
}

View File

@@ -9,19 +9,23 @@
namespace App\Tests\Twig\Runtime;
use App\Entity\User;
use App\Twig\Runtime\WidgetExtension;
use App\Widget\Type\More;
use App\Widget\WidgetInterface;
use App\Widget\WidgetRendererInterface;
use App\Widget\WidgetService;
use PHPUnit\Framework\TestCase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Security;
use Twig\Environment;
/**
* @covers \App\Twig\Runtime\WidgetExtension
*/
class WidgetExtensionTest extends TestCase
{
protected function getSut($hasWidget = null, $getWidget = null, $renderer = null): WidgetExtension
protected function getSut($hasWidget = null, $getWidget = null): WidgetExtension
{
$service = $this->createMock(WidgetService::class);
if (null !== $hasWidget) {
@@ -30,21 +34,42 @@ class WidgetExtensionTest extends TestCase
if (null !== $getWidget) {
$service->expects($this->once())->method('getWidget')->willReturn($getWidget);
}
if (null !== $renderer) {
$service->expects($this->once())->method('findRenderer')->willReturn($renderer);
}
return new WidgetExtension($service);
$interface = $this->createMock(TokenInterface::class);
$interface->expects($this->any())->method('getUser')->willReturn(new User());
$storage = $this->createMock(TokenStorageInterface::class);
$storage->expects($this->any())->method('getToken')->willReturn($interface);
$container = $this->createMock(ContainerInterface::class);
$container->expects($this->any())->method('get')->willReturn($storage);
$security = new Security($container);
return new WidgetExtension($service, $security);
}
private function getEnvironment(): Environment
{
$env = $this->createMock(Environment::class);
$env->expects($this->any())->method('render')->willReturnCallback(function (string $template, array $options) {
self::assertArrayHasKey('data', $options);
self::assertArrayHasKey('options', $options);
self::assertArrayHasKey('title', $options);
self::assertArrayHasKey('widget', $options);
return json_encode($options['options']);
});
return $env;
}
public function testRenderWidgetForInvalidValue()
{
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('Widget must either implement WidgetInterface or be a string');
$this->expectExceptionMessage('Widget must be either a WidgetInterface or a string');
$sut = $this->getSut();
/* @phpstan-ignore-next-line */
$sut->renderWidget(true);
$sut->renderWidget($this->getEnvironment(), true);
}
public function testRenderWidgetForUnknownWidget()
@@ -53,15 +78,16 @@ class WidgetExtensionTest extends TestCase
$this->expectExceptionMessage('Unknown widget "test" requested');
$sut = $this->getSut(false);
$sut->renderWidget('test');
$sut->renderWidget($this->getEnvironment(), 'test');
}
public function testRenderWidgetByString()
{
$widget = new More();
$sut = $this->getSut(true, $widget, new TestRenderer());
$widget->setId('test');
$sut = $this->getSut(true, $widget);
$options = ['foo' => 'bar', 'dataType' => 'blub'];
$result = $sut->renderWidget('test', $options);
$result = $sut->renderWidget($this->getEnvironment(), 'test', $options);
$data = json_decode($result, true);
$this->assertEquals($options, $data);
}
@@ -69,23 +95,10 @@ class WidgetExtensionTest extends TestCase
public function testRenderWidgetObject()
{
$widget = new More();
$sut = $this->getSut(null, null, new TestRenderer());
$sut = $this->getSut(null, null);
$options = ['foo' => 'bar', 'dataType' => 'blub'];
$result = $sut->renderWidget($widget, $options);
$result = $sut->renderWidget($this->getEnvironment(), $widget, $options);
$data = json_decode($result, true);
$this->assertEquals($options, $data);
}
}
class TestRenderer implements WidgetRendererInterface
{
public function supports(WidgetInterface $widget): bool
{
return true;
}
public function render(WidgetInterface $widget, array $options = []): string
{
return json_encode($widget->getOptions($options));
}
}

View File

@@ -22,7 +22,7 @@ class RuntimeExtensionsTest extends TestCase
{
public function testGetFilters()
{
$expected = ['md2html', 'desc2html', 'comment2html', 'comment1line', 'colorize'];
$expected = ['md2html', 'desc2html', 'comment2html', 'comment1line', 'colorize', 'icon'];
$i = 0;
$sut = new RuntimeExtensions();
@@ -43,10 +43,12 @@ class RuntimeExtensionsTest extends TestCase
'get_title',
'progressbar_color',
'javascript_translations',
'theme_config',
'form_time_presets',
'active_timesheets',
'favorite_timesheets',
'encore_entry_css_source',
'render_widget',
'icon',
];
$i = 0;