This repository has been archived by the owner on Jul 6, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 58
/
build.gradle
259 lines (197 loc) · 10.1 KB
/
build.gradle
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
ext {
grailsSDKsDir = project.hasProperty('grailsSDKsDir') ? project.property('grailsSDKsDir') : System.properties['user.home'] + '/sdk/grails'
workspace = project.hasProperty('workspace') ? project.property('workspace') : System.properties['java.io.tmpdir']
isTravisBuild = System.getenv().get("TRAVIS") == 'true'
isWindows = System.properties['os.name'].toLowerCase().contains('windows')
}
task acceptanceTest(dependsOn: ":spring-security-oauth2-provider:install") {
description = 'Tests the plugin against a specific version or versions of Grails'
group = 'Verification'
doLast {
List<String> grailsVersions = []
if (project.hasProperty('grailsVersions')) {
grailsVersions = project.property('grailsVersions').tokenize(',')
}
else {
println "Specify versions of Grails to test in a CSV list:\n" +
"gradle acceptanceTest -P grailsVersions=3.0.9,3.0.10"
}
grailsVersions.each { String version ->
println "Starting acceptance tests for Grails ${version}"
String grailsHome = grailsHome(version)
String testProjectName = 'grails_' + version.replaceAll('\\.', '_') + '_spring_security_oauth2_provider_test'
createApp(grailsHome, testProjectName)
String testProjectDir = testProjectDir(testProjectName)
updateBuildScript(testProjectDir)
runQuickstart(grailsHome, testProjectDir)
copyTestResources(grailsHome, testProjectDir, testProjectName)
runTests(grailsHome, testProjectDir)
}
}
}
private void createApp(String grailsHome, String appName) {
File dir = new File(testProjectDir(appName))
GFileUtils.deleteDirectory(dir)
callGrails(grailsHome, workspace, 'create-app', [appName])
}
private void updateBuildScript(String testProjectDir) {
println "Updating build.gradle in ${testProjectDir}"
Project plugin = project(":spring-security-oauth2-provider")
File buildGradle = new File(testProjectDir, 'build.gradle')
String contents = buildGradle.text
contents = contents.replace('compile "org.grails.plugins:scaffolding"', """
compile "org.grails.plugins:scaffolding"
compile '${plugin.group}:${plugin.name}:${plugin.version}'
""")
contents = contents.replace('testCompile "org.grails.plugins:geb"', """
testCompile "org.grails.plugins:geb"
testCompile "org.seleniumhq.selenium:selenium-chrome-driver:2.53.0"
testCompile 'com.codeborne:phantomjsdriver:1.2.1'
testCompile 'org.codehaus.groovy.modules.http-builder:http-builder:0.7.1', {
["commons-logging", "xml-apis", "groovy"].each { exclude module: it }
}
testRuntime "org.apache.httpcomponents:httpclient:4.3.2"
""")
contents = contents + """
tasks.withType(Test) {
testLogging {
events "passed", "skipped", "failed"
}
"""
if (isTravisBuild) {
contents = contents + """
jvmArgs "-XX:MaxPermSize=256m"
maxParallelForks = 2
maxHeapSize = '768m'
forkEvery = 100 // helps when tests leak memory
afterSuite {
System.out.print('.')
System.out.flush()
}
"""
}
contents = contents + """
}
"""
buildGradle.withWriter { it.writeLine contents }
}
private void runQuickstart(String grailsHome, String testProjectDir) {
callGrails(grailsHome, testProjectDir, 's2-quickstart', ['test.oauth2', 'User', 'Role'])
callGrails(grailsHome, testProjectDir, 's2-init-oauth2-provider', ['test.oauth2', 'Client', 'AuthorizationCode', 'AccessToken', 'RefreshToken'])
callGrails(grailsHome, testProjectDir, 's2-init-oauth2-approval', ['test.oauth2', 'UserApproval'])
File applicationGroovy = new File(testProjectDir, 'grails-app/conf/application.groovy')
String contents = applicationGroovy.text
contents = contents.replace('grails.plugin.springsecurity.controllerAnnotations.staticRules = [', """
grails.plugin.springsecurity.controllerAnnotations.staticRules = [
[pattern: '/oauth/authorize', access: "isFullyAuthenticated() and (request.getMethod().equals('GET') or request.getMethod().equals('POST'))"],
[pattern: '/oauth/token', access: "isFullyAuthenticated() and request.getMethod().equals('POST')"],
""")
applicationGroovy.withWriter { it.writeLine contents }
applicationGroovy.withWriterAppend { it.writeLine '''grails.plugin.springsecurity.filterChain.chainMap = [
[pattern: '/oauth/token', filters: 'JOINED_FILTERS,-oauth2ProviderFilter,-securityContextPersistenceFilter,-logoutFilter,-authenticationProcessingFilter,-rememberMeAuthenticationFilter,-exceptionTranslationFilter'],
[pattern: '/securedOAuth2Resources/**', filters: 'JOINED_FILTERS,-securityContextPersistenceFilter,-logoutFilter,-authenticationProcessingFilter,-rememberMeAuthenticationFilter,-oauth2BasicAuthenticationFilter,-exceptionTranslationFilter'],
[pattern: '/**', filters: 'JOINED_FILTERS,-statelessSecurityContextPersistenceFilter,-oauth2ProviderFilter,-clientCredentialsTokenEndpointFilter,-oauth2BasicAuthenticationFilter,-oauth2ExceptionTranslationFilter']
]'''}
}
private void copyTestResources(String grailsHome, String destinationDir, String appName) {
String sourceDir = project(":test-app").projectDir
/* Configuration for HTTP Basic Authentication */
passHttpBasicToIntegrationTestTask(destinationDir)
/* Bootstrap (Client Registration) */
ant.copy file: "$sourceDir/grails-app/init/BootStrap.groovy",
tofile: "$destinationDir/grails-app/init/BootStrap.groovy",
overwrite: true
/* Change the redirect uri to use for registration */
changeRedirectUriConstant(destinationDir, 'grails-app/init/BootStrap.groovy', appName)
/* Controllers */
ant.copydir src: "$sourceDir/grails-app/controllers",
dest: "$destinationDir/grails-app/controllers",
forceoverwrite: true
/* Views */
['logout', 'redirect', 'securedOAuth2Resources'].each { name ->
ant.mkdir dir: "$destinationDir/grails-app/views/$name"
ant.copy file: "$sourceDir/grails-app/views/$name/index.gsp",
tofile: "$destinationDir/grails-app/views/$name/index.gsp",
overwrite: true
}
ant.copy file: "$sourceDir/grails-app/views/index.gsp",
tofile: "$destinationDir/grails-app/views/index.gsp",
overwrite: true
/* Tests */
ant.copydir src: "$sourceDir/src/integration-test",
dest: "$destinationDir/src/integration-test",
forceoverwrite: true
ant.copydir src: "$sourceDir/src/test/groovy/helper",
dest: "$destinationDir/src/test/groovy/helper",
forceoverwrite: true
/* Change redirect uri referenced in tests */
changeRedirectUriConstant(destinationDir, 'src/integration-test/groovy/test/oauth2/AbstractAuthorizationEndpointFunctionalSpec.groovy', appName)
/* Custom TokenEnhancer */
ant.copy file: "$sourceDir/grails-app/conf/spring/resources.groovy",
tofile: "$destinationDir/grails-app/conf/spring/resources.groovy",
overwrite: true
ant.copy file: "$sourceDir/src/main/groovy/test/FooBarTokenEnhancer.groovy",
tofile: "$destinationDir/src/main/groovy/test/FooBarTokenEnhancer.groovy",
overwrite: true
}
private void changeRedirectUriConstant(String projectDir, String path, String appName) {
File file = new File(projectDir, path)
String contents = file.text
String original = "REDIRECT_URI = 'http://localhost:8080/grails-spring-security-oauth2-provider/redirect'"
String replacement = "REDIRECT_URI = 'http://localhost:8080/${appName}/redirect'"
contents = contents.replace(original, replacement)
file.withWriter { it.writeLine contents }
}
private void passHttpBasicToIntegrationTestTask(String projectDir) {
File build = new File(projectDir, "build.gradle")
build.append('\nintegrationTest { systemProperties = ["http.basic": System.getProperty("http.basic")] }\n')
}
private void runTests(String grailsHome, String projectDir) {
callGrails(grailsHome, projectDir, 'test-app')
callGrails(grailsHome, projectDir, 'test-app', ['-Dhttp.basic="true"'])
}
private String grailsHome(String version) {
return grailsSDKsDir + '/' + version
}
private String testProjectDir(String name) {
return workspace + '/' + name
}
// From http://stackoverflow.com/questions/14165517/processbuilder-forwarding-stdout-and-stderr-of-started-processes-without-blocki
// For some reason gradle swallows output even when you use inheritIO on the process builder
private void inheritIO(final InputStream src, final PrintStream dest) {
new Thread(new Runnable() {
public void run() {
Scanner sc = new Scanner(src);
while (sc.hasNextLine()) {
def line = sc.nextLine()
logger.quiet(line)
dest.println(line);
}
}
}).start();
}
private void callGrails(String grailsHome, String projectDir, String action,
List extraArgs = null, boolean ignoreFailure = false) {
StringBuilder commandBuilder = new StringBuilder("${grailsHome}/bin/grails${isWindows?'.bat':''} ${action}")
extraArgs.each { arg ->
commandBuilder.append(" ")
commandBuilder.append(arg)
}
commandBuilder.append(" ")
commandBuilder.append("--stacktrace ")
commandBuilder.append("--debug ")
String command = commandBuilder.toString()
println "Running '$command'"
ProcessBuilder processBuilder = new ProcessBuilder(command.tokenize())
File workingDir = new File(projectDir)
processBuilder.directory(workingDir)
Map<String,String> environment = processBuilder.environment()
environment.put("GRAILS_HOME", grailsHome)
Process process = processBuilder.start()
inheritIO(process.getInputStream(), System.out)
inheritIO(process.getErrorStream(), System.err)
int exitCode = process.waitFor()
if (exitCode && !ignoreFailure) {
throw new GradleException("Received Grails exit code: ${exitCode}")
}
}