Unable to get mock container to return anything but null - symfony

I have a test that fails due to me being unable to successfully stub the get method of the Controller:
1) Tests\my-project\BackendBundle\Service\PdfGenerateServiceTest::test_getHttpPathToPtImage_should_return_the_default_avatar_when_photo_is_null
TypeError: Argument 1 passed to Mock_Pdf_d0288d34::setLogger() must implement interface Psr\Log\LoggerInterface, null given, called in /var/www/my-project/src/my-project/BackendBundle/Service/PdfGenerateService.php on line 66
The test
public function test_getHttpPathToPtImage_should_return_the_default_avatar_when_photo_is_null()
{
$protocolAndHost = "http://foo.bar.com";
$service = new PdfGenerateService($this->createFileServiceMock(), $this->createTranslatorMock(), $this->createSnappyMock(), $this->createContainerMock(), $protocolAndHost);
$httpPathToPtImage = $service->getHttpPathToPtImage(null);
self::assertEquals($httpPathToPtImage, $protocolAndHost . "abc/def");
}
The constructor that is failing
public function __construct(FileService $fileService, Translator $translator, Pdf $snappy, ContainerInterface $container, string $protocolAndHost)
{
$this->fileService = $fileService;
$this->translator = $translator;
$this->currentLocale = $this->translator->getLocale();
/* Could reconfigure the service using `service.yml` to pass these in using DI */
$this->twig = $container->get('twig');
$this->logger = $container->get('logger'); // <--- should not be null
$timeoutInSeconds = 15; // can be high, since the job is done async in a job (user does not wait)
$snappy->setLogger($this->logger); // <--- THIS FAILS due to $this->logger being null
The stubs
protected function createContainerMock()
{
$containerMock = $this->createMock('Symfony\Component\DependencyInjection\ContainerInterface');
$loggerMock = $this->createLoggerMock();
$containerMock->method('get')->will($this->returnValueMap([
['logger', $loggerMock]
]));
return $containerMock;
}
I do not really understand why the the get('logger') call just returns null when I have setup a mock to be returned using the returnValueMap call above.
By chance, I just found a SO question on this topic where someone mentioned that you need to supply all parameters, even optional ones. I then checked out the interface, which does indeed list a second parameter:
public function get($id, $invalidBehavior = self::EXCEPTION_ON_INVALID_REFERENCE);
Still, changing the map to ['logger', null, $loggerMock] made no change, so I am a bit at a loss as to what to try next.
Phpunit 6.5, PHP 7.2, Symfony 3.4

You were really close to the solution. When providing a value for an optional parameter in returnValueMap, you must use the value itself, not just null.
So instead of
['logger', null, $loggerMock]
try specifying
['logger', ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, $loggerMock]
Complete call looks like this:
$containerMock->method('get')->will($this->returnValueMap([
['logger', ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, $loggerMock]
]));

Related

what is the correct way to pass not services to the constructor of a custom normalize in symfony

I'm creating my own Normalizer, based on the tutorial on the Symfony documentation page https://symfony.com/doc/current/serializer/custom_normalizer.html, which I find incomplete because it tells you how to create it but not apply it, that's the first point.
Then based on my little experience in Symfony I'm trying to guess how to pass data to the normalizer to be the proper calculations, the data I'm trying to pass are not services, which can be a String or a Request object, but none of this data allows me, really I need to understand or I need to refactor to get what I want?
I put my normalizer code to understand well what I am looking for.
Normalizer:
<?php
namespace App\Serializer;
use App\Entity\Task;
use App\Traits\TaskControl;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
class TaskNormalizer implements NormalizerInterface
{
use TaskControl;
private $normalizer;
private $rangeDate;
public function __construct(ObjectNormalizer $normalizer, $rangeDate )
{
$this->normalizer = $normalizer;
$this->rangeDate = $rangeDate;
}
public function normalize($task, $format = null, array $context = [])
{
$data = $this->normalizer->normalize($task, $format, $context);
dd($this->rangeDate);
$data['totalWork'] = $this->timeTask($task,$this->rangeDate);
return $data;
}
public function supportsNormalization($task, $format = null, array $context = []): bool
{
return $task instanceof Task;
}
}
Applying the normalizer:
Passing the variable $rangeDate that is dynamic from object Request.
$rangeDate = $request->request->get('range','all');
$serializer = new Serializer([new TaskNormalizer($normalizer,$rangeDate)]);
$data = $serializer->normalize($attendances, null, ['attributes' => $attributes]);
and this is the error I get:
Cannot autowire service "App\Serializer\TaskNormalizer": argument "$rangeDate" of method "__construct()" has no type-hint, you should configure its value explicitly.
Why would you pass your range date as constructor argument?
Normalizer is a service dependency, rangeDate is a dynamic value.
You can pass it as an argument for the method normalize instead either as a new argument, or in the context array:
$rangeDate = $request->request->get('range','all');
$serializer = new Serializer([new TaskNormalizer($normalizer)]);
$data = $serializer->normalize($attendances, null, ['attributes' => $attributes, 'rangeDate' => $rangeDate]);
You'll have t odeclare your service explicitely... something like this should do the trick:
## services.yml
App\Serializer\TaskNormalizer :
arguments:
$normalizer: '#serializer.normalizer.object' ## check the alias ...
$rangeDate: '%range_date%'
Keep in mind that it is better depend on interface than class, for the sake of dependency inversion principle. So you should think about changing the constructor to :
## your class
public function __construct(NormalizerInterface $normalizer, $rangeDate )
{
$this->normalizer = $normalizer;
$this->rangeDate = $rangeDate;
}

Mock two ObjectRepositories in Syfmony PHPUnit Tests

A method from my MyClass class I'd like to test looks like this:
public function needs()
{
$domains = $this->em->getRepository(WebDomain::class)->findBy(array(
'client' => $this->client
));
$hosting = $this->em->getRepository(WebHosting::class)->findBy(array(
'client' => $this->client
));
if($domains !== null && $hosting !== null){
return true;
}
return false;
}
Looking at the documentation of Symfony I create a test like this:
public function testNeeds()
{
$em = $this->createMock(ObjectManager::class);
$client = new Client();
/**
* Add WebHosting to Client
*/
$webHosting = new WebHosting();
$webHosting->setClient($client);
/**
* Create a new WebDomain for Client/WebHosting
*/
$webDomain = new WebDomain();
$webDomain->setClient($client);
$webDomain->setWebHosting($webHosting);
I know how to create a mocked repository (the needed $domains for example):
$domains = $this->createMock(ObjectRepository::class);
$domains->expects($this->any())
->method('findBy')
->willReturn($client->getWebDomain());
$em->expects($this->any())
->method('getRepository')
->willReturn($domains);
$myClass = new MyClass($client, $em);
So from my understanding, this creates a mock that whenever the method findBy is called, return the $domains, but what do I have to add in order to return the needed $hosting?
I suspect it has something to do with the $this->any(), I assume I have to narrow it down to expects(WebDomain::class) (which does not work ofc).
Since I am fairly new to UnitTests in Symfony (and in general) pointing me to the right manual might help as well. Thank you!
In you case you should return different Repository based on argument passed to getRepository method. Something like:
$emMock
->method('getRepository')
->will($this->returnValueMap([
[WebDomain::class, $webDomainRepositoryMock),
[WebHosting::class, $webHostingRepositoryMock)
]));
Note: remember to configure findBy for both repositories.

BindingResult.getFieldValue() returning null in test context for a formatted value

In a spring mvc app, I submit id's and use a formatter to convert that id to an object. It works well in the container.
But in the unit test environment, I'm seeing a problem.
I mock the formatter to always return my test value, this is fine it gets injected into the ModelAttribute. But in the BindingResult, a call to result.getFieldValue("location") for example is returning null, but only in the MockMvc context.
This is the test case:
/**
* Tests the inventory update for existing inventory records.
* #throws Exception
*/
#Test
public void testUpdateExistingProductInventory() throws Exception{
logger.entry();
VariantInventory oldInventory = new VariantInventory();
oldInventory.setId(20l);
Product product = ProductBuilder.buildBasicExisting();
Location location = new Location();
location.setId(3l);
ProductVariant variant = new ProductVariant();
variant.setId(2l);
// check the formatter is working
Mockito.when(mockProductFormatter.parse(((String)Mockito.anyObject()), ((Locale)Mockito.anyObject()))).thenReturn(product);
Product p = mockProductFormatter.parse("1", null);
Assert.assertEquals(p, product);
// check the formatter is working
Mockito.when(mockLocationFormatter.parse(((String)Mockito.anyObject()), ((Locale)Mockito.anyObject()))).thenReturn(location);
Location l = mockLocationFormatter.parse("3", null);
Assert.assertEquals(l, location);
// check the formatter is working
Mockito.when(mockVariantFormatter.parse(((String)Mockito.anyObject()), ((Locale)Mockito.anyObject()))).thenReturn(variant);
ProductVariant pv = mockVariantFormatter.parse("2", null);
Assert.assertEquals(pv, variant);
// check the formatter is working
Mockito.when(mockInventoryFormatter.parse(((String)Mockito.anyObject()), ((Locale)Mockito.anyObject()))).thenReturn(oldInventory);
VariantInventory v = mockInventoryFormatter.parse("20", null);
Assert.assertEquals(v, oldInventory);
this.mockMvc.perform(MockMvcRequestBuilders.post("/ajax/products/update/inventory")
.param("product", "1")
.param("variant", "2")
.param("location", "3")
.param("status", "ACTIVE")
.param("quantityOnHand", "30.5")
.param("lowStockQuantity", "10")
.param("inventory", "20")
)
.andExpect(status().isOk());
Mockito.verify(mockInventoryService, Mockito.times(1)).updateExisting(Mockito.eq(oldInventory), Mockito.any(VariantInventory.class));
logger.exit();
}
This is the relative part of the controller:
#RequestMapping(value = "/ajax/products/update/inventory", method= RequestMethod.POST)
public #ResponseBody
AJAXResponse updateProductInventory(#ModelAttribute ProductInventoryFormWrapper formWrapper, BindingResult result,
ModelMap map) {
logger.entry();
logger.debug("Getting product data");
if (!result.hasErrors()) {
inventoryValidator.validate(formWrapper, result);
}
}
Then skipping a few items, this is the relevant validation that fails, where I am passing location as the field.
ValidationUtils.rejectIfEmptyOrWhitespace(errors, field, "required.field", new String[]{label});
The object fails to validate because of what must be a bug.
What I observe if I debug the controller is:
The object is in the FormWrapper, and the properties are there.
But in the BindingResult object, if I call 'getFieldValue('location')` which is what's being called in the spring validation code, it's returning null, and therefore the validator rejects the value.
So for some reason the binding result hasn't registered the formatted fields or something. Note that this only happens in the Unit Test, not in the container.
Does anyone know how to fix?
Quick Edit:
I've done some more debugging, and it's failing in this block of code from AbstractPropertyBindingResult. The value is okay right up until the conversionService is called to convert it. I haven't downloaded the source beyond that method, so I can't see exactly why it's failing, but somewhere in the convert method it's being turned from the proper value, to null. I presume because I'm using MockObjects, and maybe it's calling something that I haven't anticipated to return the value.
#Override
protected Object formatFieldValue(String field, Object value) {
String fixedField = fixedField(field);
// Try custom editor...
PropertyEditor customEditor = getCustomEditor(fixedField);
if (customEditor != null) {
customEditor.setValue(value);
String textValue = customEditor.getAsText();
// If the PropertyEditor returned null, there is no appropriate
// text representation for this value: only use it if non-null.
if (textValue != null) {
return textValue;
}
}
if (this.conversionService != null) {
// Try custom converter...
TypeDescriptor fieldDesc = getPropertyAccessor().getPropertyTypeDescriptor(fixedField);
TypeDescriptor strDesc = TypeDescriptor.valueOf(String.class);
if (fieldDesc != null && this.conversionService.canConvert(fieldDesc, strDesc)) {
return this.conversionService.convert(value, fieldDesc, strDesc);
}
}
return value;
}
Ok that was a tough one, so I didn't really expect anyone to answer. But here's the answer. I was right, the Mock was being called in the validation. So I had to add an additional mock method to the formatters (print):
// check the formatter is working
Mockito.when(mockInventoryFormatter.parse(((String)Mockito.anyObject()), ((Locale)Mockito.anyObject()))).thenReturn(oldInventory);
// this was added
Mockito.when(mockInventoryFormatter.print(Mockito.any(VariantInventory.class), Mockito.any(Locale.class))).thenReturn("20");

Symfony2 set class variable with init or construct methods

Have recently been using Symfony2 after using ZF for some time.
I am having problems trying to do something relatively simple, I think.
The following code is within a controller:
private $current_setid = "";
public function __construct() {
$current_set = $this->getCurrentSet();
if ($current_set == "") {
return $this->redirect($this->generateUrl('selectset'));
}
$this->current_setid = $current_set;
}
public function getCurrentSet() {
$session = $this->get("session");
$set = $session->get('set');
return $set;
}
public function setCurrentSet($setid) {
$session = $this->get("session");
$session->set('set', "$setid");
}
If I use __construct() I get errors like:
Fatal error: Call to a member function get() on a non-object in
I have tried using __init() and init() both of which do not seem to get called.
Can anyone point me in the right direction? Is there a simple way to do this or do I have to look into event listeners?
Have you tried getting your session like they do in official documentation?
$session = $this->getRequest()->getSession();
$foo = $session->get('foo');
Basically get fetch dependencies from container and container in the Controller is injected using setter dependency injection. You just not have container in the time of __construct yet.
Just ended up opting for placing a check in every method in the class. Seems silly to have to do that but I find I often have to do that in Symfony2 with the lack of init, postDispatch type methods like ZF has.
Even trying to remove the check to another method was counter productive as I still had to check the return from that method as $this->redirect does not seem to work unless it is within an Action method. For example:
public function isSetSet() {
$current_set = $this->getCurrentSet();
if ($current_set == "") {
$url = $this->generateUrl('selectset');
return $this->redirect($url);
}
return TRUE;
}
public function someAction() {
$check = $this->isSetSet();
if($check != TRUE){
return $check;
}
...
}
So each method needs that 4 line check but the whole check can be done in 4 lines anyway so no need for that extra method:
public function anotherAction() {
$current_setid = $this->getCurrentSet();
if ($current_setid == "") {
return $this->redirect($this->generateUrl('selectset'));
}
...
}

Can I get some advice on JavaScript delegates?

I'm rusty with delegates and closures in JavaScript, and think I came across a situation where I'd like to try to use one or both.
I have a web app that behaves a lot like a forms app, with fields hitting a server to change data on every onBlur or onChange (depending on the form element). I use ASP.NET 3.5's Web Services and jQuery to do most of the work.
What you need to know for the example:
isBlocking() is a simple mechanism to form some functions to be synchronous (like a mutex)
isDirty(el) checks to make sure the value of the element actually changed before wasting a call to the server
Agent() returns a singleton instance of the WebService proxy class
getApplicationState() passes a base-64 encoded string to the web service. This string represents the state of the application -- the value of the element and the state are passed to a service that does some calculations. The onSuccess function of the web service call returns the new state, which the client processes and updates the entire screen.
waitForCallback() sets a flag that isBlocking() checks for the mutex
Here's an example of one of about 50 very similar functions:
function Field1_Changed(el) {
if (isBlocking()) return false;
if (isDirty(el)) {
Agent().Field1_Changed($j(el).val(), getApplicationState());
waitForCallback();
}
}
The big problem is that the Agent().Field_X_Changed methods can accept a different number of parameters, but it's usually just the value and the state. So, writing these functions gets repetitive. I have done this so far to try out using delegates:
function Field_Changed(el, updateFunction, checkForDirty) {
if (isBlocking()) return false;
var isDirty = true; // assume true
if (checkForDirty === true) {
isDirty = IsDirty(el);
}
if (isDirty) {
updateFunction(el);
waitForCallback();
}
}
function Field1_Changed(el) {
Field_Changed(el, function(el) {
Agent().Field1_Changed($j(el).val(), getTransactionState());
}, true);
}
This is ok, but sometimes I could have many parameters:
...
Agent().Field2_Changed($j(el).val(), index, count, getApplicationState());
....
What I'd ultimately like to do is make one-linen calls, something like this (notice no getTransactionState() calls -- I would like that automated somehow):
// Typical case: 1 value parameter
function Field1_Changed(el) {
Field_Changed(el, delegate(Agent().Field1_Changed, $j(el).val()), true);
}
// Rare case: multiple value parameters
function Field2_Changed(el, index, count) {
Field_Changed(el, delegate(Agent().Field1_Changed, $j(el).val(), index, count), true);
}
function Field_Changed(el, theDelegate, checkIsDirty) {
???
}
function delegate(method) {
/* create the change delegate */
???
}
Ok, my first question is: Is this all worth it? Is this harder to read but easier to maintain or the other way around? This is a pretty good undertaking, so I may end up putting a bounty on this one, but I'd appreciate any help you could offer. Thanks!
UPDATE
So, I've accepted an answer based on the fact that it pointed me in the right direction. I thought I'd come back and post my solution so that others who may just be starting out with delegates have something to model from. I'm also posting it to see if anybody wants to try an optimize it or make suggestions. Here's the common Field_Changed() method I came up with, with checkForDirty and omitState being optional parameters:
function Field_Changed(el, args, delegate, checkForDirty, omitState) {
if (isBlocking()) return false;
if (!$j.isArray(args) || args.length == 0) {
alert('The "args" parameter in Field_Changed() must be an array.');
return false;
}
checkForDirty = checkForDirty || true; // assume true if not passed
var isDirty = true; // assume true for updates that don't require this check
if (checkForDirty === true) {
isDirty = fieldIsDirty(el);
}
if (isDirty) {
omitState = omitState || false; // assume false if not passed
if (!omitState) {
var state = getTransactionState();
args.push(state);
}
delegate.apply(this, args);
waitForCallback();
}
}
It handles everything I need it to (check for dirty, applying the application state when I need it to, and forcing synchronous webservice calls. I use it like this:
function TransactionAmount_Changed(el) {
Field_Changed(el, [cleanDigits($j(el).val())], Agent().TransactionAmount_Changed, true);
}
cleanDigits strips out junk characters the user may have tried to type in. So, thanks to everyone, and happy coding!
OK, few things:
Delegates are extremely simple in javascript since functions are first class members.
Function.apply lets you call a function with an array of arguments.
So you can write it this way
function Field_Changed(delegate, args)
{
if (isBlocking()) return false;
if (isDirty(args[0])) { //args[0] is el
delegate.apply(this, args);
waitForCallback();
}
}
And call it as:
Field_Changed(Agent().Field2_Changed, [el, getApplicationState(), whatever...]);
I have been using the following utility function that I wrote a long time ago:
/**
* #classDescription This class contains different utility functions
*/
function Utils()
{}
/**
* This method returns a delegate function closure that will call
* targetMethod on targetObject with specified arguments and with
* arguments specified by the caller of this delegate
*
* #param {Object} targetObj - the object to call the method on
* #param {Object} targetMethod - the method to call on the object
* #param {Object} [arg1] - optional argument 1
* #param {Object} [arg2] - optional argument 2
* #param {Object} [arg3] - optional argument 3
*/
Utils.createDelegate = function( targetObj, targetMethod, arg1, arg2, arg3 )
{
// Create an array containing the arguments
var initArgs = new Array();
// Skip the first two arguments as they are the target object and method
for( var i = 2; i < arguments.length; ++i )
{
initArgs.push( arguments[i] );
}
// Return the closure
return function()
{
// Add the initial arguments of the delegate
var args = initArgs.slice(0);
// Add the actual arguments specified by the call to this list
for( var i = 0; i < arguments.length; ++i )
{
args.push( arguments[i] );
}
return targetMethod.apply( targetObj, args );
};
}
So, in your example, I would replace
function Field1_Changed(el) {
Field_Changed(el, delegate(Agent().Field1_Changed, $j(el).val()), true);
}
With something along the lines
function Field1_Changed(el) {
Field_Changed(el, Utils.createDelegate(Agent(), Agent().Field1_Changed, $j(el).val()), true);
}
Then, inside of Agent().FieldX_Changed I would manually call getApplicationState() (and encapsulate that logic into a generic method to process field changes that all of the Agent().FieldX_Changed methods would internally call).
Closures and delegates in JavaScript:
http://www.terrainformatica.com/2006/08/delegates-in-javascript/
http://www.terrainformatica.com/2006/08/delegates-in-javascript-now-with-parameters/

Resources