replace invalid characters in generated method names with underscore (#519)

* replace invalid characters in generated method names with underscore

fixes #518
This commit is contained in:
Tom Hombergs
2018-01-12 23:35:03 +01:00
committed by Marcin Grzejszczak
parent 833a7114ab
commit 659545a774
4 changed files with 52 additions and 2 deletions

View File

@@ -61,7 +61,7 @@ class MethodBuilder {
return new MethodBuilder(methodName, stubContent, configProperties, contract.ignored || stubContent.ignored)
}
private static String methodName(ContractMetadata contract, File stubsFile, Contract stubContent) {
static String methodName(ContractMetadata contract, File stubsFile, Contract stubContent) {
if (stubContent.name) {
return NamesUtil.camelCase(NamesUtil.convertIllegalPackageChars(stubContent.name))
} else if (contract.convertedContract.size() > 1) {
@@ -72,7 +72,7 @@ class MethodBuilder {
}
private static String camelCasedMethodFromFileName(File stubsFile) {
return NamesUtil.camelCase(NamesUtil.toLastDot(NamesUtil.afterLast(stubsFile.path, File.separator)))
return NamesUtil.camelCase(NamesUtil.convertIllegalMethodNameChars(NamesUtil.toLastDot(NamesUtil.afterLast(stubsFile.path, File.separator))))
}
/**

View File

@@ -111,4 +111,13 @@ class NamesUtil {
static String convertIllegalPackageChars(String packageName) {
return packageName.replaceAll('[_\\- .+]', '_')
}
/**
* Converts illegal characters in method names to underscores
*/
static String convertIllegalMethodNameChars(String methodName) {
String result = methodName.replaceAll('^[^a-zA-Z_$]', '_')
result = result.replaceAll('[^a-zA-Z_$0-9]', '_')
return result
}
}

View File

@@ -0,0 +1,34 @@
package org.springframework.cloud.contract.verifier.builder
import org.springframework.cloud.contract.spec.Contract
import org.springframework.cloud.contract.verifier.file.ContractMetadata
import spock.lang.Issue
import spock.lang.Specification
class MethodBuilderSpec extends Specification {
@Issue('#518')
def "should map create valid method name from file name containing illegal chars"() {
given:
Contract contractDsl = Contract.make {
request {
method 'GET'
urlPath '/foo'
}
response {
status 200
body(foo: "foo")
headers {
contentType(applicationJson())
}
}
}
ContractMetadata metadata = new ContractMetadata(null, false, 0, null, contractDsl)
when:
File stubFile = new File("5invalid-method:name.groovy")
String methodName = MethodBuilder.methodName(metadata, stubFile, contractDsl)
then:
methodName.equals("_invalid_method_name")
}
}

View File

@@ -104,4 +104,11 @@ class NamesUtilSpec extends Specification {
expect:
NamesUtil.convertIllegalPackageChars(string) == "a_b_c_1_0_x_d1174dd"
}
def "should convert all illegal method chars to legal ones"() {
given:
String string = '10a-b c.1.0.x+d1174$dd'
expect:
NamesUtil.convertIllegalMethodNameChars(string) == '_0a_b_c_1_0_x_d1174$dd'
}
}