How to test broadcast driver? - laravel

I am wondering if its possible to test ShouldBroadcast in Laravel?
My test will trigger the even that implements ShouldBroadcast, however, I've noticed that broadcasting didn't happen.
Of course, the broadcasting event is working in the app it self.
Has any one tried such test?

It's an old question, but just in case it can help someone : i did for myself an assert function that you should add to your TestCase.php.
The idea is to set the broadcast driver to "log" and then to read the 4th line from the end to see if it's a broadcast log.
In your phpunit.xml
Add the folowing line to the node:
<env name="BROADCAST_DRIVER" value="log"/>
In your TestCase.php file
Add the folowing function :
public function assertEventIsBroadcasted($eventClassName, $channel=""){
$logfileFullpath = storage_path("logs/laravel.log");
$logfile = explode("\n", file_get_contents($logfileFullpath));
if(count($logfile) > 4){
$supposedLastEventLogged = $logfile[count($logfile)-5];
$this->assertContains("Broadcasting [", $supposedLastEventLogged, "No broadcast were found.\n");
$this->assertContains("Broadcasting [".$eventClassName."]", $supposedLastEventLogged, "A broadcast was found, but not for the classname '".$eventClassName."'.\n");
if($channel != "")
$this->assertContains("Broadcasting [".$eventClassName."] on channels [".$channel."]", $supposedLastEventLogged, "The expected broadcast (".$eventClassName.") event was found, but not on the expected channel '".$channel."'.\n");
}else{
$this->fail("No informations found in the file log '".$logfileFullpath."'.");
}
}

Instead of checking what's written in log, you can to use the assertion 'expectsEvents', which you can test if a certain event is launched.
public function testMethod(){
$this->expectsEvents(YourEventClass::class)
...your code test...
}
For more info:
https://laravel-guide.readthedocs.io/en/latest/mocking/

with Adrienc solutions with dynamically getting index of last event
private function getIndexOfLoggedEvent(array $logfile)
{
for ($i = count($logfile) - 1; $i >=0 ; $i--) {
if (strpos($logfile[$i], 'Broadcasting [Illuminate\Notifications\Events\BroadcastNotificationCreated]') !== false) {
return $i;
}
}
}
which will give you index of the line of last broadcast

I took both previous answers, and put them together.
This works with laravel 5.7.
In your TestCase.php file:
public function assertEventIsBroadcasted($eventClassName, $channel = '')
{
$date = Carbon::now()->format('Y-m-d');
$logfileFullpath = storage_path("logs/laravel-{$date}.log");
$logfile = explode("\n", file_get_contents($logfileFullpath));
$indexOfLoggedEvent = $this->getIndexOfLoggedEvent($logfile);
if ($indexOfLoggedEvent) {
$supposedLastEventLogged = $logfile[$indexOfLoggedEvent];
$this->assertContains('Broadcasting [', $supposedLastEventLogged, "No broadcast were found.\n");
$this->assertContains(
'Broadcasting [' . $eventClassName . ']',
$supposedLastEventLogged,
"A broadcast was found, but not for the classname '" . $eventClassName . "'.\n"
);
if ($channel != '') {
$this->assertContains(
'Broadcasting [' . $eventClassName . '] on channels [' . $channel . ']',
$supposedLastEventLogged,
'The expected broadcast (' . $eventClassName . ") event was found, but not on the expected channel '" . $channel . "'.\n"
);
}
} else {
$this->fail("No informations found in the file log '" . $logfileFullpath . "'.");
}
}
private function getIndexOfLoggedEvent(array $logfile)
{
for ($i = count($logfile) - 1; $i >= 0; $i--) {
if (strpos($logfile[$i], 'local.INFO: Broadcasting') !== false) {
return $i;
}
}
return false;
}
A test could look like this:
/**
* #test
*/
public function notifications_are_broadcasted()
{
$notification = factory(Notification::class)->create();
broadcast(new NewNotification($notification));
$this->assertEventIsBroadcasted(
NewNotificationEvent::class,
'private-notification.' . $notification->id
);
}

Related

Stripe PHP Best way to debug an SignatureVerificationException with Stripe-cli

I created a webhook to get informations about checkout sessions :
public function stripeWebhookCheckout(Request $request)
{
\Stripe\Stripe::setApiKey(env("STRIPE_SECRET"));
// You can find your endpoint's secret in your webhook settings
$endpoint_secret = 'whsec_fVBkAmCztUTacQKZiyjmcq6QQrl8lKL1';
$payload = #file_get_contents('php://input');
$sig_header = $_SERVER['HTTP_STRIPE_SIGNATURE'];
$event = null;
try {
$event = \Stripe\Webhook::constructEvent(
$payload,
$sig_header,
$endpoint_secret
);
} catch (\UnexpectedValueException $e) {
// Invalid payload
http_response_code(400);
exit();
} catch (\Stripe\Exception\SignatureVerificationException $e) {
// Invalid signature
http_response_code(400);
exit();
}
// Handle the checkout.session.completed event
if ($event->type == 'checkout.session.completed') {
$session = $event->data->object;
// Fulfill the purchase...
handle_checkout_session($session);
$stripeSessionId = $session['id'];
if (isset($stripeSessionId)) {
$payment = Payment::where('stripe_sessioncheckout_id', '=', $stripeSessionId)->first();
$payment->status = "success";
$payment->data = $session;
$payment->save();
}
}
http_response_code(200);
}
I use stripe-cli to test my webhook in local. And i have this kind of result
$ stripe listen --forward-to jvlb.test/api/stripe/webhook/checkout
> Ready! Your webhook signing secret is whsec_sc9Gh9A6zx3IOfBpH62F9DdPYIhSUYtw (^C to quit)
2019-11-28 16:19:06 --> charge.succeeded [evt_1FjsW5FIYszmshR0eGSB9GDo]
2019-11-28 16:19:06 <-- [400] GET https://jvlb.test/api/stripe/webhook/checkout [evt_1FjsW5FIYszmshR0eGSB9GDo]
To debug it i changes the http_response_code(400) and I realised it generate a SignatureVerificationException.
My question is, how can i debug this ? Is it the $_SERVER['HTTP_STRIPE_SIGNATURE'] who is wrong ?
Thanks
i found a solution, if it can help people in the future :
I made a mistake in the way i use stripe-cli, i forgot "https://".
The good way is :
stripe listen --forward-to https://jvlb.test/api/stripe/webhook/checkout
And then i had few error of code to manage. I just used the tail command on my log file
tail -f storage/logs/laravel-2019-11-29.log

How to fix laravel migrate receiving "Curl error (code 3): <url> malformed"?

I just pulled some updates in a repository. Then when I use the command "php artisan migrate" it gives me an error. See the screenshot below.
How can I fix this?
Or what seems to be causing this?
Thank you!
Edit
Heres the code for Util.php. But I don't think I should be messing with it since it came from vendors directory.
<?php
namespace Monolog\Handler\Curl;
class Util
{
private static $retriableErrorCodes = array(
CURLE_COULDNT_RESOLVE_HOST,
CURLE_COULDNT_CONNECT,
CURLE_HTTP_NOT_FOUND,
CURLE_READ_ERROR,
CURLE_OPERATION_TIMEOUTED,
CURLE_HTTP_POST_ERROR,
CURLE_SSL_CONNECT_ERROR,
);
public static function execute($ch, $retries = 5, $closeAfterDone = true)
{
while ($retries--) {
if (curl_exec($ch) === false) {
$curlErrno = curl_errno($ch);
if (false === in_array($curlErrno, self::$retriableErrorCodes, true) || !$retries) {
$curlError = curl_error($ch);
if ($closeAfterDone) {
curl_close($ch);
}
throw new \RuntimeException(sprintf('Curl error (code %s): %s', $curlErrno, $curlError));
}
continue;
}
if ($closeAfterDone) {
curl_close($ch);
}
break;
}
}
}
Not a permanent fix, but rather than have this you can commented it out throw new \RuntimeException(sprintf('Curl error (code %d): %s', $curlErrno, $curlError)); and the I had return true;

New Caller Insert to Database with Codeigniter using the Twilio API

Below is the function to receive all incoming calls in my Controller
public function call_incoming()
{
$blocklist = $this->call_log_model->get_blocklist($_REQUEST['From']);
$tenantNum = $this->call_log_model->get_called_tenant($_REQUEST['From']);
$tenantInfoByNumber = $this->account_model->getTenantInfoByNumber($tenantNum->to_tenant);
$officeStatus = $this->check_office_hours($tenantInfoByNumber->start_office_hours, $tenantInfoByNumber->end_office_hours);
$calldisposition = $this->calldisp_model->get_call_disposition($tenantInfoByNumber->user_id);
$response = new Services_Twilio_Twiml;
if($blocklist == 0)
{
if($officeStatus == "open")
{
if($_POST['Called'] != AGENTPOOL_NUM)
{
$data = array(
'caller'=>$_REQUEST['From'],
'to_tenant'=>$_POST['Called'],
'date_created'=>date('Y-m-d H:i:s')
);
$this->call_log_model->insert_caller_to_tenant($data);
$dial = $response->dial(NULL, array('callerId' => $_REQUEST['From']));
$dial->number(AGENTPOOL_NUM);
print $response;
}
else
{
$gather = $response->gather(array('numDigits' => 1, 'action'=>HTTP_BASE_URL.'agent/call_controls/call_incoming_pressed', 'timeout'=>'5' , 'method'=>'POST'));
$ctr = 1;
foreach($calldisposition as $val )
{
$gather->say('To go to '.$val->disposition_name.', press '.$ctr, array('voice' => 'alice'));
$gather->pause("");
$ctr++;
}
print $response;
}
}
else
{
$response->say('Thank you for calling. Please be advise that our office hours is from '.$tenantInfoByNumber->start_office_hours.' to '.$tenantInfoByNumber->end_office_hours);
$response->hangup();
print $response;
}
}
else
{
$response->say('This number is blocked. Goodbye!');
$response->hangup();
print $response;
}
}
Please advise if I need to post the model...
Here is whats happening everytime an unknown number calls in, the caller will hear an application error has occurred error message and when checking the Twilio console the error it is giving me is
A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object
Filename: agent/Call_controls.php
Line Number: 357
Please be advised that this error only occurs when the caller is a number not in our database yet. When the call comes from a number already saved in our databse, this codes works...
Thank you for the help...
if($tenantNum) {
$tenantInfoByNumber = $this->account_model->getTenantInfoByNumber($tenantNum->to_t‌​enant);
} else {
$tenantInfoByNumber = ""; // fill this in with relevant fill data
}
This should fix your issue, as there is no TenantNum returned, there is no data, so make it yourself for unknown numbers.

use symfony form validator for Bulk-Insert

i receive an CSV File from the User and I want to insert it into the Database. I want to use the Form Validation:
$pf = new ProductForm();
$old_memory_usage = 0;
while($data = $csvreader->read())
{
$mem = memory_get_usage() / 1024;
echo "Memory-Usage: " . $mem . " KB; Mem-Diff: " . $mem - $old_memory_usage . "\n";
$old_memory_usage = $mem;
$p = new Product();
$p->fromArray($data);
$pf->bind($p->toArray(), array());
if($pf->isValid())
{
$p->save();
}
else
{
//display error message to the user
}
}
This works fine when isValid() returns true. The Memory Difference is 0 KB. But if there is an Error in the "form" the memory-difference is 6-7 KB. So I get an allowed_memory error when the CSV-File is very huge.
I tryed to free the form like:
unset($pf)
$pf = null;
$pf = new ProductForm();
no success. It is just worse!
ans ideas?
thx!
You can disable doctrine profiler in your databse yml:
dev:
doctrine:
class: sfDoctrineDatabase
param:
profiler: false

NuSOAP on XAMPP with PHP5: failed to open stream

Hey guys, I have a problem (again). This time I am trying to use NuSoap w/ XAMPP 1.7.1 which includes PHP5 and MySQL ... I wrote a soap-client:
<?php
// Pull in the NuSOAP code
require_once('nusoap.php');
// Create the client instance
$client = new soapclient('http://localhost/mysql/helloworld2.php');
// Check for an error
$err = $client->getError();
if ($err) {
// Display the error
echo '<p><b>Constructor error: ' . $err . '</b></p>';
// At this point, you know the call that follows will fail
}
// Call the SOAP method
$result = $client->call('hello', array('name' => 'Doro'));
// Check for a fault
if ($client->fault) {
echo '<p><b>Fault: ';
print_r($result);
echo '</b></p>';
} else {
// Check for errors
$err = $client->getError();
if ($err) {
// Display the error
echo '<p><b>Error: ' . $err . '</b></p>';
} else {
// Display the result
print_r($result);
}
}
?>
and my soap-server:
// Enable debugging *before* creating server instance
$debug = 1;
// Create the server instance
$server = new soap_server;
// Register the method to expose
$server->register('hello');
// Define the method as a PHP function
function hello($name) {
$dbhost = 'blah';
$dbuser = 'blub';
$dbpass = 'booboo';
try{
$conn = MYSQL_CONNECT($dbhost, $dbuser, $dbpass)
or die ('Error connecting to mysql');
if( !$conn ){
return 'Hello, '.$name.' ... too bad, I cannot connect to the db!';
}
else{
$dbname = 'soaperina';
MYSQL_SELECT_DB($dbname) or die('Error connecting to '.dbname);
$queryres = #mysql_db_query(
'response',
'SELECT * FROM farben');
return 'RESPONSE: <br>';
while( $arr = mysql_fetch_array( $queryres ) ){
return $arr["ID"]." - ".$arr["Farben"]." - ".$arr["Rating"]."<br>";
}
}
}
catch(Exception $e){
return 'Sorry, '.$name.', but that did not work at all!';
}
}
// Use the request to (try to) invoke the service
$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
$server->service($HTTP_RAW_POST_DATA);
?>
I know that PHP works, the Apache works, MySQL works ... it also works together, but when I try to make it work with NuSOAP it does not work. I get following:
Warning:
SoapClient::SoapClient(http://localhost/mysql/helloworld2.php)
[soapclient.soapclient]: failed to
open stream: Ein Verbindungsversuch
ist fehlgeschlagen, da die Gegenstelle
nach einer bestimmten Zeitspanne nicht
richtig reagiert hat, oder die
hergestellte Verbindung war
fehlerhaft, da der verbundene Host
nicht reagiert hat. in
C:\xampp\htdocs\mysql\helloworld2client.php
on line 6
Warning: SoapClient::SoapClient()
[soapclient.soapclient]: I/O warning :
failed to load external entity
"http://localhost/mysql/helloworld2.php"
in
C:\xampp\htdocs\mysql\helloworld2client.php
on line 6
Fatal error: Maximum execution time of
60 seconds exceeded in
C:\xampp\htdocs\mysql\helloworld2client.php
on line 41
I have no idea what that is supposed to mean. I hope ya'll can help!!! Thnx in advance :)
I used NuSOAP version 1.7.3 with PHP5. In this NuSOAP 1.7.3, soapclient class renamed by nu_soapclient.
You can try this:
$client = new nusoap_client('http://localhost/mysql/helloworld2.php');
to give an answer to my own question: nusoap has a problem with php5 ... there are some answers and some solutions on the net (not many), but they didn't work with me. I downgraded to php4 and it works fine ...

Resources