Skip to content

Instantly share code, notes, and snippets.

@timwhitlock
Created January 19, 2014 22:39
Show Gist options
  • Select an option

  • Save timwhitlock/8511971 to your computer and use it in GitHub Desktop.

Select an option

Save timwhitlock/8511971 to your computer and use it in GitHub Desktop.
Testing for Guzzle model structure.
<?php
use Guzzle\Http\Message\Response;
use Guzzle\Plugin\Mock\MockPlugin;
use Guzzle\Service\Client;
use Guzzle\Service\Description\ServiceDescription;
use Guzzle\Tests\GuzzleTestCase;
class ModelTest extends GuzzleTestCase {
public function testModel(){
// Define a service with a test() method
$service = ServiceDescription::factory( array(
'name' => 'test-service',
'operations' => array (
'test' => array (
'uri' => '/test.json',
'httpMethod' => 'GET',
'responseClass' => 'TestModel',
),
),
'models' => array (
'TestModel' => array (
'type' => 'object',
'properties' => array (
// property that will exist in response
'foo' => array (
'type' => 'integer',
'location' => 'json',
),
// property that won't exist in response
'bar' => array (
'type' => 'integer',
'location' => 'json',
'required' => true, // <- makes no difference
),
),
),
),
) );
$client = new Client;
$client->setDescription( $service );
// fake a response with valid "foo" and invalid "baz" properties
$plugin = new MockPlugin();
$plugin->addResponse( new Response( 200, array(), '{"foo":1,"baz":"nan"}' ) );
$client->addSubscriber( $plugin );
$response = $client->test();
// test value of "foo" key, which will exist
$this->assertEquals( 1, $response->get('foo') );
// test value of "bar" key which isn't in response
// Why doesn't the model complain this is missing in response?
$this->assertEquals( null, $response->get('bar') ); -
// test value of "baz" key, which isn't in model schema
// Why doesn't this fail if it's not valid?
$this->assertEquals( "nan", $response->get('baz') );
// test model structure is present
// Why is this empty?
$structure = $response->getStructure()->toArray();
$this->assertGreaterThan( 0, count($structure), 'Model structure is empty' );
}
}
@timwhitlock
Copy link
Author

@mtdowling
Copy link

Setting required to true on response models has not effect, and that's intentional.

Response models can pick up additional properties from the actual response because it assumes that additionalProperties is set to true by default. Set additionalProperties to false to disable this.

You need to opt-in to getting the original schema used to generate a response model. See: guzzle/guzzle@a909b0b

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment