@Before
  public void before() throws IOException, JDOMException {

    factory = fixture.getFactory();
    fixture.initSystemData();

    StringBuffer standardConfigXml = new StringBuffer();
    standardConfigXml.append("<config name=\"MyContentType\" version=\"1.0\">");
    standardConfigXml.append("     <form>");

    standardConfigXml.append("         <title name=\"myTitle\"/>");

    standardConfigXml.append("         <block name=\"TestBlock1\">");

    standardConfigXml.append(
        "             <input name=\"myTitle\" required=\"true\" type=\"text\">");
    standardConfigXml.append("                 <display>My title</display>");
    standardConfigXml.append("                 <xpath>contentdata/mytitle</xpath>");
    standardConfigXml.append("             </input>");

    standardConfigXml.append("             <input name=\"myBinaryfile\" type=\"uploadfile\">");
    standardConfigXml.append("                 <display>My binaryfile</display>");
    standardConfigXml.append("                 <xpath>contentdata/mybinaryfile</xpath>");
    standardConfigXml.append("             </input>");

    standardConfigXml.append("         </block>");
    standardConfigXml.append("     </form>");
    standardConfigXml.append("</config>");
    standardConfig = XMLDocumentFactory.create(standardConfigXml.toString()).getAsJDOMDocument();

    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setRemoteAddr("127.0.0.1");
    ServletRequestAccessor.setRequest(request);
  }
 @Test
 public void shouldSearchAConceptSourceIfItMatchesTheQuery() throws Exception {
   MockHttpServletRequest req = request(RequestMethod.GET, getURI());
   req.addParameter("q", "ome");
   SimpleObject result = deserialize(handle(req));
   Assert.assertEquals(2, Util.getResultsSize(result));
 }
  public void testRepeatedRequestCatching() throws Exception {
    String event = "theEvent";
    String widgetKey = StandardViewPortWidget.CHILD_KEY;

    adapter = (ServletServiceAdapterComponent) initAdapter("repeatedRequest.xml");
    // lets get reference to the bean doing the heavy-lifting
    // its a singleton, so we're cool
    BeanFactory factory = servlet.getFactory();
    MockViewPortWidget widget = (MockViewPortWidget) factory.getBean("rootWidget");

    req.addParameter(StandardWidget.EVENT_HANDLER_ID_KEY, event);
    req.addParameter(StandardWidgetContainerWidget.EVENT_PATH_KEY, widgetKey);

    // first request, transactionId will get intialized
    adapter.service(req, resp);
    // helper returns true on null transactionId

    MockEventfulStandardWidget child1 =
        (MockEventfulStandardWidget) widget.getChildren().get(widgetKey);
    req.addParameter(
        StandardTransactionFilterWidget.TRANSACTION_ID_KEY, "" + child1.getTransactionId());

    // second request with the valid transactionId
    adapter.service(req, resp);

    assertTrue(child1.getEventProcessed());
    child1.setEventProcessed(false);

    req.addParameter(
        StandardTransactionFilterWidget.TRANSACTION_ID_KEY, "" + child1.getTransactionId());
    adapter.service(req, resp);
    // transactionId used 2nd time, should not process the event
    assertFalse(child1.getEventProcessed());
  }
Example #4
0
  public void testRunWithOnlyFormName() throws Exception {
    MockHttpServletRequest request = constructMockRequest("POST", "/document/validate", WILDCARD);
    request.setContent(("document=").getBytes()); // NOTE: need space between periods.
    MockHttpServletResponse response = invoke(request);

    assertEquals("HTTP status", HttpStatus.OK.getCode(), response.getStatus());
  }
  @Test
  public void resolveViewNameRedirectView() throws Exception {
    request.addHeader("Accept", "application/json");
    request.setRequestURI("/test");

    StaticWebApplicationContext webAppContext = new StaticWebApplicationContext();
    webAppContext.setServletContext(new MockServletContext());
    webAppContext.refresh();

    UrlBasedViewResolver urlViewResolver = new InternalResourceViewResolver();
    urlViewResolver.setApplicationContext(webAppContext);
    ViewResolver xmlViewResolver = createMock(ViewResolver.class);
    viewResolver.setViewResolvers(Arrays.<ViewResolver>asList(xmlViewResolver, urlViewResolver));

    View xmlView = createMock("application_xml", View.class);
    View jsonView = createMock("application_json", View.class);
    viewResolver.setDefaultViews(Arrays.asList(jsonView));

    String viewName = "redirect:anotherTest";
    Locale locale = Locale.ENGLISH;

    expect(xmlViewResolver.resolveViewName(viewName, locale)).andReturn(xmlView);
    expect(jsonView.getContentType()).andReturn("application/json").anyTimes();

    replay(xmlViewResolver, xmlView, jsonView);

    View actualView = viewResolver.resolveViewName(viewName, locale);
    assertEquals("Invalid view", RedirectView.class, actualView.getClass());

    verify(xmlViewResolver, xmlView, jsonView);
  }
  @Test
  public void testPrepareResponse() throws UnknownHostException {
    HttpClientSPIAgent httpClientSPIAgent =
        new HttpClientSPIAgent(
            _spiConfiguration, new MockRegistrationReference(new MockIntraband()));

    MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();

    mockHttpServletRequest.setAttribute(WebKeys.SPI_AGENT_PORTLET, _portlet);

    MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();

    HttpServletResponse httpServletResponse =
        httpClientSPIAgent.prepareResponse(mockHttpServletRequest, mockHttpServletResponse);

    Assert.assertSame(
        mockHttpServletResponse,
        mockHttpServletRequest.getAttribute(WebKeys.SPI_AGENT_ORIGINAL_RESPONSE));
    Assert.assertNotNull(mockHttpServletRequest.getAttribute(WebKeys.SPI_AGENT_RESPONSE));

    Assert.assertSame(BufferCacheServletResponse.class, httpServletResponse.getClass());

    BufferCacheServletResponse bufferCacheServletResponse =
        (BufferCacheServletResponse) httpServletResponse;

    ServletResponse servletResponse = bufferCacheServletResponse.getResponse();

    Assert.assertSame(ReadOnlyServletResponse.class, servletResponse.getClass());

    ReadOnlyServletResponse readOnlyServletResponse = (ReadOnlyServletResponse) servletResponse;

    Assert.assertSame(mockHttpServletResponse, readOnlyServletResponse.getResponse());
  }
  @Test
  public void verifyOKWithState() throws Exception {
    final MockHttpServletRequest mockRequest =
        new MockHttpServletRequest("GET", CONTEXT + OAuthConstants.CALLBACK_AUTHORIZE_URL);
    mockRequest.addParameter(OAuthConstants.TICKET, SERVICE_TICKET);
    final MockHttpSession mockSession = new MockHttpSession();
    mockSession.putValue(OAuthConstants.OAUTH20_CALLBACKURL, REDIRECT_URI);
    mockSession.putValue(OAuthConstants.OAUTH20_SERVICE_NAME, SERVICE_NAME);
    mockSession.putValue(OAuthConstants.OAUTH20_STATE, STATE);
    mockRequest.setSession(mockSession);
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();

    final ModelAndView modelAndView =
        oauth20WrapperController.handleRequest(mockRequest, mockResponse);
    assertEquals(OAuthConstants.CONFIRM_VIEW, modelAndView.getViewName());
    final Map<String, Object> map = modelAndView.getModel();
    assertEquals(SERVICE_NAME, map.get("serviceName"));
    assertEquals(
        REDIRECT_URI
            + "?"
            + OAuthConstants.CODE
            + "="
            + SERVICE_TICKET
            + "&"
            + OAuthConstants.STATE
            + "="
            + STATE,
        map.get("callbackUrl"));
  }
  @Before
  public void setUp() throws IOException {
    MockHttpServletRequest originalRequest = new MockHttpServletRequest();

    Portlet portlet =
        new PortletImpl() {

          @Override
          public String getContextName() {
            return _SERVLET_CONTEXT_NAME;
          }
        };

    originalRequest.setAttribute(WebKeys.SPI_AGENT_PORTLET, portlet);

    HttpSession session = originalRequest.getSession();

    session.setAttribute(_SESSION_ATTRIBUTE_1, _SESSION_ATTRIBUTE_1);
    session.setAttribute(_SESSION_ATTRIBUTE_2, _SESSION_ATTRIBUTE_2);

    _mockHttpServletRequest = new MockHttpServletRequest();

    _mockHttpServletRequest.setAttribute(WebKeys.SPI_AGENT_PORTLET, portlet);
    _mockHttpServletRequest.setAttribute(
        WebKeys.SPI_AGENT_REQUEST, new SPIAgentRequest(originalRequest));

    RequestAttributes.setRequestAttributes(_mockHttpServletRequest);
  }
Example #9
0
    /**
     * Issue a request with the given {@link Method} to the provided resource URI.
     *
     * @param method the http method to use
     * @param resourceUri the uri to issue the request to
     * @return the response to the request
     */
    public MockHttpServletResponse callInternal(Method method, String resourceUri)
        throws Exception {
      MockHttpServletRequest request = super.createRequest(resourceUri);
      request.setMethod(method.getName());

      return dispatch(request, null);
    }
  @Test
  public void testNormalOperationWithDefaultFilterProcessesUrl() throws Exception {
    // Setup our HTTP request
    MockHttpServletRequest request = createMockAuthenticationRequest();
    HttpSession sessionPreAuth = request.getSession();

    // Setup our filter configuration
    MockFilterConfig config = new MockFilterConfig(null, null);

    // Setup our expectation that the filter chain will not be invoked, as we redirect to
    // defaultTargetUrl
    MockFilterChain chain = new MockFilterChain(false);
    MockHttpServletResponse response = new MockHttpServletResponse();

    // Setup our test object, to grant access
    MockAuthenticationFilter filter = new MockAuthenticationFilter(true);

    filter.setFilterProcessesUrl("/j_mock_post");
    filter.setSessionAuthenticationStrategy(mock(SessionAuthenticationStrategy.class));
    filter.setAuthenticationSuccessHandler(successHandler);
    filter.setAuthenticationFailureHandler(failureHandler);
    filter.setAuthenticationManager(mock(AuthenticationManager.class));
    filter.afterPropertiesSet();

    // Test
    filter.doFilter(request, response, chain);
    assertEquals("/mycontext/logged_in.jsp", response.getRedirectedUrl());
    assertNotNull(SecurityContextHolder.getContext().getAuthentication());
    assertEquals(
        "test", SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());
    // Should still have the same session
    assertEquals(sessionPreAuth, request.getSession());
  }
  @Test
  public void testFilterProcessesUrlVariationsRespected() throws Exception {
    // Setup our HTTP request
    MockHttpServletRequest request = createMockAuthenticationRequest();
    request.setServletPath("/j_OTHER_LOCATION");
    request.setRequestURI("/mycontext/j_OTHER_LOCATION");

    // Setup our filter configuration
    MockFilterConfig config = new MockFilterConfig(null, null);

    // Setup our expectation that the filter chain will not be invoked, as we redirect to
    // defaultTargetUrl
    MockFilterChain chain = new MockFilterChain(false);
    MockHttpServletResponse response = new MockHttpServletResponse();

    // Setup our test object, to grant access
    MockAuthenticationFilter filter = new MockAuthenticationFilter(true);
    filter.setFilterProcessesUrl("/j_OTHER_LOCATION");
    filter.setAuthenticationSuccessHandler(successHandler);

    // Test
    filter.doFilter(request, response, chain);
    assertEquals("/mycontext/logged_in.jsp", response.getRedirectedUrl());
    assertNotNull(SecurityContextHolder.getContext().getAuthentication());
    assertEquals(
        "test", SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());
  }
  @Test
  public void testProduces() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest("GET", "/produces");
    request.addHeader("Accept", "application/xml");
    Object handler = this.handlerMapping.getHandler(request).getHandler();

    // See org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping#handleMatch
    assertEquals(
        Collections.singleton(MediaType.APPLICATION_XML),
        request.getAttribute(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE));

    MockHttpServletResponse response = new MockHttpServletResponse();

    this.handlerAdapter.handle(request, response, handler);
    String testResponse = response.getContentAsString();
    assertEquals("<test>XML</test>", testResponse);

    request = new MockHttpServletRequest("GET", "/produces");
    request.addHeader("Accept", "application/json");
    handler = this.handlerMapping.getHandler(request).getHandler();

    // See org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping#handleMatch
    assertNull(
        "Negated expression should not be listed as a producible type",
        request.getAttribute(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE));

    response = new MockHttpServletResponse();

    this.handlerAdapter.handle(request, response, handler);
    testResponse = response.getContentAsString();
    assertEquals("{\"json\":\"body\"}", testResponse);
  }
  @Test
  public void testParams() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest("GET", "/params");
    Object handler = null;
    try {
      handler = this.handlerMapping.getHandler(request);
    } catch (Exception e) {
      // There is no matching handlers and some default handler
      // See
      // org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping#handleNoMatch
      assertTrue(e instanceof UnsatisfiedServletRequestParameterException);
    }

    request = new MockHttpServletRequest("GET", "/params");
    request.addParameter("param1", "1");
    request.addParameter("param2", "1");

    handler = this.handlerMapping.getHandler(request).getHandler();

    MockHttpServletResponse response = new MockHttpServletResponse();

    this.handlerAdapter.handle(request, response, handler);
    String testResponse = response.getContentAsString();
    assertEquals("User=1;account=1", testResponse);

    request = new MockHttpServletRequest("GET", "/params");
    request.addParameter("param1", "1");
    handler = this.handlerMapping.getHandler(request).getHandler();

    response = new MockHttpServletResponse();

    this.handlerAdapter.handle(request, response, handler);
    testResponse = response.getContentAsString();
    assertEquals("User=1", testResponse);
  }
 /**
  * Creates a request from the given parameters.
  *
  * <p>The requestURI is automatically preceded with "/rest/" + RestConstants.VERSION_1.
  *
  * @param method
  * @param requestURI
  * @return
  */
 public MockHttpServletRequest request(RequestMethod method, String requestURI) {
   MockHttpServletRequest request =
       new MockHttpServletRequest(
           method.toString(), "/rest/" + RestConstants.VERSION_1 + "/" + requestURI);
   request.addHeader("content-type", "application/json");
   return request;
 }
  public void testProcess() throws Exception {

    Controller c = (Controller) applicationContext.getBean("peopleController");
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setMethod("POST");
    HttpServletResponse response = new MockHttpServletResponse();

    request.addParameter("importStudents", "Import Students");

    ModelAndView mav =
        c.handleRequest((HttpServletRequest) request, (HttpServletResponse) response);
    Map m = mav.getModel();
    PeopleBacking p = (PeopleBacking) m.get("peopleBacking");

    MockPageContext ctx = new MockPageContext();
    ctx.setAttribute("peopleBacking", mav.getModel().get("peopleBacking"));
    request.setAttribute("peopleBacking", mav.getModel().get("peopleBacking"));

    List<ProcessErrors> errors =
        (List<ProcessErrors>)
            ExpressionEvaluationUtils.evaluate(
                "test", "${peopleBacking.processStudentsErrors}", List.class, ctx);

    for (ProcessErrors e : errors) {
      ctx.setAttribute("processErrors", e);
      log.debug(
          ExpressionEvaluationUtils.evaluate(
              "test", "${processErrors.message}", String.class, ctx));
    }
  }
  @Test
  public void shouldNotAutoRegisterAgentIfKeysDoNotMatch() throws Exception {
    String uuid = "uuid";
    when(goConfigService.hasAgent(uuid)).thenReturn(false);
    ServerConfig serverConfig =
        new ServerConfig("artifacts", new SecurityConfig(), 10, 20, "1", "");
    when(goConfigService.serverConfig()).thenReturn(serverConfig);

    when(agentService.agentUsername(uuid, request.getRemoteAddr(), "host"))
        .thenReturn(new Username("some-agent-login-name"));
    controller.agentRequest(
        "host", uuid, "location", "233232", "osx", "", "", "", "", "", "", false, request);

    verify(agentService)
        .requestRegistration(
            new Username("some-agent-login-name"),
            AgentRuntimeInfo.fromServer(
                new AgentConfig(uuid, "host", request.getRemoteAddr()),
                false,
                "location",
                233232L,
                "osx",
                false));
    verify(goConfigService, never()).updateConfig(any(UpdateConfigCommand.class));
  }
  @AdviseWith(adviceClasses = {PropsUtilAdvice.class})
  @Test
  public void testPrepareRequest() throws Exception {
    PropsUtilAdvice.setProps(
        PropsKeys.INTRABAND_MAILBOX_REAPER_THREAD_ENABLED, Boolean.FALSE.toString());
    PropsUtilAdvice.setProps(
        PropsKeys.INTRABAND_MAILBOX_STORAGE_LIFE, String.valueOf(Long.MAX_VALUE));

    Serializer serializer = new Serializer();

    serializer.writeString(_SERVLET_CONTEXT_NAME);
    serializer.writeObject(new SPIAgentRequest(_mockHttpServletRequest));

    Method depositMailMethod =
        ReflectionUtil.getDeclaredMethod(MailboxUtil.class, "depositMail", ByteBuffer.class);

    long receipt = (Long) depositMailMethod.invoke(null, serializer.toByteBuffer());

    byte[] data = new byte[8];

    BigEndianCodec.putLong(data, 0, receipt);

    HttpClientSPIAgent httpClientSPIAgent =
        new HttpClientSPIAgent(
            _spiConfiguration, new MockRegistrationReference(new MockIntraband()));

    MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();

    mockHttpServletRequest.setContent(data);

    HttpServletRequest httpServletRequest =
        httpClientSPIAgent.prepareRequest(mockHttpServletRequest);

    Assert.assertNotNull(httpServletRequest.getAttribute(WebKeys.SPI_AGENT_REQUEST));
  }
  @Test
  public void testArgumentsMatching() throws Exception {
    MockHttpServletRequest mockHttpServletRequest = createHttpRequest("/foo/hello-world");

    try {
      lookupJSONWebServiceAction(mockHttpServletRequest);

      Assert.fail();
    } catch (RuntimeException re) {
    }

    mockHttpServletRequest =
        createHttpRequest("/foo/hello-world/user-id/173/world-name/Forbidden Planet");

    JSONWebServiceAction jsonWebServiceAction = lookupJSONWebServiceAction(mockHttpServletRequest);

    Assert.assertEquals("Welcome 173 to Forbidden Planet", jsonWebServiceAction.invoke());

    mockHttpServletRequest = createHttpRequest("/foo/hello-world");

    mockHttpServletRequest.setParameter("userId", "371");
    mockHttpServletRequest.setParameter("worldName", "Impossible Planet");

    jsonWebServiceAction = lookupJSONWebServiceAction(mockHttpServletRequest);

    Assert.assertEquals("Welcome 371 to Impossible Planet", jsonWebServiceAction.invoke());

    mockHttpServletRequest = createHttpRequest("/foo/hello-world/user-id/173");

    mockHttpServletRequest.setParameter("worldName", "Impossible Planet");

    jsonWebServiceAction = lookupJSONWebServiceAction(mockHttpServletRequest);

    Assert.assertEquals("Welcome 173 to Impossible Planet", jsonWebServiceAction.invoke());
  }
  // Can't get this to work... again the annoying "HttpMediaTypeNotSupportedException: Content type
  // 'application/json' not supported"
  @Test
  @Ignore
  public void
      updateProposal_UpdatedPackageIsToBeSubmittedWhileExistingIsDraft_ShouldMakeRestCallAndPersistWithStatusSubmitted()
          throws Exception {

    final ProposedConceptPackage proposedConcept = new ProposedConceptPackage();
    proposedConcept.setStatus(PackageStatus.DRAFT);

    final ProposedConceptService cpServiceMock = mock(ProposedConceptService.class);
    when(cpServiceMock.getProposedConceptPackageById(1)).thenReturn(proposedConcept);

    mockStatic(Context.class);
    when(Context.getService(ProposedConceptService.class)).thenReturn(cpServiceMock);

    final RestOperations restOperationsMock = mock(RestOperations.class);
    ReflectionTestUtils.setField(
        controller.getSubmitProposal(), "submissionRestTemplate", restOperationsMock);

    request = new MockHttpServletRequest("PUT", "/cpm/proposals/1");
    request.addHeader("Accept", "application/json");
    request.addHeader("Content-Type", "application/json");
    final String payload =
        "{\"name\":\"test\",\"description\":\"test\",\"email\":\"[email protected]\",\"concepts\":[]}";
    request.setContent(payload.getBytes());

    adapter.handle(request, response, controller);

    verify(restOperationsMock)
        .postForObject(
            "http://localhost:8080/openmrs/ws/cpm/dictionarymanager/proposals",
            new SubmissionDto(),
            SubmissionResponseDto.class);
    assertThat(proposedConcept.getStatus(), equalTo(PackageStatus.SUBMITTED));
  }
  @Test
  public void testDoFilterGzipResponseCompression() throws Exception {
    MockHttpServletRequest request =
        new MockHttpServletRequest(HttpMethod.POST.name(), "http://localhost:8080/gzip");
    request.addHeader(HttpHeaders.ACCEPT_ENCODING, "gzip");

    MockHttpServletResponse response = new MockHttpServletResponse();
    MockFilterChain filterChain =
        new MockFilterChain(
            servlet,
            new GzipServletFilter(),
            new OncePerRequestFilter() {
              @Override
              protected void doFilterInternal(
                  HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
                  throws ServletException, IOException {
                response.getOutputStream().write("Should be compressed".getBytes());
              }
            });
    filterChain.doFilter(request, response);

    ByteArrayOutputStream unzippedStream = new ByteArrayOutputStream();
    StreamUtils.copy(
        new GZIPInputStream(new ByteArrayInputStream(response.getContentAsByteArray())),
        unzippedStream);
    String unzipped = new String(unzippedStream.toByteArray());

    Assert.assertEquals(unzipped, "Should be compressed");
  }
  @Before
  public void setUp() throws Exception {
    MockHttpSession session =
        new MockHttpSession(servletContext) {
          @Override
          public String getId() {
            return "TEST$SESSION";
          }
        };
    MockHttpServletRequest request = new MockHttpServletRequest(servletContext);
    request.setSession(session);
    MockHttpServletResponse response = new MockHttpServletResponse();

    Configuration cfg = new ConfigurationImpl();
    cfg.setGraniteConfig("/WEB-INF/granite/granite-config-spring.xml");
    cfg.setFlexServicesConfig("/WEB-INF/flex/services-config-spring.xml");
    servletContext.setAttribute(ServletGraniteConfig.GRANITE_CONFIG_CONFIGURATION_KEY, cfg);
    GraniteConfig graniteConfig = ServletGraniteConfig.loadConfig(servletContext);
    ServicesConfig servicesConfig = ServletServicesConfig.loadConfig(servletContext);
    HttpGraniteContext.createThreadIntance(
        graniteConfig, servicesConfig, servletContext, request, response);

    springServiceFactory = new SpringServiceFactory();
    springServiceFactory.configure(new XMap("properties"));
    springServiceFactory.setApplicationContext(applicationContext);
  }
  /**
   * @see RadiologyObsFormController#saveObs(HttpServletRequest, HttpServletResponse, String,
   *     RadiologyOrder, Obs Obs, BindingResult)
   */
  @Test
  @Verifies(
      value = "should edit obs with edit reason and complex concept",
      method =
          "saveObs(HttpServletRequest, HttpServletResponse, String, RadiologyOrder, Obs Obs, BindingResult)")
  public void saveObs_ShouldEditObsWithEditReasonAndComplexConcept() {

    MockHttpSession mockSession = new MockHttpSession();
    mockRequest.addParameter("saveObs", "saveObs");
    mockRequest.setSession(mockSession);

    when(obsErrors.hasErrors()).thenReturn(false);
    ConceptComplex concept = new ConceptComplex();
    ConceptDatatype cdt = new ConceptDatatype();
    cdt.setHl7Abbreviation("ED");
    concept.setDatatype(cdt);
    mockObs.setConcept(concept);

    ModelAndView modelAndView =
        radiologyObsFormController.saveObs(
            mockRequest, null, "Test Edit Reason", mockRadiologyOrder, mockObs, obsErrors);

    assertNotNull(mockSession.getAttribute(WebConstants.OPENMRS_MSG_ATTR));
    assertThat((String) mockSession.getAttribute(WebConstants.OPENMRS_MSG_ATTR), is("Obs.saved"));
    assertThat(
        modelAndView.getViewName(),
        is(
            "redirect:"
                + RADIOLOGY_OBS_FORM_URL
                + "orderId="
                + mockRadiologyOrder.getId()
                + "&obsId="
                + mockObs.getId()));
  }
  /**
   * @see RadiologyObsFormController#saveObs(HttpServletRequest, HttpServletResponse, String,
   *     RadiologyOrder, Obs Obs, BindingResult)
   */
  @Test
  @Verifies(
      value = "should return redirecting model and view for not authenticated user",
      method =
          "saveObs(HttpServletRequest, HttpServletResponse, String, RadiologyOrder, Obs Obs, BindingResult)")
  public void saveObs_shouldReturnRedirectingModelAndViewForNotAuthenticatedUser() {

    MockHttpSession mockSession = new MockHttpSession();
    mockRequest.addParameter("saveObs", "saveObs");
    mockRequest.setSession(mockSession);

    when(Context.getAuthenticatedUser()).thenReturn(null);

    ModelAndView modelAndView =
        radiologyObsFormController.saveObs(
            mockRequest, null, "Test Edit Reason", mockRadiologyOrder, mockObs, obsErrors);

    assertThat(
        modelAndView.getViewName(),
        is(
            "redirect:"
                + RADIOLOGY_OBS_FORM_URL
                + "orderId="
                + mockRadiologyOrder.getId()
                + "&obsId="
                + mockObs.getId()));
  }
  /**
   * @see RadiologyObsFormController#voidObs(HttpServletRequest, HttpServletResponse, Order, Obs,
   *     String, String, Obs, BindingResult)
   */
  @Test
  @Verifies(
      value =
          "should void obs for given request, response, orderId, obsId, voidObs, voidReason, and obs",
      method =
          "voidObs(HttpServletRequest, HttpServletResponse, Order, Obs, String, String, Obs, BindingResult)")
  public void voidObs_ShouldVoidObsForGivenRequestResponseOrderIdObsIdVoidObsVoidReasonAndObs() {

    MockHttpSession mockSession = new MockHttpSession();
    mockRequest.addParameter("voidObs", "voidObs");
    mockRequest.setSession(mockSession);

    when(obsErrors.hasErrors()).thenReturn(false);

    ModelAndView modelAndView =
        radiologyObsFormController.voidObs(
            mockRequest, null, mockRadiologyOrder, mockObs, "Test Void Reason");

    assertNotNull(mockSession.getAttribute(WebConstants.OPENMRS_MSG_ATTR));
    assertThat(
        (String) mockSession.getAttribute(WebConstants.OPENMRS_MSG_ATTR),
        is("Obs.voidedSuccessfully"));
    assertThat(
        (String) modelAndView.getViewName(),
        is(
            "redirect:"
                + RADIOLOGY_OBS_FORM_URL
                + "orderId="
                + mockRadiologyOrder.getId()
                + "&obsId="
                + mockObs.getId()));
  }
  /**
   * @see RadiologyObsFormController#unvoidObs(HttpServletRequest, HttpServletResponse, Obs, String)
   */
  @Test
  @Verifies(
      value = "should unvoid voided obs for given request, response and obs",
      method = "unvoidObs(HttpServletRequest, HttpServletResponse, Obs, String)")
  public void unvoidObs_shouldUnvoidVoidedObsForGivenRequestResponseAndObs() {

    MockHttpSession mockSession = new MockHttpSession();
    mockRequest.addParameter("unvoidObs", "unvoidObs");
    mockRequest.setSession(mockSession);
    when(obsErrors.hasErrors()).thenReturn(false);

    mockObs.setVoided(true);

    ModelAndView modelAndView = radiologyObsFormController.unvoidObs(mockRequest, null, mockObs);
    assertThat(
        modelAndView.getViewName(),
        is(
            "redirect:"
                + RADIOLOGY_OBS_FORM_URL
                + "orderId="
                + mockRadiologyOrder.getId()
                + "&obsId="
                + mockObs.getId()));
    assertThat(
        (String) mockSession.getAttribute(WebConstants.OPENMRS_MSG_ATTR),
        is("Obs.unvoidedSuccessfully"));
  }
 protected void extendRequest(MockHttpServletRequest request) {
   super.extendRequest(request);
   request.setAttribute("countries", Country.getCountries());
   request.setAttribute("sexes", getSexes());
   request.setAttribute("other", new TestBean());
   request.setAttribute("names", getNames());
 }
  @Test
  public void verifyOK() throws Exception {
    final MockHttpServletRequest mockRequest =
        new MockHttpServletRequest("GET", CONTEXT + OAuthConstants.ACCESS_TOKEN_URL);
    mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuthConstants.REDIRECT_URI, REDIRECT_URI);
    mockRequest.setParameter(OAuthConstants.CLIENT_SECRET, CLIENT_SECRET);
    mockRequest.setParameter(OAuthConstants.CODE, CODE);
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();

    ((OAuth20WrapperController) oauth20WrapperController)
        .getServicesManager()
        .save(getRegisteredService(REDIRECT_URI, CLIENT_SECRET));

    final Map<String, Object> map = new HashMap<>();
    map.put(NAME, VALUE);
    final List<String> list = Arrays.asList(VALUE, VALUE);
    map.put(NAME2, list);

    final Principal p = org.jasig.cas.authentication.TestUtils.getPrincipal(ID, map);
    final TicketGrantingTicketImpl impl =
        new TicketGrantingTicketImpl(
            TGT_ID,
            org.jasig.cas.authentication.TestUtils.getAuthentication(p),
            new NeverExpiresExpirationPolicy());

    ((OAuth20WrapperController) oauth20WrapperController)
        .getTicketRegistry()
        .addTicket(
            new ServiceTicketImpl(
                CODE,
                impl,
                org.jasig.cas.authentication.TestUtils.getService(),
                false,
                new ExpirationPolicy() {
                  private static final long serialVersionUID = -7321055962209199811L;

                  @Override
                  public boolean isExpired(final TicketState ticketState) {
                    return false;
                  }
                }));

    oauth20WrapperController.handleRequest(mockRequest, mockResponse);

    ((OAuth20WrapperController) oauth20WrapperController).getTicketRegistry().deleteTicket(CODE);

    assertEquals("text/plain", mockResponse.getContentType());
    assertEquals(200, mockResponse.getStatus());
    final String body = mockResponse.getContentAsString();

    assertTrue(
        body.startsWith(
            OAuthConstants.ACCESS_TOKEN + '=' + TGT_ID + '&' + OAuthConstants.EXPIRES + '='));
    // delta = 2 seconds
    final int delta = 2;
    final int timeLeft =
        Integer.parseInt(StringUtils.substringAfter(body, '&' + OAuthConstants.EXPIRES + '='));
    assertTrue(timeLeft >= TIMEOUT - 10 - delta);
  }
 @Test
 public void methodOptionalHeaderWithoutValueAndDefault1() throws Exception {
   MockHttpServletRequest request = new MockHttpServletRequest();
   request.addHeader("header", "headerValue");
   ControllerUtil.sendAndReceive(
       controller, request, "remoteProviderSimple", "method18", null, "headerValue");
 }
 @Test
 public void methodRequiredHeaderWithoutValue() throws Exception {
   MockHttpServletRequest request = new MockHttpServletRequest();
   request.addHeader("header", "headerValue");
   ControllerUtil.sendAndReceive(
       controller, request, "remoteProviderSimple", "method15", a(1, "v"), "1;v;headerValue");
 }
 private ServletRequest prepareServletRequest(
     Object target, NativeWebRequest request, MethodParameter parameter) {
   String modelPrefixName = parameter.getParameterAnnotation(FormModel.class).value();
   HttpServletRequest nativeRequest = (HttpServletRequest) request.getNativeRequest();
   MultipartRequest multipartRequest =
       WebUtils.getNativeRequest(nativeRequest, MultipartRequest.class);
   MockHttpServletRequest mockRequest = null;
   if (multipartRequest != null) {
     MockMultipartHttpServletRequest mockMultipartRequest = new MockMultipartHttpServletRequest();
     for (MultipartFile file : multipartRequest.getFileMap().values()) {
       mockMultipartRequest.addFile(
           new MultipartFileWrapper(getNewParameterName(file.getName(), modelPrefixName), file));
     }
     mockRequest = mockMultipartRequest;
   } else {
     mockRequest = new MockHttpServletRequest();
   }
   for (Entry<String, String> entry : getUriTemplateVariables(request).entrySet()) {
     String parameterName = entry.getKey();
     String value = entry.getValue();
     if (isFormModelAttribute(parameterName, modelPrefixName)) {
       mockRequest.setParameter(getNewParameterName(parameterName, modelPrefixName), value);
     }
   }
   for (Object parameterEntry : nativeRequest.getParameterMap().entrySet()) {
     Entry<String, String[]> entry = (Entry<String, String[]>) parameterEntry;
     String parameterName = entry.getKey();
     String[] value = entry.getValue();
     if (isFormModelAttribute(parameterName, modelPrefixName)) {
       mockRequest.setParameter(getNewParameterName(parameterName, modelPrefixName), value);
     }
   }
   return mockRequest;
 }