GrailsLinkGenerator can't generate relative path in a service (outside/without a request)
- Dominant language
- Groovy
- Stars
- 2.9k
- Forks
- 975
- Avg merge
- 1d 22h
- Merged PRs (30d)
- 92
Description
Thanks in advance for the great work. While I was able to temporally resolve my issue by hard coding a contextPath parameter to the injected grailsLinkGenerator service, the issue remains that during an integration test, the grailsLinkGenerator is unable to produce relative links, which after debugging, is because it can not procure it from a web request. Because the service utilizing *grailsLinkGenerator* is intended to be used in a controller (in production), this may be a non issue, however attempts to use it to produce the url to be requested in an integration test places its execution without a web request, and therefore executes logic which yields an absolute url. In my view, this is only a bug if the *grailsLinkGenerator* ,while designed to be used outside a view, can not be used outside a request, such as in a background job, or integration test, etc. Because I don't know the answer to this question, I file this issue for review. However I do think it would be ideal for it to work everywhere, no matter the context.
```groovy
class ExampleService { // This is called in test spec given: exampleService.examplePath(user)
LinkGenerator grailsLinkGenerator
def examplePath(Map options = [:], User user) {
String path = grailsLinkGenerator.link(mapping: "namedMappingPath",
contextPath:"", //THIS IS REQUIRED OR IT WILL FAIL
absolute: false, params: [team: user.handle])
path
}
}
```
Line *270* expects contextPath to be returned, but never is.
https://github.com/grails/grails-core/blob/72f483b9c3336b5d3ba9289b9ccc80cdf6fb45c0/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/DefaultLinkGenerator.groovy#L267-L284
Line *51* because the request is null, the contextPath returns null.
https://github.com/grails/grails-core/blob/7ab9e47ad805fbeb9433a488dd33f91bef44c0fa/grails-web-common/src/main/groovy/org/grails/web/servlet/mvc/DefaultRequestStateLookupStrategy.java#L49-L55
Contributor guide
Research direction
Start with the referenced lines in DefaultLinkGenerator.groovy around line 270 and DefaultRequestStateLookupStrategy.java around lines 49–55, then reproduce the ExampleService call from an integration test without a web request. Trace how contextPath is selected and define the expected relative-link behavior for that context; done means the example produces a relative path without explicitly supplying contextPath.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- groovy
- Domain
- backend, web-dev
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 42/100