[TESTS] Fix remaining tests, back to 100% passed. Some minor semantic changes

This commit is contained in:
Hugo Sales 2021-11-16 14:10:19 +00:00
parent c68d7ae406
commit b4ce77320e
No known key found for this signature in database
GPG Key ID: 7D0C7EAFC9D835A0
10 changed files with 48 additions and 50 deletions

View File

@ -194,7 +194,7 @@ class GNUsocial implements EventSubscriberInterface
$this->request = $event->getRequest(); $this->request = $event->getRequest();
// Save the target path, so we can redirect back after logging in // Save the target path, so we can redirect back after logging in
if (!(!$event->isMasterRequest() || $this->request->isXmlHttpRequest() || Common::isRoute(['login', 'register', 'logout']))) { if (!(!$event->isMainRequest() || $this->request->isXmlHttpRequest() || Common::isRoute(['login', 'register', 'logout']))) {
$this->saveTargetPath($this->session, 'main', $this->request->getBaseUrl()); $this->saveTargetPath($this->session, 'main', $this->request->getBaseUrl());
} }

View File

@ -24,6 +24,7 @@ class CoreFixtures extends Fixture
foreach ([ foreach ([
'taken_user' => [LocalUser::class, 'setId', ['password' => LocalUser::hashPassword('foobar'), 'outgoing_email' => 'email@provider']], 'taken_user' => [LocalUser::class, 'setId', ['password' => LocalUser::hashPassword('foobar'), 'outgoing_email' => 'email@provider']],
'some_user' => [LocalUser::class, 'setId', []], 'some_user' => [LocalUser::class, 'setId', []],
'local_user_test_user' => [LocalUser::class, 'setId', ['password' => LocalUser::hashPassword('foobar')]],
'form_personal_info_test_user' => [LocalUser::class, 'setId', []], 'form_personal_info_test_user' => [LocalUser::class, 'setId', []],
'form_account_test_user' => [LocalUser::class, 'setId', ['password' => LocalUser::hashPassword('some password')]], 'form_account_test_user' => [LocalUser::class, 'setId', ['password' => LocalUser::hashPassword('some password')]],
'taken_group' => [LocalGroup::class, 'setGroupId', []], 'taken_group' => [LocalGroup::class, 'setGroupId', []],

View File

@ -98,14 +98,18 @@ abstract class Common
/** /**
* Set sysadmin's configuration preferences for GNU social * Set sysadmin's configuration preferences for GNU social
*
* @param $transient keep this setting in memory only
*/ */
public static function setConfig(string $section, string $setting, $value): void public static function setConfig(string $section, string $setting, $value, bool $transient = false): void
{ {
self::$config[$section][$setting] = $value; self::$config[$section][$setting] = $value;
$diff = self::arrayDiffRecursive(self::$config, self::$defaults); if (!$transient) {
$yaml = (new Yaml\Dumper(indentation: 2))->dump(['parameters' => ['locals' => ['gnusocial' => $diff]]], Yaml\Yaml::DUMP_OBJECT_AS_MAP); $diff = self::arrayDiffRecursive(self::$config, self::$defaults);
rename(INSTALLDIR . '/social.local.yaml', INSTALLDIR . '/social.local.yaml.back'); $yaml = (new Yaml\Dumper(indentation: 2))->dump(['parameters' => ['locals' => ['gnusocial' => $diff]]], Yaml\Yaml::DUMP_OBJECT_AS_MAP);
file_put_contents(INSTALLDIR . '/social.local.yaml', $yaml); rename(INSTALLDIR . '/social.local.yaml', INSTALLDIR . '/social.local.yaml.back');
file_put_contents(INSTALLDIR . '/social.local.yaml', $yaml);
}
} }
public static function getConfigDefaults() public static function getConfigDefaults()

View File

@ -23,14 +23,15 @@ declare(strict_types = 1);
namespace App\Util; namespace App\Util;
use App\Entity\LocalUser; use App\Core\DB\DB;
use App\Util\Exception\DuplicateFoundException;
use App\Util\Exception\NicknameEmptyException; use App\Util\Exception\NicknameEmptyException;
use App\Util\Exception\NicknameException; use App\Util\Exception\NicknameException;
use App\Util\Exception\NicknameInvalidException; use App\Util\Exception\NicknameInvalidException;
use App\Util\Exception\NicknameNotAllowedException; use App\Util\Exception\NicknameNotAllowedException;
use App\Util\Exception\NicknameTakenException; use App\Util\Exception\NicknameTakenException;
use App\Util\Exception\NicknameTooLongException; use App\Util\Exception\NicknameTooLongException;
use App\Util\Exception\NicknameTooShortException; use App\Util\Exception\NotFoundException;
use App\Util\Exception\NotImplementedException; use App\Util\Exception\NotImplementedException;
use Functional as F; use Functional as F;
use InvalidArgumentException; use InvalidArgumentException;
@ -58,7 +59,7 @@ class Nickname
/** /**
* Maximum number of characters in a canonical-form nickname. Changes must validate regexs * Maximum number of characters in a canonical-form nickname. Changes must validate regexs
*/ */
const MAX_LEN = 64; public const MAX_LEN = 64;
/** /**
* Regex fragment for pulling a formated nickname *OR* ID number. * Regex fragment for pulling a formated nickname *OR* ID number.
@ -69,8 +70,6 @@ class Nickname
* if you just need to check if it's properly formatted. * if you just need to check if it's properly formatted.
* *
* This, DISPLAY_FMT, and CANONICAL_FMT should not be enclosed in []s. * This, DISPLAY_FMT, and CANONICAL_FMT should not be enclosed in []s.
*
* @fixme would prefer to define in reference to the other constants
*/ */
public const INPUT_FMT = '(?:[0-9]+|[0-9a-zA-Z_]{1,' . self::MAX_LEN . '})'; public const INPUT_FMT = '(?:[0-9]+|[0-9a-zA-Z_]{1,' . self::MAX_LEN . '})';
@ -110,7 +109,8 @@ class Nickname
* *
* This, INPUT_FMT and DISPLAY_FMT should not be enclosed in []s. * This, INPUT_FMT and DISPLAY_FMT should not be enclosed in []s.
*/ */
const CANONICAL_FMT = '[0-9a-z]{1,' . self::MAX_LEN . '}'; // const CANONICAL_FMT = '[0-9A-Za-z_]{1,' . self::MAX_LEN . '}';
public const CANONICAL_FMT = self::DISPLAY_FMT;
/** /**
* Regex with non-capturing group that matches whitespace and some * Regex with non-capturing group that matches whitespace and some
@ -128,11 +128,7 @@ class Nickname
/** /**
* Check if a nickname is valid or throw exceptions if it's not. * Check if a nickname is valid or throw exceptions if it's not.
* Can optionally check if the nickname is currently in use * Can optionally check if the nickname is currently in use
* @param string $nickname *
* @param bool $check_already_used
* @param int $which
* @param bool $check_is_allowed
* @return bool
* @throws NicknameEmptyException * @throws NicknameEmptyException
* @throws NicknameNotAllowedException * @throws NicknameNotAllowedException
* @throws NicknameTakenException * @throws NicknameTakenException
@ -152,9 +148,13 @@ class Nickname
} elseif ($check_already_used) { } elseif ($check_already_used) {
switch ($which) { switch ($which) {
case self::CHECK_LOCAL_USER: case self::CHECK_LOCAL_USER:
$lu = LocalUser::getWithPK(['nickname' => $nickname]); try {
if ($lu !== null) { $lu = DB::findOneBy('local_user', ['nickname' => $nickname]);
throw new NicknameTakenException($lu->getActor()); throw new NicknameTakenException($lu->getActor());
} catch (NotFoundException) {
// continue
} catch (DuplicateFoundException) {
Log::critial("Duplicate entry in `local_user` for nickname={$nickname}");
} }
break; break;
// @codeCoverageIgnoreStart // @codeCoverageIgnoreStart
@ -176,7 +176,7 @@ class Nickname
* The canonical form will be returned, or an exception thrown if invalid. * The canonical form will be returned, or an exception thrown if invalid.
* *
* @throws NicknameEmptyException * @throws NicknameEmptyException
* @throws NicknameException (base class) * @throws NicknameException (base class)
* @throws NicknameInvalidException * @throws NicknameInvalidException
* @throws NicknameNotAllowedException * @throws NicknameNotAllowedException
* @throws NicknameTakenException * @throws NicknameTakenException
@ -185,7 +185,6 @@ class Nickname
public static function normalize(string $nickname, bool $check_already_used = false, int $which = self::CHECK_LOCAL_USER, bool $check_is_allowed = true): string public static function normalize(string $nickname, bool $check_already_used = false, int $which = self::CHECK_LOCAL_USER, bool $check_is_allowed = true): string
{ {
$nickname = trim($nickname); $nickname = trim($nickname);
$nickname = str_replace('_', '', $nickname);
$nickname = mb_strtolower($nickname); $nickname = mb_strtolower($nickname);
// We could do UTF-8 normalization (å to a, etc.) with something like Normalizer::normalize($nickname, Normalizer::FORM_C) // We could do UTF-8 normalization (å to a, etc.) with something like Normalizer::normalize($nickname, Normalizer::FORM_C)
// We won't as it could confuse tremendously the user, he must know what is valid and should fix his own input // We won't as it could confuse tremendously the user, he must know what is valid and should fix his own input
@ -218,8 +217,6 @@ class Nickname
/** /**
* Is the given string a valid canonical nickname form? * Is the given string a valid canonical nickname form?
* @param string $nickname
* @return bool
*/ */
public static function isCanonical(string $nickname): bool public static function isCanonical(string $nickname): bool
{ {
@ -228,8 +225,7 @@ class Nickname
/** /**
* Is the given string in our nickname blacklist? * Is the given string in our nickname blacklist?
* @param string $nickname *
* @return bool
* @throws NicknameEmptyException * @throws NicknameEmptyException
* @throws NicknameInvalidException * @throws NicknameInvalidException
* @throws NicknameNotAllowedException * @throws NicknameNotAllowedException
@ -242,8 +238,15 @@ class Nickname
if (empty($reserved)) { if (empty($reserved)) {
return false; return false;
} }
return in_array($nickname, array_merge($reserved, F\map($reserved, function ($n) { return \in_array(
return self::normalize($n, check_already_used: false, check_is_allowed: true); $nickname,
}))); array_merge(
$reserved,
F\map(
$reserved,
fn ($n) => self::normalize($n, check_already_used: false, check_is_allowed: false),
),
),
);
} }
} }

View File

@ -80,7 +80,7 @@ class DBTest extends GNUsocialTestCase
public function testPersistWithSameId() public function testPersistWithSameId()
{ {
$actor = Actor::create(['nickname' => 'test', 'normalized_nickname' => 'test']); $actor = Actor::create(['nickname' => 'test', 'bio' => 'some very interesting bio']);
$user = LocalUser::create(['nickname' => 'test']); $user = LocalUser::create(['nickname' => 'test']);
$id = DB::persistWithSameId($actor, $user, fn ($id) => $id); $id = DB::persistWithSameId($actor, $user, fn ($id) => $id);
static::assertTrue($id != 0); static::assertTrue($id != 0);

View File

@ -51,6 +51,6 @@ class RouterTest extends GNUsocialTestCase
public function testURLGen() public function testURLGen()
{ {
parent::bootKernel(); parent::bootKernel();
static::assertSame('/thumbnail/1', Router::url('thumbnail', ['id' => 1])); static::assertSame('/attachment/1/thumbnail/big', Router::url('attachment_thumbnail', ['id' => 1, 'size' => 'big']));
} }
} }

View File

@ -34,7 +34,7 @@ class ActorTest extends GNUsocialTestCase
public function testGetAvatarUrl() public function testGetAvatarUrl()
{ {
$actor = DB::findOneBy('actor', ['nickname' => 'taken_user']); $actor = DB::findOneBy('actor', ['nickname' => 'taken_user']);
static::assertSame("/{$actor->getId()}/avatar", $actor->getAvatarUrl()); static::assertSame('/avatar/default', $actor->getAvatarUrl());
} }
public function testSelfTags() public function testSelfTags()

View File

@ -50,7 +50,8 @@ class LocalUserTest extends GNUsocialTestCase
public function testChangePassword() public function testChangePassword()
{ {
parent::bootKernel(); parent::bootKernel();
$user = LocalUser::getByNickname('form_personal_info_test_user'); $user = LocalUser::getByNickname('local_user_test_user');
static::assertFalse($user->changePassword(old_password_plain_text: '', new_password_plain_text: 'password', override: false));
static::assertTrue($user->changePassword(old_password_plain_text: '', new_password_plain_text: 'password', override: true)); static::assertTrue($user->changePassword(old_password_plain_text: '', new_password_plain_text: 'password', override: true));
static::assertTrue($user->changePassword(old_password_plain_text: 'password', new_password_plain_text: 'new_password', override: false)); static::assertTrue($user->changePassword(old_password_plain_text: 'password', new_password_plain_text: 'new_password', override: false));
static::assertFalse($user->changePassword(old_password_plain_text: 'wrong_password', new_password_plain_text: 'new_password', override: false)); static::assertFalse($user->changePassword(old_password_plain_text: 'wrong_password', new_password_plain_text: 'new_password', override: false));

View File

@ -30,7 +30,6 @@ use App\Util\Exception\NicknameTooLongException;
use App\Util\GNUsocialTestCase; use App\Util\GNUsocialTestCase;
use App\Util\Nickname; use App\Util\Nickname;
use Jchook\AssertThrows\AssertThrows; use Jchook\AssertThrows\AssertThrows;
use Symfony\Component\DependencyInjection\ParameterBag\ContainerBagInterface;
class NicknameTest extends GNUsocialTestCase class NicknameTest extends GNUsocialTestCase
{ {
@ -38,12 +37,8 @@ class NicknameTest extends GNUsocialTestCase
public function testNormalize() public function testNormalize()
{ {
$conf = ['nickname' => ['min_length' => 4, 'reserved' => ['this_nickname_is_reserved']]]; static::bootKernel();
$cb = $this->createMock(ContainerBagInterface::class); Common::setConfig('nickname', 'blacklist', ['this_nickname_is_reserved'], transient: true);
static::assertTrue($cb instanceof ContainerBagInterface);
$cb->method('get')
->willReturnMap([['gnusocial', $conf], ['gnusocial_defaults', $conf]]);
Common::setupConfig($cb);
static::assertThrows(NicknameTooLongException::class, fn () => Nickname::normalize(str_repeat('longstring-', 128), check_already_used: false)); static::assertThrows(NicknameTooLongException::class, fn () => Nickname::normalize(str_repeat('longstring-', 128), check_already_used: false));
static::assertThrows(NicknameInvalidException::class, fn () => Nickname::normalize('null\0', check_already_used: false)); static::assertThrows(NicknameInvalidException::class, fn () => Nickname::normalize('null\0', check_already_used: false));
@ -55,7 +50,6 @@ class NicknameTest extends GNUsocialTestCase
// static::assertThrows(NicknameInvalidException::class, fn () => Nickname::normalize('FóóBár', check_already_used: false)); // static::assertThrows(NicknameInvalidException::class, fn () => Nickname::normalize('FóóBár', check_already_used: false));
static::assertThrows(NicknameNotAllowedException::class, fn () => Nickname::normalize('this_nickname_is_reserved', check_already_used: false)); static::assertThrows(NicknameNotAllowedException::class, fn () => Nickname::normalize('this_nickname_is_reserved', check_already_used: false));
static::bootKernel();
static::assertSame('foobar', Nickname::normalize('foobar', check_already_used: true)); static::assertSame('foobar', Nickname::normalize('foobar', check_already_used: true));
static::assertThrows(NicknameTakenException::class, fn () => Nickname::normalize('taken_user', check_already_used: true)); static::assertThrows(NicknameTakenException::class, fn () => Nickname::normalize('taken_user', check_already_used: true));
} }
@ -74,18 +68,13 @@ class NicknameTest extends GNUsocialTestCase
public function testIsReserved() public function testIsReserved()
{ {
$conf = ['nickname' => ['min_length' => 4, 'reserved' => ['this_nickname_is_reserved']]]; static::bootKernel();
$cb = $this->createMock(ContainerBagInterface::class); Common::setConfig('nickname', 'blacklist', ['this_nickname_is_reserved'], transient: true);
static::assertTrue($cb instanceof ContainerBagInterface);
$cb->method('get')->willReturnMap([['gnusocial', $conf], ['gnusocial_defaults', $conf]]);
Common::setupConfig($cb);
static::assertTrue(Nickname::isBlacklisted('this_nickname_is_reserved')); static::assertTrue(Nickname::isBlacklisted('this_nickname_is_reserved'));
static::assertFalse(Nickname::isBlacklisted('this_nickname_is_not_reserved')); static::assertFalse(Nickname::isBlacklisted('this_nickname_is_not_reserved'));
$conf = ['nickname' => ['min_length' => 4, 'reserved' => []]]; Common::setConfig('nickname', 'blacklist', [], transient: true);
$cb = $this->createMock(ContainerBagInterface::class);
$cb->method('get')->willReturnMap([['gnusocial', $conf], ['gnusocial_defaults', $conf]]);
Common::setupConfig($cb);
static::assertFalse(Nickname::isBlacklisted('this_nickname_is_reserved')); static::assertFalse(Nickname::isBlacklisted('this_nickname_is_reserved'));
} }
} }

View File

@ -45,7 +45,7 @@ class TemporaryFileTest extends WebTestCase
$temp = new TemporaryFile(); $temp = new TemporaryFile();
$filepath = $temp->getRealPath(); $filepath = $temp->getRealPath();
static::assertThrows(TemporaryFileException::class, fn () => $temp->commit($filepath)); static::assertThrows(TemporaryFileException::class, fn () => $temp->commit($filepath));
static::assertThrows(TemporaryFileException::class, fn () => $temp->commit('/root/cannot_write_here')); static::assertThrows(TemporaryFileException::class, fn () => $temp->commit('/root/not-a-folder/cannot_write_here'));
} }
public function testCreateDirectory() public function testCreateDirectory()