[JavaScript] Add petstore integration test to JS ES6 client (OAS3) (#2245)

* add test for js es6 oas3 client

* fix test with proper done

* add test, fix servers index check
This commit is contained in:
William Cheng 2019-02-27 11:14:51 +08:00 committed by GitHub
parent aa339d6046
commit b5ce0bddee
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
12 changed files with 362 additions and 10 deletions

View File

@ -978,13 +978,21 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
hasOptionalParams = true;
}
}
if (operation.servers != null && !operation.servers.isEmpty()) {
// add optional parameter for servers (e.g. index)
hasOptionalParams = true;
}
if (hasOptionalParams) {
argList.add("opts");
}
}
if (!usePromises) {
argList.add("callback");
}
operation.vendorExtensions.put("x-codegen-argList", StringUtils.join(argList, ", "));
operation.vendorExtensions.put("x-codegen-hasOptionalParams", hasOptionalParams);
// Store JSDoc type specification into vendor-extension: x-jsdoc-type.
for (CodegenParameter cp : operation.allParams) {

View File

@ -43,8 +43,10 @@ export default class <classname> {
* data is of type: {@link <&vendorExtensions.x-jsdoc-type>}</returnType></usePromises><#usePromises>
* @return {Promise} a {@link https://www.promisejs.org/|Promise}<#returnType>, with an object containing data of type {@link <&vendorExtensions.x-jsdoc-type>} and HTTP response</returnType><^returnType>, with an object containing HTTP response</returnType></usePromises>
*/
</emitJSDoc> <operationId><#usePromises>WithHttpInfo</usePromises>(<vendorExtensions.x-codegen-argList>) {<#hasOptionalParams>
opts = opts || {};</hasOptionalParams>
</emitJSDoc> <operationId><#usePromises>WithHttpInfo</usePromises>(<vendorExtensions.x-codegen-argList>) {
<#vendorExtensions.x-codegen-hasOptionalParams>
opts = opts || {};
</vendorExtensions.x-codegen-hasOptionalParams>
let postBody = <#bodyParam><#required><paramName></required><^required>opts['<paramName>']</required></bodyParam><^bodyParam>null</bodyParam>;
<#allParams>
<#required>
@ -76,7 +78,7 @@ export default class <classname> {
let basePaths = [<#servers>'<url>'<^-last>, </-last></servers>];
let basePath = basePaths[0]; // by default use the first one in "servers" defined in OpenAPI
if (typeof opts['_base_path_index'] !== 'undefined') {
if (opts['_base_path_index'] < 0 || opts['_base_path_index'] >= basePaths.length) {
if (opts['_base_path_index'] >= basePaths.length || opts['_base_path_index'] < 0) {
throw new Error("Invalid index " + opts['_base_path_index'] + " when selecting the host settings. Must be less than " + basePaths.length);
}
basePath = basePaths[opts['_base_path_index']];

View File

@ -92,6 +92,7 @@ Class | Method | HTTP request | Description
------------ | ------------- | ------------- | -------------
*OpenApiPetstore.AnotherFakeApi* | [**call123testSpecialTags**](docs/AnotherFakeApi.md#call123testSpecialTags) | **PATCH** /another-fake/dummy | To test special tags
*OpenApiPetstore.DefaultApi* | [**fooGet**](docs/DefaultApi.md#fooGet) | **GET** /foo |
*OpenApiPetstore.FakeApi* | [**fakeHealthGet**](docs/FakeApi.md#fakeHealthGet) | **GET** /fake/health | Health check endpoint
*OpenApiPetstore.FakeApi* | [**fakeOuterBooleanSerialize**](docs/FakeApi.md#fakeOuterBooleanSerialize) | **POST** /fake/outer/boolean |
*OpenApiPetstore.FakeApi* | [**fakeOuterCompositeSerialize**](docs/FakeApi.md#fakeOuterCompositeSerialize) | **POST** /fake/outer/composite |
*OpenApiPetstore.FakeApi* | [**fakeOuterNumberSerialize**](docs/FakeApi.md#fakeOuterNumberSerialize) | **POST** /fake/outer/number |
@ -150,6 +151,7 @@ Class | Method | HTTP request | Description
- [OpenApiPetstore.Foo](docs/Foo.md)
- [OpenApiPetstore.FormatTest](docs/FormatTest.md)
- [OpenApiPetstore.HasOnlyReadOnly](docs/HasOnlyReadOnly.md)
- [OpenApiPetstore.HealthCheckResult](docs/HealthCheckResult.md)
- [OpenApiPetstore.InlineObject](docs/InlineObject.md)
- [OpenApiPetstore.InlineObject1](docs/InlineObject1.md)
- [OpenApiPetstore.InlineObject2](docs/InlineObject2.md)

View File

@ -4,6 +4,7 @@ All URIs are relative to *http://petstore.swagger.io:80/v2*
Method | HTTP request | Description
------------- | ------------- | -------------
[**fakeHealthGet**](FakeApi.md#fakeHealthGet) | **GET** /fake/health | Health check endpoint
[**fakeOuterBooleanSerialize**](FakeApi.md#fakeOuterBooleanSerialize) | **POST** /fake/outer/boolean |
[**fakeOuterCompositeSerialize**](FakeApi.md#fakeOuterCompositeSerialize) | **POST** /fake/outer/composite |
[**fakeOuterNumberSerialize**](FakeApi.md#fakeOuterNumberSerialize) | **POST** /fake/outer/number |
@ -18,6 +19,42 @@ Method | HTTP request | Description
[**testJsonFormData**](FakeApi.md#testJsonFormData) | **GET** /fake/jsonFormData | test json serialization of form data
<a name="fakeHealthGet"></a>
# **fakeHealthGet**
> HealthCheckResult fakeHealthGet()
Health check endpoint
### Example
```javascript
import OpenApiPetstore from 'open_api_petstore';
let apiInstance = new OpenApiPetstore.FakeApi();
apiInstance.fakeHealthGet((error, data, response) => {
if (error) {
console.error(error);
} else {
console.log('API called successfully. Returned data: ' + data);
}
});
```
### Parameters
This endpoint does not need any parameter.
### Return type
[**HealthCheckResult**](HealthCheckResult.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
<a name="fakeOuterBooleanSerialize"></a>
# **fakeOuterBooleanSerialize**
> Boolean fakeOuterBooleanSerialize(opts)

View File

@ -0,0 +1,8 @@
# OpenApiPetstore.HealthCheckResult
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**nullableMessage** | **String** | | [optional]

View File

@ -15,6 +15,7 @@
import ApiClient from "../ApiClient";
import Client from '../model/Client';
import FileSchemaTestClass from '../model/FileSchemaTestClass';
import HealthCheckResult from '../model/HealthCheckResult';
import OuterComposite from '../model/OuterComposite';
import User from '../model/User';
@ -37,6 +38,42 @@ export default class FakeApi {
}
/**
* Callback function to receive the result of the fakeHealthGet operation.
* @callback module:api/FakeApi~fakeHealthGetCallback
* @param {String} error Error message, if any.
* @param {module:model/HealthCheckResult} data The data returned by the service call.
* @param {String} response The complete HTTP response.
*/
/**
* Health check endpoint
* @param {module:api/FakeApi~fakeHealthGetCallback} callback The callback function, accepting three arguments: error, data, response
* data is of type: {@link module:model/HealthCheckResult}
*/
fakeHealthGet(callback) {
let postBody = null;
let pathParams = {
};
let queryParams = {
};
let headerParams = {
};
let formParams = {
};
let authNames = [];
let contentTypes = [];
let accepts = ['application/json'];
let returnType = HealthCheckResult;
return this.apiClient.callApi(
'/fake/health', 'GET',
pathParams, queryParams, headerParams, formParams, postBody,
authNames, contentTypes, accepts, returnType, null, callback
);
}
/**
* Callback function to receive the result of the fakeOuterBooleanSerialize operation.
* @callback module:api/FakeApi~fakeOuterBooleanSerializeCallback

View File

@ -48,7 +48,8 @@ export default class PetApi {
* @param {module:model/Pet} pet Pet object that needs to be added to the store
* @param {module:api/PetApi~addPetCallback} callback The callback function, accepting three arguments: error, data, response
*/
addPet(pet, callback) {
addPet(pet, opts, callback) {
opts = opts || {};
let postBody = pet;
// verify the required parameter 'pet' is set
if (pet === undefined || pet === null) {
@ -68,10 +69,19 @@ export default class PetApi {
let contentTypes = ['application/json', 'application/xml'];
let accepts = [];
let returnType = null;
let basePaths = ['http://petstore.swagger.io/v2', 'http://path-server-test.petstore.local/v2'];
let basePath = basePaths[0]; // by default use the first one in "servers" defined in OpenAPI
if (typeof opts['_base_path_index'] !== 'undefined') {
if (opts['_base_path_index'] >= basePaths.length || opts['_base_path_index'] < 0) {
throw new Error("Invalid index " + opts['_base_path_index'] + " when selecting the host settings. Must be less than " + basePaths.length);
}
basePath = basePaths[opts['_base_path_index']];
}
return this.apiClient.callApi(
'/pet', 'POST',
pathParams, queryParams, headerParams, formParams, postBody,
authNames, contentTypes, accepts, returnType, null, callback
authNames, contentTypes, accepts, returnType, basePath, callback
);
}
@ -262,7 +272,8 @@ export default class PetApi {
* @param {module:model/Pet} pet Pet object that needs to be added to the store
* @param {module:api/PetApi~updatePetCallback} callback The callback function, accepting three arguments: error, data, response
*/
updatePet(pet, callback) {
updatePet(pet, opts, callback) {
opts = opts || {};
let postBody = pet;
// verify the required parameter 'pet' is set
if (pet === undefined || pet === null) {
@ -282,10 +293,19 @@ export default class PetApi {
let contentTypes = ['application/json', 'application/xml'];
let accepts = [];
let returnType = null;
let basePaths = ['http://petstore.swagger.io/v2', 'http://path-server-test.petstore.local/v2'];
let basePath = basePaths[0]; // by default use the first one in "servers" defined in OpenAPI
if (typeof opts['_base_path_index'] !== 'undefined') {
if (opts['_base_path_index'] >= basePaths.length || opts['_base_path_index'] < 0) {
throw new Error("Invalid index " + opts['_base_path_index'] + " when selecting the host settings. Must be less than " + basePaths.length);
}
basePath = basePaths[opts['_base_path_index']];
}
return this.apiClient.callApi(
'/pet', 'PUT',
pathParams, queryParams, headerParams, formParams, postBody,
authNames, contentTypes, accepts, returnType, null, callback
authNames, contentTypes, accepts, returnType, basePath, callback
);
}

View File

@ -33,6 +33,7 @@ import FileSchemaTestClass from './model/FileSchemaTestClass';
import Foo from './model/Foo';
import FormatTest from './model/FormatTest';
import HasOnlyReadOnly from './model/HasOnlyReadOnly';
import HealthCheckResult from './model/HealthCheckResult';
import InlineObject from './model/InlineObject';
import InlineObject1 from './model/InlineObject1';
import InlineObject2 from './model/InlineObject2';
@ -222,6 +223,12 @@ export {
*/
HasOnlyReadOnly,
/**
* The HealthCheckResult model constructor.
* @property {module:model/HealthCheckResult}
*/
HealthCheckResult,
/**
* The InlineObject model constructor.
* @property {module:model/InlineObject}

View File

@ -0,0 +1,72 @@
/**
* OpenAPI Petstore
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
*
* OpenAPI spec version: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*
*/
import ApiClient from '../ApiClient';
/**
* The HealthCheckResult model module.
* @module model/HealthCheckResult
* @version 1.0.0
*/
class HealthCheckResult {
/**
* Constructs a new <code>HealthCheckResult</code>.
* Just a string to inform instance is up and running. Make it nullable in hope to get it as pointer in generated model.
* @alias module:model/HealthCheckResult
*/
constructor() {
HealthCheckResult.initialize(this);
}
/**
* Initializes the fields of this object.
* This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins).
* Only for internal use.
*/
static initialize(obj) {
}
/**
* Constructs a <code>HealthCheckResult</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:model/HealthCheckResult} obj Optional instance to populate.
* @return {module:model/HealthCheckResult} The populated <code>HealthCheckResult</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new HealthCheckResult();
if (data.hasOwnProperty('NullableMessage')) {
obj['NullableMessage'] = ApiClient.convertToType(data['NullableMessage'], 'String');
}
}
return obj;
}
}
/**
* @member {String} NullableMessage
*/
HealthCheckResult.prototype['NullableMessage'] = undefined;
export default HealthCheckResult;

View File

@ -25,10 +25,10 @@
}(this, function(expect, OpenApiPetstore) {
'use strict';
var instance;
var api_instance;
beforeEach(function() {
instance = new OpenApiPetstore.PetApi();
api_instance = new OpenApiPetstore.PetApi();
});
var getProperty = function(object, getter, property) {
@ -47,7 +47,56 @@
object[property] = value;
}
var createRandomPet = function() {
var id = new Date().getTime();
var pet = new OpenApiPetstore.Pet();
setProperty(pet, "setId", "id", id);
setProperty(pet, "setName", "name", "pet" + id);
var category = new OpenApiPetstore.Category();
setProperty(category, "setId", "id", id);
setProperty(category, "setName", "name", "category" + id);
setProperty(pet, "setCategory", "category", category);
setProperty(pet, "setStatus", "status", "available");
var photos = ["http://foo.bar.com/1", "http://foo.bar.com/2"];
setProperty(pet, "setPhotoUrls", "photoUrls", photos);
return pet;
}
describe('PetApi', function() {
it('should create and get pet', function(done) {
this.timeout(15000);
var pet = createRandomPet();
try {
//api_instance.addPet(pet, {_base_path_index: 1}, function(error) {
api_instance.addPet(pet, null, function(error) {
if (error) throw error;
api_instance.getPetById(pet.id, function(error, fetched, response) {
if (error) throw error;
expect(response.status).to.be(200);
expect(response.ok).to.be(true);
expect(response.get('Content-Type')).to.be('application/json');
expect(fetched).to.be.a(OpenApiPetstore.Pet);
expect(fetched.id).to.be(pet.id);
expect(getProperty(fetched, "getPhotoUrls", "photoUrls"))
.to.eql(getProperty(pet, "getPhotoUrls", "photoUrls"));
expect(getProperty(fetched, "getCategory", "category"))
.to.be.a(OpenApiPetstore.Category);
expect(getProperty(getProperty(fetched, "getCategory", "category"), "getName", "name"))
.to.be(getProperty(getProperty(pet, "getCategory", "category"), "getName", "name"));
api_instance.deletePet(pet.id);
done();
});
});
} catch (error) {
done(error);
}
});
describe('addPet', function() {
it('should call addPet successfully', function(done) {
//uncomment below and update the code to test addPet

View File

@ -0,0 +1,65 @@
/**
* OpenAPI Petstore
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
*
* OpenAPI spec version: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*
*/
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD.
define(['expect.js', '../../src/index'], factory);
} else if (typeof module === 'object' && module.exports) {
// CommonJS-like environments that support module.exports, like Node.
factory(require('expect.js'), require('../../src/index'));
} else {
// Browser globals (root is window)
factory(root.expect, root.OpenApiPetstore);
}
}(this, function(expect, OpenApiPetstore) {
'use strict';
var instance;
beforeEach(function() {
instance = new OpenApiPetstore.HealthCheckResult();
});
var getProperty = function(object, getter, property) {
// Use getter method if present; otherwise, get the property directly.
if (typeof object[getter] === 'function')
return object[getter]();
else
return object[property];
}
var setProperty = function(object, setter, property, value) {
// Use setter method if present; otherwise, set the property directly.
if (typeof object[setter] === 'function')
object[setter](value);
else
object[property] = value;
}
describe('HealthCheckResult', function() {
it('should create an instance of HealthCheckResult', function() {
// uncomment below and update the code to test HealthCheckResult
//var instane = new OpenApiPetstore.HealthCheckResult();
//expect(instance).to.be.a(OpenApiPetstore.HealthCheckResult);
});
it('should have the property nullableMessage (base name: "NullableMessage")', function() {
// uncomment below and update the code to test the property nullableMessage
//var instane = new OpenApiPetstore.HealthCheckResult();
//expect(instance).to.be();
});
});
}));

View File

@ -0,0 +1,45 @@
<html>
<head>
<meta charset="utf-8">
<title>Mocha Tests</title>
<link href="https://cdn.rawgit.com/mochajs/mocha/2.2.5/mocha.css" rel="stylesheet" />
</head>
<body>
<div id="mocha"></div>
<script src="https://cdn.rawgit.com/jquery/jquery/2.1.4/dist/jquery.min.js"></script>
<script src="https://cdn.rawgit.com/Automattic/expect.js/0.3.1/index.js"></script>
<script src="http://sinonjs.org/releases/sinon-1.17.3.js"></script>
<script src="https://cdn.rawgit.com/mochajs/mocha/2.2.5/mocha.js"></script>
<script>
mocha.setup({
ui: 'bdd',
timeout: 10000
});
</script>
<script src="../node_modules/superagent/superagent.js"></script>
<script src="../src/ApiClient.js"></script>
<script src="../src/model/Category.js"></script>
<script src="../src/model/Tag.js"></script>
<script src="../src/model/InlineResponse200.js"></script>
<script src="../src/model/Pet.js"></script>
<script src="../src/model/Order.js"></script>
<script src="../src/model/User.js"></script>
<script src="../src/api/PetApi.js"></script>
<script src="../src/api/StoreApi.js"></script>
<script src="ApiClientTest.js"></script>
<script src="api/PetApiTest.js"></script>
<script src="api/StoreApiTest.js"></script>
<script>
mocha.checkLeaks();
mocha.globals(['jQuery']);
mocha.run();
</script>
</body>
</html>