Symfony 5 unittest can't fetch entity collection - phpunit

my collection is empty while I try to access it in a unittest. In dev && prod env it is accessable as aspected.
One customerOrder can have multiple invoices and one invoice can have one customerOrder.
class CustomerOrderServiceTest extends KernelTestCase
{
use RefreshDatabaseTrait;
public function testAdd()
{
self::bootKernel();
$container = self::$container;
$orderRepository = $container->get(CustomerOrderRepository::class);
$customerOrder = $orderRepository->find(1);
foreach ($customerOrder->getInvoices() as $invoice) {
dump('Invoice id: ' . $invoice->getId());
}
dump('Invoice count: ' . $customerOrder->getInvoices()->count());
$invoiceRepository = $container->get(InvoiceRepository::class);
$invoice = $invoiceRepository->find(1);
dump('Order id: ' . $invoice->getCustomerOrder()->getId());
dump('Invoice count: ' . $invoice->getCustomerOrder()->getInvoices()->count());
}
}
The Output is
Testing Project Test Suite
^ "Invoice count: 0"
^ "Order id: 1"
^ "Invoice count: 0"
So the Order is accessable over the invoice but not the other way around.
The entities:
/**
* CustomerOrder
* #ORM\Entity(repositoryClass="App\Repository\CustomerOrderRepository")
*/
class CustomerOrder{
/**
* #var Collection
* #ORM\OneToMany(targetEntity="App\Entity\Invoice", mappedBy="customerOrder", cascade={"persist"}, fetch="EAGER")
*/
private $invoices;
}
/**
* Invoice
* #ORM\Entity(repositoryClass="App\Repository\InvoiceRepository")
* #ORM\Table(uniqueConstraints={#ORM\UniqueConstraint(name="number",columns={"number", "owner"})})
*/
class Invoice{
/**
* #var CustomerOrder
*/
private $customerOrder;
}
<?xml version="1.0" encoding="UTF-8"?>
<!-- https://phpunit.readthedocs.io/en/latest/configuration.html -->
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="bin/.phpunit/phpunit.xsd"
colors="true"
bootstrap="tests/bootstrap.php"
>
<php>
<ini name="error_reporting" value="-1"/>
<server name="APP_ENV" value="test" force="true"/>
<server name="SHELL_VERBOSITY" value="-1"/>
<server name="SYMFONY_PHPUNIT_REMOVE" value=""/>
<server name="SYMFONY_PHPUNIT_VERSION" value="7.5"/>
<!-- ###+ symfony/framework-bundle ### -->
<env name="APP_ENV" value="test" force="true"/>
<env name="APP_SECRET" value="*****"/>
<!-- ###- symfony/framework-bundle ### -->
</php>
<testsuites>
<testsuite name="Project Test Suite">
<directory>tests</directory>
</testsuite>
</testsuites>
<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">src</directory>
</whitelist>
</filter>
<listeners>
<listener class="Symfony\Bridge\PhpUnit\SymfonyTestsListener" />
</listeners>
</phpunit>

Related

Symfony 4 translation are not working

the problem is not symfony, is me lol, I need help cause is not working fine, when i change my locale the text is still in english, there is my code
translation.yaml
framework:
default_locale: '%locale%'
translator:
paths:
- '%kernel.project_dir%/translations'
fallbacks:
- '%locale%'
framework.yaml
framework:
secret: '%env(APP_SECRET)%'
default_locale: en
csrf_protection: true
On my FrontController
`/**
* #Route("/{_locale}/",
* requirements={"_locale"="en|es"},
* name="index")
*/
public function index()
{
if($this->getUser()){
return $this->redirectToRoute('index');
}else{
$register= new Register();
$form = $this->createForm(RegisterType::class, $register,array(
'empty_data'=>'user_register',
'validation_groups' => array('default', 'empty_data'),
));
}`
my messages.es.xlf
<?xml version="1.0"?>
<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
<file source-language="en" datatype="plaintext" original="file.ext">
<body>
<trans-unit id="sign_in">
<source>Sign in</source>
<target>Entrar</target>
</trans-unit>
</body>
</file>
on my template
{{ 'Sign in'|trans }}
well, the problem, is i change my url http://...../en/ to http://..../es/ is not working, but if i change my fallback manuale to es on translation.yaml is working fine, but then dons't work on /en/ any idea??

How to supply hiveconf variable from hive oozie action

I want to supply variable as hiveconf namespace from my hive-oozie action, how to do that?
<action name="setupAct">
<hive xmlns="uri:oozie:hive-action:0.2">
<job-tracker>maprfs:///</job-tracker>
<name-node>maprfs:///</name-node>
<script>
XYZ.hql
</script>
<!--how to add variable to hiveconf-->
<param>DB_NAME=test</param>
</hive>
<ok to="ok" />
<error to="error" />
</action>
The values inside param element are supplied as --hivevar namespace to hive.
Below is application log, the param element gets added as hivevar:
------------------------
DB_NAME=test
------------------------
Hive command arguments :
--hivevar
DB_NAME=test
-f
test.hql
For hiveconf in Oozie, Use the configuration element.
<hive xmlns="uri:oozie:hive-action:0.2">
<job-tracker>maprfs:///</job-tracker>
<name-node>maprfs:///</name-node>
<script>
XYZ.hql
</script>
<!--how to add variable to hiveconf-->
<configuration>
<property>
<name>hive.default.fileformat</name>
<value>Parquet</value>
</property>
</configuration>
<param>DB_NAME=test</param>
</hive>

Phpunit Test -Can't find entity (Symfony)

I am new to symfony and phpunit testing and have been getting this error
Cannot stub or mock class or interface "com\twcl\agripayrollBundle\Entity\Payrollperiod" which does not exist
This is my test which is in the Selenium Test files in the Tests directory.
use com\twcl\agripayrollBundle\Mapping\PayPeriodManager;
use com\twcl\agripayrollBundle\Entity\Payrollperiod;
use Doctrine\ORM\EntityRepository;
use Doctrine\Common\Persistence\ObjectManager;
class PayrollperiodManagerTest extends PHPUnit_Framework_TestCase {public function testPayrollPeriodManager()
{
$payperiod= $this->createMock(Payrollperiod::class);
$payperiod->expects($this->once())
->method('setstartDate')
->will($this->setValue(2011-01-01));
$payperiod->expects($this->once())
->method('setendDate')
->will($this->setValue(2011-01-18));
$payperiod->expects($this->once())
->method('setState')
->will($this->setValue('Active'));
var_dump($payperiod);
die();
}
}
This is my phpunit.xml.dist
<!-- http://phpunit.de/manual/4.1/en/appendixes.configuration.html -->
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://schema.phpunit.de/4.1/phpunit.xsd"
backupGlobals="false"
colors="true"
bootstrap="bootstrap.php.cache"
>
<testsuites>
<testsuite name="Project Test Suite">
<directory>../src/*/*Bundle/Tests</directory>
<directory>../src/*/Bundle/*Bundle/Tests</directory>
</testsuite>
</testsuites>
<!--
<php>
<server name="KERNEL_DIR" value="/path/to/your/app/" />
</php>
-->
<filter>
<whitelist>
<directory>../src</directory>
<exclude>
<directory>../src/*/*Bundle/Resources</directory>
<directory>../src/*/*Bundle/Tests</directory>
<directory>../src/*/Bundle/*Bundle/Resources</directory>
<directory>../src/*/Bundle/*Bundle/Tests</directory>
</exclude>
</whitelist>
</filter>
</phpunit>
My autoloader
<?php
use Doctrine\Common\Annotations\AnnotationRegistry;
use Composer\Autoload\ClassLoader;
/**
* #var ClassLoader $loader
*/
$loader = require __DIR__.'/../vendor/autoload.php';
AnnotationRegistry::registerLoader(array($loader, 'loadClass'));
return $loader;

EasyAdminBundle entities labels translations

I'm unable to configure translations. My config.yml has (among others) this entry:
easy_admin:
entities:
Blog:
label: app.blog
class: AppBundle\Entity\Blog
I've also created a translation resorce: messages.es.xliff with this entry:
<?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" version="1.2">
<file source-language="es" target-language="es" datatype="plaintext" original="file.ext">
<body>
<trans-unit id="app.blog">
<source>app.blog</source>
<target>Blog</target>
</trans-unit>
</body>
</file>
</xliff>
but the translated literal doesn't appear in the left menu.
Thank you very much for your help.
At last I've changed the name of translation ressource to EasyAdminBundle.es.yml and now everything works fine.
Ensure you have the translator service enabled. In app/config/config.yml:
framework:
translator: { fallbacks: ["en"] }

Spring MVC - form generating new model object instances

I have a simple mvc application, which lists all rules in a DB, and allows a user to select a specific row to delete that rule. The controller has a simple listRules() method which adds two model objects to the ModelMap.
#Controller
public class RulesController {
#Resource
private RuleManager ruleManager;
#RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView listRules() {
ModelAndView mv = new ModelAndView("/rules");
List<Rule> rules = this.ruleManager.getAllRules();
ListRulesModel listRulesModel = new ListRulesModel();
listRulesModel.setRules(rules);
mv.addObject("listRulesModel",listRulesModel);
SelectedRuleModel selectedRuleModel = new SelectedRuleModel();
mv.addObject("selectedRuleModel",selectedRuleModel);
return mv;
}
#RequestMapping(value = "/submit", method = RequestMethod.POST, params = {"delete"})
public ModelAndView deleteRule(#ModelAttribute("selectedRuleModel") SelectedRuleModel selectedRuleModel,ModelMap model) {
System.out.println("deleteRule "+selectedRuleModel.hashCode());
System.out.println("model "+model);
if(selectedRuleModel.getRuleId()!=null)
getRuleManager().deleteRule(getRuleManager().getRule(selectedRuleModel.getRuleId()));
return new ModelAndView("redirect:/");
}
My model objects are
public class ListRulesModel {
private List<Rule> rules = null;
public List<Rule> getRules() {
return rules;
}
public void setRules(List<Rule> rules) {
this.rules = rules;
}
}
and
public class SelectedRuleModel {
#NotNull
private Integer ruleId = null;
public Integer getRuleId() {
return ruleId;
}
public void setRuleId(Integer ruleId) {
this.ruleId = ruleId;
}
#Override
public String toString() {
return String.format("SelectedRuleModel [ruleId=%s]", ruleId);
}
}
The main elements of my view are a table form which shows each rule as a row. A radiobutton should populate the 'selectedRuleModel.ruleId' field with the value of the rule within the list.
<head>
<script type="text/javascript" src="<c:url value="/resources/js/jquery-2.1.1.min.js"/>"></script>
<script type="text/javascript" src="<c:url value="/resources/js/jquery.tablesorter.min.js"/>"> </script>
<script type="text/javascript" src="<c:url value="/resources/js/jquery.tablesorter.widgets.min.js"/>"></script>
<script type="text/javascript" src="<c:url value="/resources/js/rules.js"/>"></script>
<link href="<c:url value="/resources/css/base.css"/>" rel="stylesheet"/>
<link href="<c:url value="/resources/css/theme.blue.css"/>" rel="stylesheet"/>
<link href="<c:url value="/resources/css/rules.css"/>" rel="stylesheet"/>
</head>
<form:form method="POST" action="submit" modelAttribute="selectedRuleModel">
<button type="submit" name="delete" value="delete" class="btn btn-primary">Delete Selected Rule</button>
...
<c:forEach items="${listRulesModel.rules}" var="rule" varStatus="status">
<tr>
<td><form:radiobutton path="ruleId" value="${rule.id}"/></td>
<td>${rule.name}</td>
<td>${rule.batch}</td>
...
</form>
Everytime i submit the "delete row" form it appears that a new 'SelectedRuleModel' object is passed as a parameter to the deleteRule() method, such that the 'ruleId' value is always null. What am io doing wrong with my model/method mapping?
The generated HTML is
<form id="selectedRuleModel" action="submit" method="POST">
<button type="submit" name="amend" value="amend" class="btn btn-primary">Amend Selected Rule</button>
<button type="submit" name="branch" value="branch" class="btn btn-primary">Branch Selected Rule</button>
<button type="submit" name="delete" value="delete" class="btn btn-primary">Delete Selected Rule</button>
</div>
<!-- Add rule table -->
<table id="rulesTable" class="tablesorter">
<thead>
<tr>
<th>ID</th>
<th>Rule Name</th>
....
</tr>
</thead>
<tbody>
<tr>
<td><input id="ruleId2" name="ruleId" type="radio" value="20"/></td>
<td>Gender_Balance</td>
<td>*</td>
....
EDIT - I've update the controller method deleteRule() to include the BindResult object.
#RequestMapping(value = "/submit", method = RequestMethod.POST, params = {"delete"})
public ModelAndView deleteRule(
#Valid #ModelAttribute("selectedRuleModel") SelectedRuleModel selectedRuleModel,
BindingResult result, ModelMap model) {
System.out.println("deleteRule "+selectedRuleModel.getRuleId());
System.out.println("model "+model.toString());
System.out.println("BindingResult "+result.toString());
if(selectedRuleModel.getRuleId()!=null)
getRuleManager().deleteRule(getRuleManager().getRule(selectedRuleModel.getRuleId()));
return new ModelAndView("redirect:/");
}
As you can see in the logging for this method, the 'selectedRuleModel' is null but the model has a 'selectedRuleModel' with a null 'ruleId' value.
2014-10-14 11:18:21,428 INFO [STDOUT] (http-127.0.0.1-8080-2) deleteRule null
2014-10-14 11:18:21,428 INFO [STDOUT] (http-127.0.0.1-8080-2) model {selectedRuleModel=SelectedRuleModel [ruleId=null], org.springframework.validation.BindingResult.selectedRuleModel=org.springframework.validation.BeanPropertyBindingResult: 0 errors}
2014-10-14 11:18:21,428 INFO [STDOUT] (http-127.0.0.1-8080-2) BindingResult org.springframework.validation.BeanPropertyBindingResult: 0 errors
EDIT Adding web.xml and applicationContext.xml in case someone spots that i'm not initialising some required component correctly.
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<servlet>
<servlet-name>hedgingcorrection</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>namespace</param-name>
<param-value>applicationContext</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>hedgingcorrection</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<jsp-config>
<taglib>
<taglib-uri>/spring</taglib-uri>
<taglib-location>/WEB-INF/tld/spring-form.tld</taglib-location>
</taglib>
</jsp-config>
</web-app>
And my applicationContext.xml has
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<mvc:annotation-driven/>
<mvc:resources mapping="/resources/**" location="/resources/"/>
<mvc:view-controller path="/"/>
<context:component-scan base-package="abc.xwz.web.correction.controller"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
I removed the three mvc elements from my applicationContext.xml file it the form started working.
<mvc:annotation-driven/>
<mvc:resources mapping="/resources/**" location="/resources/"/>
<mvc:view-controller path="/"/>
FRIDAY EDIT - I've isolated the issue to the inclusion of the javascript elements in the jsp form. Without the javascript files included, the form submits data to the controller. When the scripts are added it seems that the form data is not correctly bound to the ModelAttribute object. The javascript files are primarily aimed at enabling the tablesorting features on the html table, so i can't understand why they are effecting the action of the submit buttons. 50 points for someone who can explain it.
The only thing I can think of is that rules.js or one of the other javascript imports may be disabling the radio button just before the submit - in which case no value would be submitted in the POST operation, which would then makes sense as to why the ModelAttribute is not being popualated.

Resources