Add lots of tests

This commit is contained in:
James Agnew 2016-06-14 17:57:08 -04:00
parent dba470f8d6
commit f3dcc3e893
30 changed files with 824 additions and 278 deletions

View File

@ -7,6 +7,7 @@ import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.commons.lang3.time.FastDateFormat;
@ -16,14 +17,15 @@ import ca.uhn.fhir.model.api.TemporalPrecisionEnum;
import ca.uhn.fhir.parser.DataFormatException;
public abstract class BaseDateTimeDt extends BasePrimitive<Date> {
static final long NANOS_PER_MILLIS = 1000000L;
static final long NANOS_PER_SECOND = 1000000000L;
private static final FastDateFormat ourHumanDateFormat = FastDateFormat.getDateInstance(FastDateFormat.MEDIUM);
private static final FastDateFormat ourHumanDateTimeFormat = FastDateFormat.getDateTimeInstance(FastDateFormat.MEDIUM, FastDateFormat.MEDIUM);
private String myFractionalSeconds;
private TemporalPrecisionEnum myPrecision = TemporalPrecisionEnum.SECOND;
private TemporalPrecisionEnum myPrecision = null;
private TimeZone myTimeZone;
private boolean myTimeZoneZulu = false;
/**
@ -186,11 +188,13 @@ public abstract class BaseDateTimeDt extends BasePrimitive<Date> {
if (getValue() == null) {
return null;
}
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(getValue());
GregorianCalendar cal;
if (getTimeZone() != null) {
cal.setTimeZone(getTimeZone());
cal = new GregorianCalendar(getTimeZone());
} else {
cal = new GregorianCalendar();
}
cal.setTime(getValue());
return cal;
}
@ -199,6 +203,9 @@ public abstract class BaseDateTimeDt extends BasePrimitive<Date> {
*/
abstract boolean isPrecisionAllowed(TemporalPrecisionEnum thePrecision);
/**
* Returns true if the timezone is set to GMT-0:00 (Z)
*/
public boolean isTimeZoneZulu() {
return myTimeZoneZulu;
}
@ -229,7 +236,7 @@ public abstract class BaseDateTimeDt extends BasePrimitive<Date> {
String value = theValue;
boolean fractionalSecondsSet = false;
if (value.length() > 0 && (value.charAt(0) == ' ' || value.charAt(value.length()-1) == ' ')) {
if (value.length() > 0 && (value.charAt(0) == ' ' || value.charAt(value.length() - 1) == ' ')) {
value = value.trim();
}
@ -394,12 +401,12 @@ public abstract class BaseDateTimeDt extends BasePrimitive<Date> {
/**
* Sets the value for this type using the given Java Date object as the time, and using the default precision for
* this datatype, as well as the local timezone as determined by the local operating
* this datatype (unless the precision is already set), as well as the local timezone as determined by the local operating
* system. Both of these properties may be modified in subsequent calls if neccesary.
*/
@Override
public BaseDateTimeDt setValue(Date theValue) {
setValue(theValue, getDefaultPrecisionForDatatype());
setValue(theValue, getPrecision());
return this;
}
@ -415,7 +422,9 @@ public abstract class BaseDateTimeDt extends BasePrimitive<Date> {
* @throws DataFormatException
*/
public void setValue(Date theValue, TemporalPrecisionEnum thePrecision) throws DataFormatException {
if (getTimeZone() == null) {
setTimeZone(TimeZone.getDefault());
}
myPrecision = thePrecision;
myFractionalSeconds = "";
if (theValue != null) {
@ -490,11 +499,195 @@ public abstract class BaseDateTimeDt extends BasePrimitive<Date> {
}
}
private void validateLengthIsAtLeast(String theValue, int theLength) {
if (theValue.length() < theLength) {
throwBadDateFormat(theValue);
}
}
/**
* Returns the year, e.g. 2015
*/
public Integer getYear() {
return getFieldValue(Calendar.YEAR);
}
/**
* Returns the month with 0-index, e.g. 0=January
*/
public Integer getMonth() {
return getFieldValue(Calendar.MONTH);
}
/**
* Returns the month with 1-index, e.g. 1=the first day of the month
*/
public Integer getDay() {
return getFieldValue(Calendar.DAY_OF_MONTH);
}
/**
* Returns the hour of the day in a 24h clock, e.g. 13=1pm
*/
public Integer getHour() {
return getFieldValue(Calendar.HOUR_OF_DAY);
}
/**
* Returns the minute of the hour in the range 0-59
*/
public Integer getMinute() {
return getFieldValue(Calendar.MINUTE);
}
/**
* Returns the second of the minute in the range 0-59
*/
public Integer getSecond() {
return getFieldValue(Calendar.SECOND);
}
/**
* Returns the milliseconds within the current second.
* <p>
* Note that this method returns the
* same value as {@link #getNanos()} but with less precision.
* </p>
*/
public Integer getMillis() {
return getFieldValue(Calendar.MILLISECOND);
}
/**
* Returns the nanoseconds within the current second
* <p>
* Note that this method returns the
* same value as {@link #getMillis()} but with more precision.
* </p>
*/
public Long getNanos() {
if (isBlank(myFractionalSeconds)) {
return null;
}
String retVal = StringUtils.rightPad(myFractionalSeconds, 9, '0');
retVal = retVal.substring(0, 9);
return Long.parseLong(retVal);
}
/**
* Sets the year, e.g. 2015
*/
public BaseDateTimeDt setYear(int theYear) {
setFieldValue(Calendar.YEAR, theYear, null, 0, 9999);
return this;
}
/**
* Sets the month with 0-index, e.g. 0=January
*/
public BaseDateTimeDt setMonth(int theMonth) {
setFieldValue(Calendar.MONTH, theMonth, null, 0, 11);
return this;
}
/**
* Sets the month with 1-index, e.g. 1=the first day of the month
*/
public BaseDateTimeDt setDay(int theDay) {
setFieldValue(Calendar.DAY_OF_MONTH, theDay, null, 0, 31);
return this;
}
/**
* Sets the hour of the day in a 24h clock, e.g. 13=1pm
*/
public BaseDateTimeDt setHour(int theHour) {
setFieldValue(Calendar.HOUR_OF_DAY, theHour, null, 0, 23);
return this;
}
/**
* Sets the minute of the hour in the range 0-59
*/
public BaseDateTimeDt setMinute(int theMinute) {
setFieldValue(Calendar.MINUTE, theMinute, null, 0, 59);
return this;
}
/**
* Sets the second of the minute in the range 0-59
*/
public BaseDateTimeDt setSecond(int theSecond) {
setFieldValue(Calendar.SECOND, theSecond, null, 0, 59);
return this;
}
/**
* Sets the milliseconds within the current second.
* <p>
* Note that this method sets the
* same value as {@link #setNanos(long)} but with less precision.
* </p>
*/
public BaseDateTimeDt setMillis(int theMillis) {
setFieldValue(Calendar.MILLISECOND, theMillis, null, 0, 999);
return this;
}
/**
* Sets the nanoseconds within the current second
* <p>
* Note that this method sets the
* same value as {@link #setMillis(int)} but with more precision.
* </p>
*/
public BaseDateTimeDt setNanos(long theNanos) {
validateValueInRange(theNanos, 0, NANOS_PER_SECOND-1);
String fractionalSeconds = StringUtils.leftPad(Long.toString(theNanos), 9, '0');
// Strip trailing 0s
for (int i = fractionalSeconds.length(); i > 0; i--) {
if (fractionalSeconds.charAt(i-1) != '0') {
fractionalSeconds = fractionalSeconds.substring(0, i);
break;
}
}
int millis = (int)(theNanos / NANOS_PER_MILLIS);
setFieldValue(Calendar.MILLISECOND, millis, fractionalSeconds, 0, 999);
return this;
}
private void setFieldValue(int theField, int theValue, String theFractionalSeconds, int theMinimum, int theMaximum) {
validateValueInRange(theValue, theMinimum, theMaximum);
Calendar cal;
if (getValue() == null) {
cal = new GregorianCalendar(0, 0, 0);
} else {
cal = getValueAsCalendar();
}
if (theField != -1) {
cal.set(theField, theValue);
}
if (theFractionalSeconds != null) {
myFractionalSeconds = theFractionalSeconds;
} else if (theField == Calendar.MILLISECOND) {
myFractionalSeconds = StringUtils.leftPad(Integer.toString(theValue), 3, '0');
}
super.setValue(cal.getTime());
}
private void validateValueInRange(long theValue, long theMinimum, long theMaximum) {
if (theValue < theMinimum || theValue > theMaximum) {
throw new IllegalArgumentException("Value " + theValue + " is not between allowable range: " + theMinimum + " - " + theMaximum);
}
}
private Integer getFieldValue(int theField) {
if (getValue() == null) {
return null;
}
Calendar cal = getValueAsCalendar();
return cal.get(theField);
}
}

View File

@ -185,5 +185,4 @@ public class InstantDt extends BaseDateTimeDt {
return DEFAULT_PRECISION;
}
}

View File

@ -32,22 +32,6 @@ import ca.uhn.fhir.model.api.annotation.SimpleSetter;
@DatatypeDef(name = "uri")
public class UriDt extends BasePrimitive<String> {
/**
* Creates a new UriDt instance which uses the given OID as the content (and prepends "urn:oid:" to the OID string
* in the value of the newly created UriDt, per the FHIR specification).
*
* @param theOid
* The OID to use (<code>null</code> is acceptable and will result in a UriDt instance with a
* <code>null</code> value)
* @return A new UriDt instance
*/
public static UriDt fromOid(String theOid) {
if (theOid == null) {
return new UriDt();
}
return new UriDt("urn:oid:" + theOid);
}
private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(UriDt.class);
/**
@ -119,18 +103,15 @@ public class UriDt extends BasePrimitive<String> {
URI retVal;
try {
retVal = new URI(theValue).normalize();
} catch (URISyntaxException e1) {
ourLog.debug("Failed to normalize URL '{}', message was: {}", theValue, e1.toString());
return theValue;
}
String urlString = retVal.toString();
if (urlString.endsWith("/") && urlString.length() > 1) {
try {
retVal = new URI(urlString.substring(0, urlString.length() - 1));
}
} catch (URISyntaxException e) {
ourLog.debug("Failed to normalize URL '{}', message was: {}", urlString, e.toString());
}
ourLog.debug("Failed to normalize URL '{}', message was: {}", theValue, e.toString());
return theValue;
}
return retVal.toASCIIString();
}
@ -139,4 +120,20 @@ public class UriDt extends BasePrimitive<String> {
return theValue;
}
/**
* Creates a new UriDt instance which uses the given OID as the content (and prepends "urn:oid:" to the OID string
* in the value of the newly created UriDt, per the FHIR specification).
*
* @param theOid
* The OID to use (<code>null</code> is acceptable and will result in a UriDt instance with a
* <code>null</code> value)
* @return A new UriDt instance
*/
public static UriDt fromOid(String theOid) {
if (theOid == null) {
return new UriDt();
}
return new UriDt("urn:oid:" + theOid);
}
}

View File

@ -29,7 +29,6 @@ import java.util.List;
import org.hl7.fhir.instance.model.api.IPrimitiveType;
import ca.uhn.fhir.model.api.IQueryParameterAnd;
import ca.uhn.fhir.model.primitive.DateTimeDt;
import ca.uhn.fhir.parser.DataFormatException;
import ca.uhn.fhir.rest.method.QualifiedParamList;
import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException;
@ -301,7 +300,9 @@ public class DateRangeParam implements IQueryParameterAnd<DateParam> {
}
/**
* Sets the range from a pair of dates, inclusive on both ends
* Sets the range from a pair of dates, inclusive on both ends. Note that if
* theLowerBound is after theUpperBound, thie method will automatically reverse
* the order of the arguments in order to create an inclusive range.
*
* @param theLowerBound
* A qualified date param representing the lower date bound (optionally may include time), e.g.
@ -313,8 +314,18 @@ public class DateRangeParam implements IQueryParameterAnd<DateParam> {
* theUpperBound may both be populated, or one may be null, but it is not valid for both to be null.
*/
public void setRangeFromDatesInclusive(IPrimitiveType<Date> theLowerBound, IPrimitiveType<Date> theUpperBound) {
myLowerBound = theLowerBound != null ? new DateParam(ParamPrefixEnum.GREATERTHAN_OR_EQUALS, theLowerBound) : null;
myUpperBound = theUpperBound != null ? new DateParam(ParamPrefixEnum.LESSTHAN_OR_EQUALS, theUpperBound) : null;
IPrimitiveType<Date> lowerBound = theLowerBound;
IPrimitiveType<Date> upperBound = theUpperBound;
if (lowerBound != null && lowerBound.getValue() != null && upperBound != null && upperBound.getValue() != null) {
if (lowerBound.getValue().after(upperBound.getValue())) {
IPrimitiveType<Date> temp = lowerBound;
lowerBound = upperBound;
upperBound = temp;
}
}
myLowerBound = lowerBound != null ? new DateParam(ParamPrefixEnum.GREATERTHAN_OR_EQUALS, lowerBound) : null;
myUpperBound = upperBound != null ? new DateParam(ParamPrefixEnum.LESSTHAN_OR_EQUALS, upperBound) : null;
validateAndThrowDataFormatExceptionIfInvalid();
}

View File

@ -45,26 +45,31 @@ public class NonPrettyPrintWriterWrapper implements XMLStreamWriter {
}
@Override
@CoverageIgnore
public String getPrefix(String theUri) throws XMLStreamException {
return myTarget.getPrefix(theUri);
}
@Override
@CoverageIgnore
public void setPrefix(String thePrefix, String theUri) throws XMLStreamException {
myTarget.setPrefix(thePrefix, theUri);
}
@Override
@CoverageIgnore
public void setDefaultNamespace(String theUri) throws XMLStreamException {
myTarget.setDefaultNamespace(theUri);
}
@Override
@CoverageIgnore
public void setNamespaceContext(NamespaceContext theContext) throws XMLStreamException {
myTarget.setNamespaceContext(theContext);
}
@Override
@CoverageIgnore
public NamespaceContext getNamespaceContext() {
return myTarget.getNamespaceContext();
}
@ -94,16 +99,19 @@ public class NonPrettyPrintWriterWrapper implements XMLStreamWriter {
}
@Override
@CoverageIgnore
public void writeEmptyElement(String theNamespaceURI, String theLocalName) throws XMLStreamException {
myTarget.writeEmptyElement(theNamespaceURI, theLocalName);
}
@Override
@CoverageIgnore
public void writeEmptyElement(String thePrefix, String theLocalName, String theNamespaceURI) throws XMLStreamException {
myTarget.writeEmptyElement(thePrefix, theLocalName, theNamespaceURI);
}
@Override
@CoverageIgnore
public void writeEmptyElement(String theLocalName) throws XMLStreamException {
myTarget.writeEmptyElement(theLocalName);
}
@ -127,11 +135,13 @@ public class NonPrettyPrintWriterWrapper implements XMLStreamWriter {
}
@Override
@CoverageIgnore
public void writeAttribute(String thePrefix, String theNamespaceURI, String theLocalName, String theValue) throws XMLStreamException {
myTarget.writeAttribute(thePrefix, theNamespaceURI, theLocalName, theValue);
}
@Override
@CoverageIgnore
public void writeAttribute(String theNamespaceURI, String theLocalName, String theValue) throws XMLStreamException {
myTarget.writeAttribute(theNamespaceURI, theLocalName, theValue);
}
@ -152,36 +162,43 @@ public class NonPrettyPrintWriterWrapper implements XMLStreamWriter {
}
@Override
@CoverageIgnore
public void writeProcessingInstruction(String theTarget) throws XMLStreamException {
myTarget.writeProcessingInstruction(theTarget);
}
@Override
@CoverageIgnore
public void writeProcessingInstruction(String theTarget, String theData) throws XMLStreamException {
myTarget.writeProcessingInstruction(theTarget, theData);
}
@Override
@CoverageIgnore
public void writeCData(String theData) throws XMLStreamException {
myTarget.writeCData(theData);
}
@Override
@CoverageIgnore
public void writeDTD(String theDtd) throws XMLStreamException {
myTarget.writeDTD(theDtd);
}
@Override
@CoverageIgnore
public void writeEntityRef(String theName) throws XMLStreamException {
myTarget.writeEntityRef(theName);
}
@Override
@CoverageIgnore
public void writeStartDocument() throws XMLStreamException {
myTarget.writeStartDocument();
}
@Override
@CoverageIgnore
public void writeStartDocument(String theVersion) throws XMLStreamException {
myTarget.writeStartDocument(theVersion);
}
@ -206,9 +223,7 @@ public class NonPrettyPrintWriterWrapper implements XMLStreamWriter {
}
static void writeCharacters(char[] theText, int theStart, int theLen, XMLStreamWriter target, int insidePre) throws XMLStreamException {
if (theLen == 0) {
return;
} else {
if (theLen > 0) {
if (insidePre > 0) {
target.writeCharacters(theText, theStart, theLen);
} else {
@ -240,6 +255,7 @@ public class NonPrettyPrintWriterWrapper implements XMLStreamWriter {
}
@Override
@CoverageIgnore
public Object getProperty(String theName) throws IllegalArgumentException {
return myTarget.getProperty(theName);
}

View File

@ -1,37 +1,19 @@
package ca.uhn.fhir.util;
/*
* #%L
* HAPI FHIR - Core Library
* %%
* Copyright (C) 2014 - 2016 University Health Network
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.io.IOException;
import java.net.ServerSocket;
import java.util.ArrayList;
import java.util.List;
/**
* Provides server ports
*/
@CoverageIgnore
public class PortUtil {
private static List<Integer> ourPorts = new ArrayList<Integer>();
/*
* Non instantiable
*/
private PortUtil() {
// nothing
}
/**
* This is really only used for unit tests but is included in the library so it can be reused across modules. Use with caution.
@ -41,20 +23,13 @@ public class PortUtil {
try {
server = new ServerSocket(0);
int port = server.getLocalPort();
ourPorts.add(port);
server.close();
Thread.sleep(500);
return port;
} catch (IOException e) {
throw new Error(e);
} catch (InterruptedException e) {
} catch (Exception e) {
throw new Error(e);
}
}
public static List<Integer> list() {
return ourPorts;
}
}

View File

@ -61,7 +61,7 @@ public class FhirValidator {
myContext = theFhirContext;
if (ourPhlocPresentOnClasspath == null) {
ourPhlocPresentOnClasspath = SchematronProvider.isScematronAvailable(theFhirContext);
ourPhlocPresentOnClasspath = SchematronProvider.isSchematronAvailable(theFhirContext);
}
}

View File

@ -23,6 +23,7 @@ package ca.uhn.fhir.validation.schematron;
import java.lang.reflect.Constructor;
import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.util.CoverageIgnore;
import ca.uhn.fhir.validation.FhirValidator;
import ca.uhn.fhir.validation.IValidatorModule;
@ -32,7 +33,8 @@ public class SchematronProvider {
private static final String I18N_KEY_NO_PHLOC_WARNING = FhirValidator.class.getName() + ".noPhlocWarningOnStartup";
private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(FhirValidator.class);
public static boolean isScematronAvailable(FhirContext theFhirContext) {
@CoverageIgnore
public static boolean isSchematronAvailable(FhirContext theFhirContext) {
try {
Class.forName("com.phloc.schematron.ISchematronResource");
return true;
@ -42,6 +44,8 @@ public class SchematronProvider {
}
}
@SuppressWarnings("unchecked")
@CoverageIgnore
public static Class<? extends IValidatorModule> getSchematronValidatorClass() {
try {
return (Class<? extends IValidatorModule>) Class.forName("ca.uhn.fhir.validation.schematron.SchematronBaseValidator");
@ -50,6 +54,7 @@ public class SchematronProvider {
}
}
@CoverageIgnore
public static IValidatorModule getSchematronValidatorInstance(FhirContext myContext) {
try {
Class<? extends IValidatorModule> cls = getSchematronValidatorClass();

View File

@ -77,5 +77,10 @@ ca.uhn.fhir.jpa.dao.BaseHapiFhirResourceDao.successfulUpdate=Successfully update
ca.uhn.fhir.jpa.dao.SearchBuilder.invalidQuantityPrefix=Unable to handle quantity prefix "{0}" for value: {1}
ca.uhn.fhir.jpa.dao.SearchBuilder.invalidNumberPrefix=Unable to handle number prefix "{0}" for value: {1}
ca.uhn.fhir.jpa.provider.BaseJpaProvider.cantCombintAtAndSince=Unable to combine _at and _since parameters for history operation
ca.uhn.fhir.jpa.term.BaseHapiTerminologySvc.cannotCreateDuplicateCodeSystemUri=Can not create multiple code systems with URI "{0}", already have one with resource ID: {1}
ca.uhn.fhir.jpa.term.BaseHapiTerminologySvc.expansionTooLarge=Expansion of ValueSet produced too many codes (maximum {0}) - Operation aborted!
ca.uhn.fhir.jpa.term.BaseHapiTerminologySvc.expansionTooLarge=Expansion of ValueSet produced too many codes (maximum {0}) - Operation aborted!

View File

@ -1,5 +1,7 @@
package ca.uhn.fhir.jpa.provider;
import java.util.Date;
/*
* #%L
* HAPI FHIR JPA Server
@ -28,9 +30,10 @@ import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.jboss.logging.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.rest.param.DateRangeParam;
import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException;
import ca.uhn.fhir.rest.server.servlet.ServletRequestDetails;
public class BaseJpaProvider {
@ -41,6 +44,9 @@ public class BaseJpaProvider {
private FhirContext myContext;
/**
* @param theRequest The servlet request
*/
public void endRequest(HttpServletRequest theRequest) {
MDC.remove(REMOTE_ADDR);
MDC.remove(REMOTE_UA);
@ -54,10 +60,25 @@ public class BaseJpaProvider {
return myContext;
}
protected DateRangeParam processSinceOrAt(Date theSince, DateRangeParam theAt) {
boolean haveAt = theAt != null && (theAt.getLowerBoundAsInstant() != null || theAt.getUpperBoundAsInstant() != null);
if (haveAt && theSince != null) {
String msg = getContext().getLocalizer().getMessage(BaseJpaProvider.class, "cantCombintAtAndSince");
throw new InvalidRequestException(msg);
}
if (haveAt) {
return theAt;
}
return new DateRangeParam(theSince, null);
}
public void setContext(FhirContext theContext) {
myContext = theContext;
}
public void startRequest(HttpServletRequest theRequest) {
if (theRequest == null) {
return;

View File

@ -65,24 +65,29 @@ public abstract class BaseJpaResourceProvider<T extends IBaseResource> extends B
HttpServletRequest theRequest,
@IdParam IIdType theId,
@Since Date theSince,
// @At DateRangeParam theAt,
@At DateRangeParam theAt,
RequestDetails theRequestDetails) {
//@formatter:on
startRequest(theRequest);
try {
// DateRangeParam sinceOrAt = processSinceOrAt(theSince)
return myDao.history(theId, theSince, null, theRequestDetails);
DateRangeParam sinceOrAt = processSinceOrAt(theSince, theAt);
return myDao.history(theId, sinceOrAt.getLowerBoundAsInstant(), sinceOrAt.getUpperBoundAsInstant(), theRequestDetails);
} finally {
endRequest(theRequest);
}
}
@History
public IBundleProvider getHistoryForResourceType(HttpServletRequest theRequest, @Since Date theDate, RequestDetails theRequestDetails) {
public IBundleProvider getHistoryForResourceType(
HttpServletRequest theRequest,
@Since Date theSince,
@At DateRangeParam theAt,
RequestDetails theRequestDetails) {
startRequest(theRequest);
try {
return myDao.history(theDate, null, theRequestDetails);
DateRangeParam sinceOrAt = processSinceOrAt(theSince, theAt);
return myDao.history(sinceOrAt.getLowerBoundAsInstant(), sinceOrAt.getUpperBoundAsInstant(), theRequestDetails);
} finally {
endRequest(theRequest);
}

View File

@ -28,10 +28,12 @@ import org.springframework.beans.factory.annotation.Required;
import ca.uhn.fhir.jpa.dao.IFhirSystemDao;
import ca.uhn.fhir.model.api.TagList;
import ca.uhn.fhir.rest.annotation.At;
import ca.uhn.fhir.rest.annotation.GetTags;
import ca.uhn.fhir.rest.annotation.History;
import ca.uhn.fhir.rest.annotation.Since;
import ca.uhn.fhir.rest.method.RequestDetails;
import ca.uhn.fhir.rest.param.DateRangeParam;
import ca.uhn.fhir.rest.server.IBundleProvider;
public class BaseJpaSystemProvider<T, MT> extends BaseJpaProvider {
@ -48,10 +50,11 @@ public class BaseJpaSystemProvider<T, MT> extends BaseJpaProvider {
}
@History
public IBundleProvider historyServer(HttpServletRequest theRequest, @Since Date theDate, RequestDetails theRequestDetails) {
public IBundleProvider historyServer(HttpServletRequest theRequest, @Since Date theDate, @At DateRangeParam theAt, RequestDetails theRequestDetails) {
startRequest(theRequest);
try {
return myDao.history(theDate, null, theRequestDetails);
DateRangeParam range = super.processSinceOrAt(theDate, theAt);
return myDao.history(range.getLowerBoundAsInstant(), range.getUpperBoundAsInstant(), theRequestDetails);
} finally {
endRequest(theRequest);
}

View File

@ -62,7 +62,7 @@ public class BaseJpaResourceProviderValueSetDstu3 extends JpaResourceProviderDst
}
if (moreThanOneTrue(haveId, haveIdentifier, haveValueSet)) {
throw new InvalidRequestException("$expand must EITHER be invoked at the type level, or have an identifier specified, or have a ValueSet specified. Can not combine these options.");
throw new InvalidRequestException("$expand must EITHER be invoked at the instance level, or have an identifier specified, or have a ValueSet specified. Can not combine these options.");
}
startRequest(theServletRequest);

View File

@ -41,4 +41,10 @@ public class BaseFhirDaoTest extends BaseJpaTest {
}
@Override
protected FhirContext getContext() {
return ourCtx;
}
}

View File

@ -16,6 +16,7 @@ import javax.persistence.EntityManager;
import org.apache.commons.io.IOUtils;
import org.hibernate.search.jpa.Search;
import org.hl7.fhir.dstu3.model.Bundle.BundleEntryComponent;
import org.hl7.fhir.instance.model.api.IBaseBundle;
import org.hl7.fhir.instance.model.api.IBaseResource;
import org.hl7.fhir.instance.model.api.IIdType;
import org.junit.AfterClass;
@ -26,6 +27,7 @@ import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;
import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.jpa.entity.ForcedId;
import ca.uhn.fhir.jpa.entity.ResourceHistoryTable;
import ca.uhn.fhir.jpa.entity.ResourceHistoryTag;
@ -55,9 +57,10 @@ import ca.uhn.fhir.rest.method.IRequestOperationCallback;
import ca.uhn.fhir.rest.server.IBundleProvider;
import ca.uhn.fhir.rest.server.interceptor.IServerInterceptor;
import ca.uhn.fhir.rest.server.servlet.ServletRequestDetails;
import ca.uhn.fhir.util.BundleUtil;
import ca.uhn.fhir.util.TestUtil;
public class BaseJpaTest {
public abstract class BaseJpaTest {
private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(BaseJpaTest.class);
protected ServletRequestDetails mySrd;
@ -74,6 +77,32 @@ public class BaseJpaTest {
return theSearch.getResources(0, theSearch.size());
}
protected abstract FhirContext getContext();
protected List<String> toUnqualifiedVersionlessIdValues(IBaseBundle theFound) {
List<String> retVal = new ArrayList<String>();
List<IBaseResource> res = BundleUtil.toListOfResources(getContext(), theFound);
int size = res.size();
ourLog.info("Found {} results", size);
for (IBaseResource next : res) {
retVal.add(next.getIdElement().toUnqualifiedVersionless().getValue());
}
return retVal;
}
protected List<String> toUnqualifiedIdValues(IBaseBundle theFound) {
List<String> retVal = new ArrayList<String>();
List<IBaseResource> res = BundleUtil.toListOfResources(getContext(), theFound);
int size = res.size();
ourLog.info("Found {} results", size);
for (IBaseResource next : res) {
retVal.add(next.getIdElement().toUnqualified().getValue());
}
return retVal;
}
protected List<IIdType> toUnqualifiedVersionlessIds(Bundle theFound) {
List<IIdType> retVal = new ArrayList<IIdType>();
for (Entry next : theFound.getEntry()) {

View File

@ -31,17 +31,21 @@ import ca.uhn.fhir.util.TestUtil;
@SuppressWarnings("unused")
public class FhirResourceDaoDstu1Test extends BaseJpaTest {
private static AnnotationConfigApplicationContext ourAppCtx;
private static FhirContext ourCtx;
private static IFhirResourceDao<Device> ourDeviceDao;
private static IFhirResourceDao<DiagnosticReport> ourDiagnosticReportDao;
private static IFhirResourceDao<Encounter> ourEncounterDao;
private static AnnotationConfigApplicationContext ourAppCtx;
private static IFhirResourceDao<Location> ourLocationDao;
private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(FhirResourceDaoDstu1Test.class);
private static IFhirResourceDao<Observation> ourObservationDao;
private static IFhirResourceDao<Organization> ourOrganizationDao;
private static IFhirResourceDao<Patient> ourPatientDao;
private static FhirContext ourCtx;
@Override
protected FhirContext getContext() {
return ourCtx;
}
@Test
public void testCreateDuplicateIdFails() {
@ -125,6 +129,12 @@ public class FhirResourceDaoDstu1Test extends BaseJpaTest {
}
@AfterClass
public static void afterClassClearContext() {
ourAppCtx.close();
TestUtil.clearAllStaticFieldsForUnitTest();
}
@SuppressWarnings("unchecked")
@BeforeClass
public static void beforeClass() {
@ -139,10 +149,4 @@ public class FhirResourceDaoDstu1Test extends BaseJpaTest {
ourCtx = ourAppCtx.getBean(FhirContext.class);
}
@AfterClass
public static void afterClassClearContext() {
ourAppCtx.close();
TestUtil.clearAllStaticFieldsForUnitTest();
}
}

View File

@ -53,27 +53,25 @@ import ca.uhn.fhir.util.TestUtil;
public class FhirSystemDaoDstu1Test extends BaseJpaTest {
private static AnnotationConfigApplicationContext ourCtx;
private static EntityManager ourEntityManager;
private static FhirContext ourFhirContext;
private static IFhirResourceDao<Location> ourLocationDao;
private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(FhirSystemDaoDstu1Test.class);
private static IFhirResourceDao<Observation> ourObservationDao;
private static IFhirResourceDao<Patient> ourPatientDao;
private static IFhirSystemDao<List<IResource>, MetaDt> ourSystemDao;
private static EntityManager ourEntityManager;
private static PlatformTransactionManager ourTxManager;
@AfterClass
public static void afterClassClearContext() {
ourCtx.close();
TestUtil.clearAllStaticFieldsForUnitTest();
}
@Before
public void before() {
super.purgeDatabase(ourEntityManager, ourTxManager);
}
@Override
protected FhirContext getContext() {
return ourFhirContext;
}
@Test
public void testGetResourceCounts() {
Observation obs = new Observation();
@ -382,7 +380,6 @@ public class FhirSystemDaoDstu1Test extends BaseJpaTest {
assertThat(encodeResourceToString, not(containsString("smsp")));
}
/**
* This is the correct way to do this, not {@link #testTransactionWithCidIds()}
*/
@ -479,6 +476,11 @@ public class FhirSystemDaoDstu1Test extends BaseJpaTest {
}
@AfterClass
public static void afterClassClearContext() {
ourCtx.close();
TestUtil.clearAllStaticFieldsForUnitTest();
}
@SuppressWarnings("unchecked")
@BeforeClass

View File

@ -73,31 +73,17 @@ import ca.uhn.fhir.util.TestUtil;
//@formatter:on
public abstract class BaseJpaDstu2Test extends BaseJpaTest {
@AfterClass
public static void afterClassClearContext() throws Exception {
TestUtil.clearAllStaticFieldsForUnitTest();
}
@Autowired
protected ApplicationContext myAppCtx;
@Autowired
protected IFulltextSearchSvc mySearchDao;
@Autowired
@Qualifier("myConceptMapDaoDstu2")
protected IFhirResourceDao<ConceptMap> myConceptMapDao;
@Autowired
@Qualifier("myAppointmentDaoDstu2")
protected IFhirResourceDao<Appointment> myAppointmentDao;
@Autowired
@Qualifier("myBundleDaoDstu2")
protected IFhirResourceDao<Bundle> myBundleDao;
@Autowired
@Qualifier("myMedicationDaoDstu2")
protected IFhirResourceDao<Medication> myMedicationDao;
@Autowired
@Qualifier("myMedicationOrderDaoDstu2")
protected IFhirResourceDao<MedicationOrder> myMedicationOrderDao;
@Qualifier("myConceptMapDaoDstu2")
protected IFhirResourceDao<ConceptMap> myConceptMapDao;
@Autowired
protected DaoConfig myDaoConfig;
@Autowired
@ -112,11 +98,9 @@ public abstract class BaseJpaDstu2Test extends BaseJpaTest {
@Autowired
@Qualifier("myEncounterDaoDstu2")
protected IFhirResourceDao<Encounter> myEncounterDao;
// @PersistenceContext()
// @PersistenceContext()
@Autowired
protected EntityManager myEntityManager;
@Autowired
@Qualifier("myFhirContextDstu2")
protected FhirContext myFhirCtx;
@ -127,6 +111,17 @@ public abstract class BaseJpaDstu2Test extends BaseJpaTest {
@Autowired
@Qualifier("myLocationDaoDstu2")
protected IFhirResourceDao<Location> myLocationDao;
@Autowired
@Qualifier("myMediaDaoDstu2")
protected IFhirResourceDao<Media> myMediaDao;
@Autowired
@Qualifier("myMedicationDaoDstu2")
protected IFhirResourceDao<Medication> myMedicationDao;
@Autowired
@Qualifier("myMedicationOrderDaoDstu2")
protected IFhirResourceDao<MedicationOrder> myMedicationOrderDao;
@Autowired
@Qualifier("myObservationDaoDstu2")
protected IFhirResourceDao<Observation> myObservationDao;
@ -137,9 +132,6 @@ public abstract class BaseJpaDstu2Test extends BaseJpaTest {
@Qualifier("myPatientDaoDstu2")
protected IFhirResourceDaoPatient<Patient> myPatientDao;
@Autowired
@Qualifier("myMediaDaoDstu2")
protected IFhirResourceDao<Media> myMediaDao;
@Autowired
@Qualifier("myPractitionerDaoDstu2")
protected IFhirResourceDao<Practitioner> myPractitionerDao;
@Autowired
@ -152,6 +144,8 @@ public abstract class BaseJpaDstu2Test extends BaseJpaTest {
@Qualifier("myResourceProvidersDstu2")
protected Object myResourceProviders;
@Autowired
protected IFulltextSearchSvc mySearchDao;
@Autowired
@Qualifier("myStructureDefinitionDaoDstu2")
protected IFhirResourceDao<StructureDefinition> myStructureDefinitionDao;
@Autowired
@ -171,21 +165,11 @@ public abstract class BaseJpaDstu2Test extends BaseJpaTest {
@Autowired
@Qualifier("myValueSetDaoDstu2")
protected IFhirResourceDaoValueSet<ValueSet, CodingDt, CodeableConceptDt> myValueSetDao;
@Before
public void beforeCreateInterceptor() {
myInterceptor = mock(IServerInterceptor.class);
myDaoConfig.setInterceptors(myInterceptor);
}
@Before
public void beforeResetConfig() {
myDaoConfig.setHardSearchLimit(1000);
myDaoConfig.setHardTagListLimit(1000);
myDaoConfig.setIncludeLimit(2000);
myDaoConfig.setAllowExternalReferences(new DaoConfig().isAllowExternalReferences());
}
@Before
@Transactional
public void beforeFlushFT() {
@ -204,6 +188,19 @@ public abstract class BaseJpaDstu2Test extends BaseJpaTest {
purgeDatabase(entityManager, myTxManager);
}
@Before
public void beforeResetConfig() {
myDaoConfig.setHardSearchLimit(1000);
myDaoConfig.setHardTagListLimit(1000);
myDaoConfig.setIncludeLimit(2000);
myDaoConfig.setAllowExternalReferences(new DaoConfig().isAllowExternalReferences());
}
@Override
protected FhirContext getContext() {
return myFhirCtx;
}
protected <T extends IBaseResource> T loadResourceFromClasspath(Class<T> type, String resourceName) throws IOException {
InputStream stream = FhirResourceDaoDstu2SearchNoFtTest.class.getResourceAsStream(resourceName);
if (stream == null) {
@ -221,4 +218,9 @@ public abstract class BaseJpaDstu2Test extends BaseJpaTest {
return retVal;
}
@AfterClass
public static void afterClassClearContext() throws Exception {
TestUtil.clearAllStaticFieldsForUnitTest();
}
}

View File

@ -29,7 +29,6 @@ import ca.uhn.fhir.rest.param.StringAndListParam;
import ca.uhn.fhir.rest.param.StringOrListParam;
import ca.uhn.fhir.rest.param.StringParam;
import ca.uhn.fhir.rest.server.Constants;
import ca.uhn.fhir.rest.server.servlet.ServletRequestDetails;
import ca.uhn.fhir.util.TestUtil;
public class FhirResourceDaoDstu2SearchFtTest extends BaseJpaDstu2Test {
@ -41,7 +40,6 @@ public class FhirResourceDaoDstu2SearchFtTest extends BaseJpaDstu2Test {
TestUtil.clearAllStaticFieldsForUnitTest();
}
@Test
public void testSuggestIgnoresBase64Content() {
Patient patient = new Patient();
@ -52,7 +50,7 @@ public class FhirResourceDaoDstu2SearchFtTest extends BaseJpaDstu2Test {
med.getSubject().setReference(ptId);
med.getSubtype().setText("Systolic Blood Pressure");
med.getContent().setContentType("LCws");
med.getContent().setData(new Base64BinaryDt(new byte[] {44,44,44,44,44,44,44,44}));
med.getContent().setData(new Base64BinaryDt(new byte[] { 44, 44, 44, 44, 44, 44, 44, 44 }));
med.getContent().setTitle("bbbb syst");
myMediaDao.create(med, mySrd);
ourLog.info(myFhirCtx.newJsonParser().encodeResourceToString(med));
@ -150,7 +148,6 @@ public class FhirResourceDaoDstu2SearchFtTest extends BaseJpaDstu2Test {
}
@Test
public void testSearchAndReindex() {
Patient patient;
@ -240,7 +237,7 @@ public class FhirResourceDaoDstu2SearchFtTest extends BaseJpaDstu2Test {
request = mock(HttpServletRequest.class);
StringAndListParam param;
ourLog.info("Pt1:{} Pt2:{} Obs1:{} Obs2:{} Obs3:{}", new Object[] {ptId1.getIdPart(), ptId2.getIdPart(), obsId1.getIdPart(), obsId2.getIdPart(), obsId3.getIdPart()});
ourLog.info("Pt1:{} Pt2:{} Obs1:{} Obs2:{} Obs3:{}", new Object[] { ptId1.getIdPart(), ptId2.getIdPart(), obsId1.getIdPart(), obsId2.getIdPart(), obsId3.getIdPart() });
param = new StringAndListParam();
param.addAnd(new StringOrListParam().addOr(new StringParam("obsvalue1")));
@ -332,7 +329,7 @@ public class FhirResourceDaoDstu2SearchFtTest extends BaseJpaDstu2Test {
request = mock(HttpServletRequest.class);
StringAndListParam param;
ourLog.info("Pt1:{} Pt2:{} Obs1:{} Obs2:{} Obs3:{}", new Object[] {ptId1.getIdPart(), ptId2.getIdPart(), obsId1.getIdPart(), obsId2.getIdPart(), obsId3.getIdPart()});
ourLog.info("Pt1:{} Pt2:{} Obs1:{} Obs2:{} Obs3:{}", new Object[] { ptId1.getIdPart(), ptId2.getIdPart(), obsId1.getIdPart(), obsId2.getIdPart(), obsId3.getIdPart() });
param = new StringAndListParam();
param.addAnd(new StringOrListParam().addOr(new StringParam("obsvalue1")));
@ -377,10 +374,8 @@ public class FhirResourceDaoDstu2SearchFtTest extends BaseJpaDstu2Test {
}
/**
* When processing transactions, we do two passes. Make sure we don't update the lucene index twice since that would
* be inefficient
* When processing transactions, we do two passes. Make sure we don't update the lucene index twice since that would be inefficient
*/
@Test
public void testSearchDontReindexForUpdateWithIndexDisabled() {

View File

@ -792,19 +792,19 @@ public class FhirResourceDaoDstu2SearchNoFtTest extends BaseJpaDstu2Test {
{
SearchParameterMap params = new SearchParameterMap();
List<IIdType> patients = toUnqualifiedVersionlessIds(myPatientDao.search(params));
assertThat(patients, hasItems(id1a, id1b, id2));
assertThat(patients, containsInAnyOrder(id1a, id1b, id2));
}
{
SearchParameterMap params = new SearchParameterMap();
params.setLastUpdated(new DateRangeParam(beforeAny, null));
List<IIdType> patients = toUnqualifiedVersionlessIds(myPatientDao.search(params));
assertThat(patients, hasItems(id1a, id1b, id2));
assertThat(patients, containsInAnyOrder(id1a, id1b, id2));
}
{
SearchParameterMap params = new SearchParameterMap();
params.setLastUpdated(new DateRangeParam(beforeR2, null));
List<IIdType> patients = toUnqualifiedVersionlessIds(myPatientDao.search(params));
assertThat(patients, hasItems(id2));
assertThat(patients, containsInAnyOrder(id2));
assertThat(patients, not(hasItems(id1a, id1b)));
}
{
@ -812,13 +812,13 @@ public class FhirResourceDaoDstu2SearchNoFtTest extends BaseJpaDstu2Test {
params.setLastUpdated(new DateRangeParam(beforeAny, beforeR2));
List<IIdType> patients = toUnqualifiedVersionlessIds(myPatientDao.search(params));
assertThat(patients.toString(), patients, not(hasItems(id2)));
assertThat(patients.toString(), patients, (hasItems(id1a, id1b)));
assertThat(patients.toString(), patients, (containsInAnyOrder(id1a, id1b)));
}
{
SearchParameterMap params = new SearchParameterMap();
params.setLastUpdated(new DateRangeParam(null, beforeR2));
List<IIdType> patients = toUnqualifiedVersionlessIds(myPatientDao.search(params));
assertThat(patients, (hasItems(id1a, id1b)));
assertThat(patients, (containsInAnyOrder(id1a, id1b)));
assertThat(patients, not(hasItems(id2)));
}
}

View File

@ -106,9 +106,6 @@ public abstract class BaseJpaDstu3Test extends BaseJpaTest {
@Qualifier("myCarePlanDaoDstu3")
protected IFhirResourceDao<CarePlan> myCarePlanDao;
@Autowired
@Qualifier("myConditionDaoDstu3")
protected IFhirResourceDao<Condition> myConditionDao;
@Autowired
@Qualifier("myCodeSystemDaoDstu3")
protected IFhirResourceDao<CodeSystem> myCodeSystemDao;
@Autowired
@ -118,6 +115,9 @@ public abstract class BaseJpaDstu3Test extends BaseJpaTest {
@Qualifier("myConceptMapDaoDstu3")
protected IFhirResourceDao<ConceptMap> myConceptMapDao;
@Autowired
@Qualifier("myConditionDaoDstu3")
protected IFhirResourceDao<Condition> myConditionDao;
@Autowired
protected DaoConfig myDaoConfig;
@Autowired
@Qualifier("myDeviceDaoDstu3")
@ -213,7 +213,6 @@ public abstract class BaseJpaDstu3Test extends BaseJpaTest {
@Autowired
@Qualifier("myValueSetDaoDstu3")
protected IFhirResourceDaoValueSet<ValueSet, Coding, CodeableConcept> myValueSetDao;
@After()
public void afterGrabCaches() {
ourValueSetDao = myValueSetDao;
@ -251,6 +250,11 @@ public abstract class BaseJpaDstu3Test extends BaseJpaTest {
myDaoConfig.setIncludeLimit(2000);
}
@Override
protected FhirContext getContext() {
return myFhirCtx;
}
protected <T extends IBaseResource> T loadResourceFromClasspath(Class<T> type, String resourceName) throws IOException {
InputStream stream = FhirResourceDaoDstu2SearchNoFtTest.class.getResourceAsStream(resourceName);
if (stream == null) {

View File

@ -63,7 +63,6 @@ import ca.uhn.fhir.rest.server.IResourceProvider;
import ca.uhn.fhir.rest.server.RestfulServer;
import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException;
import ca.uhn.fhir.rest.server.exceptions.UnprocessableEntityException;
import ca.uhn.fhir.rest.server.servlet.ServletRequestDetails;
import ca.uhn.fhir.util.TestUtil;
public class ResourceProviderDstu1Test extends BaseJpaTest {
@ -88,6 +87,10 @@ public class ResourceProviderDstu1Test extends BaseJpaTest {
TestUtil.clearAllStaticFieldsForUnitTest();
}
@Override
protected FhirContext getContext() {
return ourCtx;
}
// private static JpaConformanceProvider ourConfProvider;
@ -121,11 +124,11 @@ public class ResourceProviderDstu1Test extends BaseJpaTest {
}
ourClient.transaction().withResources(resources).prettyPrint().encodedXml().execute();
Bundle found = ourClient.search().forResource(Organization.class).where(Organization.NAME.matches().value("testCountParam_01")).limitTo(10).execute();
Bundle found = ourClient.search().forResource(Organization.class).where(Organization.NAME.matches().value("testCountParam_01")).count(10).execute();
assertEquals(100, found.getTotalResults().getValue().intValue());
assertEquals(10, found.getEntries().size());
found = ourClient.search().forResource(Organization.class).where(Organization.NAME.matches().value("testCountParam_01")).limitTo(999).execute();
found = ourClient.search().forResource(Organization.class).where(Organization.NAME.matches().value("testCountParam_01")).count(999).execute();
assertEquals(100, found.getTotalResults().getValue().intValue());
assertEquals(50, found.getEntries().size());

View File

@ -3,7 +3,8 @@ package ca.uhn.fhir.jpa.provider;
import static org.hamcrest.Matchers.blankOrNullString;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import java.io.InputStream;
@ -11,13 +12,10 @@ import org.apache.commons.io.IOUtils;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.hamcrest.text.IsBlankString;
import org.hl7.fhir.instance.model.api.IBaseResource;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.jpa.config.TestDstu1Config;
@ -32,19 +30,22 @@ import ca.uhn.fhir.model.dstu.resource.Observation;
import ca.uhn.fhir.model.dstu.resource.Organization;
import ca.uhn.fhir.model.dstu.resource.Patient;
import ca.uhn.fhir.model.dstu.resource.Questionnaire;
import ca.uhn.fhir.model.dstu2.resource.Bundle;
import ca.uhn.fhir.model.primitive.IdDt;
import ca.uhn.fhir.rest.client.IGenericClient;
import ca.uhn.fhir.rest.server.RestfulServer;
import ca.uhn.fhir.util.TestUtil;
public class SystemProviderDstu1Test extends BaseJpaTest {
private static AnnotationConfigApplicationContext ourAppCtx;
private static IGenericClient ourClient;
private static FhirContext ourCtx;
private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(SystemProviderDstu1Test.class);
private static Server ourServer;
private static AnnotationConfigApplicationContext ourAppCtx;
private static FhirContext ourCtx;
private static IGenericClient ourClient;
@Override
protected FhirContext getContext() {
return ourCtx;
}
@Test
public void testTransactionFromBundle() throws Exception {
@ -65,7 +66,12 @@ public class SystemProviderDstu1Test extends BaseJpaTest {
}
@AfterClass
public static void afterClassClearContext() throws Exception {
ourServer.stop();
ourAppCtx.stop();
TestUtil.clearAllStaticFieldsForUnitTest();
}
@SuppressWarnings("unchecked")
@BeforeClass
@ -112,18 +118,9 @@ public class SystemProviderDstu1Test extends BaseJpaTest {
ourServer.setHandler(proxyHandler);
ourServer.start();
ourCtx.getRestfulClientFactory().setSocketTimeout(600 * 1000);
ourClient = ourCtx.newRestfulGenericClient(serverBase);
ourClient.setLogRequestAndResponse(true);
}
@AfterClass
public static void afterClassClearContext() throws Exception {
ourServer.stop();
ourAppCtx.stop();
TestUtil.clearAllStaticFieldsForUnitTest();
}
}

View File

@ -7,6 +7,7 @@ import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.startsWith;
import static org.hamcrest.Matchers.stringContainsInOrder;
@ -17,21 +18,17 @@ import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.forwardedUrlPattern;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
@ -44,6 +41,7 @@ import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.hamcrest.Matchers;
import org.hl7.fhir.dstu3.model.BaseResource;
import org.hl7.fhir.dstu3.model.Bundle;
import org.hl7.fhir.dstu3.model.Bundle.BundleEntryComponent;
@ -98,27 +96,23 @@ import org.junit.AfterClass;
import org.junit.Ignore;
import org.junit.Test;
import ca.uhn.fhir.jpa.dao.SearchParameterMap;
import ca.uhn.fhir.model.api.IQueryParameterType;
import com.google.common.collect.Lists;
import ca.uhn.fhir.model.primitive.InstantDt;
import ca.uhn.fhir.model.primitive.UriDt;
import ca.uhn.fhir.rest.api.MethodOutcome;
import ca.uhn.fhir.rest.api.SummaryEnum;
import ca.uhn.fhir.rest.client.IGenericClient;
import ca.uhn.fhir.rest.param.DateRangeParam;
import ca.uhn.fhir.rest.param.HasParam;
import ca.uhn.fhir.rest.param.ParamPrefixEnum;
import ca.uhn.fhir.rest.param.StringAndListParam;
import ca.uhn.fhir.rest.param.StringOrListParam;
import ca.uhn.fhir.rest.param.StringParam;
import ca.uhn.fhir.rest.param.TokenParam;
import ca.uhn.fhir.rest.server.Constants;
import ca.uhn.fhir.rest.server.IBundleProvider;
import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException;
import ca.uhn.fhir.rest.server.exceptions.PreconditionFailedException;
import ca.uhn.fhir.rest.server.exceptions.ResourceGoneException;
import ca.uhn.fhir.rest.server.exceptions.UnprocessableEntityException;
import ca.uhn.fhir.rest.server.servlet.ServletRequestDetails;
import ca.uhn.fhir.util.BundleUtil;
import ca.uhn.fhir.util.TestUtil;
import ca.uhn.fhir.util.UrlUtil;
@ -131,21 +125,11 @@ public class ResourceProviderDstu3Test extends BaseResourceProviderDstu3Test {
public static void afterClassClearContext() {
TestUtil.clearAllStaticFieldsForUnitTest();
}
protected List<String> toUnqualifiedVersionlessIdValues(IBaseBundle theFound) {
List<String> retVal = new ArrayList<String>();
List<IBaseResource> res = BundleUtil.toListOfResources(myFhirCtx, theFound);
int size = res.size();
ourLog.info("Found {} results", size);
for (IBaseResource next : res) {
retVal.add(next.getIdElement().toUnqualifiedVersionless().getValue());
}
return retVal;
}
@Test
public void testHasParameter() throws Exception {
IIdType pid0, pid1;
IIdType pid0;
{
Patient patient = new Patient();
patient.addIdentifier().setSystem("urn:system").setValue("001");
@ -156,7 +140,7 @@ public class ResourceProviderDstu3Test extends BaseResourceProviderDstu3Test {
Patient patient = new Patient();
patient.addIdentifier().setSystem("urn:system").setValue("001");
patient.addName().addFamily("Tester").addGiven("Joe");
pid1 = myPatientDao.create(patient, mySrd).getId().toUnqualifiedVersionless();
myPatientDao.create(patient, mySrd).getId().toUnqualifiedVersionless();
}
{
Observation obs = new Observation();
@ -176,10 +160,56 @@ public class ResourceProviderDstu3Test extends BaseResourceProviderDstu3Test {
}
String uri = ourServerBase + "/Patient?_has:Observation:subject:identifier=" + UrlUtil.escape("urn:system|FOO");
List<String> ids = searchAndReturnUnqualifiedIdValues(uri);
List<String> ids = searchAndReturnUnqualifiedVersionlessIdValues(uri);
assertThat(ids, contains(pid0.getValue()));
}
@Test
public void testHistoryWithAtParameter() throws Exception {
String methodName = "testHistoryWithFromAndTo";
Patient patient = new Patient();
patient.addName().addFamily(methodName);
IIdType id = myPatientDao.create(patient, mySrd).getId().toUnqualifiedVersionless();
List<Date> preDates = Lists.newArrayList();
List<String> ids = Lists.newArrayList();
for (int i = 0; i < 10; i++) {
Thread.sleep(10);
preDates.add(new Date());
patient.setId(id);
patient.getName().get(0).getFamily().get(0).setValue(methodName + "_i");
ids.add(myPatientDao.update(patient, mySrd).getId().toUnqualified().getValue());
}
List<String> idValues;
idValues = searchAndReturnUnqualifiedIdValues(ourServerBase + "/Patient/" + id.getIdPart() + "/_history?_at=gt" + toStr(preDates.get(0)) + "&_at=lt" + toStr(preDates.get(3)));
assertThat(idValues, contains(ids.get(2), ids.get(1), ids.get(0)));
idValues = searchAndReturnUnqualifiedIdValues(ourServerBase + "/Patient/_history?_at=gt" + toStr(preDates.get(0)) + "&_at=lt" + toStr(preDates.get(3)));
assertThat(idValues, contains(ids.get(2), ids.get(1), ids.get(0)));
idValues = searchAndReturnUnqualifiedIdValues(ourServerBase + "/_history?_at=gt" + toStr(preDates.get(0)) + "&_at=lt" + toStr(preDates.get(3)));
assertThat(idValues, contains(ids.get(2), ids.get(1), ids.get(0)));
idValues = searchAndReturnUnqualifiedIdValues(ourServerBase + "/_history?_at=gt2060");
assertThat(idValues, empty());
idValues = searchAndReturnUnqualifiedIdValues(ourServerBase + "/_history?_at=" + InstantDt.withCurrentTime().getYear());
assertThat(idValues, hasSize(10)); // 10 is the page size
idValues = searchAndReturnUnqualifiedIdValues(ourServerBase + "/_history?_at=ge" + InstantDt.withCurrentTime().getYear());
assertThat(idValues, hasSize(10));
idValues = searchAndReturnUnqualifiedIdValues(ourServerBase + "/_history?_at=gt" + InstantDt.withCurrentTime().getYear());
assertThat(idValues, hasSize(0));
}
private String toStr(Date theDate) {
return new InstantDt(theDate).getValueAsString();
}
@Test
public void testHasParameterNoResults() throws Exception {
@ -195,11 +225,10 @@ public class ResourceProviderDstu3Test extends BaseResourceProviderDstu3Test {
}
private List<String> searchAndReturnUnqualifiedIdValues(String uri) throws IOException, ClientProtocolException {
private List<String> searchAndReturnUnqualifiedVersionlessIdValues(String uri) throws IOException, ClientProtocolException {
List<String> ids;
HttpGet get = new HttpGet(uri);
CloseableHttpResponse response = ourHttpClient.execute(get);
try {
String resp = IOUtils.toString(response.getEntity().getContent());
@ -212,7 +241,21 @@ public class ResourceProviderDstu3Test extends BaseResourceProviderDstu3Test {
return ids;
}
private List<String> searchAndReturnUnqualifiedIdValues(String uri) throws IOException, ClientProtocolException {
List<String> ids;
HttpGet get = new HttpGet(uri);
CloseableHttpResponse response = ourHttpClient.execute(get);
try {
String resp = IOUtils.toString(response.getEntity().getContent());
ourLog.info(resp);
Bundle bundle = myFhirCtx.newXmlParser().parseResource(Bundle.class, resp);
ids = toUnqualifiedIdValues(bundle);
} finally {
IOUtils.closeQuietly(response);
}
return ids;
}
/**
* Issue submitted by Bryn
@ -224,7 +267,6 @@ public class ResourceProviderDstu3Test extends BaseResourceProviderDstu3Test {
ourClient.create().resource(input).execute().getResource();
}
@Test
public void testSearchByExtendedChars() throws Exception {
for (int i = 0; i < 10; i++) {
@ -254,10 +296,8 @@ public class ResourceProviderDstu3Test extends BaseResourceProviderDstu3Test {
IOUtils.closeQuietly(resp.getEntity().getContent());
}
}
@Override
public void before() throws Exception {
super.before();
@ -576,7 +616,8 @@ public class ResourceProviderDstu3Test extends BaseResourceProviderDstu3Test {
ourLog.info(responseString);
assertEquals(400, response.getStatusLine().getStatusCode());
OperationOutcome oo = myFhirCtx.newXmlParser().parseResource(OperationOutcome.class, responseString);
assertEquals("Can not create resource with ID \"2\", ID must not be supplied on a create (POST) operation (use an HTTP PUT / update operation if you wish to supply an ID)", oo.getIssue().get(0).getDiagnostics());
assertEquals("Can not create resource with ID \"2\", ID must not be supplied on a create (POST) operation (use an HTTP PUT / update operation if you wish to supply an ID)",
oo.getIssue().get(0).getDiagnostics());
} finally {
response.getEntity().getContent().close();
@ -659,7 +700,8 @@ public class ResourceProviderDstu3Test extends BaseResourceProviderDstu3Test {
//@formatter:on
fail();
} catch (PreconditionFailedException e) {
assertEquals("HTTP 412 Precondition Failed: Failed to DELETE resource with match URL \"Patient?identifier=testDeleteConditionalMultiple\" because this search matched 2 resources", e.getMessage());
assertEquals("HTTP 412 Precondition Failed: Failed to DELETE resource with match URL \"Patient?identifier=testDeleteConditionalMultiple\" because this search matched 2 resources",
e.getMessage());
}
// Not deleted yet..
@ -791,8 +833,7 @@ public class ResourceProviderDstu3Test extends BaseResourceProviderDstu3Test {
}
/*
* Try it with a raw socket call. The Apache client won't let us use the unescaped "|" in the URL but we want to
* make sure that works too..
* Try it with a raw socket call. The Apache client won't let us use the unescaped "|" in the URL but we want to make sure that works too..
*/
Socket sock = new Socket();
sock.setSoTimeout(3000);
@ -1326,7 +1367,8 @@ public class ResourceProviderDstu3Test extends BaseResourceProviderDstu3Test {
response.close();
}
get = new HttpGet(ourServerBase + "/Patient/" + pId.getIdPart() + "/$everything?_lastUpdated=%3E" + new InstantType(new Date(time2)).getValueAsString() + "&_lastUpdated=%3C" + new InstantType(new Date(time3)).getValueAsString());
get = new HttpGet(ourServerBase + "/Patient/" + pId.getIdPart() + "/$everything?_lastUpdated=%3E" + new InstantType(new Date(time2)).getValueAsString() + "&_lastUpdated=%3C"
+ new InstantType(new Date(time3)).getValueAsString());
response = ourHttpClient.execute(get);
try {
assertEquals(200, response.getStatusLine().getStatusCode());
@ -1918,7 +1960,8 @@ public class ResourceProviderDstu3Test extends BaseResourceProviderDstu3Test {
Patient patient = new Patient();
patient.addIdentifier().setSystem("urn:system").setValue("testSearchTokenParam001");
patient.addName().addFamily("Tester").addGiven("testSearchTokenParam1");
patient.addCommunication().getLanguage().setText("testSearchTokenParamComText").addCoding().setCode("testSearchTokenParamCode").setSystem("testSearchTokenParamSystem").setDisplay("testSearchTokenParamDisplay");
patient.addCommunication().getLanguage().setText("testSearchTokenParamComText").addCoding().setCode("testSearchTokenParamCode").setSystem("testSearchTokenParamSystem")
.setDisplay("testSearchTokenParamDisplay");
myPatientDao.create(patient, mySrd);
patient = new Patient();
@ -2635,7 +2678,8 @@ public class ResourceProviderDstu3Test extends BaseResourceProviderDstu3Test {
ourLog.info(responseString);
assertEquals(400, response.getStatusLine().getStatusCode());
OperationOutcome oo = myFhirCtx.newXmlParser().parseResource(OperationOutcome.class, responseString);
assertThat(oo.getIssue().get(0).getDiagnostics(), containsString("Can not update resource, resource body must contain an ID element which matches the request URL for update (PUT) operation - Resource body ID of \"333\" does not match URL ID of \"2\""));
assertThat(oo.getIssue().get(0).getDiagnostics(), containsString(
"Can not update resource, resource body must contain an ID element which matches the request URL for update (PUT) operation - Resource body ID of \"333\" does not match URL ID of \"2\""));
} finally {
response.close();
}
@ -2659,7 +2703,8 @@ public class ResourceProviderDstu3Test extends BaseResourceProviderDstu3Test {
ourLog.info(resp);
assertEquals(412, response.getStatusLine().getStatusCode());
assertThat(resp, not(containsString("Resource has no id")));
assertThat(resp, stringContainsInOrder(">ERROR<", "[Patient.contact]", "<pre>SHALL at least contain a contact's details or a reference to an organization", "<issue><severity value=\"error\"/>"));
assertThat(resp,
stringContainsInOrder(">ERROR<", "[Patient.contact]", "<pre>SHALL at least contain a contact's details or a reference to an organization", "<issue><severity value=\"error\"/>"));
} finally {
IOUtils.closeQuietly(response.getEntity().getContent());
response.close();
@ -2785,7 +2830,8 @@ public class ResourceProviderDstu3Test extends BaseResourceProviderDstu3Test {
assertEquals(200, response.getStatusLine().getStatusCode());
assertThat(resp, not(containsString("Resource has no id")));
assertThat(resp, containsString("<pre>No issues detected during validation</pre>"));
assertThat(resp, stringContainsInOrder("<issue>", "<severity value=\"information\"/>", "<code value=\"informational\"/>", "<diagnostics value=\"No issues detected during validation\"/>", "</issue>"));
assertThat(resp,
stringContainsInOrder("<issue>", "<severity value=\"information\"/>", "<code value=\"informational\"/>", "<diagnostics value=\"No issues detected during validation\"/>", "</issue>"));
} finally {
IOUtils.closeQuietly(response.getEntity().getContent());
response.close();
@ -2810,7 +2856,8 @@ public class ResourceProviderDstu3Test extends BaseResourceProviderDstu3Test {
assertEquals(200, response.getStatusLine().getStatusCode());
assertThat(resp, not(containsString("Resource has no id")));
assertThat(resp, containsString("<pre>No issues detected during validation</pre>"));
assertThat(resp, stringContainsInOrder("<issue>", "<severity value=\"information\"/>", "<code value=\"informational\"/>", "<diagnostics value=\"No issues detected during validation\"/>", "</issue>"));
assertThat(resp,
stringContainsInOrder("<issue>", "<severity value=\"information\"/>", "<code value=\"informational\"/>", "<diagnostics value=\"No issues detected during validation\"/>", "</issue>"));
} finally {
IOUtils.closeQuietly(response.getEntity().getContent());
response.close();

View File

@ -172,7 +172,7 @@ public class ResourceProviderDstu3ValueSetTest extends BaseResourceProviderDstu3
.execute();
fail();
} catch (InvalidRequestException e) {
assertEquals("HTTP 400 Bad Request: $expand must EITHER be invoked at the type level, or have an identifier specified, or have a ValueSet specified. Can not combine these options.", e.getMessage());
assertEquals("HTTP 400 Bad Request: $expand must EITHER be invoked at the instance level, or have an identifier specified, or have a ValueSet specified. Can not combine these options.", e.getMessage());
}
//@formatter:on
@ -188,7 +188,7 @@ public class ResourceProviderDstu3ValueSetTest extends BaseResourceProviderDstu3
.execute();
fail();
} catch (InvalidRequestException e) {
assertEquals("HTTP 400 Bad Request: $expand must EITHER be invoked at the type level, or have an identifier specified, or have a ValueSet specified. Can not combine these options.", e.getMessage());
assertEquals("HTTP 400 Bad Request: $expand must EITHER be invoked at the instance level, or have an identifier specified, or have a ValueSet specified. Can not combine these options.", e.getMessage());
}
//@formatter:on

View File

@ -46,6 +46,13 @@ public class DateRangeParamTest {
DateRangeParam range = new DateRangeParam(startDateTime, endDateTime);
assertEquals("2009-12-31T19:00:00.000-05:00", range.getValuesAsQueryTokens().get(0).getValueAsString());
assertEquals("2009-12-31T19:00:00.100-05:00", range.getValuesAsQueryTokens().get(1).getValueAsString());
// Now try with arguments reversed (should still create same range)
range = new DateRangeParam(endDateTime, startDateTime);
assertEquals("2009-12-31T19:00:00.000-05:00", range.getValuesAsQueryTokens().get(0).getValueAsString());
assertEquals("2009-12-31T19:00:00.100-05:00", range.getValuesAsQueryTokens().get(1).getValueAsString());
} finally {
TimeZone.setDefault(tz);
}

View File

@ -32,10 +32,126 @@ public class BaseDateTimeDtDstu2Test {
private static FhirContext ourCtx = FhirContext.forDstu2();
private static Locale ourDefaultLocale;
private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(BaseDateTimeDtDstu2Test.class);
private SimpleDateFormat myDateInstantParser;
private FastDateFormat myDateInstantZoneParser;
@Test
public void testSetPartialsYearFromExisting() {
InstantDt dt = new InstantDt("2011-03-11T15:44:13.27564757855254768473697463986328969635-08:00");
dt.setYear(2016);
assertEquals(2016, dt.getYear().intValue());
String valueAsString = dt.getValueAsString();
ourLog.info(valueAsString);
assertEquals("2016-03-11T15:44:13.27564757855254768473697463986328969635-08:00", valueAsString);
}
@Test
public void testSetPartialsMonthFromExisting() {
InstantDt dt = new InstantDt("2011-03-11T15:44:13.27564757855254768473697463986328969635-08:00");
dt.setMonth(3);
assertEquals(3, dt.getMonth().intValue());
String valueAsString = dt.getValueAsString();
ourLog.info(valueAsString);
assertEquals("2011-04-11T15:44:13.27564757855254768473697463986328969635-08:00", valueAsString);
}
@Test
public void testSetPartialsDayFromExisting() {
InstantDt dt = new InstantDt("2011-03-11T15:44:13.27564757855254768473697463986328969635-08:00");
dt.setDay(15);
assertEquals(15, dt.getDay().intValue());
String valueAsString = dt.getValueAsString();
ourLog.info(valueAsString);
assertEquals("2011-03-15T15:44:13.27564757855254768473697463986328969635-08:00", valueAsString);
}
@Test
public void testSetPartialsHourFromExisting() {
InstantDt dt = new InstantDt("2011-03-11T15:44:13.27564757855254768473697463986328969635-08:00");
dt.setHour(23);
assertEquals(23, dt.getHour().intValue());
String valueAsString = dt.getValueAsString();
ourLog.info(valueAsString);
assertEquals("2011-03-11T23:44:13.27564757855254768473697463986328969635-08:00", valueAsString);
}
@Test
public void testSetPartialsMinuteFromExisting() {
InstantDt dt = new InstantDt("2011-03-11T15:44:13.27564757855254768473697463986328969635-08:00");
dt.setMinute(54);
assertEquals(54, dt.getMinute().intValue());
String valueAsString = dt.getValueAsString();
ourLog.info(valueAsString);
assertEquals("2011-03-11T15:54:13.27564757855254768473697463986328969635-08:00", valueAsString);
}
@Test
public void testSetPartialsSecondFromExisting() {
InstantDt dt = new InstantDt("2011-03-11T15:44:13.27564757855254768473697463986328969635-08:00");
dt.setSecond(1);
assertEquals(1, dt.getSecond().intValue());
String valueAsString = dt.getValueAsString();
ourLog.info(valueAsString);
assertEquals("2011-03-11T15:44:01.27564757855254768473697463986328969635-08:00", valueAsString);
}
@Test
public void testSetPartialsMillisFromExisting() {
InstantDt dt = new InstantDt("2011-03-11T15:44:13.27564757855254768473697463986328969635-08:00");
dt.setMillis(12);
assertEquals(12, dt.getMillis().intValue());
assertEquals(12 * BaseDateTimeDt.NANOS_PER_MILLIS, dt.getNanos().longValue());
String valueAsString = dt.getValueAsString();
ourLog.info(valueAsString);
assertEquals("2011-03-11T15:44:13.012-08:00", valueAsString);
}
@Test
public void testSetPartialsNanosFromExisting() {
InstantDt dt = new InstantDt("2011-03-11T15:44:13.27564757855254768473697463986328969635-08:00");
dt.setNanos(100000000L);
assertEquals(100000000L, dt.getNanos().longValue());
assertEquals(100, dt.getMillis().intValue());
String valueAsString = dt.getValueAsString();
ourLog.info(valueAsString);
assertEquals("2011-03-11T15:44:13.100-08:00", valueAsString);
}
@Test
public void testSetPartialsInvalid() {
InstantDt dt = new InstantDt("2011-03-11T15:44:13.27564757855254768473697463986328969635-08:00");
dt.setNanos(0);
dt.setNanos(BaseDateTimeDt.NANOS_PER_SECOND - 1);
try {
dt.setNanos(BaseDateTimeDt.NANOS_PER_SECOND);
} catch (IllegalArgumentException e) {
assertEquals("Value 1000000000 is not between allowable range: 0 - 999999999", e.getMessage());
}
}
@Test
public void testGetPartials() {
InstantDt dt = new InstantDt("2011-03-11T15:44:13.27564757855254768473697463986328969635-08:00");
assertEquals(2011, dt.getYear().intValue());
assertEquals(2, dt.getMonth().intValue());
assertEquals(11, dt.getDay().intValue());
assertEquals(15, dt.getHour().intValue());
assertEquals(44, dt.getMinute().intValue());
assertEquals(13, dt.getSecond().intValue());
assertEquals(275, dt.getMillis().intValue());
assertEquals(275647578L, dt.getNanos().longValue());
dt = new InstantDt();
assertEquals(null, dt.getYear());
assertEquals(null, dt.getMonth());
assertEquals(null, dt.getDay());
assertEquals(null, dt.getHour());
assertEquals(null, dt.getMinute());
assertEquals(null, dt.getSecond());
assertEquals(null, dt.getMillis());
assertEquals(null, dt.getNanos());
}
@Before
public void before() {
myDateInstantParser = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

View File

@ -0,0 +1,56 @@
package ca.uhn.fhir.model.primitive;
import static org.junit.Assert.*;
import org.junit.Test;
public class UriDtTest {
@Test
public void testFromOid() {
UriDt uri = UriDt.fromOid("0.1.2.3.4");
assertEquals("urn:oid:0.1.2.3.4", uri.getValue());
}
@Test
public void testFromOidNull() {
UriDt uri = UriDt.fromOid(null);
assertEquals(null, uri.getValue());
}
@Test
public void testEqualsObject() {
UriDt dt = new UriDt("http://example.com/foo");
assertTrue(dt.equals(dt));
assertFalse(dt.equals(null));
assertFalse(dt.equals(new UriDt()));
assertTrue(dt.equals(new UriDt("http://example.com/foo")));
assertTrue(dt.equals(new UriDt("http://example.com/foo/")));
assertFalse(dt.equals(new UriDt("http://blah.com/foo/")));
assertFalse(dt.equals(new StringDt("http://example.com/foo")));
}
@Test
public void testEqualsString() {
UriDt dt = new UriDt("http://example.com/foo");
assertTrue(dt.equals("http://example.com/foo"));
}
@Test
public void testHashCode() {
UriDt dt = new UriDt("http://example.com/foo");
assertEquals(-1671329151, dt.hashCode());
dt = new UriDt();
assertEquals(31, dt.hashCode());
}
@Test
public void testSetInvalid() {
UriDt dt = new UriDt();
dt.setValue("blah : // AA");
dt.hashCode();
}
}

View File

@ -1040,8 +1040,11 @@ public class XmlParserDstu2Test {
}
/**
* Make sure whitespace is preserved for pre tags
*/
@Test
public void testEncodeDivWithPre() {
public void testEncodeDivWithPrePrettyPrint() {
Patient p = new Patient();
p.getText().setDiv("<div>\n\n<p>A P TAG</p><p><pre>line1\nline2\nline3 <b>BOLD</b></pre></p></div>");
@ -1059,6 +1062,28 @@ public class XmlParserDstu2Test {
}
/**
* Make sure whitespace is preserved for pre tags
*/
@Test
public void testEncodeDivWithPreNonPrettyPrint() {
Patient p = new Patient();
p.getText().setDiv("<div>\n\n<p>A P TAG</p><p><pre>line1\nline2\nline3 <b>BOLD</b></pre></p></div>");
String output = ourCtx.newXmlParser().setPrettyPrint(false).encodeResourceToString(p);
ourLog.info(output);
//@formatter:off
assertThat(output, stringContainsInOrder(
"<text><div",
"<p>A P TAG</p><p>",
"<pre>line1\nline2\nline3 <b>BOLD</b></pre>"
));
//@formatter:on
}
@Test
public void testEncodeDoesntIncludeUuidId() {
Patient p = new Patient();

View File

@ -119,8 +119,31 @@ public class XmlParserDstu3Test {
ourCtx.setNarrativeGenerator(null);
}
/**
* Make sure whitespace is preserved for pre tags
*/
@Test
public void testEncodeDivWithPre() {
public void testEncodeDivWithPreNonPrettyPrint() {
Patient p = new Patient();
p.getText().setDivAsString("<div>\n\n<p>A P TAG</p><p><pre>line1\nline2\nline3 <b>BOLD</b></pre></p></div>");
String output = ourCtx.newXmlParser().setPrettyPrint(false).encodeResourceToString(p);
ourLog.info(output);
//@formatter:off
assertThat(output, stringContainsInOrder(
"<text><div",
"<p>A P TAG</p><p>",
"<pre>line1\nline2\nline3 <b>BOLD</b></pre>"
));
//@formatter:on
}
@Test
public void testEncodeDivWithPrePrettyPrint() {
Patient p = new Patient();
p.getText().setDivAsString("<div>\n\n<p>A P TAG</p><p><pre>line1\nline2\nline3 <b>BOLD</b></pre></p></div>");