I want to create a test which I will use from Controller so I write:
<?php
namespace App\Http\Controllers\Modules;
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Laravel\Dusk\ElementResolver;
use Exception;
use Facebook\WebDriver\Chrome\ChromeOptions;
use Facebook\WebDriver\Remote\DesiredCapabilities;
use Facebook\WebDriver\Remote\RemoteWebDriver;
use Laravel\Dusk\Browser;
use Laravel\Dusk\Chrome\ChromeProcess;
class TestController extends Controller {
public function test() {
$process = (new ChromeProcess)->toProcess();
if ($process->isStarted()) {
$process->stop();
}
$process->start();
$options = (new ChromeOptions)->addArguments(['--disable-gpu', '--headless', '--no-sandbox']);
$capabilities = DesiredCapabilities::chrome()
->setCapability(ChromeOptions::CAPABILITY, $options);
$driver = retry(1, function () use ($capabilities) {
return RemoteWebDriver::create('http://localhost:9515', $capabilities, 60000, 60000);
}, 50);
$browser = new Browser($driver, new ElementResolver($driver, ''));
$browser->resize(1920, 1080);
$browser->visit('https://example.com/login')->click('#.btn > form > div.auth-form-body.mt-3 > input.btn.btn-primary.btn-block');
$browser->driver->takeScreenshot(base_path('tests/Browser/screenshots/logged.png'));
}
}
When I run this script using localhost:8000/test I got this message:
Facebook \ WebDriver \ Exception \ WebDriverCurlException Curl error
thrown for http POST to /session with params:
{"desiredCapabilities":{"browserName":"chrome","platform":"ANY","chromeOptions":{"binary":"","args":["--disable-gpu","--headless","--no-sandbox"]}}}
Failed to connect to localhost port 9515: Connection refused
How I can solve this problem?
Current I use WAMP server on Win10 for local testing but then I will move the code on Linux Ubuntu 18.
I can't fully explain it, but this works for me on Windows:
$process = (new ChromeProcess)->toProcess();
if ($process->isStarted()) {
$process->stop();
}
$process->start(null, [
'SystemRoot' => 'C:\\WINDOWS',
'TEMP' => 'C:\Users\<User>\AppData\Local\Temp',
]);
[...]
Replace <User> with the name of your user directory.
Related
Im new to Lumen, I have managed to create and register the following ArangoDB service provider along with the service below and got it to work, but Im confused how I actually use them in another service or helper.
registered the provider in bootstrap/app.php
$app->register(App\Providers\ArangoServiceProvider::class);
ArangoServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class ArangoServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->singleton('ArangoService', function ($app) {
return new ArangoService($app);
});
}
public function boot()
{
//
}
}
ArangoService.php
<?
namespace App\Services;
use ArangoDBClient\Collection as ArangoCollection;
use ArangoDBClient\CollectionHandler as ArangoCollectionHandler;
use ArangoDBClient\Connection as ArangoConnection;
use ArangoDBClient\ConnectionOptions as ArangoConnectionOptions;
use ArangoDBClient\DocumentHandler as ArangoDocumentHandler;
use ArangoDBClient\Document as ArangoDocument;
use ArangoDBClient\Exception as ArangoException;
use ArangoDBClient\Export as ArangoExport;
use ArangoDBClient\ConnectException as ArangoConnectException;
use ArangoDBClient\ClientException as ArangoClientException;
use ArangoDBClient\ServerException as ArangoServerException;
use ArangoDBClient\Statement as ArangoStatement;
use ArangoDBClient\UpdatePolicy as ArangoUpdatePolicy;
class ArangoService{
public function __construct() {
$connectionOptions = [
// database name
ArangoConnectionOptions::OPTION_DATABASE => 'dbname',
// server endpoint to connect to
ArangoConnectionOptions::OPTION_ENDPOINT => 'tcp://123456789',
// authorization type to use (currently supported: 'Basic')
ArangoConnectionOptions::OPTION_AUTH_TYPE => 'Basic',
// user for basic authorization
ArangoConnectionOptions::OPTION_AUTH_USER => 'root',
// password for basic authorization
ArangoConnectionOptions::OPTION_AUTH_PASSWD => 'passwd',
// connection persistence on server. can use either 'Close' (one-time connections) or 'Keep-Alive' (re-used connections)
ArangoConnectionOptions::OPTION_CONNECTION => 'Keep-Alive',
// connect timeout in seconds
ArangoConnectionOptions::OPTION_TIMEOUT => 3,
// whether or not to reconnect when a keep-alive connection has timed out on server
ArangoConnectionOptions::OPTION_RECONNECT => true,
// optionally create new collections when inserting documents
ArangoConnectionOptions::OPTION_CREATE => true,
// optionally create new collections when inserting documents
ArangoConnectionOptions::OPTION_UPDATE_POLICY => ArangoUpdatePolicy::LAST,
];
// turn on exception logging (logs to whatever PHP is configured)
ArangoException::enableLogging();
$connection = new ArangoConnection($connectionOptions);
$collectionHandler = new ArangoCollectionHandler($connection);
$handler = new ArangoDocumentHandler($connection);
}
public function main(){
print "hello world!<br/>";
}
}
This all above works, but how do I in a controller, call a service, lets call it "UsersService" that has functions like GetUser() , how does this "UsersService" use the $connection, $collectionHandler and $handler , that I have created in my ArangoDB service.
route pointing to a controller (got that one)
controller calling UsersService
UsersService using the arango service and passing something back to the controller
grateful for any help!
I have this plain console program:
namespace MyApp\Console;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
class MaConsole extends Command {
protected function configure()
{
$this->setDescription('Console\'s not console');
}
protected function execute(
\Symfony\Component\Console\Input\InputInterface $input,
\Symfony\Component\Console\Output\OutputInterface $output
) {
$output->writeln('Doing Stuff');
}
}
And I load it like that:
namespace MyApp;
use Symfony\Component\Console\Application as SymfonyApplication;
use MyApp\Console\MaConsole;
class Application extends SymfonyApplication
{
public function __construct(
string $name = 'staff',
string $version = '0.0.1'
) {
parent::__construct($name, $version);
throw new \Exception('Test Sentry on Playground');
$this->add(new MaConsole());
}
}
And I want to log the exception thrown above in Sentry service. So I my entrypoint is:
use MyApp\Application;
require __DIR__ . '/vendor/autoload.php';
Sentry\init([
'dsn' => getenv('SENTRY_DSN'),
'environment' => getenv('ENVIRONMENT')
]);
$application = (new Application())->run();
But I fail to log the error into sentry, even thouhg I have set the correct enviromental variables.
The application does not load the Full Symfony framework, but instead it uses the console only components so I have no idea if I should use the Sentry Symfony Integration: https://docs.sentry.io/platforms/php/symfony/
The reason why is because I do not know how in my case to load the bundle, therefore I use the SDK.
Edit 1:
I also tried to catch the exception and manually log it but form some reason is not logged as well:
use MyApp\Application;
require __DIR__ . '/vendor/autoload.php';
try {
Sentry\init([
'dsn' => getenv('SENTRY_DSN'),
'environment' => getenv('ENVIRONMENT')
]);
throw new \Exception('Test Sentry on Playground');
$application = (new Application())->run();
} catch(Exception $e) {
Sentry\captureException($e);
}
You can use the dispatcher :
use Symfony\Component\EventDispatcher\EventDispatcher;
$dispatcher = new EventDispatcher();
$dispatcher->addListener(ConsoleEvents::ERROR, function (ConsoleErrorEvent $event) use ($env) {
Sentry\init([
'dsn' => getenv('SENTRY_DSN'),
'environment' => $env
]);
Sentry\captureException($event->getError());
});
$kernel = new AppKernel($env, $debug);
$application = new Application($kernel);
$application->setDispatcher($dispatcher);
$application->run($input);
after migration Symfony from 3.3 to 3.4, my function not working (it works before). I have to clear cache in controller, and when I execute command below, function returns error.
exec(sprintf(
"php %s/bin/console cache:clear --env=prod",
$this->getParameter('kernel.project_dir')
));
It returns something like that:
Fatal error: require(): Failed opening required '/[...]/var/cache/prod/ContainerAcrshql/getTwig_ExceptionListenerService.php' (include_path='.:/usr/local/share/pear') in /[...]/var/cache/prod/ContainerAcrshql/appProdProjectContainer.php on line 764 Fatal error: require(): Failed opening required '/[...]/var/cache/prod/ContainerAcrshql/getSwiftmailer_EmailSender_ListenerService.php' (include_path='.:/usr/local/share/pear') in /[...]/var/cache/prod/ContainerAcrshql/appProdProjectContainer.php on line 764
In addition I can tell You, that in dev environment it works properly. Also when project run localy and simulate prod env (in address bar I type app.php after localhost:8000). I haven't other server to check if problem still occured
I'm calling an already implemented Symfony's command that clear or warmup cache (tested on Symfony 4).
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\BufferedOutput;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\KernelInterface;
class CommandController extends AbstractController
{
/**
*
* #Route("/command/cache/clear", name="command_cache_clear")
*/
public function command_cache_clear(KernelInterface $kernel)
{
return $this->do_command($kernel, 'cache:clear');
}
/**
*
* #Route("/command/cache/warmup", name="command_cache_warmup")
*/
public function command_cache_warmup(KernelInterface $kernel)
{
return $this->do_command($kernel, 'cache:warmup');
}
private function do_command($kernel, $command)
{
$env = $kernel->getEnvironment();
$application = new Application($kernel);
$application->setAutoExit(false);
$input = new ArrayInput(array(
'command' => $command,
'--env' => $env
));
$output = new BufferedOutput();
$application->run($input, $output);
$content = $output->fetch();
return new Response($content);
}
}
You should add a valid permissions to the var/ directory to access to cache files:
chmod ... var/ -R
The user used when accessing from web is www-data
I am newbie in elasticsearch and somewhere in laravel also.. I am trying to configure elasticsearch with laravel . elasticsearch is running on 9200 port. When execute below code , it throws cURL error.I never configured 1080 port. Don't knw why it's trying to connect 1080 port ? How to change this port ?
code
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Elasticsearch\ClientBuilder;
use Elastica\Client as ElasticaClient;
class clientController extends Controller
{
protected $elasticsearch;
protected $elastica;
public function __construct()
{
$logger = ClientBuilder::defaultLogger('d:/your.log');
$this->elasticsearch = ClientBuilder::create()
->setLogger($logger)
->setRetries(0)
->build();
$elasticConfig=['host'=>"locahost",
"port"=>9200,
"index"=>'pets'];
$this->elastica = new ElasticaClient($elasticConfig);
}
public function elasticsearchTest(){
dump($this->elasticsearch);
// echo "\n\n Retrive Doc";
$param = [
'index' => 'pets',
'type' => 'dog',
'id'=>'1'
];
$res = $this->elasticsearch->get($param);
dump($res); exit;
}
}
I followed steps in this related question but this error appeared to me, Can you help please?
HttpException in HttpRequestEventSubscriber.php line 74: Error on
Connection "default" with message "cURL error 7: Failed to connect to
localhost port 7474: Connection refused (see
http://curl.haxx.se/libcurl/c/libcurl-errors.html)"
this is my .env code
`APP_ENV=local
APP_DEBUG=true
APP_KEY=ChTIcRHTSR35M6rP0jwmOmhMNLuFpMVe
NEO4J_HOST=localhost
NEO4J_PORT=7474
NEO4J_USER=neo4j
NEO4J_PASSWORD=admin
NEO4J_TIMEOUT=300
CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync
MAIL_DRIVER=smtp
MAIL_HOST=mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
`
this is NeoClientServiceProvider code
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Neoxygen\NeoClient\ClientBuilder;
class NeoClientServiceProvider extends ServiceProvider
{
/**
* Register the application services.
*
* #return void
*/
public function register()
{
$this->app->singleton('neoclient', function ($app) {
return ClientBuilder::create()
->addConnection('default', 'http', env('NEO4J_HOST'), intval(env('NEO4J_PORT')), true, env('NEO4J_USER'), env('NEO4J_PASSWORD'))
->setDefaultTimeout( intval(env('NEO4J_TIMEOUT')) )
->setAutoFormatResponse(true)
->build();
});
}
}
this is provider
App\Providers\NeoClientServiceProvider::class,
aliases
'NeoClient' => App\NeoClient::class
this is NeoClient class code
<?php namespace App;
use Illuminate\Support\Facades\Facade;
class NeoClient extends Facade
{
protected static function getFacadeAccessor() { return 'neoclient'; }
}
my test controller
<?php
namespace App\Http\Controllers;
use App\NeoClient;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class test extends Controller
{
public function index()
{
$data = NeoClient::sendCypherQuery('CREATE (user:User {name:"Kenneth"}) RETURN user');
}
}
when I made dump for this in function addConnection which is in ClientBuilder class
public function addConnection($alias, $scheme, $host, $port, $authMode = false, $authUser = null, $authPassword = null)
{
$this->configuration['connections'][$alias] = array(
'scheme' => $scheme,
'host' => $host,
'port' => $port,
'auth' => $authMode,
'user' => $authUser,
'password' => $authPassword,
);
dd($this);
return $this;
}
Ok. I installed Homestead to reproduce your environment. As told in the comments this should have been a host issue. I managed to make your connection to neo4j working :
ssh to homestead :
ssh vagrant#127.0.0.1 -p 2222
display the gateway ip of the vagrant box :
vagrant#homestead:~$ ip route show
default via 10.0.2.2 dev eth0
10.0.2.0/24 dev eth0 proto kernel scope link src 10.0.2.15
192.168.10.0/24 dev eth1 proto kernel scope link src 192.168.10.10
Here the host gateway is 10.0.2.2
Use the gateway as neo4j host :
$ curl --user neo4j:admin "http://10.0.2.2:7474/db/data/"
"extensions" : { },
"node" : "http://10.0.2.2:7474/db/data/node",
"node_index" : "http://10.0.2.2:7474/db/data/index/node",
"relationship_index" : "http://10.0.2.2:7474/db/data/index/relationship",
"extensions_info" : "http://10.0.2.2:7474/db/data/ext",
"relationship_types" : "http://10.0.2.2:7474/db/data/relationship/types",
"batch" : "http://10.0.2.2:7474/db/data/batch",
"cypher" : "http://10.0.2.2:7474/db/data/cypher",
"indexes" : "http://10.0.2.2:7474/db/data/schema/index",
"constraints" : "http://10.0.2.2:7474/db/data/schema/constraint",
"transaction" : "http://10.0.2.2:7474/db/data/transaction",
"node_labels" : "http://10.0.2.2:7474/db/data/labels",
"neo4j_version" : "3.0.0-alpha.163"