[TEST] Raise test coverage for UserPanel to 100%

This commit is contained in:
Hugo Sales 2021-08-04 20:11:01 +00:00
parent 480665afc8
commit b5de80303a
No known key found for this signature in database
GPG Key ID: 7D0C7EAFC9D835A0
2 changed files with 194 additions and 64 deletions

View File

@ -41,6 +41,8 @@ use App\Core\Form;
use function App\Core\I18n\_m; use function App\Core\I18n\_m;
use App\Entity\UserNotificationPrefs; use App\Entity\UserNotificationPrefs;
use App\Util\Common; use App\Util\Common;
use App\Util\Exception\AuthenticationException;
use App\Util\Exception\ServerException;
use App\Util\Form\ArrayTransformer; use App\Util\Form\ArrayTransformer;
use App\Util\Form\FormFields; use App\Util\Form\FormFields;
use App\Util\Formatting; use App\Util\Formatting;
@ -50,7 +52,7 @@ use Functional as F;
use Misd\PhoneNumberBundle\Form\Type\PhoneNumberType; use Misd\PhoneNumberBundle\Form\Type\PhoneNumberType;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType; use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\LanguageType; use Symfony\Component\Form\Extension\Core\Type\LocaleType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType; use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType; use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Component\Form\Extension\Core\Type\TextType;
@ -71,14 +73,15 @@ class UserPanel extends AbstractController
*/ */
public function all_settings(Request $request) public function all_settings(Request $request)
{ {
$personal_form = $this->personal_info($request);
$account_form = $this->account($request); $account_form = $this->account($request);
$notifications_form = $this->notifications($request); $personal_form = $this->personal_info($request);
$notifications_form_array = $this->notifications($request);
return ['_template' => 'settings/base.html.twig', return [
'_template' => 'settings/base.html.twig',
'prof' => $personal_form->createView(), 'prof' => $personal_form->createView(),
'acc' => $account_form->createView(), 'acc' => $account_form->createView(),
'tabbed_forms_notify' => $notifications_form, 'tabbed_forms_notify' => $notifications_form_array,
]; ];
} }
@ -88,24 +91,23 @@ class UserPanel extends AbstractController
public function personal_info(Request $request) public function personal_info(Request $request)
{ {
$user = Common::user(); $user = Common::user();
$user = $user->getActor(); $actor = $user->getActor();
$extra = ['self_tags' => $user->getSelfTags()]; $extra = ['self_tags' => $actor->getSelfTags()];
$form_definition = [ $form_definition = [
['nickname', TextType::class, ['label' => _m('Nickname'), 'required' => true, 'help' => _m('1-64 lowercase letters or numbers, no punctuation or spaces.')]], ['nickname', TextType::class, ['label' => _m('Nickname'), 'required' => true, 'help' => _m('1-64 lowercase letters or numbers, no punctuation or spaces.')]],
['full_name', TextType::class, ['label' => _m('Full Name'), 'required' => false, 'help' => _m('A full name is required, if empty it will be set to your nickname.')]], ['full_name', TextType::class, ['label' => _m('Full Name'), 'required' => false, 'help' => _m('A full name is required, if empty it will be set to your nickname.')]],
['homepage', TextType::class, ['label' => _m('Homepage'), 'required' => false, 'help' => _m('URL of your homepage, blog, or profile on another site.')]], ['homepage', TextType::class, ['label' => _m('Homepage'), 'required' => false, 'help' => _m('URL of your homepage, blog, or profile on another site.')]],
['bio', TextareaType::class, ['label' => _m('Bio'), 'required' => false, 'help' => _m('Describe yourself and your interests.')]], ['bio', TextareaType::class, ['label' => _m('Bio'), 'required' => false, 'help' => _m('Describe yourself and your interests.')]],
['location', TextType::class, ['label' => _m('Location'), 'required' => false, 'help' => _m('Where you are, like "City, State (or Region), Country".')]], ['location', TextType::class, ['label' => _m('Location'), 'required' => false, 'help' => _m('Where you are, like "City, State (or Region), Country".')]],
['self_tags', TextType::class, ['label' => _m('Self Tags'), 'required' => false, 'transformer' => ArrayTransformer::class, 'help' => _m('Tags for yourself (letters, numbers, -, ., and _), comma- or space-separated.')]], ['self_tags', TextType::class, ['label' => _m('Self Tags'), 'required' => false, 'help' => _m('Tags for yourself (letters, numbers, -, ., and _), comma- or space-separated.'), 'transformer' => ArrayTransformer::class]],
['save', SubmitType::class, ['label' => _m('Save')]], ['save', SubmitType::class, ['label' => _m('Save personal info')]],
]; ];
$extra_step = function ($data, $extra_args) use ($user) { $extra_step = function ($data, $extra_args) use ($user) {
$user->setNickname($data['nickname']); $user->setNickname($data['nickname']);
}; };
$form = Form::handle($form_definition, $request, $user, $extra, $extra_step, [['self_tags' => $extra['self_tags']]]); $form = Form::handle($form_definition, $request, $actor, $extra, $extra_step, [['self_tags' => $extra['self_tags']]]);
return $form; return $form;
//return ['_template' => 'settings/profile.html.twig', 'prof' => $form->createView()];
} }
/** /**
@ -114,20 +116,40 @@ class UserPanel extends AbstractController
public function account(Request $request) public function account(Request $request)
{ {
$user = Common::user(); $user = Common::user();
$form_definition = [ // TODO Add support missing settings
$form = Form::create([
['outgoing_email', TextType::class, ['label' => _m('Outgoing email'), 'required' => true, 'help' => _m('Change the email we use to contact you')]], ['outgoing_email', TextType::class, ['label' => _m('Outgoing email'), 'required' => true, 'help' => _m('Change the email we use to contact you')]],
['incoming_email', TextType::class, ['label' => _m('Incoming email'), 'required' => true, 'help' => _m('Change the email you use to contact us (for posting, for instance)')]], ['incoming_email', TextType::class, ['label' => _m('Incoming email'), 'required' => true, 'help' => _m('Change the email you use to contact us (for posting, for instance)')]],
['password', TextType::class, ['label' => _m('Password'), 'required' => false, 'help' => _m('Change your password'), 'attr' => ['placeholder' => '********']]],
['old_password', TextType::class, ['label' => _m('Old password'), 'required' => false, 'help' => _m('Enter your old password for verification'), 'attr' => ['placeholder' => '********']]], ['old_password', TextType::class, ['label' => _m('Old password'), 'required' => false, 'help' => _m('Enter your old password for verification'), 'attr' => ['placeholder' => '********']]],
['language', LanguageType::class, ['label' => _m('Language'), 'required' => false, 'help' => _m('Your preferred language')]], FormFields::repeated_password(['required' => false]),
['language', LocaleType::class, ['label' => _m('Language'), 'required' => false, 'help' => _m('Your preferred language')]],
['phone_number', PhoneNumberType::class, ['label' => _m('Phone number'), 'required' => false, 'help' => _m('Your phone number'), 'data_class' => null]], ['phone_number', PhoneNumberType::class, ['label' => _m('Phone number'), 'required' => false, 'help' => _m('Your phone number'), 'data_class' => null]],
['save', SubmitType::class, ['label' => _m('Save')]], ['save', SubmitType::class, ['label' => _m('Save account info')]],
]; ]);
$form = Form::handle($form_definition, $request, $user); $form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$data = $form->getData();
if (!is_null($data['old_password'])) {
$data['password'] = $form->get('password')->getData();
if (!($user->changePassword($data['old_password'], $data['password']))) {
throw new AuthenticationException(_m('The provided password is incorrect'));
}
}
unset($data['old_password'], $data['password']);
foreach ($data as $key => $val) {
$method = 'set' . ucfirst(Formatting::snakeCaseToCamelCase($key));
if (method_exists($user, $method)) {
$user->{$method}($val);
}
}
DB::flush();
}
return $form; return $form;
//return ['_template' => 'settings/account.html.twig', 'acc' => $form->createView()];
} }
/** /**
@ -147,12 +169,12 @@ class UserPanel extends AbstractController
$label = str_replace('_', ' ', ucfirst($name)); $label = str_replace('_', ' ', ucfirst($name));
$labels = [ $labels = [
'target_actor_id' => 'Target Actors', 'target_gsactor_id' => 'Target Actors',
'dm' => 'DM', 'dm' => 'DM',
]; ];
$help = [ $help = [
'target_actor_id' => 'If specified, these settings apply only to these profiles (comma- or space-separated list)', 'target_gsactor_id' => 'If specified, these settings apply only to these profiles (comma- or space-separated list)',
'activity_by_followed' => 'Notify me when someone I follow has new activity', 'activity_by_followed' => 'Notify me when someone I follow has new activity',
'mention' => 'Notify me when mentions me in a notice', 'mention' => 'Notify me when mentions me in a notice',
'reply' => 'Notify me when someone replies to a notice made by me', 'reply' => 'Notify me when someone replies to a notice made by me',
@ -169,13 +191,15 @@ class UserPanel extends AbstractController
$form_defs['placeholder'][$name] = [$name, CheckboxType::class, ['data' => $val, 'label' => _m($labels[$name] ?? $label), 'help' => _m($help[$name])]]; $form_defs['placeholder'][$name] = [$name, CheckboxType::class, ['data' => $val, 'label' => _m($labels[$name] ?? $label), 'help' => _m($help[$name])]];
break; break;
case Types::INTEGER: case Types::INTEGER:
if ($name == 'target_actor_id') { if ($name == 'target_gsactor_id') {
$form_defs['placeholder'][$name] = ['target_actors', TextType::class, ['data' => $val, 'label' => _m($labels[$name]), 'help' => _m($help[$name])], 'transformer' => ActorArrayTransformer::class]; $form_defs['placeholder'][$name] = [$name, TextType::class, ['data' => $val, 'label' => _m($labels[$name]), 'help' => _m($help[$name])], 'transformer' => ActorArrayTransformer::class];
} }
break; break;
default: default:
dd($type_str); // @codeCoverageIgnoreStart
throw new Exception("Structure of table user_notification_prefs changed in a way not accounted to in notification settings ({$name})", 500); throw new ServerException(_m('Internal server error'));
Log::critical("Structure of table user_notification_prefs changed in a way not accounted to in notification settings ({$name}): " . $type_str);
// @codeCoverageIgnoreEnd
} }
} }
@ -195,6 +219,7 @@ class UserPanel extends AbstractController
if ($form->isSubmitted() && $form->isValid()) { if ($form->isSubmitted() && $form->isValid()) {
$data = $form->getData(); $data = $form->getData();
unset($data['translation_domain']); unset($data['translation_domain']);
try {
[$ent, $is_update] = UserNotificationPrefs::createOrUpdate( [$ent, $is_update] = UserNotificationPrefs::createOrUpdate(
array_merge(['user_id' => $user->getId(), 'transport' => $transport_name], $data), array_merge(['user_id' => $user->getId(), 'transport' => $transport_name], $data),
find_by_keys: ['user_id', 'transport'] find_by_keys: ['user_id', 'transport']
@ -203,6 +228,12 @@ class UserPanel extends AbstractController
DB::persist($ent); DB::persist($ent);
} }
DB::flush(); DB::flush();
// @codeCoverageIgnoreStart
} catch (\Exception $e) {
// Somehow, the exception doesn't bubble up in phpunit
dd($data, $e);
// @codeCoverageIgnoreEnd
}
} }
} }
@ -210,9 +241,5 @@ class UserPanel extends AbstractController
return $f->createView(); return $f->createView();
}); });
return $tabbed_forms; return $tabbed_forms;
/*return [
'_template' => 'settings/notifications.html.twig',
'tabbed_forms' => $tabbed_forms,
];*/
} }
} }

View File

@ -23,24 +23,127 @@ namespace App\Tests\Core;
use App\Core\DB\DB; use App\Core\DB\DB;
use App\Util\GNUsocialTestCase; use App\Util\GNUsocialTestCase;
use Symfony\Component\HttpFoundation\Request; use Functional as F;
use Jchook\AssertThrows\AssertThrows;
class UserPanelTest extends GNUsocialTestCase class UserPanelTest extends GNUsocialTestCase
{ {
// public function testPersonalInfo() use AssertThrows;
// {
// $client = static::createClient();
// $user = DB::findOneBy('local_user', ['nickname' => 'form_test_user']);
// $client->loginUser($user);
// $client->request('GET', '/settings'); /**
// $client->followRedirect(); * @covers \App\Controller\UserPanel::all_settings
// $this->assertResponseIsSuccessful(); * @covers \App\Controller\UserPanel::personal_info
// $this->assertRouteSame('settings_personal_info'); */
// $crawler = $client->submitForm('Save', [ public function testPersonalInfo()
// 'nickname' => 'form_test_user_new_nickname', {
// 'full_name' => 'Form User', $client = static::createClient();
// 'homepage' => '', $user = DB::findOneBy('local_user', ['nickname' => 'form_personal_info_test_user']);
// ]); $client->loginUser($user);
// }
$client->request('GET', '/settings');
$this->assertResponseIsSuccessful();
$crawler = $client->submitForm('Save personal info', [
'save[nickname]' => 'form_test_user_new_nickname',
'save[full_name]' => 'Form User',
'save[homepage]' => 'https://gnu.org',
'save[bio]' => 'I was born at a very young age',
'save[location]' => 'right here',
'save[self_tags]' => 'foo bar',
]);
$changed_user = DB::findOneBy('local_user', ['id' => $user->getId()]);
$actor = $changed_user->getActor();
static::assertSame($changed_user->getNickname(), 'form_test_user_new_nickname');
static::assertSame($actor->getNickname(), 'form_test_user_new_nickname');
static::assertSame($actor->getFullName(), 'Form User');
static::assertSame($actor->getHomepage(), 'https://gnu.org');
static::assertSame($actor->getBio(), 'I was born at a very young age');
static::assertSame($actor->getLocation(), 'right here');
$tags = F\map($actor->getSelfTags(), fn ($tag) => $tag->getTag());
sort($tags);
static::assertSame($tags, ['bar', 'foo']);
}
/**
* @covers \App\Controller\UserPanel::account
* @covers \App\Controller\UserPanel::all_settings
*/
public function testAccount()
{
$client = static::createClient();
$user = DB::findOneBy('local_user', ['nickname' => 'form_account_test_user']);
$client->loginUser($user);
$client->request('GET', '/settings');
$this->assertResponseIsSuccessful();
$crawler = $client->submitForm('Save account info', [
'save[outgoing_email]' => 'outgoing@provider',
'save[incoming_email]' => 'incoming@provider',
'save[old_password]' => 'some password',
'save[password][first]' => 'this is some test password',
'save[password][second]' => 'this is some test password',
'save[language]' => 'pt',
'save[phone_number]' => '+351908555842', // from fakenumber.net
]);
$changed_user = DB::findOneBy('local_user', ['id' => $user->getId()]);
static::assertSame($changed_user->getOutgoingEmail(), 'outgoing@provider');
static::assertSame($changed_user->getIncomingEmail(), 'incoming@provider');
static::assertTrue($changed_user->checkPassword('this is some test password'));
static::assertSame($changed_user->getLanguage(), 'pt');
static::assertSame($changed_user->getPhoneNumber()->getNationalNumber(), '908555842');
}
/**
* @covers \App\Controller\UserPanel::account
* @covers \App\Controller\UserPanel::all_settings
*/
public function testAccountWrongPassword()
{
$client = static::createClient();
$user = DB::findOneBy('local_user', ['nickname' => 'form_account_test_user']);
$client->loginUser($user);
$client->request('GET', '/settings');
$this->assertResponseIsSuccessful();
$crawler = $client->submitForm('Save account info', [
'save[old_password]' => 'some wrong password',
'save[password][first]' => 'this is some test password',
'save[password][second]' => 'this is some test password',
]);
$this->assertResponseStatusCodeSame(500); // 401 in future
$this->assertSelectorTextContains('.stacktrace', 'AuthenticationException');
}
/**
* @covers \App\Controller\UserPanel::all_settings
* @covers \App\Controller\UserPanel::notifications
*/
public function testNotifications()
{
$client = static::createClient();
$user = DB::findOneBy('local_user', ['nickname' => 'form_account_test_user']);
$client->loginUser($user);
$client->request('GET', '/settings');
$this->assertResponseIsSuccessful();
$crawler = $client->submitForm('Save notification settings for Email', [
'save_email[activity_by_followed]' => false,
'save_email[mention]' => true,
'save_email[reply]' => false,
'save_email[follow]' => true,
'save_email[favorite]' => false,
'save_email[nudge]' => true,
'save_email[dm]' => false,
'save_email[enable_posting]' => true,
]);
$settings = DB::findOneBy('user_notification_prefs', ['user_id' => $user->getId(), 'transport' => 'email']);
static::assertSame($settings->getActivityByFollowed(), false);
static::assertSame($settings->getMention(), true);
static::assertSame($settings->getReply(), false);
static::assertSame($settings->getFollow(), true);
static::assertSame($settings->getFavorite(), false);
static::assertSame($settings->getNudge(), true);
static::assertSame($settings->getDm(), false);
static::assertSame($settings->getEnablePosting(), true);
}
} }