Laravel Dusk Can't Read Click of Undefined - php

I tried simple demo of laravel dusk but I get the following error; I tried to update composer installer as suggested by some solution and also tried to set duskcommand.php as suggested on git but still having the error.
Warning: TTY mode is not supported on Windows platform.
PHPUnit 7.3.5 by Sebastian Bergmann and contributors.
[1004/130622.087:ERROR:gpu_process_transport_factory.cc(1007)] Lost UI shared context.
Tests\Browser\RegisterTest::testExample
Facebook\WebDriver\Exception\UnknownServerException: unknown error: Cannot read property 'click' of undefined
(Session info: headless chrome=69.0.3497.100)
(Driver info: chromedriver=2.35.528161 (5b82f2d2aae0ca24b877009200ced9065a772e73),platform=Windows NT 10.0.17134 x86_64)
I'm trying this demo in Windows 10.
below is my RegisterTest.php
<?php
namespace Tests\Browser;
use Tests\DuskTestCase;
use Laravel\Dusk\Browser;
use Illuminate\Foundation\Testing\DatabaseMigrations;
class RegisterTest extends DuskTestCase
{
/**
* A Dusk test example.
*
* #return void
*/
public function testExample()
{
$this->browse(function ($browser) {
$browser->visit('/') //Go to the homepage
->clickLink('Register') //Click the Register link
->assertSee('Register') //Make sure the phrase in the argument is on the page
//Fill the form with these values
->value('#name', 'Joe')
->value('#email', 'joe#example.com')
->value('#password', '123456')
->value('#password-confirm', '123456')
->click('button[type="submit"]') //Click the submit button on the page
->assertPathIs('/home') //Make sure you are in the home page
//Make sure you see the phrase in the argument
->assertSee("You are logged in!");
});
}
}

Related

Symfony 4.4 Upgrade - DoctrineUpdateCommand no longer called from console command

I am upgrading our Symfony application from version 3.4 to version 4.4, which includes an upgrade of Doctrine from 1.12 to 2.3. I had previously written a class that modified the results to the doctrine:schema:update command, which worked great, but appears not to be working now. The class is below.
To modify doctrine:schema:update, I created a class called DoctrineUpdateCommand, which extended \Doctrine\ORM\Tools\Console\Command\SchemaTool\UpdateCommand, and placed it in the Command folder of the bundle. This was all that was needed. I referenced this answer to figure out how to do it: How to set up entity (doctrine) for database view in Symfony 2.
We need to override the doctrine:schema:update command because one of our entities refers to a MySQL view instead of a MySQL table. Further, the entity is referenced as both a stand alone entity, and as a many-to-many join. The override class caused the entity and join to be ignored. It also added a sql statement to create the view.
After the upgrade, if I run php console doctrine:schema:update --dump-sql, I get these results:
19:08:16 CRITICAL [console] Error thrown while running command "doctrine:schema:update --dump-sql". Message: "The table with name 'nest_qa.assignedrole_privilegerole' already exists." ["exception" => Doctrine\DBAL\Schema\SchemaException^ { …},"command" => "doctrine:schema:update --dump-sql","message" => "The table with name 'nest_qa.assignedrole_privilegerole' already exists."]
In SchemaException.php line 112:
The table with name 'nest_qa.assignedrole_privilegerole' already exists.
I am fairly certain that the extension of the doctrine command is no longer being called, and it's using the default command instead, but I can't figure out how to change that. Any help would be appreciated.
Here is the original class:
<?php
namespace ApiBundle\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Doctrine\ORM\Tools\SchemaTool;
class DoctrineUpdateCommand extends \Doctrine\ORM\Tools\Console\Command\SchemaTool\UpdateCommand{
protected $ignoredEntities = array(
'ApiBundle\Entity\AssignedrolePrivilegerole',
);
protected $ignoreAssociationMappings = array(
'ApiBundle\Entity\Privilegerole' => 'assignedroles',
'ApiBundle\Entity\Assignedrole' => 'privilegeroles',
);
protected function executeSchemaCommand(InputInterface $input, OutputInterface $output, SchemaTool $schemaTool, array $metadatas, SymfonyStyle $ui) {
/** #var $metadata \Doctrine\ORM\Mapping\ClassMetadata */
$newMetadatas = array();
foreach ($metadatas as $metadata) {
if (array_key_exists($metadata->getName(), $this->ignoreAssociationMappings)) {
if(array_key_exists($this->ignoreAssociationMappings[$metadata->getName()], $metadata->getAssociationMappings())){
unset($metadata->associationMappings[$this->ignoreAssociationMappings[$metadata->getName()]]);
}
}
//If metadata element is not in the ignore array, add it to the new metadata array
if (!in_array($metadata->getName(), $this->ignoredEntities)){
array_push($newMetadatas, $metadata);
}
}
parent::executeSchemaCommand($input, $output, $schemaTool, $newMetadatas, $ui);
$output->writeln("------Create view for assignedrole_privilegerole");
$output->writeln("CREATE VIEW `assignedrole_privilegerole` AS select `Assignedrole`.`id` AS `assignedrole_id`,`Privilegerole`.`id` AS `privilegerole_id` from (`Assignedrole` join `Privilegerole`) where ((`Assignedrole`.`role_id` = `Privilegerole`.`role_id`) and ((`Assignedrole`.`unit_id` = `Privilegerole`.`unit_id`) or `Privilegerole`.`unit_id` in (select `Unittree`.`ancestor_id` from `Unittree` where (`Unittree`.`descendant_id` = `Assignedrole`.`unit_id`)))) ;");
}
}
Console commands in symfony <4.x were registered by scanning Command folder inside a bundle. Since bundles are obsolete in symfony 4+, you have to define commands in your services definition by tagging the command class, or use DI autoconfiguration.
Option 1: explicitly add console.command tag to the service definition:
services:
ApiBundle\Command\DoctrineUpdateCommand:
tags:
- { name: twig.extension }
Option 2: use DI autoconfiguration:
services:
ApiBundle\Command\DoctrineUpdateCommand:
autoconfigure: true
After your class is registered as a console command, it must override the default one.
See symfony docs for more: Console Command

Can't generate API documentation in l5-swagger

I'm starting to study swagger.
I'm trying to do the same which is done in a book "Hands-On Full Stack Web Development with Angular 6 and Laravel 5".
Using php-fpm bash after typing command "php artisan l5-swagger:generate"
I have got this exception in VS Code terminal:
root#8e6435be9103:/application# php artisan l5-swagger:generate
Regenerating docs
ErrorException : Required #OA\Info() not found
at /application/vendor/zircote/swagger-php/src/Logger.php:39
35| $this->log = function ($entry, $type) {
36| if ($entry instanceof Exception) {
37| $entry = $entry->getMessage();
> 39| trigger_error($entry, $type);
40| };
41| }
42|
43| /**
Exception trace:
1 trigger_error("Required #OA\Info() not found")
/application/vendor/zircote/swagger-php/src/Logger.php:39
2 OpenApi\Logger::OpenApi\{closure}("Required #OA\Info() not found")
/application/vendor/zircote/swagger-php/src/Logger.php:71
And when I trying to open http://localhost:8081/api/documentation url it gives this error:
Failed to load API definition.
Fetch errorNot Found http://localhost:8081/docs/api-docs.json
I'am using php-fpm bash inside docker.
My OS is Ubuntu 18.04.3 LTS.
Can anyone help me to fix this problem.
Thank you!!!
You have to put some annotations in your code before running php artisan l5-swagger:generate. First, go to app/Http/Controllers/Controller.php and add a phpdoc comment block as follow before the class declaration:
/**
* #OA\Info(title="My First API", version="0.1")
*/
This annotation by itself is sufficient to resolve the issue that you described, but if you execute php artisan l5-swagger:generate again you will see the following Exception:
ErrorException : Required #OA\PathItem() not found
at /home/nathanael/dev/laravel-projects/laravel-swagger/vendor/zircote/swagger-php/src/Logger.php:39
35| $this->log = function ($entry, $type) {
36| if ($entry instanceof Exception) {
37| $entry = $entry->getMessage();
38| }
> 39| trigger_error($entry, $type);
40| };
41| }
42|
43| /**
Exception trace:
1 trigger_error("Required #OA\PathItem() not found")
/home/nathanael/dev/laravel-projects/laravel-swagger/vendor/zircote/swagger-php/src/Logger.php:39
2 OpenApi\Logger::OpenApi\{closure}("Required #OA\PathItem() not found")
/home/nathanael/dev/laravel-projects/laravel-swagger/vendor/zircote/swagger-php/src/Logger.php:71
Please use the argument -v to see more details.
That's because you must have at least one method in a controller with an annotation that describes a route.
You can easily create a resource in your application to test running php artisan make:controller ProjectsController -r and adding Route::resource('projects', 'ProjectsController') to routes/web.php.
After creating the controller open it and add the following phpdoc comment block before the index method, for example:
/**
* #OA\Get(
* path="/projects",
* #OA\Response(response="200", description="Display a listing of projects.")
* )
*/
Then, run php artisan l5-swagger:generate again and you must see a success message in the terminal.

Why am I unable to catch the Unexpected Alert Exception?

I am using a try catch block to catch an exception and I am unable to catch it as it still says:
In Exception.php line 155:
unexpected alert open: {Alert text : The form is not complete and has not been submitted yet. There is 1 problem with your submission.}
(Session info: chrome=73.0.3683.75)
(Driver info: chromedriver=2.41.578700 (2f1ed5f9343c13f73144538f15c00b370eda6706),platform=Linux 4.15.0-38-generic x86_64)
My feature file:
<?php
use Behat\Behat\Hook\Scope\AfterStepScope;
use Behat\Behat\Tester\Exception\PendingException;
use Behat\Behat\Context\Context;
use Behat\MinkExtension\Context\MinkContext;
use WebDriver\Exception\UnexpectedAlertOpen;
/**
* Defines application features from the specific context.
*/
class FeatureContext extends MinkContext implements Context
{
/**
* Initializes context.
*
* Every scenario gets its own context instance.
* You can also pass arbitrary arguments to the
* context constructor through behat.yml.
*/
public function __construct()
{
}
/**
* #Given I fill in the email field with :email
*/
public function iFillInTheEmailFieldWith($email)
{
dump($email);
$this->visit('/471w2222');
$page = $this->getSession()->getPage();
$page->find('xpath', '//*[#id="tfa_1111"]')->setValue($email);
}
/**
* #When I submit the form
*/
public function iSubmitTheForm()
{
try {
$page = $this->getSession()->getPage();
$page->find('xpath', '//*[#id="submit_button"]')->click();
}
catch (UnexpectedAlertOpen $e){
dd($e->getMessage());
$this->getSession()->getDriver()->getWebDriverSession()->accept_alert();
}
}
}
The alert shows up :
$page->find('xpath', '//*[#id="submit_button"]')->click();
executes. But it is unable to catch it. Why?
As per the error message...
(Session info: chrome=73.0.3683.75)
(Driver info: chromedriver=2.41.578700 (2f1ed5f9343c13f73144538f15c00b370eda6706),platform=Linux 4.15.0-38-generic x86_64)
...the main issue is the incompatibility between the version of the binaries you are using as follows:
You are using chromedriver=2.41
Release Notes of chromedriver=2.41 clearly mentions the following :
Supports Chrome v67-69
You are using chrome=73.0
Release Notes of ChromeDriver v2.46 clearly mentions the following :
Supports Chrome v71-73
So there is a clear mismatch between the ChromeDriver v2.41 and the Chrome Browser v73.0
Solution
Upgrade ChromeDriver to current ChromeDriver v2.46 level.
Keep Chrome version between Chrome v73 levels. (as per ChromeDriver v2.45 release notes)
Clean your Project Workspace through your IDE and Rebuild your project with required dependencies only.
If your base Web Client version is too old, then uninstall it and install a recent GA and released version of Web Client.
Take a System Reboot.
Execute your #Test.
Always invoke driver.quit() within tearDown(){} method to close & destroy the WebDriver and Web Client instances gracefully.

DoctrineCacheBundle: Flush cache via SYmfony route

Over my Symfony project I use the DoctrineCacheBundle and I want when I visit http://example.com/api/cache/flush I want to uncache (flush) any cached key.
The sole reason is because I have applications that visit the url above in order to remove any cached result.
As far I searched the DoctrineCacheBundle uses a command in order to uncache the cached results (as you can see via php ./bin/console list doctrine:cache command):
Symfony 3.3.12 (kernel: app, env: dev, debug: true)
Usage:
command [options] [arguments]
Options:
-h, --help Display this help message
-q, --quiet Do not output any message
-V, --version Display this application version
--ansi Force ANSI output
--no-ansi Disable ANSI output
-n, --no-interaction Do not ask any interactive question
-e, --env=ENV The environment name [default: "dev"]
--no-debug Switches off debug mode
-v|vv|vvv, --verbose Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug
Available commands for the "doctrine:cache" namespace:
doctrine:cache:clear Flush a given cache
doctrine:cache:contains Check if a cache entry exists
doctrine:cache:delete Delete a cache entry
doctrine:cache:flush [doctrine:cache:clear] Flush a given cache
doctrine:cache:stats Get stats on a given cache provider
But how can I do this programmatically?
The best way is to make your own Cache adapter by following one of theese 2 approaches:
Approach 1: Use dedicated manager for uncaching:
namespace AppBundle\CacheManagers;
use Doctrine\Common\Cache\FlushableCache;
class PurgeAllcachesManager
{
/**
* #var FlushableCache
*/
private $purgeCachingHandler=null;
public function __construct(FlushableCache $purgeCachingHandler)
{
$this->purgeCachingHandler=$purgeCachingHandler;
}
/**
* Method that does all the dirty job to uncache all the keys
*/
public function uncache()
{
$this->purgeCachingHandler->flushAll();
}
}
Approach2: Do as Doctrine does:
namespace AppBundle\CacheManagers;
use Doctrine\Common\Cache\Cache as CacheHandler;
class PurgeAllcachesManager
{
/**
* #var CacheHandler
*/
private $cacheHandler=null;
public function __construct(CacheHandler $cacheHandler)
{
$this->cacheHandler=$cacheHandler;
}
/**
* Method that does all the dirty job to uncache all the keys
* #throws Exception
*/
public function uncacheAllKeys()
{
if(!method_exists($this->purgeCachingHandler) ){
throw new Exception("You cannot empty the cache");
}
$this->purgeCachingHandler->flushAll();
}
//Yet another methods to handle the cache
}
Also have a look on this question for extra info on how to use it.

Call to a member function getSession() on a non-object in vendor/behat/mink-extension/src/Behat/MinkExtension/Context/RawMinkContext.php on line 81

I get this error when trying to run my behat tests from the command line.
The full output of the error looks like this:
$ behat
Feature: View a list of current custom tariffs
In order to provide custom call pricing to customers
As a user of the Voxbeam Admin site
I expect to be able to correctly administrate a users custom tariffs
#sahi
Scenario: Listing existing custom tariffs # features/custom_tariff_admin.feature:7
PHP Fatal error: Call to a member function getSession() on a non-object in /Users/stuart/bin/vendor/behat/mink-extension/src/Behat/MinkExtension/Context/RawMinkContext.php on line 81
PHP Stack trace:
PHP 1. {main}() /Users/stuart/bin/vendor/behat/behat/bin/behat:0
PHP 2. Symfony\Component\Console\Application->run() /Users/stuart/bin/vendor/behat/behat/bin/behat:32
PHP 3. Behat\Behat\Console\BehatApplication->doRun() /Users/stuart/bin/vendor/symfony/console/Symfony/Component/Console/Application.php:106
PHP 4. Symfony\Component\Console\Application->doRun() /Users/stuart/bin/vendor/behat/behat/src/Behat/Behat/Console/BehatApplication.php:68
PHP 5. Symfony\Component\Console\Command\Command->run() /Users/stuart/bin/vendor/symfony/console/Symfony/Component/Console/Application.php:193
PHP 6. Behat\Behat\Console\Command\BehatCommand->execute() /Users/stuart/bin/vendor/symfony/console/Symfony/Component/Console/Command/Command.php:240
PHP 7. Behat\Behat\Console\Command\BehatCommand->runFeatures() /Users/stuart/bin/vendor/behat/behat/src/Behat/Behat/Console/Command/BehatCommand.php:128
PHP 8. Behat\Gherkin\Node\AbstractNode->accept() /Users/stuart/bin/vendor/behat/behat/src/Behat/Behat/Console/Command/BehatCommand.php:150
PHP 9. Behat\Behat\Tester\FeatureTester->visit() /Users/stuart/bin/vendor/behat/gherkin/src/Behat/Gherkin/Node/AbstractNode.php:42
PHP 10. Behat\Gherkin\Node\AbstractNode->accept() /Users/stuart/bin/vendor/behat/behat/src/Behat/Behat/Tester/FeatureTester.php:88
PHP 11. Behat\Behat\Tester\ScenarioTester->visit() /Users/stuart/bin/vendor/behat/gherkin/src/Behat/Gherkin/Node/AbstractNode.php:42
PHP 12. Behat\Behat\Tester\ScenarioTester->visitStep() /Users/stuart/bin/vendor/behat/behat/src/Behat/Behat/Tester/ScenarioTester.php:87
PHP 13. Behat\Gherkin\Node\AbstractNode->accept() /Users/stuart/bin/vendor/behat/behat/src/Behat/Behat/Tester/ScenarioTester.php:148
PHP 14. Behat\Behat\Tester\StepTester->visit() /Users/stuart/bin/vendor/behat/gherkin/src/Behat/Gherkin/Node/AbstractNode.php:42
PHP 15. Behat\Behat\Tester\StepTester->executeStep() /Users/stuart/bin/vendor/behat/behat/src/Behat/Behat/Tester/StepTester.php:95
PHP 16. Behat\Behat\Tester\StepTester->executeStepDefinition() /Users/stuart/bin/vendor/behat/behat/src/Behat/Behat/Tester/StepTester.php:126
PHP 17. Behat\Behat\Definition\Annotation\Definition->run() /Users/stuart/bin/vendor/behat/behat/src/Behat/Behat/Tester/StepTester.php:157
PHP 18. call_user_func_array() /Users/stuart/bin/vendor/behat/behat/src/Behat/Behat/Definition/Annotation/Definition.php:155
PHP 19. Behat\MinkExtension\Context\MinkContext->visit() /Users/stuart/bin/vendor/behat/behat/src/Behat/Behat/Definition/Annotation/Definition.php:155
PHP 20. Behat\MinkExtension\Context\RawMinkContext->getSession() /Users/stuart/bin/vendor/behat/mink-extension/src/Behat/MinkExtension/Context/MinkContext.php:45
My behat.yml is:
# behat.yml
default:
paths:
features: features
bootstrap: %behat.paths.features%/bootstrap
extensions:
Behat\MinkExtension\Extension:
base_url: 'http://dev.example.com'
goutte: ~
sahi: ~
annotations:
paths:
features: features/annotations
closures:
paths:
features: features/closures
I have a very simple FeatureContext:
<?php
use Behat\Behat\Context\ClosuredContextInterface,
Behat\Behat\Context\BehatContext,
Behat\Behat\Exception\PendingException,
Behat\Behat\Context\Step;
use Behat\Gherkin\Node\PyStringNode,
Behat\Gherkin\Node\TableNode;
use Behat\MinkExtension\Context\MinkContext;
//
// Require 3rd-party libraries here:
//
// require_once 'PHPUnit/Autoload.php';
// require_once 'PHPUnit/Framework/Assert/Functions.php';
//
/**
* Features context.
*/
class FeatureContext extends MinkContext
{
/**
* #Given /^I am logged in as "([^"]*)" with password "([^"]*)"$/
*/
public function iAmLoggedInAsWithPassword($userName, $password)
{
return array(
new Step\Given('I am on "/login"'),
new Step\Given('I should see "fert"')
);
}
//
// Place your definition and hook methods here:
//
// /**
// * #Given /^I have done something with "([^"]*)"$/
// */
// public function iHaveDoneSomethingWith($argument)
// {
// doSomethingWith($argument);
// }
//
}
and an equally simple feature:
Feature: Administer a customers custom tariffs
In order to provide custom call pricing to customers
As a user of the Admin site
I expect to be able to correctly administrate a users custom tariffs
Scenario: Listing existing custom tariffs
Given I am on "/"
I should see "Fert"
Make sure your behat.yml file is in the correct location. It should be in the root of your project, not in any subdirectories.
If the advice of Stuart Grimshaw doesn't owrk, it can be because of two reasons :
Your composer.json configuration is not correct; it is tricky to get the correct versions of the 5 or 6 different modules that are needed to make Mink, Behat, Goutte, Selenium, Zombie, maybe Symfony2.. all work together; so please check manually, in each composer.json of those extensions, the required versions of other components; also, try not to use mink-bundle, whose versions of required dependancies seem old
Do not run the bin\behat command (under Windows or Linux) from your bundle directory; otherwise the .yml configuration file is not found (for sure some obscure reason related to relative paths). You should run the bin\behat command from the root of your project (run the cd command to it first
I was getting a similar fatal error as well
PHP Fatal error: Call to a member function getSession() on a non-object in /home/ahad/sites/symfony/vendor/behat/mink-extension/src/Behat/MinkExtension/Context/RawMinkContext.php on line 101
I have put my answer over here Struggling to get Mink working with Behat
Which solved my problem.

Categories