Showing posts with label Request Mocking In Grails. Show all posts
Showing posts with label Request Mocking In Grails. Show all posts

Thursday, January 2, 2020

Request Mocking In Grails For Back-end/Background Threads | Mock Request With Session

Request Mocking In Grails For Back-end/Background Threads | Mock Request With Session

package com.pkm.util

import grails.gsp.PageRenderer
import grails.util.Holders
import org.codehaus.groovy.grails.web.servlet.mvc.GrailsHttpSession
import org.codehaus.groovy.grails.web.servlet.mvc.GrailsWebRequest
import org.springframework.web.context.request.RequestContextHolder

import javax.servlet.ServletContext
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpSession
/**
 * Created by pritom on 16/08/2017.
 */
class HibernateRequestUtils {
    static GrailsWebRequest getRequest() {
        return RequestContextHolder.getRequestAttributes()
    }

    static HttpSession getSession() {
        return request?.session
    }

    static void setValueToSession(String key, def value) {
        session.putAt(key, value)
    }

    static def getValueFromSession(String key) {
        return session.getAt(key)
    }

    static boolean isBound() {
        HttpServletRequest.isBound()
    }

    static boolean hasSession() {
        session != null
    }

    static def mock(Closure closure = null) {
        return HttpServletRequest.mock(closure)
    }

    static {
        HttpServletRequest.metaClass.static.with {
            isBound = {
                RequestContextHolder.requestAttributes != null
            }
            mock = { closure = null ->
                HttpServletRequest _request = PageRenderer.PageRenderRequestCreator.createInstance("/page/dummy")
                _request.IS_DUMMY = true
                _request."javax.servlet.include.servlet_path" = "/page/dummy.dispatch"
                GrailsWebRequest webRequest = new GrailsWebRequest(
                        _request,
                        PageRenderer.PageRenderResponseCreator.createInstance(new PrintWriter(new StringWriter())),
                        Holders.servletContext
                ) {
                    private MockedHttpSession _session

                    MockedHttpSession getSession() {
                        if (this._session == null) {
                            this._session = new MockedHttpSession()
                        }
                        return this._session
                    }
                }
                RequestContextHolder.setRequestAttributes(webRequest)
                if (closure) {
                    def returned = closure()
                    RequestContextHolder.resetRequestAttributes()
                    return returned
                }
                return webRequest
            }
        }
    }
}

class MockedHttpSession extends GrailsHttpSession {
    MockedHttpSession() {
        super(null)
    }

    private LinkedHashMap attributes = [:]

    Object getAttribute(String name) {
        attributes[name]
    }

    Enumeration getAttributeNames() {
        Collections.enumeration(attributes.keySet())
    }

    long getCreationTime() {
        0
    }

    long getLastAccessedTime() {
        0
    }

    int getMaxInactiveInterval() {
        0
    }

    ServletContext getServletContext() {
        return Holders.servletContext
    }

    @Deprecated
    String[] getValueNames() {
        [] as String[]
    }

    @Deprecated
    void putValue(String name, Object value) {}

    @Deprecated
    void removeValue(String name) {}

    void invalidate() {}

    boolean isNew() {true}

    void removeAttribute(String name) {
        attributes.remove(name)
    }

    void setAttribute(String name, Object value) {
        attributes[name] = value
    }

    void setMaxInactiveInterval(int arg0) {}
}


And use be like below:


if (HibernateRequestUtils.isBound()) {
    DO YOU CODE IN HTTP REQUEST
}
else {
    HibernateRequestUtils.mock {
        DO YOUR CODE IN MOCK REQUEST AS YOU DO IN REAL REQUEST
    }
}



Saturday, July 5, 2014

Request Mocking In Grails For Back-end/Background Threads


import javax.servlet.http.HttpServletRequest
import org.springframework.web.context.request.RequestContextHolder
import org.codehaus.groovy.grails.web.context.ServletContextHolder
import org.springframework.web.context.support.WebApplicationContextUtils

def getRequest() {
    def webRequest = RequestContextHolder.getRequestAttributes();
    if(!webRequest) {
        def servletContext  = ServletContextHolder.getServletContext();
        def applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
        webRequest = grails.util.GrailsWebUtil.bindMockWebRequest(applicationContext);
    }
    return webRequest.request;
}


This code can broke while working on a WAR environment. The problem was that the 
MockWebRequest class was part of the org.springframework:org.springframework.test:3.0.3.RELEASE jar 
and had to be included in the BuildConfig.groovy as

dependencies {
    runtime 'org.springframework:org.springframework.test:3.0.3.RELEASE'
}

Ensure that the line:

mavenCentral()


is not commented in BuildConfig.groovy

https://drive.google.com/file/d/0B5nZNPW48dpFd3U2UG9DMmVsX28/edit?usp=sharing