hook_form_user_register_form_alter (Altering added fields) - drupal-8

The following does not work: (#description and #attributes does work. #required does not)
function bncreports_form_user_register_form_alter(&$form, FormStateInterface $form_state, $form_id)
{
$form['account']['mail']['#attributes'] = ['onblur' => "getElementById('edit-name').value=this.value.toLowerCase();"];
$form['account']['name']['#description'] = 'Use Email address as your username';
$form['account']['name']['#attributes'] = ['onblur' => 'this.value=this.value.toLowerCase();'];
$form['field_district']['widget']['#required'] = true;
}
Why not?

Related

How to use Moq in unit test that calls another method in same EF Repository

In my project I am using Repository.
I'm trying to unit test a SAVE method and return the call value via the Get method.
I'm having a Repository Query mockup issue when calling through the Get method. Can you help me in this case?
I Have a Class:
public class ClientRoleBo
{
private readonly IRepositoryBase<ClientRole> _repository;
public ClientRoleBo(IRepositoryBase<ClientRole> repository)
{
_repository = repository;
}
public Task<ClientRoleResp?> Get(Guid clientGuid, Guid id)
{
return Task.FromResult(
_repository.Query(x => x.Guid == id && x.ClientGuid == clientGuid && !x.IsDeleted)
.Select(x => new ClientRoleResp
{
Code = x.Code,
Guid = x.Guid,
IsActive = x.IsActive,
Name = x.Name
}).FirstOrDefault()
);
}
public async Task<ClientRole> Save(Guid clientGuid, Guid? guid, ClientRoleReq req)
{
ClientRole? data = null;
var existItem = _repository.Query(x => x.Code == req.Code && x.ClientGuid == clientGuid).FirstOrDefault();
if (existItem != null)
throw new HttpResponseException(400, "Exist clientrole");
data = new()
{
Code = req.Code,
Name = req.Name,
IsActive = req.IsActive,
ModifiedDate = DateTime.Now,
CreatedDate = DateTime.Now,
ClientGuid = clientGuid
};
await _repository.AddAsync(data);
return (await Get(clientGuid, data!.Guid))!;
}
}
I have a issue when code call method "Save" return data of method "Get" same Repository
My Mock Repository:
public class TestClientRole{
public static IRepositoryBase<TEntiy> MockRepo<TEntiy>(TEntiy[] data, Expression<Func<TEntiy, bool>> returnExpression = null) where TEntiy : class
{
var mock = new Mock<IRepositoryBase<TEntiy>>();
mock.Setup(x => x.Query(
It.IsAny<Expression<Func<TEntiy, bool>>>()
)).Returns(returnExpression != null ? data.AsQueryable().Where(returnExpression).AsEnumerable() : data.AsEnumerable());
return mock.Object;
}
[Fact]
public void Save()
{
var clientRoles = new ClientRole[]
{
new ClientRole
{
Code = "123",
Name = "Role1",
Guid = Guid.NewGuid(),
},
new ClientRole
{
Code = "1234",
Name = "Role2",
Guid = Guid.NewGuid(),
}
};
var mockRepo = MockRepo<ClientRole>(clientRoles, x => x.Guid == clientRoles[0].Guid);
var svc = new ClientRoleBo(mockRepo);
var res = svc.Save(Guid.NewGuid, null, new ClientRoleReq { Code = "Role", Name = "Role" }).GetAwaiter().GetResult();
Assert.True(res.Guid == clientRoles[0].Guid);
}
}

How to mock IdentityServerDbContext to add ApplicationUser

I tried following code but it's give exceptions:
var mockIdsDbContext = new Mock<IdentityServerDbContext>();
var applicationUser = new ApplicationUser()
{
Id = Guid.NewGuid().ToString(),
Email = "shashikant0423#gmail.com",
PhoneNumber = "999999999"
};
var usersTestData = new List<ApplicationUser>() { applicationUser };
var users = MockDbSet(usersTestData);
mockIdsDbContext.Setup(x => x.Users).Returns(userManager.Object.Users);
Mock<DbSet<T>> MockDbSet<T>(IEnumerable<T> list) where T : class, new()
{
IQueryable<T> queryableList = list.AsQueryable();
Mock<DbSet<T>> dbSetMock = new Mock<DbSet<T>>();
dbSetMock.As<IQueryable<T>>().Setup(x => x.Provider).Returns(queryableList.Provider);
dbSetMock.As<IQueryable<T>>().Setup(x => x.Expression).Returns(queryableList.Expression);
dbSetMock.As<IQueryable<T>>().Setup(x => x.ElementType).Returns(queryableList.ElementType);
dbSetMock.As<IQueryable<T>>().Setup(x => x.GetEnumerator()).Returns(() => queryableList.GetEnumerator());
//dbSetMock.Setup(x => x.Create()).Returns(new T());
return dbSetMock;
}
but I got error like:
Can not instantiate proxy of class: RenewPlus.IdentityServer.Data.IdentityServerDbContext. Could not find a parameterless constructor
Instead of mocking the rather complex DbContext I'd recommend instead using the Microsoft.EntityFrameworkCore.InMemory driver.
https://learn.microsoft.com/en-us/ef/core/providers/in-memory/

Error Unit test symfony

When I try to execute this unit test
I have a problem
so this is my function testErrors
.
public function testErrors(){
$client = static::createClient();
$crawler = $client->request('GET', '/add');
$form = $crawler->selectButton('save')->form(array(
'user[firstName]' => 'test1',
'user[lastName]' => 'test',
'user[email]' => 'test#gmail.com',
));
$crawler = $client->submit($form);
// 3 errors
$this->assertTrue($crawler->filter('.error_list')->count() == 3);
// Error firstName field
$this->assertTrue($crawler->filter('#firstName')->siblings()->first()->filter('.error_list')->count() == 1);
// Error lasName field
$this->assertTrue($crawler->filter('#lastName')->siblings()->first()->filter('.error_list')->count() == 1);
// Error email field
$this->assertTrue($crawler->filter('#email')->siblings()->first()->filter('.error_list')->count() == 1);
}
I have this problem
InvalidArgumentException: The current node list is empty .
this is my Controller
/**
* #Route("/add", name="addPage")
*/
public function AddAction(Request $request)
{
$user = new User();
$form = $this->createFormBuilder($user)
->add('email', TextType::class)
->add('firstName', TextType::class)
->add('lastName', TextType::class)
->add('save', SubmitType::class, array('label' => 'Add'))
->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$firstName = $form['firstName']->getData();
$lastName = $form['lastName']->getData();
$email = $form['email']->getData();
$user->setFirstName($firstName);
$user->setLastName($lastName);
$user->setEmail($email);
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
$this->addFlash('notice','user added' );
return $this->redirectToRoute('listPage');
}
I think it's your selectButton('save') what gives you the error. Try it with your button label Add instead of save

Unit testing a controller action method using MOQ

I have the following controller action method.
[HttpPost]
public ActionResult CreateProvider(Provider provider)
{
try
{
int providerCreationSuccessful = _repository.CreateProvider(provider);
if (providerCreationSuccessful == 2)
TempData["userIntimation"] = "Provider Registered Successfully";
//return RedirectToAction("ShowTheListOfProviders");
}
catch (Exception Ex)
{
_logger.Error(Ex.Message);
return View("Error");
}
return Json(new { url = Url.Action("ShowTheListOfProviders", "Provider") });
}
I had written the following Test case for the above method,which was working
[TestMethod()]
public void CreateProviderTest()
{
mockProviderRepository.Setup(provider => provider.CreateProvider(_provider)).Returns(new int());
var providerCreationResult = _providerController.CreateProvider(_provider) as ActionResult;
Assert.IsNotNull(providerCreationResult);
}
As can be seen from my code in the action method,I am redirecting using AJAX,hence returning JSON of the url to be redirected to.
Now,the test is obviously failing.I am new to unit tests and was wondering,what updates I needed to make to the Testmethod for it to pass.Please guide me.Thanks.
If you want test the Json Result contains the expected URL, you can write a test like below.
[TestMethod]
public void CreateProvider_Execute_EnsureJsonContainsExpectedUrl()
{
var context = new Mock<HttpContextBase>();
var request = new Mock<HttpRequestBase>();
var response = new Mock<HttpResponseBase>();
context.Setup(ctx => ctx.Request).Returns(request.Object);
context.Setup(ctx => ctx.Response).Returns(response.Object);
request.SetupGet(x => x.ApplicationPath).Returns("/");
request.SetupGet(x => x.Url).Returns(new Uri("http://localhost/a", UriKind.Absolute));
response.Setup(x => x.ApplyAppPathModifier(It.IsAny<string>())).Returns<string>(x => x);
context.SetupGet(x => x.Request).Returns(request.Object);
context.SetupGet(x => x.Response).Returns(response.Object);
RouteConfig.RegisterRoutes(new RouteCollection());
var repoStub = new Mock<IRepository>();
repoStub.Setup(x => x.CreateProvider(new Provider())).Returns(1);
var sut = new HomeController(repoStub.Object, new Mock<ILogger>().Object);
sut.Url = new UrlHelper(new RequestContext(context.Object, new RouteData()), routes);
var result = sut.CreateProvider(new Provider()) as JsonResult;
var actualUrl = GetValueFromJsonResult<string>(result, "url");
Assert.AreEqual<string>("/Provider/ShowTheListOfProviders", actualUrl);
}
private T GetValueFromJsonResult<T>(JsonResult jsonResult, string propertyName)
{
var property =
jsonResult.Data.GetType().GetProperties()
.Where(p => string.Compare(p.Name, propertyName) == 0)
.FirstOrDefault();
if (null == property)
throw new ArgumentException("propertyName not found", "propertyName");
return (T)property.GetValue(jsonResult.Data, null);
}

Symfony2 - Tests with FOSUserBundle

i would write a test for Symfony2 with FOSUserBundle.
At the moment i tried some ways and no one works.
I need a function like "createAuthClient".
Here is my basic class.
I post it because you could understand my problem better.
<?php
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\BrowserKit\Cookie;
class WebTestMain extends WebTestCase
{
protected static $container;
static protected function createClient(array $options = array(), array $server = array())
{
$client = parent::createClient($options, $server);
self::$container = self::$kernel->getContainer();
return $client;
}
static function createAuthClient(array $options = array(), array $server = array())
{
// see lines below with my tries
}
}
First try:
if(static::$kernel === null)
{
static::$kernel = static::createKernel($options);
static::$kernel->boot();
}
if(static::$container === null)
{
self::$container = self::$kernel->getContainer();
}
$parameters = self::$container->getParameter('test');
$server = array_merge(array('HTTP_HOST' => $parameters['host'], 'HTTP_USER_AGENT' => $parameters['useragent']), $server);
$client = self::createClient($options, $server);
$userProvider = self::$container->get('fos_user.user_manager');
$user = $userProvider->findUserBy(array('id' => 1));
$client->getCookieJar()->set(new Cookie('MOCKSESSID', true));
$session = self::$kernel->getContainer()->get('session');
$token = new UsernamePasswordToken($user, null, 'main', $user->getRoles());
$client->getContainer()->get('security.context')->setToken($token);
$session->set('_security_main', serialize($token));
return $client;
Then i searched and searched...
My second try.
if(static::$kernel === null)
{
static::$kernel = static::createKernel($options);
static::$kernel->boot();
}
if(static::$container === null)
{
self::$container = self::$kernel->getContainer();
}
$parameters = self::$container->getParameter('test');
$server = array_merge(
array(
'HTTP_HOST' => $parameters['host'],
'HTTP_USER_AGENT' => $parameters['useragent'],
'PHP_AUTH_USER' => 'admin',
'PHP_AUTH_PW' => 'admin'
),
$server
);
$client = static::createClient(array(), array());
$client->followRedirects();
return $client;
And here is my last try before i post this question...
$client = self::createClient($options, $server);
$parameters = self::$container->getParameter('test');
$server = array_merge(
array(
'HTTP_HOST' => $parameters['host'],
'HTTP_USER_AGENT' => $parameters['useragent']
),
$server
);
$client->setServerParameters($server);
$usermanager = self::$container->get('fos_user.user_manager');
$testuser = $usermanager->createUser();
$testuser->setUsername('test');
$testuser->setEmail('test#mail.org');
$testuser->setPlainPassword('test');
$usermanager->updateUser($testuser);
return $client;
Thank you in Advance.
The best way I have found to test with an authenticated user is to just visit your login page and submit the form with user name and password you have loaded from a fixture. This may seem slow and cumbersome but will test what the user will actually do. You can even create your own method to make using it quick and easy.
public function doLogin($username, $password) {
$crawler = $this->client->request('GET', '/login');
$form = $crawler->selectButton('_submit')->form(array(
'_username' => $username,
'_password' => $password,
));
$this->client->submit($form);
$this->assertTrue($this->client->getResponse()->isRedirect());
$crawler = $this->client->followRedirect();
}
Create an AbstractControllerTest and create an authorized client on setUp() as follow:
<?php
// ...
use Symfony\Component\BrowserKit\Cookie;
abstract class AbstractControllerTest extends WebTestCase
{
/**
* #var Client
*/
protected $client = null;
public function setUp()
{
$this->client = $this->createAuthorizedClient();
}
/**
* #return Client
*/
protected function createAuthorizedClient()
{
$client = static::createClient();
$container = $client->getContainer();
$session = $container->get('session');
/** #var $userManager \FOS\UserBundle\Doctrine\UserManager */
$userManager = $container->get('fos_user.user_manager');
/** #var $loginManager \FOS\UserBundle\Security\LoginManager */
$loginManager = $container->get('fos_user.security.login_manager');
$firewallName = $container->getParameter('fos_user.firewall_name');
$user = $userManager->findUserBy(array('username' => 'REPLACE_WITH_YOUR_TEST_USERNAME'));
$loginManager->loginUser($firewallName, $user);
// save the login token into the session and put it in a cookie
$container->get('session')->set('_security_' . $firewallName,
serialize($container->get('security.context')->getToken()));
$container->get('session')->save();
$client->getCookieJar()->set(new Cookie($session->getName(), $session->getId()));
return $client;
}
}
NOTE: Please, replace the username with your test username.
Then, extends the AbstractControllerTest and use the global $client to make requests as follow:
class ControllerTest extends AbstractControllerTest
{
public function testIndexAction()
{
$crawler = $this->client->request('GET', '/admin/');
$this->assertEquals(
Response::HTTP_OK,
$this->client->getResponse()->getStatusCode()
);
}
}
This method tested and works fine