I am at a complete loss here...The two calls bellow are using the same service yet one works great the other fails...I was hoping another set of eyeballs might catch something I am doing wrong. On the google OAuth Playground they both seem to be working fine
!! CRASHES !!
//Googles Class
class Google_Service_Proximitybeacon_BeaconsDiagnostics_Resource extends Google_Service_Resource
{
public function listBeaconsDiagnostics($beaconName, $optParams = array())
{
$params = array('beaconName' => $beaconName);
$params = array_merge($params, $optParams);
return $this->call('list', array($params), "Google_Service_Proximitybeacon_ListDiagnosticsResponse");
}
}
//Service
$service = new Google_Service_Proximitybeacon($client);
//Call
$beaconName = 'beacons/3!f7826da64fa24e9880243rgenfgv43kgekfe';
$request = $service->diagnostics->listBeaconsDiagnostics($beaconName);
!! WORKS GREAT !!
//Googles Class
class Google_Service_Proximitybeacon_Namespaces_Resource extends Google_Service_Resource
{
public function listNamespaces($optParams = array())
{
$params = array();
$params = array_merge($params, $optParams);
return $this->call('list', array($params), "Google_Service_Proximitybeacon_ListNamespacesResponse");
}
}
//Service
$service = new Google_Service_Proximitybeacon($client);
//Call
$request = $service->namespaces->listNamespaces();
Fatal error: Uncaught Error: Call to a member function listBeaconsDiagnostics() on null in /home/xtractio/public_html/test4.php:121 Stack trace: #0 {main} thrown in /home/xtractio/public_html/test4.php on line 121
This is the fatal error I am receiving, just odd that both the calls above and other calls are pretty much identical but these two extended classes attachments/diagnostics seem to be causing the most issue.
Thanks in advance!
Related
I have a class I want to test that uses this module PHP HTTP client for Emarsys webservice, but when I try to test it, I will always get $response as "Credentials are invalid" from the module itself.
Here's a snippet of my code: (Given that I was able to correctly create my setUp() for Test Class since I was able to use it for other tests)
Test.php
Class TestClass extends UnitTestCase {
public function testCreateWithValidEmail() {
$newsletter = new Newsletter();
$form = new FormState();
$form->setValue('email', 'abc#def.ghi');
$response = $newsletter->register($form);
// Assertion here
}
}
Class.php
use Snowcap\Emarsys\CurlClient;
use Snowcap\Emarsys\Client;
Class Newsletter {
public function register(FormStateInterface $state){
$emailData = $state->getValue('email');
$httpClient = new CurlClient();
$client = new Client($httpClient, $api_username, $api_secret);
$someData = [
"3" => $emailData, // since 3 is the index ID for email
// ...more data here
];
$response = $client->createContact($someData);
}
}
Do I have to create a mock of something here to pass a dummy api and secret then force a valid response from createContact?
You are in the good direction. But that Newsletter class needs the $httpClient injected.
So you will be able to do:
$client = $this->getMockBuilder(Snowcap\Emarsys\CurlClient::class)
->disableOriginalConstructor()
->getMock();
$response = $this->getMockBuilder(ResponseInterface::class)
->disableOriginalConstructor()
->getMock();
$response->expects($this->any())
->method('getStatusCode')
->willReturn(Response::HTTP_OK);
$client->expects($this->any())
->method('createContact')
->with($someData)
->will($this->returnValue($response));
$newsletter = new Newsletter($client);
$response = $newsletter->register($form);
// Assertion here
I am relatively new to PHP, which might well prove to be the main problem here - I get the feeling I'm missing something somewhat fundamental about PHP internals that would either make solving this straightforward, or make it glaringly obvious why I am wasting my time!...
Basically in the following Slim API code I would like the exception handling added by the excellent entomb/slim-json-api middleware to also apply to the subsequent myMiddleware. As implemented below, it only seems to handle failures generated in the route code...
(PHP v 5.4.17)
$ php composer.phar info
entomb/slim-json-api dev-master c11e001 Slim extension to implement fast JSON API's
slim/slim 2.6.2 Slim Framework, a PHP micro framework
API code:
require 'vendor/autoload.php';
use Slim\Middleware;
class myMiddleware extends Middleware
{
public function call()
{
$uri_array = explode('/', $this->app->request->getResourceUri());
$env = $this->app->environment;
if($uri_array[2] == 98) {
throw new \Exception("User $uri_array[2], you are not even welcome in middleware!");
} else {
$body = array('user_from_middleware' => $uri_array[2]);
$env['slim.input'] = json_encode($body);
}
$this->next->call();
}
}
///////////////////////////////////////////////////////////////////////////////////
$app = new \Slim\Slim();
$app->view(new \JsonApiView());
$app->add(new \JsonApiMiddleware());
$app->add(new myMiddleware());
$app->get('/user/:id', function($id) use ($app) {
if ($id == 99) {
throw new \Exception("User $id, you are not welcome!");
} else {
$body = json_decode($app->request->getBody());
$body->msg = "User $id welcome to my API!";
$app->render(200,(array) $body);
}
});
Here's a request that misses both Exceptions:
$ curl http://localhost:8082/test.php/user/1
{"user_from_middleware":"1","msg":"User 1 welcome to my API!","error":false,"status":200}
...this one fires the Exception in route, showing that the JsonApiMiddleware is working:
$ curl http://localhost:8082/test.php/user/99
{"msg":"ERROR: User 99, you are not welcome!","error":true,"status":500}
...but when this one fires the Exception in myMiddleware the API returns nothing:
$ curl http://localhost:8082/test.php/user/98
$
...and I can see from the log that the exception was definitely thrown:
[Mon Nov 7 21:54:08 2016] PHP Fatal error: Uncaught exception 'Exception' with message 'User 98, you are not even welcome in middleware!' in /path/to/test.php:14
Stack trace:
#0 /path/to/vendor/slim/slim/Slim/Slim.php(1302): myMiddleware->call()
#1 /path/to/test.php(42): Slim\Slim->run()
#2 {main}
thrown in /path/to/test.php on line 14
What am I missing? Apologies again if this is a tedious question.
Probably you should not $this->next->call() in MyMiddlware if an exception is thrown?..
class myMiddleware extends Middleware
{
public function call()
{
$uri_array = explode('/', $this->app->request->getResourceUri());
$env = $this->app->environment;
if($uri_array[2] == 98) {
throw new \Exception("User $uri_array[2], you are not even welcome in middleware!");
} else {
$body = array('user_from_middleware' => $uri_array[2]);
$env['slim.input'] = json_encode($body);
$this->next->call(); // call next callable only if exception was not thrown
}
}
}
Seems like you're using Slim v 2., but this is what I'd do in Slim 3.5.*
I am trying to assign a value to a variable inside the first testing function and then use it in other testing functions inside the class.
right now in my code the second function fails due to this error:
1) ApiAdTest::testApiAd_postedAdCreated
GuzzleHttp\Exception\ClientException: Client error: 404
and i dont know why. this is how the code looks like:
class ApiAdTest extends PHPUnit_Framework_TestCase
{
protected $adId;
private static $base_url = 'http://10.0.0.38/adserver/src/public/';
private static $path = 'api/ad/';
//start of expected flow
public function testApiAd_postAd()
{
$client = new Client(['base_uri' => self::$base_url]);
$response = $client->post(self::$path, ['form_params' => [
'name' => 'bellow content - guzzle testing'
]]);
$data = json_decode($response->getBody());
$this->adId = $data->id;
$code = $response->getStatusCode();
$this->assertEquals($code, 200);
}
public function testApiAd_postedAdCreated()
{
$client = new Client(['base_uri' => self::$base_url]);
$response = $client->get(self::$path.$this->adId);
$code = $response->getStatusCode();
$data = json_decode($response->getBody());
$this->assertEquals($code, 200);
$this->assertEquals($data->id, $this->adId);
$this->assertEquals($data->name, 'bellow content - guzzle testing');
}
in the phpunit doumintation https://phpunit.de/manual/current/en/fixtures.html i see i can define a
a variable inside the setUp method and then use it as i want but in my case i only know the value after the first post executes. any idea how can i use $this->adId in the second function??
Unit tests by definition should not rely on one another. You will end up with unstable and fragile tests which are then hard to debug the moment they start failing, since the cause is in another test case.
There is no guarantee in which order the tests execute in PHPUnit by default.
PHPUnit supports the #depends annotation to achieve what you want, the docs have the same warning though.
I'm writing unit tests for my application. I wrote a function to login different user (to test user levels) and a function to generate valid or invalid form data (to test my form handling).
When the test submits a form, it throws an exception:
Uncaught PHP Exception LogicException: "Cannot set session ID after the session has started."
I'm using Symfony 2.6.4. I can't find any usefull information about this error message. The test worked perfectly a while ago.
class ControllerTest extends WebTestCase
{
public $client = null;
public $route = 'home/';
/**
* #var \Doctrine\ORM\EntityManager
*/
public $em;
public function setUp()
{
self::bootKernel();
$this->client = static::createClient();
$this->em = static::$kernel->getContainer()
->get('doctrine')
->getManager()
;
}
public function logIn($role = 'admin')
{
if ($role === 'admin') {
$userId = 20;
} elseif ($role === 'user') {
$userId = 29;
}
$user = $this->em->getRepository('Acme\DemoBundle\Entity\User')->find($userId);
$session = $this->client->getContainer()->get('session');
$firewall = 'main';
$token = new UsernamePasswordToken($user, $user->getPassword(), $firewall);
$session->set('_security_'.$firewall, serialize($token));
$session->save();
$cookie = new Cookie($session->getName(), $session->getId());
$this->client->getCookieJar()->set($cookie);
}
public function getFormData($valid = true)
{
//function to generate (in)valid formdata
}
public function getFormRequest($data, $url)
{
return $this->client->request(
'POST',
$url,
$data,
[],
[
'CONTENT_TYPE' => 'application/json',
'HTTP_X-Requested-With' => 'XMLHttpRequest',
]
);
}
//works OK
public function testNewScenario()
{
$url = $this->baseurl . 'new';
$this->logIn('admin');
$crawler = $this->client->request('GET', $url);
$this->assertEquals(200, $this->client->getResponse()->getStatusCode(), "Unexpected HTTP status code for GET " . $url);
}
public function testValidNewScenario()
{
$this->logIn('admin');
$validData = $this->getFormData(true);
//this function throws the exception
$this->getFormRequest($validData, $this->baseurl);
$this->assertEquals(200, $this->client->getResponse()->getStatusCode(), "Unexpected HTTP status code for POST " . $this->baseurl);
}
}
Here's the relevant part of my config_test.yml:
framework:
test: ~
session:
storage_id: session.storage.mock_file
profiler:
collect: false
What's going on?
I don't know if this is still a problem for the OP as this is an old post, but the same issue had me running around in circles for best part of 3 hours trying to find a way out of it. And seeing as there doesnt seem to be a solution anywhere at all. Heres a possible one.
The problem exists in tests which are trying to create a full login.
Current symfony docs state that its preferred to use basic_http authentication in your tests, but if, like me, you need to be testing access levels youll need to be following this method.
The problem seems to occur when we try to set the cookieJar up. This (for me) always threw an error.
Cannot set session ID after the session has started
the solution as it turns out is reasonably simple. Wrap the cookie set code in a condition that checks for a current session id.
if( !$this->session->getId() ) {
$this->cookie = new Cookie( $this->session->getName(), $this->session->getId() );
$this->client->getCookieJar()->set( $this->cookie ); // <--- this is the problem line
}
its also worth noting that calling $this->session->invalidate() does not solve the issue.
I hope this helps someone and saves them some time.
This effected me on Symfony2.1 (no chance of upgrading), but Ive seen mentions of 2.6 getting it when combined with FOSFacebookBundle (where I believe the issue was fixed).
I want to test my application. Everything works fine to the point where i want to test my own viewHelpers (actionHelpers).
The problem is, i want to use the url-ViewHelper in my own viewHelper to generate links.
Therefore i use this statements.
$urlHelper = $serviceLocator->getServiceLocator()->get('ViewHelperManager')->get('url');
$urlHelper->__invoke('test',array(),array(),true);
This works great.
But now i want to test parts of my application where my view helper is used. Everything works fine to the point where i use the url_ViewHelper.
I get following exception:
Fatal error: Call to a member function getRouteMatch() on a non-object in ****\vendor\zendframework\zendframework\library\Zend\Mvc\Service\ViewHelperManagerFactory.php on line 70
Is there something wrong in the way i setUp my test?
$serviceManager = Bootstrap::getServiceManager();
$this->controller = new IndexController();
$this->request = new Request();
$this->routeMatch = new RouteMatch(array('controller' => 'index'));
$this->event = new MvcEvent();
$config = $serviceManager->get('Config');
$routerConfig = isset($config['router']) ? $config['router'] : array();
$router = HttpRouter::factory($routerConfig);
$this->event->setRouter($router);
$this->event->setRouteMatch($this->routeMatch);
$this->controller->setEvent($this->event);
$this->controller->setServiceLocator($serviceManager);
Thank you very much for help!