CLean up to avoid intermittent test failure (#2329)

* CLean up to avoid intermittent test failure

* One more intermittent test fix
This commit is contained in:
James Agnew 2021-01-29 05:28:21 -05:00 committed by GitHub
parent 8854f344b3
commit 947622d25f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 14 additions and 674 deletions

View File

@ -8,6 +8,7 @@ import java.io.IOException;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.Date; import java.util.Date;
import ca.uhn.fhir.rest.api.EncodingEnum;
import ca.uhn.fhir.rest.api.PreferReturnEnum; import ca.uhn.fhir.rest.api.PreferReturnEnum;
import org.hl7.fhir.dstu3.model.*; import org.hl7.fhir.dstu3.model.*;
import org.junit.jupiter.api.*; import static org.hamcrest.MatcherAssert.assertThat; import org.junit.jupiter.api.*; import static org.hamcrest.MatcherAssert.assertThat;
@ -99,6 +100,7 @@ public class GenericClientDstu3IT {
.build(); .build();
IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir");
client.setEncoding(EncodingEnum.JSON);
Patient pt = new Patient(); Patient pt = new Patient();
pt.getText().setDivAsString("A PATIENT"); pt.getText().setDivAsString("A PATIENT");
@ -131,6 +133,8 @@ public class GenericClientDstu3IT {
ArgumentCaptor<Request> capt = prepareClientForSearchResponse(); ArgumentCaptor<Request> capt = prepareClientForSearchResponse();
IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir");
client.setEncoding(EncodingEnum.JSON);
int idx = 0; int idx = 0;
client client
@ -143,7 +147,7 @@ public class GenericClientDstu3IT {
.returnBundle(Bundle.class) .returnBundle(Bundle.class)
.execute(); .execute();
assertEquals("http://example.com/fhir/Patient", capt.getAllValues().get(idx).url().toString()); assertEquals("http://example.com/fhir/Patient?_format=json", capt.getAllValues().get(idx).url().toString());
idx++; idx++;
} }
@ -170,6 +174,7 @@ public class GenericClientDstu3IT {
.build(); .build();
IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir");
client.setEncoding(EncodingEnum.JSON);
Binary bin = new Binary(); Binary bin = new Binary();
bin.setContent(new byte[] { 0, 1, 2, 3, 4 }); bin.setContent(new byte[] { 0, 1, 2, 3, 4 });
@ -178,7 +183,7 @@ public class GenericClientDstu3IT {
Request request = capt.getAllValues().get(0); Request request = capt.getAllValues().get(0);
ourLog.info(request.headers().toString()); ourLog.info(request.headers().toString());
assertEquals("http://example.com/fhir/Binary", request.url().toString()); assertEquals("http://example.com/fhir/Binary?_format=json", request.url().toString());
validateUserAgent(capt); validateUserAgent(capt);
assertEquals(Constants.CT_FHIR_JSON_NEW + ";charset=utf-8", request.body().contentType().toString().toLowerCase().replace(" ", "")); assertEquals(Constants.CT_FHIR_JSON_NEW + ";charset=utf-8", request.body().contentType().toString().toLowerCase().replace(" ", ""));
@ -242,6 +247,7 @@ public class GenericClientDstu3IT {
.build(); .build();
IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir");
client.setEncoding(EncodingEnum.JSON);
Patient pt = new Patient(); Patient pt = new Patient();
pt.getText().setDivAsString("A PATIENT"); pt.getText().setDivAsString("A PATIENT");
@ -251,8 +257,9 @@ public class GenericClientDstu3IT {
assertNull(outcome.getOperationOutcome()); assertNull(outcome.getOperationOutcome());
assertNotNull(outcome.getResource()); assertNotNull(outcome.getResource());
assertEquals(1, capt.getAllValues().size());
assertEquals("<div xmlns=\"http://www.w3.org/1999/xhtml\">FINAL VALUE</div>", ((Patient) outcome.getResource()).getText().getDivAsString()); assertEquals("<div xmlns=\"http://www.w3.org/1999/xhtml\">FINAL VALUE</div>", ((Patient) outcome.getResource()).getText().getDivAsString());
assertEquals("http://example.com/fhir/Patient", capt.getAllValues().get(0).url().toString()); assertEquals("http://example.com/fhir/Patient?_format=json", capt.getAllValues().get(0).url().toString());
} }
@ -271,673 +278,6 @@ public class GenericClientDstu3IT {
} }
/*
@Test
public void testForceConformance() throws Exception {
final IParser p = ourCtx.newJsonParser();
final Conformance conf = new Conformance();
conf.setCopyright("COPY");
final Patient patient = new Patient();
patient.addName().addFamily("FAM");
ArgumentCaptor<Request> capt = ArgumentCaptor.forClass(Request.class);
when(myHttpClient.newCall(capt.capture())).thenReturn(myHttpResponse);
when(myHttpResponse.execute().code()).thenReturn(200);
when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_JSON_NEW + "; charset=UTF-8"));
when(myHttpResponse.execute().body()).thenReturn(ResponseBody.create(MediaType.parse(Constants.CT_FHIR_XML + "; charset=UTF-8"), respString));
when(myHttpResponse.getEntity().getContent()).thenAnswer(new Answer<ReaderInputStream>() {
private int myCount = 0;
@Override
public ReaderInputStream answer(InvocationOnMock theInvocation) throws Throwable {
final String respString;
if (myCount == 1 || myCount == 2) {
ourLog.info("Encoding patient");
respString = p.encodeResourceToString(patient);
} else {
ourLog.info("Encoding conformance");
respString = p.encodeResourceToString(conf);
}
myCount++;
return new ReaderInputStream(new StringReader(respString), Charset.forName("UTF-8"));
}
});
ourCtx.getRestfulClientFactory().setServerValidationMode(ServerValidationModeEnum.ONCE);
IGenericClient client = ourCtx.newRestfulGenericClient("http://testForceConformance.com/fhir");
client.read().resource("Patient").withId("1").execute();
assertEquals(2, capt.getAllValues().size());
assertEquals("http://testForceConformance.com/fhir/metadata?_format=json", capt.getAllValues().get(0).getURI().toASCIIString());
assertEquals("http://testForceConformance.com/fhir/Patient/1?_format=json", capt.getAllValues().get(1).getURI().toASCIIString());
client.read().resource("Patient").withId("1").execute();
assertEquals(3, capt.getAllValues().size());
assertEquals("http://testForceConformance.com/fhir/Patient/1?_format=json", capt.getAllValues().get(2).getURI().toASCIIString());
client.forceConformanceCheck();
assertEquals(4, capt.getAllValues().size());
assertEquals("http://testForceConformance.com/fhir/metadata?_format=json", capt.getAllValues().get(3).getURI().toASCIIString());
}
@Test
public void testHttp499() throws Exception {
ArgumentCaptor<Request> capt = ArgumentCaptor.forClass(Request.class);
when(myHttpClient.newCall(capt.capture())).thenReturn(myHttpResponse);
when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 499, "Wacky Message"));
when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_XML + "; charset=UTF-8"));
when(myHttpResponse.getEntity().getContent()).thenAnswer(new Answer<InputStream>() {
@Override
public InputStream answer(InvocationOnMock theInvocation) throws Throwable {
return new ReaderInputStream(new StringReader("HELLO"), StandardCharsets.UTF_8);
}
});
IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir");
try {
client.read().resource(Patient.class).withId("1").execute();
fail();
} catch (UnclassifiedServerFailureException e) {
assertEquals("ca.uhn.fhir.rest.server.exceptions.UnclassifiedServerFailureException: HTTP 499 Wacky Message", e.toString());
assertEquals("HELLO", e.getResponseBody());
}
}
@Test
public void testHttp501() throws Exception {
ArgumentCaptor<Request> capt = ArgumentCaptor.forClass(Request.class);
when(myHttpClient.newCall(capt.capture())).thenReturn(myHttpResponse);
when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 501, "Not Implemented"));
when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_XML + "; charset=UTF-8"));
when(myHttpResponse.getEntity().getContent()).thenAnswer(new Answer<InputStream>() {
@Override
public InputStream answer(InvocationOnMock theInvocation) throws Throwable {
return new ReaderInputStream(new StringReader("not implemented"), Charset.forName("UTF-8"));
}
});
IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir");
try {
client.read().resource(Patient.class).withId("1").execute();
fail();
} catch (NotImplementedOperationException e) {
assertEquals("HTTP 501 Not Implemented", e.getMessage());
}
}
@SuppressWarnings("deprecation")
@Test
public void testInvalidConformanceCall() {
IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir");
try {
client.conformance();
fail();
} catch (IllegalArgumentException e) {
assertEquals("Must call fetchConformance() instead of conformance() for RI/STU3+ structures", e.getMessage());
}
}
@Test
public void testPutDoesntForceAllIdsJson() throws Exception {
IParser p = ourCtx.newJsonParser();
Patient patient = new Patient();
patient.setId("PATIENT1");
patient.addName().addFamily("PATIENT1");
Bundle bundle = new Bundle();
bundle.setId("BUNDLE1");
bundle.addEntry().setResource(patient);
final String encoded = p.encodeResourceToString(bundle);
assertEquals("{\"resourceType\":\"Bundle\",\"id\":\"BUNDLE1\",\"entry\":[{\"resource\":{\"resourceType\":\"Patient\",\"id\":\"PATIENT1\",\"name\":[{\"family\":[\"PATIENT1\"]}]}}]}", encoded);
ArgumentCaptor<Request> capt = ArgumentCaptor.forClass(Request.class);
when(myHttpClient.newCall(capt.capture())).thenReturn(myHttpResponse);
when(myHttpResponse.execute().code()).thenReturn(200);
when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_JSON_NEW + "; charset=UTF-8"));
when(myHttpResponse.getEntity().getContent()).thenAnswer(new Answer<ReaderInputStream>() {
@Override
public ReaderInputStream answer(InvocationOnMock theInvocation) throws Throwable {
return new ReaderInputStream(new StringReader(encoded), Charset.forName("UTF-8"));
}
});
IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir");
//@formatter:off
client
.update()
.resource(bundle)
.prefer(PreferReturnEnum.REPRESENTATION)
.encodedJson()
.execute();
//@formatter:on
HttpPut httpRequest = (HttpPut) capt.getValue();
assertEquals("http://example.com/fhir/Bundle/BUNDLE1?_format=json", httpRequest.getURI().toASCIIString());
String requestString = IOUtils.toString(httpRequest.getEntity().getContent(), StandardCharsets.UTF_8);
assertEquals(encoded, requestString);
}
@Test
public void testResponseHasContentTypeMissing() throws Exception {
IParser p = ourCtx.newJsonParser();
Patient patient = new Patient();
patient.addName().addFamily("FAM");
final String respString = p.encodeResourceToString(patient);
ArgumentCaptor<Request> capt = ArgumentCaptor.forClass(Request.class);
when(myHttpClient.newCall(capt.capture())).thenReturn(myHttpResponse);
when(myHttpResponse.execute().code()).thenReturn(200);
when(myHttpResponse.getEntity().getContentType()).thenReturn(null);
when(myHttpResponse.getEntity().getContent()).thenAnswer(new Answer<ReaderInputStream>() {
@Override
public ReaderInputStream answer(InvocationOnMock theInvocation) throws Throwable {
return new ReaderInputStream(new StringReader(respString), Charset.forName("UTF-8"));
}
});
IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir");
try {
client.read().resource(Patient.class).withId("1").execute();
fail();
} catch (NonFhirResponseException e) {
assertEquals("Response contains no Content-Type", e.getMessage());
}
// Patient resp = client.read().resource(Patient.class).withId("1").execute();
// assertEquals("FAM", resp.getNameFirstRep().getFamilyAsSingleString());
}
@Test
public void testResponseHasContentTypeNonFhir() throws Exception {
IParser p = ourCtx.newJsonParser();
Patient patient = new Patient();
patient.addName().addFamily("FAM");
final String respString = p.encodeResourceToString(patient);
ArgumentCaptor<Request> capt = ArgumentCaptor.forClass(Request.class);
when(myHttpClient.newCall(capt.capture())).thenReturn(myHttpResponse);
when(myHttpResponse.execute().code()).thenReturn(200);
when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", "text/plain"));
// when(myHttpResponse.getEntity().getContentType()).thenReturn(null);
when(myHttpResponse.getEntity().getContent()).thenAnswer(new Answer<ReaderInputStream>() {
@Override
public ReaderInputStream answer(InvocationOnMock theInvocation) throws Throwable {
return new ReaderInputStream(new StringReader(respString), Charset.forName("UTF-8"));
}
});
IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir");
try {
client.read().resource(Patient.class).withId("1").execute();
fail();
} catch (NonFhirResponseException e) {
assertEquals("Response contains non FHIR Content-Type 'text/plain' : {\"resourceType\":\"Patient\",\"name\":[{\"family\":[\"FAM\"]}]}", e.getMessage());
}
// Patient resp = client.read().resource(Patient.class).withId("1").execute();
// assertEquals("FAM", resp.getNameFirstRep().getFamilyAsSingleString());
}
@Test
public void testSearchByDate() throws Exception {
final String msg = "{\"resourceType\":\"Bundle\",\"id\":null,\"base\":\"http://localhost:57931/fhir/contextDev\",\"total\":1,\"link\":[{\"relation\":\"self\",\"url\":\"http://localhost:57931/fhir/contextDev/Patient?identifier=urn%3AMultiFhirVersionTest%7CtestSubmitPatient01&_format=json\"}],\"entry\":[{\"resource\":{\"resourceType\":\"Patient\",\"id\":\"1\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2014-12-20T18:41:29.706-05:00\"},\"identifier\":[{\"system\":\"urn:MultiFhirVersionTest\",\"value\":\"testSubmitPatient01\"}]}}]}";
ArgumentCaptor<Request> capt = ArgumentCaptor.forClass(Request.class);
when(myHttpClient.newCall(capt.capture())).thenReturn(myHttpResponse);
when(myHttpResponse.execute().code()).thenReturn(200);
when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_JSON + "; charset=UTF-8"));
when(myHttpResponse.getEntity().getContent()).then(new Answer<InputStream>() {
@Override
public InputStream answer(InvocationOnMock theInvocation) throws Throwable {
return new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8"));
}
});
IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir");
int idx = 0;
DateTimeDt now = DateTimeDt.withCurrentTime();
String dateString = now.getValueAsString().substring(0, 10);
//@formatter:off
client.search()
.forResource("Patient")
.where(Patient.BIRTHDATE.after().day(dateString))
.returnBundle(Bundle.class)
.execute();
//@formatter:on
assertEquals("http://example.com/fhir/Patient?birthdate=gt"+dateString + "&_format=json", capt.getAllValues().get(idx).getURI().toString());
idx++;
}
@Test
public void testSearchByString() throws Exception {
final String msg = "{\"resourceType\":\"Bundle\",\"id\":null,\"base\":\"http://localhost:57931/fhir/contextDev\",\"total\":1,\"link\":[{\"relation\":\"self\",\"url\":\"http://localhost:57931/fhir/contextDev/Patient?identifier=urn%3AMultiFhirVersionTest%7CtestSubmitPatient01&_format=json\"}],\"entry\":[{\"resource\":{\"resourceType\":\"Patient\",\"id\":\"1\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2014-12-20T18:41:29.706-05:00\"},\"identifier\":[{\"system\":\"urn:MultiFhirVersionTest\",\"value\":\"testSubmitPatient01\"}]}}]}";
ArgumentCaptor<Request> capt = ArgumentCaptor.forClass(Request.class);
when(myHttpClient.newCall(capt.capture())).thenReturn(myHttpResponse);
when(myHttpResponse.execute().code()).thenReturn(200);
when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_JSON + "; charset=UTF-8"));
when(myHttpResponse.getEntity().getContent()).then(new Answer<InputStream>() {
@Override
public InputStream answer(InvocationOnMock theInvocation) throws Throwable {
return new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8"));
}
});
IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir");
int idx = 0;
//@formatter:off
client.search()
.forResource("Patient")
.where(Patient.NAME.matches().value("AAA"))
.returnBundle(Bundle.class)
.execute();
//@formatter:on
assertEquals("http://example.com/fhir/Patient?name=AAA&_format=json", capt.getAllValues().get(idx).getURI().toString());
idx++;
//@formatter:off
client.search()
.forResource("Patient")
.where(Patient.NAME.matches().value(new StringDt("AAA")))
.returnBundle(Bundle.class)
.execute();
//@formatter:on
assertEquals("http://example.com/fhir/Patient?name=AAA&_format=json", capt.getAllValues().get(idx).getURI().toString());
idx++;
//@formatter:off
client.search()
.forResource("Patient")
.where(Patient.NAME.matches().values("AAA", "BBB"))
.returnBundle(Bundle.class)
.execute();
//@formatter:on
assertEquals("http://example.com/fhir/Patient?name=AAA,BBB&_format=json", UrlUtil.unescape(capt.getAllValues().get(idx).getURI().toString()));
idx++;
//@formatter:off
client.search()
.forResource("Patient")
.where(Patient.NAME.matches().values(Arrays.asList("AAA", "BBB")))
.returnBundle(Bundle.class)
.execute();
//@formatter:on
assertEquals("http://example.com/fhir/Patient?name=AAA,BBB&_format=json", UrlUtil.unescape(capt.getAllValues().get(idx).getURI().toString()));
idx++;
//@formatter:off
client.search()
.forResource("Patient")
.where(Patient.NAME.matchesExactly().value("AAA"))
.returnBundle(Bundle.class)
.execute();
//@formatter:on
assertEquals("http://example.com/fhir/Patient?name%3Aexact=AAA&_format=json", capt.getAllValues().get(idx).getURI().toString());
idx++;
//@formatter:off
client.search()
.forResource("Patient")
.where(Patient.NAME.matchesExactly().value(new StringDt("AAA")))
.returnBundle(Bundle.class)
.execute();
//@formatter:on
assertEquals("http://example.com/fhir/Patient?name%3Aexact=AAA&_format=json", capt.getAllValues().get(idx).getURI().toString());
idx++;
}
@Test
public void testSearchByUrl() throws Exception {
final String msg = "{\"resourceType\":\"Bundle\",\"id\":null,\"base\":\"http://localhost:57931/fhir/contextDev\",\"total\":1,\"link\":[{\"relation\":\"self\",\"url\":\"http://localhost:57931/fhir/contextDev/Patient?identifier=urn%3AMultiFhirVersionTest%7CtestSubmitPatient01&_format=json\"}],\"entry\":[{\"resource\":{\"resourceType\":\"Patient\",\"id\":\"1\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2014-12-20T18:41:29.706-05:00\"},\"identifier\":[{\"system\":\"urn:MultiFhirVersionTest\",\"value\":\"testSubmitPatient01\"}]}}]}";
ArgumentCaptor<Request> capt = ArgumentCaptor.forClass(Request.class);
when(myHttpClient.newCall(capt.capture())).thenReturn(myHttpResponse);
when(myHttpResponse.execute().code()).thenReturn(200);
when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_JSON + "; charset=UTF-8"));
when(myHttpResponse.getEntity().getContent()).then(new Answer<InputStream>() {
@Override
public InputStream answer(InvocationOnMock theInvocation) throws Throwable {
return new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8"));
}
});
IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir");
int idx = 0;
//@formatter:off
client.search()
.forResource("Device")
.where(Device.URL.matches().value("http://foo.com"))
.returnBundle(Bundle.class)
.execute();
//@formatter:on
assertEquals("http://example.com/fhir/Device?url=http://foo.com&_format=json", UrlUtil.unescape(capt.getAllValues().get(idx).getURI().toString()));
idx++;
}
@Test
public void testAcceptHeaderWithEncodingSpecified() throws Exception {
final String msg = "{\"resourceType\":\"Bundle\",\"id\":null,\"base\":\"http://localhost:57931/fhir/contextDev\",\"total\":1,\"link\":[{\"relation\":\"self\",\"url\":\"http://localhost:57931/fhir/contextDev/Patient?identifier=urn%3AMultiFhirVersionTest%7CtestSubmitPatient01&_format=json\"}],\"entry\":[{\"resource\":{\"resourceType\":\"Patient\",\"id\":\"1\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2014-12-20T18:41:29.706-05:00\"},\"identifier\":[{\"system\":\"urn:MultiFhirVersionTest\",\"value\":\"testSubmitPatient01\"}]}}]}";
ArgumentCaptor<Request> capt = ArgumentCaptor.forClass(Request.class);
when(myHttpClient.newCall(capt.capture())).thenReturn(myHttpResponse);
when(myHttpResponse.execute().code()).thenReturn(200);
when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_JSON + "; charset=UTF-8"));
when(myHttpResponse.getEntity().getContent()).then(new Answer<InputStream>() {
@Override
public InputStream answer(InvocationOnMock theInvocation) throws Throwable {
return new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8"));
}
});
IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir");
int idx = 0;
//@formatter:off
client.setEncoding(EncodingEnum.JSON);
client.search()
.forResource("Device")
.returnBundle(Bundle.class)
.execute();
//@formatter:on
assertEquals("http://example.com/fhir/Device?_format=json", UrlUtil.unescape(capt.getAllValues().get(idx).getURI().toString()));
assertEquals("application/fhir+json;q=1.0, application/json+fhir;q=0.9", capt.getAllValues().get(idx).getFirstHeader(Constants.HEADER_ACCEPT).getValue());
idx++;
//@formatter:off
client.setEncoding(EncodingEnum.XML);
client.search()
.forResource("Device")
.returnBundle(Bundle.class)
.execute();
//@formatter:on
assertEquals("http://example.com/fhir/Device?_format=xml", UrlUtil.unescape(capt.getAllValues().get(idx).getURI().toString()));
assertEquals("application/fhir+xml;q=1.0, application/xml+fhir;q=0.9", capt.getAllValues().get(idx).getFirstHeader(Constants.HEADER_ACCEPT).getValue());
idx++;
}
@Test
public void testSearchForUnknownType() throws Exception {
IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir");
try {
client.search(new UriDt("?aaaa"));
fail();
} catch (IllegalArgumentException e) {
assertEquals("Unable to determine the resource type from the given URI: ?aaaa", e.getMessage());
}
}
@Test
public void testTransactionWithInvalidBody() throws Exception {
IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir");
// Transaction
try {
client.transaction().withBundle("FOO");
fail();
} catch (IllegalArgumentException e) {
assertEquals("Unable to determing encoding of request (body does not appear to be valid XML or JSON)", e.getMessage());
}
// Create
try {
client.create().resource("FOO").execute();
fail();
} catch (IllegalArgumentException e) {
assertEquals("Unable to determing encoding of request (body does not appear to be valid XML or JSON)", e.getMessage());
}
// Update
try {
client.update().resource("FOO").execute();
fail();
} catch (IllegalArgumentException e) {
assertEquals("Unable to determing encoding of request (body does not appear to be valid XML or JSON)", e.getMessage());
}
// Validate
try {
client.validate().resource("FOO").execute();
fail();
} catch (IllegalArgumentException e) {
assertEquals("Unable to determing encoding of request (body does not appear to be valid XML or JSON)", e.getMessage());
}
}
//TODO: narratives don't work without stax
@Test
@Disabled
public void testUpdateById() throws Exception {
IParser p = ourCtx.newJsonParser();
OperationOutcome conf = new OperationOutcome();
conf.getText().setDivAsString("OK!");
final String respString = p.encodeResourceToString(conf);
ArgumentCaptor<Request> capt = ArgumentCaptor.forClass(Request.class);
when(myHttpClient.newCall(capt.capture())).thenReturn(myHttpResponse);
when(myHttpResponse.execute().code()).thenReturn(200);
when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_JSON_NEW + "; charset=UTF-8"));
when(myHttpResponse.getEntity().getContent()).thenAnswer(new Answer<ReaderInputStream>() {
@Override
public ReaderInputStream answer(InvocationOnMock theInvocation) throws Throwable {
return new ReaderInputStream(new StringReader(respString), Charset.forName("UTF-8"));
}
});
IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir");
Patient pt = new Patient();
pt.setId("222");
pt.getText().setDivAsString("A PATIENT");
client.update().resource(pt).withId("111").execute();
ourLog.info(Arrays.asList(capt.getAllValues().get(0).getAllHeaders()).toString());
assertEquals("http://example.com/fhir/Patient/111", capt.getAllValues().get(0).getURI().toASCIIString());
validateUserAgent(capt);
assertEquals("application/xml+fhir;charset=utf-8", capt.getAllValues().get(0).getHeaders("Content-Type")[0].getValue().toLowerCase().replace(" ", ""));
assertEquals(Constants.HEADER_ACCEPT_VALUE_JSON_NON_LEGACY, capt.getAllValues().get(0).getHeaders("Accept")[0].getValue());
String body = extractBodyAsString(capt);
assertThat(body, containsString("<id value=\"111\"/>"));
}
// TODO: narratives don't work without stax
@Test
@Disabled
public void testUpdateWithPreferRepresentationServerReturnsOO() throws Exception {
final IParser p = ourCtx.newJsonParser();
final OperationOutcome resp0 = new OperationOutcome();
resp0.getText().setDivAsString("OK!");
final Patient resp1 = new Patient();
resp1.getText().setDivAsString("FINAL VALUE");
ArgumentCaptor<Request> capt = ArgumentCaptor.forClass(Request.class);
when(myHttpClient.newCall(capt.capture())).thenReturn(myHttpResponse);
when(myHttpResponse.execute().code()).thenReturn(200);
when(myHttpResponse.getAllHeaders()).thenAnswer(new Answer<Header[]>() {
@Override
public Header[] answer(InvocationOnMock theInvocation) throws Throwable {
return new Header[] { new BasicHeader(Constants.HEADER_LOCATION, "http://foo.com/base/Patient/222/_history/3") };
}
});
when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_JSON_NEW + "; charset=UTF-8"));
when(myHttpResponse.getEntity().getContent()).thenAnswer(new Answer<ReaderInputStream>() {
@Override
public ReaderInputStream answer(InvocationOnMock theInvocation) throws Throwable {
if (myAnswerCount++ == 0) {
return new ReaderInputStream(new StringReader(p.encodeResourceToString(resp0)), Charset.forName("UTF-8"));
} else {
return new ReaderInputStream(new StringReader(p.encodeResourceToString(resp1)), Charset.forName("UTF-8"));
}
}
});
IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir");
Patient pt = new Patient();
pt.setId("Patient/222");
pt.getText().setDivAsString("A PATIENT");
MethodOutcome outcome = client.update().resource(pt).prefer(PreferReturnEnum.REPRESENTATION).execute();
assertEquals(2, myAnswerCount);
assertNotNull(outcome.getOperationOutcome());
assertNotNull(outcome.getResource());
assertEquals("<div xmlns=\"http://www.w3.org/1999/xhtml\">OK!</div>", ((OperationOutcome) outcome.getOperationOutcome()).getText().getDivAsString());
assertEquals("<div xmlns=\"http://www.w3.org/1999/xhtml\">FINAL VALUE</div>", ((Patient) outcome.getResource()).getText().getDivAsString());
assertEquals(myAnswerCount, capt.getAllValues().size());
assertEquals("http://example.com/fhir/Patient/222", capt.getAllValues().get(0).getURI().toASCIIString());
assertEquals("http://foo.com/base/Patient/222/_history/3", capt.getAllValues().get(1).getURI().toASCIIString());
}
@Test
public void testUpdateWithPreferRepresentationServerReturnsResource() throws Exception {
final IParser p = ourCtx.newJsonParser();
final Patient resp1 = new Patient();
resp1.setActive(true);
ArgumentCaptor<Request> capt = ArgumentCaptor.forClass(Request.class);
when(myHttpClient.newCall(capt.capture())).thenReturn(myHttpResponse);
when(myHttpResponse.execute().code()).thenReturn(200);
when(myHttpResponse.getAllHeaders()).thenAnswer(new Answer<Header[]>() {
@Override
public Header[] answer(InvocationOnMock theInvocation) throws Throwable {
return new Header[] { new BasicHeader(Constants.HEADER_LOCATION, "http://foo.com/base/Patient/222/_history/3") };
}
});
when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_JSON_NEW + "; charset=UTF-8"));
when(myHttpResponse.getEntity().getContent()).thenAnswer(new Answer<ReaderInputStream>() {
@Override
public ReaderInputStream answer(InvocationOnMock theInvocation) throws Throwable {
myAnswerCount++;
return new ReaderInputStream(new StringReader(p.encodeResourceToString(resp1)), Charset.forName("UTF-8"));
}
});
IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir");
Patient pt = new Patient();
pt.setId("Patient/222");
pt.getText().setDivAsString("A PATIENT");
MethodOutcome outcome = client.update().resource(pt).prefer(PreferReturnEnum.REPRESENTATION).execute();
assertEquals(1, myAnswerCount);
assertNull(outcome.getOperationOutcome());
assertNotNull(outcome.getResource());
assertEquals(true, ((Patient) outcome.getResource()).getActive());
assertEquals(myAnswerCount, capt.getAllValues().size());
assertEquals("http://example.com/fhir/Patient/222?_format=json", capt.getAllValues().get(0).getURI().toASCIIString());
}
@Test
public void testUserAgentForConformance() throws Exception {
IParser p = ourCtx.newJsonParser();
Conformance conf = new Conformance();
conf.setCopyright("COPY");
final String respString = p.encodeResourceToString(conf);
ArgumentCaptor<Request> capt = ArgumentCaptor.forClass(Request.class);
when(myHttpClient.newCall(capt.capture())).thenReturn(myHttpResponse);
when(myHttpResponse.execute().code()).thenReturn(200);
when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_JSON_NEW + "; charset=UTF-8"));
when(myHttpResponse.getEntity().getContent()).thenAnswer(new Answer<ReaderInputStream>() {
@Override
public ReaderInputStream answer(InvocationOnMock theInvocation) throws Throwable {
return new ReaderInputStream(new StringReader(respString), Charset.forName("UTF-8"));
}
});
IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir");
client.fetchConformance().ofType(Conformance.class).execute();
assertEquals("http://example.com/fhir/metadata?_format=json", capt.getAllValues().get(0).getURI().toASCIIString());
validateUserAgent(capt);
}
// TODO: narratives don't work without stax
@Test
@Disabled
public void testValidate() throws Exception {
final IParser p = ourCtx.newXmlParser();
final OperationOutcome resp0 = new OperationOutcome();
resp0.getText().setDivAsString("OK!");
ArgumentCaptor<Request> capt = ArgumentCaptor.forClass(Request.class);
when(myHttpClient.newCall(capt.capture())).thenReturn(myHttpResponse);
when(myHttpResponse.execute().code()).thenReturn(200);
when(myHttpResponse.getAllHeaders()).thenAnswer(new Answer<Header[]>() {
@Override
public Header[] answer(InvocationOnMock theInvocation) throws Throwable {
return new Header[] {};
}
});
when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_XML + "; charset=UTF-8"));
when(myHttpResponse.getEntity().getContent()).thenAnswer(new Answer<ReaderInputStream>() {
@Override
public ReaderInputStream answer(InvocationOnMock theInvocation) throws Throwable {
return new ReaderInputStream(new StringReader(p.encodeResourceToString(resp0)), Charset.forName("UTF-8"));
}
});
IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir");
Patient pt = new Patient();
pt.setId("Patient/222");
pt.getText().setDivAsString("A PATIENT");
MethodOutcome outcome = client.validate().resource(pt).execute();
assertNotNull(outcome.getOperationOutcome());
assertEquals("<div xmlns=\"http://www.w3.org/1999/xhtml\">OK!</div>", ((OperationOutcome) outcome.getOperationOutcome()).getText().getDivAsString());
}
*/
@AfterAll @AfterAll
public static void afterClassClearContext() { public static void afterClassClearContext() {
TestUtil.clearAllStaticFieldsForUnitTest(); TestUtil.clearAllStaticFieldsForUnitTest();

View File

@ -683,7 +683,7 @@ public class GenericClient extends BaseClient implements IGenericClient {
OutcomeResponseHandler binding = new OutcomeResponseHandler(myPrefer); OutcomeResponseHandler binding = new OutcomeResponseHandler(myPrefer);
Map<String, List<String>> params = new HashMap<String, List<String>>(); Map<String, List<String>> params = new HashMap<>();
return invoke(params, binding, invocation); return invoke(params, binding, invocation);
} }

View File

@ -42,11 +42,11 @@ import ca.uhn.fhir.util.FhirTerser;
public abstract class RestfulClientFactory implements IRestfulClientFactory { public abstract class RestfulClientFactory implements IRestfulClientFactory {
private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(RestfulClientFactory.class); private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(RestfulClientFactory.class);
private Set<String> myValidatedServerBaseUrls = Collections.synchronizedSet(new HashSet<String>()); private final Set<String> myValidatedServerBaseUrls = Collections.synchronizedSet(new HashSet<>());
private int myConnectionRequestTimeout = DEFAULT_CONNECTION_REQUEST_TIMEOUT; private int myConnectionRequestTimeout = DEFAULT_CONNECTION_REQUEST_TIMEOUT;
private int myConnectTimeout = DEFAULT_CONNECT_TIMEOUT; private int myConnectTimeout = DEFAULT_CONNECT_TIMEOUT;
private FhirContext myContext; private FhirContext myContext;
private Map<Class<? extends IRestfulClient>, ClientInvocationHandlerFactory> myInvocationHandlers = new HashMap<>(); private final Map<Class<? extends IRestfulClient>, ClientInvocationHandlerFactory> myInvocationHandlers = new HashMap<>();
private ServerValidationModeEnum myServerValidationMode = DEFAULT_SERVER_VALIDATION_MODE; private ServerValidationModeEnum myServerValidationMode = DEFAULT_SERVER_VALIDATION_MODE;
private int mySocketTimeout = DEFAULT_SOCKET_TIMEOUT; private int mySocketTimeout = DEFAULT_SOCKET_TIMEOUT;
private String myProxyUsername; private String myProxyUsername;
@ -316,7 +316,7 @@ public abstract class RestfulClientFactory implements IRestfulClientFactory {
String serverFhirVersionString = null; String serverFhirVersionString = null;
Object value = t.getSingleValueOrNull(conformance, "fhirVersion"); Object value = t.getSingleValueOrNull(conformance, "fhirVersion");
if (value instanceof IPrimitiveType) { if (value instanceof IPrimitiveType) {
serverFhirVersionString = IPrimitiveType.class.cast(value).getValueAsString(); serverFhirVersionString = ((IPrimitiveType<?>) value).getValueAsString();
} }
FhirVersionEnum serverFhirVersionEnum = null; FhirVersionEnum serverFhirVersionEnum = null;
if (StringUtils.isBlank(serverFhirVersionString)) { if (StringUtils.isBlank(serverFhirVersionString)) {