/**
   * @see RadiologyObsFormController#saveObs(HttpServletRequest, HttpServletResponse, String,
   *     RadiologyOrder, Obs Obs, BindingResult)
   */
  @Test
  @Verifies(
      value = "should populate model and view with obs occuring thrown APIException",
      method =
          "saveObs(HttpServletRequest, HttpServletResponse, String, RadiologyOrder, Obs Obs, BindingResult)")
  public void saveObs_ShouldPopulateModelAndViewWithObsOccuringThrownAPIException()
      throws Exception {

    MockHttpSession mockSession = new MockHttpSession();
    MockMultipartHttpServletRequest mockRequest = new MockMultipartHttpServletRequest();
    mockRequest.addParameter("editReason", "Test Edit Reason");
    mockRequest.setSession(mockSession);

    when(obsErrors.hasErrors()).thenReturn(false);
    mockObs.setConcept(new Concept());
    final String fileName = "test.txt";
    final byte[] content = "Hello World".getBytes();
    MockMultipartFile mockMultipartFile =
        new MockMultipartFile("complexDataFile", fileName, "text/plain", content);

    mockRequest.addFile(mockMultipartFile);
    APIException apiException = new APIException("Test Exception Handling");
    when(obsService.saveObs(mockObs, "Test Edit Reason")).thenThrow(apiException);
    ModelAndView modelAndView =
        radiologyObsFormController.saveObs(
            mockRequest, null, "Test Edit Reason", mockRadiologyOrder, mockObs, obsErrors);
    assertThat(modelAndView.getViewName(), is("module/radiology/radiologyObsForm"));
    assertNotNull(modelAndView);

    assertThat(modelAndView.getModelMap(), hasKey("obs"));
    Obs obs = (Obs) modelAndView.getModelMap().get("obs");
    assertThat(obs, is(mockObs));
  }
  @Test
  public void testUsingRegexQueryWithOptions() throws Exception {

    template.remove(new Query(), PersonWithIdPropertyOfTypeObjectId.class);

    PersonWithIdPropertyOfTypeObjectId p1 = new PersonWithIdPropertyOfTypeObjectId();
    p1.setFirstName("Sven");
    p1.setAge(11);
    template.insert(p1);
    PersonWithIdPropertyOfTypeObjectId p2 = new PersonWithIdPropertyOfTypeObjectId();
    p2.setFirstName("Mary");
    p2.setAge(21);
    template.insert(p2);
    PersonWithIdPropertyOfTypeObjectId p3 = new PersonWithIdPropertyOfTypeObjectId();
    p3.setFirstName("Ann");
    p3.setAge(31);
    template.insert(p3);
    PersonWithIdPropertyOfTypeObjectId p4 = new PersonWithIdPropertyOfTypeObjectId();
    p4.setFirstName("samantha");
    p4.setAge(41);
    template.insert(p4);

    Query q1 = new Query(Criteria.where("firstName").regex("S.*"));
    List<PersonWithIdPropertyOfTypeObjectId> results1 =
        template.find(q1, PersonWithIdPropertyOfTypeObjectId.class);
    Query q2 = new Query(Criteria.where("firstName").regex("S.*", "i"));
    List<PersonWithIdPropertyOfTypeObjectId> results2 =
        template.find(q2, PersonWithIdPropertyOfTypeObjectId.class);
    assertThat(results1.size(), is(1));
    assertThat(results2.size(), is(2));
  }
  @Test
  public void testUsingUpdateWithMultipleSet() throws Exception {

    template.remove(new Query(), PersonWithIdPropertyOfTypeObjectId.class);

    PersonWithIdPropertyOfTypeObjectId p1 = new PersonWithIdPropertyOfTypeObjectId();
    p1.setFirstName("Sven");
    p1.setAge(11);
    template.insert(p1);
    PersonWithIdPropertyOfTypeObjectId p2 = new PersonWithIdPropertyOfTypeObjectId();
    p2.setFirstName("Mary");
    p2.setAge(21);
    template.insert(p2);

    Update u = new Update().set("firstName", "Bob").set("age", 10);

    WriteResult wr = template.updateMulti(new Query(), u, PersonWithIdPropertyOfTypeObjectId.class);

    assertThat(wr.getN(), is(2));

    Query q1 = new Query(Criteria.where("age").in(11, 21));
    List<PersonWithIdPropertyOfTypeObjectId> r1 =
        template.find(q1, PersonWithIdPropertyOfTypeObjectId.class);
    assertThat(r1.size(), is(0));
    Query q2 = new Query(Criteria.where("age").is(10));
    List<PersonWithIdPropertyOfTypeObjectId> r2 =
        template.find(q2, PersonWithIdPropertyOfTypeObjectId.class);
    assertThat(r2.size(), is(2));
    for (PersonWithIdPropertyOfTypeObjectId p : r2) {
      assertThat(p.getAge(), is(10));
      assertThat(p.getFirstName(), is("Bob"));
    }
  }
Esempio n. 4
0
 /** @throws Exception */
 @Test
 public void allocateIdWithParentKey() throws Exception {
   Key parentKey = KeyFactory.createKey("Parent", 1);
   Key key = DatastoreUtil.allocateId(ds, parentKey, "Child");
   assertThat(key, is(notNullValue()));
   assertThat(key.isComplete(), is(true));
 }
Esempio n. 5
0
 /** @throws Exception */
 @Test
 public void allocateIdsAsyncWithParentKey() throws Exception {
   Key parentKey = KeyFactory.createKey("Parent", 1);
   Future<KeyRange> future = DatastoreUtil.allocateIdsAsync(ds, parentKey, "Child", 2);
   assertThat(future, is(notNullValue()));
   assertThat(future.get().getSize(), is(2L));
 }
Esempio n. 6
0
 @Test
 public void firstCategoryAttributeFromJava() throws Exception {
   Node node = with(XML).get("shopping.category[0]");
   assertThat(node.getAttribute("@type"), equalTo("groceries"));
   assertThat(node.getAttribute("type"), equalTo("groceries"));
   assertThat((String) node.get("@type"), equalTo("groceries"));
 }
Esempio n. 7
0
  @Test
  @Graph(
      nodes = {
        @NODE(
            name = "I",
            properties = {
              @PROP(key = "prop", value = "Hello", type = GraphDescription.PropType.STRING)
            }),
        @NODE(name = "you")
      },
      relationships = {
        @REL(
            start = "I",
            end = "him",
            type = "know",
            properties = {
              @PROP(key = "prop", value = "World", type = GraphDescription.PropType.STRING)
            })
      })
  public void nodes_are_represented_as_nodes() throws Exception {
    data.get();
    String script = "START n = node(%I%) MATCH n-[r]->() RETURN n, r";

    String response = cypherRestCall(script, Status.OK);

    assertThat(response, containsString("Hello"));
    assertThat(response, containsString("World"));
  }
 @Test
 public void catMoreTextThanFitsInSingleBufferReceivedOnStdout() throws Exception {
   ProcessExecutorParams params;
   if (Platform.detect() == Platform.WINDOWS) {
     params =
         ProcessExecutorParams.ofCommand(
             "python", "-c", "import sys, shutil; shutil.copyfileobj(sys.stdin, sys.stdout)");
   } else {
     params = ProcessExecutorParams.ofCommand("cat");
   }
   ListeningProcessExecutor executor = new ListeningProcessExecutor();
   StringBuilder sb = new StringBuilder();
   // Use a 3 byte Unicode sequence to ensure writes go across byte buffer
   // boundaries, and append it as many times as needed to ensure it doesn't
   // fit in a single I/O buffer.
   String threeByteUTF8 = "\u2764";
   for (int i = 0; i < ListeningProcessExecutor.LaunchedProcess.BUFFER_CAPACITY + 1; i++) {
     sb.append(threeByteUTF8);
   }
   sb.append(String.format("%n"));
   String longString = sb.toString();
   StdinWritingListener listener = new StdinWritingListener(longString);
   ListeningProcessExecutor.LaunchedProcess process = executor.launchProcess(params, listener);
   process.wantWrite();
   int returnCode = executor.waitForProcess(process);
   assertThat(returnCode, equalTo(0));
   assertThat(listener.capturedStdout.toString("UTF-8"), equalTo(longString));
   assertThat(listener.capturedStderr.toString("UTF-8"), is(emptyString()));
 }
  /** See issue #50 */
  @Test
  public void testOutOfBoundsDate() {
    Patient p = new Patient();
    p.setBirthDate(new DateDt("2000-15-31"));

    String encoded = ourCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(p);
    ourLog.info(encoded);

    assertThat(encoded, StringContains.containsString("2000-15-31"));

    p = ourCtx.newXmlParser().parseResource(Patient.class, encoded);
    assertEquals("2000-15-31", p.getBirthDateElement().getValueAsString());
    assertEquals("2001-03-31", new SimpleDateFormat("yyyy-MM-dd").format(p.getBirthDate()));

    ValidationResult result = ourCtx.newValidator().validateWithResult(p);
    String resultString =
        ourCtx
            .newXmlParser()
            .setPrettyPrint(true)
            .encodeResourceToString(result.toOperationOutcome());
    ourLog.info(resultString);

    assertEquals(2, ((OperationOutcome) result.toOperationOutcome()).getIssue().size());
    assertThat(resultString, StringContains.containsString("2000-15-31"));
  }
  @Test
  public void shouldIncludeCause() throws Exception {
    // Given
    ExceptionRepresentation rep =
        new ExceptionRepresentation(
            new RuntimeException(
                "Hoho", new RuntimeException("Haha", new RuntimeException("HAHA!"))));

    Map<String, Object> output = new HashMap<String, Object>();
    MappingSerializer serializer =
        new MappingSerializer(
            new MapWrappingWriter(output), URI.create(""), mock(ExtensionInjector.class));

    // When
    rep.serialize(serializer);

    // Then
    assertThat(output.containsKey("cause"), is(true));
    assertThat(output.get("cause"), is(Map.class));
    assertThat((String) ((Map<String, Object>) output.get("cause")).get("message"), is("Haha"));
    assertThat(((Map<String, Object>) output.get("cause")).get("cause"), is(Map.class));
    assertThat(
        (String)
            ((Map<String, Object>) ((Map<String, Object>) output.get("cause")).get("cause"))
                .get("message"),
        is("HAHA!"));
  }
  @Test
  public void testCollectLanguages() throws Exception {

    // given
    List<RepositoryWrapper> repos =
        asList( //
            repo("C", 30, "Go", 15, "Java", 4), //
            repo("C", 30, "Go", 15, "Java", 4), //
            repo("Java", 2));
    // when
    List<Language> langs = new ArrayList<>(task.collectLanguages(org(repos)));

    // then
    assertThat(langs, hasSize(3));
    sort(langs, (p1, p2) -> p1.getName().compareTo(p2.getName()));

    assertThat(langs.get(0).getName(), equalTo("C"));
    assertThat(langs.get(0).getProjectsCount(), equalTo(2));
    assertThat(langs.get(0).getPercentage(), equalTo(60));

    assertThat(langs.get(1).getName(), equalTo("Go"));
    assertThat(langs.get(1).getProjectsCount(), equalTo(2));
    assertThat(langs.get(1).getPercentage(), equalTo(30));

    assertThat(langs.get(2).getName(), equalTo("Java"));
    assertThat(langs.get(2).getProjectsCount(), equalTo(3));
    assertThat(langs.get(2).getPercentage(), equalTo(10));
  }
 @Test
 public void providesAnAntBuilderFactory() {
   assertThat(registry.getFactory(AntBuilder.class), instanceOf(DefaultAntBuilderFactory.class));
   assertThat(
       registry.getFactory(AntBuilder.class),
       sameInstance((Object) registry.getFactory(AntBuilder.class)));
 }
  @Test
  public void getResourceStream() throws Exception {
    String text = readText(velocityLoader.getResourceStream("test.vm"));
    assertEquals("test", text);

    text = readText(velocityLoader.getResourceStream("test2.vm"));
    assertEquals("test2", text);

    // 模板名为空
    try {
      velocityLoader.getResourceStream(null);
      fail();
    } catch (org.apache.velocity.exception.ResourceNotFoundException e) {
      assertThat(e, exception("Need to specify a template name"));
    }

    // 模板不存在
    try {
      velocityLoader.getResourceStream("notExist.vm");
      fail();
    } catch (org.apache.velocity.exception.ResourceNotFoundException e) {
      assertThat(
          e, exception("SpringResourceLoaderAdapter", "could not find template: notExist.vm"));
    }
  }
  /** @see RadiologyObsFormController#updateReadingPhysician(Study) */
  @Test
  @Verifies(
      value = "should not update reading physician for given study with reading physician",
      method = "updateReadingPhysician(Study)")
  public void
      updateReadingPhysician_shouldNotUpdateReadingPhysicianForGivenStudyWithReadingPhysician()
          throws Exception {

    User otherMockReadingPhysician = RadiologyTestData.getMockRadiologyReadingPhysician();
    assertThat(mockReadingPhysician, is(not(otherMockReadingPhysician)));

    mockStudy.setReadingPhysician(mockReadingPhysician);
    when(Context.getAuthenticatedUser()).thenReturn(otherMockReadingPhysician);

    Method updateReadingPhysicianMethod =
        radiologyObsFormController
            .getClass()
            .getDeclaredMethod(
                "updateReadingPhysician", new Class[] {org.openmrs.module.radiology.Study.class});
    updateReadingPhysicianMethod.setAccessible(true);

    assertThat(mockStudy.getReadingPhysician(), is(mockReadingPhysician));

    updateReadingPhysicianMethod.invoke(radiologyObsFormController, new Object[] {mockStudy});

    assertThat(mockStudy.getReadingPhysician(), is(mockReadingPhysician));
  }
Esempio n. 15
0
 @Test
 public void multipleGetsWithOneInstanceOfXmlPath() throws Exception {
   final XmlPath xmlPath = new XmlPath(XML);
   assertThat(xmlPath.getInt("shopping.category.item.size()"), equalTo(5));
   assertThat(
       xmlPath.getList("shopping.category.item.children().list()", String.class), hasItem("Pens"));
 }
Esempio n. 16
0
 @Test
 public void iteratingNullIsEmptyIterable() {
   assertThat(on((String) null), sameInstance(Iterate.<Character>none()));
   assertThat(on((Integer[]) null), sameInstance(Iterate.<Integer>none()));
   assertThat(on((Iterable<Integer>) null), sameInstance(Iterate.<Integer>none()));
   assertThat(on((byte[]) null), sameInstance(Iterate.<Byte>none()));
 }
Esempio n. 17
0
 @Test
 public void convertsNonRootObjectGraphToJavaObjects() throws Exception {
   NodeChildren categories = with(XML).get("shopping.category");
   assertThat(categories.size(), equalTo(3));
   assertThat(
       categories.toString(), equalTo("Chocolate10Coffee20Paper5Pens15.5Kathryn's Birthday200"));
 }
Esempio n. 18
0
  @Test
  public void testHttp() throws Exception {
    // Verify that http_proxy and HTTP_PROXY are used for http requests
    assertExpectedProxyConfig(
        proxyConfigFromEnv(
                "http",
                ImmutableMap.of(
                    "http_proxy", PROXY_URL,
                    "HTTP_PROXY", "http://ignore",
                    "https_proxy", "http://ignore",
                    "HTTPS_PROXY", "http://ignore"))
            .get());
    assertExpectedProxyConfig(
        proxyConfigFromEnv(
                "http",
                ImmutableMap.of(
                    "HTTP_PROXY", PROXY_URL,
                    "https_proxy", "http://ignore",
                    "HTTPS_PROXY", "http://ignore"))
            .get());

    // Verify that https_proxy and HTTPS_PROXY are not used for http requests
    assertThat(
        proxyConfigFromEnv(
            "http", ImmutableMap.of("https_proxy", PROXY_URL, "HTTPS_PROXY", "http://ignore")),
        is(Optional.absent()));

    assertThat(
        proxyConfigFromEnv("http", ImmutableMap.of("HTTPS_PROXY", PROXY_URL)),
        is(Optional.absent()));
  }
Esempio n. 19
0
 @Test
 public void getSingleAttributes() throws Exception {
   final Map<String, String> categoryAttributes =
       with(XML).get("shopping.category[0].attributes()");
   assertThat(categoryAttributes.size(), equalTo(1));
   assertThat(categoryAttributes.get("type"), equalTo("groceries"));
 }
Esempio n. 20
0
  @Test
  public void buttonIsAddedToLeftNavigation() {
    Navbar navbar = new Navbar("id");
    navbar.addComponents(
        new INavbarComponent() {
          @Override
          public Component create(String markupId) {
            return new NavbarButton<Page>(Page.class, Model.of("Link Name"));
          }

          @Override
          public Navbar.ComponentPosition getPosition() {
            return Navbar.ComponentPosition.LEFT;
          }
        });

    tester().startComponentInPage(navbar);
    TagTester tagTester = tester().getTagByWicketId("navLeftList");

    Assert.assertThat(tagTester.hasChildTag("a"), is(equalTo(true)));
    Assert.assertThat(
        tester().getTagByWicketId(Navbar.componentId()).hasAttribute("href"), is(equalTo(true)));
    Assert.assertThat(
        tester().getTagByWicketId(Navbar.componentId()).getValue(), containsString("Link Name"));
  }
Esempio n. 21
0
  @Test
  public void testCachedPut() throws Exception {
    HttpFields header = new HttpFields();

    header.put("Connection", "Keep-Alive");
    header.put("tRansfer-EncOding", "CHUNKED");
    header.put("CONTENT-ENCODING", "gZIP");

    ByteBuffer buffer = BufferUtil.allocate(1024);
    BufferUtil.flipToFill(buffer);
    HttpGenerator.putTo(header, buffer);
    BufferUtil.flipToFlush(buffer, 0);
    String out = BufferUtil.toString(buffer).toLowerCase();

    Assert.assertThat(
        out,
        Matchers.containsString(
            (HttpHeader.CONNECTION + ": " + HttpHeaderValue.KEEP_ALIVE).toLowerCase()));
    Assert.assertThat(
        out,
        Matchers.containsString(
            (HttpHeader.TRANSFER_ENCODING + ": " + HttpHeaderValue.CHUNKED).toLowerCase()));
    Assert.assertThat(
        out,
        Matchers.containsString(
            (HttpHeader.CONTENT_ENCODING + ": " + HttpHeaderValue.GZIP).toLowerCase()));
  }
Esempio n. 22
0
  @Test
  public void buttonWithIconIsAddedToLeftNavigation() {
    Navbar navbar = new Navbar("id");
    navbar.addComponents(
        new INavbarComponent() {
          @Override
          public Component create(String markupId) {
            return new NavbarButton<Page>(Page.class, Model.of("Link Name"))
                .setIconType(IconType.aligncenter);
          }

          @Override
          public Navbar.ComponentPosition getPosition() {
            return Navbar.ComponentPosition.LEFT;
          }
        });

    tester().startComponentInPage(navbar);

    Assert.assertThat(
        tester().getTagByWicketId(Navbar.componentId()).hasChildTag("i"), is(equalTo(true)));
    Assert.assertThat(
        tester().getTagByWicketId("icon").getAttribute("class"),
        containsString("icon-align-center"));
  }
Esempio n. 23
0
 /** @throws Exception */
 @SuppressWarnings("unchecked")
 @Test
 public void getModelMeta() throws Exception {
   ModelMeta<Hoge> modelMeta = DatastoreUtil.getModelMeta(Hoge.class);
   assertThat(modelMeta, is(notNullValue()));
   assertThat(modelMeta, is(sameInstance((ModelMeta) Datastore.getModelMeta(Hoge.class))));
 }
  @Test
  public void analyseSingleArticleSourcesTest() {
    Library library = createSimpleLibrary();
    Article article = library.getArticles().get(0);
    assertThat("name of article", article.getTitle(), is(equalTo("F**k the system")));

    ISourceAnalysator analysator = createSourceAnalysator(library);
    Map<GeneralSource, List<Source>> generalSources =
        analysator.getGeneralSourcesOfArticle(article);
    assertThat("general sopurces count", generalSources.size(), is(equalTo(2)));

    List<GeneralSource> requiredSources = Lists.newArrayList(spiegel, guardian);
    for (Entry<GeneralSource, List<Source>> entry : generalSources.entrySet()) {
      GeneralSource generalSource = entry.getKey();
      boolean removedGeneralSource = requiredSources.remove(generalSource);
      assertThat("expected general source was found", removedGeneralSource, is(true));
      List<Source> sources = entry.getValue();
      if (generalSource.equals(spiegel)) {
        assertThat(
            "count of referenced articles of " + generalSource.getName(),
            sources.size(),
            is(equalTo(2)));
      } else if (generalSource.equals(guardian)) {
        assertThat(
            "count of referenced articles of " + generalSource.getName(),
            sources.size(),
            is(equalTo(1)));
      } else {
        fail("wrong general source");
      }
    }
    printSourcesOfArticles(Lists.newArrayList(article), generalSources);
  }
  @Test
  public void testUsingAnInQueryWithStringId() throws Exception {

    template.remove(new Query(), PersonWithIdPropertyOfTypeString.class);

    PersonWithIdPropertyOfTypeString p1 = new PersonWithIdPropertyOfTypeString();
    p1.setFirstName("Sven");
    p1.setAge(11);
    template.insert(p1);
    PersonWithIdPropertyOfTypeString p2 = new PersonWithIdPropertyOfTypeString();
    p2.setFirstName("Mary");
    p2.setAge(21);
    template.insert(p2);
    PersonWithIdPropertyOfTypeString p3 = new PersonWithIdPropertyOfTypeString();
    p3.setFirstName("Ann");
    p3.setAge(31);
    template.insert(p3);
    PersonWithIdPropertyOfTypeString p4 = new PersonWithIdPropertyOfTypeString();
    p4.setFirstName("John");
    p4.setAge(41);
    template.insert(p4);

    Query q1 = new Query(Criteria.where("age").in(11, 21, 41));
    List<PersonWithIdPropertyOfTypeString> results1 =
        template.find(q1, PersonWithIdPropertyOfTypeString.class);
    Query q2 = new Query(Criteria.where("firstName").in("Ann", "Mary"));
    List<PersonWithIdPropertyOfTypeString> results2 =
        template.find(q2, PersonWithIdPropertyOfTypeString.class);
    Query q3 = new Query(Criteria.where("id").in(p3.getId(), p4.getId()));
    List<PersonWithIdPropertyOfTypeString> results3 =
        template.find(q3, PersonWithIdPropertyOfTypeString.class);
    assertThat(results1.size(), is(3));
    assertThat(results2.size(), is(2));
    assertThat(results3.size(), is(2));
  }
 @Test
 public void testTwoLikes() {
   SparseVector vec = sum.summarize(History.forUser(42, Like.create(42, 39), Like.create(42, 67)));
   assertThat(vec.size(), equalTo(2));
   assertThat(vec.get(39), equalTo(1.0));
   assertThat(vec.get(67), equalTo(1.0));
 }
  @Test
  public void testUsingAnOrQuery() throws Exception {

    template.remove(new Query(), PersonWithIdPropertyOfTypeObjectId.class);

    PersonWithIdPropertyOfTypeObjectId p1 = new PersonWithIdPropertyOfTypeObjectId();
    p1.setFirstName("Sven");
    p1.setAge(11);
    template.insert(p1);
    PersonWithIdPropertyOfTypeObjectId p2 = new PersonWithIdPropertyOfTypeObjectId();
    p2.setFirstName("Mary");
    p2.setAge(21);
    template.insert(p2);
    PersonWithIdPropertyOfTypeObjectId p3 = new PersonWithIdPropertyOfTypeObjectId();
    p3.setFirstName("Ann");
    p3.setAge(31);
    template.insert(p3);
    PersonWithIdPropertyOfTypeObjectId p4 = new PersonWithIdPropertyOfTypeObjectId();
    p4.setFirstName("John");
    p4.setAge(41);
    template.insert(p4);

    Query orQuery =
        new Query(new Criteria().orOperator(where("age").in(11, 21), where("age").is(31)));
    List<PersonWithIdPropertyOfTypeObjectId> results =
        template.find(orQuery, PersonWithIdPropertyOfTypeObjectId.class);
    assertThat(results.size(), is(3));
    for (PersonWithIdPropertyOfTypeObjectId p : results) {
      assertThat(p.getAge(), isOneOf(11, 21, 31));
    }
  }
Esempio n. 28
0
  @Test
  public void testMultipart() throws IOException, JSONException {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://localhost:" + PORT + "/");

    File image = new File("resources/test/base.png");
    FileBody imagePart = new FileBody(image);
    StringBody messagePart = new StringBody("some message");

    MultipartEntity req = new MultipartEntity();
    req.addPart("image", imagePart);
    req.addPart("message", messagePart);
    httppost.setEntity(req);

    ImageEchoServer server = new ImageEchoServer(PORT);
    HttpResponse response = httpclient.execute(httppost);
    server.stop();

    HttpEntity resp = response.getEntity();
    assertThat(resp.getContentType().getValue(), is("application/json"));

    // sweet one-liner to convert an inputstream to a string from stackoverflow:
    // http://stackoverflow.com/questions/309424/in-java-how-do-i-read-convert-an-inputstream-to-a-string
    String out = new Scanner(resp.getContent()).useDelimiter("\\A").next();

    JSONObject json = new JSONObject(out);

    String base64 = Base64.encodeFromFile("resources/test/base.png");

    assertThat(json.getString("screenshot"), is(base64));
    assertThat(json.getBoolean("imageEcho"), is(true));
  }
  @Test
  public void testRemovingDocument() throws Exception {

    PersonWithIdPropertyOfTypeObjectId p1 = new PersonWithIdPropertyOfTypeObjectId();
    p1.setFirstName("Sven_to_be_removed");
    p1.setAge(51);
    template.insert(p1);

    Query q1 = new Query(Criteria.where("id").is(p1.getId()));
    PersonWithIdPropertyOfTypeObjectId found1 =
        template.findOne(q1, PersonWithIdPropertyOfTypeObjectId.class);
    assertThat(found1, notNullValue());
    Query _q = new Query(Criteria.where("_id").is(p1.getId()));
    template.remove(_q, PersonWithIdPropertyOfTypeObjectId.class);
    PersonWithIdPropertyOfTypeObjectId notFound1 =
        template.findOne(q1, PersonWithIdPropertyOfTypeObjectId.class);
    assertThat(notFound1, nullValue());

    PersonWithIdPropertyOfTypeObjectId p2 = new PersonWithIdPropertyOfTypeObjectId();
    p2.setFirstName("Bubba_to_be_removed");
    p2.setAge(51);
    template.insert(p2);

    Query q2 = new Query(Criteria.where("id").is(p2.getId()));
    PersonWithIdPropertyOfTypeObjectId found2 =
        template.findOne(q2, PersonWithIdPropertyOfTypeObjectId.class);
    assertThat(found2, notNullValue());
    template.remove(q2, PersonWithIdPropertyOfTypeObjectId.class);
    PersonWithIdPropertyOfTypeObjectId notFound2 =
        template.findOne(q2, PersonWithIdPropertyOfTypeObjectId.class);
    assertThat(notFound2, nullValue());
  }
  /**
   * @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()));
  }