Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Headers disappear in integration test on REST service

I have an integration test in my Grails 3.2.2 application that is supposed to check that CORS support is operational. When I start the application and use something like Paw or Postman to do a request, the breakpoint I have set in CorsFilter shows that my headers are set properly. But when I do the same request from an integration test using RestBuilder with the following code:

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
}

The breakpoint in CorsFilter shows that both headers are null:

enter image description here

And the weird thing is that when I put a breakpoint in RestTemplate, right before the request is executed, the headers are there:

enter image description here

I don't get how those headers can disappear. Any idea?

like image 562
Sebastien Avatar asked Nov 15 '16 13:11

Sebastien


1 Answers

I was working on this problem problem recently, and while I don't know where RestBuilder is suppressing the Origin header, I did come up with a workaround for testing that grails' CORS support is operating as configured: using HTTPBuilder instead of RestBuilder to invoke the service.

After adding org.codehaus.groovy.modules.http-builder:http-builder:0.7.1 as a testCompile dependency in build.gradle, and with grails.cors.allowedOrigins set to http://localhost, the following tests both worked as desired:

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
    }
}
like image 194
Wes Price Avatar answered Sep 25 '22 00:09

Wes Price