Groovy Tip: Accessing Pattern Matcher instance Used in Switch Case Statements

Groovy allows you to use regular expression patterns in the switch case statements

doMatch '2'
doMatch 'a1'
def doMatch(s) {
    switch(s) {
        case ~/\d/:
            println 'a digit'
        case ~/.*\d/:
            println 'ends with a digit'

But what if you needed access to the underlying matcher instance that was used to do the pattern matching. Is there any magic symbol (‘$’, ‘#’, ‘$$’, ‘##’, ….) that gives you handle to that matcher in Groovy?

The short answer is: No.

The longer answer is: Yes, and here is how you can do it:

import java.util.regex.Matcher
def s = 'tracking_level_9'
switch(s) {
    case ~/tracking_level_(\d)/:
        def m = Matcher.lastMatcher
        println m[0][1]
        assert '9' == m[0][1]

Hope it helps some time.

Grails: Functional Testing a File Upload using HTTPBuilder / Spock

Let’s continue a bit more on the previous post and see how can we do functional testing of the same file-upload feature using HTTPBuilder and Spock libraries.

It needs to be a functional test and not an integration test, because for Grails integration tests, there is no real HTTP layer that comes in the picture to separate the HTTP client requests from your Grails application on the server. Functional tests allow us to hit the application to do the file upload, as normal users of the application would – going through the various layers of the application, verifying on the way various other things like security, URL mappings, etc, etc. How much more real and useful, the testing can get!🙂

Although HTTPBuilder usually makes such testing a piece of cake, when it comes to making multipart/form-data requests, there is no direct support in it I could find. After searching here and there, I found that it is, eventually, fairly easy to plug-in a multipart entity in a HTTPBuilder post request, as shown in the example below.

Note: You need to additionally use the HTTPMime module of Apache HTTPComponents project.

import static


import javax.servlet.http.HttpServletResponse

import org.apache.http.entity.mime.MultipartEntity
import org.apache.http.entity.mime.content.FileBody

import spock.lang.Specification

class FileUploadSpec extends Specification
    def baseUrl = 'http://localhost:8080/<yourapp>' // your app URL
    def 'upload image'()
        when: 'uploading image'
        def imageType = 'image/jpeg'
        def imgFile = new File('<path to some existing image file>')
        assert imgFile.exists()

        def cbFile = new FileBody(imgFile, imageType)

        def http = new HTTPBuilder(baseUrl)
        http.auth.basic '<login id>', '<password>' // login credentials
        resp = http.request(POST) { req ->
            uri.path = 'user' // controller that recieves the file upload post request
            def mpEntity = new MultipartEntity()
            mpEntity.addPart("profileImg", cbFile)
            req.entity = mpEntity
        then: 'there was no problem faced'
        resp.status == HttpServletResponse.SC_OK

That’s it. Simple, isn’t it?🙂

Grails: Mock Testing a File Upload

Here is a quick note on how to mock test a file upload feature in a Grails application (credits: Luke Daley). A little trick is needed here because by default in the unit tests, Grails will only give you an instance of MockHttpServletRequest as the request and that does not have any support for multipart/form-data.

But, hey, you are using the ultra-dynamic Groovy language underneath. How difficult could it be to turn Grails’ arm a bit to make it give you a multipart http request instead (MockMultipartHttpServletRequest)!

Here is how you can do it:

import org.springframework.mock.web.MockMultipartFile
import org.springframework.mock.web.MockMultipartHttpServletRequest

class FileUploadControllerTests extends grails.test.ControllerUnitTestCase
    void testFileUpload()
        def imgContentType = 'image/jpeg'
        def imgContentBytes = '123' as byte[]
        controller.metaClass.request = new MockMultipartHttpServletRequest()
            new MockMultipartFile('image', 'myImage.jpg', imgContentType, imgContentBytes)

        assertEquals HttpServletResponse.SC_OK, controller.response.status

Article “Introduction to Groovy++” in GroovyMag Feb 2011 issue

My first ever article in a technical magazine – “Introduction to Groovy++” in GroovyMag’s latest issue (Feb, 2011) – better late than never!🙂

I got a free issue coupon code too – qduourl – it is supposed to be valid for some 20-odd downloads – one first come, first serve basis. So, anyone interested, please use it.

Hope there will be more write-ups and more coupon codes.🙂