1
0
mirror of https://github.com/chylex/Nextcloud-News.git synced 2025-04-26 05:15:46 +02:00

Move to nextcloud config and update phpunit

Signed-off-by: Sean Molenaar <sean@seanmolenaar.eu>
This commit is contained in:
Sean Molenaar 2020-09-20 22:03:05 +02:00 committed by Benjamin Brahmer
parent 2c8b4fa019
commit 60ab4941cc
57 changed files with 1667 additions and 1767 deletions

View File

@ -28,7 +28,7 @@ jobs:
- 5432:5432 # Maps tcp port 5432 on service container to the host
strategy:
matrix:
php-versions: ['7.2', '7.3', '7.4']
php-versions: ['7.3', '7.4']
nextcloud: ['20']
database: ['sqlite', 'pgsql', 'mysql']
experimental: [false]

View File

@ -47,6 +47,7 @@ Before you update to a new version, [check the changelog](https://github.com/nex
<repair-steps>
<post-migration>
<step>OCA\News\Migration\MigrateStatusFlags</step>
<step>OCA\News\Migration\MigrateConfig</step>
</post-migration>
</repair-steps>

View File

@ -42,10 +42,10 @@
},
"require": {
"php": "^7.2",
"ezyang/htmlpurifier": "4.12.0",
"ezyang/htmlpurifier": "^4.13.0",
"pear/net_url2": "2.2.2",
"riimu/kit-pathjoin": "1.2.0",
"debril/feed-io": "^4.5",
"debril/feed-io": "^v4.7.8",
"arthurhoaro/favicon": "^1.2",
"ext-json": "*",
"ext-simplexml": "*",
@ -53,11 +53,11 @@
"andreskrey/readability.php": "^2.1"
},
"require-dev": {
"phpunit/phpunit": "^7.5",
"squizlabs/php_codesniffer": "^3.4",
"phpunit/phpunit": "9.2.6",
"squizlabs/php_codesniffer": "^3.5.6",
"guzzlehttp/guzzle": "^6.3",
"symfony/service-contracts": "1.1.8",
"phpstan/phpstan": "^0.12.38"
"symfony/service-contracts": "2.2.0",
"phpstan/phpstan": "^0.12.43"
},
"replace": {
"guzzlehttp/guzzle": "*",

885
composer.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -18,28 +18,32 @@ use HTMLPurifier;
use HTMLPurifier_Config;
use Favicon\Favicon;
use OC\Encryption\Update;
use OCA\News\Config\LegacyConfig;
use OCA\News\Config\FetcherConfig;
use OCA\News\Db\FolderMapper;
use OCA\News\Service\FeedService;
use OCA\News\Service\FolderService;
use OCA\News\Service\ItemService;
use OCA\News\Utility\PsrLogger;
use OCP\BackgroundJob\IJobList;
use OCA\News\Utility\Updater;
use OCP\IContainer;
use OCP\INavigationManager;
use OCP\IURLGenerator;
use OCP\IConfig;
use OCP\ILogger;
use OCP\ITempManager;
use OCP\AppFramework\App;
use OCP\Files\IRootFolder;
use OCP\Files\Node;
use OCA\News\Config\AppConfig;
use OCA\News\Config\Config;
use OCA\News\Db\MapperFactory;
use OCA\News\Db\ItemMapper;
use OCA\News\Fetcher\FeedFetcher;
use OCA\News\Fetcher\Fetcher;
use OCA\News\Fetcher\YoutubeFetcher;
use OCA\News\Scraper\Scraper;
use Psr\Log\LoggerInterface;
/**
* Class Application
@ -49,6 +53,24 @@ use OCA\News\Scraper\Scraper;
class Application extends App
{
/**
* App Name
*/
public const NAME = 'news';
/**
* List of default settings
*/
public const DEFAULT_SETTINGS = [
'autoPurgeMinimumInterval' => 60,
'autoPurgeCount' => 200,
'maxRedirects' => 10,
'feedFetcherTimeout' => 60,
'useCronUpdates' => true,
'exploreUrl' => '',
'updateInterval' => 3600,
];
/**
* Application constructor.
*
@ -56,7 +78,7 @@ class Application extends App
*/
public function __construct(array $urlParams = [])
{
parent::__construct('news', $urlParams);
parent::__construct(self::NAME, $urlParams);
$container = $this->getContainer();
@ -77,20 +99,6 @@ class Application extends App
return $c->query(MapperFactory::class)->build();
});
/**
* App config parser.
*/
$container->registerService(AppConfig::class, function (IContainer $c): AppConfig {
$config = new AppConfig(
$c->query(INavigationManager::class),
$c->query(IURLGenerator::class),
$c->query(IJobList::class)
);
$config->loadConfig($c->query('info'));
return $config;
});
/**
* Core
*/
@ -98,38 +106,24 @@ class Application extends App
return ['app' => $c->query('AppName')];
});
$container->registerService('databaseType', function (IContainer $c) {
return $c->query(IConfig::class)->getSystemValue('dbtype');
});
$container->registerService('ConfigView', function (IContainer $c): Node {
$container->registerService('ConfigView', function (IContainer $c): ?Node {
/** @var IRootFolder $fs */
$fs = $c->query(IRootFolder::class);
$path = 'news/config';
if ($fs->nodeExists($path)) {
return $fs->get($path);
} else {
return $fs->newFolder($path);
return null;
}
});
/**
* Logger base
*/
$container->registerService(PsrLogger::class, function (IContainer $c): PsrLogger {
return new PsrLogger(
$c->query('ServerContainer')->getLogger(),
$c->query('AppName')
);
});
$container->registerService(Config::class, function (IContainer $c): Config {
$config = new Config(
$container->registerService(LegacyConfig::class, function (IContainer $c): LegacyConfig {
$config = new LegacyConfig(
$c->query('ConfigView'),
$c->query(PsrLogger::class),
$c->query(LoggerInterface::class),
$c->query('LoggerParameters')
);
$config->read($c->query('configFile'), true);
$config->read($c->query('configFile'), false);
return $config;
});
@ -175,7 +169,7 @@ class Application extends App
*/
$container->registerService(FetcherConfig::class, function (IContainer $c): FetcherConfig {
$fConfig = new FetcherConfig();
$fConfig->setConfig($c->query(Config::class))
$fConfig->setConfig($c->query(IConfig::class))
->setProxy($c->query(IConfig::class));
return $fConfig;
@ -183,7 +177,7 @@ class Application extends App
$container->registerService(FeedIo::class, function (IContainer $c): FeedIo {
$config = $c->query(FetcherConfig::class);
return new FeedIo($config->getClient(), $c->query(PsrLogger::class));
return new FeedIo($config->getClient(), $c->query(LoggerInterface::class));
});
$container->registerService(Favicon::class, function (IContainer $c): Favicon {
@ -209,7 +203,7 @@ class Application extends App
*/
$container->registerService(Scraper::class, function (IContainer $c): Scraper {
return new Scraper(
$c->query(PsrLogger::class)
$c->query(LoggerInterface::class)
);
});
}

View File

@ -13,7 +13,15 @@ namespace OCA\News\Command;
use FeedIo\FeedIo;
use Favicon\Favicon;
use HTMLPurifier;
use OCA\News\Db\FeedMapper;
use OCA\News\Db\ItemMapper;
use OCA\News\Fetcher\Fetcher;
use OCA\News\Service\FeedService;
use OCA\News\Utility\Time;
use OCP\IConfig;
use OCP\IL10N;
use OCP\ILogger;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputArgument;
@ -38,8 +46,8 @@ class ShowFeed extends Command
*/
public function __construct(Fetcher $feedFetcher)
{
$this->feedFetcher = $feedFetcher;
parent::__construct();
$this->feedFetcher = $feedFetcher;
}
protected function configure()

View File

@ -1,207 +0,0 @@
<?php
/**
* Nextcloud - News
*
* This file is licensed under the Affero General Public License version 3 or
* later. See the COPYING file.
*
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Config;
use OCA\News\Utility\PsrLogger;
use OCP\Files\Folder;
class Config
{
private $fileSystem;
private $autoPurgeMinimumInterval; // seconds, used to define how
// long deleted folders and feeds
// should still be kept for an
// undo actions
private $autoPurgeCount; // number of allowed unread articles per feed
private $maxRedirects; // seconds
private $feedFetcherTimeout; // seconds
private $useCronUpdates; // turn off updates run by the cron
private $logger;
private $loggerParams;
private $maxSize;
private $exploreUrl;
private $updateInterval;
public function __construct(
Folder $fileSystem,
PsrLogger $logger,
$LoggerParameters
) {
$this->fileSystem = $fileSystem;
$this->autoPurgeMinimumInterval = 60;
$this->autoPurgeCount = 200;
$this->maxRedirects = 10;
$this->maxSize = 100 * 1024 * 1024; // 100Mb
$this->feedFetcherTimeout = 60;
$this->useCronUpdates = true;
$this->logger = $logger;
$this->exploreUrl = '';
$this->loggerParams = $LoggerParameters;
$this->updateInterval = 3600;
}
public function getAutoPurgeMinimumInterval()
{
if ($this->autoPurgeMinimumInterval > 60) {
return $this->autoPurgeMinimumInterval;
} else {
return 60;
}
}
public function getAutoPurgeCount()
{
return $this->autoPurgeCount;
}
public function getMaxRedirects()
{
return $this->maxRedirects;
}
public function getFeedFetcherTimeout()
{
return $this->feedFetcherTimeout;
}
public function getUseCronUpdates()
{
return $this->useCronUpdates;
}
public function getMaxSize()
{
return $this->maxSize;
}
public function getExploreUrl()
{
return $this->exploreUrl;
}
public function getUpdateInterval()
{
return $this->updateInterval;
}
public function setAutoPurgeMinimumInterval($value)
{
$this->autoPurgeMinimumInterval = $value;
}
public function setAutoPurgeCount($value)
{
$this->autoPurgeCount = $value;
}
public function setMaxRedirects($value)
{
$this->maxRedirects = $value;
}
public function setFeedFetcherTimeout($value)
{
$this->feedFetcherTimeout = $value;
}
public function setUseCronUpdates($value)
{
$this->useCronUpdates = $value;
}
public function setMaxSize($value)
{
$this->maxSize = $value;
}
public function setExploreUrl($value)
{
$this->exploreUrl = $value;
}
public function setUpdateInterval($value)
{
$this->updateInterval = $value;
}
public function read($configPath, $createIfNotExists = false)
{
if ($createIfNotExists && !$this->fileSystem->nodeExists($configPath)) {
$this->fileSystem->newFile($configPath);
$this->write($configPath);
} else {
$content = $this->fileSystem->get($configPath)->getContent();
$configValues = parse_ini_string($content);
if ($configValues === false || count($configValues) === 0) {
$this->logger->warning(
'Configuration invalid. Ignoring values.',
$this->loggerParams
);
} else {
foreach ($configValues as $key => $value) {
if (property_exists($this, $key)) {
$type = gettype($this->$key);
settype($value, $type);
$this->$key = $value;
} else {
$this->logger->warning(
'Configuration value "' . $key .
'" does not exist. Ignored value.',
$this->loggerParams
);
}
}
}
}
}
public function write($configPath)
{
$ini =
'autoPurgeMinimumInterval = ' .
$this->autoPurgeMinimumInterval . "\n" .
'autoPurgeCount = ' .
$this->autoPurgeCount . "\n" .
'maxRedirects = ' .
$this->maxRedirects . "\n" .
'maxSize = ' .
$this->maxSize . "\n" .
'exploreUrl = ' .
$this->exploreUrl . "\n" .
'feedFetcherTimeout = ' .
$this->feedFetcherTimeout . "\n" .
'updateInterval = ' .
$this->updateInterval . "\n" .
'useCronUpdates = ' .
var_export($this->useCronUpdates, true);
;
$this->fileSystem->get($configPath)->putContent($ini);
}
}

View File

@ -15,6 +15,7 @@ namespace OCA\News\Config;
use FeedIo\Adapter\ClientInterface;
use \GuzzleHttp\Client;
use OCA\News\AppInfo\Application;
use OCA\News\Fetcher\Client\FeedIoClient;
use OCA\News\Fetcher\Client\LegacyGuzzleClient;
use OCP\IConfig;
@ -44,13 +45,6 @@ class FetcherConfig
*/
protected $redirects;
/**
* Max size of the recieved data.
* @deprecated guzzle can't handle this
* @var string
*/
protected $max_size;
/**
* User agent for the client.
* @var string
@ -96,8 +90,7 @@ class FetcherConfig
$config['redirect.max'] = $this->redirects;
}
$guzzle = new Client($config);
return $guzzle;
return new Client($config);
}
/**
@ -121,22 +114,28 @@ class FetcherConfig
$config['request.options']['redirect.max'] = $this->redirects;
}
$guzzle = new Client($config);
return $guzzle;
return new Client($config);
}
/**
* Set settings for config.
*
* @param Config $config The shared configuration
* @param IConfig $config The shared configuration
*
* @return self
*/
public function setConfig(Config $config)
public function setConfig(IConfig $config)
{
$this->client_timeout = $config->getFeedFetcherTimeout();
$this->redirects = $config->getMaxRedirects();
$this->max_size = $config->getMaxSize();
$this->client_timeout = $config->getAppValue(
Application::NAME,
'feedFetcherTimeout',
Application::DEFAULT_SETTINGS['feedFetcherTimeout']
);
$this->redirects = $config->getAppValue(
Application::NAME,
'maxRedirects',
Application::DEFAULT_SETTINGS['maxRedirects']
);
return $this;
}

View File

@ -0,0 +1,87 @@
<?php
/**
* Nextcloud - News
*
* This file is licensed under the Affero General Public License version 3 or
* later. See the COPYING file.
*
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Config;
use OCA\News\AppInfo\Application;
use OCA\News\Utility\PsrLogger;
use OCP\Files\Folder;
use OCP\IConfig;
use Psr\Log\LoggerInterface;
class LegacyConfig
{
private $fileSystem;
public $autoPurgeMinimumInterval; // seconds, used to define how
// long deleted folders and feeds
// should still be kept for an
// undo actions
public $autoPurgeCount; // number of allowed unread articles per feed
public $maxRedirects; // seconds
public $feedFetcherTimeout; // seconds
public $useCronUpdates; // turn off updates run by the cron
public $logger;
public $loggerParams;
public $maxSize;
public $exploreUrl;
public $updateInterval;
public function __construct(
?Folder $fileSystem,
LoggerInterface $logger,
$LoggerParameters
) {
$this->fileSystem = $fileSystem;
$this->autoPurgeMinimumInterval = 60;
$this->autoPurgeCount = 200;
$this->maxRedirects = 10;
$this->maxSize = 100 * 1024 * 1024; // 100Mb
$this->feedFetcherTimeout = 60;
$this->useCronUpdates = true;
$this->logger = $logger;
$this->exploreUrl = '';
$this->loggerParams = $LoggerParameters;
$this->updateInterval = 3600;
}
public function read($configPath, $createIfNotExists = false)
{
if ($this->fileSystem === null) {
return;
}
$content = $this->fileSystem->get($configPath)->getContent();
$configValues = parse_ini_string($content);
if ($configValues === false || count($configValues) === 0) {
$this->logger->warning(
'Configuration invalid. Ignoring values.',
$this->loggerParams
);
} else {
foreach ($configValues as $key => $value) {
if (property_exists($this, $key)) {
$type = gettype($this->$key);
settype($value, $type);
$this->$key = $value;
} else {
$this->logger->warning(
'Configuration value "' . $key .
'" does not exist. Ignored value.',
$this->loggerParams
);
}
}
}
}
}

View File

@ -14,11 +14,12 @@
namespace OCA\News\Controller;
use OCA\News\AppInfo\Application;
use OCP\AppFramework\Http\TemplateResponse;
use OCP\IConfig;
use OCP\IRequest;
use OCP\AppFramework\Controller;
use OCA\News\Config\Config;
use OCA\News\Service\ItemService;
/**
@ -28,8 +29,15 @@ use OCA\News\Service\ItemService;
*/
class AdminController extends Controller
{
/**
* @var IConfig
*/
private $config;
private $configPath;
/**
* @var ItemService
*/
private $itemService;
/**
@ -37,20 +45,17 @@ class AdminController extends Controller
*
* @param string $appName The name of the app
* @param IRequest $request The request
* @param Config $config Config for nextcloud
* @param IConfig $config Config for nextcloud
* @param ItemService $itemService Service for items
* @param string $configFile Path to the config
*/
public function __construct(
$appName,
string $appName,
IRequest $request,
Config $config,
ItemService $itemService,
$configFile
IConfig $config,
ItemService $itemService
) {
parent::__construct($appName, $request);
$this->config = $config;
$this->configPath = $configFile;
$this->itemService = $itemService;
}
@ -64,20 +69,23 @@ class AdminController extends Controller
*/
public function index()
{
$data = [
'autoPurgeMinimumInterval' =>
$this->config->getAutoPurgeMinimumInterval(),
'autoPurgeCount' => $this->config->getAutoPurgeCount(),
'maxRedirects' => $this->config->getMaxRedirects(),
'feedFetcherTimeout' => $this->config->getFeedFetcherTimeout(),
'useCronUpdates' => $this->config->getUseCronUpdates(),
'maxSize' => $this->config->getMaxSize(),
'exploreUrl' => $this->config->getExploreUrl(),
'updateInterval' => $this->config->getupdateInterval(),
];
return new TemplateResponse($this->appName, 'admin', $data, 'blank');
return new TemplateResponse($this->appName, 'admin', $this->getData(), 'blank');
}
private function getData()
{
$data = [];
foreach (array_keys(Application::DEFAULT_SETTINGS) as $setting) {
$data[$setting] = $this->config->getAppValue(
Application::NAME,
$setting,
Application::DEFAULT_SETTINGS[$setting]
);
}
return $data;
}
/**
* Update the app config.
@ -86,7 +94,6 @@ class AdminController extends Controller
* @param int $autoPurgeCount New value of auto-purge count
* @param int $maxRedirects New value for max amount of redirects
* @param int $feedFetcherTimeout New timeout value for feed fetcher
* @param int $maxSize New max feed size
* @param bool $useCronUpdates Whether or not to use cron updates
* @param string $exploreUrl URL to use for the explore feed
* @param int $updateInterval Interval in which the feeds will be updated
@ -94,35 +101,22 @@ class AdminController extends Controller
* @return array with the updated values
*/
public function update(
$autoPurgeMinimumInterval,
$autoPurgeCount,
$maxRedirects,
$feedFetcherTimeout,
$maxSize,
$useCronUpdates,
$exploreUrl,
$updateInterval
int $autoPurgeMinimumInterval,
int $autoPurgeCount,
int $maxRedirects,
int $feedFetcherTimeout,
bool $useCronUpdates,
string $exploreUrl,
int $updateInterval
) {
$this->config->setAutoPurgeMinimumInterval($autoPurgeMinimumInterval);
$this->config->setAutoPurgeCount($autoPurgeCount);
$this->config->setMaxRedirects($maxRedirects);
$this->config->setMaxSize($maxSize);
$this->config->setFeedFetcherTimeout($feedFetcherTimeout);
$this->config->setUseCronUpdates($useCronUpdates);
$this->config->setExploreUrl($exploreUrl);
$this->config->setUpdateInterval($updateInterval);
$this->config->write($this->configPath);
$this->config->setAppValue($this->appName, 'autoPurgeMinimumInterval', $autoPurgeMinimumInterval);
$this->config->setAppValue($this->appName, 'autoPurgeCount', $autoPurgeCount);
$this->config->setAppValue($this->appName, 'maxRedirects', $maxRedirects);
$this->config->setAppValue($this->appName, 'feedFetcherTimeout', $feedFetcherTimeout);
$this->config->setAppValue($this->appName, 'useCronUpdates', $useCronUpdates);
$this->config->setAppValue($this->appName, 'exploreUrl', $exploreUrl);
$this->config->setAppValue($this->appName, 'updateInterval', $updateInterval);
return [
'autoPurgeMinimumInterval' =>
$this->config->getAutoPurgeMinimumInterval(),
'autoPurgeCount' => $this->config->getAutoPurgeCount(),
'maxRedirects' => $this->config->getMaxRedirects(),
'maxSize' => $this->config->getMaxSize(),
'feedFetcherTimeout' => $this->config->getFeedFetcherTimeout(),
'useCronUpdates' => $this->config->getUseCronUpdates(),
'exploreUrl' => $this->config->getExploreUrl(),
'updateInterval' => $this->config->getUpdateInterval(),
];
return $this->getData();
}
}

View File

@ -13,6 +13,7 @@
namespace OCA\News\Controller;
use OCA\News\AppInfo\Application;
use OCP\IRequest;
use OCP\IConfig;
use OCP\IL10N;
@ -24,7 +25,6 @@ use OCP\AppFramework\Http;
use OCP\AppFramework\Http\ContentSecurityPolicy;
use OCA\News\Service\StatusService;
use OCA\News\Config\Config;
use OCA\News\Explore\RecommendedSites;
use OCA\News\Explore\RecommendedSiteNotFoundException;
use OCA\News\Db\FeedType;
@ -33,32 +33,51 @@ class PageController extends Controller
{
use JSONHttpError;
/**
* @var IConfig
*/
private $settings;
/**
* @var IL10N
*/
private $l10n;
/**
* @var string
*/
private $userId;
/**
* @var IURLGenerator
*/
private $urlGenerator;
private $config;
/**
* @var RecommendedSites
*/
private $recommendedSites;
/**
* @var StatusService
*/
private $statusService;
public function __construct(
$appName,
string $appName,
IRequest $request,
IConfig $settings,
IURLGenerator $urlGenerator,
Config $config,
IL10N $l10n,
RecommendedSites $recommendedSites,
StatusService $statusService,
$UserId
string $UserId
) {
parent::__construct($appName, $request);
$this->settings = $settings;
$this->urlGenerator = $urlGenerator;
$this->l10n = $l10n;
$this->userId = $UserId;
$this->config = $config;
$this->recommendedSites = $recommendedSites;
$this->statusService = $statusService;
}
@ -109,7 +128,11 @@ class PageController extends Controller
'compactExpand'
];
$exploreUrl = $this->config->getExploreUrl();
$exploreUrl = $this->settings->getAppValue(
$this->appName,
'exploreUrl',
Application::DEFAULT_SETTINGS['exploreUrl']
);
if (trim($exploreUrl) === '') {
// default url should not feature the sites.en.json
$exploreUrl = $this->urlGenerator->linkToRoute(
@ -142,28 +165,25 @@ class PageController extends Controller
* @param bool $compact
* @param bool $preventReadOnScroll
* @param bool $oldestFirst
* @param bool $compactExpand
*/
public function updateSettings(
$showAll,
$compact,
$preventReadOnScroll,
$oldestFirst,
$compactExpand
bool $showAll,
bool $compact,
bool $preventReadOnScroll,
bool $oldestFirst,
bool $compactExpand
) {
$settings = [
'showAll',
'compact',
'preventReadOnScroll',
'oldestFirst',
'compactExpand'
'showAll' => $showAll,
'compact' => $compact,
'preventReadOnScroll' => $preventReadOnScroll,
'oldestFirst' => $oldestFirst,
'compactExpand' => $compactExpand,
];
foreach ($settings as $setting) {
if (${$setting}) {
$value = '1';
} else {
$value = '0';
}
foreach ($settings as $setting => $value) {
$value = $value ? '1' : '0';
$this->settings->setUserValue(
$this->userId,
$this->appName,
@ -178,7 +198,7 @@ class PageController extends Controller
*
* @param string $lang
*/
public function explore($lang)
public function explore(string $lang)
{
$this->settings->setUserValue(
$this->userId,

View File

@ -13,15 +13,16 @@ namespace OCA\News\Cron;
use OC\BackgroundJob\TimedJob;
use OCA\News\Config\Config;
use OCA\News\AppInfo\Application;
use OCA\News\Service\StatusService;
use OCA\News\Utility\Updater as UpdaterService;
use OCP\IConfig;
class Updater extends TimedJob
{
/**
* @var Config
* @var IConfig
*/
private $config;
/**
@ -34,7 +35,7 @@ class Updater extends TimedJob
private $updaterService;
public function __construct(
Config $config,
IConfig $config,
StatusService $status,
UpdaterService $updaterService
) {
@ -42,14 +43,24 @@ class Updater extends TimedJob
$this->status = $status;
$this->updaterService = $updaterService;
parent::setInterval($this->config->getUpdateInterval());
$interval = $this->config->getAppValue(
Application::NAME,
'updateInterval',
Application::DEFAULT_SETTINGS['updateInterval']
);
parent::setInterval($interval);
}
protected function run($argument)
{
if ($this->config->getUseCronUpdates()
&& $this->status->isProperlyConfigured()
) {
$uses_cron = $this->config->getAppValue(
Application::NAME,
'useCronUpdates',
Application::DEFAULT_SETTINGS['useCronUpdates']
);
if ($uses_cron && $this->status->isProperlyConfigured()) {
$this->updaterService->beforeUpdate();
$this->updaterService->update();
$this->updaterService->afterUpdate();

View File

@ -27,6 +27,7 @@ use OCA\News\Db\Item;
use OCA\News\Db\Feed;
use OCA\News\Utility\Time;
use OCA\News\Scraper\Scraper;
use Psr\Log\LoggerInterface;
use SimpleXMLElement;
class FeedFetcher implements IFeedFetcher
@ -44,7 +45,7 @@ class FeedFetcher implements IFeedFetcher
Favicon $favicon,
IL10N $l10n,
Time $time,
PsrLogger $logger,
LoggerInterface $logger,
Scraper $scraper
) {
$this->reader = $fetcher;

View File

@ -0,0 +1,59 @@
<?php
/**
* Nextcloud - News
*
* This file is licensed under the Affero General Public License version 3 or
* later. See the COPYING file.
*
* @author Sean Molenaar
* @copyright Sean Molenaar <sean@seanmolenaar.eu> 2020
*/
namespace OCA\News\Migration;
use OCA\News\AppInfo\Application;
use OCA\News\Config\LegacyConfig;
use OCP\IConfig;
use OCP\Migration\IRepairStep;
use OCP\Migration\IOutput;
class MigrateConfig implements IRepairStep
{
/**
* @var LegacyConfig
*/
private $config;
/**
* @var IConfig
*/
private $iConfig;
/**
* @param LegacyConfig $config
* @param IConfig $iConfig
*/
public function __construct(LegacyConfig $config, IConfig $iConfig)
{
$this->config = $config;
$this->iConfig = $iConfig;
}
public function getName()
{
return 'Migrate config to nextcloud managed config';
}
public function run(IOutput $output)
{
$version = $this->iConfig->getAppValue('news', 'installed_version', '0.0.0');
if (version_compare($version, '15.0.0', '>')) {
return;
}
foreach ($this->config as $key => $value) {
$this->iConfig->setAppValue(Application::NAME, $key, $value);
}
}
}

View File

@ -11,11 +11,10 @@
namespace OCA\News\Scraper;
use OCA\News\Utility\PsrLogger;
use andreskrey\Readability\Readability;
use andreskrey\Readability\Configuration;
use andreskrey\Readability\ParseException;
use Psr\Log\LoggerInterface;
class Scraper implements IScraper
{
@ -24,7 +23,7 @@ class Scraper implements IScraper
private $readability;
private $curl_opts;
public function __construct(PsrLogger $logger)
public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;
$this->config = new Configuration([

View File

@ -16,6 +16,8 @@ namespace OCA\News\Service;
use FeedIo\Reader\ReadErrorException;
use HTMLPurifier;
use OCA\News\AppInfo\Application;
use OCP\IConfig;
use OCP\ILogger;
use OCP\IL10N;
use OCP\AppFramework\Db\DoesNotExistException;
@ -25,7 +27,6 @@ use OCA\News\Db\Item;
use OCA\News\Db\FeedMapper;
use OCA\News\Db\ItemMapper;
use OCA\News\Fetcher\Fetcher;
use OCA\News\Config\Config;
use OCA\News\Utility\Time;
class FeedService extends Service
@ -48,9 +49,8 @@ class FeedService extends Service
ILogger $logger,
IL10N $l10n,
Time $timeFactory,
Config $config,
HTMLPurifier $purifier,
$LoggerParameters
IConfig $config,
HTMLPurifier $purifier
) {
parent::__construct($feedMapper);
$this->feedFetcher = $feedFetcher;
@ -58,11 +58,14 @@ class FeedService extends Service
$this->logger = $logger;
$this->l10n = $l10n;
$this->timeFactory = $timeFactory;
$this->autoPurgeMinimumInterval = $config->getAutoPurgeMinimumInterval(
$this->autoPurgeMinimumInterval = $config->getAppValue(
Application::NAME,
'autoPurgeMinimumInterval',
Application::DEFAULT_SETTINGS['autoPurgeMinimumInterval']
);
$this->purifier = $purifier;
$this->feedMapper = $feedMapper;
$this->loggerParams = $LoggerParameters;
$this->loggerParams = ['app' => Application::NAME];
}
/**

View File

@ -13,10 +13,11 @@
namespace OCA\News\Service;
use OCA\News\AppInfo\Application;
use OCP\IConfig;
use OCP\IL10N;
use OCA\News\Db\Folder;
use OCA\News\Db\FolderMapper;
use OCA\News\Config\Config;
use OCA\News\Utility\Time;
class FolderService extends Service
@ -31,13 +32,16 @@ class FolderService extends Service
FolderMapper $folderMapper,
IL10N $l10n,
Time $timeFactory,
Config $config
IConfig $config
) {
parent::__construct($folderMapper);
$this->l10n = $l10n;
$this->timeFactory = $timeFactory;
$this->autoPurgeMinimumInterval =
$config->getAutoPurgeMinimumInterval();
$this->autoPurgeMinimumInterval = $config->getAppValue(
Application::NAME,
'autoPurgeMinimumInterval',
Application::DEFAULT_SETTINGS['autoPurgeMinimumInterval']
);
$this->folderMapper = $folderMapper;
}
@ -91,6 +95,7 @@ class FolderService extends Service
$folder->setUserId($userId);
$folder->setParentId($parentId);
$folder->setOpened(true);
return $this->folderMapper->insert($folder);
}
@ -123,6 +128,7 @@ class FolderService extends Service
$folder = $this->find($folderId, $userId);
$folder->setName($folderName);
return $this->folderMapper->update($folder);
}
@ -160,7 +166,7 @@ class FolderService extends Service
/**
* Deletes all deleted folders
*
* @param string $userId if given it purges only folders of that user
* @param ?string $userId if given it purges only folders of that user
* @param boolean $useInterval defaults to true, if true it only purges
* entries in a given interval to give the user a chance to undo the
* deletion

View File

@ -13,13 +13,13 @@
namespace OCA\News\Service;
use OCA\News\AppInfo\Application;
use OCA\News\Db\Item;
use OCP\IConfig;
use OCP\AppFramework\Db\DoesNotExistException;
use OCA\News\Db\ItemMapper;
use OCA\News\Db\FeedType;
use OCA\News\Config\Config;
use OCA\News\Utility\Time;
class ItemService extends Service
@ -28,19 +28,16 @@ class ItemService extends Service
private $config;
private $timeFactory;
private $itemMapper;
private $systemConfig;
public function __construct(
ItemMapper $itemMapper,
Time $timeFactory,
Config $config,
IConfig $systemConfig
IConfig $config
) {
parent::__construct($itemMapper);
$this->config = $config;
$this->timeFactory = $timeFactory;
$this->itemMapper = $itemMapper;
$this->systemConfig = $systemConfig;
$this->config = $config;
}
@ -255,7 +252,11 @@ class ItemService extends Service
*/
public function autoPurgeOld()
{
$count = $this->config->getAutoPurgeCount();
$count = $this->config->getAppValue(
Application::NAME,
'autoPurgeCount',
Application::DEFAULT_SETTINGS['autoPurgeCount']
);
if ($count >= 0) {
$this->itemMapper->deleteReadOlderThanThreshold($count);
}

View File

@ -13,17 +13,14 @@
namespace OCA\News\Service;
use OCA\News\AppInfo\Application;
use OCP\IConfig;
use OCP\IDBConnection;
use OCA\News\Config\Config;
class StatusService
{
/** @var IConfig */
private $settings;
/** @var Config */
private $config;
/** @var string */
private $appName;
/** @var IDBConnection */
@ -32,22 +29,21 @@ class StatusService
public function __construct(
IConfig $settings,
IDBConnection $connection,
Config $config,
$AppName
) {
$this->settings = $settings;
$this->config = $config;
$this->appName = $AppName;
$this->connection = $connection;
}
public function isProperlyConfigured()
{
$cronMode = $this->settings->getAppValue(
'core',
'backgroundjobs_mode'
$cronMode = $this->settings->getSystemValue('backgroundjobs_mode');
$cronOff = !$this->settings->getAppValue(
Application::NAME,
'useCronUpdates',
Application::DEFAULT_SETTINGS['useCronUpdates']
);
$cronOff = !$this->config->getUseCronUpdates();
// check for cron modes which may lead to problems
return $cronMode === 'cron' || $cronOff;

View File

@ -1,44 +0,0 @@
<?php
namespace OCA\News\Settings;
use OCP\AppFramework\Http\TemplateResponse;
use OCP\Settings\ISettings;
use OCA\News\Config\Config;
class Admin implements ISettings
{
private $config;
public function __construct(Config $config)
{
$this->config = $config;
}
public function getForm()
{
$data = [
'autoPurgeMinimumInterval' =>
$this->config->getAutoPurgeMinimumInterval(),
'autoPurgeCount' => $this->config->getAutoPurgeCount(),
'maxRedirects' => $this->config->getMaxRedirects(),
'feedFetcherTimeout' => $this->config->getFeedFetcherTimeout(),
'useCronUpdates' => $this->config->getUseCronUpdates(),
'maxSize' => $this->config->getMaxSize(),
'exploreUrl' => $this->config->getExploreUrl(),
'updateInterval' => $this->config->getUpdateInterval(),
];
return new TemplateResponse('news', 'admin', $data, '');
}
public function getSection()
{
return 'news';
}
public function getPriority()
{
return 40;
}
}

View File

@ -0,0 +1,47 @@
<?php
namespace OCA\News\Settings;
use OCA\News\AppInfo\Application;
use OCP\AppFramework\Http\TemplateResponse;
use OCP\IConfig;
use OCP\Settings\ISettings;
class AdminSettings implements ISettings
{
/**
* @var IConfig
*/
private $config;
public function __construct(IConfig $config)
{
$this->config = $config;
}
public function getForm()
{
$data = [];
foreach (array_keys(Application::DEFAULT_SETTINGS) as $setting) {
$data[$setting] = $this->config->getAppValue(
Application::NAME,
$setting,
Application::DEFAULT_SETTINGS[$setting]
);
}
return new TemplateResponse(Application::NAME, 'admin', $data);
}
public function getSection()
{
return 'news';
}
public function getPriority()
{
return 40;
}
}

View File

@ -1,97 +0,0 @@
<?php
/**
* Nextcloud - News
*
* This file is licensed under the Affero General Public License version 3 or
* later. See the COPYING file.
*
* @author Sean Molenaar <sean@seanmolenaar.eu>
* @copyright 2018 Sean Molenaar
*/
namespace OCA\News\Utility;
use \OCP\ILogger;
/**
* This is a wrapper to make OC\Log conform to Psr\Log\LoggerInterface
*
* @package OCA\News\Utility
*/
class PsrLogger implements \Psr\Log\LoggerInterface
{
private $logger;
private $appName;
/**
* PsrLogger constructor.
*
* @param ILogger $logger The logger
* @param string $appName Name of the app
*/
public function __construct(ILogger $logger, $appName)
{
$this->logger = $logger;
$this->appName = $appName;
}
public function logException($exception, array $context = [])
{
$context['app'] = $this->appName;
$this->logger->logException($exception, $context);
}
public function emergency($message, array $context = [])
{
$context['app'] = $this->appName;
$this->logger->emergency($message, $context);
}
public function alert($message, array $context = [])
{
$context['app'] = $this->appName;
$this->logger->alert($message, $context);
}
public function critical($message, array $context = [])
{
$context['app'] = $this->appName;
$this->logger->critical($message, $context);
}
public function error($message, array $context = [])
{
$context['app'] = $this->appName;
$this->logger->error($message, $context);
}
public function warning($message, array $context = [])
{
$context['app'] = $this->appName;
$this->logger->warning($message, $context);
}
public function notice($message, array $context = [])
{
$context['app'] = $this->appName;
$this->logger->notice($message, $context);
}
public function info($message, array $context = [])
{
$context['app'] = $this->appName;
$this->logger->info($message, $context);
}
public function debug($message, array $context = [])
{
$context['app'] = $this->appName;
$this->logger->debug($message, $context);
}
public function log($level, $message, array $context = [])
{
$context['app'] = $this->appName;
$this->logger->log($level, $message, $context);
}
}

View File

@ -21,9 +21,19 @@ use \OCA\News\Service\ItemService;
class Updater
{
/**
* @var FolderService
*/
private $folderService;
/**
* @var FeedService
*/
private $feedService;
/**
* @var ItemService
*/
private $itemService;
public function __construct(

View File

@ -70,23 +70,6 @@ style('news', 'admin');
<p><input type="text" name="news-max-redirects"
value="<?php p($_['maxRedirects']); ?>"></p>
</div>
<div class="form-line">
<p>
<label for="news-max-size">
<?php p($l->t('Maximum feed page size')); ?>
</label>
</p>
<p>
<em>
<?php p($l->t(
'Maximum feed size in bytes. If the RSS/Atom page is ' .
'bigger than this value, the update will be aborted.'
)); ?>
</em>
</p>
<p><input type="text" name="news-max-size"
value="<?php p($_['maxSize']); ?>"></p>
</div>
<div class="form-line">
<p>
<label for="news-feed-fetcher-timeout">

View File

@ -20,7 +20,7 @@ use OCA\News\Tests\Integration\Fixtures\FeedFixture;
class FeedMapperTest extends IntegrationTest
{
public function testFind()
public function testFind()
{
$feed = new FeedFixture();
$feed = $this->feedMapper->insert($feed);
@ -31,16 +31,14 @@ class FeedMapperTest extends IntegrationTest
$this->assertEquals($feed->getLink(), $fetched->getLink());
}
/**
* @expectedException OCP\AppFramework\Db\DoesNotExistException
*/
public function testFindNotExisting()
public function testFindNotExisting()
{
$this->expectException('OCP\AppFramework\Db\DoesNotExistException');
$this->feedMapper->find(0, $this->user);
}
public function testFindAll()
public function testFindAll()
{
$feeds = [
[
@ -56,23 +54,23 @@ class FeedMapperTest extends IntegrationTest
$fetched = $this->feedMapper->findAll();
$this->assertInternalType('array', $fetched);
$this->assertIsArray($fetched);
$this->assertCount(2, $fetched);
$this->assertContainsOnlyInstancesOf(Feed::class, $fetched);
$this->tearDownUser('john');
}
public function testFindAllEmpty()
public function testFindAllEmpty()
{
$feeds = $this->feedMapper->findAll();
$this->assertInternalType('array', $feeds);
$this->assertIsArray($feeds);
$this->assertCount(0, $feeds);
}
public function testFindAllFromUser()
public function testFindAllFromUser()
{
$feeds = [
[
@ -88,7 +86,7 @@ class FeedMapperTest extends IntegrationTest
$fetched = $this->feedMapper->findAllFromUser($this->user);
$this->assertInternalType('array', $fetched);
$this->assertIsArray($fetched);
$this->assertCount(1, $fetched);
$this->assertContainsOnlyInstancesOf(Feed::class, $fetched);
@ -96,16 +94,16 @@ class FeedMapperTest extends IntegrationTest
}
public function testFindAllFromUserNotExisting()
public function testFindAllFromUserNotExisting()
{
$fetched = $this->feedMapper->findAllFromUser('notexistinguser');
$this->assertInternalType('array', $fetched);
$this->assertIsArray($fetched);
$this->assertCount(0, $fetched);
}
public function testFindByUrlHash()
public function testFindByUrlHash()
{
$feed = new FeedFixture(
[
@ -124,8 +122,9 @@ class FeedMapperTest extends IntegrationTest
/**
* @expectedException OCP\AppFramework\Db\MultipleObjectsReturnedException
*/
public function testFindByUrlHashMoreThanOneResult()
public function testFindByUrlHashMoreThanOneResult()
{
$this->expectException('OCP\AppFramework\Db\MultipleObjectsReturnedException');
$feed1 = $this->feedMapper->insert(
new FeedFixture(
[
@ -148,13 +147,14 @@ class FeedMapperTest extends IntegrationTest
/**
* @expectedException OCP\AppFramework\Db\DoesNotExistException
*/
public function testFindByUrlHashNotExisting()
public function testFindByUrlHashNotExisting()
{
$this->expectException('OCP\AppFramework\Db\DoesNotExistException');
$this->feedMapper->findByUrlHash('some random hash', $this->user);
}
public function testDelete()
public function testDelete()
{
$this->loadFixtures('default');
@ -178,7 +178,7 @@ class FeedMapperTest extends IntegrationTest
$this->assertCount(0, $items);
}
public function testGetToDelete()
public function testGetToDelete()
{
$this->loadFeedFixtures(
[
@ -191,14 +191,14 @@ class FeedMapperTest extends IntegrationTest
$fetched = $this->feedMapper->getToDelete();
$this->assertInternalType('array', $fetched);
$this->assertIsArray($fetched);
$this->assertCount(3, $fetched);
$this->assertContainsOnlyInstancesOf(Feed::class, $fetched);
$this->tearDownUser('john');
}
public function testGetToDeleteOlderThan()
public function testGetToDeleteOlderThan()
{
$this->loadFeedFixtures(
[
@ -211,14 +211,14 @@ class FeedMapperTest extends IntegrationTest
$fetched = $this->feedMapper->getToDelete(1000);
$this->assertInternalType('array', $fetched);
$this->assertIsArray($fetched);
$this->assertCount(2, $fetched);
$this->assertContainsOnlyInstancesOf(Feed::class, $fetched);
$this->tearDownUser('john');
}
public function testGetToDeleteUser()
public function testGetToDeleteUser()
{
$this->loadFeedFixtures(
[
@ -231,22 +231,22 @@ class FeedMapperTest extends IntegrationTest
$fetched = $this->feedMapper->getToDelete(2000, $this->user);
$this->assertInternalType('array', $fetched);
$this->assertIsArray($fetched);
$this->assertCount(2, $fetched);
$this->assertContainsOnlyInstancesOf(Feed::class, $fetched);
$this->tearDownUser('john');
}
public function testGetToDeleteEmpty()
public function testGetToDeleteEmpty()
{
$fetched = $this->feedMapper->getToDelete();
$this->assertInternalType('array', $fetched);
$this->assertIsArray($fetched);
$this->assertCount(0, $fetched);
}
public function testDeleteUser()
public function testDeleteUser()
{
$this->loadFixtures('default');
@ -263,7 +263,10 @@ class FeedMapperTest extends IntegrationTest
$this->assertCount(0, $items);
}
public function testDeleteUserNotExisting()
/**
* @coversNothing
*/
public function testDeleteUserNotExisting()
{
$this->feedMapper->deleteUser('notexistinguser');
}

View File

@ -1,53 +0,0 @@
<?php
/**
* Nextcloud - News
*
* This file is licensed under the Affero General Public License version 3 or
* later. See the COPYING file.
*
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright Bernhard Posselt 2015
*/
namespace OCA\News\Tests\Integration\Db;
use OCA\News\Tests\Integration\IntegrationTest;
class FolderMapperTest extends IntegrationTest
{
public function testFind()
{
}
/* TBD
public function testFindByName () {
}
public function testFindAllFromUser () {
}
public function testDelete () {
}
public function testGetToDelete () {
}
public function testDeleteUser () {
}*/
}

View File

@ -18,7 +18,7 @@ use OCA\News\Tests\Integration\Fixtures\ItemFixture;
class ItemMapperTest extends IntegrationTest
{
public function testFind()
public function testFind()
{
$feed = new FeedFixture();
$feed = $this->feedMapper->insert($feed);
@ -38,7 +38,7 @@ class ItemMapperTest extends IntegrationTest
* @param $title
* @return mixed
*/
private function whereTitleId($title)
private function whereTitleId($title)
{
return $this->findItemByTitle($title)->getId();
}
@ -46,8 +46,9 @@ class ItemMapperTest extends IntegrationTest
/**
* @expectedException OCP\AppFramework\Db\DoesNotExistException
*/
public function testFindNotFoundWhenDeletedFeed()
public function testFindNotFoundWhenDeletedFeed()
{
$this->expectException('OCP\AppFramework\Db\DoesNotExistException');
$this->loadFixtures('default');
$id = $this->whereTitleId('not found feed');
@ -58,8 +59,9 @@ class ItemMapperTest extends IntegrationTest
/**
* @expectedException OCP\AppFramework\Db\DoesNotExistException
*/
public function testFindNotFoundWhenDeletedFolder()
public function testFindNotFoundWhenDeletedFolder()
{
$this->expectException('OCP\AppFramework\Db\DoesNotExistException');
$this->loadFixtures('default');
@ -68,7 +70,7 @@ class ItemMapperTest extends IntegrationTest
}
private function deleteReadOlderThanThreshold()
private function deleteReadOlderThanThreshold()
{
$this->loadFixtures('default');
@ -84,8 +86,9 @@ class ItemMapperTest extends IntegrationTest
/**
* @expectedException OCP\AppFramework\Db\DoesNotExistException
*/
public function testDeleteOlderThanThresholdOne()
public function testDeleteOlderThanThresholdOne()
{
$this->expectException('OCP\AppFramework\Db\DoesNotExistException');
$this->loadFixtures('default');
$id = $this->whereTitleId('del1');
@ -97,8 +100,9 @@ class ItemMapperTest extends IntegrationTest
/**
* @expectedException OCP\AppFramework\Db\DoesNotExistException
*/
public function testDeleteOlderThanThresholdTwo()
public function testDeleteOlderThanThresholdTwo()
{
$this->expectException('OCP\AppFramework\Db\DoesNotExistException');
$this->loadFixtures('default');
$id = $this->whereTitleId('del2');
@ -108,7 +112,7 @@ class ItemMapperTest extends IntegrationTest
}
public function testStarredCount()
public function testStarredCount()
{
$this->loadFixtures('default');
@ -117,7 +121,7 @@ class ItemMapperTest extends IntegrationTest
}
public function testReadAll()
public function testReadAll()
{
$this->loadFixtures('default');
@ -146,7 +150,7 @@ class ItemMapperTest extends IntegrationTest
}
public function testReadFolder()
public function testReadFolder()
{
$this->loadFixtures('default');
@ -178,7 +182,7 @@ class ItemMapperTest extends IntegrationTest
}
public function testReadFeed()
public function testReadFeed()
{
$this->loadFixtures('default');
@ -209,7 +213,7 @@ class ItemMapperTest extends IntegrationTest
}
public function testDeleteUser()
public function testDeleteUser()
{
$this->loadFixtures('default');
@ -219,7 +223,7 @@ class ItemMapperTest extends IntegrationTest
$this->assertEquals(0, $id);
}
public function testGetNewestItemId()
public function testGetNewestItemId()
{
$this->loadFixtures('default');
@ -229,7 +233,7 @@ class ItemMapperTest extends IntegrationTest
$this->assertEquals($itemId, $id);
}
public function testFindAllUnreadOrStarred()
public function testFindAllUnreadOrStarred()
{
$this->loadFixtures('default');
@ -238,7 +242,7 @@ class ItemMapperTest extends IntegrationTest
}
public function testReadItem()
public function testReadItem()
{
$this->loadFixtures('readitem');
// assert that all items are unread
@ -277,7 +281,7 @@ class ItemMapperTest extends IntegrationTest
}
}
public function testUnreadItem()
public function testUnreadItem()
{
$this->loadFixtures('readitem');
// unread an item

View File

@ -1,261 +0,0 @@
<?php
/**
* Nextcloud - News
*
* This file is licensed under the Affero General Public License version 3 or
* later. See the COPYING file.
*
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Tests\Unit\Config;
use OCA\News\Config\Config;
use OCP\Files\File;
use OCP\Files\Folder;
use OCP\ILogger;
use PHPUnit\Framework\TestCase;
class ConfigTest extends TestCase
{
private $fileSystem;
private $config;
private $configPath;
private $loggerParams;
public function setUp()
{
$this->logger = $this->getMockBuilder('OCA\News\Utility\PsrLogger')
->disableOriginalConstructor()
->getMock();
$this->fileSystem = $this->getMockBuilder(Folder::class)->getMock();
$this->loggerParams = ['hi'];
$this->config = new Config(
$this->fileSystem,
$this->logger,
$this->loggerParams
);
$this->configPath = 'config.json';
}
public function testDefaults()
{
$this->assertEquals(60, $this->config->getAutoPurgeMinimumInterval());
$this->assertEquals(200, $this->config->getAutoPurgeCount());
$this->assertEquals(10, $this->config->getMaxRedirects());
$this->assertEquals(60, $this->config->getFeedFetcherTimeout());
$this->assertEquals(3600, $this->config->getUpdateInterval());
$this->assertEquals(true, $this->config->getUseCronUpdates());
$this->assertEquals('', $this->config->getExploreUrl());
$this->assertEquals(1024*1024*100, $this->config->getMaxSize());
}
public function testRead()
{
$file = $this->getMockBuilder(File::class)->getMock();
$this->fileSystem->expects($this->once())
->method('get')
->with($this->equalTo($this->configPath))
->will($this->returnValue($file));
$file->expects($this->once())
->method('getContent')
->will(
$this->returnValue(
'autoPurgeCount = 3' . "\n" . 'useCronUpdates = true'
)
);
$this->config->read($this->configPath);
$this->assertSame(3, $this->config->getAutoPurgeCount());
$this->assertSame(true, $this->config->getUseCronUpdates());
}
public function testReadIgnoresVeryLowPurgeInterval()
{
$file = $this->getMockBuilder(File::class)->getMock();
$this->fileSystem->expects($this->once())
->method('get')
->with($this->equalTo($this->configPath))
->will($this->returnValue($file));
$file->expects($this->once())
->method('getContent')
->will($this->returnValue('autoPurgeMinimumInterval = 59'));
$this->config->read($this->configPath);
$this->assertSame(60, $this->config->getAutoPurgeMinimumInterval());
}
public function testReadBool()
{
$file = $this->getMockBuilder(File::class)->getMock();
$this->fileSystem->expects($this->once())
->method('get')
->with($this->equalTo($this->configPath))
->will($this->returnValue($file));
$file->expects($this->once())
->method('getContent')
->will(
$this->returnValue(
'autoPurgeCount = 3' . "\n" . 'useCronUpdates = false'
)
);
$this->config->read($this->configPath);
$this->assertSame(3, $this->config->getAutoPurgeCount());
$this->assertSame(false, $this->config->getUseCronUpdates());
}
public function testReadLogsInvalidValue()
{
$file = $this->getMockBuilder(File::class)->getMock();
$this->fileSystem->expects($this->once())
->method('get')
->with($this->equalTo($this->configPath))
->will($this->returnValue($file));
$file->expects($this->once())
->method('getContent')
->will($this->returnValue('autoPurgeCounts = 3'));
$this->logger->expects($this->once())
->method('warning')
->with(
$this->equalTo(
'Configuration value "autoPurgeCounts" ' .
'does not exist. Ignored value.'
),
$this->equalTo($this->loggerParams)
);
$this->config->read($this->configPath);
}
public function testReadLogsInvalidINI()
{
$file = $this->getMockBuilder(File::class)->getMock();
$this->fileSystem->expects($this->once())
->method('get')
->with($this->equalTo($this->configPath))
->will($this->returnValue($file));
$file->expects($this->once())
->method('getContent')
->will($this->returnValue(''));
$this->logger->expects($this->once())
->method('warning')
->with(
$this->equalTo('Configuration invalid. Ignoring values.'),
$this->equalTo($this->loggerParams)
);
$this->config->read($this->configPath);
}
public function testWrite()
{
$json = 'autoPurgeMinimumInterval = 60' . "\n" .
'autoPurgeCount = 3' . "\n" .
'maxRedirects = 10' . "\n" .
'maxSize = 399' . "\n" .
'exploreUrl = http://google.de' . "\n" .
'feedFetcherTimeout = 60' . "\n" .
'updateInterval = 3600' . "\n" .
'useCronUpdates = true';
$this->config->setAutoPurgeCount(3);
$this->config->setMaxSize(399);
$this->config->setExploreUrl('http://google.de');
$file = $this->getMockBuilder(File::class)->getMock();
$this->fileSystem->expects($this->once())
->method('get')
->with($this->equalTo($this->configPath))
->will($this->returnValue($file));
$file->expects($this->once())
->method('putContent')
->with($this->equalTo($json));
$this->config->write($this->configPath);
}
public function testReadingNonExistentConfigWillWriteDefaults()
{
$this->fileSystem->expects($this->once())
->method('nodeExists')
->with($this->equalTo($this->configPath))
->will($this->returnValue(false));
$this->config->setUseCronUpdates(false);
$json = 'autoPurgeMinimumInterval = 60' . "\n" .
'autoPurgeCount = 200' . "\n" .
'maxRedirects = 10' . "\n" .
'maxSize = 104857600' . "\n" .
'exploreUrl = ' . "\n" .
'feedFetcherTimeout = 60' . "\n" .
'updateInterval = 3600' . "\n" .
'useCronUpdates = false';
$this->fileSystem->expects($this->once())
->method('newFile')
->with($this->equalTo($this->configPath));
$file = $this->getMockBuilder(File::class)->getMock();
$this->fileSystem->expects($this->once())
->method('get')
->with($this->equalTo($this->configPath))
->will($this->returnValue($file));
$file->expects($this->once())
->method('putContent')
->with($this->equalTo($json));
$this->config->read($this->configPath, true);
}
public function testNoLowMinimumAutoPurgeInterval()
{
$this->config->setAutoPurgeMinimumInterval(59);
$interval = $this->config->getAutoPurgeMinimumInterval();
$this->assertSame(60, $interval);
}
public function testMinimumAutoPurgeInterval()
{
$this->config->setAutoPurgeMinimumInterval(61);
$interval = $this->config->getAutoPurgeMinimumInterval();
$this->assertSame(61, $interval);
}
public function testMaxRedirects()
{
$this->config->setMaxRedirects(21);
$redirects = $this->config->getMaxRedirects();
$this->assertSame(21, $redirects);
}
public function testFeedFetcherTimeout()
{
$this->config->setFeedFetcherTimeout(2);
$timout = $this->config->getFeedFetcherTimeout();
$this->assertSame(2, $timout);
}
}

View File

@ -13,82 +13,84 @@
namespace OCA\News\Tests\Unit\Controller;
use OCA\News\Config\Config;
use OCA\News\Controller\AdminController;
use OCA\News\Service\ItemService;
use OCP\IConfig;
use OCP\IRequest;
use PHPUnit\Framework\TestCase;
class AdminControllerTest extends TestCase
{
/**
* @var string
*/
private $appName;
/**
* @var \PHPUnit\Framework\MockObject\MockObject|IRequest
*/
private $request;
/**
* @var AdminController
*/
private $controller;
/**
* @var \PHPUnit\Framework\MockObject\MockObject|IConfig
*/
private $config;
private $configPath;
/**
* @var \PHPUnit\Framework\MockObject\MockObject|ItemService
*/
private $itemService;
/**
* Gets run before each test
*/
public function setUp()
public function setUp(): void
{
$this->appName = 'news';
$this->request = $this->getMockBuilder(IRequest::class)
->disableOriginalConstructor()
->getMock();
$this->config = $this->getMockBuilder(Config::class)
$this->config = $this->getMockBuilder(IConfig::class)
->disableOriginalConstructor()
->getMock();
$this->itemService = $this->getMockBuilder(ItemService::class)
->disableOriginalConstructor()
->getMock();
$this->configPath = 'my.ini';
$this->controller = new AdminController(
$this->appName, $this->request,
$this->config, $this->itemService, $this->configPath
);
$this->controller = new AdminController($this->appName, $this->request, $this->config, $this->itemService);
}
public function testIndex()
/**
* Test \OCA\News\Controller\AdminController::index
*/
public function testIndex()
{
$expected = [
'autoPurgeMinimumInterval' => 1,
'autoPurgeCount' => 2,
'maxRedirects' => 3,
'feedFetcherTimeout' => 4,
'useCronUpdates' => 5,
'maxSize' => 7,
'useCronUpdates' => false,
'exploreUrl' => 'test',
'updateInterval' => 3600
'updateInterval' => 3601
];
$this->config->expects($this->once())
->method('getAutoPurgeMinimumInterval')
->will($this->returnValue($expected['autoPurgeMinimumInterval']));
$this->config->expects($this->once())
->method('getAutoPurgeCount')
->will($this->returnValue($expected['autoPurgeCount']));
$this->config->expects($this->once())
->method('getMaxRedirects')
->will($this->returnValue($expected['maxRedirects']));
$this->config->expects($this->once())
->method('getFeedFetcherTimeout')
->will($this->returnValue($expected['feedFetcherTimeout']));
$this->config->expects($this->once())
->method('getUseCronUpdates')
->will($this->returnValue($expected['useCronUpdates']));
$this->config->expects($this->once())
->method('getMaxSize')
->will($this->returnValue($expected['maxSize']));
$this->config->expects($this->once())
->method('getExploreUrl')
->will($this->returnValue($expected['exploreUrl']));
$this->config->expects($this->once())
->method('getUpdateInterval')
->will($this->returnValue($expected['updateInterval']));
$map = [
['news','autoPurgeMinimumInterval', 60, 1],
['news','autoPurgeCount', 200, 2],
['news','maxRedirects', 10, 3],
['news','feedFetcherTimeout', 60, 4],
['news','useCronUpdates', true, false,],
['news','exploreUrl', '', 'test'],
['news','updateInterval', 3600, 3601]
];
$this->config->expects($this->exactly(count($map)))
->method('getAppValue')
->will($this->returnValueMap($map));
$response = $this->controller->index();
$data = $response->getParams();
@ -101,75 +103,48 @@ class AdminControllerTest extends TestCase
}
public function testUpdate()
public function testUpdate()
{
$expected = [
'autoPurgeMinimumInterval' => 1,
'autoPurgeCount' => 2,
'maxRedirects' => 3,
'feedFetcherTimeout' => 4,
'useCronUpdates' => 5,
'maxSize' => 7,
'useCronUpdates' => false,
'exploreUrl' => 'test',
'updateInterval' => 3600
'updateInterval' => 3601
];
$this->config->expects($this->once())
->method('setAutoPurgeMinimumInterval')
->with($this->equalTo($expected['autoPurgeMinimumInterval']));
$this->config->expects($this->once())
->method('setAutoPurgeCount')
->with($this->equalTo($expected['autoPurgeCount']));
$this->config->expects($this->once())
->method('setMaxRedirects')
->with($this->equalTo($expected['maxRedirects']));
$this->config->expects($this->once())
->method('setFeedFetcherTimeout')
->with($this->equalTo($expected['feedFetcherTimeout']));
$this->config->expects($this->once())
->method('setUseCronUpdates')
->with($this->equalTo($expected['useCronUpdates']));
$this->config->expects($this->once())
->method('setExploreUrl')
->with($this->equalTo($expected['exploreUrl']));
$this->config->expects($this->once())
->method('setUpdateInterval')
->with($this->equalTo($expected['updateInterval']));
$this->config->expects($this->once())
->method('write')
->with($this->equalTo($this->configPath));
$this->config->expects($this->exactly(count($expected)))
->method('setAppValue')
->withConsecutive(
['news','autoPurgeMinimumInterval', 1],
['news','autoPurgeCount', 2],
['news','maxRedirects', 3],
['news','feedFetcherTimeout', 4],
['news','useCronUpdates', false],
['news','exploreUrl', 'test'],
['news','updateInterval', 3601]
);
$this->config->expects($this->once())
->method('getAutoPurgeMinimumInterval')
->will($this->returnValue($expected['autoPurgeMinimumInterval']));
$this->config->expects($this->once())
->method('getAutoPurgeCount')
->will($this->returnValue($expected['autoPurgeCount']));
$this->config->expects($this->once())
->method('getMaxRedirects')
->will($this->returnValue($expected['maxRedirects']));
$this->config->expects($this->once())
->method('getFeedFetcherTimeout')
->will($this->returnValue($expected['feedFetcherTimeout']));
$this->config->expects($this->once())
->method('getUseCronUpdates')
->will($this->returnValue($expected['useCronUpdates']));
$this->config->expects($this->once())
->method('getMaxSize')
->will($this->returnValue($expected['maxSize']));
$this->config->expects($this->once())
->method('getExploreUrl')
->will($this->returnValue($expected['exploreUrl']));
$this->config->expects($this->once())
->method('getUpdateInterval')
->will($this->returnValue($expected['updateInterval']));
$map = [
['news','autoPurgeMinimumInterval', 60, 1],
['news','autoPurgeCount', 200, 2],
['news','maxRedirects', 10, 3],
['news','feedFetcherTimeout', 60, 4],
['news','useCronUpdates', true, false,],
['news','exploreUrl', '', 'test'],
['news','updateInterval', 3600, 3601]
];
$this->config->expects($this->exactly(count($map)))
->method('getAppValue')
->will($this->returnValueMap($map));
$response = $this->controller->update(
$expected['autoPurgeMinimumInterval'],
$expected['autoPurgeCount'],
$expected['maxRedirects'],
$expected['feedFetcherTimeout'],
$expected['maxSize'],
$expected['useCronUpdates'],
$expected['exploreUrl'],
$expected['updateInterval']

View File

@ -41,7 +41,7 @@ class ExportControllerTest extends TestCase
/**
* Gets run before each test
*/
public function setUp()
public function setUp(): void
{
$this->appName = 'news';
$this->user = 'john';

View File

@ -44,7 +44,7 @@ class FeedApiControllerTest extends TestCase
private $logger;
private $loggerParams;
protected function setUp()
protected function setUp(): void
{
$this->loggerParams = ['hi'];
$this->logger = $this->getMockBuilder(ILogger::class)
@ -85,7 +85,7 @@ class FeedApiControllerTest extends TestCase
}
public function testIndex()
public function testIndex()
{
$feeds = [new Feed()];
$starredCount = 3;
@ -116,7 +116,7 @@ class FeedApiControllerTest extends TestCase
}
public function testIndexNoNewestItemId()
public function testIndexNoNewestItemId()
{
$feeds = [new Feed()];
$starredCount = 3;
@ -145,7 +145,7 @@ class FeedApiControllerTest extends TestCase
}
public function testDelete()
public function testDelete()
{
$this->feedService->expects($this->once())
->method('delete')
@ -158,7 +158,7 @@ class FeedApiControllerTest extends TestCase
}
public function testDeleteDoesNotExist()
public function testDeleteDoesNotExist()
{
$this->feedService->expects($this->once())
->method('delete')
@ -176,7 +176,7 @@ class FeedApiControllerTest extends TestCase
}
public function testCreate()
public function testCreate()
{
$feeds = [new Feed()];
@ -206,7 +206,7 @@ class FeedApiControllerTest extends TestCase
}
public function testCreateNoItems()
public function testCreateNoItems()
{
$feeds = [new Feed()];
@ -236,7 +236,7 @@ class FeedApiControllerTest extends TestCase
public function testCreateExists()
public function testCreateExists()
{
$this->feedService->expects($this->once())
->method('purgeDeleted')
@ -255,7 +255,7 @@ class FeedApiControllerTest extends TestCase
}
public function testCreateError()
public function testCreateError()
{
$this->feedService->expects($this->once())
->method('create')
@ -271,7 +271,7 @@ class FeedApiControllerTest extends TestCase
}
public function testRead()
public function testRead()
{
$this->itemService->expects($this->once())
->method('readFeed')
@ -285,7 +285,7 @@ class FeedApiControllerTest extends TestCase
}
public function testMove()
public function testMove()
{
$this->feedService->expects($this->once())
->method('patch')
@ -299,7 +299,7 @@ class FeedApiControllerTest extends TestCase
}
public function testMoveDoesNotExist()
public function testMoveDoesNotExist()
{
$this->feedService->expects($this->once())
->method('patch')
@ -315,7 +315,7 @@ class FeedApiControllerTest extends TestCase
}
public function testRename()
public function testRename()
{
$feedId = 3;
$feedTitle = 'test';
@ -332,7 +332,7 @@ class FeedApiControllerTest extends TestCase
}
public function testRenameError()
public function testRenameError()
{
$feedId = 3;
$feedTitle = 'test';
@ -370,7 +370,7 @@ class FeedApiControllerTest extends TestCase
}
public function testUpdate()
public function testUpdate()
{
$feedId = 3;
$userId = 'hi';
@ -383,7 +383,7 @@ class FeedApiControllerTest extends TestCase
}
public function testUpdateError()
public function testUpdateError()
{
$feedId = 3;
$userId = 'hi';

View File

@ -45,7 +45,7 @@ class FeedControllerTest extends TestCase
/**
* Gets run before each test
*/
public function setUp()
public function setUp(): void
{
$this->appName = 'news';
$this->user = 'jack';
@ -398,7 +398,7 @@ class FeedControllerTest extends TestCase
}
public function testImport()
public function testImport()
{
$feed = new Feed();
@ -426,7 +426,7 @@ class FeedControllerTest extends TestCase
}
public function testImportCreatesNoAdditionalFeed()
public function testImportCreatesNoAdditionalFeed()
{
$this->feedService->expects($this->once())
->method('importArticles')
@ -467,7 +467,7 @@ class FeedControllerTest extends TestCase
}
public function testRestore()
public function testRestore()
{
$this->feedService->expects($this->once())
->method('unmarkDeleted')
@ -492,7 +492,7 @@ class FeedControllerTest extends TestCase
$this->assertEquals($response->getStatus(), Http::STATUS_NOT_FOUND);
}
public function testPatch()
public function testPatch()
{
$expected = [
'pinned' => true,

View File

@ -44,7 +44,7 @@ class FolderApiControllerTest extends TestCase
private $request;
private $msg;
protected function setUp()
protected function setUp(): void
{
$this->appName = 'news';
$this->request = $this->getMockBuilder(IRequest::class)
@ -79,7 +79,7 @@ class FolderApiControllerTest extends TestCase
}
public function testIndex()
public function testIndex()
{
$folders = [new Folder()];
@ -98,7 +98,7 @@ class FolderApiControllerTest extends TestCase
}
public function testCreate()
public function testCreate()
{
$folderName = 'test';
$folder = new Folder();
@ -122,7 +122,7 @@ class FolderApiControllerTest extends TestCase
}
public function testCreateAlreadyExists()
public function testCreateAlreadyExists()
{
$msg = 'exists';
@ -141,7 +141,7 @@ class FolderApiControllerTest extends TestCase
}
public function testCreateInvalidFolderName()
public function testCreateInvalidFolderName()
{
$msg = 'exists';
@ -162,7 +162,7 @@ class FolderApiControllerTest extends TestCase
}
public function testDelete()
public function testDelete()
{
$folderId = 23;
$this->folderService->expects($this->once())
@ -173,7 +173,7 @@ class FolderApiControllerTest extends TestCase
}
public function testDeleteDoesNotExist()
public function testDeleteDoesNotExist()
{
$folderId = 23;
@ -193,7 +193,7 @@ class FolderApiControllerTest extends TestCase
}
public function testUpdate()
public function testUpdate()
{
$folderId = 23;
$folderName = 'test';
@ -209,7 +209,7 @@ class FolderApiControllerTest extends TestCase
$this->folderAPI->update($folderId, $folderName);
}
public function testUpdateDoesNotExist()
public function testUpdateDoesNotExist()
{
$folderId = 23;
$folderName = 'test';
@ -230,7 +230,7 @@ class FolderApiControllerTest extends TestCase
}
public function testUpdateExists()
public function testUpdateExists()
{
$folderId = 23;
$folderName = 'test';
@ -251,7 +251,7 @@ class FolderApiControllerTest extends TestCase
}
public function testUpdateInvalidFolderName()
public function testUpdateInvalidFolderName()
{
$folderId = 23;
$folderName = '';
@ -274,7 +274,7 @@ class FolderApiControllerTest extends TestCase
}
public function testRead()
public function testRead()
{
$this->itemService->expects($this->once())
->method('readFolder')

View File

@ -44,7 +44,7 @@ class FolderControllerTest extends TestCase
/**
* Gets run before each test
*/
public function setUp()
public function setUp(): void
{
$this->appName = 'news';
$this->user = 'jack';

View File

@ -39,7 +39,7 @@ class ItemApiControllerTest extends TestCase
private $request;
private $msg;
protected function setUp()
protected function setUp(): void
{
$this->user = 'tom';
$this->appName = 'news';
@ -71,7 +71,7 @@ class ItemApiControllerTest extends TestCase
}
public function testIndex()
public function testIndex()
{
$item = new Item();
$item->setId(5);
@ -102,7 +102,7 @@ class ItemApiControllerTest extends TestCase
}
public function testIndexDefaultBatchSize()
public function testIndexDefaultBatchSize()
{
$item = new Item();
$item->setId(5);
@ -133,7 +133,7 @@ class ItemApiControllerTest extends TestCase
}
public function testUpdated()
public function testUpdated()
{
$item = new Item();
$item->setId(5);
@ -162,7 +162,7 @@ class ItemApiControllerTest extends TestCase
}
public function testRead()
public function testRead()
{
$this->itemService->expects($this->once())
->method('read')
@ -176,7 +176,7 @@ class ItemApiControllerTest extends TestCase
}
public function testReadDoesNotExist()
public function testReadDoesNotExist()
{
$this->itemService->expects($this->once())
->method('read')
@ -194,7 +194,7 @@ class ItemApiControllerTest extends TestCase
}
public function testUnread()
public function testUnread()
{
$this->itemService->expects($this->once())
->method('read')
@ -208,7 +208,7 @@ class ItemApiControllerTest extends TestCase
}
public function testUnreadDoesNotExist()
public function testUnreadDoesNotExist()
{
$this->itemService->expects($this->once())
->method('read')
@ -226,7 +226,7 @@ class ItemApiControllerTest extends TestCase
}
public function testStar()
public function testStar()
{
$this->itemService->expects($this->once())
->method('star')
@ -241,7 +241,7 @@ class ItemApiControllerTest extends TestCase
}
public function testStarDoesNotExist()
public function testStarDoesNotExist()
{
$this->itemService->expects($this->once())
->method('star')
@ -259,7 +259,7 @@ class ItemApiControllerTest extends TestCase
}
public function testUnstar()
public function testUnstar()
{
$this->itemService->expects($this->once())
->method('star')
@ -274,7 +274,7 @@ class ItemApiControllerTest extends TestCase
}
public function testUnstarDoesNotExist()
public function testUnstarDoesNotExist()
{
$this->itemService->expects($this->once())
->method('star')
@ -292,7 +292,7 @@ class ItemApiControllerTest extends TestCase
}
public function testReadAll()
public function testReadAll()
{
$this->itemService->expects($this->once())
->method('readAll')
@ -306,7 +306,7 @@ class ItemApiControllerTest extends TestCase
public function testReadMultiple()
public function testReadMultiple()
{
$this->itemService->expects($this->at(0))
->method('read')
@ -326,7 +326,7 @@ class ItemApiControllerTest extends TestCase
}
public function testReadMultipleDoesntCareAboutException()
public function testReadMultipleDoesntCareAboutException()
{
$this->itemService->expects($this->at(0))
->method('read')
@ -342,7 +342,7 @@ class ItemApiControllerTest extends TestCase
}
public function testUnreadMultiple()
public function testUnreadMultiple()
{
$this->itemService->expects($this->at(0))
->method('read')
@ -362,7 +362,7 @@ class ItemApiControllerTest extends TestCase
}
public function testStarMultiple()
public function testStarMultiple()
{
$ids = [
[
@ -395,7 +395,7 @@ class ItemApiControllerTest extends TestCase
}
public function testStarMultipleDoesntCareAboutException()
public function testStarMultipleDoesntCareAboutException()
{
$ids = [
[
@ -423,7 +423,7 @@ class ItemApiControllerTest extends TestCase
}
public function testUnstarMultiple()
public function testUnstarMultiple()
{
$ids = [
[

View File

@ -43,7 +43,7 @@ class ItemControllerTest extends TestCase
/**
* Gets run before each test
*/
public function setUp()
public function setUp(): void
{
$this->appName = 'news';
$this->user = 'jackob';
@ -96,7 +96,7 @@ class ItemControllerTest extends TestCase
}
public function testReadMultiple()
public function testReadMultiple()
{
$this->itemService->expects($this->at(0))
->method('read')
@ -116,7 +116,7 @@ class ItemControllerTest extends TestCase
}
public function testReadMultipleDontStopOnException()
public function testReadMultipleDontStopOnException()
{
$this->itemService->expects($this->at(0))
->method('read')

View File

@ -26,7 +26,7 @@ class JSONHttpErrorTest extends TestCase
{
public function testError()
public function testError()
{
$ex = new \Exception('hi');
$test = new Test();

View File

@ -13,7 +13,7 @@
namespace OCA\News\Tests\Unit\Controller;
use OCA\News\Config\Config;
use OC\L10N\L10N;
use OCA\News\Controller\PageController;
use \OCA\News\Db\FeedType;
use OCA\News\Explore\RecommendedSites;
@ -28,26 +28,51 @@ use PHPUnit\Framework\TestCase;
class PageControllerTest extends TestCase
{
/**
* @var \PHPUnit\Framework\MockObject\MockObject|IConfig
*/
private $settings;
private $appName;
/**
* @var \PHPUnit\Framework\MockObject\MockObject|IRequest
*/
private $request;
/**
* @var PageController
*/
private $controller;
private $user;
/**
* @var \PHPUnit\Framework\MockObject\MockObject|L10N
*/
private $l10n;
/**
* @var \PHPUnit\Framework\MockObject\MockObject|IURLGenerator
*/
private $urlGenerator;
private $appConfig;
/**
* @var array
*/
private $configData;
private $config;
/**
* @var \PHPUnit\Framework\MockObject\MockObject|RecommendedSites
*/
private $recommended;
/**
* @var \PHPUnit\Framework\MockObject\MockObject|StatusService
*/
private $status;
/**
* Gets run before each test
*/
public function setUp()
public function setUp(): void
{
$this->appName = 'news';
$this->user = 'becka';
$this->configData = [
'name' => 'AppTest',
'id' => 'apptest',
@ -70,12 +95,6 @@ class PageControllerTest extends TestCase
$this->urlGenerator = $this->getMockBuilder(IURLGenerator::class)
->disableOriginalConstructor()
->getMock();
$this->appConfig = $this->getMockBuilder(Config::class)
->disableOriginalConstructor()
->getMock();
$this->config = $this->getMockBuilder(Config::class)
->disableOriginalConstructor()
->getMock();
$this->recommended = $this->getMockBuilder(RecommendedSites::class)
->disableOriginalConstructor()
->getMock();
@ -83,10 +102,14 @@ class PageControllerTest extends TestCase
->disableOriginalConstructor()
->getMock();
$this->controller = new PageController(
$this->appName, $this->request,
$this->settings, $this->urlGenerator, $this->config,
$this->l10n, $this->recommended, $this->status,
$this->user
'news',
$this->request,
$this->settings,
$this->urlGenerator,
$this->l10n,
$this->recommended,
$this->status,
'becka'
);
}
@ -95,15 +118,7 @@ class PageControllerTest extends TestCase
{
$this->status->expects($this->once())
->method('getStatus')
->will(
$this->returnValue(
[
'warnings' => [
'improperlyConfiguredCron' => false
]
]
)
);
->will($this->returnValue(['warnings' => ['improperlyConfiguredCron' => false]]));
$response = $this->controller->index();
$this->assertEquals('index', $response->getTemplateName());
@ -130,8 +145,10 @@ class PageControllerTest extends TestCase
$this->assertEquals(true, $response->getParams()['warnings']['improperlyConfiguredCron']);
}
public function testSettings()
/**
* @covers \OCA\News\Controller\PageController::settings
*/
public function testSettings()
{
$result = [
'settings' => [
@ -148,55 +165,23 @@ class PageControllerTest extends TestCase
$this->l10n->expects($this->once())
->method('getLanguageCode')
->will($this->returnValue('de'));
$this->settings->expects($this->at(0))
$this->settings->expects($this->exactly(5))
->method('getUserValue')
->with(
$this->equalTo($this->user),
$this->equalTo($this->appName),
$this->equalTo('showAll')
->withConsecutive(
['becka', 'news', 'showAll'],
['becka', 'news', 'compact'],
['becka', 'news', 'preventReadOnScroll'],
['becka', 'news', 'oldestFirst'],
['becka', 'news', 'compactExpand']
)
->will($this->returnValue('1'));
$this->settings->expects($this->at(1))
->method('getUserValue')
->with(
$this->equalTo($this->user),
$this->equalTo($this->appName),
$this->equalTo('compact')
)
->will($this->returnValue('1'));
$this->settings->expects($this->at(2))
->method('getUserValue')
->with(
$this->equalTo($this->user),
$this->equalTo($this->appName),
$this->equalTo('preventReadOnScroll')
)
->will($this->returnValue('1'));
$this->settings->expects($this->at(3))
->method('getUserValue')
->with(
$this->equalTo($this->user),
$this->equalTo($this->appName),
$this->equalTo('oldestFirst')
)
->will($this->returnValue('1'));
$this->settings->expects($this->at(4))
->method('getUserValue')
->with(
$this->equalTo($this->user),
$this->equalTo($this->appName),
$this->equalTo('compactExpand')
)
->will($this->returnValue('1'));
$this->config->expects($this->once())
->method('getExploreUrl')
$this->settings->expects($this->once())
->method('getAppValue')
->with('news', 'exploreUrl')
->will($this->returnValue(' '));
$this->urlGenerator->expects($this->once())
->method('linkToRoute')
->with(
$this->equalTo('news.page.explore'),
$this->equalTo(['lang' => 'en'])
)
->with('news.page.explore', ['lang' => 'en'])
->will($this->returnValue('test'));
@ -205,7 +190,7 @@ class PageControllerTest extends TestCase
}
public function testSettingsExploreUrlSet()
public function testSettingsExploreUrlSet()
{
$result = [
'settings' => [
@ -222,48 +207,19 @@ class PageControllerTest extends TestCase
$this->l10n->expects($this->once())
->method('getLanguageCode')
->will($this->returnValue('de'));
$this->settings->expects($this->at(0))
$this->settings->expects($this->exactly(5))
->method('getUserValue')
->with(
$this->equalTo($this->user),
$this->equalTo($this->appName),
$this->equalTo('showAll')
->withConsecutive(
['becka', 'news', 'showAll'],
['becka', 'news', 'compact'],
['becka', 'news', 'preventReadOnScroll'],
['becka', 'news', 'oldestFirst'],
['becka', 'news', 'compactExpand']
)
->will($this->returnValue('1'));
$this->settings->expects($this->at(1))
->method('getUserValue')
->with(
$this->equalTo($this->user),
$this->equalTo($this->appName),
$this->equalTo('compact')
)
->will($this->returnValue('1'));
$this->settings->expects($this->at(2))
->method('getUserValue')
->with(
$this->equalTo($this->user),
$this->equalTo($this->appName),
$this->equalTo('preventReadOnScroll')
)
->will($this->returnValue('1'));
$this->settings->expects($this->at(3))
->method('getUserValue')
->with(
$this->equalTo($this->user),
$this->equalTo($this->appName),
$this->equalTo('oldestFirst')
)
->will($this->returnValue('1'));
$this->settings->expects($this->at(4))
->method('getUserValue')
->with(
$this->equalTo($this->user),
$this->equalTo($this->appName),
$this->equalTo('compactExpand')
)
->will($this->returnValue('1'));
$this->config->expects($this->once())
->method('getExploreUrl')
$this->settings->expects($this->once())
->method('getAppValue')
->with('news', 'exploreUrl')
->will($this->returnValue('abc'));
$this->urlGenerator->expects($this->never())
->method('getAbsoluteURL');
@ -273,83 +229,50 @@ class PageControllerTest extends TestCase
$this->assertEquals($result, $response);
}
public function testUpdateSettings()
/**
* @covers \OCA\News\Controller\PageController::updateSettings
*/
public function testUpdateSettings()
{
$this->settings->expects($this->at(0))
->method('setUserValue')
->with(
$this->equalTo($this->user),
$this->equalTo($this->appName),
$this->equalTo('showAll'),
$this->equalTo('1')
);
->with('becka', 'news', 'showAll', '1');
$this->settings->expects($this->at(1))
->method('setUserValue')
->with(
$this->equalTo($this->user),
$this->equalTo($this->appName),
$this->equalTo('compact'),
$this->equalTo('1')
);
->with('becka', 'news', 'compact', '1');
$this->settings->expects($this->at(2))
->method('setUserValue')
->with(
$this->equalTo($this->user),
$this->equalTo($this->appName),
$this->equalTo('preventReadOnScroll'),
$this->equalTo('0')
);
->with('becka', 'news', 'preventReadOnScroll', '0');
$this->settings->expects($this->at(3))
->method('setUserValue')
->with(
$this->equalTo($this->user),
$this->equalTo($this->appName),
$this->equalTo('oldestFirst'),
$this->equalTo('1')
);
->with('becka', 'news', 'oldestFirst', '1');
$this->settings->expects($this->at(4))
->method('setUserValue')
->with(
$this->equalTo($this->user),
$this->equalTo($this->appName),
$this->equalTo('compactExpand'),
$this->equalTo('1')
);
->with('becka', 'news', 'compactExpand', '1');
$this->controller->updateSettings(true, true, false, true, true);
}
public function testExplore()
{
$in = 'test';
$this->settings->expects($this->at(0))
->method('setUserValue')
->with(
$this->equalTo($this->user),
$this->equalTo($this->appName),
$this->equalTo('lastViewedFeedId'),
$this->equalTo(0)
);
->with('becka', 'news', 'lastViewedFeedId', 0);
$this->settings->expects($this->at(1))
->method('setUserValue')
->with(
$this->equalTo($this->user),
$this->equalTo($this->appName),
$this->equalTo('lastViewedFeedType'),
$this->equalTo(FeedType::EXPLORE)
);
->with('becka', 'news', 'lastViewedFeedType', FeedType::EXPLORE);
$this->recommended->expects($this->once())
->method('forLanguage')
->with($this->equalTo('en'))
->with('en')
->will($this->returnValue($in));
$out = $this->controller->explore('en');
$this->assertEquals($in, $out);
}
}

View File

@ -33,7 +33,7 @@ class UserApiControllerTest extends TestCase
private $user;
private $file;
protected function setUp()
protected function setUp(): void
{
$this->appName = 'news';
$this->request = $this->getMockBuilder(IRequest::class)
@ -59,7 +59,7 @@ class UserApiControllerTest extends TestCase
}
private function expectUser($uid, $displayName, $lastLogin)
private function expectUser($uid, $displayName, $lastLogin)
{
$this->userSession->expects($this->any())
->method('getUser')
@ -75,7 +75,7 @@ class UserApiControllerTest extends TestCase
->will($this->returnValue($displayName));
}
private function expectImg($isJpg, $isPng, $user, $exists, $data)
private function expectImg($isJpg, $isPng, $user, $exists, $data)
{
$jpg = '/' . $user . '/' . 'avatar.jpg';
$png = '/' . $user . '/' . 'avatar.png';
@ -98,7 +98,7 @@ class UserApiControllerTest extends TestCase
->will($this->returnValue($data));
}
public function testGetJpeg()
public function testGetJpeg()
{
$this->expectUser('john', 'John', 123);
$this->expectImg(true, false, 'john', true, 'hi');
@ -117,7 +117,7 @@ class UserApiControllerTest extends TestCase
$this->assertEquals($expected, $result);
}
public function testGetPng()
public function testGetPng()
{
$this->expectUser('john', 'John', 123);
$this->expectImg(false, true, 'john', false, 'hi');
@ -136,7 +136,7 @@ class UserApiControllerTest extends TestCase
$this->assertEquals($expected, $result);
}
public function testNoAvatar()
public function testNoAvatar()
{
$this->expectUser('john', 'John', 123);
$this->expectImg(false, false, 'john', false, 'hi');

View File

@ -37,7 +37,7 @@ class UtilityApiControllerTest extends TestCase
private $appName;
private $status;
protected function setUp()
protected function setUp(): void
{
$this->appName = 'news';
$this->settings = $this->getMockBuilder(IConfig::class)

View File

@ -28,7 +28,7 @@ class FolderMapperTest extends MapperTestUtility
/** @var string */
private $user;
protected function setUp()
protected function setUp(): void
{
parent::setUp();

View File

@ -22,11 +22,11 @@ class ItemTest extends TestCase
{
/**
* @var Item
* @var Item
*/
private $item;
protected function setUp()
protected function setUp(): void
{
$this->item = new Item();
$this->item->setStatus(0);
@ -65,7 +65,7 @@ class ItemTest extends TestCase
}
public function testToAPI()
public function testToAPI()
{
$item = new Item();
$item->setId(3);
@ -117,7 +117,7 @@ class ItemTest extends TestCase
}
public function testJSONSerialize()
public function testJSONSerialize()
{
$item = new Item();
$item->setId(3);
@ -167,7 +167,7 @@ class ItemTest extends TestCase
);
}
public function testToExport()
public function testToExport()
{
$item = new Item();
$item->setId(3);
@ -216,7 +216,7 @@ class ItemTest extends TestCase
}
private function createImportItem($isRead)
private function createImportItem($isRead)
{
$item = new Item();
$item->setGuid('guid');
@ -242,7 +242,7 @@ class ItemTest extends TestCase
}
public function testSearchIndex()
public function testSearchIndex()
{
$item = new Item();
$item->setBody('<a>somEth&auml;ng</a>');
@ -255,7 +255,7 @@ class ItemTest extends TestCase
}
public function testFromImport()
public function testFromImport()
{
$item = $this->createImportItem(false);
@ -282,7 +282,7 @@ class ItemTest extends TestCase
}
public function testFromImportRead()
public function testFromImportRead()
{
$item = $this->createImportItem(true);
@ -315,7 +315,7 @@ class ItemTest extends TestCase
$item = new Item();
$item->setAuthor('<a>my link</li>');
$this->assertEquals('my link', $item->getAuthor());
$this->assertContains('author', $item->getUpdatedFields());
$this->assertArrayHasKey('author', $item->getUpdatedFields());
}
@ -324,11 +324,11 @@ class ItemTest extends TestCase
$item = new Item();
$item->setTitle('<a>my link</li>');
$this->assertEquals('my link', $item->getTitle());
$this->assertContains('title', $item->getUpdatedFields());
$this->assertArrayHasKey('title', $item->getUpdatedFields());
}
public function testSetXSSUrl()
public function testSetXSSUrl()
{
$item = new Item();
$item->setUrl('javascript:alert()');
@ -336,7 +336,7 @@ class ItemTest extends TestCase
}
public function testSetMagnetUrl()
public function testSetMagnetUrl()
{
$item = new Item();
$item->setUrl('magnet://link.com');
@ -344,7 +344,7 @@ class ItemTest extends TestCase
}
public function testMakeLinksInBodyOpenNewTab()
public function testMakeLinksInBodyOpenNewTab()
{
$item = new Item();
$item->setBody("<a href=\"test\">ha</a>");
@ -354,7 +354,7 @@ class ItemTest extends TestCase
);
}
public function testComputeFingerPrint()
public function testComputeFingerPrint()
{
$title = 'a';
$body = 'b';

View File

@ -29,26 +29,26 @@ class MapperFactoryTest extends TestCase
private $db;
private $settings;
public function setUp()
public function setUp(): void
{
$this->db = $this->getMockBuilder(IDBConnection::class)
->disableOriginalConstructor()
->getMock();
}
public function testGetItemMapperSqlite()
public function testGetItemMapperSqlite()
{
$factory = new MapperFactory($this->db, 'sqlite', new Time());
$this->assertTrue($factory->build() instanceof ItemMapper);
}
public function testGetItemMapperPostgres()
public function testGetItemMapperPostgres()
{
$factory = new MapperFactory($this->db, 'pgsql', new Time());
$this->assertTrue($factory->build() instanceof ItemMapper);
}
public function testGetItemMapperMysql()
public function testGetItemMapperMysql()
{
$factory = new MapperFactory($this->db, 'mysql', new Time());
$this->assertTrue($factory->build() instanceof MysqlMapper);

View File

@ -43,7 +43,7 @@ abstract class MapperTestUtility extends TestCase
* Run this function before the actual test to either set or initialize the
* db. After this the db can be accessed by using $this->db
*/
protected function setUp()
protected function setUp(): void
{
parent::setUp();
@ -64,7 +64,7 @@ abstract class MapperTestUtility extends TestCase
* @param array $array
* @return bool true if associative
*/
private function isAssocArray(array $array)
private function isAssocArray(array $array)
{
return array_values($array) !== $array;
}
@ -75,7 +75,7 @@ abstract class MapperTestUtility extends TestCase
* @param $value
* @return PDO constant
*/
private function getPDOType($value)
private function getPDOType($value)
{
switch (gettype($value)) {
case 'integer':

View File

@ -25,7 +25,9 @@ use OCA\News\Scraper\Scraper;
use OCA\News\Fetcher\FeedFetcher;
use OCA\News\Utility\PsrLogger;
use OCP\ILogger;
use PHPUnit\Framework\TestCase;
use Psr\Log\LoggerInterface;
/**
* Class FeedFetcherTest
@ -83,7 +85,7 @@ class FeedFetcherTest extends TestCase
private $feed_mock;
/**
* @var PsrLogger
* @var LoggerInterface
*/
private $logger;
@ -128,7 +130,7 @@ class FeedFetcherTest extends TestCase
private $modified;
private $location;
protected function setUp()
protected function setUp(): void
{
$this->l10n = $this->getMockBuilder(\OCP\IL10N::class)
->disableOriginalConstructor()
@ -161,8 +163,7 @@ class FeedFetcherTest extends TestCase
$timeFactory->expects($this->any())
->method('getTime')
->will($this->returnValue($this->time));
$this->logger = $this->getMockBuilder(PsrLogger::class)
->disableOriginalConstructor()
$this->logger = $this->getMockBuilder(LoggerInterface::class)
->getMock();
$this->scraper = $this->getMockBuilder(Scraper::class)
->disableOriginalConstructor()
@ -373,7 +374,7 @@ class FeedFetcherTest extends TestCase
{
$this->setUpReader($this->url);
$feed = $this->createFeed(false);
$feed = $this->createFeed('de-DE', false);
$this->favicon->expects($this->never())
->method('get');

View File

@ -34,7 +34,7 @@ class FetcherTest extends TestCase
private $fetcher;
protected function setUp()
protected function setUp(): void
{
$this->fetcher = new Fetcher();
}

View File

@ -35,7 +35,7 @@ class YoutubeFetcherTest extends TestCase
*/
private $feedFetcher;
public function setUp()
public function setUp(): void
{
$this->feedFetcher = $this->getMockBuilder(FeedFetcher::class)
->disableOriginalConstructor()

View File

@ -22,7 +22,7 @@ class TextDownloadResponseTest extends TestCase
{
protected function setUp()
protected function setUp(): void
{
$this->response = new TextDownloadResponse(
'sometext', 'file', 'content'
@ -30,7 +30,7 @@ class TextDownloadResponseTest extends TestCase
}
public function testRender()
public function testRender()
{
$this->assertEquals('sometext', $this->response->render());
}

View File

@ -21,13 +21,13 @@ class TextResponseTest extends TestCase
{
protected function setUp()
protected function setUp(): void
{
$this->response = new TextResponse('sometext');
}
public function testRender()
public function testRender()
{
$this->assertEquals('sometext', $this->response->render());
}

View File

@ -22,15 +22,15 @@ class MigrateStatusFlagsTest extends TestCase
{
/**
* @var IDBConnection|\PHPUnit_Framework_MockObject_MockObject
* @var IDBConnection|\PHPUnit_Framework_MockObject_MockObject
*/
protected $db;
/**
* @var IConfig|\PHPUnit_Framework_MockObject_MockObject
* @var IConfig|\PHPUnit_Framework_MockObject_MockObject
*/
protected $config;
/**
* @var IOutput|\PHPUnit_Framework_MockObject_MockObject
* @var IOutput|\PHPUnit_Framework_MockObject_MockObject
*/
protected $output;
@ -41,7 +41,7 @@ class MigrateStatusFlagsTest extends TestCase
$this->output = $this->createMock(IOutput::class);
}
public function testRun()
public function testRun()
{
$statement = $this->createMock(Statement::class);
$statement->expects($this->exactly(1))
@ -67,11 +67,11 @@ class MigrateStatusFlagsTest extends TestCase
$migration->run($this->output);
}
/**
* @expectedException \Exception
*/
public function testRunException()
public function testRunException()
{
$this->expectException('\Exception');
$this->expectExceptionMessage('Could not migrate status');
$statement = $this->createMock(Statement::class);
$statement->expects($this->exactly(1))
->method('execute')
@ -96,7 +96,7 @@ class MigrateStatusFlagsTest extends TestCase
$migration->run($this->output);
}
public function testRunNewerVersion()
public function testRunNewerVersion()
{
$this->config->expects($this->exactly(1))
->method('getAppValue')

View File

@ -16,7 +16,7 @@ namespace OCA\News\Tests\Unit\Service;
use FeedIo\Reader\ReadErrorException;
use OCA\News\Config\Config;
use OC\L10N\L10N;
use OCA\News\Db\FeedMapper;
use OCA\News\Db\ItemMapper;
use OCA\News\Service\FeedService;
@ -28,6 +28,7 @@ use OCA\News\Db\Feed;
use OCA\News\Db\Item;
use OCA\News\Fetcher\Fetcher;
use OCA\News\Fetcher\FetcherException;
use OCP\IConfig;
use OCP\IL10N;
use OCP\ILogger;
@ -37,28 +38,60 @@ use PHPUnit\Framework\TestCase;
class FeedServiceTest extends TestCase
{
/**
* @var \PHPUnit\Framework\MockObject\MockObject|FeedMapper
*/
private $feedMapper;
/**
* @var \PHPUnit\Framework\MockObject\MockObject|ItemMapper
*/
private $itemMapper;
/** @var FeedService */
private $feedService;
private $user;
private $response;
private $fetcher;
private $itemMapper;
private $threshold;
private $time;
private $importParser;
private $autoPurgeMinimumInterval;
private $purifier;
private $l10n;
private $logger;
private $loggerParams;
protected function setUp()
/**
* @var string
*/
private $user;
/**
* @var \PHPUnit\Framework\MockObject\MockObject|Fetcher
*/
private $fetcher;
/**
* @var int
*/
private $time;
/**
* @var int
*/
private $autoPurgeMinimumInterval;
/**
* @var \PHPUnit\Framework\MockObject\MockObject|\HTMLPurifier
*/
private $purifier;
/**
* @var \PHPUnit\Framework\MockObject\MockObject|L10N
*/
private $l10n;
/**
* @var \PHPUnit\Framework\MockObject\MockObject|ILogger
*/
private $logger;
protected function setUp(): void
{
$this->logger = $this->getMockBuilder(ILogger::class)
->disableOriginalConstructor()
->getMock();
$this->loggerParams = ['hi'];
$loggerParams = ['hi'];
$this->time = 222;
$this->autoPurgeMinimumInterval = 10;
$timeFactory = $this->getMockBuilder(Time::class)
@ -86,31 +119,34 @@ class FeedServiceTest extends TestCase
->getMockBuilder(\HTMLPurifier::class)
->disableOriginalConstructor()
->getMock();
$config = $this->getMockBuilder(Config::class)
$config = $this->getMockBuilder(IConfig::class)
->disableOriginalConstructor()
->getMock();
$config->expects($this->any())
->method('getAutoPurgeMinimumInterval')
->method('getAppValue')
->with('news', 'autoPurgeMinimumInterval')
->will($this->returnValue($this->autoPurgeMinimumInterval));
$this->feedService = new FeedService(
$this->feedMapper,
$this->fetcher, $this->itemMapper, $this->logger, $this->l10n,
$timeFactory, $config, $this->purifier, $this->loggerParams
$timeFactory, $config, $this->purifier, $loggerParams
);
$this->user = 'jack';
}
/**
* @covers \OCA\News\Service\FeedService::findAll
*/
public function testFindAll()
{
$this->feedMapper->expects($this->once())
->method('findAllFromUser')
->with($this->equalTo($this->user))
->will($this->returnValue($this->response));
->with($this->user)
->will($this->returnValue([]));
$result = $this->feedService->findAll($this->user);
$this->assertEquals($this->response, $result);
$this->assertEquals([], $result);
}
@ -120,7 +156,7 @@ class FeedServiceTest extends TestCase
$url = 'test';
$this->fetcher->expects($this->once())
->method('fetch')
->with($this->equalTo($url))
->with($url)
->will($this->throwException($ex));
$this->expectException(ServiceNotFoundException::class);
$this->feedService->create($url, 1, $this->user);
@ -1145,12 +1181,9 @@ class FeedServiceTest extends TestCase
$this->feedService->patch(3, $this->user, ['fullTextEnabled' => true]);
}
/**
* @expectedException OCA\News\Service\ServiceNotFoundException
*/
public function testPatchDoesNotExist()
{
$this->expectException('OCA\News\Service\ServiceNotFoundException');
$feed = Feed::fromRow(['id' => 3]);
$this->feedMapper->expects($this->once())
->method('find')

View File

@ -13,13 +13,14 @@
namespace OCA\News\Tests\Unit\Service;
use OCA\News\Config\Config;
use OC\L10N\L10N;
use \OCA\News\Db\Folder;
use OCA\News\Db\FolderMapper;
use OCA\News\Service\FolderService;
use OCA\News\Service\ServiceConflictException;
use OCA\News\Service\ServiceValidationException;
use OCA\News\Utility\Time;
use OCP\IConfig;
use OCP\IL10N;
use PHPUnit\Framework\TestCase;
@ -28,14 +29,37 @@ use PHPUnit\Framework\TestCase;
class FolderServiceTest extends TestCase
{
/**
* @var \PHPUnit\Framework\MockObject\MockObject|FolderMapper
*/
private $folderMapper;
/**
* @var FolderService
*/
private $folderService;
/**
* @var int
*/
private $time;
/**
* @var string
*/
private $user;
/**
* @var int
*/
private $autoPurgeMinimumInterval;
/**
* @var \PHPUnit\Framework\MockObject\MockObject|L10N
*/
private $l10n;
protected function setUp()
protected function setUp(): void
{
$this->l10n = $this->getMockBuilder(IL10N::class)
->disableOriginalConstructor()
@ -51,11 +75,12 @@ class FolderServiceTest extends TestCase
->disableOriginalConstructor()
->getMock();
$this->autoPurgeMinimumInterval = 10;
$config = $this->getMockBuilder(Config::class)
$config = $this->getMockBuilder(IConfig::class)
->disableOriginalConstructor()
->getMock();
$config->expects($this->any())
->method('getAutoPurgeMinimumInterval')
->method('getAppValue')
->with('news', 'autoPurgeMinimumInterval')
->will($this->returnValue($this->autoPurgeMinimumInterval));
$this->folderService = new FolderService(
$this->folderMapper, $this->l10n, $timeFactory, $config
@ -119,11 +144,10 @@ class FolderServiceTest extends TestCase
$this->folderService->create($folderName, 'john', 3);
}
/**
* @expectedException \OCA\News\Service\ServiceValidationException
*/
public function testCreateThrowsExWhenFolderNameEmpty()
{
$this->expectException('OCA\News\Service\ServiceValidationException');
$folderName = '';
$this->folderMapper->expects($this->once())
@ -211,7 +235,7 @@ class FolderServiceTest extends TestCase
}
public function testMarkDeleted()
public function testMarkDeleted()
{
$id = 3;
$folder = new Folder();
@ -230,7 +254,7 @@ class FolderServiceTest extends TestCase
}
public function testUnmarkDeleted()
public function testUnmarkDeleted()
{
$id = 3;
$folder = new Folder();
@ -295,7 +319,7 @@ class FolderServiceTest extends TestCase
}
public function testDeleteUser()
public function testDeleteUser()
{
$this->folderMapper->expects($this->once())
->method('deleteUser')

View File

@ -13,7 +13,6 @@
namespace OCA\News\Tests\Unit\Service;
use OCA\News\Config\Config;
use OCA\News\Db\ItemMapper;
use OCA\News\Service\ItemService;
use OCA\News\Service\ServiceNotFoundException;
@ -30,20 +29,26 @@ use PHPUnit\Framework\TestCase;
class ItemServiceTest extends TestCase
{
/**
* @var \PHPUnit\Framework\MockObject\MockObject|ItemMapper
*/
private $mapper;
/**
* @var ItemService
* @var ItemService
*/
private $itemService;
private $user;
private $response;
private $status;
private $time;
private $newestItemId;
private $config;
private $systemConfig;
protected function setUp()
/**
* @var int
*/
private $time;
/**
* @var \PHPUnit\Framework\MockObject\MockObject|IConfig
*/
private $config;
protected function setUp(): void
{
$this->time = 222;
$this->timeFactory = $this->getMockBuilder(Time::class)
@ -58,23 +63,10 @@ class ItemServiceTest extends TestCase
$this->mapper = $this->getMockBuilder(ItemMapper::class)
->disableOriginalConstructor()
->getMock();
$this->config = $this->getMockBuilder(Config::class)
$this->config = $this->getMockBuilder(IConfig::class)
->disableOriginalConstructor()
->getMock();
$this->systemConfig = $this->getMockBuilder(IConfig::class)
->disableOriginalConstructor()
->getMock();
$this->itemService = new ItemService(
$this->mapper,
$this->timeFactory, $this->config, $this->systemConfig
);
$this->user = 'jack';
$this->id = 3;
$this->updatedSince = 20333;
$this->showAll = true;
$this->offset = 5;
$this->limit = 20;
$this->newestItemId = 4;
$this->itemService = new ItemService($this->mapper, $this->timeFactory, $this->config);
}
@ -84,18 +76,15 @@ class ItemServiceTest extends TestCase
$this->mapper->expects($this->once())
->method('findAllNewFeed')
->with(
$this->equalTo($this->id),
$this->equalTo($this->updatedSince),
$this->equalTo($this->showAll),
$this->equalTo($this->user)
$this->equalTo(3),
$this->equalTo(20333),
$this->equalTo(true),
$this->equalTo('jack')
)
->will($this->returnValue($this->response));
->will($this->returnValue([]));
$result = $this->itemService->findAllNew(
$this->id, $type, $this->updatedSince, $this->showAll,
$this->user
);
$this->assertEquals($this->response, $result);
$result = $this->itemService->findAllNew(3, $type, 20333, true, 'jack');
$this->assertEquals([], $result);
}
@ -105,18 +94,15 @@ class ItemServiceTest extends TestCase
$this->mapper->expects($this->once())
->method('findAllNewFolder')
->with(
$this->equalTo($this->id),
$this->equalTo($this->updatedSince),
$this->equalTo($this->showAll),
$this->equalTo($this->user)
$this->equalTo(3),
$this->equalTo(20333),
$this->equalTo(true),
$this->equalTo('jack')
)
->will($this->returnValue($this->response));
->will($this->returnValue(['val']));
$result = $this->itemService->findAllNew(
$this->id, $type, $this->updatedSince, $this->showAll,
$this->user
);
$this->assertEquals($this->response, $result);
$result = $this->itemService->findAllNew(3, $type, 20333, true, 'jack');
$this->assertEquals(['val'], $result);
}
@ -126,18 +112,18 @@ class ItemServiceTest extends TestCase
$this->mapper->expects($this->once())
->method('findAllNew')
->with(
$this->equalTo($this->updatedSince),
$this->equalTo(20333),
$this->equalTo($type),
$this->equalTo($this->showAll),
$this->equalTo($this->user)
$this->equalTo(true),
$this->equalTo('jack')
)
->will($this->returnValue($this->response));
->will($this->returnValue(['val']));
$result = $this->itemService->findAllNew(
$this->id, $type, $this->updatedSince, $this->showAll,
$this->user
3, $type, 20333, true,
'jack'
);
$this->assertEquals($this->response, $result);
$this->assertEquals(['val'], $result);
}
@ -147,21 +133,21 @@ class ItemServiceTest extends TestCase
$this->mapper->expects($this->once())
->method('findAllFeed')
->with(
$this->equalTo($this->id),
$this->equalTo($this->limit),
$this->equalTo($this->offset),
$this->equalTo($this->showAll),
$this->equalTo(3),
$this->equalTo(20),
$this->equalTo(5),
$this->equalTo(true),
$this->equalTo(false),
$this->equalTo($this->user),
$this->equalTo('jack'),
$this->equalTo([])
)
->will($this->returnValue($this->response));
->will($this->returnValue(['val']));
$result = $this->itemService->findAll(
$this->id, $type, $this->limit, $this->offset,
$this->showAll, false, $this->user
3, $type, 20, 5,
true, false, 'jack'
);
$this->assertEquals($this->response, $result);
$this->assertEquals(['val'], $result);
}
@ -171,21 +157,21 @@ class ItemServiceTest extends TestCase
$this->mapper->expects($this->once())
->method('findAllFolder')
->with(
$this->equalTo($this->id),
$this->equalTo($this->limit),
$this->equalTo($this->offset),
$this->equalTo($this->showAll),
$this->equalTo(3),
$this->equalTo(20),
$this->equalTo(5),
$this->equalTo(true),
$this->equalTo($this->user),
$this->equalTo(true),
$this->equalTo('jack'),
$this->equalTo([])
)
->will($this->returnValue($this->response));
->will($this->returnValue(['val']));
$result = $this->itemService->findAll(
$this->id, $type, $this->limit, $this->offset,
$this->showAll, true, $this->user
3, $type, 20, 5,
true, true, 'jack'
);
$this->assertEquals($this->response, $result);
$this->assertEquals(['val'], $result);
}
@ -195,21 +181,21 @@ class ItemServiceTest extends TestCase
$this->mapper->expects($this->once())
->method('findAll')
->with(
$this->equalTo($this->limit),
$this->equalTo($this->offset),
$this->equalTo(20),
$this->equalTo(5),
$this->equalTo($type),
$this->equalTo($this->showAll),
$this->equalTo(true),
$this->equalTo($this->user),
$this->equalTo(true),
$this->equalTo('jack'),
$this->equalTo([])
)
->will($this->returnValue($this->response));
->will($this->returnValue(['val']));
$result = $this->itemService->findAll(
$this->id, $type, $this->limit, $this->offset,
$this->showAll, true, $this->user
3, $type, 20, 5,
true, true, 'jack'
);
$this->assertEquals($this->response, $result);
$this->assertEquals(['val'], $result);
}
@ -220,21 +206,21 @@ class ItemServiceTest extends TestCase
$this->mapper->expects($this->once())
->method('findAll')
->with(
$this->equalTo($this->limit),
$this->equalTo($this->offset),
$this->equalTo(20),
$this->equalTo(5),
$this->equalTo($type),
$this->equalTo($this->showAll),
$this->equalTo(true),
$this->equalTo($this->user),
$this->equalTo(true),
$this->equalTo('jack'),
$this->equalTo($search)
)
->will($this->returnValue($this->response));
->will($this->returnValue(['val']));
$result = $this->itemService->findAll(
$this->id, $type, $this->limit, $this->offset,
$this->showAll, true, $this->user, $search
3, $type, 20, 5,
true, true, 'jack', $search
);
$this->assertEquals($this->response, $result);
$this->assertEquals(['val'], $result);
}
@ -260,7 +246,7 @@ class ItemServiceTest extends TestCase
->with(
$this->equalTo($guidHash),
$this->equalTo($feedId),
$this->equalTo($this->user)
$this->equalTo('jack')
)
->will($this->returnValue($item));
@ -268,7 +254,7 @@ class ItemServiceTest extends TestCase
->method('update')
->with($this->equalTo($expectedItem));
$this->itemService->star($feedId, $guidHash, true, $this->user);
$this->itemService->star($feedId, $guidHash, true, 'jack');
$this->assertTrue($item->isStarred());
}
@ -296,7 +282,7 @@ class ItemServiceTest extends TestCase
->with(
$this->equalTo($guidHash),
$this->equalTo($feedId),
$this->equalTo($this->user)
$this->equalTo('jack')
)
->will($this->returnValue($item));
@ -304,7 +290,7 @@ class ItemServiceTest extends TestCase
->method('update')
->with($this->equalTo($expectedItem));
$this->itemService->star($feedId, $guidHash, false, $this->user);
$this->itemService->star($feedId, $guidHash, false, 'jack');
$this->assertFalse($item->isStarred());
}
@ -329,11 +315,11 @@ class ItemServiceTest extends TestCase
$this->equalTo($itemId),
$this->equalTo(true),
$this->equalTo($this->time),
$this->equalTo($this->user)
$this->equalTo('jack')
)
->will($this->returnValue($item));
$this->itemService->read($itemId, true, $this->user);
$this->itemService->read($itemId, true, 'jack');
}
@ -345,7 +331,7 @@ class ItemServiceTest extends TestCase
->method('readItem')
->will($this->throwException(new DoesNotExistException('')));
$this->itemService->read(1, true, $this->user);
$this->itemService->read(1, true, 'jack');
}
public function testStarDoesNotExist()
@ -356,7 +342,7 @@ class ItemServiceTest extends TestCase
->method('findByGuidHash')
->will($this->throwException(new DoesNotExistException('')));
$this->itemService->star(1, 'hash', true, $this->user);
$this->itemService->star(1, 'hash', true, 'jack');
}
@ -369,10 +355,10 @@ class ItemServiceTest extends TestCase
->with(
$this->equalTo($highestItemId),
$this->equalTo($this->time),
$this->equalTo($this->user)
$this->equalTo('jack')
);
$this->itemService->readAll($highestItemId, $this->user);
$this->itemService->readAll($highestItemId, 'jack');
}
@ -387,10 +373,10 @@ class ItemServiceTest extends TestCase
$this->equalTo($folderId),
$this->equalTo($highestItemId),
$this->equalTo($this->time),
$this->equalTo($this->user)
$this->equalTo('jack')
);
$this->itemService->readFolder($folderId, $highestItemId, $this->user);
$this->itemService->readFolder($folderId, $highestItemId, 'jack');
}
@ -405,17 +391,18 @@ class ItemServiceTest extends TestCase
$this->equalTo($feedId),
$this->equalTo($highestItemId),
$this->equalTo($this->time),
$this->equalTo($this->user)
$this->equalTo('jack')
);
$this->itemService->readFeed($feedId, $highestItemId, $this->user);
$this->itemService->readFeed($feedId, $highestItemId, 'jack');
}
public function testAutoPurgeOldWillPurgeOld()
{
$this->config->expects($this->once())
->method('getAutoPurgeCount')
->method('getAppValue')
->with('news', 'autoPurgeCount')
->will($this->returnValue(2));
$this->mapper->expects($this->once())
->method('deleteReadOlderThanThreshold')
@ -427,7 +414,8 @@ class ItemServiceTest extends TestCase
public function testAutoPurgeOldWontPurgeOld()
{
$this->config->expects($this->once())
->method('getAutoPurgeCount')
->method('getAppValue')
->with('news', 'autoPurgeCount')
->will($this->returnValue(-1));
$this->mapper->expects($this->never())
->method('deleteReadOlderThanThreshold');
@ -436,23 +424,23 @@ class ItemServiceTest extends TestCase
}
public function testGetNewestItemId()
public function testGetNewestItemId()
{
$this->mapper->expects($this->once())
->method('getNewestItemId')
->with($this->equalTo($this->user))
->with($this->equalTo('jack'))
->will($this->returnValue(12));
$result = $this->itemService->getNewestItemId($this->user);
$result = $this->itemService->getNewestItemId('jack');
$this->assertEquals(12, $result);
}
public function testGetNewestItemIdDoesNotExist()
public function testGetNewestItemIdDoesNotExist()
{
$this->mapper->expects($this->once())
->method('getNewestItemId')
->with($this->equalTo($this->user))
->with($this->equalTo('jack'))
->will(
$this->throwException(
new DoesNotExistException('There are no items')
@ -460,7 +448,7 @@ class ItemServiceTest extends TestCase
);
$this->expectException(ServiceNotFoundException::class);
$this->itemService->getNewestItemId($this->user);
$this->itemService->getNewestItemId('jack');
}
@ -470,10 +458,10 @@ class ItemServiceTest extends TestCase
$this->mapper->expects($this->once())
->method('starredCount')
->with($this->equalTo($this->user))
->with($this->equalTo('jack'))
->will($this->returnValue($star));
$result = $this->itemService->starredCount($this->user);
$result = $this->itemService->starredCount('jack');
$this->assertEquals($star, $result);
}
@ -485,22 +473,22 @@ class ItemServiceTest extends TestCase
$this->mapper->expects($this->once())
->method('findAllUnreadOrStarred')
->with($this->equalTo($this->user))
->with($this->equalTo('jack'))
->will($this->returnValue($star));
$result = $this->itemService->getUnreadOrStarred($this->user);
$result = $this->itemService->getUnreadOrStarred('jack');
$this->assertEquals($star, $result);
}
public function testDeleteUser()
public function testDeleteUser()
{
$this->mapper->expects($this->once())
->method('deleteUser')
->will($this->returnValue($this->user));
->will($this->returnValue('jack'));
$this->itemService->deleteUser($this->user);
$this->itemService->deleteUser('jack');
}

View File

@ -37,7 +37,7 @@ class ServiceTest extends TestCase
protected $mapper;
protected $newsService;
protected function setUp()
protected function setUp(): void
{
$this->mapper = $this->getMockBuilder(ItemMapper::class)
->disableOriginalConstructor()

View File

@ -13,8 +13,6 @@
namespace OCA\News\Tests\Unit\Service;
use OCA\News\Config\Config;
use \OCA\News\Db\FeedType;
use OCA\News\Service\StatusService;
use OCP\IConfig;
use OCP\IDBConnection;
@ -23,83 +21,174 @@ use PHPUnit\Framework\TestCase;
class StatusServiceTest extends TestCase
{
/**
* @var \PHPUnit\Framework\MockObject\MockObject|IConfig
*/
private $settings;
private $config;
private $service;
private $appName;
public function setUp()
/**
* @var \PHPUnit\Framework\MockObject\MockObject|IDBConnection
*/
private $connection;
/**
* @var StatusService
*/
private $service;
public function setUp(): void
{
$this->appName = 'news';
$this->settings = $this->getMockBuilder(IConfig::class)
->disableOriginalConstructor()
->getMock();
$this->config = $this->getMockBuilder(Config::class)
$this->connection = $this->getMockBuilder(IDBConnection::class)
->disableOriginalConstructor()
->getMock();
$this->db = $this->getMockBuilder(IDBConnection::class)
->disableOriginalConstructor()
->getMock();
$this->service = new StatusService(
$this->settings, $this->db,
$this->config, $this->appName
);
$this->service = new StatusService($this->settings, $this->connection, 'news');
}
private function beforeStatus($cronMode='cron', $cronEnabled=true,
$version='1.0'
) {
$this->settings->expects($this->at(0))
->method('getAppValue')
->with(
$this->equalTo($this->appName),
$this->equalTo('installed_version')
)
->will($this->returnValue($version));
$this->settings->expects($this->at(1))
->method('getAppValue')
->with(
$this->equalTo('core'),
$this->equalTo('backgroundjobs_mode')
)
->will($this->returnValue($cronMode));
$this->config->expects($this->once())
->method('getUseCronUpdates')
->will($this->returnValue($cronEnabled));
}
/**
* @covers \OCA\News\Service\StatusService::getStatus
*/
public function testGetStatus()
{
$this->beforeStatus();
$this->settings->expects($this->exactly(2))
->method('getAppValue')
->withConsecutive(
['news', 'installed_version'],
['news', 'useCronUpdates']
)
->will($this->returnValueMap([
['news', 'installed_version', '', '1.0'],
['news', 'useCronUpdates', true, true],
]));
$this->settings->expects($this->exactly(1))
->method('getSystemValue')
->with('backgroundjobs_mode')
->will($this->returnValue('cron'));
$this->connection->expects($this->exactly(1))
->method('supports4ByteText')
->will($this->returnValue(true));
$expected = [
'version' => '1.0',
'warnings' => [
'improperlyConfiguredCron' => false,
'incorrectDbCharset' => false,
],
];
$response = $this->service->getStatus();
$this->assertEquals('1.0', $response['version']);
$this->assertFalse($response['warnings']['improperlyConfiguredCron']);
$this->assertEquals($expected, $response);
}
/**
* @covers \OCA\News\Service\StatusService::getStatus
*/
public function testGetStatusNoCorrectCronAjax()
{
$this->beforeStatus('ajax');
$this->settings->expects($this->exactly(2))
->method('getAppValue')
->withConsecutive(
['news', 'installed_version'],
['news', 'useCronUpdates']
)
->will($this->returnValueMap([
['news', 'installed_version', '', '1.0'],
['news', 'useCronUpdates', true, true],
]));
$this->settings->expects($this->exactly(1))
->method('getSystemValue')
->with('backgroundjobs_mode')
->will($this->returnValue('ajax'));
$this->connection->expects($this->exactly(1))
->method('supports4ByteText')
->will($this->returnValue(true));
$expected = [
'version' => '1.0',
'warnings' => [
'improperlyConfiguredCron' => true,
'incorrectDbCharset' => false,
],
];
$response = $this->service->getStatus();
$this->assertTrue($response['warnings']['improperlyConfiguredCron']);
$this->assertEquals($expected, $response);
}
/**
* @covers \OCA\News\Service\StatusService::getStatus
*/
public function testGetStatusNoCorrectCronTurnedOff()
{
$this->beforeStatus('ajax', false);
$this->settings->expects($this->exactly(2))
->method('getAppValue')
->withConsecutive(
['news', 'installed_version'],
['news', 'useCronUpdates']
)
->will($this->returnValueMap([
['news', 'installed_version', '', '1.0'],
['news', 'useCronUpdates', true, false],
]));
$this->settings->expects($this->exactly(1))
->method('getSystemValue')
->with('backgroundjobs_mode')
->will($this->returnValue('ajax'));
$this->connection->expects($this->exactly(1))
->method('supports4ByteText')
->will($this->returnValue(true));
$expected = [
'version' => '1.0',
'warnings' => [
'improperlyConfiguredCron' => false,
'incorrectDbCharset' => false,
],
];
$response = $this->service->getStatus();
$this->assertFalse($response['warnings']['improperlyConfiguredCron']);
$this->assertEquals($expected, $response);
}
/**
* @covers \OCA\News\Service\StatusService::getStatus
*/
public function testGetStatusReportsNon4ByteText()
{
$this->settings->expects($this->exactly(2))
->method('getAppValue')
->withConsecutive(
['news', 'installed_version'],
['news', 'useCronUpdates']
)
->will($this->returnValueMap([
['news', 'installed_version', '', '1.0'],
['news', 'useCronUpdates', true, false],
]));
$this->settings->expects($this->exactly(1))
->method('getSystemValue')
->with('backgroundjobs_mode')
->will($this->returnValue('ajax'));
$this->connection->expects($this->exactly(1))
->method('supports4ByteText')
->will($this->returnValue(false));
$expected = [
'version' => '1.0',
'warnings' => [
'improperlyConfiguredCron' => false,
'incorrectDbCharset' => true,
],
];
$response = $this->service->getStatus();
$this->assertEquals($expected, $response);
}
}

View File

@ -32,7 +32,7 @@ class OPMLExporterTest extends TestCase
/** @var Folder */
private $folder2;
protected function setUp()
protected function setUp(): void
{
$this->exporter = new OPMLExporter();
$this->folder1 = new Folder();
@ -55,7 +55,7 @@ class OPMLExporterTest extends TestCase
}
private function getAttribute($item, $name)
private function getAttribute($item, $name)
{
// used to fix scrutinizer errors
if ($item instanceof \DOMElement) {
@ -75,7 +75,7 @@ class OPMLExporterTest extends TestCase
}
public function testBuildReturnsFolders()
public function testBuildReturnsFolders()
{
$result = $this->exporter->build([$this->folder1, $this->folder2], []);
$xpath = new \DOMXpath($result);
@ -101,7 +101,7 @@ class OPMLExporterTest extends TestCase
}
public function testBuildReturnsOnlyOneFeedIfParentFolderNotThere()
public function testBuildReturnsOnlyOneFeedIfParentFolderNotThere()
{
$result = $this->exporter->build([], [$this->feed1, $this->feed2]);
$xpath = new \DOMXpath($result);
@ -127,7 +127,7 @@ class OPMLExporterTest extends TestCase
}
public function testBuildReturnsFeedsAndFolders()
public function testBuildReturnsFeedsAndFolders()
{
$result = $this->exporter->build(
[$this->folder1, $this->folder2],

View File

@ -28,7 +28,7 @@ class UpdaterTest extends TestCase
private $itemService;
private $updater;
protected function setUp()
protected function setUp(): void
{
$this->folderService = $this->getMockBuilder(FolderService::class)
->disableOriginalConstructor()
@ -46,7 +46,7 @@ class UpdaterTest extends TestCase
);
}
public function testBeforeUpdate()
public function testBeforeUpdate()
{
$this->folderService->expects($this->once())
->method('purgeDeleted');
@ -56,14 +56,14 @@ class UpdaterTest extends TestCase
}
public function testAfterUpdate()
public function testAfterUpdate()
{
$this->itemService->expects($this->once())
->method('autoPurgeOld');
$this->updater->afterUpdate();
}
public function testUpdate()
public function testUpdate()
{
$this->feedService->expects($this->once())
->method('updateAll');