small example of a first integration-test of the code-generator

This commit is contained in:
Kristof Vrolijkx 2016-05-01 14:27:41 +02:00
parent de5363c21b
commit f8046bc9c9
19 changed files with 474 additions and 52 deletions

View File

@ -1,32 +1,13 @@
package io.swagger.codegen;
import io.swagger.codegen.auth.AuthMethod;
import java.util.HashMap;
import java.util.Map;
import io.swagger.codegen.auth.AuthMethod;
public class ClientOpts {
protected String uri;
protected String target;
protected AuthMethod auth;
protected Map<String, String> properties = new HashMap<String, String>();
protected String outputDirectory;
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
public String getTarget() {
return target;
}
public void setTarget(String target) {
this.target = target;
}
public Map<String, String> getProperties() {
return properties;
@ -36,19 +17,10 @@ public class ClientOpts {
this.properties = properties;
}
public String getOutputDirectory() {
return outputDirectory;
}
public void setOutputDirectory(String outputDirectory) {
this.outputDirectory = outputDirectory;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("ClientOpts: {\n");
sb.append(" uri: ").append(uri).append(",");
sb.append(" auth: ").append(auth).append(",");
sb.append(properties);
sb.append("}");
@ -57,30 +29,20 @@ public class ClientOpts {
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (this == o) { return true; }
if (o == null || getClass() != o.getClass()) { return false; }
ClientOpts that = (ClientOpts) o;
if (uri != null ? !uri.equals(that.uri) : that.uri != null)
return false;
if (target != null ? !target.equals(that.target) : that.target != null)
return false;
if (auth != null ? !auth.equals(that.auth) : that.auth != null)
return false;
if (properties != null ? !properties.equals(that.properties) : that.properties != null)
return false;
return outputDirectory != null ? outputDirectory.equals(that.outputDirectory) : that.outputDirectory == null;
if (auth != null ? !auth.equals(that.auth) : that.auth != null) { return false; }
return getProperties().equals(that.getProperties());
}
@Override
public int hashCode() {
int result = uri != null ? uri.hashCode() : 0;
result = 31 * result + (target != null ? target.hashCode() : 0);
result = 31 * result + (auth != null ? auth.hashCode() : 0);
result = 31 * result + (properties != null ? properties.hashCode() : 0);
result = 31 * result + (outputDirectory != null ? outputDirectory.hashCode() : 0);
int result = auth != null ? auth.hashCode() : 0;
result = 31 * result + getProperties().hashCode();
return result;
}
}

View File

@ -0,0 +1,74 @@
package io.swagger.codegen.typescript.integrationtest;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import org.testng.reporters.Files;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import io.swagger.codegen.ClientOptInput;
import io.swagger.codegen.ClientOpts;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.DefaultGenerator;
import io.swagger.codegen.languages.TypeScriptAngular2ClientCodegen;
import io.swagger.models.Swagger;
import io.swagger.parser.SwaggerParser;
import static io.swagger.codegen.typescript.integrationtest.AssertFile.assertPathEqualsRecursively;
public class Angular2GenerationWithAditionPropertiesTest {
private DefaultGenerator codeGen;
private Path integrationTestPath;
private Path outputPath;
private Path specPath;
private Path expectedPath;
@BeforeMethod
public void setUp() {
codeGen = new DefaultGenerator();
integrationTestPath = Paths.get("target/test-classes/integrationtest").toAbsolutePath();
outputPath = integrationTestPath.resolve("typescript/additional-properties-result");
expectedPath = integrationTestPath.resolve("typescript/additional-properties-expected");
specPath = integrationTestPath.resolve("typescript/additional-properties-spec.json");
}
protected CodegenConfig getCodegenConfig() {
return new TypeScriptAngular2ClientCodegen();
}
protected Map<String, String> configProperties() {
Map<String, String> propeties = new HashMap<>();
propeties.put("npmName", "additionalPropertiesTest");
propeties.put("npmVersion", "1.0.2");
propeties.put("snapshot", "false");
return propeties;
}
@Test(description = "The correct output is generated for a spec with additional-properties")
public void shouldGenerateCorrectTypescriptModels() throws IOException {
String specContent = Files.readFile(specPath.toFile());
Swagger swagger = new SwaggerParser().parse(specContent);
CodegenConfig codegenConfig = getCodegenConfig();
codegenConfig.setOutputDir(outputPath.toString());
ClientOpts clientOpts = new ClientOpts();
clientOpts.setProperties(configProperties());
ClientOptInput opts = new ClientOptInput()
.config(codegenConfig)
.opts(clientOpts)
.swagger(swagger);
codeGen.opts(opts).generate();
assertPathEqualsRecursively(expectedPath, outputPath);
}
}

View File

@ -0,0 +1,94 @@
package io.swagger.codegen.typescript.integrationtest;
import org.testng.Assert;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.fail;
/**
* Assertion for recursively testing directories.
*
* @author andreas
*/
public class AssertFile {
private AssertFile() {
throw new RuntimeException("This class should not be instantiated");
}
/**
* Asserts that two directories are recursively equal. If they are not, an {@link AssertionError} is thrown with the
* given message.<br/>
* There will be a binary comparison of all files under expected with all files under actual. File attributes will
* not be considered.<br/>
* Missing or additional files are considered an error.<br/>
*
* @param expected Path expected directory
* @param actual Path actual directory
*/
public static final void assertPathEqualsRecursively(final Path expected, final Path actual) {
Assert.assertNotNull(expected);
Assert.assertNotNull(actual);
final Path absoluteExpected = expected.toAbsolutePath();
final Path absoluteActual = actual.toAbsolutePath();
try {
Files.walkFileTree(expected, new FileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path expectedDir, BasicFileAttributes attrs) throws IOException {
Path relativeExpectedDir = absoluteExpected.relativize(expectedDir.toAbsolutePath());
Path actualDir = absoluteActual.resolve(relativeExpectedDir);
if (!Files.exists(actualDir)) {
fail(String.format("Directory \'%s\' missing in target.", expectedDir.getFileName()));
}
assertEquals(expectedDir.toFile().list().length,
actualDir.toFile().list().length,
String.format("Directory size of \'%s\' differ. ", relativeExpectedDir));
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path expectedFile, BasicFileAttributes attrs) throws IOException {
Path relativeExpectedFile = absoluteExpected.relativize(expectedFile.toAbsolutePath());
Path actualFile = absoluteActual.resolve(relativeExpectedFile);
if (!Files.exists(actualFile)) {
fail(String.format("File \'%s\' missing in target.", expectedFile.getFileName()));
}
assertEquals(Files.readAllLines(expectedFile, Charset.defaultCharset()),
Files.readAllLines(actualFile, Charset.defaultCharset()),
String.format("File content of \'%s\' differ. ", relativeExpectedFile));
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
fail(exc.getMessage());
return FileVisitResult.TERMINATE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
return FileVisitResult.CONTINUE;
}
});
} catch (IOException e) {
fail(e.getMessage());
}
}
}

View File

@ -1,4 +1,4 @@
package io.swagger.codegen.typescriptangular;
package io.swagger.codegen.typescript.typescriptangular;
import io.swagger.codegen.AbstractOptionsTest;
import io.swagger.codegen.CodegenConfig;

View File

@ -1,4 +1,4 @@
package io.swagger.codegen.typescriptangular;
package io.swagger.codegen.typescript.typescriptangular;
import io.swagger.codegen.CodegenModel;
import io.swagger.codegen.CodegenProperty;

View File

@ -1,4 +1,4 @@
package io.swagger.codegen.typescriptangular2;
package io.swagger.codegen.typescript.typescriptangular2;
import io.swagger.codegen.AbstractOptionsTest;
import io.swagger.codegen.CodegenConfig;

View File

@ -1,4 +1,4 @@
package io.swagger.codegen.typescriptangular2;
package io.swagger.codegen.typescript.typescriptangular2;
import com.google.common.collect.Sets;

View File

@ -1,4 +1,4 @@
package io.swagger.codegen.typescriptnode;
package io.swagger.codegen.typescript.typescriptnode;
import io.swagger.codegen.AbstractOptionsTest;
import io.swagger.codegen.CodegenConfig;

View File

@ -1,4 +1,4 @@
package io.swagger.codegen.typescriptnode;
package io.swagger.codegen.typescript.typescriptnode;
import io.swagger.codegen.CodegenModel;
import io.swagger.codegen.CodegenProperty;

View File

@ -0,0 +1,33 @@
## additionalPropertiesTest@1.0.0
### Building
To build an compile the typescript sources to javascript use:
```
npm install
npm run build
```
### publishing
First build the package than run ```npm publish```
### consuming
navigate to the folder of your consuming project and run one of next commando's.
_published:_
```
npm install additionalPropertiesTest@1.0.0 --save
```
_unPublished (not recommended):_
```
npm install PATH_TO_GENERATED_PACKAGE --save
```
In your angular2 project:
TODO: paste example.

View File

@ -0,0 +1,64 @@
import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from 'angular2/http';
import {Injectable} from 'angular2/core';
import {Observable} from 'rxjs/Observable';
import * as models from '../model/models';
/* tslint:disable:no-unused-variable member-ordering */
'use strict';
@Injectable()
export class UserApi {
protected basePath = 'http://additional-properties.swagger.io/v2';
public defaultHeaders : Headers = new Headers();
constructor(protected http: Http, basePath: string) {
if (basePath) {
this.basePath = basePath;
}
}
/**
* Add a new User to the store
*
* @param body User object that needs to be added to the store
*/
public addUser (body?: models.User, extraHttpRequestParams?: any ) : Observable<{}> {
const path = this.basePath + '/user';
let queryParameters: any = ""; // This should probably be an object in the future
let headerParams = this.defaultHeaders;
let requestOptions: RequestOptionsArgs = {
method: 'POST',
headers: headerParams,
search: queryParameters
};
requestOptions.body = JSON.stringify(body);
return this.http.request(path, requestOptions)
.map((response: Response) => response.json());
}
/**
* Update an existing User
*
* @param body User object that needs to be added to the store
*/
public updateUser (body?: models.User, extraHttpRequestParams?: any ) : Observable<{}> {
const path = this.basePath + '/user';
let queryParameters: any = ""; // This should probably be an object in the future
let headerParams = this.defaultHeaders;
let requestOptions: RequestOptionsArgs = {
method: 'PUT',
headers: headerParams,
search: queryParameters
};
requestOptions.body = JSON.stringify(body);
return this.http.request(path, requestOptions)
.map((response: Response) => response.json());
}
}

View File

@ -0,0 +1,3 @@
export * from '../api/UserApi';

View File

@ -0,0 +1,2 @@
export * from 'api/api';
export * from 'model/models';

View File

@ -0,0 +1,14 @@
'use strict';
import * as models from './models';
export interface User {
[key: string]: string
id?: number;
/**
* User Status
*/
userStatus?: number;
}

View File

@ -0,0 +1,30 @@
{
"name": "additionalPropertiesTest",
"version": "1.0.0",
"description": "swagger client for additionalPropertiesTest",
"author": "Swagger Codegen Contributors",
"keywords": [
"swagger-client"
],
"license": "MIT",
"files": [
"lib"
],
"main": "./lib/index.js",
"typings": "./lib/index.d.ts",
"scripts": {
"build": "typings install && tsc"
},
"peerDependencies": {
"angular2": "^2.0.0-beta.15",
"rxjs": "^5.0.0-beta.2"
},
"devDependencies": {
"typescript": "^1.8.10",
"typings": "^0.8.1",
"angular2": "^2.0.0-beta.15",
"es6-shim": "^0.35.0",
"es7-reflect-metadata": "^1.6.0",
"rxjs": "5.0.0-beta.2",
"zone.js": "^0.6.10"
}}

View File

@ -0,0 +1,27 @@
{
"compilerOptions": {
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"noImplicitAny": false,
"suppressImplicitAnyIndexErrors": true,
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"removeComments": true,
"sourceMap": true,
"outDir": "./lib",
"noLib": false,
"declaration": true
},
"exclude": [
"node_modules",
"typings/main.d.ts",
"typings/main",
"lib"
],
"filesGlob": [
"./model/*.ts",
"./api/*.ts",
"typings/browser.d.ts"
]
}

View File

@ -0,0 +1,5 @@
{
"ambientDependencies": {
"core-js": "registry:dt/core-js#0.0.0+20160317120654"
}
}

View File

@ -0,0 +1,110 @@
{
"swagger": "2.0",
"info": {
"description": "This is a test spec",
"version": "1.0.0",
"title": "Swagger Additional Properties",
"termsOfService": "http://swagger.io/terms/",
"contact": {
"email": "apiteam@swagger.io"
},
"license": {
"name": "Apache 2.0",
"url": "http://www.apache.org/licenses/LICENSE-2.0.html"
}
},
"host": "additional-properties.swagger.io",
"basePath": "/v2",
"schemes": [
"http"
],
"paths": {
"/user": {
"post": {
"tags": [
"user"
],
"summary": "Add a new User to the store",
"description": "",
"operationId": "addUser",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"parameters": [
{
"in": "body",
"name": "body",
"description": "User object that needs to be added to the store",
"required": false,
"schema": {
"$ref": "#/definitions/User"
}
}
],
"responses": {
"405": {
"description": "Invalid input"
}
}
},
"put": {
"tags": [
"user"
],
"summary": "Update an existing User",
"description": "",
"operationId": "updateUser",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"parameters": [
{
"in": "body",
"name": "body",
"description": "User object that needs to be added to the store",
"required": false,
"schema": {
"$ref": "#/definitions/User"
}
}
],
"responses": {
"405": {
"description": "Validation exception"
},
"404": {
"description": "User not found"
},
"400": {
"description": "Invalid ID supplied"
}
}
}
}
},
"definitions": {
"User": {
"type": "object",
"properties": {
"id": {
"type": "integer",
"format": "int64"
},
"userStatus": {
"type": "integer",
"format": "int32",
"description": "User Status"
}
},
"additionalProperties": {
"type": "string"
}
}
}
}