Seb*_*ien 9 testing rest grails spring
我在我的Grails 3.2.2应用程序中进行了集成测试,该测试应该检查CORS支持是否正常运行.当我启动应用程序并使用Paw或Postman之类的东西来执行请求时,我在CorsFilter中设置的断点显示我的标题设置正确.但是,当我使用RestBuilder进行集成测试时,使用以下代码执行相同的请求:
void "Test request http OPTIONS"() {
given: "JSON content request"
when: "OPTIONS are requested"
def rest = new RestBuilder()
def optionsUrl = url(path)
def resp = rest.options(optionsUrl) {
header 'Origin', 'http://localhost:4200'
header 'Access-Control-Request-Method', 'GET'
}
then: "they are returned"
resp.status == HttpStatus.SC_OK
!resp.json
}
Run Code Online (Sandbox Code Playgroud)
CorsFilter中的断点显示两个标头都为空:
奇怪的是,当我在RestTemplate中放置一个断点时,就在请求执行之前,标题就在那里:
我不明白这些标题会如何消失.任何的想法?
小智 2
我最近正在解决这个问题,虽然我不知道 RestBuilder 在哪里抑制 Origin 标头,但我确实想出了一个解决方法来测试 grails 的 CORS 支持是否按配置运行:使用 HTTPBuilder 而不是 RestBuilder 来调用服务。
在 中添加org.codehaus.groovy.modules.http-builder:http-builder:0.7.1
为 testCompile 依赖项build.gradle
并grails.cors.allowedOrigins
设置为后http://localhost
,以下测试均按预期工作:
import geb.spock.GebSpec
import grails.test.mixin.integration.Integration
import groovyx.net.http.HTTPBuilder
import groovyx.net.http.HttpResponseException
import groovyx.net.http.Method
@Integration
class ExampleSpec extends GebSpec {
def 'verify that explicit, allowed origin works'() {
when:
def http = new HTTPBuilder("http://localhost:${serverPort}/todo/1")
def result = http.request(Method.GET, "application/json") { req ->
headers.'Origin' = "http://localhost"
}
then:
result.id == 1
result.name == "task 1.1"
}
def 'verify that explicit, disallowed origin is disallowed'() {
when:
def http = new HTTPBuilder("http://localhost:${serverPort}/todo/1")
http.request(Method.GET, "application/json") { req ->
headers.'Origin' = "http://foobar.com"
}
then:
HttpResponseException e = thrown()
e.statusCode == 403
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
431 次 |
最近记录: |