I am trying to run doctrine commands on my windows OS. i am using following command,
"vendor/bin/doctrine.bat" orm:schema-tool:create
Following is my cli-config.php
<?php
// cli-config.php
require_once 'bootstrap.php';
// Any way to access the EntityManager from your application
$em = GetMyEntityManager();
$helperSet = new \Symfony\Component\Console\Helper\HelperSet(array(
'db' => new \Doctrine\DBAL\Tools\Console\Helper\ConnectionHelper($em->getConnection()),
'em' => new \Doctrine\ORM\Tools\Console\Helper\EntityManagerHelper($em)
));
i am getting this error
call to undefind function GetEnttyManager()
i am following http://doctrine-orm.readthedocs.org/en/latest/reference/tools.html for refrence
EDIT I reset the tags and now it is for ZF2
Call doctrine update like this:
$ path/to/your/php your/zf2/public/index.php orm:schema-tool:create
Note: don't use standard doctrine documentation for zf2 project, there are tutorials and documentations special for doctrine for zf2. Doctrine behaviour in zf2 is not quite the same as in Symfony.
Related
I need help to figure out why a VichUploaderBundle mapping doesn't exist.
I'm using VichUploaderBundle with EasyAdmin and ORM doctrine.
My vich_uploader.yaml file
vich_uploader:
db_driver: orm
mappings:
products:
#uri_prefix: '%app.path.node_images%'
uri_prefix: '%app.path.product_images%'
#uri_prefix: /products
#upload_destination: '%kernel.root_dir%/../web%app.path.node_images%'
upload_destination: '%kernel.root_dir%/../web/%app.path.product_images%'
Class debugging says the mapping is there
root#92d9f528832e:/app# php bin/console vich:mapping:debug-class
App\\Entity\\Node
Introspecting class App\Entity\Node:
Found field "imageFile", storing file name in "image" and using mapping
"product_images"
But mapping debugger can't find it
root#92d9f528832e:/app# php bin/console vich:mapping:debug
product_images
In MappingDebugCommand.php line 37:
Mapping "product_images" does not exist.
Here's my class
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\File\File;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
/**
* #ORM\Entity
* #ORM\Table(name="nodes")
* #ORM\Entity(repositoryClass="App\Repository\NodeRepository")
* #Vich\Uploadable
*/
class Node
{
/**
* #Vich\UploadableField(mapping="product_images", fileNameProperty="image")
*
* #var File
*/
private $imageFile;
/**
* #ORM\Column(type="datetime")
* #var \DateTime
*/
Here is my doctrine installation output:
doctrine/annotations v1.6.0 Docblock Annotations Parser
doctrine/cache v1.8.0 Caching library offering an object-oriented API for many cache backends
doctrine/collections v1.5.0 Collections Abstraction library
doctrine/common v2.10.0 PHP Doctrine Common project is a library that provides additional functi...
doctrine/dbal v2.8.0 Database Abstraction Layer
doctrine/doctrine-bundle 1.10.0 Symfony DoctrineBundle
doctrine/doctrine-cache-bundle 1.3.5 Symfony Bundle for Doctrine Cache
doctrine/doctrine-migrations-bundle v1.3.1 Symfony DoctrineMigrationsBundle
doctrine/event-manager v1.0.0 Doctrine Event Manager component
doctrine/inflector v1.3.0 Common String Manipulations with regard to casing and singular/plural ru...
doctrine/instantiator 1.1.0 A small, lightweight utility to instantiate objects in PHP without invok...
doctrine/lexer v1.0.1 Base library for a lexer that can be used in Top-Down, Recursive Descent...
doctrine/migrations v1.8.1 Database Schema migrations using Doctrine DBAL
doctrine/orm v2.6.3 Object-Relational-Mapper for PHP
doctrine/persistence v1.1.0 The Doctrine Persistence project is a set of shared interfaces and funct...
doctrine/reflection v1.0.0 Doctrine Reflection component
opsway/doctrine-dbal-postgresql v0.8.1 Extensions for support Postgres in Doctrine DBAL & DQL
symfony/doctrine-bridge v4.2.0 Symfony Doctrine Bridge
vich/uploader-bundle 1.8.5
I mistakenly named mapping "products" instead of "product_images".
I am trying to mock a CakePHP 3 component which checks if the user is allowed to view the page or not.
I tried this:
$authComponent = $this->getMockBuilder(App\Controller\Component\AuthorizationComponent::class)
->getMock();
$authComponent
->method('isAuthorized')
->willReturn($this->returnValue(true));
However, when running the test, it says:
Trying to configure method "isAuthorized" which cannot be configured because it does not exist, has not been specified, is final, or is static
Most probably I wrongly created the mock. Can anyone tell me how to do it correctly?
Specify mocked methods with setMethods() before getMock():
$authComponent = $this
->getMockBuilder(App\Controller\Component\AuthorizationComponent::class)
->setMethods(['isAuthorized'])
->getMock();
We are currently using CodeCeption to do some acceptance testing, but I would like to also add unit testing to the current setup.
Has anyone done Unit testing in Zend Framework 2 project using CodeCeption? And if so, how did you set up the environment?
Found this in codeception docs: http://codeception.com/docs/modules/ZF2
There is an example in this github project: https://github.com/Danielss89/zf2-codeception
I solved this problem by using PHPUnit. I followed the Zend PHPUnit guide, http://framework.zend.com/manual/current/en/tutorials/unittesting.html, which only got me so far. But, I was able to bootstrap Zend using a phpunit.xml file and pointing that to _bootstrap.php. Codeception is also able to bootstrap my tests using the _bootstrap.php file. So, now I can run my tests using both:
phpunit --bootstrap tests/unit/_bootstrap.php
and
php vendor/bin/codecept run unit
I was surprised to see how few examples there are for this. I was writing tests for a job queue client. Here is a bit of my test:
protected function setUp()
{
$this->serviceManager = new ServiceManager(new ServiceManagerConfig());
$config = Bootstrap::getConfig();
$this->serviceManager->setService('ApplicationConfig', $config);
$this->serviceManager->get('ModuleManager')->loadModules();
$this->client = $this->serviceManager->get('jobclient');
$this->client->addServers(array(array('ip' => '127.0.0.1', 'port' => '666')));
}
public function testServiceCreateSuccess() {
$this->client->setQueue($this->testData['queue']);
$this->assertEquals($this->client->getQueue(), $this->testData['queue'], 'We get the expected queue');
}
I mocked the job client and had a local config. My _bootstrap.php file looks basically the same as the Zend example except that I am using factories defined in the service config to manage some objects. So, I performed the "setService" method in the test setup rather then in the bootsrap init.
Just begun creating some unit tests for my controllers within my CakePHP application however I am completely flummoxed on how I should create a mock for the Auth Component, I have read the CookBook and thought I had it right, but keep getting thrown this error.
Error: Call to a member function allow() on a non-object
Within the controller I am testing there is a beforeFilter function with the following code:
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('create');
}
Within my test I have included the following:
$Leagues = $this->generate('Leagues', array(
'components' => array(
'Auth'
)
));
I have played around with staticExpects() also but it doesn't seem to have much affect (I am also unsure what I need to put in to staticExpects()).
What do you mean by mock? Just stuffing an object with data that you set? The error you're getting is because you need to use
$this->Auth->allow(array('create'))
Found the issue - I have included the Auth component within AppController.php, and not specifically within the controller I was trying to test. By including it with my controller specifically the errors have gone away.
Not sure if I'm asking the right question so please bear with me! Bit of an NHibernate noob.
We're using Fluent NH and have the following id generation scheme for all tables
public class IdGenerationConvention : IIdConvention
{
public void Apply(IIdentityInstance instance)
{
var where = string.Format("TableKey = '{0}'", instance.EntityType.Name);
instance.GeneratedBy.HiLo("HiloPrimaryKeys", "NextHighValue", "1000", x => x.AddParam("where", where));
}
}
We have an SQL script that generates the HiloPrimaryKeys table and seeds it with data which gets run during deployment. This is working fine.
I'm now trying to write unit tests to verify our persistence layer, ideally using SQLite in memory configuration for speed. This is how I configure NH for the tests:
[SetUp]
public void SetupContext()
{
config = new SQLiteConfiguration()
.InMemory()
.ShowSql()
.Raw("hibernate.generate_statistics", "true");
var nhConfig = Fluently.Configure()
.Database(PersistenceConfigurer)
.Mappings(mappings =>
mappings.FluentMappings.AddFromAssemblyOf<DocumentMap>()
.Conventions.AddFromAssemblyOf<IdGenerationConvention>());
SessionSource = new SessionSource(nhConfig);
Session = SessionSource.CreateSession();
SessionSource.BuildSchema(Session);
}
The problem is I don't know how to tell NHibernate about our deployment script so that it generates the correct schema and seed data during tests.
The specific problem I get is when running the following PersistenceSpecification test:
[Test]
public void ShouldAddDocumentToDatabaseWithSimpleValues()
{
new PersistenceSpecification<Document>(Session)
.CheckProperty(x => x.CreatedBy, "anonymous")
.CheckProperty(x => x.CreatedOn, new DateTime(1954, 12, 23))
.CheckProperty(x => x.Reference, "anonymous")
.CheckProperty(x => x.IsMigrated, true)
.CheckReference(x => x.DocumentType, documentType)
.VerifyTheMappings();
}
Which throws the following exception:
TestCase ... failed:
Execute
NHibernate.Exceptions.GenericADOException:
could not get or update next value[SQL: ]
---> System.Data.SQLite.SQLiteException: SQLite error
no such column: TableKey
So my deduction is that it hasn't run the deployment script when checking the persistence spec.
Is there an existing solution to this situation? My Google-fu seems to have deserted me on this one.
As Brian said, you can run the deployment script after the schema is built. This code works well for me:
var config = new SQLiteConfiguration()
.InMemory()
.ShowSql()
.Raw("hibernate.generate_statistics", "true");
var nhConfig = Fluently.Configure()
.Database(config)
.Mappings(mappings =>
mappings.FluentMappings.AddFromAssemblyOf<DocumentMap>()
.Conventions.AddFromAssemblyOf<IdGenerationConvention>());
var SessionSource = new SessionSource(nhConfig);
var Session = SessionSource.CreateSession();
SessionSource.BuildSchema(Session);
// run the deployment script
var deploymentScriptQuery = Session.CreateSQLQuery("ALTER TABLE HiloPrimaryKeys ADD COLUMN TableKey VARCHAR(255); INSERT INTO HiloPrimaryKeys (TableKey, NextHighValue) values ('Document', 1);");
deploymentScriptQuery.ExecuteUpdate();
The deployment script could be loaded from file etc...
Building FNH configuration and database schema is time consuming action. Execution of test suit will take unacceptable amount of time if the count of tests that are using the schema grows and the schema and the configuration are built by each test class. Both configuration and schema should be shared between all tests. Here is how to achieve that without loosing test isolation.
EDIT:
If more than one session instance is required in test then connection pooling should be turned on, or both sessions should be created via the same connection. Details here...
Disclaimer: I'm not an NHibernate user...
...But one possible workaround would be to run your deployment script (or some variation of it) in your test's Setup method (using a shell execute/Process.Start) or to run it in your build script just before you run these tests. You may need to add cleanup in this case if you want a fresh database each test.
We have an SQL script that generates the HiloPrimaryKeys table and seeds it with data which gets run during deployment. This is working fine.
Can you create an entity that gets mapped that represents this HiloPrimaryKeys table and fill this table before your tests start? You could put this in a base class that all your other tests inherit from so that you wouldn't have to add this to every testing class.
This is similar to Brian's solution but instead this table will be created when you do your automapping just like the rest of your tables.