[英]Symfony or something else get confused with logged in user while executing a test
After a lot of research and without found nothing helpful I come here to see if can get some help. 经过大量的研究,没有发现任何有用的东西,我来这里看看是否能得到一些帮助。 I'm building some functional tests for my code and one of those test need a fake user for work since in the function at controller I need to access to User
object by using this piece of code: 我正在为我的代码构建一些功能测试,其中一个测试需要一个假用户工作,因为在控制器的函数中我需要使用这段代码访问User
对象:
$account = $this->getUser();
$user = $account->getUser();
This is the code in my test: 这是我测试中的代码:
public function testmodifyCommissionAction() {
$this->logIn();
$updateCompanyCommission = $this->client->getContainer()->get('router')->generate('updateCompanyCommission', array(), false);
$this->client->request("POST", $updateCompanyCommission, array(
'id' => rand(1, 10),
'fee' => rand(1, 10)
));
var_dump($this->client->getResponse()->getContent());
$this->assertSame(200, $this->client->getResponse()->getStatusCode()); // Test if response is OK
$this->assertSame('application/json', $this->client->getResponse()->headers->get('Content-Type')); // Test if Content-Type is valid application/json
$this->assertNotEmpty($this->client->getResponse()->getContent()); // Test that response is not empty
$decoded = json_decode($this->client->getResponse()->getContent(), true);
} }
private function logIn() {
$session = $this->client->getContainer()->get('session');
$firewall = 'secured_area';
$token = new UsernamePasswordToken('admin', null, $firewall, array('ROLE_ADMIN'));
$session->set('_security_' . $firewall, serialize($token));
$session->save();
$cookie = new Cookie($session->getName(), $session->getId());
$this->client->getCookieJar()->set($cookie);
}
Now, where is the problem here? 现在,这里的问题在哪里? If I login in my application using valid credentials and run the test then I got this error: 如果我使用有效凭据登录我的应用程序并运行测试,那么我收到此错误:
Cannot set session ID after the session has started. 会话启动后无法设置会话ID。 (500 Internal Server Error) (500内部服务器错误)
If I logout and run the same test it works, so something is wrong here and I can't get what is, any help? 如果我注销并运行相同的测试它是有效的,所以这里有些问题,我无法得到什么,有什么帮助? advice? 建议? tips? 提示? example of working code? 工作代码的例子?
EDIT: created User and try to login with the current created User 编辑:创建用户并尝试使用当前创建的用户登录
I modified a bit the method and now this is the current code I have: 我修改了一下方法,现在这是我当前的代码:
protected function createUser() {
$kernel = new \AppKernel('test', true);
$kernel->boot();
$this->container = $kernel->getContainer();
$userManager = $this->container->get('fos_user.user_manager');
$userManager->createUser();
$data['firstname'] = $this->generateRandomString(4);
$data['lastname'] = $this->generateRandomString(4);
$data['lastname2'] = "";
$data['photo'] = "";
$data['banner'] = "";
$data['password'] = md5($this->generateRandomString(18));
$data['email'] = $this->generateRandomString(6) . "@test.com";
$user = $userManager->createAccountAndUser($data);
return $user;
}
This is the function I'm using to login, modified also to add support for current user: 这是我用来登录的功能,也修改为添加对当前用户的支持:
private function logIn($client, $user) {
$session = $client->getContainer()->get('session');
$firewall = 'main';
$token = new UsernamePasswordToken($user, null, $firewall, array('ROLE_USER'));
$session->set('_security_' . $firewall, serialize($token));
$session->save();
$cookie = new Cookie($session->getName(), $session->getId());
$client->getCookieJar()->set($cookie);
}
And this is the test I'm trying to run: 这是我正在尝试运行的测试:
public function testmodifyCommissionAction() {
$client = static::createClient();
$user = $this->createUser();
$this->logIn($client, $user->getUser()->getAlias());
$updateCompanyCommission = $client->getContainer()->get('router')->generate('updateCompanyCommission', array(), false);
$client->request("POST", $updateCompanyCommission, array(
'id' => rand(1, 10),
'fee' => rand(1, 10)
));
$this->assertSame(200, $client->getResponse()->getStatusCode());
$this->assertSame('application/json', $client->getResponse()->headers->get('Content-Type'));
$this->assertNotEmpty($client->getResponse()->getContent());
}
But fails with this message: 但是失败了这条消息:
PHP Fatal error: Call to a member function getUser() on a non-object in /var/www/html/kraken/src/Wuelto/Company/ApprovalBundle/Controller/FeeCompanyController.php on line 47
PHP Stack trace:
PHP 1. {main}() /usr/bin/phpunit:0
PHP 2. PHPUnit_TextUI_Command::main() /usr/bin/phpunit:46
PHP 3. PHPUnit_TextUI_Command->run() /usr/share/pear/PHPUnit/TextUI/Command.php:129
PHP 4. PHPUnit_TextUI_TestRunner->doRun() /usr/share/pear/PHPUnit/TextUI/Command.php:176
PHP 5. PHPUnit_Framework_TestSuite->run() /usr/share/pear/PHPUnit/TextUI/TestRunner.php:349
PHP 6. PHPUnit_Framework_TestSuite->runTest() /usr/share/pear/PHPUnit/Framework/TestSuite.php:745
PHP 7. PHPUnit_Framework_TestCase->run() /usr/share/pear/PHPUnit/Framework/TestSuite.php:775
PHP 8. PHPUnit_Framework_TestResult->run() /usr/share/pear/PHPUnit/Framework/TestCase.php:783
PHP 9. PHPUnit_Framework_TestCase->runBare() /usr/share/pear/PHPUnit/Framework/TestResult.php:648
PHP 10. PHPUnit_Framework_TestCase->runTest() /usr/share/pear/PHPUnit/Framework/TestCase.php:838
PHP 11. ReflectionMethod->invokeArgs() /usr/share/pear/PHPUnit/Framework/TestCase.php:983
PHP 12. Wuelto\Company\ApprovalBundle\Tests\Controller\FeeCompanyControllerTest->testmodifyCommissionAction() /usr/share/pear/PHPUnit/Framework/TestCase.php:983
PHP 13. Symfony\Component\BrowserKit\Client->request() /var/www/html/kraken/src/Wuelto/Company/ApprovalBundle/Tests/Controller/FeeCompanyControllerTest.php:71
PHP 14. Symfony\Bundle\FrameworkBundle\Client->doRequest() /var/www/html/kraken/vendor/symfony/symfony/src/Symfony/Component/BrowserKit/Client.php:325
PHP 15. Symfony\Component\HttpKernel\Client->doRequest() /var/www/html/kraken/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Client.php:111
PHP 16. Symfony\Component\HttpKernel\Kernel->handle() /var/www/html/kraken/vendor/symfony/symfony/src/Symfony/Component/HttpKernel/Client.php:81
PHP 17. Symfony\Component\HttpKernel\DependencyInjection\ContainerAwareHttpKernel->handle() /var/www/html/kraken/app/bootstrap.php.cache:2303
PHP 18. Symfony\Component\HttpKernel\HttpKernel->handle() /var/www/html/kraken/app/bootstrap.php.cache:3022
PHP 19. Symfony\Component\HttpKernel\HttpKernel->handleRaw() /var/www/html/kraken/app/bootstrap.php.cache:2883
PHP 20. call_user_func_array:{/var/www/html/kraken/app/bootstrap.php.cache:2911}() /var/www/html/kraken/app/bootstrap.php.cache:2911
PHP 21. Company\ApprovalBundle\Controller\FeeCompanyController->modifyCommissionAction() /var/www/html/kraken/app/bootstrap.php.cache:2911
I can't find where is the problem, any help? 我找不到问题在哪里,有什么帮助吗?
Solution: The problem was on this line: 解决方案:问题出在这一行:
$this->logIn($client, $user->getUser()->getAlias());
since I was trying to pass $user->getUser()->getAlias()
instead of $user
the object. 因为我试图传递$user->getUser()->getAlias()
而不是$user
对象。
EDIT 2: Sort code and getting error while trying to DELETE the recently test user 编辑2:在尝试删除最近测试用户时对代码进行排序并获取错误
Now I made some changes and pass the $this->createUser()
to setUp()
function in order to have User object on $this->user
var. 现在我做了一些更改并将$this->createUser()
传递给setUp()
函数,以便在$this->user
var上有User对象。
public function setUp() {
static::$kernel = static::createKernel();
static::$kernel->boot();
$this->em = static::$kernel->getContainer()->get('doctrine')->getManager();
$fixture = new LoadFeeData();
$fixture->load($this->em);
$this->user = $this->createUser();
parent::setUp();
}
Now in tearDown()
I'm trying to delete the current User I created earlier with this code: 现在在tearDown()
我试图删除我之前使用此代码创建的当前用户:
protected function tearDown() {
parent::tearDown();
$this->em->remove($this->user);
$this->em->flush();
$this->em->close();
}
But get this error: 但得到这个错误:
1) Company\ApprovalBundle\Tests\Controller\FeeCompanyControllerTest::testmodifyCommissionAction
Undefined index: 0000000065c988b30000000022bd0894
/var/www/html/kraken/vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php:2860
/var/www/html/kraken/vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php:1736
/var/www/html/kraken/vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php:1397
/var/www/html/kraken/vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php:1677
/var/www/html/kraken/vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php:1645
/var/www/html/kraken/vendor/doctrine/orm/lib/Doctrine/ORM/EntityManager.php:647
/var/www/html/kraken/app/cache/test/jms_diextra/doctrine/EntityManager_533ab9b6c8c69.php:59
/var/www/html/kraken/src/Company/ApprovalBundle/Tests/Controller/FeeCompanyControllerTest.php:131
Why I can't delete the User? 为什么我无法删除用户?
What I typically do is enable http_basic security for the test environment and then do the following to get an authenticated client: 我通常做的是为测试环境启用http_basic安全性,然后执行以下操作以获取经过身份验证的客户端:
config_test.yml config_test.yml
security:
firewalls:
wsse_secured: # This should be your firewall name
http_basic: true
Next, make sure your tests extend the Symfony WebTestCase (Symfony\\Bundle\\FrameworkBundle\\Test\\WebTestCase) 接下来,确保您的测试扩展Symfony WebTestCase(Symfony \\ Bundle \\ FrameworkBundle \\ Test \\ WebTestCase)
Then you can just call: 然后你可以打电话:
$client = $this->createClient([], [
'PHP_AUTH_USER' => $username,
'PHP_AUTH_PW' => $password,
]);
client->request("POST", $updateCompanyCommission, array(
'id' => rand(1, 10),
'fee' => rand(1, 10)
));
...
Using this method, the users need to either be loaded as a data fixture, or you can write a method to create a user in the setUp
and destroy the user in the tearDown
. 使用此方法,用户需要作为数据夹具加载,或者您可以编写一个方法来在setUp
创建用户并在tearDown
销毁用户。 Here is the method that I use to create a user for a test: 以下是我用于为测试创建用户的方法:
protected function createUser($password, $timezone, $roles)
{
$kernel = new \AppKernel('test', true);
$kernel->boot();
/** @var Account $user */
$this->container = $kernel->getContainer();
$userManager = $this->container->get('fos_user.user_manager');
$user = $userManager->createUser();
$user->setEmail('unique-email-address@not-here.com');
$user->setUsername('auniqueusername');
$user->setPlainPassword($password);
$user->setTimezone($timezone);
$user->setEnabled(true);
foreach ($roles as $role) {
$user->addRole($role);
}
$userManager->updateUser($user);
return $user;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.