Copy tests from "samples/client/petstore/php"

This commit is contained in:
akihito.nakano 2018-03-29 19:46:18 +09:00
parent a3c28adaef
commit a6af75f99e
21 changed files with 1505 additions and 0 deletions

View File

@ -0,0 +1,85 @@
<?php
namespace Swagger\Client;
use Swagger\Client\Api\PetApi;
use Swagger\Client\Model\Pet;
class AsyncTest extends \PHPUnit_Framework_TestCase
{
/** @var PetApi */
private $api;
/** @var int */
private $petId;
public function setUp()
{
$this->api = new Api\PetApi();
$this->petId = 10005;
$pet = new Model\Pet;
$pet->setId($this->petId);
$pet->setName("PHP Unit Test");
$pet->setPhotoUrls(array("http://test_php_unit_test.com"));
// new tag
$tag= new Model\Tag;
$tag->setId($this->petId); // use the same id as pet
$tag->setName("test php tag");
// new category
$category = new Model\Category;
$category->setId($this->petId); // use the same id as pet
$category->setName("test php category");
$pet->setTags(array($tag));
$pet->setCategory($category);
$pet_api = new Api\PetApi();
// add a new pet (model)
$add_response = $pet_api->addPet($pet);
}
public function testAsyncRequest()
{
$promise = $this->api->getPetByIdAsync(10005);
$promise2 = $this->api->getPetByIdAsync(10005);
$pet = $promise->wait();
$pet2 = $promise2->wait();
$this->assertInstanceOf(Pet::class, $pet);
$this->assertInstanceOf(Pet::class, $pet2);
}
public function testAsyncRequestWithHttpInfo()
{
$promise = $this->api->getPetByIdAsyncWithHttpInfo($this->petId);
list($pet, $status, $headers) = $promise->wait();
$this->assertEquals(200, $status);
$this->assertInternalType('array', $headers);
$this->assertInstanceOf(Pet::class, $pet);
}
public function testAsyncThrowingException()
{
$this->setExpectedException(ApiException::class);
$promise = $this->api->getPetByIdAsync(0);
$promise->wait();
}
public function testAsyncApiExceptionWithoutWaitIsNotThrown()
{
$promise = $this->api->getPetByIdAsync(0);
sleep(1);
}
public function testAsyncHttpInfoThrowingException()
{
$this->setExpectedException(ApiException::class);
$promise = $this->api->getPetByIdAsyncWithHttpInfo(0);
$promise->wait();
}
}

View File

@ -0,0 +1,62 @@
<?php
namespace Swagger\Client;
use Swagger\Client\Api\FakeApi;
use Swagger\Client\Api\PetApi;
use Swagger\Client\Model\Pet;
require_once __DIR__ . '/FakeHttpClient.php';
class AuthTest extends \PHPUnit_Framework_TestCase
{
public function testCustomApiKeyHeader()
{
$authConfig = new Configuration();
$authConfig->setApiKey('api_key', '123qwe');
$fakeHttpClient = new FakeHttpClient();
$api = new PetApi($fakeHttpClient, $authConfig);
$api->getPetById(123);
$headers = $fakeHttpClient->getLastRequest()->getHeaders();
$this->assertArrayHasKey('api_key', $headers);
$this->assertEquals(['123qwe'], $headers['api_key']);
}
public function testApiToken()
{
$authConfig = new Configuration();
$authConfig->setAccessToken('asd123');
$fakeHttpClient = new FakeHttpClient();
$api = new PetApi($fakeHttpClient, $authConfig);
$api->addPet(new Pet());
$headers = $fakeHttpClient->getLastRequest()->getHeaders();
$this->assertArrayHasKey('Authorization', $headers);
$this->assertEquals(['Bearer asd123'], $headers['Authorization']);
}
public function testBasicAuth()
{
$username = 'user';
$password = 'password';
$authConfig = new Configuration();
$authConfig->setUsername($username);
$authConfig->setPassword($password);
$fakeHttpClient = new FakeHttpClient();
$api = new FakeApi($fakeHttpClient, $authConfig);
$api->testEndpointParameters(123, 100.1, 'ASD_', 'ASD');
$headers = $fakeHttpClient->getLastRequest()->getHeaders();
$this->assertArrayHasKey('Authorization', $headers);
$encodedCredentials = base64_encode("$username:$password");
$this->assertEquals(["Basic $encodedCredentials"], $headers['Authorization']);
}
}

View File

@ -0,0 +1,34 @@
<?php
namespace Swagger\Client;
use Swagger\Client\Model\FormatTest;
class DateTimeSerializerTest extends \PHPUnit_Framework_TestCase
{
public function testDateTimeSanitazion()
{
$dateTime = new \DateTime('April 30, 1973 17:05 CEST');
$input = new FormatTest([
'date_time' => $dateTime,
]);
$data = ObjectSerializer::sanitizeForSerialization($input);
$this->assertEquals($data->dateTime, '1973-04-30T17:05:00+02:00');
}
public function testDateSanitazion()
{
$dateTime = new \DateTime('April 30, 1973 17:05 CEST');
$input = new FormatTest([
'date' => $dateTime,
]);
$data = ObjectSerializer::sanitizeForSerialization($input);
$this->assertEquals($data->date, '1973-04-30');
}
}

View File

@ -0,0 +1,26 @@
<?php
namespace Swagger\Client;
class DebugTest extends \PHPUnit_Framework_TestCase
{
public function testEnableDebugOutput()
{
$this->expectOutputRegex('#GET /v2/pet/1 HTTP/1.1#');
$config = new Configuration();
$config->setDebug(true);
$api = new Api\PetApi(null, $config);
$api->getPetById(1);
}
public function testEnableDebugOutputAsync()
{
$this->expectOutputRegex('#GET /v2/pet/1 HTTP/1.1#');
$config = new Configuration();
$config->setDebug(true);
$api = new Api\PetApi(null, $config);
$promise = $api->getPetByIdAsync(1);
$promise->wait();
}
}

View File

@ -0,0 +1,15 @@
<?php
namespace Swagger\Client;
use Swagger\Client\Model\EnumClass;
class EnumClassTest extends \PHPUnit_Framework_TestCase
{
public function testPossibleValues()
{
$this->assertSame(EnumClass::ABC, '_abc');
$this->assertSame(EnumClass::EFG, '-efg');
$this->assertSame(EnumClass::XYZ, '(xyz)');
}
}

View File

@ -0,0 +1,34 @@
<?php
namespace Swagger\Client;
use Swagger\Client\Model\EnumTest;
class EnumTestTest extends \PHPUnit_Framework_TestCase
{
public function testPossibleValues()
{
$this->assertSame(EnumTest::ENUM_STRING_UPPER, "UPPER");
$this->assertSame(EnumTest::ENUM_STRING_LOWER, "lower");
$this->assertSame(EnumTest::ENUM_INTEGER_1, 1);
$this->assertSame(EnumTest::ENUM_INTEGER_MINUS_1, -1);
$this->assertSame(EnumTest::ENUM_NUMBER_1_DOT_1, 1.1);
$this->assertSame(EnumTest::ENUM_NUMBER_MINUS_1_DOT_2, -1.2);
}
public function testNonRequiredPropertyIsOptional()
{
$enum = new EnumTest([
'enum_string_required' => 'UPPER',
]);
$this->assertSame([], $enum->listInvalidProperties());
$this->assertTrue($enum->valid());
}
public function testRequiredProperty()
{
$enum = new EnumTest();
$this->assertSame(["'enum_string_required' can't be null"], $enum->listInvalidProperties());
$this->assertFalse($enum->valid());
}
}

View File

@ -0,0 +1,41 @@
<?php
namespace Swagger\Client;
use GuzzleHttp\Client;
class ExceptionTest extends \PHPUnit_Framework_TestCase
{
/**
* @expectedException \Swagger\Client\ApiException
* @expectedExceptionCode 404
* @expectedExceptionMessage http://petstore.swagger.io/INVALID_URL/store/inventory
*/
public function testNotFound()
{
$config = new Configuration();
$config->setHost('http://petstore.swagger.io/INVALID_URL');
$api = new Api\StoreApi(
new Client(),
$config
);
$api->getInventory();
}
/**
* @expectedException \Swagger\Client\ApiException
* @expectedExceptionMessage Could not resolve host
*/
public function testWrongHost()
{
$config = new Configuration();
$config->setHost('http://wrong_host.zxc');
$api = new Api\StoreApi(
new Client(),
$config
);
$api->getInventory();
}
}

View File

@ -0,0 +1,69 @@
<?php
namespace Swagger\Client;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Psr7\Response;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
class FakeHttpClient implements ClientInterface
{
/** @var RequestInterface|null */
private $request;
/** @var ResponseInterface|null */
private $response;
/**
* @return null|RequestInterface
*/
public function getLastRequest()
{
return $this->request;
}
/**
* @param null|ResponseInterface $response
*/
public function setResponse(ResponseInterface $response = null)
{
$this->response = $response;
}
/**
* Send an HTTP request.
*
* @param RequestInterface $request Request to send
* @param array $options Request options to apply to the given
* request and to the transfer.
*
* @return ResponseInterface
* @throws GuzzleException
*/
public function send(RequestInterface $request, array $options = [])
{
$this->request = $request;
return $this->response ?: new Response(200);
}
public function sendAsync(RequestInterface $request, array $options = [])
{
throw new \RuntimeException('not implemented');
}
public function request($method, $uri, array $options = [])
{
throw new \RuntimeException('not implemented');
}
public function requestAsync($method, $uri, array $options = [])
{
throw new \RuntimeException('not implemented');
}
public function getConfig($option = null)
{
throw new \RuntimeException('not implemented');
}
}

View File

@ -0,0 +1,56 @@
<?php
namespace Swagger\Client;
class HeaderSelectorTest extends \PHPUnit_Framework_TestCase
{
public function testSelectingHeaders()
{
$selector = new HeaderSelector();
$headers = $selector->selectHeaders([
'application/xml',
'application/json'
], []);
$this->assertSame('application/json', $headers['Accept']);
$headers = $selector->selectHeaders([], []);
$this->assertArrayNotHasKey('Accept', $headers);
$header = $selector->selectHeaders([
'application/yaml',
'application/xml'
], []);
$this->assertSame('application/yaml,application/xml', $header['Accept']);
// test selectHeaderContentType
$headers = $selector->selectHeaders([], [
'application/xml',
'application/json'
]);
$this->assertSame('application/json', $headers['Content-Type']);
$headers = $selector->selectHeaders([], []);
$this->assertSame('application/json', $headers['Content-Type']);
$headers = $selector->selectHeaders([], [
'application/yaml',
'application/xml'
]);
$this->assertSame('application/yaml,application/xml', $headers['Content-Type']);
}
public function testSelectingHeadersForMultipartBody()
{
// test selectHeaderAccept
$selector = new HeaderSelector();
$headers = $selector->selectHeadersForMultipart([
'application/xml',
'application/json'
]);
$this->assertSame('application/json', $headers['Accept']);
$this->assertArrayNotHasKey('Content-Type', $headers);
$headers = $selector->selectHeadersForMultipart([]);
$this->assertArrayNotHasKey('Accept', $headers);
$this->assertArrayNotHasKey('Content-Type', $headers);
}
}

View File

@ -0,0 +1,31 @@
<?php
namespace Swagger\Client;
require_once __DIR__ . '/FakeHttpClient.php';
class HeadersTest extends \PHPUnit_Framework_TestCase
{
/** @var FakeHttpClient */
private $fakeHttpClient;
public function setUp()
{
$this->fakeHttpClient = new FakeHttpClient();
}
public function testUserAgent()
{
$config = new Configuration();
$config->setUserAgent('value');
$api = new Api\PetApi($this->fakeHttpClient, $config);
$api->getPetById(3);
$request = $this->fakeHttpClient->getLastRequest();
$headers = $request->getHeaders();
$this->assertArrayHasKey('User-Agent', $headers);
$this->assertEquals(['value'], $headers['User-Agent']);
}
}

View File

@ -0,0 +1,96 @@
<?php
namespace Swagger\Client;
use Swagger\Client\Model\Animal;
use Swagger\Client\Model\AnimalFarm;
use Swagger\Client\Model\Cat;
use Swagger\Client\Model\Dog;
/**
* Test that Dog properly inherit Animal
*
* @package Swagger\Client
*/
class ModelInheritanceTest extends \PHPUnit_Framework_TestCase
{
/**
* test if default values works
*/
public function testDefaultValues()
{
// add some animals to the farm to make sure the ArrayAccess
// interface works
$dog = new Dog();
$animal = new Animal();
// assert we can look up the animals in the farm by array
// indices (let's try a random order)
$this->assertSame('red', $dog->getColor());
$this->assertSame('red', $animal->getColor());
}
/**
* test inheritance in the model
*/
public function testInheritance()
{
$newDog = new Dog;
// the object should be an instance of the derived class
$this->assertInstanceOf(Dog::class, $newDog);
// the object should also be an instance of the parent class
$this->assertInstanceOf(Animal::class, $newDog);
}
/**
* test inheritance constructor is working with data initialization
*/
public function testInheritanceConstructorDataInitialization()
{
// initialize the object with data in the constructor
$data = [
'class_name' => 'Dog',
'breed' => 'Great Dane',
];
$newDog = new Dog($data);
// the property on the derived class should be set
$this->assertSame('Great Dane', $newDog->getBreed());
// the property on the parent class should be set
$this->assertSame('Dog', $newDog->getClassName());
}
/**
* test if discriminator is initialized automatically
*/
public function testDiscriminatorInitialization()
{
$newDog = new Dog();
$this->assertSame('Dog', $newDog->getClassName());
}
/**
* test if ArrayAccess interface works
*/
public function testArrayStuff()
{
// create an AnimalFarm which is an object implementing the ArrayAccess interface
$farm = new AnimalFarm();
// add some animals to the farm to make sure the ArrayAccess interface works
$farm[] = new Dog();
$farm[] = new Cat();
$farm[] = new Animal();
// assert we can look up the animals in the farm by array indices (let's try a random order)
$this->assertInstanceOf(Cat::class, $farm[1]);
$this->assertInstanceOf(Dog::class, $farm[0]);
$this->assertInstanceOf(Animal::class, $farm[2]);
// let's try to `foreach` the animals in the farm and let's try to use the objects we loop through
foreach ($farm as $animal) {
$this->assertContains($animal->getClassName(), ['Dog', 'Cat', 'Animal']);
$this->assertInstanceOf('Swagger\Client\Model\Animal', $animal);
}
}
}

View File

@ -0,0 +1,25 @@
<?php
namespace Swagger\Client;
// test object serializer
class ObjectSerializerTest extends \PHPUnit_Framework_TestCase
{
// test sanitizeFilename
public function testSanitizeFilename()
{
// initialize the API client
$s = new ObjectSerializer();
$this->assertSame("sun.gif", $s->sanitizeFilename("sun.gif"));
$this->assertSame("sun.gif", $s->sanitizeFilename("../sun.gif"));
$this->assertSame("sun.gif", $s->sanitizeFilename("/var/tmp/sun.gif"));
$this->assertSame("sun.gif", $s->sanitizeFilename("./sun.gif"));
$this->assertSame("sun", $s->sanitizeFilename("sun"));
$this->assertSame("sun.gif", $s->sanitizeFilename("..\sun.gif"));
$this->assertSame("sun.gif", $s->sanitizeFilename("\var\tmp\sun.gif"));
$this->assertSame("sun.gif", $s->sanitizeFilename("c:\var\tmp\sun.gif"));
$this->assertSame("sun.gif", $s->sanitizeFilename(".\sun.gif"));
}
}

View File

@ -0,0 +1,133 @@
<?php
namespace Swagger\Client;
class OrderApiTest extends \PHPUnit_Framework_TestCase
{
// add a new pet (id 10005) to ensure the pet object is available for all the tests
public static function setUpBeforeClass()
{
// for error reporting (need to run with php5.3 to get no warning)
//ini_set('display_errors', 1);
//error_reporting(~0);
}
// test get inventory
public function testOrderEnum()
{
$this->assertSame(Model\Order::STATUS_PLACED, "placed");
$this->assertSame(Model\Order::STATUS_APPROVED, "approved");
}
// test get inventory
public function testOrder()
{
// initialize the API client
$order = new Model\Order();
$order->setStatus("placed");
$this->assertSame("placed", $order->getStatus());
}
/**
* @expectedException InvalidArgumentException
*/
public function testOrderException()
{
// initialize the API client
$order = new Model\Order();
$order->setStatus("invalid_value");
}
// test deseralization of order
public function testDeserializationOfOrder()
{
$order_json = <<<ORDER
{
"id": 10,
"petId": 20,
"quantity": 30,
"shipDate": "2015-08-22T07:13:36.613Z",
"status": "placed",
"complete": false
}
ORDER;
$order = ObjectSerializer::deserialize(
json_decode($order_json),
'Swagger\Client\Model\Order'
);
$this->assertInstanceOf('Swagger\Client\Model\Order', $order);
$this->assertSame(10, $order->getId());
$this->assertSame(20, $order->getPetId());
$this->assertSame(30, $order->getQuantity());
$this->assertTrue(new \DateTime("2015-08-22T07:13:36.613Z") == $order->getShipDate());
$this->assertSame("placed", $order->getStatus());
$this->assertSame(false, $order->getComplete());
}
// test deseralization of array of array of order
public function testDeserializationOfArrayOfArrayOfOrder()
{
$order_json = <<<ORDER
[[{
"id": 10,
"petId": 20,
"quantity": 30,
"shipDate": "2015-08-22T07:13:36.613Z",
"status": "placed",
"complete": false
}]]
ORDER;
$order = ObjectSerializer::deserialize(
json_decode($order_json),
'Swagger\Client\Model\Order[][]'
);
$this->assertArrayHasKey(0, $order);
$this->assertArrayHasKey(0, $order[0]);
$_order = $order[0][0];
$this->assertInstanceOf('Swagger\Client\Model\Order', $_order);
$this->assertSame(10, $_order->getId());
$this->assertSame(20, $_order->getPetId());
$this->assertSame(30, $_order->getQuantity());
$this->assertTrue(new \DateTime("2015-08-22T07:13:36.613Z") == $_order->getShipDate());
$this->assertSame("placed", $_order->getStatus());
$this->assertSame(false, $_order->getComplete());
}
// test deseralization of map of map of order
public function testDeserializationOfMapOfMapOfOrder()
{
$order_json = <<<ORDER
{
"test": {
"test2": {
"id": 10,
"petId": 20,
"quantity": 30,
"shipDate": "2015-08-22T07:13:36.613Z",
"status": "placed",
"complete": false
}
}
}
ORDER;
$order = ObjectSerializer::deserialize(
json_decode($order_json),
'map[string,map[string,\Swagger\Client\Model\Order]]'
);
$this->assertArrayHasKey('test', $order);
$this->assertArrayHasKey('test2', $order['test']);
$_order = $order['test']['test2'];
$this->assertInstanceOf('Swagger\Client\Model\Order', $_order);
$this->assertSame(10, $_order->getId());
$this->assertSame(20, $_order->getPetId());
$this->assertSame(30, $_order->getQuantity());
$this->assertTrue(new \DateTime("2015-08-22T07:13:36.613Z") == $_order->getShipDate());
$this->assertSame("placed", $_order->getStatus());
$this->assertSame(false, $_order->getComplete());
}
}

View File

@ -0,0 +1,94 @@
<?php
namespace Swagger\Client;
use Swagger\Client\Model\EnumTest;
use Swagger\Client\Model\OuterEnum;
class OuterEnumTest extends \PHPUnit_Framework_TestCase
{
public function testDeserialize()
{
$result = ObjectSerializer::deserialize(
"placed",
OuterEnum::class
);
$this->assertInternalType('string', $result);
$this->assertEquals('placed', $result);
}
public function testDeserializeInvalidValue()
{
$this->setExpectedException(\InvalidArgumentException::class, 'Invalid value for enum');
ObjectSerializer::deserialize(
"lkjfalgkdfjg",
OuterEnum::class
);
}
public function testDeserializeNested()
{
$json = '{
"enum_string": "UPPER",
"enum_integer": -1,
"enum_number": -1.2,
"outerEnum": "approved"
}';
/** * @var EnumTest $result */
$result = ObjectSerializer::deserialize(
json_decode($json),
EnumTest::class
);
$this->assertInstanceOf(EnumTest::class, $result);
$this->assertEquals('approved', $result->getOuterEnum());
}
public function testSanitize()
{
$json = "placed";
$result = ObjectSerializer::sanitizeForSerialization(
$json
);
$this->assertInternalType('string', $result);
}
public function testSanitizeNested()
{
$input = new EnumTest([
'enum_string' => 'UPPER',
'enum_integer' => -1,
'enum_number' => -1.2,
'outer_enum' => 'approved'
]);
$result = ObjectSerializer::sanitizeForSerialization(
$input
);
$this->assertInternalType('object', $result);
$this->assertInstanceOf(\stdClass::class, $result);
$this->assertInternalType('string', $result->outerEnum);
$this->assertEquals('approved', $result->outerEnum);
}
public function testSanitizeNestedInvalidValue()
{
$this->setExpectedException(\InvalidArgumentException::class, 'Invalid value for enum');
$input = new EnumTest([
'enum_string' => 'UPPER',
'enum_integer' => -1,
'enum_number' => -1.2,
'outer_enum' => 'invalid_value'
]);
ObjectSerializer::sanitizeForSerialization($input);
}
}

View File

@ -0,0 +1,65 @@
<?php
namespace Swagger\Client;
use Swagger\Client\Api\FakeApi;
use Swagger\Client\Api\UserApi;
require_once __DIR__ . '/FakeHttpClient.php';
class ParametersTest extends \PHPUnit_Framework_TestCase
{
/** @var FakeHttpClient */
private $fakeHttpClient;
/** @var FakeApi */
private $fakeApi;
/** @var UserApi */
private $userApi;
public function setUp()
{
$this->fakeHttpClient = new FakeHttpClient();
$this->fakeApi = new Api\FakeApi($this->fakeHttpClient);
$this->userApi = new Api\UserApi($this->fakeHttpClient);
}
public function testHeaderParam()
{
$this->fakeApi->testEnumParameters([], [], [], 'something');
$request = $this->fakeHttpClient->getLastRequest();
$headers = $request->getHeaders();
$this->assertArrayHasKey('enum_header_string', $headers);
$this->assertEquals(['something'], $headers['enum_header_string']);
}
public function testHeaderParamCollection()
{
$this->fakeApi->testEnumParameters([], [], ['string1', 'string2']);
$request = $this->fakeHttpClient->getLastRequest();
$headers = $request->getHeaders();
$this->assertArrayHasKey('enum_header_string_array', $headers);
$this->assertEquals(['string1,string2'], $headers['enum_header_string_array']);
}
public function testInlineAdditionalProperties()
{
$param = new \stdClass();
$param->foo = 'bar';
$this->fakeApi->testInlineAdditionalProperties($param);
$request = $this->fakeHttpClient->getLastRequest();
$this->assertSame('{"foo":"bar"}', $request->getBody()->getContents());
}
// missing example for collection path param in config
// public function testPathParamCollection()
// {
// $this->userApi->getUserByNameWithHttpInfo(['aa', 'bb']);
// $request = $this->fakeHttpClient->getLastRequest();
// $this->assertEquals('user/aa,bb', urldecode($request->getUri()->getPath()));
// }
}

View File

@ -0,0 +1,404 @@
<?php
namespace Swagger\Client;
use Swagger\Client\Api\PetApi;
use Swagger\Client\Model\ApiResponse;
use Swagger\Client\Model\Pet;
class PetApiTest extends \PHPUnit_Framework_TestCase
{
/** @var PetApi */
private $api;
// add a new pet (id 10005) to ensure the pet object is available for all the tests
public static function setUpBeforeClass()
{
// increase memory limit to avoid fatal error due to findPetByStatus
// returning a lot of data
ini_set('memory_limit', '256M');
// enable debugging
//Configuration::$debug = true;
// new pet
$newPetId = 10005;
$newPet = new Model\Pet;
$newPet->setId($newPetId);
$newPet->setName("PHP Unit Test");
$newPet->setPhotoUrls(["http://test_php_unit_test.com"]);
// new tag
$tag = new Model\Tag;
$tag->setId($newPetId); // use the same id as pet
$tag->setName("test php tag");
// new category
$category = new Model\Category;
$category->setId($newPetId); // use the same id as pet
$category->setName("test php category");
$newPet->setTags(array($tag));
$newPet->setCategory($category);
$config = new Configuration();
$petApi = new Api\PetApi(null, $config);
// add a new pet (model)
list(, $status) = $petApi->addPetWithHttpInfo($newPet);
\PHPUnit_Framework_Assert::assertEquals(200, $status);
}
public function setUp()
{
$this->api = new Api\PetApi();
}
public function testGetPetById()
{
$petId = 10005;
$pet = $this->api->getPetById($petId);
$this->assertSame($pet->getId(), $petId);
$this->assertSame($pet->getName(), 'PHP Unit Test');
$this->assertSame($pet->getPhotoUrls()[0], 'http://test_php_unit_test.com');
$this->assertSame($pet->getCategory()->getId(), $petId);
$this->assertSame($pet->getCategory()->getName(), 'test php category');
$this->assertSame($pet->getTags()[0]->getId(), $petId);
$this->assertSame($pet->getTags()[0]->getName(), 'test php tag');
}
/**
* comment out as we've removed invalid endpoints from the spec, we'll introduce something
* similar in the future when we've time to update the petstore server
*
* // test getPetById with a Pet object (id 10005)
* public function testGetPetByIdInObject()
* {
* // initialize the API client without host
* $pet_id = 10005; // ID of pet that needs to be fetched
* $pet_api = new Api\PetApi();
* $pet_api->getApiClient()->getConfig()->setApiKey('api_key', '111222333444555');
* // return Pet (inline model)
* $response = $pet_api->getPetByIdInObject($pet_id);
* $this->assertInstanceOf('Swagger\Client\Model\InlineResponse200', $response);
* $this->assertSame($response->getId(), $pet_id);
* $this->assertSame($response->getName(), 'PHP Unit Test');
* $this->assertSame($response->getPhotoUrls()[0], 'http://test_php_unit_test.com');
*
* // category is type "object"
* $this->assertInternalType('array', $response->getCategory());
* $this->assertSame($response->getCategory()['id'], $pet_id);
* $this->assertSame($response->getCategory()['name'], 'test php category');
*
* $this->assertSame($response->getTags()[0]->getId(), $pet_id);
* $this->assertSame($response->getTags()[0]->getName(), 'test php tag');
* }
*/
// test getPetByIdWithHttpInfo with a Pet object (id 10005)
public function testGetPetByIdWithHttpInfo()
{
// initialize the API client without host
$petId = 10005; // ID of pet that needs to be fetched
/** @var $pet Pet */
list($pet, $status_code, $response_headers) = $this->api->getPetByIdWithHttpInfo($petId);
$this->assertSame($pet->getId(), $petId);
$this->assertSame($pet->getName(), 'PHP Unit Test');
$this->assertSame($pet->getCategory()->getId(), $petId);
$this->assertSame($pet->getCategory()->getName(), 'test php category');
$this->assertSame($pet->getTags()[0]->getId(), $petId);
$this->assertSame($pet->getTags()[0]->getName(), 'test php tag');
$this->assertSame($status_code, 200);
$this->assertSame($response_headers['Content-Type'], ['application/json']);
}
public function testFindPetByStatus()
{
$response = $this->api->findPetsByStatus('available');
$this->assertGreaterThan(0, count($response)); // at least one object returned
$this->assertSame(get_class($response[0]), Pet::class); // verify the object is Pet
foreach ($response as $pet) {
$this->assertSame($pet['status'], 'available');
}
$response = $this->api->findPetsByStatus('unknown_and_incorrect_status');
$this->assertCount(0, $response);
}
public function testFindPetsByTags()
{
$response = $this->api->findPetsByTags('test php tag');
$this->assertGreaterThan(0, count($response)); // at least one object returned
$this->assertSame(get_class($response[0]), Pet::class); // verify the object is Pet
foreach ($response as $pet) {
$this->assertSame($pet['tags'][0]['name'], 'test php tag');
}
$response = $this->api->findPetsByTags('unknown_and_incorrect_tag');
$this->assertCount(0, $response);
}
public function testUpdatePet()
{
$petId = 10001;
$updatedPet = new Model\Pet;
$updatedPet->setId($petId);
$updatedPet->setName('updatePet');
$updatedPet->setStatus('pending');
$result = $this->api->updatePet($updatedPet);
$this->assertNull($result);
// verify updated Pet
$result = $this->api->getPetById($petId);
$this->assertSame($result->getId(), $petId);
$this->assertSame($result->getStatus(), 'pending');
$this->assertSame($result->getName(), 'updatePet');
}
// test updatePetWithFormWithHttpInfo and verify by the "name" of the response
public function testUpdatePetWithFormWithHttpInfo()
{
$petId = 10001; // ID of pet that needs to be fetched
// update Pet (form)
list($update_response, $status_code, $http_headers) = $this->api->updatePetWithFormWithHttpInfo(
$petId,
'update pet with form with http info'
);
// return nothing (void)
$this->assertNull($update_response);
$this->assertSame($status_code, 200);
$this->assertSame($http_headers['Content-Type'], ['application/json']);
$response = $this->api->getPetById($petId);
$this->assertSame($response->getId(), $petId);
$this->assertSame($response->getName(), 'update pet with form with http info');
}
// test updatePetWithForm and verify by the "name" and "status" of the response
public function testUpdatePetWithForm()
{
$pet_id = 10001; // ID of pet that needs to be fetched
$result = $this->api->updatePetWithForm($pet_id, 'update pet with form', 'sold');
// return nothing (void)
$this->assertNull($result);
$response = $this->api->getPetById($pet_id);
$this->assertSame($response->getId(), $pet_id);
$this->assertSame($response->getName(), 'update pet with form');
$this->assertSame($response->getStatus(), 'sold');
}
// test addPet and verify by the "id" and "name" of the response
public function testAddPet()
{
$new_pet_id = 10005;
$newPet = new Model\Pet;
$newPet->setId($new_pet_id);
$newPet->setName("PHP Unit Test 2");
// add a new pet (model)
$add_response = $this->api->addPet($newPet);
// return nothing (void)
$this->assertNull($add_response);
// verify added Pet
$response = $this->api->getPetById($new_pet_id);
$this->assertSame($response->getId(), $new_pet_id);
$this->assertSame($response->getName(), 'PHP Unit Test 2');
}
/*
* comment out as we've removed invalid endpoints from the spec, we'll introduce something
* similar in the future when we've time to update the petstore server
*
// test addPetUsingByteArray and verify by the "id" and "name" of the response
public function testAddPetUsingByteArray()
{
// initialize the API client
$config = (new Configuration())->setHost('http://petstore.swagger.io/v2');
$api_client = new ApiClient($config);
$new_pet_id = 10005;
$new_pet = new Model\Pet;
$new_pet->setId($new_pet_id);
$new_pet->setName("PHP Unit Test 3");
// new tag
$tag= new Model\Tag;
$tag->setId($new_pet_id); // use the same id as pet
$tag->setName("test php tag");
// new category
$category = new Model\Category;
$category->setId($new_pet_id); // use the same id as pet
$category->setName("test php category");
$new_pet->setTags(array($tag));
$new_pet->setCategory($category);
$pet_api = new Api\PetApi($api_client);
// add a new pet (model)
$object_serializer = new ObjectSerializer();
$pet_json_string = json_encode($object_serializer->sanitizeForSerialization($new_pet));
$add_response = $pet_api->addPetUsingByteArray($pet_json_string);
// return nothing (void)
$this->assertSame($add_response, NULL);
// verify added Pet
$response = $pet_api->getPetById($new_pet_id);
$this->assertSame($response->getId(), $new_pet_id);
$this->assertSame($response->getName(), 'PHP Unit Test 3');
}
*/
// test upload file
public function testUploadFile()
{
// upload file
$pet_id = 10001;
$response = $this->api->uploadFile($pet_id, 'test meta', __DIR__ . '/../composer.json');
// return ApiResponse
$this->assertInstanceOf(ApiResponse::class, $response);
}
/*
* comment out as we've removed invalid endpoints from the spec, we'll introduce something
* similar in the future when we've time to update the petstore server
*
// test byte array response
public function testGetPetByIdWithByteArray()
{
// initialize the API client
$config = new Configuration();
$config->setHost('http://petstore.swagger.io/v2');
$api_client = new APIClient($config);
$pet_api = new Api\PetApi($api_client);
// test getPetByIdWithByteArray
$pet_id = 10005;
$bytes = $pet_api->petPetIdtestingByteArraytrueGet($pet_id);
$json = json_decode($bytes, true);
$this->assertInternalType("string", $bytes);
$this->assertSame($json['id'], $pet_id);
// not testing name as it's tested by addPetUsingByteArray
//$this->assertSame($json['name'], 'PHP Unit Test');
$this->assertSame($json['category']['id'], $pet_id);
$this->assertSame($json['category']['name'], 'test php category');
$this->assertSame($json['tags'][0]['id'], $pet_id);
$this->assertSame($json['tags'][0]['name'], 'test php tag');
}
*/
// test empty object serialization
public function testEmptyPetSerialization()
{
$new_pet = new Model\Pet;
// the empty object should be serialised to {}
$this->assertSame("{}", "$new_pet");
}
// test inheritance in the model
public function testInheritance()
{
$new_dog = new Model\Dog;
// the object should be an instance of the derived class
$this->assertInstanceOf('Swagger\Client\Model\Dog', $new_dog);
// the object should also be an instance of the parent class
$this->assertInstanceOf('Swagger\Client\Model\Animal', $new_dog);
}
// test inheritance constructor is working with data
// initialization
public function testInheritanceConstructorDataInitialization()
{
// initialize the object with data in the constructor
$data = array(
'class_name' => 'Dog',
'breed' => 'Great Dane'
);
$new_dog = new Model\Dog($data);
// the property on the derived class should be set
$this->assertSame('Great Dane', $new_dog->getBreed());
// the property on the parent class should be set
$this->assertSame('Dog', $new_dog->getClassName());
}
// test if discriminator is initialized automatically
public function testDiscriminatorInitialization()
{
$new_dog = new Model\Dog();
$this->assertSame('Dog', $new_dog->getClassName());
}
// test if ArrayAccess interface works
public function testArrayStuff()
{
// create an AnimalFarm which is an object implementing the
// ArrayAccess interface
$farm = new Model\AnimalFarm();
// add some animals to the farm to make sure the ArrayAccess
// interface works
$farm[] = new Model\Dog();
$farm[] = new Model\Cat();
$farm[] = new Model\Animal();
// assert we can look up the animals in the farm by array
// indices (let's try a random order)
$this->assertInstanceOf('Swagger\Client\Model\Cat', $farm[1]);
$this->assertInstanceOf('Swagger\Client\Model\Dog', $farm[0]);
$this->assertInstanceOf('Swagger\Client\Model\Animal', $farm[2]);
// let's try to `foreach` the animals in the farm and let's
// try to use the objects we loop through
foreach ($farm as $animal) {
$this->assertContains($animal->getClassName(), array('Dog', 'Cat', 'Animal'));
$this->assertInstanceOf('Swagger\Client\Model\Animal', $animal);
}
}
// test if default values works
public function testDefaultValues()
{
// add some animals to the farm to make sure the ArrayAccess
// interface works
$dog = new Model\Dog();
$animal = new Model\Animal();
// assert we can look up the animals in the farm by array
// indices (let's try a random order)
$this->assertSame('red', $dog->getColor());
$this->assertSame('red', $animal->getColor());
}
/**
* test invalid argument
*
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage Missing the required parameter $status when calling findPetsByStatus
*/
public function testInvalidArgument()
{
// the argument is required, and we must specify one or some from 'available', 'pending', 'sold'
$this->api->findPetsByStatus([]);
}
// Disabled as currently we don't have any endpoint that would return file
// For testing I just replaced url and return type in Api method.
// public function testDownloadingLargeFile()
// {
// $petId = 10005;
// $config = new Configuration();
// $config->setHost('https://getcomposer.org');
// $api = new PetApi(new Client(), $config);
// $result = $api->getPetById($petId);
// $this->assertInstanceOf(\SplFileObject::class, $result);
// var_dump([
// 'peak mem (MiB)' => memory_get_peak_usage(true)/1024/1024,
// 'file size (MiB)' => $result->getSize()/1024/1024,
// 'path' => sys_get_temp_dir() . '/' . $result->getFilename()
// ]);
// }
}

View File

@ -0,0 +1,18 @@
<?php
namespace Swagger\Client;
use Swagger\Client\Model\Pet;
class PetTest extends \PHPUnit_Framework_TestCase
{
/**
* test empty object serialization
*/
public function testEmptyPetSerialization()
{
$new_pet = new Pet;
// the empty object should be serialised to {}
$this->assertSame("{}", "$new_pet");
}
}

View File

@ -0,0 +1,34 @@
<?php
namespace Swagger\Client;
use Swagger\Client\Api\FakeApi;
class RequestTest extends \PHPUnit_Framework_TestCase
{
/** @var FakeApi */
private $api;
/** @var FakeHttpClient */
private $fakeClient;
public function setUp()
{
$this->fakeClient = new FakeHttpClient();
$this->api = new Api\FakeApi($this->fakeClient);
}
public function testFormDataEncodingToJson()
{
$this->api->testJsonFormData('value', 'value2');
$request = $this->fakeClient->getLastRequest();
$contentType = $request->getHeader('Content-Type');
$this->assertEquals(['application/json'], $contentType);
$requestContent = $request->getBody()->getContents();
$expected = json_encode(['param' => 'value', 'param2' => 'value2']);
$this->assertEquals($expected, $requestContent);
}
}

View File

@ -0,0 +1,95 @@
<?php
namespace Swagger\Client;
use GuzzleHttp\Psr7\Response;
use Swagger\Client\Api\PetApi;
use Swagger\Client\Model\Pet;
require_once __DIR__ . '/FakeHttpClient.php';
class ResponseTypesTest extends \PHPUnit_Framework_TestCase
{
/** @var PetApi */
private $api;
/** @var FakeHttpClient */
private $fakeHttpClient;
public function setUp()
{
$this->fakeHttpClient = new FakeHttpClient();
$this->api = new PetApi($this->fakeHttpClient);
}
public function testDefined200ReturnType()
{
$this->fakeHttpClient->setResponse(new Response(200, [], json_encode([])));
$result = $this->api->getPetById(123);
$this->assertInstanceOf(Pet::class, $result);
}
public function testDefault2xxReturnType()
{
$this->fakeHttpClient->setResponse(new Response(255, [], json_encode([])));
$result = $this->api->getPetById(123);
$this->assertInstanceOf(Pet::class, $result);
}
/**
* @expectedException \Swagger\Client\ApiException
* @expectedExceptionCode 400
*/
public function testDefinedErrorException()
{
$statusCode = 400;
$this->fakeHttpClient->setResponse(new Response($statusCode, [], '{}'));
$this->api->getPetById(123);
}
// missing case in spec:
// responses:
// '400':
// description: failure
// schema:
// $ref: '#/definitions/Error'
// public function testDefinedErrorResponseObject()
// {
// $result = null;
// try {
// $this->fakeHttpClient->setResponse(new Response(400, [], '{}'));
// $this->api->getPetById(123);
// } catch (ApiException $e) {
// $result = $e->getResponseObject();
// }
//
// $this->assertInstanceOf(Error::class, $result);
// }
/**
* @expectedException \Swagger\Client\ApiException
* @expectedExceptionCode 404
*/
public function testDefaultErrorException()
{
$statusCode = 404;
$this->fakeHttpClient->setResponse(new Response($statusCode, [], '{}'));
$this->api->getPetById(123);
}
public function testDefaultErrorResponseObject()
{
$result = null;
try {
$this->fakeHttpClient->setResponse(new Response(404, [], '{}'));
$this->api->getPetById(123);
} catch (ApiException $e) {
$result = $e->getResponseObject();
}
$this->assertNull($result);
}
}

View File

@ -0,0 +1,56 @@
<?php
namespace Swagger\Client;
use Swagger\Client\Api\PetApi;
use Swagger\Client\Api\StoreApi;
use Swagger\Client\Model\Category;
use Swagger\Client\Model\Pet;
use Swagger\Client\Model\Tag;
class StoreApiTest extends \PHPUnit_Framework_TestCase
{
/** @var StoreApi */
private $api;
public function setUp()
{
$this->api = new StoreApi();
}
/**
* Setup before running each test case
*/
public static function setUpBeforeClass()
{
// add a new pet (id 10005) to ensure the pet object is available for all the tests
// new pet
$id = 10005;
$pet = new Pet();
$pet->setId($id);
$pet->setName('PHP Unit Test');
$pet->setStatus('available');
// new tag
$tag = new Tag();
$tag->setId($id); // use the same id as pet
$tag->setName('test php tag');
// new category
$category = new Category();
$category->setId($id); // use the same id as pet
$category->setName('test php category');
$pet->setTags([$tag]);
$pet->setCategory($category);
$api = new PetApi();
$api->addPet($pet);
}
public function testGetInventory()
{
$result = $this->api->getInventory();
$this->assertInternalType('array', $result);
$this->assertInternalType('int', $result['available']);
}
}

View File

@ -0,0 +1,32 @@
<?php
namespace Swagger\Client;
use Swagger\Client\Api\UserApi;
class UserApiTest extends \PHPUnit_Framework_TestCase
{
/** @var UserApi*/
private $api;
public function setUp()
{
$this->api = new Api\UserApi();
}
// test login use
public function testLoginUser()
{
// initialize the API client
// login
$response = $this->api->loginUser('xxxxx', 'yyyyyyyy');
$this->assertInternalType('string', $response);
$this->assertRegExp(
'/^logged in user session/',
$response,
"response string starts with 'logged in user session'"
);
}
}