Final fixes

Signed-off-by: Georg Ehrke <developer@georgehrke.com>
This commit is contained in:
Georg Ehrke 2019-08-12 13:20:03 +02:00 committed by Roeland Jago Douma
parent 2d6473e79b
commit 4d28a4544e
No known key found for this signature in database
GPG Key ID: F941078878347C0C
19 changed files with 1625 additions and 834 deletions

@ -1 +1 @@
Subproject commit ef289bc27eae0cdfc3f74f419ace8dda8dd84ef0 Subproject commit 49ccfbb28661b9ef7743c1725cd2571259215929

View File

@ -23,7 +23,7 @@ declare(strict_types=1);
*/ */
namespace OCA\DAV\BackgroundJob; namespace OCA\DAV\BackgroundJob;
use OC\BackgroundJob\QueuedJob; use OCP\BackgroundJob\QueuedJob;
use OCA\DAV\CalDAV\Reminder\ReminderService; use OCA\DAV\CalDAV\Reminder\ReminderService;
use OCP\AppFramework\Utility\ITimeFactory; use OCP\AppFramework\Utility\ITimeFactory;
use OCP\BackgroundJob\IJobList; use OCP\BackgroundJob\IJobList;

View File

@ -63,7 +63,7 @@ class Backend {
$query = $this->db->getQueryBuilder(); $query = $this->db->getQueryBuilder();
$query->select(['cr.*', 'co.calendardata', 'c.displayname', 'c.principaluri']) $query->select(['cr.*', 'co.calendardata', 'c.displayname', 'c.principaluri'])
->from('calendar_reminders', 'cr') ->from('calendar_reminders', 'cr')
// ->where($query->expr()->lte('cr.notification_date', $query->createNamedParameter($this->timeFactory->getTime()))) ->where($query->expr()->lte('cr.notification_date', $query->createNamedParameter($this->timeFactory->getTime())))
->leftJoin('cr', 'calendarobjects', 'co', $query->expr()->eq('cr.object_id', 'co.id')) ->leftJoin('cr', 'calendarobjects', 'co', $query->expr()->eq('cr.object_id', 'co.id'))
->leftJoin('cr', 'calendars', 'c', $query->expr()->eq('cr.calendar_id', 'c.id')); ->leftJoin('cr', 'calendars', 'c', $query->expr()->eq('cr.calendar_id', 'c.id'));
$stmt = $query->execute(); $stmt = $query->execute();

View File

@ -25,8 +25,6 @@ declare(strict_types=1);
*/ */
namespace OCA\DAV\CalDAV\Reminder\NotificationProvider; namespace OCA\DAV\CalDAV\Reminder\NotificationProvider;
use \DateTime;
use \DateTimeImmutable;
use OCA\DAV\CalDAV\Reminder\INotificationProvider; use OCA\DAV\CalDAV\Reminder\INotificationProvider;
use OCP\IConfig; use OCP\IConfig;
use OCP\IL10N; use OCP\IL10N;
@ -36,7 +34,6 @@ use OCP\L10N\IFactory as L10NFactory;
use OCP\IUser; use OCP\IUser;
use Sabre\VObject\Component\VEvent; use Sabre\VObject\Component\VEvent;
use Sabre\VObject\DateTimeParser; use Sabre\VObject\DateTimeParser;
use Sabre\VObject\Parameter;
use Sabre\VObject\Property; use Sabre\VObject\Property;
/** /**
@ -49,22 +46,22 @@ abstract class AbstractProvider implements INotificationProvider {
/** @var string */ /** @var string */
public const NOTIFICATION_TYPE = ''; public const NOTIFICATION_TYPE = '';
/** @var ILogger */ /** @var ILogger */
protected $logger; protected $logger;
/** @var L10NFactory */ /** @var L10NFactory */
private $l10nFactory; private $l10nFactory;
/** @var IL10N[] */ /** @var IL10N[] */
private $l10ns; private $l10ns;
/** @var string */ /** @var string */
private $fallbackLanguage; private $fallbackLanguage;
/** @var IURLGenerator */ /** @var IURLGenerator */
protected $urlGenerator; protected $urlGenerator;
/** @var IConfig */ /** @var IConfig */
protected $config; protected $config;
/** /**
@ -79,9 +76,9 @@ abstract class AbstractProvider implements INotificationProvider {
IConfig $config) { IConfig $config) {
$this->logger = $logger; $this->logger = $logger;
$this->l10nFactory = $l10nFactory; $this->l10nFactory = $l10nFactory;
$this->urlGenerator = $urlGenerator; $this->urlGenerator = $urlGenerator;
$this->config = $config; $this->config = $config;
} }
/** /**
* Send notification * Send notification
@ -91,22 +88,22 @@ abstract class AbstractProvider implements INotificationProvider {
* @param IUser[] $users * @param IUser[] $users
* @return void * @return void
*/ */
abstract public function send(VEvent $vevent, abstract public function send(VEvent $vevent,
string $calendarDisplayName, string $calendarDisplayName,
array $users=[]): void; array $users=[]): void;
/** /**
* @return string * @return string
*/ */
protected function getFallbackLanguage():string { protected function getFallbackLanguage():string {
if ($this->fallbackLanguage) { if ($this->fallbackLanguage) {
return $this->fallbackLanguage; return $this->fallbackLanguage;
} }
$fallbackLanguage = $this->l10nFactory->findLanguage(); $fallbackLanguage = $this->l10nFactory->findLanguage();
$this->fallbackLanguage = $fallbackLanguage; $this->fallbackLanguage = $fallbackLanguage;
return $fallbackLanguage; return $fallbackLanguage;
} }
/** /**
@ -114,7 +111,7 @@ abstract class AbstractProvider implements INotificationProvider {
* @return bool * @return bool
*/ */
protected function hasL10NForLang(string $lang):bool { protected function hasL10NForLang(string $lang):bool {
return $this->l10nFactory->languageExists('dav', $lang); return $this->l10nFactory->languageExists('dav', $lang);
} }
/** /**

View File

@ -25,8 +25,7 @@ declare(strict_types=1);
*/ */
namespace OCA\DAV\CalDAV\Reminder\NotificationProvider; namespace OCA\DAV\CalDAV\Reminder\NotificationProvider;
use DateTime; use \DateTime;
use DateTimeImmutable;
use OCP\IConfig; use OCP\IConfig;
use OCP\IL10N; use OCP\IL10N;
use OCP\ILogger; use OCP\ILogger;
@ -97,36 +96,35 @@ class EmailProvider extends AbstractProvider {
$organizer = $this->getOrganizerEMailAndNameFromEvent($vevent); $organizer = $this->getOrganizerEMailAndNameFromEvent($vevent);
foreach($sortedByLanguage as $lang => $emailAddresses) { foreach($sortedByLanguage as $lang => $emailAddresses) {
if ($this->hasL10NForLang($lang)) { if (!$this->hasL10NForLang($lang)) {
$lang = $fallbackLanguage; $lang = $fallbackLanguage;
} }
$l10n = $this->getL10NForLang($lang); $l10n = $this->getL10NForLang($lang);
$fromEMail = \OCP\Util::getDefaultEmailAddress('reminders-noreply'); $fromEMail = \OCP\Util::getDefaultEmailAddress('reminders-noreply');
$message = $this->mailer->createMessage();
$message->setFrom([$fromEMail]);
if ($organizer) {
$message->setReplyTo($organizer);
}
$message->setTo([])
->setBcc($emailAddresses);
$template = $this->mailer->createEMailTemplate('dav.calendarReminder'); $template = $this->mailer->createEMailTemplate('dav.calendarReminder');
$template->addHeader(); $template->addHeader();
$this->addSubjectAndHeading($template, $l10n, $vevent); $this->addSubjectAndHeading($template, $l10n, $vevent);
$this->addBulletList($template, $l10n, $calendarDisplayName, $vevent); $this->addBulletList($template, $l10n, $calendarDisplayName, $vevent);
$template->addFooter(); $template->addFooter();
$message->useTemplate($template);
try { foreach ($emailAddresses as $emailAddress) {
$failed = $this->mailer->send($message); $message = $this->mailer->createMessage();
if ($failed) { $message->setFrom([$fromEMail]);
$this->logger->error('Unable to deliver message to {failed}', ['app' => 'dav', 'failed' => implode(', ', $failed)]); if ($organizer) {
$message->setReplyTo($organizer);
}
$message->setTo([$emailAddress]);
$message->useTemplate($template);
try {
$failed = $this->mailer->send($message);
if ($failed) {
$this->logger->error('Unable to deliver message to {failed}', ['app' => 'dav', 'failed' => implode(', ', $failed)]);
}
} catch (\Exception $ex) {
$this->logger->logException($ex, ['app' => 'dav']);
} }
} catch (\Exception $ex) {
$this->logger->logException($ex, ['app' => 'dav']);
} }
} }
} }
@ -165,9 +163,9 @@ class EmailProvider extends AbstractProvider {
$template->addBodyListItem((string) $vevent->DESCRIPTION, $l10n->t('Description:'), $template->addBodyListItem((string) $vevent->DESCRIPTION, $l10n->t('Description:'),
$this->getAbsoluteImagePath('actions/more.svg')); $this->getAbsoluteImagePath('actions/more.svg'));
} }
} }
/** /**
* @param string $path * @param string $path
* @return string * @return string
*/ */
@ -201,35 +199,6 @@ class EmailProvider extends AbstractProvider {
return [$organizerEMail]; return [$organizerEMail];
} }
/**
* @param array $sortedByLanguage
* @param IUser[] $users
* @param string $defaultLanguage
*/
private function sortUsersByLanguage(array &$sortedByLanguage,
array $users,
string $defaultLanguage):void {
/**
* @var array $sortedByLanguage
* [
* 'de' => ['a@b.com', 'c@d.com'],
* ...
* ]
*/
foreach($users as $user) {
/** @var IUser $user */
$emailAddress = $user->getEMailAddress();
$lang = $this->config->getUserValue($user->getUID(),
'core', 'lang', $defaultLanguage);
if (!isset($sortedByLanguage[$lang])) {
$sortedByLanguage[$lang] = [];
}
$sortedByLanguage[$lang][] = $emailAddress;
}
}
/** /**
* @param array $emails * @param array $emails
* @param string $defaultLanguage * @param string $defaultLanguage
@ -386,7 +355,7 @@ class EmailProvider extends AbstractProvider {
} }
} }
return array_unique($emailAddresses); return $emailAddresses;
} }
/** /**
@ -415,7 +384,9 @@ class EmailProvider extends AbstractProvider {
$diff = $dtstartDt->diff($dtendDt); $diff = $dtstartDt->diff($dtendDt);
/** @phan-suppress-next-line PhanUndeclaredClassMethod */
$dtstartDt = new \DateTime($dtstartDt->format(\DateTime::ATOM)); $dtstartDt = new \DateTime($dtstartDt->format(\DateTime::ATOM));
/** @phan-suppress-next-line PhanUndeclaredClassMethod */
$dtendDt = new \DateTime($dtendDt->format(\DateTime::ATOM)); $dtendDt = new \DateTime($dtendDt->format(\DateTime::ATOM));
if ($isAllDay) { if ($isAllDay) {
@ -432,7 +403,9 @@ class EmailProvider extends AbstractProvider {
$startTimezone = $endTimezone = null; $startTimezone = $endTimezone = null;
if (!$vevent->DTSTART->isFloating()) { if (!$vevent->DTSTART->isFloating()) {
/** @phan-suppress-next-line PhanUndeclaredClassMethod */
$startTimezone = $vevent->DTSTART->getDateTime()->getTimezone()->getName(); $startTimezone = $vevent->DTSTART->getDateTime()->getTimezone()->getName();
/** @phan-suppress-next-line PhanUndeclaredClassMethod */
$endTimezone = $this->getDTEndFromEvent($vevent)->getDateTime()->getTimezone()->getName(); $endTimezone = $this->getDTEndFromEvent($vevent)->getDateTime()->getTimezone()->getName();
} }

View File

@ -47,7 +47,7 @@ class PushProvider extends AbstractProvider {
/** @var string */ /** @var string */
public const NOTIFICATION_TYPE = 'DISPLAY'; public const NOTIFICATION_TYPE = 'DISPLAY';
/** @var IManager */ /** @var IManager */
private $manager; private $manager;
/** @var ITimeFactory */ /** @var ITimeFactory */
@ -70,7 +70,7 @@ class PushProvider extends AbstractProvider {
parent::__construct($logger, $l10nFactory, $urlGenerator, $config); parent::__construct($logger, $l10nFactory, $urlGenerator, $config);
$this->manager = $manager; $this->manager = $manager;
$this->timeFactory = $timeFactory; $this->timeFactory = $timeFactory;
} }
/** /**
* Send push notification to all users. * Send push notification to all users.
@ -80,13 +80,13 @@ class PushProvider extends AbstractProvider {
* @param IUser[] $users * @param IUser[] $users
* @throws \Exception * @throws \Exception
*/ */
public function send(VEvent $vevent, public function send(VEvent $vevent,
string $calendarDisplayName=null, string $calendarDisplayName=null,
array $users=[]):void { array $users=[]):void {
$eventDetails = $this->extractEventDetails($vevent); $eventDetails = $this->extractEventDetails($vevent);
$eventDetails['calendar_displayname'] = $calendarDisplayName; $eventDetails['calendar_displayname'] = $calendarDisplayName;
foreach($users as $user) { foreach($users as $user) {
/** @var INotification $notification */ /** @var INotification $notification */
$notification = $this->manager->createNotification(); $notification = $this->manager->createNotification();
$notification->setApp(Application::APP_ID) $notification->setApp(Application::APP_ID)
@ -101,7 +101,7 @@ class PushProvider extends AbstractProvider {
$this->manager->notify($notification); $this->manager->notify($notification);
} }
} }
/** /**
* @var VEvent $vevent * @var VEvent $vevent
@ -124,11 +124,15 @@ class PushProvider extends AbstractProvider {
? ((string) $vevent->LOCATION) ? ((string) $vevent->LOCATION)
: null, : null,
'all_day' => $start instanceof Property\ICalendar\Date, 'all_day' => $start instanceof Property\ICalendar\Date,
/** @phan-suppress-next-line PhanUndeclaredClassMethod */
'start_atom' => $start->getDateTime()->format(\DateTime::ATOM), 'start_atom' => $start->getDateTime()->format(\DateTime::ATOM),
'start_is_floating' => $start->isFloating(), 'start_is_floating' => $start->isFloating(),
/** @phan-suppress-next-line PhanUndeclaredClassMethod */
'start_timezone' => $start->getDateTime()->getTimezone()->getName(), 'start_timezone' => $start->getDateTime()->getTimezone()->getName(),
/** @phan-suppress-next-line PhanUndeclaredClassMethod */
'end_atom' => $end->getDateTime()->format(\DateTime::ATOM), 'end_atom' => $end->getDateTime()->format(\DateTime::ATOM),
'end_is_floating' => $end->isFloating(), 'end_is_floating' => $end->isFloating(),
/** @phan-suppress-next-line PhanUndeclaredClassMethod */
'end_timezone' => $end->getDateTime()->getTimezone()->getName(), 'end_timezone' => $end->getDateTime()->getTimezone()->getName(),
]; ];
} }

View File

@ -31,8 +31,8 @@ namespace OCA\DAV\CalDAV\Reminder;
*/ */
class NotificationProviderManager { class NotificationProviderManager {
/** @var INotificationProvider[] */ /** @var INotificationProvider[] */
private $providers = []; private $providers = [];
/** /**
* Checks whether a provider for a given ACTION exists * Checks whether a provider for a given ACTION exists
@ -45,23 +45,23 @@ class NotificationProviderManager {
&& isset($this->providers[$type])); && isset($this->providers[$type]));
} }
/** /**
* Get provider for a given ACTION * Get provider for a given ACTION
* *
* @param string $type * @param string $type
* @return INotificationProvider * @return INotificationProvider
* @throws NotificationProvider\ProviderNotAvailableException * @throws NotificationProvider\ProviderNotAvailableException
* @throws NotificationTypeDoesNotExistException * @throws NotificationTypeDoesNotExistException
*/ */
public function getProvider(string $type):INotificationProvider { public function getProvider(string $type):INotificationProvider {
if (in_array($type, ReminderService::REMINDER_TYPES, true)) { if (in_array($type, ReminderService::REMINDER_TYPES, true)) {
if (isset($this->providers[$type])) { if (isset($this->providers[$type])) {
return $this->providers[$type]; return $this->providers[$type];
} }
throw new NotificationProvider\ProviderNotAvailableException($type); throw new NotificationProvider\ProviderNotAvailableException($type);
} }
throw new NotificationTypeDoesNotExistException($type); throw new NotificationTypeDoesNotExistException($type);
} }
/** /**
* Registers a new provider * Registers a new provider
@ -69,7 +69,7 @@ class NotificationProviderManager {
* @param string $providerClassName * @param string $providerClassName
* @throws \OCP\AppFramework\QueryException * @throws \OCP\AppFramework\QueryException
*/ */
public function registerProvider(string $providerClassName):void { public function registerProvider(string $providerClassName):void {
$provider = \OC::$server->query($providerClassName); $provider = \OC::$server->query($providerClassName);
if (!$provider instanceof INotificationProvider) { if (!$provider instanceof INotificationProvider) {

View File

@ -25,7 +25,7 @@ declare(strict_types=1);
namespace OCA\DAV\CalDAV\Reminder; namespace OCA\DAV\CalDAV\Reminder;
use DateTime; use \DateTime;
use OCA\DAV\AppInfo\Application; use OCA\DAV\AppInfo\Application;
use OCP\AppFramework\Utility\ITimeFactory; use OCP\AppFramework\Utility\ITimeFactory;
use OCP\IL10N; use OCP\IL10N;
@ -85,10 +85,6 @@ class Notifier implements INotifier {
* @since 17.0.0 * @since 17.0.0
*/ */
public function getName():string { public function getName():string {
if ($this->l10n) {
return $this->l10n->t('Calendar');
}
return $this->l10nFactory->get('dav')->t('Calendar'); return $this->l10nFactory->get('dav')->t('Calendar');
} }
@ -143,7 +139,7 @@ class Notifier implements INotifier {
private function prepareNotificationSubject(INotification $notification): void { private function prepareNotificationSubject(INotification $notification): void {
$parameters = $notification->getSubjectParameters(); $parameters = $notification->getSubjectParameters();
$startTime = \DateTime::createFromFormat(\DateTimeInterface::ATOM, $parameters['start_atom']); $startTime = \DateTime::createFromFormat(\DateTime::ATOM, $parameters['start_atom']);
$now = $this->timeFactory->getDateTime(); $now = $this->timeFactory->getDateTime();
$title = $this->getTitleFromParameters($parameters); $title = $this->getTitleFromParameters($parameters);
@ -220,8 +216,8 @@ class Notifier implements INotifier {
* @throws \Exception * @throws \Exception
*/ */
private function generateDateString(array $parameters):string { private function generateDateString(array $parameters):string {
$startDateTime = DateTime::createFromFormat(DATE_ATOM, $parameters['start_atom']); $startDateTime = DateTime::createFromFormat(\DateTime::ATOM, $parameters['start_atom']);
$endDateTime = DateTime::createFromFormat(DATE_ATOM, $parameters['end_atom']); $endDateTime = DateTime::createFromFormat(\DateTime::ATOM, $parameters['end_atom']);
$isAllDay = $parameters['all_day']; $isAllDay = $parameters['all_day'];
$diff = $startDateTime->diff($endDateTime); $diff = $startDateTime->diff($endDateTime);

View File

@ -24,7 +24,7 @@ declare(strict_types=1);
*/ */
namespace OCA\DAV\CalDAV\Reminder; namespace OCA\DAV\CalDAV\Reminder;
use DateTimeImmutable; use \DateTimeImmutable;
use OCA\DAV\CalDAV\CalDavBackend; use OCA\DAV\CalDAV\CalDavBackend;
use OCP\AppFramework\Utility\ITimeFactory; use OCP\AppFramework\Utility\ITimeFactory;
use OCP\IGroup; use OCP\IGroup;
@ -40,11 +40,11 @@ use Sabre\VObject\Recur\NoInstancesException;
class ReminderService { class ReminderService {
/** @var Backend */ /** @var Backend */
private $backend; private $backend;
/** @var NotificationProviderManager */ /** @var NotificationProviderManager */
private $notificationProviderManager; private $notificationProviderManager;
/** @var IUserManager */ /** @var IUserManager */
private $userManager; private $userManager;
@ -83,19 +83,19 @@ class ReminderService {
* @param CalDavBackend $caldavBackend * @param CalDavBackend $caldavBackend
* @param ITimeFactory $timeFactory * @param ITimeFactory $timeFactory
*/ */
public function __construct(Backend $backend, public function __construct(Backend $backend,
NotificationProviderManager $notificationProviderManager, NotificationProviderManager $notificationProviderManager,
IUserManager $userManager, IUserManager $userManager,
IGroupManager $groupManager, IGroupManager $groupManager,
CalDavBackend $caldavBackend, CalDavBackend $caldavBackend,
ITimeFactory $timeFactory) { ITimeFactory $timeFactory) {
$this->backend = $backend; $this->backend = $backend;
$this->notificationProviderManager = $notificationProviderManager; $this->notificationProviderManager = $notificationProviderManager;
$this->userManager = $userManager; $this->userManager = $userManager;
$this->groupManager = $groupManager; $this->groupManager = $groupManager;
$this->caldavBackend = $caldavBackend; $this->caldavBackend = $caldavBackend;
$this->timeFactory = $timeFactory; $this->timeFactory = $timeFactory;
} }
/** /**
* Process reminders to activate * Process reminders to activate
@ -103,12 +103,12 @@ class ReminderService {
* @throws NotificationProvider\ProviderNotAvailableException * @throws NotificationProvider\ProviderNotAvailableException
* @throws NotificationTypeDoesNotExistException * @throws NotificationTypeDoesNotExistException
*/ */
public function processReminders():void { public function processReminders():void {
$reminders = $this->backend->getRemindersToProcess(); $reminders = $this->backend->getRemindersToProcess();
foreach($reminders as $reminder) { foreach($reminders as $reminder) {
$vcalendar = $this->parseCalendarData($reminder['calendardata']); $vcalendar = $this->parseCalendarData($reminder['calendardata']);
if (!$vcalendar) { if (!$vcalendar) {
$this->backend->removeReminder($reminder['id']); $this->backend->removeReminder($reminder['id']);
continue; continue;
} }
@ -140,7 +140,7 @@ class ReminderService {
$this->deleteOrProcessNext($reminder, $vevent); $this->deleteOrProcessNext($reminder, $vevent);
} }
} }
/** /**
* @param string $action * @param string $action
@ -175,7 +175,7 @@ class ReminderService {
/** /**
* @param array $objectData * @param array $objectData
*/ */
private function onCalendarObjectCreate(array $objectData):void { private function onCalendarObjectCreate(array $objectData):void {
/** @var VObject\Component\VCalendar $vcalendar */ /** @var VObject\Component\VCalendar $vcalendar */
$vcalendar = $this->parseCalendarData($objectData['calendardata']); $vcalendar = $this->parseCalendarData($objectData['calendardata']);
if (!$vcalendar) { if (!$vcalendar) {
@ -343,7 +343,7 @@ class ReminderService {
'is_repeat_based' => false, 'is_repeat_based' => false,
]; ];
$repeat = $valarm->REPEAT ? (int) $valarm->REPEAT : 0; $repeat = isset($valarm->REPEAT) ? (int) $valarm->REPEAT->getValue() : 0;
for($i = 0; $i < $repeat; $i++) { for($i = 0; $i < $repeat; $i++) {
if ($valarm->DURATION === null) { if ($valarm->DURATION === null) {
continue; continue;
@ -671,7 +671,7 @@ class ReminderService {
return null; return null;
} }
if (strcasecmp($principalUri, 'principals/users/') !== 0) { if (stripos($principalUri, 'principals/users/') !== 0) {
return null; return null;
} }

View File

@ -324,7 +324,8 @@ class Version1004Date20170825134824 extends SimpleMigrationStep {
'length' => 1, 'length' => 1,
]); ]);
$table->addColumn('stripattachments', 'smallint', [ $table->addColumn('stripattachments', 'smallint', [
'notnull' => false,
'length' => 1,
]); ]);
$table->addColumn('lastmodified', 'integer', [ $table->addColumn('lastmodified', 'integer', [
'notnull' => false, 'notnull' => false,

View File

@ -51,17 +51,42 @@ class EventReminderJobTest extends TestCase {
public function data(): array public function data(): array
{ {
return [[true], [false]]; return [
[true, true, true],
[true, false, false],
[false, true, false],
[false, false, false],
];
} }
/** /**
* @dataProvider data * @dataProvider data
*
* @param bool $sendEventReminders * @param bool $sendEventReminders
* @param bool $sendEventRemindersMode
* @param bool $expectCall
*/ */
public function testRun(bool $sendEventReminders): void public function testRun(bool $sendEventReminders, bool $sendEventRemindersMode, bool $expectCall): void {
{ $this->config->expects($this->at(0))
$this->config->expects($this->once())->method('getAppValue')->with('dav', 'sendEventReminders', 'yes')->willReturn($sendEventReminders ? 'yes' : 'no'); ->method('getAppValue')
$this->reminderService->expects($this->exactly($sendEventReminders ? 1 : 0))->method('processReminders'); ->with('dav', 'sendEventReminders', 'yes')
->willReturn($sendEventReminders ? 'yes' : 'no');
if ($sendEventReminders) {
$this->config->expects($this->at(1))
->method('getAppValue')
->with('dav', 'sendEventRemindersMode', 'backgroundjob')
->willReturn($sendEventRemindersMode ? 'backgroundjob' : 'cron');
}
if ($expectCall) {
$this->reminderService->expects($this->once())
->method('processReminders');
} else {
$this->reminderService->expects($this->never())
->method('processReminders');
}
$this->backgroundJob->run([]); $this->backgroundJob->run([]);
} }

View File

@ -1,8 +1,11 @@
<?php <?php
declare(strict_types=1);
/** /**
* @copyright Copyright (c) 2018, Thomas Citharel * @copyright Copyright (c) 2019, Thomas Citharel
* @copyright Copyright (c) 2019, Georg Ehrke
* *
* @author Thomas Citharel <tcit@tcit.fr> * @author Thomas Citharel <tcit@tcit.fr>
* @author Georg Ehrke <oc.list@georgehrke.com>
* *
* @license AGPL-3.0 * @license AGPL-3.0
* *
@ -21,7 +24,6 @@
*/ */
namespace OCA\DAV\Tests\unit\CalDAV\Reminder; namespace OCA\DAV\Tests\unit\CalDAV\Reminder;
use OCP\IDBConnection;
use OCP\DB\QueryBuilder\IQueryBuilder; use OCP\DB\QueryBuilder\IQueryBuilder;
use OCP\AppFramework\Utility\ITimeFactory; use OCP\AppFramework\Utility\ITimeFactory;
use OCA\DAV\CalDAV\Reminder\Backend as ReminderBackend; use OCA\DAV\CalDAV\Reminder\Backend as ReminderBackend;
@ -29,285 +31,367 @@ use Test\TestCase;
class BackendTest extends TestCase { class BackendTest extends TestCase {
/** /**
* Reminder Backend * Reminder Backend
* *
* @var ReminderBackend|\PHPUnit\Framework\MockObject\MockObject * @var ReminderBackend|\PHPUnit\Framework\MockObject\MockObject
*/ */
private $reminderBackend; private $reminderBackend;
/** @var IDBConnection|\PHPUnit\Framework\MockObject\MockObject */
private $dbConnection;
/** @var ITimeFactory|\PHPUnit\Framework\MockObject\MockObject */ /** @var ITimeFactory|\PHPUnit\Framework\MockObject\MockObject */
private $timeFactory; private $timeFactory;
public function setUp() { public function setUp() {
parent::setUp(); parent::setUp();
$this->dbConnection = $this->createMock(IDBConnection::class); $query = self::$realDatabase->getQueryBuilder();
$query->delete('calendar_reminders')->execute();
$query->delete('calendarobjects')->execute();
$query->delete('calendars')->execute();
$this->timeFactory = $this->createMock(ITimeFactory::class); $this->timeFactory = $this->createMock(ITimeFactory::class);
$this->reminderBackend = new ReminderBackend($this->dbConnection, $this->timeFactory); $this->reminderBackend = new ReminderBackend(self::$realDatabase, $this->timeFactory);
}
public function testCleanRemindersForEvent(): void $this->createRemindersTestSet();
{
/** @var IQueryBuilder|\PHPUnit\Framework\MockObject\MockObject $queryBuilder */
$queryBuilder = $this->createMock(IQueryBuilder::class);
$stmt = $this->createMock(\Doctrine\DBAL\Driver\Statement::class);
$expr = $this->createMock(\OCP\DB\QueryBuilder\IExpressionBuilder::class);
$this->dbConnection->expects($this->once())
->method('getQueryBuilder')
->with()
->will($this->returnValue($queryBuilder));
$queryBuilder->method('expr')
->will($this->returnValue($expr));
$expr->method('eq')
->will($this->returnValueMap([
['calendarid', 'createNamedParameter-1', null, 'WHERE_CLAUSE_1'],
['objecturi', 'createNamedParameter-2', null, 'WHERE_CLAUSE_2'],
]));
$queryBuilder->method('createNamedParameter')
->will($this->returnValueMap([
[1, \PDO::PARAM_STR, null, 'createNamedParameter-1'],
['object.ics', \PDO::PARAM_STR, null, 'createNamedParameter-2'],
]));
$queryBuilder->expects($this->at(0))
->method('delete')
->with('calendar_reminders')
->willReturn($queryBuilder);
$queryBuilder->expects($this->at(3))
->method('where')
->with('WHERE_CLAUSE_1')
->will($this->returnValue($queryBuilder));
$queryBuilder->expects($this->at(6))
->method('andWhere')
->with('WHERE_CLAUSE_2')
->will($this->returnValue($queryBuilder));
$queryBuilder->expects($this->at(7))
->method('execute')
->with()
->willReturn($stmt);
$this->reminderBackend->cleanRemindersForEvent(1, 'object.ics');
} }
public function testCleanRemindersForCalendar(): void protected function tearDown() {
{ $query = self::$realDatabase->getQueryBuilder();
/** @var IQueryBuilder|\PHPUnit\Framework\MockObject\MockObject $queryBuilder */ $query->delete('calendar_reminders')->execute();
$queryBuilder = $this->createMock(IQueryBuilder::class); $query->delete('calendarobjects')->execute();
$stmt = $this->createMock(\Doctrine\DBAL\Driver\Statement::class); $query->delete('calendars')->execute();
$expr = $this->createMock(\OCP\DB\QueryBuilder\IExpressionBuilder::class);
$this->dbConnection->expects($this->once())
->method('getQueryBuilder')
->with()
->will($this->returnValue($queryBuilder));
$queryBuilder->method('expr')
->will($this->returnValue($expr));
$expr->method('eq')
->will($this->returnValueMap([
['calendarid', 'createNamedParameter-1', null, 'WHERE_CLAUSE_1'],
]));
$queryBuilder->method('createNamedParameter')
->will($this->returnValueMap([
[1337, \PDO::PARAM_STR, null, 'createNamedParameter-1'],
]));
$queryBuilder->expects($this->at(0))
->method('delete')
->with('calendar_reminders')
->willReturn($queryBuilder);
$queryBuilder->expects($this->at(3))
->method('where')
->with('WHERE_CLAUSE_1')
->will($this->returnValue($queryBuilder));
$queryBuilder->expects($this->at(4))
->method('execute')
->with()
->willReturn($stmt);
$this->reminderBackend->cleanRemindersForCalendar(1337);
} }
public function testRemoveReminder(): void
{
/** @var IQueryBuilder|\PHPUnit\Framework\MockObject\MockObject $queryBuilder */
$queryBuilder = $this->createMock(IQueryBuilder::class);
$stmt = $this->createMock(\Doctrine\DBAL\Driver\Statement::class);
$expr = $this->createMock(\OCP\DB\QueryBuilder\IExpressionBuilder::class);
$this->dbConnection->expects($this->once()) public function testCleanRemindersForEvent(): void {
->method('getQueryBuilder') $query = self::$realDatabase->getQueryBuilder();
->with() $rows = $query->select('*')
->will($this->returnValue($queryBuilder)); ->from('calendar_reminders')
$queryBuilder->method('expr') ->execute()
->will($this->returnValue($expr)); ->fetchAll();
$expr->method('eq') $this->assertCount(4, $rows);
->will($this->returnValueMap([
['id', 'createNamedParameter-1', null, 'WHERE_CLAUSE_1'],
]));
$queryBuilder->method('createNamedParameter')
->will($this->returnValueMap([
[16, \PDO::PARAM_STR, null, 'createNamedParameter-1'],
]));
$queryBuilder->expects($this->at(0)) $this->reminderBackend->cleanRemindersForEvent(1);
->method('delete')
->with('calendar_reminders')
->willReturn($queryBuilder);
$queryBuilder->expects($this->at(3))
->method('where')
->with('WHERE_CLAUSE_1')
->will($this->returnValue($queryBuilder));
$queryBuilder->expects($this->at(4))
->method('execute')
->with()
->willReturn($stmt);
$this->reminderBackend->removeReminder(16); $query = self::$realDatabase->getQueryBuilder();
$rows = $query->select('*')
->from('calendar_reminders')
->execute()
->fetchAll();
$this->assertCount(2, $rows);
} }
public function testGetRemindersToProcess(): void public function testCleanRemindersForCalendar(): void {
{ $query = self::$realDatabase->getQueryBuilder();
$dbData = [[ $rows = $query->select('*')
'cr.id' => 30, ->from('calendar_reminders')
'cr.calendarid' => 3, ->execute()
'cr.objecturi' => 'object.ics', ->fetchAll();
'cr.type' => 'EMAIL',
'cr.notificationdate' => 1337,
'cr.uid' => 'user1',
'co.calendardata' => 'BEGIN:VCALENDAR',
'c.displayname' => 'My Calendar'
]];
$this->timeFactory->expects($this->exactly(2)) $this->assertCount(4, $rows);
$this->reminderBackend->cleanRemindersForCalendar(1);
$query = self::$realDatabase->getQueryBuilder();
$rows = $query->select('*')
->from('calendar_reminders')
->execute()
->fetchAll();
$this->assertCount(1, $rows);
}
public function testRemoveReminder(): void {
$query = self::$realDatabase->getQueryBuilder();
$rows = $query->select('*')
->from('calendar_reminders')
->execute()
->fetchAll();
$this->assertCount(4, $rows);
$this->reminderBackend->removeReminder((int) $rows[3]['id']);
$query = self::$realDatabase->getQueryBuilder();
$rows = $query->select('*')
->from('calendar_reminders')
->execute()
->fetchAll();
$this->assertCount(3, $rows);
}
public function testGetRemindersToProcess(): void {
$this->timeFactory->expects($this->exactly(1))
->method('getTime') ->method('getTime')
->with() ->with()
->willReturn(1337); ->willReturn(123457);
/** @var IQueryBuilder|\PHPUnit\Framework\MockObject\MockObject $queryBuilder */ $rows = $this->reminderBackend->getRemindersToProcess();
$queryBuilder = $this->createMock(IQueryBuilder::class);
$stmt = $this->createMock(\Doctrine\DBAL\Driver\Statement::class);
$expr = $this->createMock(\OCP\DB\QueryBuilder\IExpressionBuilder::class);
$this->dbConnection->expects($this->once()) $this->assertCount(2, $rows);
->method('getQueryBuilder') unset($rows[0]['id']);
->with() unset($rows[1]['id']);
->willReturn($queryBuilder);
$queryBuilder->method('expr')
->willReturn($expr);
$expr->method('eq') $this->assertEquals($rows[0], [
->willReturnMap([ 'calendar_id' => 1,
['cr.calendarid', 'c.id', null, 'EQ_CLAUSE_1'], 'object_id' => 1,
['co.uri', 'cr.objecturi', null, 'EQ_CLAUSE_2'], 'uid' => 'asd',
]); 'is_recurring' => false,
$expr->method('andX') 'recurrence_id' => 123458,
->willReturnMap([ 'is_recurrence_exception' => false,
['EQ_CLAUSE_1', 'EQ_CLAUSE_2', 'ANDX_CLAUSE'], 'event_hash' => 'asd123',
]); 'alarm_hash' => 'asd567',
'type' => 'EMAIL',
$expr->method('lte') 'is_relative' => true,
->with('cr.notificationdate', 'createNamedParameter-1', null) 'notification_date' => 123456,
->willReturn('LTE_CLAUSE_1'); 'is_repeat_based' => false,
'calendardata' => 'Calendar data 123',
$expr->method('gte') 'displayname' => 'Displayname 123',
->with('cr.eventstartdate', 'createNamedParameter-1', null) 'principaluri' => 'principals/users/user001',
->willReturn('GTE_CLAUSE_2'); ]);
$this->assertEquals($rows[1], [
$queryBuilder->method('createNamedParameter') 'calendar_id' => 1,
->willReturnMap([ 'object_id' => 1,
[1337, \PDO::PARAM_STR, null, 'createNamedParameter-1'], 'uid' => 'asd',
]); 'is_recurring' => false,
'recurrence_id' => 123458,
$queryBuilder->expects($this->at(0)) 'is_recurrence_exception' => false,
->method('select') 'event_hash' => 'asd123',
->with(['cr.id', 'cr.calendarid', 'cr.objecturi', 'cr.type', 'cr.notificationdate', 'cr.uid', 'co.calendardata', 'c.displayname']) 'alarm_hash' => 'asd567',
->willReturn($queryBuilder); 'type' => 'AUDIO',
$queryBuilder->expects($this->at(1)) 'is_relative' => true,
->method('from') 'notification_date' => 123456,
->with('calendar_reminders', 'cr') 'is_repeat_based' => false,
->willReturn($queryBuilder); 'calendardata' => 'Calendar data 123',
$queryBuilder->expects($this->at(4)) 'displayname' => 'Displayname 123',
->method('where') 'principaluri' => 'principals/users/user001',
->with('LTE_CLAUSE_1') ]);
->willReturn($queryBuilder);
$queryBuilder->expects($this->at(7))
->method('andWhere')
->with('GTE_CLAUSE_2')
->willReturn($queryBuilder);
$queryBuilder->expects($this->at(9))
->method('leftJoin')
->with('cr', 'calendars', 'c', 'EQ_CLAUSE_1')
->willReturn($queryBuilder);
$queryBuilder->expects($this->at(13))
->method('leftJoin')
->with('cr', 'calendarobjects', 'co', 'ANDX_CLAUSE')
->willReturn($queryBuilder);
$queryBuilder->expects($this->at(14))
->method('execute')
->with()
->willReturn($stmt);
$stmt->expects($this->once())
->method('fetchAll')
->with()
->willReturn($dbData);
$actual = $this->reminderBackend->getRemindersToProcess();
$this->assertEquals($dbData, $actual);
} }
public function testInsertReminder(): void public function testGetAllScheduledRemindersForEvent(): void {
{ $rows = $this->reminderBackend->getAllScheduledRemindersForEvent(1);
/** @var IQueryBuilder|\PHPUnit\Framework\MockObject\MockObject $queryBuilder */
$queryBuilder = $this->createMock(IQueryBuilder::class);
$stmt = $this->createMock(\Doctrine\DBAL\Driver\Statement::class);
$expr = $this->createMock(\OCP\DB\QueryBuilder\IExpressionBuilder::class);
$this->dbConnection->expects($this->once()) $this->assertCount(2, $rows);
->method('getQueryBuilder') unset($rows[0]['id']);
->with() unset($rows[1]['id']);
->will($this->returnValue($queryBuilder));
$queryBuilder->method('expr')
->will($this->returnValue($expr));
$queryBuilder->method('createNamedParameter') $this->assertEquals($rows[0], [
->will($this->returnValueMap([ 'calendar_id' => 1,
['user1', \PDO::PARAM_STR, null, 'createNamedParameter-1'], 'object_id' => 1,
['1', \PDO::PARAM_STR, null, 'createNamedParameter-2'], 'uid' => 'asd',
['object.ics', \PDO::PARAM_STR, null, 'createNamedParameter-3'], 'is_recurring' => false,
['EMAIL', \PDO::PARAM_STR, null, 'createNamedParameter-4'], 'recurrence_id' => 123458,
[1227, \PDO::PARAM_STR, null, 'createNamedParameter-5'], 'is_recurrence_exception' => false,
[1337, \PDO::PARAM_STR, null, 'createNamedParameter-6'], 'event_hash' => 'asd123',
])); 'alarm_hash' => 'asd567',
'type' => 'EMAIL',
'is_relative' => true,
'notification_date' => 123456,
'is_repeat_based' => false,
]);
$this->assertEquals($rows[1], [
'calendar_id' => 1,
'object_id' => 1,
'uid' => 'asd',
'is_recurring' => false,
'recurrence_id' => 123458,
'is_recurrence_exception' => false,
'event_hash' => 'asd123',
'alarm_hash' => 'asd567',
'type' => 'AUDIO',
'is_relative' => true,
'notification_date' => 123456,
'is_repeat_based' => false,
]);
}
$queryBuilder->expects($this->at(0)) public function testInsertReminder(): void {
->method('insert') $query = self::$realDatabase->getQueryBuilder();
->with('calendar_reminders') $rows = $query->select('*')
->willReturn($queryBuilder); ->from('calendar_reminders')
$queryBuilder->expects($this->at(7)) ->execute()
->method('values') ->fetchAll();
->with([
'uid' => 'createNamedParameter-1', $this->assertCount(4, $rows);
'calendarid' => 'createNamedParameter-2',
'objecturi' => 'createNamedParameter-3', $this->reminderBackend->insertReminder(42, 1337, 'uid99', true, 12345678,
'type' => 'createNamedParameter-4', true, 'hash99', 'hash42', 'AUDIO', false, 12345670, false);
'notificationdate' => 'createNamedParameter-5',
'eventstartdate' => 'createNamedParameter-6', $query = self::$realDatabase->getQueryBuilder();
$rows = $query->select('*')
->from('calendar_reminders')
->execute()
->fetchAll();
$this->assertCount(5, $rows);
unset($rows[4]['id']);
$this->assertEquals($rows[4], [
'calendar_id' => '42',
'object_id' => '1337',
'is_recurring' => '1',
'uid' => 'uid99',
'recurrence_id' => '12345678',
'is_recurrence_exception' => '1',
'event_hash' => 'hash99',
'alarm_hash' => 'hash42',
'type' => 'AUDIO',
'is_relative' => '0',
'notification_date' => '12345670',
'is_repeat_based' => '0',
]);
}
public function testUpdateReminder() {
$query = self::$realDatabase->getQueryBuilder();
$rows = $query->select('*')
->from('calendar_reminders')
->execute()
->fetchAll();
$this->assertCount(4, $rows);
$this->assertEquals($rows[3]['notification_date'], 123600);
$reminderId = (int) $rows[3]['id'];
$newNotificationDate = 123700;
$this->reminderBackend->updateReminder($reminderId, $newNotificationDate);
$query = self::$realDatabase->getQueryBuilder();
$row = $query->select('notification_date')
->from('calendar_reminders')
->where($query->expr()->eq('id', $query->createNamedParameter($reminderId)))
->execute()
->fetch();
$this->assertEquals((int) $row['notification_date'], 123700);
}
private function createRemindersTestSet(): void {
$query = self::$realDatabase->getQueryBuilder();
$query->insert('calendars')
->values([
'id' => $query->createNamedParameter(1),
'principaluri' => $query->createNamedParameter('principals/users/user001'),
'displayname' => $query->createNamedParameter('Displayname 123'),
]) ])
->willReturn($queryBuilder); ->execute();
$queryBuilder->expects($this->at(8))
->method('execute')
->with()
->willReturn($stmt);
$actual = $this->reminderBackend->insertReminder('user1', '1', 'object.ics', 'EMAIL', 1227, 1337); $query = self::$realDatabase->getQueryBuilder();
} $query->insert('calendars')
->values([
'id' => $query->createNamedParameter(99),
'principaluri' => $query->createNamedParameter('principals/users/user002'),
'displayname' => $query->createNamedParameter('Displayname 99'),
])
->execute();
$query = self::$realDatabase->getQueryBuilder();
$query->insert('calendarobjects')
->values([
'id' => $query->createNamedParameter(1),
'calendardata' => $query->createNamedParameter('Calendar data 123'),
'calendarid' => $query->createNamedParameter(1),
'size' => $query->createNamedParameter(42),
])
->execute();
$query = self::$realDatabase->getQueryBuilder();
$query->insert('calendarobjects')
->values([
'id' => $query->createNamedParameter(2),
'calendardata' => $query->createNamedParameter('Calendar data 456'),
'calendarid' => $query->createNamedParameter(1),
'size' => $query->createNamedParameter(42),
])
->execute();
$query = self::$realDatabase->getQueryBuilder();
$query->insert('calendarobjects')
->values([
'id' => $query->createNamedParameter(10),
'calendardata' => $query->createNamedParameter('Calendar data 789'),
'calendarid' => $query->createNamedParameter(99),
'size' => $query->createNamedParameter(42),
])
->execute();
$query = self::$realDatabase->getQueryBuilder();
$query->insert('calendar_reminders')
->values([
'calendar_id' => $query->createNamedParameter(1),
'object_id' => $query->createNamedParameter(1),
'uid' => $query->createNamedParameter('asd'),
'is_recurring' => $query->createNamedParameter(0),
'recurrence_id' => $query->createNamedParameter(123458),
'is_recurrence_exception' => $query->createNamedParameter(0),
'event_hash' => $query->createNamedParameter('asd123'),
'alarm_hash' => $query->createNamedParameter('asd567'),
'type' => $query->createNamedParameter('EMAIL'),
'is_relative' => $query->createNamedParameter(1),
'notification_date' => $query->createNamedParameter(123456),
'is_repeat_based' => $query->createNamedParameter(0),
])
->execute();
$query = self::$realDatabase->getQueryBuilder();
$query->insert('calendar_reminders')
->values([
'calendar_id' => $query->createNamedParameter(1),
'object_id' => $query->createNamedParameter(1),
'uid' => $query->createNamedParameter('asd'),
'is_recurring' => $query->createNamedParameter(0),
'recurrence_id' => $query->createNamedParameter(123458),
'is_recurrence_exception' => $query->createNamedParameter(0),
'event_hash' => $query->createNamedParameter('asd123'),
'alarm_hash' => $query->createNamedParameter('asd567'),
'type' => $query->createNamedParameter('AUDIO'),
'is_relative' => $query->createNamedParameter(1),
'notification_date' => $query->createNamedParameter(123456),
'is_repeat_based' => $query->createNamedParameter(0),
])
->execute();
$query = self::$realDatabase->getQueryBuilder();
$query->insert('calendar_reminders')
->values([
'calendar_id' => $query->createNamedParameter(1),
'object_id' => $query->createNamedParameter(2),
'uid' => $query->createNamedParameter('asd'),
'is_recurring' => $query->createNamedParameter(0),
'recurrence_id' => $query->createNamedParameter(123900),
'is_recurrence_exception' => $query->createNamedParameter(0),
'event_hash' => $query->createNamedParameter('asd123'),
'alarm_hash' => $query->createNamedParameter('asd567'),
'type' => $query->createNamedParameter('EMAIL'),
'is_relative' => $query->createNamedParameter(1),
'notification_date' => $query->createNamedParameter(123499),
'is_repeat_based' => $query->createNamedParameter(0),
])
->execute();
$query = self::$realDatabase->getQueryBuilder();
$query->insert('calendar_reminders')
->values([
'calendar_id' => $query->createNamedParameter(99),
'object_id' => $query->createNamedParameter(10),
'uid' => $query->createNamedParameter('asd'),
'is_recurring' => $query->createNamedParameter(0),
'recurrence_id' => $query->createNamedParameter(123900),
'is_recurrence_exception' => $query->createNamedParameter(0),
'event_hash' => $query->createNamedParameter('asd123'),
'alarm_hash' => $query->createNamedParameter('asd567'),
'type' => $query->createNamedParameter('DISPLAY'),
'is_relative' => $query->createNamedParameter(1),
'notification_date' => $query->createNamedParameter(123600),
'is_repeat_based' => $query->createNamedParameter(0),
])
->execute();
}
} }

View File

@ -1,4 +1,5 @@
<?php <?php
declare(strict_types=1);
/** /**
* @copyright Copyright (c) 2019, Thomas Citharel * @copyright Copyright (c) 2019, Thomas Citharel
* *
@ -19,9 +20,9 @@
* along with this program. If not, see <http://www.gnu.org/licenses/> * along with this program. If not, see <http://www.gnu.org/licenses/>
* *
*/ */
namespace OCA\DAV\Tests\unit\CalDAV\Reminder; namespace OCA\DAV\Tests\unit\CalDAV\Reminder\NotificationProvider;
use OCA\DAV\CalDAV\Reminder\AbstractNotificationProvider; use OCA\DAV\CalDAV\Reminder\NotificationProvider\AbstractProvider;
use OCP\IConfig; use OCP\IConfig;
use OCP\IL10N; use OCP\IL10N;
use OCP\ILogger; use OCP\ILogger;
@ -33,23 +34,23 @@ use Sabre\VObject\Component\VCalendar;
abstract class AbstractNotificationProviderTest extends TestCase { abstract class AbstractNotificationProviderTest extends TestCase {
/** @var ILogger|\PHPUnit\Framework\MockObject\MockObject */ /** @var ILogger|\PHPUnit\Framework\MockObject\MockObject */
protected $logger; protected $logger;
/** @var L10NFactory|\PHPUnit\Framework\MockObject\MockObject */ /** @var L10NFactory|\PHPUnit\Framework\MockObject\MockObject */
protected $l10nFactory; protected $l10nFactory;
/** @var IL10N|\PHPUnit\Framework\MockObject\MockObject */ /** @var IL10N|\PHPUnit\Framework\MockObject\MockObject */
protected $l10n; protected $l10n;
/** @var IURLGenerator|\PHPUnit\Framework\MockObject\MockObject */ /** @var IURLGenerator|\PHPUnit\Framework\MockObject\MockObject */
protected $urlGenerator; protected $urlGenerator;
/** @var IConfig|\PHPUnit\Framework\MockObject\MockObject */ /** @var IConfig|\PHPUnit\Framework\MockObject\MockObject */
protected $config; protected $config;
/** @var AbstractNotificationProvider|\PHPUnit\Framework\MockObject\MockObject */ /** @var AbstractProvider|\PHPUnit\Framework\MockObject\MockObject */
protected $provider; protected $provider;
/** /**
* @var VCalendar * @var VCalendar
@ -69,19 +70,20 @@ abstract class AbstractNotificationProviderTest extends TestCase {
public function setUp() { public function setUp() {
parent::setUp(); parent::setUp();
$this->logger = $this->createMock(ILogger::class); $this->logger = $this->createMock(ILogger::class);
$this->l10nFactory = $this->createMock(L10NFactory::class); $this->l10nFactory = $this->createMock(L10NFactory::class);
$this->l10n = $this->createMock(IL10N::class); $this->l10n = $this->createMock(IL10N::class);
$this->urlGenerator = $this->createMock(IURLGenerator::class); $this->urlGenerator = $this->createMock(IURLGenerator::class);
$this->config = $this->createMock(IConfig::class); $this->config = $this->createMock(IConfig::class);
$this->vcalendar = new VCalendar(); $this->vcalendar = new VCalendar();
$this->vcalendar->add('VEVENT', [ $this->vcalendar->add('VEVENT', [
'SUMMARY' => 'Fellowship meeting', 'SUMMARY' => 'Fellowship meeting',
'DTSTART' => new \DateTime('2017-01-01 00:00:00') // 1483228800 'DTSTART' => new \DateTime('2017-01-01 00:00:00+00:00'), // 1483228800,
]); 'UID' => 'uid1234',
]);
$this->calendarDisplayName = 'Personal'; $this->calendarDisplayName = 'Personal';
$this->user = $this->createMock(IUser::class); $this->user = $this->createMock(IUser::class);
} }
} }

View File

@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2019, Georg Ehrke
*
* @author Georg Ehrke <oc.list@georgehrke.com>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OCA\DAV\Tests\unit\CalDAV\Reminder\NotificationProvider;
use OCA\DAV\CalDAV\Reminder\NotificationProvider\AudioProvider;
class AudioProviderTest extends PushProviderTest {
public function testNotificationType():void {
$this->assertEquals(AudioProvider::NOTIFICATION_TYPE, 'AUDIO');
}
}

View File

@ -1,8 +1,11 @@
<?php <?php
declare(strict_types=1);
/** /**
* @copyright Copyright (c) 2019, Thomas Citharel * @copyright Copyright (c) 2019, Thomas Citharel
* @copyright Copyright (c) 2019, Georg Ehrke
* *
* @author Thomas Citharel <tcit@tcit.fr> * @author Thomas Citharel <tcit@tcit.fr>
* @author Georg Ehrke <oc.list@georgehrke.com>
* *
* @license AGPL-3.0 * @license AGPL-3.0
* *
@ -22,7 +25,6 @@
namespace OCA\DAV\Tests\unit\CalDAV\Reminder\NotificationProvider; namespace OCA\DAV\Tests\unit\CalDAV\Reminder\NotificationProvider;
use OCA\DAV\CalDAV\Reminder\NotificationProvider\EmailProvider; use OCA\DAV\CalDAV\Reminder\NotificationProvider\EmailProvider;
use OCA\DAV\CalDAV\Reminder\AbstractNotificationProvider;
use OCP\IConfig; use OCP\IConfig;
use OCP\IL10N; use OCP\IL10N;
use OCP\ILogger; use OCP\ILogger;
@ -33,194 +35,512 @@ use OCP\Mail\IEMailTemplate;
use OCP\Mail\IMailer; use OCP\Mail\IMailer;
use OCP\Mail\IAttachment; use OCP\Mail\IAttachment;
use OCP\Mail\IMessage; use OCP\Mail\IMessage;
use Sabre\VObject\Component\VCalendar;
use Test\TestCase; use Test\TestCase;
use OCA\DAV\Tests\unit\CalDAV\Reminder\AbstractNotificationProviderTest;
class EmailProviderTest extends AbstractNotificationProviderTest { class EmailProviderTest extends AbstractNotificationProviderTest {
const USER_EMAIL = 'frodo@hobb.it'; const USER_EMAIL = 'frodo@hobb.it';
/** @var ILogger|\PHPUnit\Framework\MockObject\MockObject */ /** @var ILogger|\PHPUnit\Framework\MockObject\MockObject */
protected $logger; protected $logger;
/** @var L10NFactory|\PHPUnit\Framework\MockObject\MockObject */ /** @var L10NFactory|\PHPUnit\Framework\MockObject\MockObject */
protected $l10nFactory; protected $l10nFactory;
/** @var IL10N|\PHPUnit\Framework\MockObject\MockObject */ /** @var IL10N|\PHPUnit\Framework\MockObject\MockObject */
protected $l10n; protected $l10n;
/** @var IURLGenerator|\PHPUnit\Framework\MockObject\MockObject */ /** @var IURLGenerator|\PHPUnit\Framework\MockObject\MockObject */
protected $urlGenerator; protected $urlGenerator;
/** @var IConfig|\PHPUnit\Framework\MockObject\MockObject */ /** @var IConfig|\PHPUnit\Framework\MockObject\MockObject */
protected $config; protected $config;
/** @var IMailer|\PHPUnit\Framework\MockObject\MockObject */ /** @var IMailer|\PHPUnit\Framework\MockObject\MockObject */
private $mailer; private $mailer;
public function setUp() { public function setUp() {
parent::setUp(); parent::setUp();
$this->mailer = $this->createMock(IMailer::class); $this->mailer = $this->createMock(IMailer::class);
$this->provider = new EmailProvider( $this->provider = new EmailProvider(
$this->config, $this->config,
$this->mailer, $this->mailer,
$this->logger, $this->logger,
$this->l10nFactory, $this->l10nFactory,
$this->urlGenerator $this->urlGenerator
); );
} }
public function testSendWithNoUserEmail(): void public function testSendWithoutAttendees():void {
{ $user1 = $this->createMock(IUser::class);
$this->user->expects($this->once()) $user1->method('getUID')
->method('getEMailAddress') ->willReturn('uid1');
->with() $user1->method('getEMailAddress')
->willReturn(null); ->willReturn('uid1@example.com');
$user2 = $this->createMock(IUser::class);
$user2->method('getUID')
->willReturn('uid2');
$user2->method('getEMailAddress')
->willReturn('uid2@example.com');
$user3 = $this->createMock(IUser::class);
$user3->method('getUID')
->willReturn('uid3');
$user3->method('getEMailAddress')
->willReturn('uid3@example.com');
$user4 = $this->createMock(IUser::class);
$user4->method('getUID')
->willReturn('uid4');
$user4->method('getEMailAddress')
->willReturn(null);
$this->mailer $users = [$user1, $user2, $user3, $user4];
->expects($this->never())
->method('send');
$this->provider->send($this->vcalendar, $this->calendarDisplayName, $this->user); $this->config->expects($this->at(0))
} ->method('getUserValue')
->with('uid1', 'core', 'lang', null)
->willReturn(null);
$this->config->expects($this->at(1))
->method('getUserValue')
->with('uid2', 'core', 'lang', null)
->willReturn('de');
$this->config->expects($this->at(2))
->method('getUserValue')
->with('uid3', 'core', 'lang', null)
->willReturn('de');
public function testSendWithFailedRecipients(): void $enL10N = $this->createMock(IL10N::class);
{ $enL10N->method('t')
$this->user->expects($this->exactly(2)) ->will($this->returnArgument(0));
->method('getEMailAddress') $enL10N->method('l')
->with() ->will($this->returnArgument(0));
->willReturn(self::USER_EMAIL);
$this->mailer $deL10N = $this->createMock(IL10N::class);
->expects($this->once()) $deL10N->method('t')
->method('send') ->will($this->returnArgument(0));
->willReturn([self::USER_EMAIL]) $deL10N->method('l')
; ->will($this->returnArgument(0));
$this->logger $this->l10nFactory->expects($this->at(0))
->expects($this->once()) ->method('findLanguage')
->method('error'); ->with()
->willReturn('en');
$l10n = $this->createMock(IL10N::class); $this->l10nFactory->expects($this->at(1))
$this->l10nFactory ->method('languageExists')
->method('get') ->with('dav', 'en')
->willReturn($l10n); ->willReturn(true);
$this->provider->send($this->vcalendar, $this->calendarDisplayName, $this->user); $this->l10nFactory->expects($this->at(2))
} ->method('get')
->with('dav', 'en')
->willReturn($enL10N);
public function testSendWithMailerFailure(): void $this->l10nFactory->expects($this->at(3))
{ ->method('languageExists')
$this->user->expects($this->exactly(2)) ->with('dav', 'de')
->method('getEMailAddress') ->willReturn(true);
->with()
->willReturn(self::USER_EMAIL);
$ex = new \Exception(); $this->l10nFactory->expects($this->at(4))
->method('get')
->with('dav', 'de')
->willReturn($deL10N);
$this->mailer $template1 = $this->getTemplateMock();
->expects($this->once()) $message11 = $this->getMessageMock('uid1@example.com', $template1);
->method('send') $template2 = $this->getTemplateMock();
->will($this->throwException($ex)) $message21 = $this->getMessageMock('uid2@example.com', $template2);
; $message22 = $this->getMessageMock('uid3@example.com', $template2);
$this->logger $this->mailer->expects($this->at(0))
->expects($this->once()) ->method('createEMailTemplate')
->method('logException') ->with('dav.calendarReminder')
->with($ex, ['app' => 'dav']); ->willReturn($template1);
$l10n = $this->createMock(IL10N::class); $this->mailer->expects($this->at(1))
$this->l10nFactory ->method('createMessage')
->method('get') ->with()
->willReturn($l10n); ->willReturn($message11);
$this->mailer->expects($this->at(2))
->method('send')
->with($message11)
->willReturn([]);
$this->provider->send($this->vcalendar, $this->calendarDisplayName, $this->user); $this->mailer->expects($this->at(3))
} ->method('createEMailTemplate')
->with('dav.calendarReminder')
->willReturn($template2);
public function testSend(): void $this->mailer->expects($this->at(4))
{ ->method('createMessage')
$this->user->expects($this->exactly(2)) ->with()
->method('getEMailAddress') ->willReturn($message21);
->with() $this->mailer->expects($this->at(5))
->willReturn(self::USER_EMAIL); ->method('send')
->with($message21)
->willReturn([]);
$this->mailer->expects($this->at(6))
->method('createMessage')
->with()
->willReturn($message22);
$this->mailer->expects($this->at(7))
->method('send')
->with($message22)
->willReturn([]);
$this->user->expects($this->once()) $this->setupURLGeneratorMock(2);
->method('getDisplayName')
->with()
->willReturn('Frodo');
$this->urlGenerator $vcalendar = $this->getNoAttendeeVCalendar();
->expects($this->exactly(2)) $this->provider->send($vcalendar->VEVENT, $this->calendarDisplayName, $users);
->method('getAbsoluteURL'); }
$this->urlGenerator public function testSendWithAttendees(): void {
->expects($this->exactly(2)) $user1 = $this->createMock(IUser::class);
->method('imagePath'); $user1->method('getUID')
->willReturn('uid1');
$user1->method('getEMailAddress')
->willReturn('uid1@example.com');
$user2 = $this->createMock(IUser::class);
$user2->method('getUID')
->willReturn('uid2');
$user2->method('getEMailAddress')
->willReturn('uid2@example.com');
$user3 = $this->createMock(IUser::class);
$user3->method('getUID')
->willReturn('uid3');
$user3->method('getEMailAddress')
->willReturn('uid3@example.com');
$user4 = $this->createMock(IUser::class);
$user4->method('getUID')
->willReturn('uid4');
$user4->method('getEMailAddress')
->willReturn(null);
$mailMessage = $this->createMock(IMessage::class); $users = [$user1, $user2, $user3, $user4];
$mailMessage->expects($this->once())
->method('setFrom')
->with([\OCP\Util::getDefaultEmailAddress('invitations-noreply') => 'Nextcloud'])
->willReturn($mailMessage);
$mailMessage->expects($this->once()) $this->config->expects($this->at(0))
->method('setTo') ->method('getUserValue')
->with([self::USER_EMAIL => 'Frodo']) ->with('uid1', 'core', 'lang', null)
->willReturn($mailMessage); ->willReturn(null);
$this->config->expects($this->at(1))
->method('getUserValue')
->with('uid2', 'core', 'lang', null)
->willReturn('de');
$this->config->expects($this->at(2))
->method('getUserValue')
->with('uid3', 'core', 'lang', null)
->willReturn('de');
$mailMessage $enL10N = $this->createMock(IL10N::class);
->expects($this->never()) $enL10N->method('t')
->method('setReplyTo') ->will($this->returnArgument(0));
->willReturn($mailMessage); $enL10N->method('l')
->will($this->returnArgument(0));
$emailTemplate = $this->createMock(IEMailTemplate::class); $deL10N = $this->createMock(IL10N::class);
$this->mailer $deL10N->method('t')
->expects($this->once()) ->will($this->returnArgument(0));
->method('createEMailTemplate') $deL10N->method('l')
->willReturn($emailTemplate); ->will($this->returnArgument(0));
$emailTemplate->expects($this->once()) $this->l10nFactory->expects($this->at(0))
->method('findLanguage')
->with()
->willReturn('en');
$this->l10nFactory->expects($this->at(1))
->method('languageExists')
->with('dav', 'de')
->willReturn(true);
$this->l10nFactory->expects($this->at(2))
->method('get')
->with('dav', 'de')
->willReturn($enL10N);
$this->l10nFactory->expects($this->at(3))
->method('languageExists')
->with('dav', 'en')
->willReturn(true);
$this->l10nFactory->expects($this->at(4))
->method('get')
->with('dav', 'en')
->willReturn($deL10N);
$template1 = $this->getTemplateMock();
$message11 = $this->getMessageMock('foo1@example.org', $template1);
$message12 = $this->getMessageMock('uid2@example.com', $template1);
$message13 = $this->getMessageMock('uid3@example.com', $template1);
$template2 = $this->getTemplateMock();
$message21 = $this->getMessageMock('foo3@example.org', $template2);
$message22 = $this->getMessageMock('foo4@example.org', $template2);
$message23 = $this->getMessageMock('uid1@example.com', $template2);
$this->mailer->expects($this->at(0))
->method('createEMailTemplate')
->with('dav.calendarReminder')
->willReturn($template1);
$this->mailer->expects($this->at(1))
->method('createMessage')
->with()
->willReturn($message11);
$this->mailer->expects($this->at(2))
->method('send')
->with($message11)
->willReturn([]);
$this->mailer->expects($this->at(3))
->method('createMessage')
->with()
->willReturn($message12);
$this->mailer->expects($this->at(4))
->method('send')
->with($message12)
->willReturn([]);
$this->mailer->expects($this->at(5))
->method('createMessage')
->with()
->willReturn($message13);
$this->mailer->expects($this->at(6))
->method('send')
->with($message13)
->willReturn([]);
$this->mailer->expects($this->at(7))
->method('createEMailTemplate')
->with('dav.calendarReminder')
->willReturn($template2);
$this->mailer->expects($this->at(8))
->method('createMessage')
->with()
->willReturn($message21);
$this->mailer->expects($this->at(9))
->method('send')
->with($message21)
->willReturn([]);
$this->mailer->expects($this->at(10))
->method('createMessage')
->with()
->willReturn($message22);
$this->mailer->expects($this->at(11))
->method('send')
->with($message22)
->willReturn([]);
$this->mailer->expects($this->at(12))
->method('createMessage')
->with()
->willReturn($message23);
$this->mailer->expects($this->at(13))
->method('send')
->with($message23)
->willReturn([]);
$this->setupURLGeneratorMock(2);
$vcalendar = $this->getAttendeeVCalendar();
$this->provider->send($vcalendar->VEVENT, $this->calendarDisplayName, $users);
}
/**
* @return IEMailTemplate
*/
private function getTemplateMock():IEMailTemplate {
$template = $this->createMock(IEMailTemplate::class);
$template->expects($this->at(0))
->method('addHeader')
->with()
->willReturn($template);
$template->expects($this->at(1))
->method('setSubject') ->method('setSubject')
->with('Notification: Fellowship meeting'); ->with()
->willReturn($template);
$emailTemplate->expects($this->once()) $template->expects($this->at(2))
->method('addHeader'); ->method('addHeading')
->with()
->willReturn($template);
$emailTemplate->expects($this->once()) $template->expects($this->at(3))
->method('addHeading'); ->method('addBodyListItem')
->with()
->willReturn($template);
$emailTemplate->expects($this->exactly(2)) $template->expects($this->at(4))
->method('addBodyListItem'); ->method('addBodyListItem')
->with()
->willReturn($template);
$emailTemplate->expects($this->once()) $template->expects($this->at(5))
->method('addFooter'); ->method('addBodyListItem')
->with()
->willReturn($template);
$mailMessage->expects($this->once()) $template->expects($this->at(6))
->method('useTemplate') ->method('addBodyListItem')
->with($emailTemplate); ->with()
->willReturn($template);
$this->mailer $template->expects($this->at(7))
->expects($this->once()) ->method('addFooter')
->method('createMessage') ->with()
->willReturn($mailMessage); ->willReturn($template);
$emailAttachment = $this->createMock(IAttachment::class); return $template;
$this->mailer }
->expects($this->once())
->method('createAttachment')
->willReturn($emailAttachment);
$this->mailer /**
->expects($this->once()) * @param array $toMail
->method('send'); * @param IEMailTemplate $templateMock
* @param array $replyTo
* @return IMessage
*/
private function getMessageMock(string $toMail, IEMailTemplate $templateMock, array $replyTo=null):IMessage {
$message = $this->createMock(IMessage::class);
$i = 0;
$l10n = $this->createMock(IL10N::class); $message->expects($this->at($i++))
$this->l10nFactory ->method('setFrom')
->method('get') ->with([\OCP\Util::getDefaultEmailAddress('reminders-noreply')])
->willReturn($l10n); ->willReturn($message);
$this->provider->send($this->vcalendar, $this->calendarDisplayName, $this->user); if ($replyTo) {
} $message->expects($this->at($i++))
->method('setReplyTo')
->with($replyTo)
->willReturn($message);
}
$message->expects($this->at($i++))
->method('setTo')
->with([$toMail])
->willReturn($message);
$message->expects($this->at($i++))
->method('useTemplate')
->with($templateMock)
->willReturn($message);
return $message;
}
private function getNoAttendeeVCalendar():VCalendar {
$vcalendar = new VCalendar();
$vcalendar->add('VEVENT', [
'SUMMARY' => 'Fellowship meeting',
'DTSTART' => new \DateTime('2017-01-01 00:00:00+00:00'), // 1483228800,
'UID' => 'uid1234',
'LOCATION' => 'Location 123',
'DESCRIPTION' => 'DESCRIPTION 456',
]);
return $vcalendar;
}
private function getAttendeeVCalendar():VCalendar {
$vcalendar = new VCalendar();
$vcalendar->add('VEVENT', [
'SUMMARY' => 'Fellowship meeting',
'DTSTART' => new \DateTime('2017-01-01 00:00:00+00:00'), // 1483228800,
'UID' => 'uid1234',
'LOCATION' => 'Location 123',
'DESCRIPTION' => 'DESCRIPTION 456',
]);
$vcalendar->VEVENT->add(
'ATTENDEE',
'mailto:foo1@example.org',
[
'LANG' => 'de',
'PARTSTAT' => 'NEEDS-ACTION',
]
);
$vcalendar->VEVENT->add(
'ATTENDEE',
'mailto:foo2@example.org',
[
'LANG' => 'de',
'PARTSTAT' => 'DECLINED',
]
);
$vcalendar->VEVENT->add(
'ATTENDEE',
'mailto:foo3@example.org',
[
'LANG' => 'en',
'PARTSTAT' => 'CONFIRMED',
]
);
$vcalendar->VEVENT->add(
'ATTENDEE',
'mailto:foo4@example.org'
);
$vcalendar->VEVENT->add(
'ATTENDEE',
'tomail:foo5@example.org'
);
return $vcalendar;
}
private function setupURLGeneratorMock(int $times=1):void {
for ($i = 0; $i < $times; $i++) {
$this->urlGenerator
->expects($this->at(8 * $i))
->method('imagePath')
->with('core', 'actions/info.svg')
->willReturn('imagePath1');
$this->urlGenerator
->expects($this->at(8 * $i + 1))
->method('getAbsoluteURL')
->with('imagePath1')
->willReturn('AbsURL1');
$this->urlGenerator
->expects($this->at(8 * $i + 2))
->method('imagePath')
->with('core', 'places/calendar.svg')
->willReturn('imagePath2');
$this->urlGenerator
->expects($this->at(8 * $i + 3))
->method('getAbsoluteURL')
->with('imagePath2')
->willReturn('AbsURL2');
$this->urlGenerator
->expects($this->at(8 * $i + 4))
->method('imagePath')
->with('core', 'actions/address.svg')
->willReturn('imagePath3');
$this->urlGenerator
->expects($this->at(8 * $i + 5))
->method('getAbsoluteURL')
->with('imagePath3')
->willReturn('AbsURL3');
$this->urlGenerator
->expects($this->at(8 * $i + 6))
->method('imagePath')
->with('core', 'actions/more.svg')
->willReturn('imagePath4');
$this->urlGenerator
->expects($this->at(8 * $i + 7))
->method('getAbsoluteURL')
->with('imagePath4')
->willReturn('AbsURL4');
}
}
} }

View File

@ -1,8 +1,11 @@
<?php <?php
declare(strict_types=1);
/** /**
* @copyright Copyright (c) 2019, Thomas Citharel * @copyright Copyright (c) 2019, Thomas Citharel
* @copyright Copyright (c) 2019, Georg Ehrke
* *
* @author Thomas Citharel <tcit@tcit.fr> * @author Thomas Citharel <tcit@tcit.fr>
* @author Georg Ehrke <oc.list@georgehrke.com>
* *
* @license AGPL-3.0 * @license AGPL-3.0
* *
@ -23,7 +26,6 @@ namespace OCA\DAV\Tests\unit\CalDAV\Reminder\NotificationProvider;
use OCA\DAV\AppInfo\Application; use OCA\DAV\AppInfo\Application;
use OCA\DAV\CalDAV\Reminder\NotificationProvider\PushProvider; use OCA\DAV\CalDAV\Reminder\NotificationProvider\PushProvider;
use OCA\DAV\CalDAV\Reminder\AbstractNotificationProvider;
use OCP\IConfig; use OCP\IConfig;
use OCP\IL10N; use OCP\IL10N;
use OCP\ILogger; use OCP\ILogger;
@ -34,7 +36,6 @@ use OCP\Notification\IManager;
use OCP\Notification\INotification; use OCP\Notification\INotification;
use OCP\AppFramework\Utility\ITimeFactory; use OCP\AppFramework\Utility\ITimeFactory;
use Test\TestCase; use Test\TestCase;
use OCA\DAV\Tests\unit\CalDAV\Reminder\AbstractNotificationProviderTest;
class PushProviderTest extends AbstractNotificationProviderTest { class PushProviderTest extends AbstractNotificationProviderTest {
@ -75,65 +76,111 @@ class PushProviderTest extends AbstractNotificationProviderTest {
); );
} }
public function testSend(): void public function testNotificationType():void {
{ $this->assertEquals(PushProvider::NOTIFICATION_TYPE, 'DISPLAY');
$notification = $this->createMock(INotification::class); }
$notification
->expects($this->once())
->method('setApp')
->with(Application::APP_ID)
->willReturn($notification);
$notification public function testSend(): void {
->expects($this->once()) $user1 = $this->createMock(IUser::class);
->method('setUser') $user1->method('getUID')
->willReturn($notification) ->willReturn('uid1');
; $user2 = $this->createMock(IUser::class);
$user2->method('getUID')
->willReturn('uid2');
$user3 = $this->createMock(IUser::class);
$user3->method('getUID')
->willReturn('uid3');
$notification $users = [$user1, $user2, $user3];
->expects($this->once())
->method('setDateTime')
->willReturn($notification)
;
$notification $dateTime = new \DateTime('@946684800');
->expects($this->once()) $this->timeFactory->method('getDateTime')
->method('setObject')
->willReturn($notification)
;
$notification
->expects($this->once())
->method('setSubject')
->willReturn($notification)
;
$notification
->expects($this->once())
->method('setMessage')
->willReturn($notification)
;
$this->manager
->expects($this->once())
->method('createNotification')
->willReturn($notification);
$this->manager
->expects($this->once())
->method('notify')
->with($notification);
$l10n = $this->createMock(IL10N::class);
$this->l10nFactory
->method('get')
->willReturn($l10n);
$this->timeFactory->expects($this->once())
->method('getDateTime')
->with() ->with()
->willReturn(new \DateTime()); ->willReturn($dateTime);
$this->provider->send($this->vcalendar, $this->calendarDisplayName, $this->user); $notification1 = $this->createNotificationMock('uid1', $dateTime);
$notification2 = $this->createNotificationMock('uid2', $dateTime);
$notification3 = $this->createNotificationMock('uid3', $dateTime);
$this->manager->expects($this->at(0))
->method('createNotification')
->with()
->willReturn($notification1);
$this->manager->expects($this->at(2))
->method('createNotification')
->with()
->willReturn($notification2);
$this->manager->expects($this->at(4))
->method('createNotification')
->with()
->willReturn($notification3);
$this->manager->expects($this->at(1))
->method('notify')
->with($notification1);
$this->manager->expects($this->at(3))
->method('notify')
->with($notification2);
$this->manager->expects($this->at(5))
->method('notify')
->with($notification3);
$this->provider->send($this->vcalendar->VEVENT, $this->calendarDisplayName, $users);
} }
/**
* @param string $uid
* @param \DateTime $dt
*/
private function createNotificationMock(string $uid, \DateTime $dt):INotification {
$notification = $this->createMock(INotification::class);
$notification
->expects($this->once())
->method('setApp')
->with('dav')
->willReturn($notification);
$notification->expects($this->once())
->method('setUser')
->with($uid)
->willReturn($notification);
$notification->expects($this->once())
->method('setDateTime')
->with($dt)
->willReturn($notification);
$notification->expects($this->once())
->method('setObject')
->with('dav', 'uid1234')
->willReturn($notification);
$notification->expects($this->once())
->method('setSubject')
->with('calendar_reminder', [
'title' => 'Fellowship meeting',
'start_atom' => '2017-01-01T00:00:00+00:00',
])
->willReturn($notification);
$notification
->expects($this->once())
->method('setMessage')
->with('calendar_reminder', [
'title' => 'Fellowship meeting',
'start_atom' => '2017-01-01T00:00:00+00:00',
'description' => null,
'location' => null,
'all_day' => false,
'start_is_floating' => false,
'start_timezone' => 'UTC',
'end_atom' => '2017-01-01T00:00:00+00:00',
'end_is_floating' => false,
'end_timezone' => 'UTC',
'calendar_displayname' => 'Personal',
])
->willReturn($notification);
return $notification;
}
} }

View File

@ -1,8 +1,11 @@
<?php <?php
declare(strict_types=1);
/** /**
* @copyright Copyright (c) 2019, Thomas Citharel * @copyright Copyright (c) 2019, Thomas Citharel
* @copyright Copyright (c) 2019, Georg Ehrke
* *
* @author Thomas Citharel <tcit@tcit.fr> * @author Thomas Citharel <tcit@tcit.fr>
* @author Georg Ehrke <oc.list@georgehrke.com>
* *
* @license AGPL-3.0 * @license AGPL-3.0
* *
@ -31,8 +34,8 @@ use Test\TestCase;
class NotificationProviderManagerTest extends TestCase { class NotificationProviderManagerTest extends TestCase {
/** @var NotificationProviderManager|\PHPUnit\Framework\MockObject\MockObject */ /** @var NotificationProviderManager|\PHPUnit\Framework\MockObject\MockObject */
private $providerManager; private $providerManager;
/** /**
* @throws \OCP\AppFramework\QueryException * @throws \OCP\AppFramework\QueryException
@ -40,9 +43,9 @@ class NotificationProviderManagerTest extends TestCase {
public function setUp() { public function setUp() {
parent::setUp(); parent::setUp();
$this->providerManager = new NotificationProviderManager(); $this->providerManager = new NotificationProviderManager();
$this->providerManager->registerProvider(EmailProvider::class); $this->providerManager->registerProvider(EmailProvider::class);
} }
/** /**
* @expectedException OCA\DAV\CalDAV\Reminder\NotificationTypeDoesNotExistException * @expectedException OCA\DAV\CalDAV\Reminder\NotificationTypeDoesNotExistException
@ -50,10 +53,9 @@ class NotificationProviderManagerTest extends TestCase {
* @throws ProviderNotAvailableException * @throws ProviderNotAvailableException
* @throws NotificationTypeDoesNotExistException * @throws NotificationTypeDoesNotExistException
*/ */
public function testGetProviderForUnknownType(): void public function testGetProviderForUnknownType(): void{
{ $this->providerManager->getProvider('NOT EXISTENT');
$this->providerManager->getProvider('NOT EXISTENT'); }
}
/** /**
* @expectedException OCA\DAV\CalDAV\Reminder\NotificationProvider\ProviderNotAvailableException * @expectedException OCA\DAV\CalDAV\Reminder\NotificationProvider\ProviderNotAvailableException
@ -61,28 +63,16 @@ class NotificationProviderManagerTest extends TestCase {
* @throws NotificationTypeDoesNotExistException * @throws NotificationTypeDoesNotExistException
* @throws ProviderNotAvailableException * @throws ProviderNotAvailableException
*/ */
public function testGetProviderForUnRegisteredType(): void public function testGetProviderForUnRegisteredType(): void{
{ $this->providerManager->getProvider('AUDIO');
$this->providerManager->getProvider('AUDIO'); }
}
/** public function testGetProvider(): void{
* @throws NotificationTypeDoesNotExistException $provider = $this->providerManager->getProvider('EMAIL');
* @throws ProviderNotAvailableException $this->assertInstanceOf(EmailProvider::class, $provider);
*/ }
public function testGetProvider(): void
{
$provider = $this->providerManager->getProvider('EMAIL');
$this->assertInstanceOf(EmailProvider::class, $provider);
}
/** public function testRegisterProvider(): void{
* @throws NotificationTypeDoesNotExistException
* @throws ProviderNotAvailableException
* @throws \OCP\AppFramework\QueryException
*/
public function testRegisterProvider(): void
{
$this->providerManager->registerProvider(PushProvider::class); $this->providerManager->registerProvider(PushProvider::class);
$provider = $this->providerManager->getProvider('DISPLAY'); $provider = $this->providerManager->getProvider('DISPLAY');
$this->assertInstanceOf(PushProvider::class, $provider); $this->assertInstanceOf(PushProvider::class, $provider);
@ -93,8 +83,12 @@ class NotificationProviderManagerTest extends TestCase {
* @expectedException \InvalidArgumentException * @expectedException \InvalidArgumentException
* @throws \OCP\AppFramework\QueryException * @throws \OCP\AppFramework\QueryException
*/ */
public function testRegisterBadProvider(): void public function testRegisterBadProvider(): void{
{
$this->providerManager->registerProvider(Capabilities::class); $this->providerManager->registerProvider(Capabilities::class);
} }
public function testHasProvider(): void {
$this->assertTrue($this->providerManager->hasProvider('EMAIL'));
$this->assertFalse($this->providerManager->hasProvider('EMAIL123'));
}
} }

View File

@ -1,8 +1,11 @@
<?php <?php
declare(strict_types=1);
/** /**
* @copyright Copyright (c) 2019 Thomas Citharel <tcit@tcit.fr> * @copyright Copyright (c) 2019, Thomas Citharel
* @copyright Copyright (c) 2019, Georg Ehrke
* *
* @author Thomas Citharel <tcit@tcit.fr> * @author Thomas Citharel <tcit@tcit.fr>
* @author Georg Ehrke <oc.list@georgehrke.com>
* *
* @license AGPL-3.0 * @license AGPL-3.0
* *
@ -24,6 +27,7 @@ namespace OCA\DAV\Tests\unit\CalDAV\Reminder;
use OCA\DAV\AppInfo\Application; use OCA\DAV\AppInfo\Application;
use OCA\DAV\CalDAV\Reminder\Notifier; use OCA\DAV\CalDAV\Reminder\Notifier;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\IL10N; use OCP\IL10N;
use OCP\IURLGenerator; use OCP\IURLGenerator;
use OCP\L10N\IFactory; use OCP\L10N\IFactory;
@ -36,22 +40,33 @@ class NotifierTest extends TestCase {
/** @var IFactory|\PHPUnit\Framework\MockObject\MockObject */ /** @var IFactory|\PHPUnit\Framework\MockObject\MockObject */
protected $factory; protected $factory;
/** @var IURLGenerator|\PHPUnit\Framework\MockObject\MockObject */ /** @var IURLGenerator|\PHPUnit\Framework\MockObject\MockObject */
protected $urlGenerator; protected $urlGenerator;
/** @var IL10N|\PHPUnit\Framework\MockObject\MockObject */ /** @var IL10N|\PHPUnit\Framework\MockObject\MockObject */
protected $l; protected $l10n;
/** @var ITimeFactory|\PHPUnit\Framework\MockObject\MockObject */
protected $timeFactory;
protected function setUp() { protected function setUp() {
parent::setUp(); parent::setUp();
$this->urlGenerator = $this->createMock(IURLGenerator::class); $this->urlGenerator = $this->createMock(IURLGenerator::class);
$this->l = $this->createMock(IL10N::class); $this->l10n = $this->createMock(IL10N::class);
$this->l->expects($this->any()) $this->l10n->expects($this->any())
->method('t') ->method('t')
->willReturnCallback(function($string, $args) { ->willReturnCallback(function($string, $args) {
return vsprintf($string, $args); return vsprintf($string, $args);
}); });
$this->l->expects($this->any()) $this->l10n->expects($this->any())
->method('l')
->willReturnCallback(function($string, $args) {
/** \DateTime $args */
return $args->format(\DateTime::ATOM);
});
$this->l10n->expects($this->any())
->method('n') ->method('n')
->willReturnCallback(function($textSingular, $textPlural, $count, $args) { ->willReturnCallback(function($textSingular, $textPlural, $count, $args) {
$text = $count === 1 ? $textSingular : $textPlural; $text = $count === 1 ? $textSingular : $textPlural;
@ -61,14 +76,28 @@ class NotifierTest extends TestCase {
$this->factory = $this->createMock(IFactory::class); $this->factory = $this->createMock(IFactory::class);
$this->factory->expects($this->any()) $this->factory->expects($this->any())
->method('get') ->method('get')
->willReturn($this->l); ->willReturn($this->l10n);
$this->timeFactory = $this->createMock(ITimeFactory::class);
$this->timeFactory
->method('getDateTime')
->willReturn(\DateTime::createFromFormat(\DateTime::ATOM, '2005-08-15T14:00:00+02:00'));
$this->notifier = new Notifier( $this->notifier = new Notifier(
$this->factory, $this->factory,
$this->urlGenerator $this->urlGenerator,
$this->timeFactory
); );
} }
public function testGetId():void {
$this->assertEquals($this->notifier->getID(), 'dav');
}
public function testGetName():void {
$this->assertEquals($this->notifier->getName(), 'Calendar');
}
/** /**
* @expectedException \InvalidArgumentException * @expectedException \InvalidArgumentException
* @expectedExceptionMessage Notification not from this app * @expectedExceptionMessage Notification not from this app
@ -111,17 +140,24 @@ class NotifierTest extends TestCase {
[ [
'calendar_reminder', 'calendar_reminder',
[ [
'title' => 'foo', 'title' => 'Title of this event',
'start' => time() - 60 * 60 * 24 'start_atom' => '2005-08-15T15:52:01+02:00'
], ],
'foo (one day ago)', 'Title of this event (in 1 hour, 52 minutes)',
[ [
'when' => 'foo', 'title' => 'Title of this event',
'description' => 'bar', 'description' => null,
'location' => 'NC Headquarters', 'location' => 'NC Headquarters',
'calendar' => 'Personal' 'all_day' => false,
'start_atom' => '2005-08-15T15:52:01+02:00',
'start_is_floating' => false,
'start_timezone' => 'Europe/Berlin',
'end_atom' => '2005-08-15T17:52:01+02:00',
'end_is_floating' => false,
'end_timezone' => 'Europe/Berlin',
'calendar_displayname' => 'Personal',
], ],
'Calendar: Personal<br>Date: foo<br>Description: bar<br>Where: NC Headquarters' "Calendar: Personal\r\nDate: 2005-08-15T15:52:01+02:00, 2005-08-15T15:52:01+02:00 - 2005-08-15T17:52:01+02:00 (Europe/Berlin)\r\nWhere: NC Headquarters"
], ],
]; ];
} }

View File

@ -1,4 +1,5 @@
<?php <?php
declare(strict_types=1);
/** /**
* @copyright Copyright (c) 2019, Thomas Citharel * @copyright Copyright (c) 2019, Thomas Citharel
* *
@ -21,12 +22,15 @@
*/ */
namespace OCA\DAV\Tests\unit\CalDAV\Reminder; namespace OCA\DAV\Tests\unit\CalDAV\Reminder;
use OCA\DAV\CalDAV\CalDavBackend;
use OCA\DAV\CalDAV\Reminder\AbstractNotificationProvider; use OCA\DAV\CalDAV\Reminder\AbstractNotificationProvider;
use OCA\DAV\CalDAV\Reminder\Backend; use OCA\DAV\CalDAV\Reminder\Backend;
use OCA\DAV\CalDAV\Reminder\INotificationProvider;
use OCA\DAV\CalDAV\Reminder\NotificationProviderManager; use OCA\DAV\CalDAV\Reminder\NotificationProviderManager;
use OCA\DAV\CalDAV\Reminder\NotificationProvider\EmailProvider; use OCA\DAV\CalDAV\Reminder\NotificationProvider\EmailProvider;
use OCA\DAV\CalDAV\Reminder\NotificationProvider\PushProvider; use OCA\DAV\CalDAV\Reminder\NotificationProvider\PushProvider;
use OCA\DAV\CalDAV\Reminder\ReminderService; use OCA\DAV\CalDAV\Reminder\ReminderService;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\IGroup; use OCP\IGroup;
use OCP\IGroupManager; use OCP\IGroupManager;
use OCP\IUser; use OCP\IUser;
@ -51,6 +55,15 @@ class ReminderServiceTest extends TestCase {
/** @var IUserSession|\PHPUnit\Framework\MockObject\MockObject */ /** @var IUserSession|\PHPUnit\Framework\MockObject\MockObject */
private $userSession; private $userSession;
/** @var CalDavBackend|\PHPUnit\Framework\MockObject\MockObject */
private $caldavBackend;
/** @var ITimeFactory|\PHPUnit\Framework\MockObject\MockObject */
private $timeFactory;
/** @var ReminderService */
private $reminderService;
public const CALENDAR_DATA = <<<EOD public const CALENDAR_DATA = <<<EOD
BEGIN:VCALENDAR BEGIN:VCALENDAR
PRODID:-//Nextcloud calendar v1.6.4 PRODID:-//Nextcloud calendar v1.6.4
@ -68,6 +81,87 @@ BEGIN:VALARM
ACTION:EMAIL ACTION:EMAIL
TRIGGER:-PT15M TRIGGER:-PT15M
END:VALARM END:VALARM
BEGIN:VALARM
ACTION:DISPLAY
TRIGGER;VALUE=DATE-TIME:20160608T000000Z
END:VALARM
END:VEVENT
END:VCALENDAR
EOD;
public const CALENDAR_DATA_REPEAT = <<<EOD
BEGIN:VCALENDAR
PRODID:-//Nextcloud calendar v1.6.4
BEGIN:VEVENT
CREATED:20160602T133732
DTSTAMP:20160602T133732
LAST-MODIFIED:20160602T133732
UID:wej2z68l9h
SUMMARY:Test Event
LOCATION:Somewhere ...
DESCRIPTION:maybe ....
DTSTART;TZID=Europe/Berlin;VALUE=DATE:20160609
DTEND;TZID=Europe/Berlin;VALUE=DATE:20160610
BEGIN:VALARM
ACTION:EMAIL
TRIGGER:-PT15M
REPEAT:4
DURATION:PT2M
END:VALARM
END:VEVENT
END:VCALENDAR
EOD;
public const CALENDAR_DATA_RECURRING = <<<EOD
BEGIN:VCALENDAR
PRODID:-//Nextcloud calendar v1.6.4
BEGIN:VEVENT
CREATED:20160602T133732
DTSTAMP:20160602T133732
LAST-MODIFIED:20160602T133732
UID:wej2z68l9h
SUMMARY:Test Event
LOCATION:Somewhere ...
DESCRIPTION:maybe ....
DTSTART;TZID=Europe/Berlin;VALUE=DATE:20160609
DTEND;TZID=Europe/Berlin;VALUE=DATE:20160610
RRULE:FREQ=WEEKLY
BEGIN:VALARM
ACTION:EMAIL
TRIGGER:-PT15M
END:VALARM
BEGIN:VALARM
ACTION:EMAIL
TRIGGER:-P8D
END:VALARM
END:VEVENT
END:VCALENDAR
EOD;
public const CALENDAR_DATA_RECURRING_REPEAT = <<<EOD
BEGIN:VCALENDAR
PRODID:-//Nextcloud calendar v1.6.4
BEGIN:VEVENT
CREATED:20160602T133732
DTSTAMP:20160602T133732
LAST-MODIFIED:20160602T133732
UID:wej2z68l9h
SUMMARY:Test Event
LOCATION:Somewhere ...
DESCRIPTION:maybe ....
DTSTART;TZID=Europe/Berlin;VALUE=DATE:20160609
DTEND;TZID=Europe/Berlin;VALUE=DATE:20160610
RRULE:FREQ=WEEKLY
BEGIN:VALARM
ACTION:EMAIL
TRIGGER:-PT15M
REPEAT:4
DURATION:PT2M
END:VALARM
BEGIN:VALARM
ACTION:EMAIL
TRIGGER:-P8D
END:VALARM
END:VEVENT END:VEVENT
END:VCALENDAR END:VCALENDAR
EOD; EOD;
@ -79,198 +173,383 @@ EOD;
$this->notificationProviderManager = $this->createMock(NotificationProviderManager::class); $this->notificationProviderManager = $this->createMock(NotificationProviderManager::class);
$this->userManager = $this->createMock(IUserManager::class); $this->userManager = $this->createMock(IUserManager::class);
$this->groupManager = $this->createMock(IGroupManager::class); $this->groupManager = $this->createMock(IGroupManager::class);
$this->userSession = $this->createMock(IUserSession::class); $this->caldavBackend = $this->createMock(CalDavBackend::class);
$this->timeFactory = $this->createMock(ITimeFactory::class);
$this->caldavBackend->method('getShares')->willReturn([]);
$this->reminderService = new ReminderService($this->backend,
$this->notificationProviderManager,
$this->userManager,
$this->groupManager,
$this->caldavBackend,
$this->timeFactory);
} }
public function dataTestProcessReminders(): array public function testOnCalendarObjectDelete():void {
{ $this->backend->expects($this->once())
return [ ->method('cleanRemindersForEvent')
[ ->with(44);
[], null
],
[
[
[
'calendardata' => self::CALENDAR_DATA,
'displayname' => 'Personal',
'type' => 'EMAIL',
'uid' => 1,
'id' => 1,
],
],
$this->createMock(EmailProvider::class),
],
[
[
[
'calendardata' => self::CALENDAR_DATA,
'displayname' => 'Personal',
'type' => 'DISPLAY',
'uid' => 1,
'id' => 1,
],
],
$this->createMock(PushProvider::class),
]
];
}
/** $action = '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject';
* @dataProvider dataTestProcessReminders $objectData = [
* @param array $reminders 'id' => '44',
* @param AbstractNotificationProvider|null $notificationProvider 'component' => 'vevent',
* @throws \OCA\DAV\CalDAV\Reminder\NotificationProvider\ProviderNotAvailableException
* @throws \OCA\DAV\CalDAV\Reminder\NotificationTypeDoesNotExistException
* @throws \OC\User\NoUserException
*/
public function testProcessReminders(array $reminders, ?AbstractNotificationProvider $notificationProvider): void
{
$user = $this->createMock(IUser::class);
$this->backend->expects($this->once())->method('getRemindersToProcess')->willReturn($reminders);
if (count($reminders) > 0) {
$this->userManager->expects($this->exactly(count($reminders)))->method('get')->willReturn($user);
$this->backend->expects($this->exactly(count($reminders)))->method('removeReminder');
$this->notificationProviderManager->expects($this->exactly(count($reminders)))->method('getProvider')->willReturn($notificationProvider);
}
$reminderService = new ReminderService($this->backend, $this->notificationProviderManager, $this->userManager, $this->groupManager, $this->userSession);
$reminderService->processReminders();
}
/**
* @expectedException OC\User\NoUserException
*/
public function testProcessReminderWithBadUser(): void
{
$this->backend->expects($this->once())->method('getRemindersToProcess')->willReturn([
[
'calendardata' => self::CALENDAR_DATA,
'type' => 'DISPLAY',
'uid' => 1,
'id' => 1,
]
]);
$this->userManager->expects($this->once())->method('get')->with(1)->willReturn(null);
$reminderService = new ReminderService($this->backend, $this->notificationProviderManager, $this->userManager, $this->groupManager, $this->userSession);
$reminderService->processReminders();
}
public function providesTouchCalendarObject(): array
{
return [
[
'\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject',
[
'principaluri' => 'principals/users/personal'
],
[],
[
'calendarid' => 1,
'uri' => 'something.ics',
],
0
],
[
'\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject',
[
'principaluri' => 'principals/users/personal'
],
[],
[
'calendarid' => 1,
'uri' => 'something.ics',
'calendardata' => self::CALENDAR_DATA
],
0
],
[
'\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject',
[
'principaluri' => 'principals/users/someone',
'uri' => 'personal'
],
[
[
'{http://owncloud.org/ns}principal' => 'principals/users/someone'
]
],
[
'calendarid' => 1,
'uri' => 'something.ics',
'calendardata' => self::CALENDAR_DATA
],
0
],
[
'\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject',
[
'principaluri' => 'principals/users/someone',
'uri' => 'personal'
],
[
[
'{http://owncloud.org/ns}principal' => 'principals/groups/somegroup'
]
],
[
'calendarid' => 1,
'uri' => 'something.ics',
'calendardata' => self::CALENDAR_DATA
],
1
]
]; ];
$this->reminderService->onTouchCalendarObject($action, $objectData);
} }
/** public function testOnCalendarObjectCreateSingleEntry():void {
* @dataProvider providesTouchCalendarObject $action = '\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject';
* @param string $action $objectData = [
* @param array $calendarData 'calendardata' => self::CALENDAR_DATA,
* @param array $shares 'id' => '42',
* @param array $objectData 'calendarid' => '1337',
* @param int $numberOfGroups 'component' => 'vevent',
* @throws \OC\User\NoUserException ];
* @throws \Sabre\VObject\InvalidDataException
*/
public function testOnTouchCalendarObject(string $action, array $calendarData, array $shares, array $objectData, int $numberOfGroups): void
{
$this->backend->expects($this->once())->method('cleanRemindersForEvent')->with($objectData['calendarid'], $objectData['uri']);
if ($action !== '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject') { $this->backend->expects($this->exactly(2))
$user = $this->createMock(IUser::class); ->method('insertReminder')
$user->expects($this->once())->method('getUID')->willReturn('user'); ->withConsecutive(
[1337, 42, 'wej2z68l9h', false, 1465430400, false, '5c70531aab15c92b52518ae10a2f78a4', 'de919af7429d3b5c11e8b9d289b411a6', 'EMAIL', true, 1465429500, false],
[1337, 42, 'wej2z68l9h', false, 1465430400, false, '5c70531aab15c92b52518ae10a2f78a4', '35b3eae8e792aa2209f0b4e1a302f105', 'DISPLAY', false, 1465344000, false]
)
->willReturn(1);
$this->userSession->expects($this->once())->method('getUser')->willReturn($user); $this->timeFactory->expects($this->once())
if ($numberOfGroups === 0) { ->method('getDateTime')
$this->backend->expects($this->exactly(count($shares) + 1))->method('insertReminder'); ->with()
} else { ->willReturn(\DateTime::createFromFormat(\DateTime::ATOM, '2016-06-08T00:00:00+00:00'));
$group = $this->createMock(IGroup::class);
$groupUser = $this->createMock(IUser::class); $this->reminderService->onTouchCalendarObject($action, $objectData);
$groupUser->expects($this->once())->method('getUID')->willReturn('groupuser');
$group->expects($this->once())->method('getUsers')->willReturn([$groupUser]);
$this->groupManager->expects($this->exactly($numberOfGroups))->method('get')->willReturn($group);
}
}
$reminderService = new ReminderService($this->backend, $this->notificationProviderManager, $this->userManager, $this->groupManager, $this->userSession);
$reminderService->onTouchCalendarObject($action, $calendarData, $shares, $objectData);
} }
/** public function testOnCalendarObjectCreateSingleEntryWithRepeat(): void {
* @expectedException OC\User\NoUserException $action = '\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject';
*/ $objectData = [
public function testOnTouchCalendarObjectWithNoSession(): void 'calendardata' => self::CALENDAR_DATA_REPEAT,
{ 'id' => '42',
$this->backend->expects($this->once())->method('cleanRemindersForEvent'); 'calendarid' => '1337',
$this->userSession->expects($this->once())->method('getUser')->willReturn(null); 'component' => 'vevent',
];
$reminderService = new ReminderService($this->backend, $this->notificationProviderManager, $this->userManager, $this->groupManager, $this->userSession); $this->backend->expects($this->exactly(5))
$reminderService->onTouchCalendarObject('', ['principaluri' => 'foo'], [], ['calendarid' => 1, 'uri' => 'bar']); ->method('insertReminder')
->withConsecutive(
[1337, 42, 'wej2z68l9h', false, 1465430400, false, '5c70531aab15c92b52518ae10a2f78a4', 'ecacbf07d413c3c78d1ac7ad8c469602', 'EMAIL', true, 1465429500, false],
[1337, 42, 'wej2z68l9h', false, 1465430400, false, '5c70531aab15c92b52518ae10a2f78a4', 'ecacbf07d413c3c78d1ac7ad8c469602', 'EMAIL', true, 1465429620, true],
[1337, 42, 'wej2z68l9h', false, 1465430400, false, '5c70531aab15c92b52518ae10a2f78a4', 'ecacbf07d413c3c78d1ac7ad8c469602', 'EMAIL', true, 1465429740, true],
[1337, 42, 'wej2z68l9h', false, 1465430400, false, '5c70531aab15c92b52518ae10a2f78a4', 'ecacbf07d413c3c78d1ac7ad8c469602', 'EMAIL', true, 1465429860, true],
[1337, 42, 'wej2z68l9h', false, 1465430400, false, '5c70531aab15c92b52518ae10a2f78a4', 'ecacbf07d413c3c78d1ac7ad8c469602', 'EMAIL', true, 1465429980, true]
)
->willReturn(1);
$this->timeFactory->expects($this->once())
->method('getDateTime')
->with()
->willReturn(\DateTime::createFromFormat(\DateTime::ATOM, '2016-06-08T00:00:00+00:00'));
$this->reminderService->onTouchCalendarObject($action, $objectData);
} }
public function testOnTouchCalendarObjectWithNoCalendarURI(): void public function testOnCalendarObjectCreateRecurringEntry(): void {
{ $action = '\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject';
$reminderService = new ReminderService($this->backend, $this->notificationProviderManager, $this->userManager, $this->groupManager, $this->userSession); $objectData = [
$this->assertNull($reminderService->onTouchCalendarObject('', [], [], [])); 'calendardata' => self::CALENDAR_DATA_RECURRING,
'id' => '42',
'calendarid' => '1337',
'component' => 'vevent',
];
$this->backend->expects($this->exactly(2))
->method('insertReminder')
->withConsecutive(
[1337, 42, 'wej2z68l9h', true, 1467244800, false, 'fbdb2726bc0f7dfacac1d881c1453e20', 'de919af7429d3b5c11e8b9d289b411a6', 'EMAIL', true, 1467243900, false],
[1337, 42, 'wej2z68l9h', true, 1467849600, false, 'fbdb2726bc0f7dfacac1d881c1453e20', '8996992118817f9f311ac5cc56d1cc97', 'EMAIL', true, 1467158400, false]
)
->willReturn(1);
$this->timeFactory->expects($this->once())
->method('getDateTime')
->with()
->willReturn(\DateTime::createFromFormat(\DateTime::ATOM, '2016-06-29T00:00:00+00:00'));
$this->reminderService->onTouchCalendarObject($action, $objectData);
}
public function testOnCalendarObjectCreateRecurringEntryWithRepeat():void {
$action = '\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject';
$objectData = [
'calendardata' => self::CALENDAR_DATA_RECURRING_REPEAT,
'id' => '42',
'calendarid' => '1337',
'component' => 'vevent',
];
$this->backend->expects($this->exactly(6))
->method('insertReminder')
->withConsecutive(
[1337, 42, 'wej2z68l9h', true, 1467244800, false, 'fbdb2726bc0f7dfacac1d881c1453e20', 'ecacbf07d413c3c78d1ac7ad8c469602', 'EMAIL', true, 1467243900, false],
[1337, 42, 'wej2z68l9h', true, 1467244800, false, 'fbdb2726bc0f7dfacac1d881c1453e20', 'ecacbf07d413c3c78d1ac7ad8c469602', 'EMAIL', true, 1467244020, true],
[1337, 42, 'wej2z68l9h', true, 1467244800, false, 'fbdb2726bc0f7dfacac1d881c1453e20', 'ecacbf07d413c3c78d1ac7ad8c469602', 'EMAIL', true, 1467244140, true],
[1337, 42, 'wej2z68l9h', true, 1467244800, false, 'fbdb2726bc0f7dfacac1d881c1453e20', 'ecacbf07d413c3c78d1ac7ad8c469602', 'EMAIL', true, 1467244260, true],
[1337, 42, 'wej2z68l9h', true, 1467244800, false, 'fbdb2726bc0f7dfacac1d881c1453e20', 'ecacbf07d413c3c78d1ac7ad8c469602', 'EMAIL', true, 1467244380, true],
[1337, 42, 'wej2z68l9h', true, 1467849600, false, 'fbdb2726bc0f7dfacac1d881c1453e20', '8996992118817f9f311ac5cc56d1cc97', 'EMAIL', true, 1467158400, false]
)
->willReturn(1);
$this->timeFactory->expects($this->once())
->method('getDateTime')
->with()
->willReturn(\DateTime::createFromFormat(\DateTime::ATOM, '2016-06-29T00:00:00+00:00'));
$this->reminderService->onTouchCalendarObject($action, $objectData);
}
public function testProcessReminders():void {
$this->backend->expects($this->at(0))
->method('getRemindersToProcess')
->with()
->willReturn([
[
'id' => 1,
'calendar_id' => 1337,
'object_id' => 42,
'uid' => 'wej2z68l9h',
'is_recurring' => false,
'recurrence_id' => 1465430400,
'is_recurrence_exception' => false,
'event_hash' => '5c70531aab15c92b52518ae10a2f78a4',
'alarm_hash' => 'de919af7429d3b5c11e8b9d289b411a6',
'type' => 'EMAIL',
'is_relative' => true,
'notification_date' => 1465429500,
'is_repeat_based' => false,
'calendardata' => self::CALENDAR_DATA,
'displayname' => 'Displayname 123',
'principaluri' => 'principals/users/user001',
],
[
'id' => 2,
'calendar_id' => 1337,
'object_id' => 42,
'uid' => 'wej2z68l9h',
'is_recurring' => false,
'recurrence_id' => 1465430400,
'is_recurrence_exception' => false,
'event_hash' => '5c70531aab15c92b52518ae10a2f78a4',
'alarm_hash' => 'ecacbf07d413c3c78d1ac7ad8c469602',
'type' => 'EMAIL',
'is_relative' => true,
'notification_date' => 1465429740,
'is_repeat_based' => true,
'calendardata' => self::CALENDAR_DATA_REPEAT,
'displayname' => 'Displayname 123',
'principaluri' => 'principals/users/user001',
],
[
'id' => 3,
'calendar_id' => 1337,
'object_id' => 42,
'uid' => 'wej2z68l9h',
'is_recurring' => false,
'recurrence_id' => 1465430400,
'is_recurrence_exception' => false,
'event_hash' => '5c70531aab15c92b52518ae10a2f78a4',
'alarm_hash' => '35b3eae8e792aa2209f0b4e1a302f105',
'type' => 'DISPLAY',
'is_relative' => false,
'notification_date' => 1465344000,
'is_repeat_based' => false,
'calendardata' => self::CALENDAR_DATA,
'displayname' => 'Displayname 123',
'principaluri' => 'principals/users/user001',
],
[
'id' => 4,
'calendar_id' => 1337,
'object_id' => 42,
'uid' => 'wej2z68l9h',
'is_recurring' => true,
'recurrence_id' => 1467244800,
'is_recurrence_exception' => false,
'event_hash' => 'fbdb2726bc0f7dfacac1d881c1453e20',
'alarm_hash' => 'ecacbf07d413c3c78d1ac7ad8c469602',
'type' => 'EMAIL',
'is_relative' => true,
'notification_date' => 1467243900,
'is_repeat_based' => false,
'calendardata' => self::CALENDAR_DATA_RECURRING_REPEAT,
'displayname' => 'Displayname 123',
'principaluri' => 'principals/users/user001',
],
[
'id' => 5,
'calendar_id' => 1337,
'object_id' => 42,
'uid' => 'wej2z68l9h',
'is_recurring' => true,
'recurrence_id' => 1467849600,
'is_recurrence_exception' => false,
'event_hash' => 'fbdb2726bc0f7dfacac1d881c1453e20',
'alarm_hash' => '8996992118817f9f311ac5cc56d1cc97',
'type' => 'EMAIL',
'is_relative' => true,
'notification_date' => 1467158400,
'is_repeat_based' => false,
'calendardata' => self::CALENDAR_DATA_RECURRING,
'displayname' => 'Displayname 123',
'principaluri' => 'principals/users/user001',
]
]);
$this->notificationProviderManager->expects($this->at(0))
->method('hasProvider')
->with('EMAIL')
->willReturn(true);
$provider1 = $this->createMock(INotificationProvider::class);
$this->notificationProviderManager->expects($this->at(1))
->method('getProvider')
->with('EMAIL')
->willReturn($provider1);
$this->notificationProviderManager->expects($this->at(2))
->method('hasProvider')
->with('EMAIL')
->willReturn(true);
$provider2 = $this->createMock(INotificationProvider::class);
$this->notificationProviderManager->expects($this->at(3))
->method('getProvider')
->with('EMAIL')
->willReturn($provider2);
$this->notificationProviderManager->expects($this->at(4))
->method('hasProvider')
->with('DISPLAY')
->willReturn(true);
$provider3 = $this->createMock(INotificationProvider::class);
$this->notificationProviderManager->expects($this->at(5))
->method('getProvider')
->with('DISPLAY')
->willReturn($provider3);
$this->notificationProviderManager->expects($this->at(6))
->method('hasProvider')
->with('EMAIL')
->willReturn(true);
$provider4 = $this->createMock(INotificationProvider::class);
$this->notificationProviderManager->expects($this->at(7))
->method('getProvider')
->with('EMAIL')
->willReturn($provider4);
$this->notificationProviderManager->expects($this->at(8))
->method('hasProvider')
->with('EMAIL')
->willReturn(true);
$provider5 = $this->createMock(INotificationProvider::class);
$this->notificationProviderManager->expects($this->at(9))
->method('getProvider')
->with('EMAIL')
->willReturn($provider5);
$user = $this->createMock(IUser::class);
$this->userManager->expects($this->exactly(5))
->method('get')
->with('user001')
->willReturn($user);
$provider1->expects($this->once())
->method('send')
->with($this->callback(function($vevent) {
if ($vevent->DTSTART->getDateTime()->format(\DateTime::ATOM) !== '2016-06-09T00:00:00+00:00') {
return false;
}
return true;
}, 'Displayname 123', $user));
$provider2->expects($this->once())
->method('send')
->with($this->callback(function($vevent) {
if ($vevent->DTSTART->getDateTime()->format(\DateTime::ATOM) !== '2016-06-09T00:00:00+00:00') {
return false;
}
return true;
}, 'Displayname 123', $user));
$provider3->expects($this->once())
->method('send')
->with($this->callback(function($vevent) {
if ($vevent->DTSTART->getDateTime()->format(\DateTime::ATOM) !== '2016-06-09T00:00:00+00:00') {
return false;
}
return true;
}, 'Displayname 123', $user));
$provider4->expects($this->once())
->method('send')
->with($this->callback(function($vevent) {
if ($vevent->DTSTART->getDateTime()->format(\DateTime::ATOM) !== '2016-06-30T00:00:00+00:00') {
return false;
}
return true;
}, 'Displayname 123', $user));
$provider5->expects($this->once())
->method('send')
->with($this->callback(function($vevent) {
if ($vevent->DTSTART->getDateTime()->format(\DateTime::ATOM) !== '2016-07-07T00:00:00+00:00') {
return false;
}
return true;
}, 'Displayname 123', $user));
$this->backend->expects($this->at(1))
->method('removeReminder')
->with(1);
$this->backend->expects($this->at(2))
->method('removeReminder')
->with(2);
$this->backend->expects($this->at(3))
->method('removeReminder')
->with(3);
$this->backend->expects($this->at(4))
->method('removeReminder')
->with(4);
$this->backend->expects($this->at(5))
->method('insertReminder')
->with(1337, 42, 'wej2z68l9h', true, 1467849600, false, 'fbdb2726bc0f7dfacac1d881c1453e20', 'ecacbf07d413c3c78d1ac7ad8c469602', 'EMAIL', true, 1467848700, false)
->willReturn(99);
$this->backend->expects($this->at(6))
->method('insertReminder')
->with(1337, 42, 'wej2z68l9h', true, 1467849600, false, 'fbdb2726bc0f7dfacac1d881c1453e20', 'ecacbf07d413c3c78d1ac7ad8c469602', 'EMAIL', true, 1467848820, true)
->willReturn(99);
$this->backend->expects($this->at(7))
->method('insertReminder')
->with(1337, 42, 'wej2z68l9h', true, 1467849600, false, 'fbdb2726bc0f7dfacac1d881c1453e20', 'ecacbf07d413c3c78d1ac7ad8c469602', 'EMAIL', true, 1467848940, true)
->willReturn(99);
$this->backend->expects($this->at(8))
->method('insertReminder')
->with(1337, 42, 'wej2z68l9h', true, 1467849600, false, 'fbdb2726bc0f7dfacac1d881c1453e20', 'ecacbf07d413c3c78d1ac7ad8c469602', 'EMAIL', true, 1467849060, true)
->willReturn(99);
$this->backend->expects($this->at(9))
->method('insertReminder')
->with(1337, 42, 'wej2z68l9h', true, 1467849600, false, 'fbdb2726bc0f7dfacac1d881c1453e20', 'ecacbf07d413c3c78d1ac7ad8c469602', 'EMAIL', true, 1467849180, true)
->willReturn(99);
$this->backend->expects($this->at(10))
->method('removeReminder')
->with(5);
$this->backend->expects($this->at(11))
->method('insertReminder')
->with(1337, 42, 'wej2z68l9h', true, 1468454400, false, 'fbdb2726bc0f7dfacac1d881c1453e20', '8996992118817f9f311ac5cc56d1cc97', 'EMAIL', true, 1467763200, false)
->willReturn(99);
$this->timeFactory->method('getDateTime')
->willReturn(\DateTime::createFromFormat(\DateTime::ATOM, '2016-06-08T00:00:00+00:00'));
$this->reminderService->processReminders();
} }
} }