Search in sources :

Example 91 with MockServletContext

use of org.springframework.web.testfixture.servlet.MockServletContext in project spring-framework by spring-projects.

the class OpenEntityManagerInViewTests method testOpenEntityManagerInViewFilter.

@Test
public void testOpenEntityManagerInViewFilter() throws Exception {
    given(manager.isOpen()).willReturn(true);
    final EntityManagerFactory factory2 = mock(EntityManagerFactory.class);
    final EntityManager manager2 = mock(EntityManager.class);
    given(factory2.createEntityManager()).willReturn(manager2);
    given(manager2.isOpen()).willReturn(true);
    MockServletContext sc = new MockServletContext();
    StaticWebApplicationContext wac = new StaticWebApplicationContext();
    wac.setServletContext(sc);
    wac.getDefaultListableBeanFactory().registerSingleton("entityManagerFactory", factory);
    wac.getDefaultListableBeanFactory().registerSingleton("myEntityManagerFactory", factory2);
    wac.refresh();
    sc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
    MockHttpServletRequest request = new MockHttpServletRequest(sc);
    MockHttpServletResponse response = new MockHttpServletResponse();
    MockFilterConfig filterConfig = new MockFilterConfig(wac.getServletContext(), "filter");
    MockFilterConfig filterConfig2 = new MockFilterConfig(wac.getServletContext(), "filter2");
    filterConfig2.addInitParameter("entityManagerFactoryBeanName", "myEntityManagerFactory");
    final OpenEntityManagerInViewFilter filter = new OpenEntityManagerInViewFilter();
    filter.init(filterConfig);
    final OpenEntityManagerInViewFilter filter2 = new OpenEntityManagerInViewFilter();
    filter2.init(filterConfig2);
    final FilterChain filterChain = (servletRequest, servletResponse) -> {
        assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue();
        servletRequest.setAttribute("invoked", Boolean.TRUE);
    };
    final FilterChain filterChain2 = (servletRequest, servletResponse) -> {
        assertThat(TransactionSynchronizationManager.hasResource(factory2)).isTrue();
        filter.doFilter(servletRequest, servletResponse, filterChain);
    };
    FilterChain filterChain3 = new PassThroughFilterChain(filter2, filterChain2);
    assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse();
    assertThat(TransactionSynchronizationManager.hasResource(factory2)).isFalse();
    filter2.doFilter(request, response, filterChain3);
    assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse();
    assertThat(TransactionSynchronizationManager.hasResource(factory2)).isFalse();
    assertThat(request.getAttribute("invoked")).isNotNull();
    verify(manager).close();
    verify(manager2).close();
    wac.close();
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) BeforeEach(org.junit.jupiter.api.BeforeEach) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) AsyncWebRequest(org.springframework.web.context.request.async.AsyncWebRequest) StaticWebApplicationContext(org.springframework.web.context.support.StaticWebApplicationContext) Callable(java.util.concurrent.Callable) WebAsyncManager(org.springframework.web.context.request.async.WebAsyncManager) TransactionSynchronizationManager(org.springframework.transaction.support.TransactionSynchronizationManager) ServletWebRequest(org.springframework.web.context.request.ServletWebRequest) MockHttpServletResponse(org.springframework.web.testfixture.servlet.MockHttpServletResponse) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) BDDMockito.given(org.mockito.BDDMockito.given) SimpleAsyncTaskExecutor(org.springframework.core.task.SimpleAsyncTaskExecutor) AsyncEvent(jakarta.servlet.AsyncEvent) StandardServletAsyncWebRequest(org.springframework.web.context.request.async.StandardServletAsyncWebRequest) WebAsyncUtils(org.springframework.web.context.request.async.WebAsyncUtils) MockHttpServletRequest(org.springframework.web.testfixture.servlet.MockHttpServletRequest) FilterChain(jakarta.servlet.FilterChain) WebApplicationContext(org.springframework.web.context.WebApplicationContext) MockFilterConfig(org.springframework.web.testfixture.servlet.MockFilterConfig) Mockito.times(org.mockito.Mockito.times) EntityManagerFactory(jakarta.persistence.EntityManagerFactory) Mockito.verify(org.mockito.Mockito.verify) TimeUnit(java.util.concurrent.TimeUnit) Test(org.junit.jupiter.api.Test) CountDownLatch(java.util.concurrent.CountDownLatch) AfterEach(org.junit.jupiter.api.AfterEach) AsyncListener(jakarta.servlet.AsyncListener) EntityManager(jakarta.persistence.EntityManager) MockAsyncContext(org.springframework.web.testfixture.servlet.MockAsyncContext) PassThroughFilterChain(org.springframework.web.testfixture.servlet.PassThroughFilterChain) Mockito.reset(org.mockito.Mockito.reset) MockServletContext(org.springframework.web.testfixture.servlet.MockServletContext) Mockito.mock(org.mockito.Mockito.mock) EntityManager(jakarta.persistence.EntityManager) MockHttpServletRequest(org.springframework.web.testfixture.servlet.MockHttpServletRequest) EntityManagerFactory(jakarta.persistence.EntityManagerFactory) FilterChain(jakarta.servlet.FilterChain) PassThroughFilterChain(org.springframework.web.testfixture.servlet.PassThroughFilterChain) PassThroughFilterChain(org.springframework.web.testfixture.servlet.PassThroughFilterChain) StaticWebApplicationContext(org.springframework.web.context.support.StaticWebApplicationContext) MockServletContext(org.springframework.web.testfixture.servlet.MockServletContext) MockHttpServletResponse(org.springframework.web.testfixture.servlet.MockHttpServletResponse) MockFilterConfig(org.springframework.web.testfixture.servlet.MockFilterConfig) Test(org.junit.jupiter.api.Test)

Example 92 with MockServletContext

use of org.springframework.web.testfixture.servlet.MockServletContext in project spring-framework by spring-projects.

the class RequestContextListenerTests method requestContextListenerWithSameThreadAndAttributesGone.

@Test
public void requestContextListenerWithSameThreadAndAttributesGone() {
    RequestContextListener listener = new RequestContextListener();
    MockServletContext context = new MockServletContext();
    MockHttpServletRequest request = new MockHttpServletRequest(context);
    request.setAttribute("test", "value");
    assertThat(RequestContextHolder.getRequestAttributes()).isNull();
    listener.requestInitialized(new ServletRequestEvent(context, request));
    assertThat(RequestContextHolder.getRequestAttributes()).isNotNull();
    assertThat(RequestContextHolder.getRequestAttributes().getAttribute("test", RequestAttributes.SCOPE_REQUEST)).isEqualTo("value");
    MockRunnable runnable = new MockRunnable();
    RequestContextHolder.getRequestAttributes().registerDestructionCallback("test", runnable, RequestAttributes.SCOPE_REQUEST);
    request.clearAttributes();
    listener.requestDestroyed(new ServletRequestEvent(context, request));
    assertThat(RequestContextHolder.getRequestAttributes()).isNull();
    assertThat(runnable.wasExecuted()).isTrue();
}
Also used : MockRunnable(org.springframework.core.task.MockRunnable) MockHttpServletRequest(org.springframework.web.testfixture.servlet.MockHttpServletRequest) ServletRequestEvent(jakarta.servlet.ServletRequestEvent) MockServletContext(org.springframework.web.testfixture.servlet.MockServletContext) Test(org.junit.jupiter.api.Test)

Example 93 with MockServletContext

use of org.springframework.web.testfixture.servlet.MockServletContext in project spring-framework by spring-projects.

the class BeanNameUrlHandlerMappingTests method setUp.

@BeforeEach
public void setUp() throws Exception {
    MockServletContext sc = new MockServletContext("");
    wac = new XmlWebApplicationContext();
    wac.setServletContext(sc);
    wac.setConfigLocations(new String[] { CONF });
    wac.refresh();
}
Also used : XmlWebApplicationContext(org.springframework.web.context.support.XmlWebApplicationContext) MockServletContext(org.springframework.web.testfixture.servlet.MockServletContext) BeforeEach(org.junit.jupiter.api.BeforeEach)

Example 94 with MockServletContext

use of org.springframework.web.testfixture.servlet.MockServletContext in project spring-framework by spring-projects.

the class FreeMarkerViewTests method freeMarkerViewResolver.

@Test
public void freeMarkerViewResolver() throws Exception {
    MockServletContext sc = new MockServletContext();
    FreeMarkerConfigurer configurer = new FreeMarkerConfigurer();
    configurer.setConfiguration(new TestConfiguration());
    StaticWebApplicationContext wac = new StaticWebApplicationContext();
    wac.setServletContext(sc);
    wac.getBeanFactory().registerSingleton("configurer", configurer);
    wac.refresh();
    FreeMarkerViewResolver vr = new FreeMarkerViewResolver("prefix_", "_suffix");
    vr.setApplicationContext(wac);
    View view = vr.resolveViewName("test", Locale.CANADA);
    assertThat(view.getClass()).as("Correct view class").isEqualTo(FreeMarkerView.class);
    assertThat(((FreeMarkerView) view).getUrl()).as("Correct URL").isEqualTo("prefix_test_suffix");
    view = vr.resolveViewName("non-existing", Locale.CANADA);
    assertThat(view).isNull();
    view = vr.resolveViewName("redirect:myUrl", Locale.getDefault());
    assertThat(view.getClass()).as("Correct view class").isEqualTo(RedirectView.class);
    assertThat(((RedirectView) view).getUrl()).as("Correct URL").isEqualTo("myUrl");
    view = vr.resolveViewName("forward:myUrl", Locale.getDefault());
    assertThat(view.getClass()).as("Correct view class").isEqualTo(InternalResourceView.class);
    assertThat(((InternalResourceView) view).getUrl()).as("Correct URL").isEqualTo("myUrl");
}
Also used : StaticWebApplicationContext(org.springframework.web.context.support.StaticWebApplicationContext) AbstractView(org.springframework.web.servlet.view.AbstractView) InternalResourceView(org.springframework.web.servlet.view.InternalResourceView) RedirectView(org.springframework.web.servlet.view.RedirectView) View(org.springframework.web.servlet.View) MockServletContext(org.springframework.web.testfixture.servlet.MockServletContext) Test(org.junit.jupiter.api.Test)

Example 95 with MockServletContext

use of org.springframework.web.testfixture.servlet.MockServletContext in project spring-framework by spring-projects.

the class FreeMarkerMacroTests method getMacroOutput.

private String getMacroOutput(String name) throws Exception {
    String macro = fetchMacro(name);
    assertThat(macro).isNotNull();
    FileSystemResource resource = new FileSystemResource(System.getProperty("java.io.tmpdir") + "/tmp.ftl");
    FileCopyUtils.copy("<#import \"spring.ftl\" as spring />\n" + macro, new FileWriter(resource.getPath()));
    DummyMacroRequestContext rc = new DummyMacroRequestContext(request);
    Map<String, String> msgMap = new HashMap<>();
    msgMap.put("hello", "Howdy");
    msgMap.put("world", "Mundo");
    rc.setMessageMap(msgMap);
    Map<String, String> themeMsgMap = new HashMap<>();
    themeMsgMap.put("hello", "Howdy!");
    themeMsgMap.put("world", "Mundo!");
    rc.setThemeMessageMap(themeMsgMap);
    rc.setContextPath("/springtest");
    TestBean darren = new TestBean("Darren", 99);
    TestBean fred = new TestBean("Fred");
    fred.setJedi(true);
    darren.setSpouse(fred);
    darren.setJedi(true);
    darren.setStringArray(new String[] { "John", "Fred" });
    request.setAttribute("command", darren);
    Map<String, String> names = new HashMap<>();
    names.put("Darren", "Darren Davison");
    names.put("John", "John Doe");
    names.put("Fred", "Fred Bloggs");
    names.put("Rob&Harrop", "Rob Harrop");
    Configuration config = fc.getConfiguration();
    Map<String, Object> model = new HashMap<>();
    model.put("command", darren);
    model.put(AbstractTemplateView.SPRING_MACRO_REQUEST_CONTEXT_ATTRIBUTE, rc);
    model.put("msgArgs", new Object[] { "World" });
    model.put("nameOptionMap", names);
    model.put("options", names.values());
    FreeMarkerView view = new FreeMarkerView();
    view.setBeanName("myView");
    view.setUrl("tmp.ftl");
    view.setExposeSpringMacroHelpers(false);
    view.setConfiguration(config);
    view.setServletContext(new MockServletContext());
    view.render(model, request, response);
    // tokenize output and ignore whitespace
    String output = response.getContentAsString();
    output = output.replace("\r\n", "\n");
    return output.trim();
}
Also used : Configuration(freemarker.template.Configuration) HashMap(java.util.HashMap) TestBean(org.springframework.beans.testfixture.beans.TestBean) FileWriter(java.io.FileWriter) DummyMacroRequestContext(org.springframework.web.servlet.view.DummyMacroRequestContext) FileSystemResource(org.springframework.core.io.FileSystemResource) MockServletContext(org.springframework.web.testfixture.servlet.MockServletContext)

Aggregations

MockServletContext (org.springframework.web.testfixture.servlet.MockServletContext)138 Test (org.junit.jupiter.api.Test)112 MockHttpServletRequest (org.springframework.web.testfixture.servlet.MockHttpServletRequest)44 MockHttpServletResponse (org.springframework.web.testfixture.servlet.MockHttpServletResponse)38 StaticWebApplicationContext (org.springframework.web.context.support.StaticWebApplicationContext)24 ServletContext (jakarta.servlet.ServletContext)22 ServletContextEvent (jakarta.servlet.ServletContextEvent)21 BeforeEach (org.junit.jupiter.api.BeforeEach)17 WebApplicationContext (org.springframework.web.context.WebApplicationContext)17 MockFilterConfig (org.springframework.web.testfixture.servlet.MockFilterConfig)14 MockServletConfig (org.springframework.web.testfixture.servlet.MockServletConfig)13 Resource (org.springframework.core.io.Resource)12 XmlWebApplicationContext (org.springframework.web.context.support.XmlWebApplicationContext)12 HashMap (java.util.HashMap)11 AnnotationConfigWebApplicationContext (org.springframework.web.context.support.AnnotationConfigWebApplicationContext)11 ServletContextAwareProcessor (org.springframework.web.context.support.ServletContextAwareProcessor)10 TestBean (org.springframework.beans.testfixture.beans.TestBean)9 ClassPathResource (org.springframework.core.io.ClassPathResource)9 SimpleWebApplicationContext (org.springframework.web.servlet.SimpleWebApplicationContext)9 HttpServletResponse (jakarta.servlet.http.HttpServletResponse)7