You have requested a non-existent service "test.service_container". Did you mean this: "service_container"? - symfony

PHPUnit 7.5.15 by Sebastian Bergmann and contributors.
Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException : You have requested a non-existent service "test.service_container". Did you mean this: "service_container"?
/opt/project/backend/vendor/symfony/symfony/src/Symfony/Component/DependencyInjection/Container.php:277
/opt/project/backend/vendor/symfony/symfony/src/Symfony/Component/DependencyInjection/Container.php:225
/opt/project/backend/tests/Functional/KernelAwareTest.php:49
/opt/project/backend/tests/Functional/FlightTaskManagement/AssignEmployeeToTaskTest.php:47
public function setUp(): void
{
global $kernel;
$this->kernel = TestKernel::get();
$kernel = $this->kernel;
$container = $this->kernel->getContainer();
if ($container === null)
throw new \InvalidArgumentException('Container can not be null.');
$this->container = $container->get('test.service_container');
// $this->container = $container->get('service_container');
/** #var Registry $doctrine */
$doctrine = $this->container->get('doctrine');
/** #var \Doctrine\ORM\EntityManager $manager */
$manager = $doctrine->getManager();
$this->entityManager = $manager;
$this->entityManager->beginTransaction();
if (!$this->container->initialized(WorkDistributionTransport::class)) {
$this->container->set(WorkDistributionTransport::class, new InMemoryTransport());
}
if (!$this->container->initialized(Configuration::class)) {
$this->container->set(Configuration::class, new TestConfiguration());
}
parent::setUp();
}
It fails at line
$this->container = $container->get('test.service_container');
Symfony is 4.1 but looks like not finished to update. I can't remember by what we decided that it was not finished to update from earlier version.
Not clear if that is the problem that it is not finished to update. Looks like in 4.0 there is no such service so thats why. But then how to make it appear here?
Or maybe I can use
$this->container = $container->get('service_container');
as with earlier versions? Just what is faster way?
I just tried using
$this->container = $container->get('service_container');
but I then get
Doctrine\DBAL\DBALException : An exception occured while establishing a connection to figure out your platform version.
You can circumvent this by setting a 'server_version' configuration value
But I had set the version in config_test.yml so not clear which way is faster to fix.
doctrine:
dbal:
server_version: 5.7
driver: pdo_mysql
host: db_test
port: null
dbname: project
user: project
password: project
Probably if I load service_container then it does not load test config and thats why I get this server_version error. So then need to somehow make it load test config.

Found: I had hardcoded dev environment in AppKernel. Probably thats why I was getting this error. Hardcoding test env fixed. Would be good somehow to make it without hardcoding, but it is still better than nothing:
public function __construct($environment, $debug)
{
// $environment ='dev';
$environment ='test';
$debug= true;
parent::__construct($environment, $debug);
date_default_timezone_set('UTC');
}

Related

ONGR Elasticsearch Bundle AWS Connection Issue

Hello Ther i try to connenct to ES indet that is located on AWS, but i still get he Error.
[Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException]
You have requested a non-existent service "es.managers.default".
I installed the bundle using Conposer, as described on the Docs.
then added a config part tom my config.ylm
ongr_elasticsearch:
managers:
default:
index:
index_name: contents
hosts:
- https://search-***.es.amazonaws.com:443
mappings:
- StatElasticBundle
i have a awsaccesskey and a awssecretkey, but i don't now where i have to put them, so i created a aws_connection section in the parameters.yml and try to load it
Then i try to establish a connection in my SymfonyBundle and created a class in my Bundle->DepandencyInjection folder to extend my bundle, this is where i get the error. Mayby someone of you struggled with the same error?
Thanks for help.
Class StatElasticExtension extends Extension
{
const YAML_FILES = [
'parameters.yml',
'config.yml',
'services.yml'
];
/**
* {#inheritdoc}
*/
public function load(array $configs, ContainerBuilder $container)
{
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
foreach (self::YAML_FILES as $yml) {
$loader->load($yml);
}
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
$serviceDefinition = $container->getDefinition('es.managers.default');
$awsConnections = $container->getParameter('aws_connections');
$elasticsearchClient = $this->getClient($awsConnections);
$serviceDefinition->replaceArgument(2, $elasticsearchClient);
}
The correct service name is es.manager.default.

Suppress symfony 4 response body in phpunit test

I am migrating a Silex app to Symfony Flex and everything is working so far, except that when I run the phpunit tests I get the response body output into the phpunit output.
ie.
> bin/phpunit
#!/usr/bin/env php
PHPUnit 6.5.13 by Sebastian Bergmann and contributors.
Testing unit
.......<http://data.nobelprize.org/resource/laureate/914> a <http://data.nobelprize.org/terms/Laureate> , <http://xmlns.com/foaf/0.1/Person> ;
<http://www.w3.org/2000/01/rdf-schema#label> "Malala Yousafzai" ;
<http://data.nobelprize.org/terms/laureateAward> <http://data.nobelprize.org/resource/laureateaward/974> ;
<http://data.nobelprize.org/terms/nobelPrize> <http://data.nobelprize.org/resource/nobelprize/Peace/2014> ;
the entire RDF document then
. 8 / 8 (100%)
Time: 1.07 seconds, Memory: 14.00MB
OK (8 tests, 71 assertions)
Generating code coverage report in Clover XML format ... done
So it is working fine, but I can't figure out how to disable this output?
The request is simply
$this->client->request('GET', "/nobel_914.ttl", [], [], ['HTTP_ACCEPT' => $request_mime]);
$this->assertEquals(200, $this->client->getResponse()->getStatusCode(), "GET should be allowed.");
$response = $this->client->getResponse();
$charset = $response->getCharset();
etc.
and the client is setup in a base class like this
class MyAppTestBase extends WebTestCase
{
/**
* #var \Symfony\Component\BrowserKit\Client
*/
protected $client;
/**
* {#inheritdoc}
*/
public function setUp() {
parent::setUp();
$this->client = static::createClient();
$this->client->catchExceptions(false);
}
I'm sure I'm missing something obvious but this is new to me. I am running in the 'test' environment and with 'debug' == false.
Any help appreciated.
So this was probably a problem all along but just started being exposed in the switch from Silex to Symfony Flex.
We were streaming responses via
$filename = $this->path;
$stream = function () use ($filename) {
readfile($filename);
};
return new StreamedResponse($stream, 200, $res->headers->all());
and the readfile was throwing the content to the output buffer. Switching the readfile to file_get_contents resolved this
$filename = $this->path;
$stream = function () use ($filename) {
file_get_contents($filename);
};
return new StreamedResponse($stream, 200, $res->headers->all());

Symfony2 send email from service

I created the next class:
//src/AppBundle/Services/RegisterMail.php
namespace AppBundle\Services;
class RegisterMail{
protected $mailer;
public function __construct($mailer)
{
$this->mailer = $mailer;
}
public function sendPassword(){
$message = \Swift_Message::newInstance()
->setSubject('Otro correo')
->setFrom('fromEmail#fromEmail.com')
->setTo('toEmail#toEmail.com')
->setBody('hola desde el servicio')
;
$envia = $this->mailer->send($message);
}
}
And I declare it as a service in my services.yml
services:
registermail:
class: AppBundle\Services\RegisterMail
arguments: [#mailer]
In my controller call the service:
//src/AppBundle/Controller/DefaultController
namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
class DefaultController extends Controller
{
/**
* #Route("/")
*/
public function indexAction()
{
//EnvĂ­o el email con el password
$mailer = $this->get('registermail');
$mailer->sendPassword();
return $this->render(':Default:index.html.twig');
}
}
The email are sent, but the page still loading 30 seconds, and I have an alert from developer toolbar: "An error occurred while loading the web debug toolbar (404: not found). Do you want to open the profiler?
If Accept the message symfony profiler don't show any error.
If Cancel the message developer toolbar don't appears.
What am I doing wrong?
Thank you!
#RL83 you are probably sending the message synchronously by not using any kind of spool in swiftmailer and your smtp provider is working slowly.
You should try using an async spool queue, I'd recommend using https://github.com/radutopala/TSSAutomailerBundle, which provides you with a database queue. So basically, you'll not only have a spool queue but also a history of the sent emails, stored in the database layer.
Try to replace your code with this:
//src/AppBundle/Services/RegisterMail.php
namespace AppBundle\Services;
class RegisterMail{
protected $mailer;
protected $transport; // <- Add transport to your service
public function __construct($mailer, $transport)
{
$this->mailer = $mailer;
$this->transport = $transport;
}
public function sendPassword() // <- change the method like this
{
$email = $mailer->createMessage()
->setSubject('Otro correo')
->setFrom('fromEmail#fromEmail.com')
->setTo('toEmail#toEmail.com')
->setCharset("UTF-8")
->setContentType('text/html')
->setBody('hola desde el servicio')
;
$send = $mailer->send($email);
$spool->flushQueue($transport);
}
}
Register your service and add the new dependency - the transport service "#swiftmailer.transport.real"
services:
registermail:
class: AppBundle\Services\RegisterMail
arguments: ["#mailer", "#swiftmailer.transport.real" ]
And your trouble will be resolved
Thank for your answers and sorry for the delay.
#lyberteam when i put your code, i get this error message:
Notice: Undefined variable: mailer
500 Internal Server Error - ContextErrorException
Here: $email = $mailer->createMessage()
Any suggestion?
Thank you

symfony2 behat in test enviroment: DB tables not created

I am trying to behat my application and I have a big problem; DB tables are not created so I can't put any fixtures.
My scenario is:
Scenario: Check the stories page
Given Database is set
And I am logged as "admin" and password "123123123"
And print last response
...
Part of FeatureContext:
/**
* #Given /^Database is set$/
*/
public function databaseIsSet()
{
$this->generateSchema() ;
$admin = new User() ;
$admin->setRoles(array(User::ROLE_SUPER_ADMIN)) ;
$admin->setEnabled(true) ;
$admin->setUsername("admin") ;
$admin->setPlainPassword("123123123") ;
$admin->setEmail("admin#mysite.com") ;
$em = $this->getEntityManager() ;
$em->persist($admin) ;
$em->flush() ;
echo $admin->getId() . "==" ;
echo "db set" ;
}
/**
* #Given /^I am logged as "([^"]*)" and password "([^"]*)"$/
*/
public function iAmLoggedAsAndPassword($username, $password)
{
return array(
new Step\When('I am on "/login"'),
new Step\When('I fill in "username" with "' . $username . '"'),
new Step\When('I fill in "password" with "' . $password . '"'),
new Step\When('I press "Login"'),
);
}
protected function generateSchema()
{
// Get the metadatas of the application to create the schema.
$metadatas = $this->getMetadatas();
if ( ! empty($metadatas)) {
/**
* #var \Doctrine\ORM\Tools\SchemaTool
*/
$tool = new SchemaTool($this->getEntityManager());
// $tool->dropDatabase() ;
$tool->createSchema($metadatas);
} else {
throw new Doctrine\DBAL\Schema\SchemaException('No Metadata Classes to process.');
}
}
/**
* Overwrite this method to get specific metadatas.
*
* #return Array
*/
protected function getMetadatas()
{
$result = $this->getEntityManager()->getMetadataFactory()->getAllMetadata() ;return $result;
}
protected function getEntityManager()
{
return $this->kernel->getContainer()->get("doctrine")->getEntityManager() ;
}
....
The code for generateSchema is taken somewhere from internet and used in Phpunits tests I have and works perfectly.
But; when I run bin/behat, I get
SQLSTATE[HY000]: General error: 1 no such table: tbl_user
after login part of scenario.
The echo statement I have is also shown in output, just to make sure the method is actually executed. Also, $admin gets an ID of 1 which is also visible in output.
My test env is using default sqlite DB, and it is irrelevant if I put 'http://mysite.local/app_dev.php/' or 'http://mysite.local/app_test.php/' for base_url in config; the login doesn't work although I copy&pasted it from knpLabs page. To make sure $admin is still in DB, I tried to reload it from repository and it works (I removed that part of code).
Help?
Actually, I found the problem. Sqlite works in-memory and upon each request to some page like login url, the previous state had been lost. I created new enviroment app_behat.php with these setting in config_behat.yml:
imports:
- { resource: config.yml }
framework:
test: ~
session:
storage_id: session.storage.mock_file
doctrine:
dbal:
dbname: other_database
and it works now. Maybe someone will find this usefull.
I had the same problem and for me the problem was in config_test.yml file.
I changed pdo_sqlite to pdo_mysql.
doctrine:
dbal:
driver: pdo_mysql
# driver: pdo_sqlite
And it works like a charm.

Symfony Service setting NULL data

I've been having several issues with creating a service in Symfony 2.0, but have found workarounds for everything but the service setting null data.
public function logAction($request, $entityManager)
{
$logs = new Logs();
$logs->setRoute = $request->get('_route');
$logs->setController = $request->get('_controller');
$logs->setRequest = json_encode($request->attributes->all());
$logs->setPath = $request->server->get('PATH_INFO');
$logs->setIp = $request->server->get('REMOTE_ADDR');
$em = $entityManager;
$em->persist($logs);
$em->flush();
}
I'm passing the EntityManager when calling the service in another controller, I'll post that code just in case:
public function pageAction($id = null, Request $request)
{
$log = $this->get('logging');
$log->logAction($request, $this->getDoctrine()->getEntityManager());
return $this->render('AcmeDemoBundle:Demo:viewPage.html.twig', array('name' => $id));
}
I have created a services.yml file following the official docs (in the Log Bundle) and an actual row is inserted, but all fields are set to NULL. If I try to do a die in one of the setters in the entity file it doesn't die, so it seems like something isn't making it. (I have both the EntityManager and Entity files used at the top of the log service file before anyone asks)
Any help would be greatly appreciated.
$logs->setRoute = $request->get('_route');
Should be:
$logs->setRoute($request->get('_route'));
For D2 all the accessors need to be methods.

Resources