/
UrlMappingsUnitTestMixin.groovy
295 lines (263 loc) · 11.5 KB
/
UrlMappingsUnitTestMixin.groovy
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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
/*
* Copyright 2011 SpringSource
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package grails.test.mixin.web
import static junit.framework.Assert.assertEquals
import static junit.framework.Assert.assertNotNull
import junit.framework.AssertionFailedError
import org.codehaus.groovy.grails.commons.ControllerArtefactHandler
import org.codehaus.groovy.grails.commons.GrailsControllerClass
import org.codehaus.groovy.grails.commons.UrlMappingsArtefactHandler
import org.codehaus.groovy.grails.web.mapping.UrlMappingInfo
import org.codehaus.groovy.grails.web.mapping.UrlMappingsHolder
import org.codehaus.groovy.grails.web.mapping.UrlMappingsHolderFactoryBean
import org.codehaus.groovy.grails.web.mapping.filter.UrlMappingsFilter
import org.codehaus.groovy.grails.web.pages.GroovyPagesTemplateEngine
import org.codehaus.groovy.grails.web.util.WebUtils
/**
* A mixin for testing URL mappings in Grails.
*
* @author Luke Daley
* @author Graeme Rocher
*
* @since 2.0
*/
class UrlMappingsUnitTestMixin extends ControllerUnitTestMixin {
private assertionKeys = ["controller", "action", "view"]
/**
* Mocks specific URL mappings class
*
* @param urlMappingsClass The URL mappings class to mock
* @return The UrlMappingsHolder class
*/
UrlMappingsHolder mockUrlMappings(Class urlMappingsClass) {
grailsApplication.addArtefact(UrlMappingsArtefactHandler.TYPE, urlMappingsClass)
defineBeans(true) {
grailsUrlMappingsHolder(UrlMappingsHolderFactoryBean) {
grailsApplication = grailsApplication
servletContext = servletContext
}
}
getUrlMappingsHolder()
}
/**
* @return The {@link UrlMappingsHolder} bean
*/
UrlMappingsHolder getUrlMappingsHolder() {
applicationContext.getBean("grailsUrlMappingsHolder", UrlMappingsHolder)
}
/**
* Maps a URI and returns the appropriate controller instance
*
* @param uri The URI to map
* @return The controller instance
*/
def mapURI(String uri) {
UrlMappingsHolder mappingsHolder = getUrlMappingsHolder()
if (!UrlMappingsFilter.isUriExcluded(mappingsHolder, uri)) {
UrlMappingInfo[] mappingInfos = mappingsHolder.matchAll(uri, request.method)
for (UrlMappingInfo info in mappingInfos) {
def backupParams = new HashMap(webRequest.params)
info.configure(webRequest)
webRequest.params.putAll(backupParams)
if (info.viewName == null && info.URI == null) {
def controller = grailsApplication.getArtefactForFeature(ControllerArtefactHandler.TYPE,
"${WebUtils.SLASH}${info.controllerName}${WebUtils.SLASH}${info.actionName ?: ''}")
if (controller != null) {
return applicationContext.getBean(controller.fullName)
}
}
}
}
}
/**
* asserts a controller exists for the specified name and url
*
* @param controller The controller name
* @param url The url
*/
void assertController(controller, url) {
final controllerClass = getControllerClass(controller)
if (!controllerClass) {
throw new AssertionFailedError("Url mapping assertion for '$url' failed, '$controller' is not a valid controller")
}
}
/**
* Asserts an action exists for the specified controller name, action name and url
*
* @param controller The controller name
* @param action The action name
* @param url The URL
*/
void assertAction(controller, action, url) {
final controllerClass = getControllerClass(controller)
if (!controllerClass?.mapsToURI("/$controller/$action")) {
throw new AssertionFailedError("Url mapping assertion for '$url' failed, '$action' is not a valid action of controller '$controller'")
}
}
/**
* Asserts a view exists for the specified controller name, view name and url
*
* @param controller The controller name
* @param view The view name
* @param url The url
*/
void assertView(controller, view, url) {
def pathPattern = ((controller) ? "$controller/" : "") + "${view}.gsp"
if (!pathPattern.startsWith('/')) {
pathPattern = "/$pathPattern"
}
GroovyPagesTemplateEngine templateEngine = applicationContext.getBean("groovyPagesTemplateEngine", GroovyPagesTemplateEngine)
def t = templateEngine.createTemplate(pathPattern)
if (!t) {
throw new AssertionFailedError(
(controller) ? "Url mapping assertion for '$url' failed, '$view' is not a valid view of controller '$controller'" : "Url mapping assertion for '$url' failed, '$view' is not a valid view")
}
}
/**
* Asserts a URL mapping maps to the controller and action specified by named parameters. Example:
*
* <pre>
* <code>
* assertUrlMapping("/action1", controller: "grailsUrlMappingsTestCaseFake", action: "action1")
* </code>
* </pre>
* @param assertions The assertions as named parameters
* @param url The URL as a string
*/
void assertUrlMapping(Map assertions, url) {
assertUrlMapping(assertions, url, null)
}
/**
* Asserts a URL mapping maps to the controller and action specified by named parameters. Example:
*
* <pre>
* <code>
* assertUrlMapping("/action1", controller: "grailsUrlMappingsTestCaseFake", action: "action1")
* </code>
* </pre>
* @param assertions The assertions as named parameters
* @param url The URL as a string
* @param paramAssertions The parameters to assert defined in the body of the closure
*/
void assertUrlMapping(Map assertions, url, Closure paramAssertions) {
assertForwardUrlMapping(assertions, url, paramAssertions)
if (assertions.controller && !(url instanceof Integer)) {
assertReverseUrlMapping(assertions, url, paramAssertions)
}
}
void assertForwardUrlMapping(assertions, url) {
assertForwardUrlMapping(assertions, url, null)
}
void assertForwardUrlMapping(assertions, url, paramAssertions) {
UrlMappingsHolder mappingsHolder = applicationContext.getBean("grailsUrlMappingsHolder", UrlMappingsHolder)
if (assertions.action && !assertions.controller) {
throw new AssertionFailedError("Cannot assert action for url mapping without asserting controller")
}
if (assertions.controller) assertController(assertions.controller, url)
if (assertions.action) assertAction(assertions.controller, assertions.action, url)
if (assertions.view) assertView(assertions.controller, assertions.view, url)
def mappingInfos
if (url instanceof Integer) {
mappingInfos = []
def mapping = mappingsHolder.matchStatusCode(url)
if (mapping) mappingInfos << mapping
}
else {
mappingInfos = mappingsHolder.matchAll(url)
}
if (mappingInfos.size() == 0) throw new AssertionFailedError("url '$url' did not match any mappings")
def mappingMatched = mappingInfos.any {mapping ->
mapping.configure(webRequest)
for (key in assertionKeys) {
if (assertions.containsKey(key)) {
def expected = assertions[key]
def actual = mapping."${key}Name"
switch (key) {
case "controller":
if (actual && !getControllerClass(actual)) return false
break
case "view":
if (actual[0] == "/") actual = actual.substring(1)
if (expected[0] == "/") expected = expected.substring(1)
break
case "action":
if (key == "action" && actual == null) {
final controllerClass = getControllerClass(assertions.controller)
actual = controllerClass?.defaultAction
}
break
}
assertEquals("Url mapping $key assertion for '$url' failed", expected, actual)
}
}
if (paramAssertions) {
def params = [:]
paramAssertions.delegate = params
paramAssertions.resolveStrategy = Closure.DELEGATE_ONLY
paramAssertions.call()
params.each {name, value ->
assertEquals("Url mapping '$name' parameter assertion for '$url' failed", value, mapping.params[name])
}
}
return true
}
if (!mappingMatched) throw new IllegalArgumentException("url '$url' did not match any mappings")
}
/**
* Asserts the given controller and action produce the given reverse URL mapping
*
* <pre>
* <code>
* assertReverseUrlMapping("/action1", controller: "grailsUrlMappingsTestCaseFake", action: "action1")
* </code>
* </pre>
* @param assertions The assertions as named parameters
* @param url The URL as a string
*/
void assertReverseUrlMapping(Map assertions, url) {
assertReverseUrlMapping(assertions, url, null)
}
/**
* Asserts the given controller and action produce the given reverse URL mapping
*
* <pre>
* <code>
* assertReverseUrlMapping("/action1", controller: "grailsUrlMappingsTestCaseFake", action: "action1")
* </code>
* </pre>
* @param assertions The assertions as named parameters
* @param url The URL as a string
* @param paramAssertions The parameters to assert defined in the body of the closure
*/
void assertReverseUrlMapping(Map assertions, url, Closure paramAssertions) {
UrlMappingsHolder mappingsHolder = applicationContext.getBean("grailsUrlMappingsHolder", UrlMappingsHolder)
def controller = assertions.controller
def action = assertions.action
def params = [:]
if (paramAssertions) {
paramAssertions.delegate = params
paramAssertions.resolveStrategy = Closure.DELEGATE_ONLY
paramAssertions.call()
}
def urlCreator = mappingsHolder.getReverseMapping(controller, action, params)
assertNotNull("could not create reverse mapping of '$url' for {controller = $controller, action = $action, params = $params}", urlCreator)
def createdUrl = urlCreator.createRelativeURL(controller, action, params, "UTF-8")
assertEquals("reverse mapping assertion for {controller = $controller, action = $action, params = $params}", url, createdUrl)
}
private GrailsControllerClass getControllerClass(controller) {
return grailsApplication.getArtefactByLogicalPropertyName(ControllerArtefactHandler.TYPE, controller)
}
}