src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
ACLFileParser { public static AuthorizationsCollector parse(File file) throws ParseException { if (file == null) { LOG.warn("parsing NULL file, so fallback on default configuration!"); return AuthorizationsCollector.emptyImmutableCollector(); } if (!file.exists()) { LOG.warn( String.format( "parsing not existing file %s, so fallback on default configuration!", file.getAbsolutePath())); return AuthorizationsCollector.emptyImmutableCollector(); } try { FileReader reader = new FileReader(file); return parse(reader); } catch (FileNotFoundException fex) { LOG.warn( String.format( "parsing not existing file %s, so fallback on default configuration!", file.getAbsolutePath()), fex); return AuthorizationsCollector.emptyImmutableCollector(); } } private ACLFileParser(); static AuthorizationsCollector parse(File file); static AuthorizationsCollector parse(Reader reader); }
@Test public void testParseEmpty() throws ParseException { Reader conf = new StringReader(" "); AuthorizationsCollector authorizations = ACLFileParser.parse(conf); assertTrue(authorizations.isEmpty()); } @Test public void testParseValidComment() throws ParseException { Reader conf = new StringReader("#simple comment"); AuthorizationsCollector authorizations = ACLFileParser.parse(conf); assertTrue(authorizations.isEmpty()); } @Test(expected = ParseException.class) public void testParseInvalidComment() throws ParseException { Reader conf = new StringReader(" #simple comment"); ACLFileParser.parse(conf); } @Test public void testParseSingleLineACL() throws ParseException { Reader conf = new StringReader("topic /weather/italy/anemometer"); AuthorizationsCollector authorizations = ACLFileParser.parse(conf); assertTrue(authorizations.canRead(new Topic("/weather/italy/anemometer"), "", "")); assertTrue(authorizations.canWrite(new Topic("/weather/italy/anemometer"), "", "")); }
ConfigurationParser { void parse(File file) throws ParseException { if (file == null) { LOG.warn("parsing NULL file, so fallback on default configuration!"); return; } if (!file.exists()) { LOG.warn( String.format( "parsing not existing file %s, so fallback on default configuration!", file.getAbsolutePath())); return; } try { FileReader reader = new FileReader(file); parse(reader); } catch (FileNotFoundException fex) { LOG.warn( String.format( "parsing not existing file %s, so fallback on default configuration!", file.getAbsolutePath()), fex); return; } } }
@Test(expected = ParseException.class) public void parseInvalidComment() throws ParseException { Reader conf = new StringReader(" #simple comment"); m_parser.parse(conf); }
BrokerInterceptor implements Interceptor { @Override public void notifyClientConnected(final MqttConnectMessage msg) { for (final InterceptHandler handler : this.handlers.get(InterceptConnectMessage.class)) { if(LOG.isDebugEnabled()){ LOG.debug("Sending MQTT CONNECT message to interceptor. CId={}, interceptorId={}", msg.payload().clientIdentifier(), handler.getID()); } executor.execute(new Runnable() { @Override public void run() { handler.onConnect(new InterceptConnectMessage(msg)); } }); } } private BrokerInterceptor(int poolSize, List<InterceptHandler> handlers); BrokerInterceptor(List<InterceptHandler> handlers); BrokerInterceptor(IConfig props, List<InterceptHandler> handlers); @Override void notifyClientConnected(final MqttConnectMessage msg); @Override void notifyClientDisconnected(final String clientID, final String username); @Override void notifyClientConnectionLost(final String clientID, final String username); @Override void notifyTopicPublished(final MoquetteMessage msg, final String clientID, final String username); @Override void notifyTopicSubscribed(final Subscription sub, final String username); @Override void notifyTopicUnsubscribed(final String topic, final String clientID, final String username); @Override void notifyMessageAcknowledged(final InterceptAcknowledgedMessage msg); @Override void addInterceptHandler(InterceptHandler interceptHandler); @Override void removeInterceptHandler(InterceptHandler interceptHandler); }
@Test public void testNotifyClientConnected() throws Exception { interceptor.notifyClientConnected(MqttMessageBuilders.connect().build()); interval(); assertEquals(40, n.get()); }
BrokerInterceptor implements Interceptor { @Override public void notifyClientDisconnected(final String clientID, final String username) { for (final InterceptHandler handler : this.handlers.get(InterceptDisconnectMessage.class)) { if(LOG.isDebugEnabled()){ LOG.debug("Notifying MQTT client disconnection to interceptor. CId={}, username={}, interceptorId={}", clientID, username, handler.getID()); } executor.execute(new Runnable() { @Override public void run() { handler.onDisconnect(new InterceptDisconnectMessage(clientID, username)); } }); } } private BrokerInterceptor(int poolSize, List<InterceptHandler> handlers); BrokerInterceptor(List<InterceptHandler> handlers); BrokerInterceptor(IConfig props, List<InterceptHandler> handlers); @Override void notifyClientConnected(final MqttConnectMessage msg); @Override void notifyClientDisconnected(final String clientID, final String username); @Override void notifyClientConnectionLost(final String clientID, final String username); @Override void notifyTopicPublished(final MoquetteMessage msg, final String clientID, final String username); @Override void notifyTopicSubscribed(final Subscription sub, final String username); @Override void notifyTopicUnsubscribed(final String topic, final String clientID, final String username); @Override void notifyMessageAcknowledged(final InterceptAcknowledgedMessage msg); @Override void addInterceptHandler(InterceptHandler interceptHandler); @Override void removeInterceptHandler(InterceptHandler interceptHandler); }
@Test public void testNotifyClientDisconnected() throws Exception { interceptor.notifyClientDisconnected("cli1234", "cli1234"); interval(); assertEquals(50, n.get()); }
BrokerInterceptor implements Interceptor { @Override public void notifyTopicPublished(final MoquetteMessage msg, final String clientID, final String username) { int messageId = msg.getMessageId(); String topic = msg.getTopic(); for (final InterceptHandler handler : this.handlers.get(InterceptPublishMessage.class)) { if(LOG.isDebugEnabled()){ LOG.debug("Notifying MQTT PUBLISH message to interceptor. CId={}, messageId={}, topic={}, interceptorId={}", clientID, messageId, topic, handler.getID()); } executor.execute(new Runnable() { @Override public void run() { handler.onPublish(new InterceptPublishMessage(msg, clientID, username)); } }); } } private BrokerInterceptor(int poolSize, List<InterceptHandler> handlers); BrokerInterceptor(List<InterceptHandler> handlers); BrokerInterceptor(IConfig props, List<InterceptHandler> handlers); @Override void notifyClientConnected(final MqttConnectMessage msg); @Override void notifyClientDisconnected(final String clientID, final String username); @Override void notifyClientConnectionLost(final String clientID, final String username); @Override void notifyTopicPublished(final MoquetteMessage msg, final String clientID, final String username); @Override void notifyTopicSubscribed(final Subscription sub, final String username); @Override void notifyTopicUnsubscribed(final String topic, final String clientID, final String username); @Override void notifyMessageAcknowledged(final InterceptAcknowledgedMessage msg); @Override void addInterceptHandler(InterceptHandler interceptHandler); @Override void removeInterceptHandler(InterceptHandler interceptHandler); }
@Test public void testNotifyTopicPublished() throws Exception { MqttPublishMessage msg = MqttMessageBuilders.publish().qos(MqttQoS.AT_MOST_ONCE).payload(Unpooled.copiedBuffer("Hello".getBytes())).build(); MoquetteMessage moquetteMessage = new MoquetteMessage(msg.fixedHeader(), msg.variableHeader(), msg.content()); interceptor.notifyTopicPublished(moquetteMessage, "cli1234", "cli1234"); interval(); assertEquals(60, n.get()); }
BrokerInterceptor implements Interceptor { @Override public void notifyTopicSubscribed(final Subscription sub, final String username) { for (final InterceptHandler handler : this.handlers.get(InterceptSubscribeMessage.class)) { if(LOG.isDebugEnabled()){ LOG.debug("Notifying MQTT SUBSCRIBE message to interceptor. CId={}, topicFilter={}, interceptorId={}", sub.getClientId(), sub.getTopicFilter(), handler.getID()); } executor.execute(new Runnable() { @Override public void run() { handler.onSubscribe(new InterceptSubscribeMessage(sub, username)); } }); } } private BrokerInterceptor(int poolSize, List<InterceptHandler> handlers); BrokerInterceptor(List<InterceptHandler> handlers); BrokerInterceptor(IConfig props, List<InterceptHandler> handlers); @Override void notifyClientConnected(final MqttConnectMessage msg); @Override void notifyClientDisconnected(final String clientID, final String username); @Override void notifyClientConnectionLost(final String clientID, final String username); @Override void notifyTopicPublished(final MoquetteMessage msg, final String clientID, final String username); @Override void notifyTopicSubscribed(final Subscription sub, final String username); @Override void notifyTopicUnsubscribed(final String topic, final String clientID, final String username); @Override void notifyMessageAcknowledged(final InterceptAcknowledgedMessage msg); @Override void addInterceptHandler(InterceptHandler interceptHandler); @Override void removeInterceptHandler(InterceptHandler interceptHandler); }
@Test public void testNotifyTopicSubscribed() throws Exception { interceptor.notifyTopicSubscribed(new Subscription("cli1", new Topic("o2"), MqttQoS.AT_MOST_ONCE), "cli1234"); interval(); assertEquals(70, n.get()); }
BrokerInterceptor implements Interceptor { @Override public void notifyTopicUnsubscribed(final String topic, final String clientID, final String username) { for (final InterceptHandler handler : this.handlers.get(InterceptUnsubscribeMessage.class)) { if(LOG.isDebugEnabled()){ LOG.debug("Notifying MQTT UNSUBSCRIBE message to interceptor. CId={}, topic={}, interceptorId={}", clientID, topic, handler.getID()); } executor.execute(new Runnable() { @Override public void run() { handler.onUnsubscribe(new InterceptUnsubscribeMessage(topic, clientID, username)); } }); } } private BrokerInterceptor(int poolSize, List<InterceptHandler> handlers); BrokerInterceptor(List<InterceptHandler> handlers); BrokerInterceptor(IConfig props, List<InterceptHandler> handlers); @Override void notifyClientConnected(final MqttConnectMessage msg); @Override void notifyClientDisconnected(final String clientID, final String username); @Override void notifyClientConnectionLost(final String clientID, final String username); @Override void notifyTopicPublished(final MoquetteMessage msg, final String clientID, final String username); @Override void notifyTopicSubscribed(final Subscription sub, final String username); @Override void notifyTopicUnsubscribed(final String topic, final String clientID, final String username); @Override void notifyMessageAcknowledged(final InterceptAcknowledgedMessage msg); @Override void addInterceptHandler(InterceptHandler interceptHandler); @Override void removeInterceptHandler(InterceptHandler interceptHandler); }
@Test public void testNotifyTopicUnsubscribed() throws Exception { interceptor.notifyTopicUnsubscribed("o2", "cli1234", "cli1234"); interval(); assertEquals(80, n.get()); }
MapDBPersistentStore implements IStore { @Override public void close() { if (this.m_db.isClosed()) { LOG.warn("MapDB store is already closed. Nothing will be done"); return; } LOG.info("Performing last commit to MapDB"); this.m_db.commit(); LOG.info("Closing MapDB store"); this.m_db.close(); LOG.info("Stopping MapDB commit tasks"); this.m_scheduler.shutdown(); try { m_scheduler.awaitTermination(10L, TimeUnit.SECONDS); } catch (InterruptedException e) { } if (!m_scheduler.isTerminated()) { LOG.warn("Forcing shutdown of MapDB commit tasks"); m_scheduler.shutdown(); } LOG.info("MapDB store has been closed successfully"); } MapDBPersistentStore(IConfig props); @Override IMessagesStore messagesStore(); @Override ISessionsStore sessionsStore(); @Override void initStore(); @Override void close(); }
@Test public void testCloseShutdownCommitTask() throws InterruptedException { m_storageService.close(); assertTrue("Storage service scheduler can't be stopped in 3 seconds", m_storageService.m_scheduler.awaitTermination(3, TimeUnit.SECONDS)); assertTrue(m_storageService.m_scheduler.isTerminated()); }
ProtocolProcessor { public void processSubscribe(Channel channel, MqttSubscribeMessage msg) { String clientID = NettyUtils.clientID(channel); int messageID = messageId(msg); LOG.info("Processing SUBSCRIBE message. CId={}, messageId={}", clientID, messageID); RunningSubscription executionKey = new RunningSubscription(clientID, messageID); SubscriptionState currentStatus = subscriptionInCourse.putIfAbsent(executionKey, SubscriptionState.VERIFIED); if (currentStatus != null) { LOG.warn("Client sent another SUBSCRIBE message while this one was being processed CId={}, messageId={}", clientID, messageID); return; } String username = NettyUtils.userName(channel); List<MqttTopicSubscription> ackTopics = doVerify(clientID, username, msg); MqttSubAckMessage ackMessage = doAckMessageFromValidateFilters(ackTopics, messageID); if (!this.subscriptionInCourse.replace(executionKey, SubscriptionState.VERIFIED, SubscriptionState.STORED)) { LOG.warn("Client sent another SUBSCRIBE message while the topic filters were being verified CId={}, " + "messageId={}", clientID, messageID); return; } LOG.info("Creating and storing subscriptions CId={}, messageId={}, topics={}", clientID, messageID, ackTopics); List<Subscription> newSubscriptions = doStoreSubscription(ackTopics, clientID); for (Subscription subscription : newSubscriptions) { subscriptions.add(subscription.asClientTopicCouple()); } LOG.info("Sending SUBACK response CId={}, messageId={}", clientID, messageID); channel.writeAndFlush(ackMessage); for (Subscription subscription : newSubscriptions) { publishRetainedMessagesInSession(subscription, username); } boolean success = this.subscriptionInCourse.remove(executionKey, SubscriptionState.STORED); if (!success) { LOG.warn("Unable to perform the final subscription state update CId={}, messageId={}", clientID, messageID); } } ProtocolProcessor(); void init(SubscriptionsDirectory subscriptions, IMessagesStore storageService, ISessionsStore sessionsStore, IAuthenticator authenticator, boolean allowAnonymous, IAuthorizator authorizator, BrokerInterceptor interceptor); void init(SubscriptionsDirectory subscriptions, IMessagesStore storageService, ISessionsStore sessionsStore, IAuthenticator authenticator, boolean allowAnonymous, boolean allowZeroByteClientId, IAuthorizator authorizator, BrokerInterceptor interceptor); void init(SubscriptionsDirectory subscriptions, IMessagesStore storageService, ISessionsStore sessionsStore, IAuthenticator authenticator, boolean allowAnonymous, boolean allowZeroByteClientId, IAuthorizator authorizator, BrokerInterceptor interceptor, String serverPort); void processConnect(Channel channel, MqttConnectMessage msg); void processPubAck(Channel channel, MqttPubAckMessage msg); static IMessagesStore.StoredMessage asStoredMessage(MqttPublishMessage msg); void processPublish(Channel channel, MqttPublishMessage msg); void internalPublish(MqttPublishMessage msg, final String clientId); void processPubRel(Channel channel, MqttMessage msg); void processPubRec(Channel channel, MqttMessage msg); void processPubComp(Channel channel, MqttMessage msg); void processDisconnect(Channel channel); void processConnectionLost(String clientID, Channel channel); void processUnsubscribe(Channel channel, MqttUnsubscribeMessage msg); void processSubscribe(Channel channel, MqttSubscribeMessage msg); void notifyChannelWritable(Channel channel); void addInterceptHandler(InterceptHandler interceptHandler); void removeInterceptHandler(InterceptHandler interceptHandler); IMessagesStore getMessagesStore(); ISessionsStore getSessionsStore(); }
@Test public void testSubscribe() { MqttSubscribeMessage msg = MqttMessageBuilders.subscribe().addSubscription(MqttQoS.AT_MOST_ONCE, FAKE_TOPIC) .messageId(10).build(); m_sessionStore.createNewSession(FAKE_CLIENT_ID, false); m_processor.processSubscribe(m_channel, msg); assertTrue(m_channel.readOutbound() instanceof MqttSubAckMessage); Subscription expectedSubscription = new Subscription(FAKE_CLIENT_ID, new Topic(FAKE_TOPIC), MqttQoS.AT_MOST_ONCE); assertTrue(subscriptions.contains(expectedSubscription)); } @Test public void testDoubleSubscribe() { MqttSubscribeMessage msg = MqttMessageBuilders.subscribe().addSubscription(MqttQoS.AT_MOST_ONCE, FAKE_TOPIC) .messageId(10).build(); m_sessionStore.createNewSession(FAKE_CLIENT_ID, false); assertEquals(0, subscriptions.size()); m_processor.processSubscribe(m_channel, msg); assertEquals(1, subscriptions.size()); m_processor.processSubscribe(m_channel, msg); assertEquals(1, subscriptions.size()); Subscription expectedSubscription = new Subscription(FAKE_CLIENT_ID, new Topic(FAKE_TOPIC), MqttQoS.AT_MOST_ONCE); assertTrue(subscriptions.contains(expectedSubscription)); } @Test public void testSubscribeWithBadFormattedTopic() { MqttSubscribeMessage msg = MqttMessageBuilders.subscribe().addSubscription(MqttQoS.AT_MOST_ONCE, BAD_FORMATTED_TOPIC) .messageId(10).build(); m_sessionStore.createNewSession(FAKE_CLIENT_ID, false); assertEquals(0, subscriptions.size()); m_processor.processSubscribe(m_channel, msg); assertEquals(0, subscriptions.size()); Object recvSubAckMessage = m_channel.readOutbound(); assertTrue(recvSubAckMessage instanceof MqttSubAckMessage); verifyFailureQos((MqttSubAckMessage) recvSubAckMessage); }
ProtocolProcessor { public void processUnsubscribe(Channel channel, MqttUnsubscribeMessage msg) { List<String> topics = msg.payload().topics(); String clientID = NettyUtils.clientID(channel); LOG.info("Processing UNSUBSCRIBE message. CId={}, topics={}", clientID, topics); ClientSession clientSession = m_sessionsStore.sessionForClient(clientID); for (String t : topics) { Topic topic = new Topic(t); boolean validTopic = topic.isValid(); if (!validTopic) { channel.close(); LOG.error("Topic filter is not valid. CId={}, topics={}, badTopicFilter={}", clientID, topics, topic); return; } if(LOG.isDebugEnabled()){ LOG.debug("Removing subscription. CId={}, topic={}", clientID, topic); } subscriptions.removeSubscription(topic, clientID); clientSession.unsubscribeFrom(topic); String username = NettyUtils.userName(channel); m_interceptor.notifyTopicUnsubscribed(topic.toString(), clientID, username); } int messageID = msg.variableHeader().messageId(); MqttFixedHeader fixedHeader = new MqttFixedHeader(MqttMessageType.UNSUBACK, false, AT_LEAST_ONCE, false, 0); MqttUnsubAckMessage ackMessage = new MqttUnsubAckMessage(fixedHeader, from(messageID)); LOG.info("Sending UNSUBACK message. CId={}, topics={}, messageId={}", clientID, topics, messageID); channel.writeAndFlush(ackMessage); } ProtocolProcessor(); void init(SubscriptionsDirectory subscriptions, IMessagesStore storageService, ISessionsStore sessionsStore, IAuthenticator authenticator, boolean allowAnonymous, IAuthorizator authorizator, BrokerInterceptor interceptor); void init(SubscriptionsDirectory subscriptions, IMessagesStore storageService, ISessionsStore sessionsStore, IAuthenticator authenticator, boolean allowAnonymous, boolean allowZeroByteClientId, IAuthorizator authorizator, BrokerInterceptor interceptor); void init(SubscriptionsDirectory subscriptions, IMessagesStore storageService, ISessionsStore sessionsStore, IAuthenticator authenticator, boolean allowAnonymous, boolean allowZeroByteClientId, IAuthorizator authorizator, BrokerInterceptor interceptor, String serverPort); void processConnect(Channel channel, MqttConnectMessage msg); void processPubAck(Channel channel, MqttPubAckMessage msg); static IMessagesStore.StoredMessage asStoredMessage(MqttPublishMessage msg); void processPublish(Channel channel, MqttPublishMessage msg); void internalPublish(MqttPublishMessage msg, final String clientId); void processPubRel(Channel channel, MqttMessage msg); void processPubRec(Channel channel, MqttMessage msg); void processPubComp(Channel channel, MqttMessage msg); void processDisconnect(Channel channel); void processConnectionLost(String clientID, Channel channel); void processUnsubscribe(Channel channel, MqttUnsubscribeMessage msg); void processSubscribe(Channel channel, MqttSubscribeMessage msg); void notifyChannelWritable(Channel channel); void addInterceptHandler(InterceptHandler interceptHandler); void removeInterceptHandler(InterceptHandler interceptHandler); IMessagesStore getMessagesStore(); ISessionsStore getSessionsStore(); }
@Test public void testUnsubscribeWithBadFormattedTopic() { MqttUnsubscribeMessage msg = MqttMessageBuilders.unsubscribe().addTopicFilter(BAD_FORMATTED_TOPIC).messageId(1) .build(); m_processor.processUnsubscribe(m_channel, msg); assertFalse("If client unsubscribe with bad topic than channel must be closed", m_channel.isOpen()); }
ProtocolProcessor { static MqttQoS lowerQosToTheSubscriptionDesired(Subscription sub, MqttQoS qos) { if (qos.value() > sub.getRequestedQos().value()) { qos = sub.getRequestedQos(); } return qos; } ProtocolProcessor(); void init(SubscriptionsDirectory subscriptions, IMessagesStore storageService, ISessionsStore sessionsStore, IAuthenticator authenticator, boolean allowAnonymous, IAuthorizator authorizator, BrokerInterceptor interceptor); void init(SubscriptionsDirectory subscriptions, IMessagesStore storageService, ISessionsStore sessionsStore, IAuthenticator authenticator, boolean allowAnonymous, boolean allowZeroByteClientId, IAuthorizator authorizator, BrokerInterceptor interceptor); void init(SubscriptionsDirectory subscriptions, IMessagesStore storageService, ISessionsStore sessionsStore, IAuthenticator authenticator, boolean allowAnonymous, boolean allowZeroByteClientId, IAuthorizator authorizator, BrokerInterceptor interceptor, String serverPort); void processConnect(Channel channel, MqttConnectMessage msg); void processPubAck(Channel channel, MqttPubAckMessage msg); static IMessagesStore.StoredMessage asStoredMessage(MqttPublishMessage msg); void processPublish(Channel channel, MqttPublishMessage msg); void internalPublish(MqttPublishMessage msg, final String clientId); void processPubRel(Channel channel, MqttMessage msg); void processPubRec(Channel channel, MqttMessage msg); void processPubComp(Channel channel, MqttMessage msg); void processDisconnect(Channel channel); void processConnectionLost(String clientID, Channel channel); void processUnsubscribe(Channel channel, MqttUnsubscribeMessage msg); void processSubscribe(Channel channel, MqttSubscribeMessage msg); void notifyChannelWritable(Channel channel); void addInterceptHandler(InterceptHandler interceptHandler); void removeInterceptHandler(InterceptHandler interceptHandler); IMessagesStore getMessagesStore(); ISessionsStore getSessionsStore(); }
@Test public void testLowerTheQosToTheRequestedBySubscription() { Subscription subQos1 = new Subscription("Sub A", new Topic("a/b"), MqttQoS.AT_LEAST_ONCE); assertEquals(MqttQoS.AT_LEAST_ONCE, lowerQosToTheSubscriptionDesired(subQos1, MqttQoS.EXACTLY_ONCE)); Subscription subQos2 = new Subscription("Sub B", new Topic("a/+"), MqttQoS.EXACTLY_ONCE); assertEquals(MqttQoS.EXACTLY_ONCE, lowerQosToTheSubscriptionDesired(subQos2, MqttQoS.EXACTLY_ONCE)); }
DBAuthenticator implements IAuthenticator { @Override public synchronized boolean checkValid(String clientId, String username, byte[] password) { if (username == null || password == null) { LOG.info("username or password was null"); return false; } ResultSet r = null; try { this.preparedStatement.setString(1, username); r = this.preparedStatement.executeQuery(); if (r.next()) { final String foundPwq = r.getString(1); messageDigest.update(password); byte[] digest = messageDigest.digest(); String encodedPasswd = new String(Hex.encodeHex(digest)); return foundPwq.equals(encodedPasswd); } r.close(); } catch (SQLException e) { e.printStackTrace(); } return false; } DBAuthenticator(IConfig conf); DBAuthenticator(String driver, String jdbcUrl, String sqlQuery, String digestMethod); @Override synchronized boolean checkValid(String clientId, String username, byte[] password); }
@Test public void Db_verifyValid() { final DBAuthenticator dbAuthenticator = new DBAuthenticator( ORG_H2_DRIVER, JDBC_H2_MEM_TEST, "SELECT PASSWORD FROM ACCOUNT WHERE LOGIN=?", SHA_256); assertTrue(dbAuthenticator.checkValid(null, "dbuser", "password".getBytes())); } @Test public void Db_verifyInvalidLogin() { final DBAuthenticator dbAuthenticator = new DBAuthenticator( ORG_H2_DRIVER, JDBC_H2_MEM_TEST, "SELECT PASSWORD FROM ACCOUNT WHERE LOGIN=?", SHA_256); assertFalse(dbAuthenticator.checkValid(null, "dbuser2", "password".getBytes())); } @Test public void Db_verifyInvalidPassword() { final DBAuthenticator dbAuthenticator = new DBAuthenticator( ORG_H2_DRIVER, JDBC_H2_MEM_TEST, "SELECT PASSWORD FROM ACCOUNT WHERE LOGIN=?", SHA_256); assertFalse(dbAuthenticator.checkValid(null, "dbuser", "wrongPassword".getBytes())); }
ChainingPrincipalResolver implements PrincipalResolver { public boolean supports(final Credential credential) { return this.chain.get(0).supports(credential); } void setChain(final List<PrincipalResolver> chain); Principal resolve(final Credential credential); boolean supports(final Credential credential); }
@Test public void testSupports() throws Exception { final Credential credential = mock(Credential.class); when(credential.getId()).thenReturn("a"); final PrincipalResolver resolver1 = mock(PrincipalResolver.class); when(resolver1.supports(eq(credential))).thenReturn(true); final PrincipalResolver resolver2 = mock(PrincipalResolver.class); when(resolver2.supports(eq(credential))).thenReturn(false); final ChainingPrincipalResolver resolver = new ChainingPrincipalResolver(); resolver.setChain(Arrays.asList(resolver1, resolver2)); assertTrue(resolver.supports(credential)); }
ChainingPrincipalResolver implements PrincipalResolver { public Principal resolve(final Credential credential) { Principal result = null; Credential input = credential; for (final PrincipalResolver resolver : this.chain) { if (result != null) { input = new IdentifiableCredential(result.getId()); } result = resolver.resolve(input); } return result; } void setChain(final List<PrincipalResolver> chain); Principal resolve(final Credential credential); boolean supports(final Credential credential); }
@Test public void testResolve() throws Exception { final Credential credential = mock(Credential.class); when(credential.getId()).thenReturn("input"); final PrincipalResolver resolver1 = mock(PrincipalResolver.class); when(resolver1.supports(eq(credential))).thenReturn(true); when(resolver1.resolve((eq(credential)))).thenReturn(new SimplePrincipal("output")); final PrincipalResolver resolver2 = mock(PrincipalResolver.class); when(resolver2.supports(any(Credential.class))).thenReturn(false); when(resolver2.resolve(argThat(new ArgumentMatcher<Credential>() { @Override public boolean matches(final Object o) { return ((Credential) o).getId().equals("output"); } }))).thenReturn( new SimplePrincipal("final", Collections.<String, Object>singletonMap("mail", "final@example.com"))); final ChainingPrincipalResolver resolver = new ChainingPrincipalResolver(); resolver.setChain(Arrays.asList(resolver1, resolver2)); final Principal principal = resolver.resolve(credential); assertEquals("final", principal.getId()); assertEquals("final@example.com", principal.getAttributes().get("mail")); }
LegacyAuthenticationHandlerAdapter implements AuthenticationHandler { @Override public HandlerResult authenticate(final Credential credential) throws GeneralSecurityException, PreventedException { try { if (this.legacyHandler.authenticate(credentialsAdapter.convert(credential))) { final CredentialMetaData md; if (credential instanceof CredentialMetaData) { md = (CredentialMetaData) credential; } else { md = new BasicCredentialMetaData(credential); } return new HandlerResult(this, md); } else { throw new FailedLoginException( String.format("%s failed to authenticate %s", this.getName(), credential)); } } catch (final AuthenticationException e) { throw new GeneralSecurityException( String.format("%s failed to authenticate %s", this.getName(), credential), e); } } LegacyAuthenticationHandlerAdapter(final org.jasig.cas.authentication.handler.AuthenticationHandler legacy); LegacyAuthenticationHandlerAdapter( final org.jasig.cas.authentication.handler.AuthenticationHandler legacy, final CredentialsAdapter adapter); @Override HandlerResult authenticate(final Credential credential); @Override boolean supports(final Credential credential); @Override String getName(); }
@Test public void testAuthenticateSuccess() throws Exception { final HandlerResult result = alwaysPassHandler.authenticate(new UsernamePasswordCredential("a", "b")); assertEquals("TestAlwaysPassAuthenticationHandler", result.getHandlerName()); } @Test(expected = FailedLoginException.class) public void testAuthenticateFailure() throws Exception { alwaysFailHandler.authenticate(new UsernamePasswordCredential("a", "b")); }
JRadiusServerImpl implements RadiusServer { @Override public boolean authenticate(final String username, final String password) throws PreventedException { final AttributeList attributeList = new AttributeList(); attributeList.add(new Attr_UserName(username)); attributeList.add(new Attr_UserPassword(password)); RadiusClient client = null; try { client = this.radiusClientFactory.newInstance(); LOGGER.debug("Created RADIUS client instance {}", client); final AccessRequest request = new AccessRequest(client, attributeList); final RadiusPacket response = client.authenticate( request, RadiusClient.getAuthProtocol(this.protocol.getName()), this.retries); LOGGER.debug("RADIUS response from {}: {}", client.getRemoteInetAddress().getCanonicalHostName(), response.getClass().getName()); if (response instanceof AccessAccept) { return true; } } catch (final Exception e) { throw new PreventedException(e); } finally { if (client != null) { client.close(); } } return false; } JRadiusServerImpl(final RadiusProtocol protocol, final RadiusClientFactory clientFactory); @Override boolean authenticate(final String username, final String password); void setRetries(final int retries); static final int DEFAULT_RETRY_COUNT; }
@Test public void testAuthenticate() { assertNotNull(this.radiusServer); }
SmartOpenIdController extends DelegateController implements Serializable { @Override public boolean canHandle(final HttpServletRequest request, final HttpServletResponse response) { String openIdMode = request.getParameter("openid.mode"); if (openIdMode != null && openIdMode.equals("associate")) { logger.info("Handling request. openid.mode : {}", openIdMode); return true; } logger.info("Cannot handle request. openid.mode : {}", openIdMode); return false; } Map<String, String> getAssociationResponse(final HttpServletRequest request); @Override boolean canHandle(final HttpServletRequest request, final HttpServletResponse response); void setSuccessView(final String successView); void setFailureView(final String failureView); @NotNull void setServerManager(final ServerManager serverManager); }
@Test public void testCanHandle() { request.addParameter("openid.mode", "associate"); boolean canHandle = smartOpenIdController.canHandle(request, response); request.removeParameter("openid.mode"); assertEquals(true, canHandle); } @Test public void testCannotHandle() { request.addParameter("openid.mode", "anythingElse"); boolean canHandle = smartOpenIdController.canHandle(request, response); request.removeParameter("openid.mode"); assertEquals(false, canHandle); }
SmartOpenIdController extends DelegateController implements Serializable { public Map<String, String> getAssociationResponse(final HttpServletRequest request) { ParameterList parameters = new ParameterList(request.getParameterMap()); final String mode = parameters.hasParameter("openid.mode") ? parameters.getParameterValue("openid.mode") : null; Message response = null; if (mode != null && mode.equals("associate")) { response = serverManager.associationResponse(parameters); } final Map<String, String> responseParams = new HashMap<String, String>(); if (response != null) { responseParams.putAll(response.getParameterMap()); } return responseParams; } Map<String, String> getAssociationResponse(final HttpServletRequest request); @Override boolean canHandle(final HttpServletRequest request, final HttpServletResponse response); void setSuccessView(final String successView); void setFailureView(final String failureView); @NotNull void setServerManager(final ServerManager serverManager); }
@Test public void testGetAssociationResponse() { request.addParameter("openid.mode", "associate"); request.addParameter("openid.session_type", "DH-SHA1"); request.addParameter("openid.assoc_type", "HMAC-SHA1"); request.addParameter("openid.dh_consumer_public", "NzKoFMyrzFn/5iJFPdX6MVvNA/BChV1/sJdnYbupDn7ptn+cerwEzyFfWFx25KsoLSkxQCaSMmYtc1GPy/2GI1BSKSDhpdJmDBb" + "QRa/9Gs+giV/5fHcz/mHz8sREc7RTGI+0Ka9230arwrWt0fnoaJLRKEGUsmFR71rCo4EUOew="); Map<String, String> assocResponse = smartOpenIdController.getAssociationResponse(request); assertTrue(assocResponse.containsKey("assoc_handle")); assertTrue(assocResponse.containsKey("expires_in")); assertTrue(assocResponse.containsKey("dh_server_public")); assertTrue(assocResponse.containsKey("enc_mac_key")); request.removeParameter("openid.mode"); }
AvailableForm extends BaseForm { public boolean isRegistrationForm(){ return Constants.FORM_DISCRIMINATOR_REGISTRATION.equalsIgnoreCase(getDiscriminator()) || Constants.FORM_JSON_DISCRIMINATOR_REGISTRATION.equalsIgnoreCase(getDiscriminator()) || Constants.FORM_JSON_DISCRIMINATOR_GENERIC_REGISTRATION.equalsIgnoreCase(getDiscriminator()) || Constants.FORM_JSON_DISCRIMINATOR_SHR_REGISTRATION.equalsIgnoreCase(getDiscriminator()); } Tag[] getTags(); void setTags(Tag[] tags); boolean isDownloaded(); void setDownloaded(boolean downloaded); boolean isRegistrationForm(); boolean isProviderReport(); boolean isRelationshipForm(); }
@Test public void shouldReturnFalseIfHasNoRegistrationDiscriminator() { AvailableForm availableForm = new AvailableForm(); assertFalse(availableForm.isRegistrationForm()); for(String discriminator: nonRegistrationDiscriminators) { availableForm.setDiscriminator(discriminator); assertFalse(availableForm.isRegistrationForm()); } } @Test public void shouldReturnTrueIfHasRegistrationDiscriminator() { AvailableForm availableForm = new AvailableForm(); for(String discriminator: registrationDiscriminators) { availableForm.setDiscriminator(discriminator); assertTrue(availableForm.isRegistrationForm()); } }
FormController { public List<FormData> getAllFormData(String status) throws FormDataFetchException { try { return formService.getAllFormData(status); } catch (Exception e) { throw new FormDataFetchException(e); } } FormController(MuzimaApplication muzimaApplication); int getTotalFormCount(); Form getFormByUuid(String formId); FormTemplate getFormTemplateByUuid(String formId); AvailableForms getAvailableFormByTags(List<String> tagsUuid); List<Form> getAllAvailableForms(); AvailableForms getAvailableFormByTags(List<String> tagsUuid, boolean alwaysIncludeRegistrationForms); List<Tag> getAllTags(); List<Tag> getAllTagsExcludingRegistrationTag(); DownloadedForms getAllDownloadedForms(); List<Form> downloadAllForms(); List<FormTemplate> downloadFormTemplates(String[] formUuids); FormTemplate downloadFormTemplateByUuid(String uuid); void saveAllForms(List<Form> forms); void updateAllForms(List<Form> forms); void deleteAllForms(); void deleteAllFormTemplates(); void deleteForms(List<Form> forms); void deleteFormTemplatesByUUID(List<String> formTemplateUUIDs); void replaceFormTemplates(List<FormTemplate> formTemplates); void saveFormTemplates(List<FormTemplate> formTemplates); boolean isFormDownloaded(Form form); int getTagColor(String uuid); void resetTagColors(); List<Tag> getSelectedTags(); void setSelectedTags(List<Tag> selectedTags); FormData getFormDataByUuid(String formDataUuid); List<FormData> getFormDataByUuids(List<String> formDataUuids); CompleteFormWithPatientData getCompleteFormDataByUuid(String formDataUuid); void saveFormData(FormData formData); List<FormData> getAllFormData(String status); List<FormData> getAllFormDataByPatientUuid(String patientUuid, String status); IncompleteFormsWithPatientData getAllIncompleteFormsWithPatientData(); CompleteFormsWithPatientData getAllCompleteFormsWithPatientData(Context context); IncompleteForms getAllIncompleteFormsForPatientUuid(String patientUuid); CompleteForms getAllCompleteFormsForPatientUuid(String patientUuid); int countAllIncompleteForms(); int countAllCompleteForms(); int getCompleteFormsCountForPatient(String patientId); int getIncompleteFormsCountForPatient(String patientId); AvailableForms getDownloadedRegistrationForms(); Patient createNewPatient(MuzimaApplication muzimaApplication, FormData formData); boolean uploadAllCompletedForms(); AvailableForms getRecommendedForms(); AvailableForms getProviderReports(); int getRecommendedFormsCount(); void deleteCompleteAndIncompleteEncounterFormData(List<String> formDataUuids); List<FormData> getNonUploadedFormData(String templateUUID); void markFormDataAsIncompleteAndDeleteRelatedEncountersAndObs(final FormData formData); void deleteFormDataAndRelatedEncountersAndObs(List<FormData> formData); List<FormData> getArchivedFormData(); FormDataStatus downloadFormDataStatus(FormData formData); boolean isFormAlreadyExist(String jsonPayload, FormData formData); boolean isRegistrationFormDataWithEncounterForm(String formUuid); boolean isRegistrationFormData(FormData formData); boolean isGenericRegistrationHTMLFormData(FormData formData); boolean isEncounterFormData(FormData formData); Map<String, List<FormData>> getFormDataGroupedByPatient(List<String> uuids); Map<String, List<FormData>> deleteFormDataWithNoRelatedCompleteRegistrationFormDataInGroup( Map<String, List<FormData>> groupedFormData); Map<String, List<FormData>> deleteRegistrationFormDataWithAllRelatedEncountersInGroup(Map<String, List<FormData>> groupedFormData); AvailableForms getAvailableFormByTagsSortedByConfigOrder(List<String> tagsUuid, boolean alwaysIncludeRegistrationForms); AvailableForms getDownloadedRelationshipForms(); AvailableForm getAvailableFormByFormUuid(String uuid); ArrayList<String> getFormListAsPerConfigOrder(); AvailableForms getAvailableFormsPerConfigOrder(ArrayList<String> formUuids, List<Form> filteredForms); }
@Test public void getAllFormData_shouldReturnListOfAllFormDatas() throws Exception, FormController.FormDataFetchException { FormData formData = new FormData(); String status = "draft"; when(formService.getAllFormData(status)).thenReturn(Collections.singletonList(formData)); assertThat(formController.getAllFormData(status).size(), is(1)); assertThat(formController.getAllFormData(status), hasItem(formData)); }
FormController { public List<FormData> getAllFormDataByPatientUuid(String patientUuid, String status) throws FormDataFetchException { try { return formService.getFormDataByPatient(patientUuid, status); } catch (IOException e) { throw new FormDataFetchException(e); } } FormController(MuzimaApplication muzimaApplication); int getTotalFormCount(); Form getFormByUuid(String formId); FormTemplate getFormTemplateByUuid(String formId); AvailableForms getAvailableFormByTags(List<String> tagsUuid); List<Form> getAllAvailableForms(); AvailableForms getAvailableFormByTags(List<String> tagsUuid, boolean alwaysIncludeRegistrationForms); List<Tag> getAllTags(); List<Tag> getAllTagsExcludingRegistrationTag(); DownloadedForms getAllDownloadedForms(); List<Form> downloadAllForms(); List<FormTemplate> downloadFormTemplates(String[] formUuids); FormTemplate downloadFormTemplateByUuid(String uuid); void saveAllForms(List<Form> forms); void updateAllForms(List<Form> forms); void deleteAllForms(); void deleteAllFormTemplates(); void deleteForms(List<Form> forms); void deleteFormTemplatesByUUID(List<String> formTemplateUUIDs); void replaceFormTemplates(List<FormTemplate> formTemplates); void saveFormTemplates(List<FormTemplate> formTemplates); boolean isFormDownloaded(Form form); int getTagColor(String uuid); void resetTagColors(); List<Tag> getSelectedTags(); void setSelectedTags(List<Tag> selectedTags); FormData getFormDataByUuid(String formDataUuid); List<FormData> getFormDataByUuids(List<String> formDataUuids); CompleteFormWithPatientData getCompleteFormDataByUuid(String formDataUuid); void saveFormData(FormData formData); List<FormData> getAllFormData(String status); List<FormData> getAllFormDataByPatientUuid(String patientUuid, String status); IncompleteFormsWithPatientData getAllIncompleteFormsWithPatientData(); CompleteFormsWithPatientData getAllCompleteFormsWithPatientData(Context context); IncompleteForms getAllIncompleteFormsForPatientUuid(String patientUuid); CompleteForms getAllCompleteFormsForPatientUuid(String patientUuid); int countAllIncompleteForms(); int countAllCompleteForms(); int getCompleteFormsCountForPatient(String patientId); int getIncompleteFormsCountForPatient(String patientId); AvailableForms getDownloadedRegistrationForms(); Patient createNewPatient(MuzimaApplication muzimaApplication, FormData formData); boolean uploadAllCompletedForms(); AvailableForms getRecommendedForms(); AvailableForms getProviderReports(); int getRecommendedFormsCount(); void deleteCompleteAndIncompleteEncounterFormData(List<String> formDataUuids); List<FormData> getNonUploadedFormData(String templateUUID); void markFormDataAsIncompleteAndDeleteRelatedEncountersAndObs(final FormData formData); void deleteFormDataAndRelatedEncountersAndObs(List<FormData> formData); List<FormData> getArchivedFormData(); FormDataStatus downloadFormDataStatus(FormData formData); boolean isFormAlreadyExist(String jsonPayload, FormData formData); boolean isRegistrationFormDataWithEncounterForm(String formUuid); boolean isRegistrationFormData(FormData formData); boolean isGenericRegistrationHTMLFormData(FormData formData); boolean isEncounterFormData(FormData formData); Map<String, List<FormData>> getFormDataGroupedByPatient(List<String> uuids); Map<String, List<FormData>> deleteFormDataWithNoRelatedCompleteRegistrationFormDataInGroup( Map<String, List<FormData>> groupedFormData); Map<String, List<FormData>> deleteRegistrationFormDataWithAllRelatedEncountersInGroup(Map<String, List<FormData>> groupedFormData); AvailableForms getAvailableFormByTagsSortedByConfigOrder(List<String> tagsUuid, boolean alwaysIncludeRegistrationForms); AvailableForms getDownloadedRelationshipForms(); AvailableForm getAvailableFormByFormUuid(String uuid); ArrayList<String> getFormListAsPerConfigOrder(); AvailableForms getAvailableFormsPerConfigOrder(ArrayList<String> formUuids, List<Form> filteredForms); }
@Test public void getAllFormDataByPatientUuid_shouldReturnAllFormDataForPatientAndGivenStatus() throws Exception, FormController.FormDataFetchException { List<FormData> formDataList = new ArrayList<>(); String patientUuid = "patientUuid"; String status = "status"; when(formService.getFormDataByPatient(patientUuid, status)).thenReturn(formDataList); assertThat(formController.getAllFormDataByPatientUuid(patientUuid, status), is(formDataList)); } @Test (expected = FormController.FormDataFetchException.class) public void getAllFormDataByPatientUuid_shouldThrowFormDataFetchExpetionIfExceptionThrownByService() throws Exception, FormController.FormDataFetchException { doThrow(new IOException()).when(formService).getFormDataByPatient(anyString(), anyString()); formController.getAllFormDataByPatientUuid("", ""); }
FormController { public CompleteForms getAllCompleteFormsForPatientUuid(String patientUuid) throws FormFetchException { CompleteForms completePatientForms = new CompleteForms(); try { List<FormData> allFormData = formService.getFormDataByPatient(patientUuid, Constants.STATUS_COMPLETE); for (FormData formData : allFormData) { Form form = formService.getFormByUuid(formData.getTemplateUuid()); if (form != null) { completePatientForms.add(new CompleteFormBuilder() .withForm(form) .withFormDataUuid(formData.getUuid()) .withLastModifiedDate(formData.getSaveTime()) .withEncounterDate(formData.getEncounterDate()) .build()); } } } catch (IOException e) { throw new FormFetchException(e); } return completePatientForms; } FormController(MuzimaApplication muzimaApplication); int getTotalFormCount(); Form getFormByUuid(String formId); FormTemplate getFormTemplateByUuid(String formId); AvailableForms getAvailableFormByTags(List<String> tagsUuid); List<Form> getAllAvailableForms(); AvailableForms getAvailableFormByTags(List<String> tagsUuid, boolean alwaysIncludeRegistrationForms); List<Tag> getAllTags(); List<Tag> getAllTagsExcludingRegistrationTag(); DownloadedForms getAllDownloadedForms(); List<Form> downloadAllForms(); List<FormTemplate> downloadFormTemplates(String[] formUuids); FormTemplate downloadFormTemplateByUuid(String uuid); void saveAllForms(List<Form> forms); void updateAllForms(List<Form> forms); void deleteAllForms(); void deleteAllFormTemplates(); void deleteForms(List<Form> forms); void deleteFormTemplatesByUUID(List<String> formTemplateUUIDs); void replaceFormTemplates(List<FormTemplate> formTemplates); void saveFormTemplates(List<FormTemplate> formTemplates); boolean isFormDownloaded(Form form); int getTagColor(String uuid); void resetTagColors(); List<Tag> getSelectedTags(); void setSelectedTags(List<Tag> selectedTags); FormData getFormDataByUuid(String formDataUuid); List<FormData> getFormDataByUuids(List<String> formDataUuids); CompleteFormWithPatientData getCompleteFormDataByUuid(String formDataUuid); void saveFormData(FormData formData); List<FormData> getAllFormData(String status); List<FormData> getAllFormDataByPatientUuid(String patientUuid, String status); IncompleteFormsWithPatientData getAllIncompleteFormsWithPatientData(); CompleteFormsWithPatientData getAllCompleteFormsWithPatientData(Context context); IncompleteForms getAllIncompleteFormsForPatientUuid(String patientUuid); CompleteForms getAllCompleteFormsForPatientUuid(String patientUuid); int countAllIncompleteForms(); int countAllCompleteForms(); int getCompleteFormsCountForPatient(String patientId); int getIncompleteFormsCountForPatient(String patientId); AvailableForms getDownloadedRegistrationForms(); Patient createNewPatient(MuzimaApplication muzimaApplication, FormData formData); boolean uploadAllCompletedForms(); AvailableForms getRecommendedForms(); AvailableForms getProviderReports(); int getRecommendedFormsCount(); void deleteCompleteAndIncompleteEncounterFormData(List<String> formDataUuids); List<FormData> getNonUploadedFormData(String templateUUID); void markFormDataAsIncompleteAndDeleteRelatedEncountersAndObs(final FormData formData); void deleteFormDataAndRelatedEncountersAndObs(List<FormData> formData); List<FormData> getArchivedFormData(); FormDataStatus downloadFormDataStatus(FormData formData); boolean isFormAlreadyExist(String jsonPayload, FormData formData); boolean isRegistrationFormDataWithEncounterForm(String formUuid); boolean isRegistrationFormData(FormData formData); boolean isGenericRegistrationHTMLFormData(FormData formData); boolean isEncounterFormData(FormData formData); Map<String, List<FormData>> getFormDataGroupedByPatient(List<String> uuids); Map<String, List<FormData>> deleteFormDataWithNoRelatedCompleteRegistrationFormDataInGroup( Map<String, List<FormData>> groupedFormData); Map<String, List<FormData>> deleteRegistrationFormDataWithAllRelatedEncountersInGroup(Map<String, List<FormData>> groupedFormData); AvailableForms getAvailableFormByTagsSortedByConfigOrder(List<String> tagsUuid, boolean alwaysIncludeRegistrationForms); AvailableForms getDownloadedRelationshipForms(); AvailableForm getAvailableFormByFormUuid(String uuid); ArrayList<String> getFormListAsPerConfigOrder(); AvailableForms getAvailableFormsPerConfigOrder(ArrayList<String> formUuids, List<Form> filteredForms); }
@Test (expected = FormController.FormFetchException.class) public void getAllCompleteFormsForPatientUuid_shouldThrowFormFetchExceptionIfExceptionThrownByService() throws Exception, FormController.FormFetchException { doThrow(new IOException()).when(formService).getFormDataByPatient(anyString(),anyString()); formController.getAllCompleteFormsForPatientUuid("patientUuid"); }
FormController { public IncompleteForms getAllIncompleteFormsForPatientUuid(String patientUuid) throws FormFetchException { IncompleteForms incompleteForms = new IncompleteForms(); try { List<FormData> allFormData = formService.getFormDataByPatient(patientUuid, Constants.STATUS_INCOMPLETE); for (FormData formData : allFormData) { incompleteForms.add(new IncompleteFormBuilder().withForm(formService.getFormByUuid(formData.getTemplateUuid())) .withFormDataUuid(formData.getUuid()) .withLastModifiedDate(formData.getSaveTime()) .withEncounterDate(formData.getEncounterDate()) .build()); } } catch (IOException e) { throw new FormFetchException(e); } return incompleteForms; } FormController(MuzimaApplication muzimaApplication); int getTotalFormCount(); Form getFormByUuid(String formId); FormTemplate getFormTemplateByUuid(String formId); AvailableForms getAvailableFormByTags(List<String> tagsUuid); List<Form> getAllAvailableForms(); AvailableForms getAvailableFormByTags(List<String> tagsUuid, boolean alwaysIncludeRegistrationForms); List<Tag> getAllTags(); List<Tag> getAllTagsExcludingRegistrationTag(); DownloadedForms getAllDownloadedForms(); List<Form> downloadAllForms(); List<FormTemplate> downloadFormTemplates(String[] formUuids); FormTemplate downloadFormTemplateByUuid(String uuid); void saveAllForms(List<Form> forms); void updateAllForms(List<Form> forms); void deleteAllForms(); void deleteAllFormTemplates(); void deleteForms(List<Form> forms); void deleteFormTemplatesByUUID(List<String> formTemplateUUIDs); void replaceFormTemplates(List<FormTemplate> formTemplates); void saveFormTemplates(List<FormTemplate> formTemplates); boolean isFormDownloaded(Form form); int getTagColor(String uuid); void resetTagColors(); List<Tag> getSelectedTags(); void setSelectedTags(List<Tag> selectedTags); FormData getFormDataByUuid(String formDataUuid); List<FormData> getFormDataByUuids(List<String> formDataUuids); CompleteFormWithPatientData getCompleteFormDataByUuid(String formDataUuid); void saveFormData(FormData formData); List<FormData> getAllFormData(String status); List<FormData> getAllFormDataByPatientUuid(String patientUuid, String status); IncompleteFormsWithPatientData getAllIncompleteFormsWithPatientData(); CompleteFormsWithPatientData getAllCompleteFormsWithPatientData(Context context); IncompleteForms getAllIncompleteFormsForPatientUuid(String patientUuid); CompleteForms getAllCompleteFormsForPatientUuid(String patientUuid); int countAllIncompleteForms(); int countAllCompleteForms(); int getCompleteFormsCountForPatient(String patientId); int getIncompleteFormsCountForPatient(String patientId); AvailableForms getDownloadedRegistrationForms(); Patient createNewPatient(MuzimaApplication muzimaApplication, FormData formData); boolean uploadAllCompletedForms(); AvailableForms getRecommendedForms(); AvailableForms getProviderReports(); int getRecommendedFormsCount(); void deleteCompleteAndIncompleteEncounterFormData(List<String> formDataUuids); List<FormData> getNonUploadedFormData(String templateUUID); void markFormDataAsIncompleteAndDeleteRelatedEncountersAndObs(final FormData formData); void deleteFormDataAndRelatedEncountersAndObs(List<FormData> formData); List<FormData> getArchivedFormData(); FormDataStatus downloadFormDataStatus(FormData formData); boolean isFormAlreadyExist(String jsonPayload, FormData formData); boolean isRegistrationFormDataWithEncounterForm(String formUuid); boolean isRegistrationFormData(FormData formData); boolean isGenericRegistrationHTMLFormData(FormData formData); boolean isEncounterFormData(FormData formData); Map<String, List<FormData>> getFormDataGroupedByPatient(List<String> uuids); Map<String, List<FormData>> deleteFormDataWithNoRelatedCompleteRegistrationFormDataInGroup( Map<String, List<FormData>> groupedFormData); Map<String, List<FormData>> deleteRegistrationFormDataWithAllRelatedEncountersInGroup(Map<String, List<FormData>> groupedFormData); AvailableForms getAvailableFormByTagsSortedByConfigOrder(List<String> tagsUuid, boolean alwaysIncludeRegistrationForms); AvailableForms getDownloadedRelationshipForms(); AvailableForm getAvailableFormByFormUuid(String uuid); ArrayList<String> getFormListAsPerConfigOrder(); AvailableForms getAvailableFormsPerConfigOrder(ArrayList<String> formUuids, List<Form> filteredForms); }
@Test (expected = FormController.FormFetchException.class) public void getAllIncompleteFormsForPatientUuid_shouldThrowFormFetchExceptionIfExceptionThrownByService() throws Exception, FormController.FormFetchException { doThrow(new IOException()).when(formService).getFormDataByPatient(anyString(),anyString()); formController.getAllIncompleteFormsForPatientUuid("patientUuid"); }
FormController { public List<FormData> getNonUploadedFormData(String templateUUID) throws FormDataFetchException { List<FormData> incompleteFormData = new ArrayList<>(); try { List<FormData> formDataByTemplateUUID = formService.getFormDataByTemplateUUID(templateUUID); for (FormData formData : formDataByTemplateUUID) { if (!formData.getStatus().equals(Constants.STATUS_UPLOADED)) { incompleteFormData.add(formData); } } return incompleteFormData; } catch (IOException e) { throw new FormDataFetchException(e); } } FormController(MuzimaApplication muzimaApplication); int getTotalFormCount(); Form getFormByUuid(String formId); FormTemplate getFormTemplateByUuid(String formId); AvailableForms getAvailableFormByTags(List<String> tagsUuid); List<Form> getAllAvailableForms(); AvailableForms getAvailableFormByTags(List<String> tagsUuid, boolean alwaysIncludeRegistrationForms); List<Tag> getAllTags(); List<Tag> getAllTagsExcludingRegistrationTag(); DownloadedForms getAllDownloadedForms(); List<Form> downloadAllForms(); List<FormTemplate> downloadFormTemplates(String[] formUuids); FormTemplate downloadFormTemplateByUuid(String uuid); void saveAllForms(List<Form> forms); void updateAllForms(List<Form> forms); void deleteAllForms(); void deleteAllFormTemplates(); void deleteForms(List<Form> forms); void deleteFormTemplatesByUUID(List<String> formTemplateUUIDs); void replaceFormTemplates(List<FormTemplate> formTemplates); void saveFormTemplates(List<FormTemplate> formTemplates); boolean isFormDownloaded(Form form); int getTagColor(String uuid); void resetTagColors(); List<Tag> getSelectedTags(); void setSelectedTags(List<Tag> selectedTags); FormData getFormDataByUuid(String formDataUuid); List<FormData> getFormDataByUuids(List<String> formDataUuids); CompleteFormWithPatientData getCompleteFormDataByUuid(String formDataUuid); void saveFormData(FormData formData); List<FormData> getAllFormData(String status); List<FormData> getAllFormDataByPatientUuid(String patientUuid, String status); IncompleteFormsWithPatientData getAllIncompleteFormsWithPatientData(); CompleteFormsWithPatientData getAllCompleteFormsWithPatientData(Context context); IncompleteForms getAllIncompleteFormsForPatientUuid(String patientUuid); CompleteForms getAllCompleteFormsForPatientUuid(String patientUuid); int countAllIncompleteForms(); int countAllCompleteForms(); int getCompleteFormsCountForPatient(String patientId); int getIncompleteFormsCountForPatient(String patientId); AvailableForms getDownloadedRegistrationForms(); Patient createNewPatient(MuzimaApplication muzimaApplication, FormData formData); boolean uploadAllCompletedForms(); AvailableForms getRecommendedForms(); AvailableForms getProviderReports(); int getRecommendedFormsCount(); void deleteCompleteAndIncompleteEncounterFormData(List<String> formDataUuids); List<FormData> getNonUploadedFormData(String templateUUID); void markFormDataAsIncompleteAndDeleteRelatedEncountersAndObs(final FormData formData); void deleteFormDataAndRelatedEncountersAndObs(List<FormData> formData); List<FormData> getArchivedFormData(); FormDataStatus downloadFormDataStatus(FormData formData); boolean isFormAlreadyExist(String jsonPayload, FormData formData); boolean isRegistrationFormDataWithEncounterForm(String formUuid); boolean isRegistrationFormData(FormData formData); boolean isGenericRegistrationHTMLFormData(FormData formData); boolean isEncounterFormData(FormData formData); Map<String, List<FormData>> getFormDataGroupedByPatient(List<String> uuids); Map<String, List<FormData>> deleteFormDataWithNoRelatedCompleteRegistrationFormDataInGroup( Map<String, List<FormData>> groupedFormData); Map<String, List<FormData>> deleteRegistrationFormDataWithAllRelatedEncountersInGroup(Map<String, List<FormData>> groupedFormData); AvailableForms getAvailableFormByTagsSortedByConfigOrder(List<String> tagsUuid, boolean alwaysIncludeRegistrationForms); AvailableForms getDownloadedRelationshipForms(); AvailableForm getAvailableFormByFormUuid(String uuid); ArrayList<String> getFormListAsPerConfigOrder(); AvailableForms getAvailableFormsPerConfigOrder(ArrayList<String> formUuids, List<Form> filteredForms); }
@Test public void shouldFilterOutUploadedFormData() throws Exception, FormController.FormDataFetchException { String templateUUID = "templateUUID"; when(formService.getFormDataByTemplateUUID(templateUUID)).thenReturn(asList( formDataWithStatusAndDiscriminator(Constants.STATUS_COMPLETE, Constants.FORM_XML_DISCRIMINATOR_ENCOUNTER), formDataWithStatusAndDiscriminator(Constants.STATUS_UPLOADED, Constants.FORM_XML_DISCRIMINATOR_ENCOUNTER))); List<FormData> formDataByTemplateUUID = formController.getNonUploadedFormData(templateUUID); assertThat(formDataByTemplateUUID.size(),is(1)); assertThat(formDataByTemplateUUID.get(0).getStatus(), is(Constants.STATUS_COMPLETE)); }
LocationController { public List<Location> downloadLocationFromServerByName(String name) throws LocationDownloadException { try { return locationService.downloadLocationsByName(name); } catch (IOException e) { Log.e(getClass().getSimpleName(), "Error while searching for patients in the server", e); throw new LocationDownloadException(e); } } LocationController(LocationService locationService); List<Location> downloadLocationFromServerByName(String name); Location downloadLocationFromServerByUuid(String uuid); List<Location> downloadLocationsFromServerByUuid(String[] uuids); List<Location> getAllLocations(); void saveLocation(Location location); void saveLocations(List<Location> locations); Location getLocationByUuid(String uuid); List<LocationAttributeType> getLocationAttributesByName(String name); LocationAttributeType getLocationAttributeTypeByUuid(String uuid); Location getLocationByAttributeTypeAndValue(LocationAttributeType attributeType,String attribute); Location getLocationByName(String name); Location getLocationById(int id); void deleteLocation(Location location); void deleteLocations(List<Location> locations); List<Location> getRelatedLocations(List<FormTemplate> formTemplates); void newLocations(List<Location> locations); List<Location> newLocations(); void deleteAllLocations(); }
@Test public void shouldSearchOnServerForLocationsByNames() throws Exception, LocationController.LocationDownloadException { String name = "name"; List<Location> locations = new ArrayList<>(); when(locationService.downloadLocationsByName(name)).thenReturn(locations); assertThat(locationController.downloadLocationFromServerByName(name), is(locations)); verify(locationService).downloadLocationsByName(name); } @Test(expected = LocationController.LocationDownloadException.class) public void shouldReturnEmptyListIsExceptionThrown() throws Exception, LocationController.LocationDownloadException { String searchString = "name"; doThrow(new IOException()).when(locationService).downloadLocationsByName(searchString); assertThat(locationController.downloadLocationFromServerByName(searchString).size(), is(0)); }
LocationController { public Location downloadLocationFromServerByUuid(String uuid) throws LocationDownloadException { try { return locationService.downloadLocationByUuid(uuid); } catch (IOException e) { Log.e(getClass().getSimpleName(), "Error while searching for patients in the server", e); throw new LocationDownloadException(e); } } LocationController(LocationService locationService); List<Location> downloadLocationFromServerByName(String name); Location downloadLocationFromServerByUuid(String uuid); List<Location> downloadLocationsFromServerByUuid(String[] uuids); List<Location> getAllLocations(); void saveLocation(Location location); void saveLocations(List<Location> locations); Location getLocationByUuid(String uuid); List<LocationAttributeType> getLocationAttributesByName(String name); LocationAttributeType getLocationAttributeTypeByUuid(String uuid); Location getLocationByAttributeTypeAndValue(LocationAttributeType attributeType,String attribute); Location getLocationByName(String name); Location getLocationById(int id); void deleteLocation(Location location); void deleteLocations(List<Location> locations); List<Location> getRelatedLocations(List<FormTemplate> formTemplates); void newLocations(List<Location> locations); List<Location> newLocations(); void deleteAllLocations(); }
@Test public void shouldSearchOnServerForLocationByUuid() throws Exception, LocationController.LocationDownloadException { String uuid = "uuid"; Location location = new Location(); when(locationService.downloadLocationByUuid(uuid)).thenReturn(location); assertThat(locationController.downloadLocationFromServerByUuid(uuid), is(location)); verify(locationService).downloadLocationByUuid(uuid); }
LocationController { public List<Location> getAllLocations() throws LocationLoadException { try { return locationService.getAllLocations(); } catch (IOException e) { throw new LocationLoadException(e); } } LocationController(LocationService locationService); List<Location> downloadLocationFromServerByName(String name); Location downloadLocationFromServerByUuid(String uuid); List<Location> downloadLocationsFromServerByUuid(String[] uuids); List<Location> getAllLocations(); void saveLocation(Location location); void saveLocations(List<Location> locations); Location getLocationByUuid(String uuid); List<LocationAttributeType> getLocationAttributesByName(String name); LocationAttributeType getLocationAttributeTypeByUuid(String uuid); Location getLocationByAttributeTypeAndValue(LocationAttributeType attributeType,String attribute); Location getLocationByName(String name); Location getLocationById(int id); void deleteLocation(Location location); void deleteLocations(List<Location> locations); List<Location> getRelatedLocations(List<FormTemplate> formTemplates); void newLocations(List<Location> locations); List<Location> newLocations(); void deleteAllLocations(); }
@Test public void getAllLocations_shouldReturnAllAvailableLocations() throws IOException, LocationController.LocationLoadException { List<Location> locations = new ArrayList<>(); when(locationService.getAllLocations()).thenReturn(locations); assertThat(locationController.getAllLocations(), is(locations)); } @Test(expected = LocationController.LocationLoadException.class) public void getAllLocations_shouldThrowLoLocationFetchExceptionIfExceptionThrownByLocationService() throws IOException, LocationController.LocationLoadException { doThrow(new IOException()).when(locationService).getAllLocations(); locationController.getAllLocations(); }
MuzimaSyncService { public int authenticate(String[] credentials) { return authenticate(credentials, false); } MuzimaSyncService(MuzimaApplication muzimaContext); int authenticate(String[] credentials); int authenticate(String[] credentials, boolean isUpdatePasswordRequired); int[] downloadForms(); int[] downloadFormTemplatesAndRelatedMetadata(String[] formIds, boolean replaceExistingTemplates); int[] downloadFormTemplates(String[] formIds, boolean replaceExistingTemplates); int[] downloadLocations(String[] locationIds); int[] downloadProviders(String[] providerIds); int[] downloadConcepts(String[] conceptIds); int[] downloadCohorts(); int[] downloadCohorts(String[] cohortUuids); int[] downloadPatientsForCohortsWithUpdatesAvailable(); int[] downloadRemovedCohortMembershipData(String[] cohortUuids); int[] downloadPatientsForCohorts(String[] cohortUuids); int[] downloadPatients(String[] patientUUIDs); int[] downloadObservationsForPatientsByCohortUUIDs(String[] cohortUuids, boolean replaceExistingObservation); int[] downloadObservationsForPatientsByPatientUUIDs(List<String> patientUuids, boolean replaceExistingObservations); int[] downloadEncountersForPatientsByCohortUUIDs(String[] cohortUuids, boolean replaceExistingEncounters); int[] downloadEncountersForPatientsByPatientUUIDs(List<String> patientUuids, boolean replaceExistingEncounters); int[] uploadAllCompletedForms(); void consolidatePatients(); List<FormData> getArchivedFormData(); int[] checkAndDeleteTemporaryDataForProcessedFormData(List<FormData> archivedFormData); List<String> getUuidsForAllPatientsFromLocalStorage(); List<Patient> updatePatientsNotPartOfCohorts(); int[] downloadNotifications(String receiverUuid); int[] downloadPatientReportHeaders(String patientUuid); int[] downloadAllPatientReportHeadersAndReports(); int[] downloadPatientReportsByUuid(String[] reportUuids); void downloadSetupConfigurations(); int[] downloadSetupConfigurationTemplate(String uuid); int[] downloadAndSaveUpdatedSetupConfigurationTemplate(String uuid); int[] updateSetupConfigurationTemplates(); int[] downloadSetting(String property); int[] downloadNewSettings(); void updateSettingsPreferences(List<MuzimaSetting> muzimaSettings); int[] downloadRelationshipsTypes(); int[] downloadRelationshipsForPatientsByPatientUUIDs(List<String> patientUuids); int[] downloadRelationshipsForPatientsByCohortUUIDs(String[] cohortUuids); String getDefaultLocation(); }
@Test public void authenticate_shouldCallCloseSessionIfAuthenticationSucceed() { String[] credentials = new String[]{"username", "password", "url"}; muzimaSyncService.authenticate(credentials); verify(muzimaContext).closeSession(); } @Test public void authenticate_shouldCallCloseSessionIfExceptionOccurred() throws Exception { String[] credentials = new String[]{"username", "password", "url"}; doThrow(new ParseException()).when(muzimaContext).authenticate(credentials[0], credentials[1], credentials[2], false); muzimaSyncService.authenticate(credentials); verify(muzimaContext).closeSession(); } @Test public void authenticate_shouldReturnParsingErrorIfParsingExceptionOccurs() throws Exception { String[] credentials = new String[]{"username", "password", "url"}; doThrow(new ParseException()).when(muzimaContext).authenticate(credentials[0], credentials[1], credentials[2], false); assertThat(muzimaSyncService.authenticate(credentials), is(SyncStatusConstants.PARSING_ERROR)); } @Test public void authenticate_shouldReturnConnectionErrorIfConnectionErrorOccurs() throws Exception { String[] credentials = new String[]{"username", "password", "url"}; doThrow(new ConnectException()).when(muzimaContext).authenticate(credentials[0], credentials[1], credentials[2], false); assertThat(muzimaSyncService.authenticate(credentials), is(SyncStatusConstants.SERVER_CONNECTION_ERROR)); } @Test public void authenticate_shouldReturnAuthenticationErrorIfAuthenticationErrorOccurs() throws Exception { String[] credentials = new String[]{"username", "password", "url"}; doThrow(new IOException()).when(muzimaContext).authenticate(credentials[0], credentials[1], credentials[2], false); assertThat(muzimaSyncService.authenticate(credentials), is(SyncStatusConstants.AUTHENTICATION_ERROR)); } @Test public void authenticate_shouldReturnSuccessStatusIfAuthenticated() { String[] credentials = new String[]{"username", "password", "url"}; assertThat(muzimaSyncService.authenticate(credentials), is(SyncStatusConstants.AUTHENTICATION_SUCCESS)); } @Test public void authenticate_shouldAuthenticateIfNotAlreadyAuthenticated() throws Exception { String[] credentials = new String[]{"username", "password", "url"}; when(muzimaContext.isAuthenticated()).thenReturn(true); verify(muzimaContext, times(0)).authenticate(anyString(), anyString(), anyString(), anyBoolean()); assertThat(muzimaSyncService.authenticate(credentials), is(SyncStatusConstants.AUTHENTICATION_SUCCESS)); }
LocationController { public Location getLocationByUuid(String uuid) throws LocationLoadException { try { return locationService.getLocationByUuid(uuid); } catch (IOException e) { throw new LocationLoadException(e); } } LocationController(LocationService locationService); List<Location> downloadLocationFromServerByName(String name); Location downloadLocationFromServerByUuid(String uuid); List<Location> downloadLocationsFromServerByUuid(String[] uuids); List<Location> getAllLocations(); void saveLocation(Location location); void saveLocations(List<Location> locations); Location getLocationByUuid(String uuid); List<LocationAttributeType> getLocationAttributesByName(String name); LocationAttributeType getLocationAttributeTypeByUuid(String uuid); Location getLocationByAttributeTypeAndValue(LocationAttributeType attributeType,String attribute); Location getLocationByName(String name); Location getLocationById(int id); void deleteLocation(Location location); void deleteLocations(List<Location> locations); List<Location> getRelatedLocations(List<FormTemplate> formTemplates); void newLocations(List<Location> locations); List<Location> newLocations(); void deleteAllLocations(); }
@Test public void getLocationByUuid_shouldReturnLocationForId() throws Exception, LocationController.LocationLoadException { Location location = new Location(); String uuid = "uuid"; when(locationService.getLocationByUuid(uuid)).thenReturn(location); assertThat(locationController.getLocationByUuid(uuid), is(location)); }
ConceptController { public List<Concept> downloadConceptsByNames(List<String> names) throws ConceptDownloadException { HashSet<Concept> result = new HashSet<>(); for (String name : names) { List<Concept> concepts = downloadConceptsByNamePrefix(name); Iterator<Concept> iterator = concepts.iterator(); while (iterator.hasNext()) { Concept next = iterator.next(); if (next == null || !next.containsNameIgnoreLowerCase(name)) { iterator.remove(); } } result.addAll(concepts); } return new ArrayList<>(result); } ConceptController(ConceptService conceptService, ObservationService observationService); List<Concept> downloadConceptsByNamePrefix(String name); void deleteConcept(Concept concept); void deleteConcepts(List<Concept> concepts); void saveConcepts(List<Concept> concepts); Concept getConceptByName(String name); Concept getConceptById(int id); Concept getConceptByUuid(String uuid); List<Concept> downloadConceptsByNames(List<String> names); List<Concept> downloadConceptsByUuid(String[] uuids); List<Concept> searchConceptsLocallyByNamePrefix(String prefix); List<Concept> getConcepts(); void newConcepts(List<Concept> concepts); void resetNewConceptsList(); List<Concept> newConcepts(); List<Concept> getRelatedConcepts(List<FormTemplate> formTemplates); void deleteAllConcepts(); }
@Test public void shouldDownloadConceptUsingNonPreferredName() throws Exception, ConceptController.ConceptDownloadException { List<Concept> concepts = new ArrayList<>(); final String nonPreferredName = "NonPreferredName"; Concept aConcept = new Concept() {{ setConceptNames(new ArrayList<ConceptName>() {{ add(new ConceptName() {{ setName("PreferredName"); setPreferred(true); }}); add(new ConceptName() {{ setName(nonPreferredName); setPreferred(false); }}); }}); }}; concepts.add(aConcept); when(service.downloadConceptsByName(nonPreferredName)).thenReturn(concepts); List<String> listOfName = new ArrayList<String>() {{ add(nonPreferredName); }}; List<Concept> expectedResult = new ArrayList<>(); expectedResult.add(aConcept); assertThat(controller.downloadConceptsByNames(listOfName), is(expectedResult)); }
ConceptController { public Concept getConceptByName(String name) throws ConceptFetchException { try { List<Concept> concepts = conceptService.getConceptsByName(name); for (Concept concept : concepts) { if (concept.getName().equals(name)) { return concept; } } } catch (IOException e) { throw new ConceptFetchException(e); } return null; } ConceptController(ConceptService conceptService, ObservationService observationService); List<Concept> downloadConceptsByNamePrefix(String name); void deleteConcept(Concept concept); void deleteConcepts(List<Concept> concepts); void saveConcepts(List<Concept> concepts); Concept getConceptByName(String name); Concept getConceptById(int id); Concept getConceptByUuid(String uuid); List<Concept> downloadConceptsByNames(List<String> names); List<Concept> downloadConceptsByUuid(String[] uuids); List<Concept> searchConceptsLocallyByNamePrefix(String prefix); List<Concept> getConcepts(); void newConcepts(List<Concept> concepts); void resetNewConceptsList(); List<Concept> newConcepts(); List<Concept> getRelatedConcepts(List<FormTemplate> formTemplates); void deleteAllConcepts(); }
@Test public void shouldReturnAConceptThatMatchesNameExactly() throws Exception, ConceptController.ConceptFetchException { String conceptName = "conceptName"; List<Concept> conceptList = asList(createConceptByName("someName"),createConceptByName(conceptName)); when(service.getConceptsByName(conceptName)).thenReturn(conceptList); Concept conceptByName = controller.getConceptByName(conceptName); assertThat(conceptByName.getName(),is(conceptName)); } @Test public void shouldReturnNullIfNoConceptMatchesTheName() throws Exception, ConceptController.ConceptFetchException { String conceptName = "conceptName"; List<Concept> conceptList = asList(createConceptByName("someName"),createConceptByName("someOtherName")); when(service.getConceptsByName(conceptName)).thenReturn(conceptList); Concept conceptByName = controller.getConceptByName(conceptName); assertThat(conceptByName,nullValue()); }
ObservationController { public List<Observation> downloadObservationsByPatientUuidsAndConceptUuids(List<String> patientUuids, List<String> conceptUuids) throws DownloadObservationException { try { String paramSignature = buildParamSignature(patientUuids, conceptUuids); Date lastSyncTime = lastSyncTimeService.getLastSyncTimeFor(DOWNLOAD_OBSERVATIONS, paramSignature); List<Observation> observations = new ArrayList<>(); if (hasExactCallBeenMadeBefore(lastSyncTime)) { observations.addAll(observationService.downloadObservations(patientUuids, conceptUuids, lastSyncTime)); } else { LastSyncTime fullLastSyncTimeInfo = lastSyncTimeService.getFullLastSyncTimeInfoFor(DOWNLOAD_OBSERVATIONS); if (isFirstCallToDownloadObservationsEver(fullLastSyncTimeInfo)) { observations.addAll(observationService.downloadObservations(patientUuids, conceptUuids, null)); } else { String[] parameterSplit = fullLastSyncTimeInfo.getParamSignature().split(UUID_TYPE_SEPARATOR, -1); List<String> knownPatientsUuid = asList(parameterSplit[0].split(UUID_SEPARATOR)); List<String> newPatientsUuids = getNewUuids(patientUuids, knownPatientsUuid); List<String> knownConceptsUuid = asList(parameterSplit[1].split(UUID_SEPARATOR)); List<String> newConceptsUuids = getNewUuids(conceptUuids, knownConceptsUuid); List<String> allConceptsUuids = getAllUuids(knownConceptsUuid, newConceptsUuids); List<String> allPatientsUuids = getAllUuids(knownPatientsUuid, newPatientsUuids); paramSignature = buildParamSignature(allPatientsUuids, allConceptsUuids); if(newPatientsUuids.size()!=0) { observations = observationService.downloadObservations(newPatientsUuids, allConceptsUuids, null); observations.addAll(observationService.downloadObservations(knownPatientsUuid, newConceptsUuids, null)); observations.addAll(observationService.downloadObservations(knownPatientsUuid, knownConceptsUuid, fullLastSyncTimeInfo.getLastSyncDate())); } else{ observations.addAll(observationService.downloadObservations(patientUuids, conceptUuids, fullLastSyncTimeInfo.getLastSyncDate())); } } } LastSyncTime newLastSyncTime = new LastSyncTime(DOWNLOAD_OBSERVATIONS, sntpService.getTimePerDeviceTimeZone(), paramSignature); lastSyncTimeService.saveLastSyncTime(newLastSyncTime); return observations; } catch (IOException e) { throw new DownloadObservationException(e); } } ObservationController(ObservationService observationService, ConceptService conceptService, EncounterService encounterService, LastSyncTimeService lastSyncTimeService, SntpService sntpService); Concepts getConceptWithObservations(String patientUuid); Concepts getConceptWithObservations(String patientUuid, String conceptUuid ); List<Observation> getObservationsByPatientuuidAndConceptId(String patientUuid,int conceptid); List<Observation> getObservationsByEncounterId(int encounterId); List<Observation> getObservationsByEncounterType(int encounterTypeId,String patientUuid); int getObservationsCountByPatient(String patientUuid); int getConceptColor(String uuid); void replaceObservations(List<Observation> allObservations); Concepts searchObservationsGroupedByConcepts(String term, String patientUuid); Encounters getEncountersWithObservations(String patientUuid); Encounters getObservationsByEncounterUuid(String encounterUuid); List<Observation> getObservationsByPatient(String patientUuid); Encounters searchObservationsGroupedByEncounter(String term, String patientUuid); List<Observation> downloadObservationsByPatientUuidsAndConceptUuids(List<String> patientUuids, List<String> conceptUuids); void saveObservations(List<Observation> observations); void deleteObservations(List<Observation> observations); void deleteAllObservations(List<Concept> concepts); }
@Test public void shouldCheckLastSyncTimeBeforeDownloadingObservations() throws Exception, ObservationController.DownloadObservationException { List<String> patientUuids = asList("PatientUuid1", "PatientUuid2"); List<String> conceptUuids = asList("ConceptUuid1", "ConceptUuid2"); Date aDate = mock(Date.class); when(lastSyncTimeService.getLastSyncTimeFor(DOWNLOAD_OBSERVATIONS, "PatientUuid1,PatientUuid2;ConceptUuid1,ConceptUuid2")).thenReturn(aDate); observationController.downloadObservationsByPatientUuidsAndConceptUuids(patientUuids, conceptUuids); verify(lastSyncTimeService).getLastSyncTimeFor(DOWNLOAD_OBSERVATIONS, "PatientUuid1,PatientUuid2;ConceptUuid1,ConceptUuid2"); verify(lastSyncTimeService, never()).getFullLastSyncTimeInfoFor(DOWNLOAD_OBSERVATIONS); } @Test public void shouldUseLastSyncTimeToDownloadObservations() throws Exception, ObservationController.DownloadObservationException { List<String> patientUuids = asList("PatientUuid1", "PatientUuid2"); List<String> conceptUuids = asList("ConceptUuid1", "ConceptUuid2"); Date lastSyncTime = mock(Date.class); when(lastSyncTimeService.getLastSyncTimeFor(DOWNLOAD_OBSERVATIONS, "PatientUuid1,PatientUuid2;ConceptUuid1,ConceptUuid2")).thenReturn(lastSyncTime); observationController.downloadObservationsByPatientUuidsAndConceptUuids(patientUuids, conceptUuids); verify(observationService, never()).downloadObservationsByPatientUuidsAndConceptUuids(anyList(), anyList()); verify(observationService).downloadObservations(patientUuids, conceptUuids, lastSyncTime); } @Test public void shouldUpdateLastSyncTimeForObservation() throws Exception, ObservationController.DownloadObservationException { List<String> patientUuids = asList("PatientUuid1", "PatientUuid2"); List<String> conceptUuids = asList("ConceptUuid1", "ConceptUuid2"); Date currentDate = mock(Date.class); when(sntpService.getTimePerDeviceTimeZone()).thenReturn(currentDate); observationController.downloadObservationsByPatientUuidsAndConceptUuids(patientUuids, conceptUuids); ArgumentCaptor<LastSyncTime> argumentCaptor = ArgumentCaptor.forClass(LastSyncTime.class); verify(lastSyncTimeService).saveLastSyncTime(argumentCaptor.capture()); LastSyncTime savedLastSyncTime = argumentCaptor.getValue(); assertThat(savedLastSyncTime.getApiName(), is(DOWNLOAD_OBSERVATIONS)); assertThat(savedLastSyncTime.getLastSyncDate(), is(currentDate)); assertThat(savedLastSyncTime.getParamSignature(), is("PatientUuid1,PatientUuid2;ConceptUuid1,ConceptUuid2")); } @Test public void shouldProperlyProcessChangeInKnownPatientOrConcept() throws ObservationController.DownloadObservationException, IOException { List<String> patientUuids = asList("PatientUuid1", "PatientUuid2"); List<String> conceptUuids = asList("ConceptUuid1", "ConceptUuid2"); List<String> previousPatientUuids = asList("PatientUuid1", "PatientUuid3"); List<String> previousConceptUuids = asList("ConceptUuid1", "ConceptUuid3"); List<String> newPatientUuids = Collections.singletonList("PatientUuid2"); List<String> newConceptUuids = Collections.singletonList("ConceptUuid2"); LastSyncTime lastSyncTimeInFull = mock(LastSyncTime.class); when(lastSyncTimeInFull.getParamSignature()).thenReturn("PatientUuid1,PatientUuid3;ConceptUuid1,ConceptUuid3"); Date aDate = mock(Date.class); when(lastSyncTimeInFull.getLastSyncDate()).thenReturn(aDate); when(lastSyncTimeService.getFullLastSyncTimeInfoFor(DOWNLOAD_OBSERVATIONS)).thenReturn(lastSyncTimeInFull); List<Observation> anObservationSet = new ArrayList<>(); Observation anObservation = mock(Observation.class); anObservationSet.add(anObservation); when(observationService.downloadObservations(previousPatientUuids, previousConceptUuids, aDate)).thenReturn(anObservationSet); List<Observation> anotherObservationSet = new ArrayList<>(); Observation anotherObservation = mock(Observation.class); anotherObservationSet.add(anotherObservation); List<String> allConceptUuids = new ArrayList<>(); allConceptUuids.addAll(previousConceptUuids); allConceptUuids.addAll(newConceptUuids); Collections.sort(allConceptUuids); when(observationService.downloadObservations(newPatientUuids, allConceptUuids, null)).thenReturn(anotherObservationSet); Date currentDate = mock(Date.class); when(sntpService.getTimePerDeviceTimeZone()).thenReturn(currentDate); List<Observation> observations = observationController.downloadObservationsByPatientUuidsAndConceptUuids(patientUuids, conceptUuids); verify(lastSyncTimeService).getFullLastSyncTimeInfoFor(DOWNLOAD_OBSERVATIONS); verify(observationService).downloadObservations(previousPatientUuids, previousConceptUuids, aDate); verify(observationService).downloadObservations(previousPatientUuids, newConceptUuids, null); verify(observationService).downloadObservations(newPatientUuids, allConceptUuids, null); assertThat(observations.size(), is(2)); assertThat(observations, hasItems(anObservation, anotherObservation)); ArgumentCaptor<LastSyncTime> argumentCaptor = ArgumentCaptor.forClass(LastSyncTime.class); verify(lastSyncTimeService).saveLastSyncTime(argumentCaptor.capture()); LastSyncTime savedLastSyncTime = argumentCaptor.getValue(); assertThat(savedLastSyncTime.getApiName(), is(DOWNLOAD_OBSERVATIONS)); assertThat(savedLastSyncTime.getLastSyncDate(), is(currentDate)); assertThat(savedLastSyncTime.getParamSignature(), is("PatientUuid1,PatientUuid2,PatientUuid3;ConceptUuid1,ConceptUuid2,ConceptUuid3")); } @Test public void shouldRecognisedNonInitialisedLastSyncTime() throws ObservationController.DownloadObservationException, IOException { List<String> patientUuids = asList("PatientUuid1", "PatientUuid2"); List<String> conceptUuids = asList("ConceptUuid1", "ConceptUuid2"); when(lastSyncTimeService.getLastSyncTimeFor(DOWNLOAD_OBSERVATIONS, "PatientUuid1,PatientUuid2;ConceptUuid1,ConceptUuid2")).thenReturn(null); when(lastSyncTimeService.getFullLastSyncTimeInfoFor(DOWNLOAD_OBSERVATIONS)).thenReturn(null); observationController.downloadObservationsByPatientUuidsAndConceptUuids(patientUuids, conceptUuids); verify(observationService).downloadObservations(patientUuids, conceptUuids, null); }
ObservationController { public void saveObservations(List<Observation> observations) throws SaveObservationException { try { observationService.saveObservations(observations); } catch (IOException e) { throw new SaveObservationException(e); } } ObservationController(ObservationService observationService, ConceptService conceptService, EncounterService encounterService, LastSyncTimeService lastSyncTimeService, SntpService sntpService); Concepts getConceptWithObservations(String patientUuid); Concepts getConceptWithObservations(String patientUuid, String conceptUuid ); List<Observation> getObservationsByPatientuuidAndConceptId(String patientUuid,int conceptid); List<Observation> getObservationsByEncounterId(int encounterId); List<Observation> getObservationsByEncounterType(int encounterTypeId,String patientUuid); int getObservationsCountByPatient(String patientUuid); int getConceptColor(String uuid); void replaceObservations(List<Observation> allObservations); Concepts searchObservationsGroupedByConcepts(String term, String patientUuid); Encounters getEncountersWithObservations(String patientUuid); Encounters getObservationsByEncounterUuid(String encounterUuid); List<Observation> getObservationsByPatient(String patientUuid); Encounters searchObservationsGroupedByEncounter(String term, String patientUuid); List<Observation> downloadObservationsByPatientUuidsAndConceptUuids(List<String> patientUuids, List<String> conceptUuids); void saveObservations(List<Observation> observations); void deleteObservations(List<Observation> observations); void deleteAllObservations(List<Concept> concepts); }
@Test public void saveObservations_shouldSaveObservationsForPatient() throws Exception, ObservationController.SaveObservationException { final Concept concept1 = new Concept() {{ setUuid("concept1"); }}; final Concept concept2 = new Concept() {{ setUuid("concept2"); }}; final List<Observation> observations = buildObservations(concept1, concept2); observationController.saveObservations(observations); verify(observationService).saveObservations(observations); }
CohortController { public List<Cohort> getAllCohorts() throws CohortFetchException { try { return cohortService.getAllCohorts(); } catch (IOException e) { throw new CohortFetchException(e); } } CohortController(CohortService cohortService, LastSyncTimeService lastSyncTimeService, SntpService sntpService, MuzimaApplication muzimaApplication); String getDefaultLocation(); Provider getLoggedInProvider(); List<Cohort> getAllCohorts(); int countAllCohorts(); List<Cohort> downloadAllCohorts(String defaultLocation); List<CohortData> downloadCohortData(String[] cohortUuids, String defaulLocation); List<CohortData> downloadRemovedCohortData(String[] cohortUuids); CohortData downloadCohortDataByUuid(String uuid,String defaultLocation); CohortData downloadRemovedCohortDataByUuid(String uuid); List<Cohort> downloadCohortsByPrefix(List<String> cohortPrefixes,String defaultLocation); void saveAllCohorts(List<Cohort> cohorts); void saveOrUpdateCohorts(List<Cohort> cohorts); void deleteAllCohorts(); void deleteCohorts(List<Cohort> cohorts); List<Cohort> getSyncedCohorts(); boolean isDownloaded(Cohort cohort); boolean isUpdateAvailable(); List<Cohort> getCohortsWithPendingUpdates(); void markAsUpToDate(String[] cohortUuids); void setSyncStatus(String[] cohortUuids); int countSyncedCohorts(); void deleteAllCohortMembers(String cohortUuid); void addCohortMembers(List<CohortMember> cohortMembers); int countCohortMembers(Cohort cohort); List<Cohort> downloadCohortByName(String name); List<Cohort> downloadCohortsByUuidList(String[] uuidList); List<CohortMember> getCohortMembershipByPatientUuid(String patientUuid); void deleteAllCohortMembers(List<Cohort> allCohorts); void deleteCohortMembers(List<CohortMember> cohortMembers); }
@Test public void getAllCohorts_shouldReturnAllAvailableCohorts() throws IOException, CohortController.CohortFetchException { List<Cohort> cohorts = new ArrayList<>(); when(cohortService.getAllCohorts()).thenReturn(cohorts); assertThat(controller.getAllCohorts(), is(cohorts)); } @Test(expected = CohortController.CohortFetchException.class) public void getAllCohorts_shouldThrowCohortFetchExceptionIfExceptionThrownByCohortService() throws IOException, CohortController.CohortFetchException { doThrow(new IOException()).when(cohortService).getAllCohorts(); controller.getAllCohorts(); doThrow(new ParseException()).when(cohortService).getAllCohorts(); controller.getAllCohorts(); }
CohortController { public List<Cohort> downloadAllCohorts(String defaultLocation) throws CohortDownloadException { try { Date lastSyncTimeForCohorts = lastSyncTimeService.getLastSyncTimeFor(DOWNLOAD_COHORTS); Provider loggedInProvider = getLoggedInProvider(); List<Cohort> allCohorts = cohortService.downloadCohortsByNameAndSyncDate(StringUtils.EMPTY, lastSyncTimeForCohorts, defaultLocation, loggedInProvider); LastSyncTime lastSyncTime = new LastSyncTime(DOWNLOAD_COHORTS, sntpService.getTimePerDeviceTimeZone()); lastSyncTimeService.saveLastSyncTime(lastSyncTime); return allCohorts; } catch (IOException e) { throw new CohortDownloadException(e); } } CohortController(CohortService cohortService, LastSyncTimeService lastSyncTimeService, SntpService sntpService, MuzimaApplication muzimaApplication); String getDefaultLocation(); Provider getLoggedInProvider(); List<Cohort> getAllCohorts(); int countAllCohorts(); List<Cohort> downloadAllCohorts(String defaultLocation); List<CohortData> downloadCohortData(String[] cohortUuids, String defaulLocation); List<CohortData> downloadRemovedCohortData(String[] cohortUuids); CohortData downloadCohortDataByUuid(String uuid,String defaultLocation); CohortData downloadRemovedCohortDataByUuid(String uuid); List<Cohort> downloadCohortsByPrefix(List<String> cohortPrefixes,String defaultLocation); void saveAllCohorts(List<Cohort> cohorts); void saveOrUpdateCohorts(List<Cohort> cohorts); void deleteAllCohorts(); void deleteCohorts(List<Cohort> cohorts); List<Cohort> getSyncedCohorts(); boolean isDownloaded(Cohort cohort); boolean isUpdateAvailable(); List<Cohort> getCohortsWithPendingUpdates(); void markAsUpToDate(String[] cohortUuids); void setSyncStatus(String[] cohortUuids); int countSyncedCohorts(); void deleteAllCohortMembers(String cohortUuid); void addCohortMembers(List<CohortMember> cohortMembers); int countCohortMembers(Cohort cohort); List<Cohort> downloadCohortByName(String name); List<Cohort> downloadCohortsByUuidList(String[] uuidList); List<CohortMember> getCohortMembershipByPatientUuid(String patientUuid); void deleteAllCohortMembers(List<Cohort> allCohorts); void deleteCohortMembers(List<CohortMember> cohortMembers); }
@Test public void downloadAllCohorts_shouldReturnDownloadedCohorts() throws CohortController.CohortDownloadException, IOException { List<Cohort> downloadedCohorts = new ArrayList<>(); List<Cohort> cohorts = new ArrayList<>(); when(cohortService.downloadCohortsByName(StringUtils.EMPTY,null, null)).thenReturn(downloadedCohorts); when(lastSyncTimeService.getLastSyncTimeFor(DOWNLOAD_COHORTS)).thenReturn(null); controller.downloadAllCohorts(null); assertThat(controller.downloadAllCohorts(null), is(downloadedCohorts)); } @Test(expected = CohortController.CohortDownloadException.class) public void downloadAllCohorts_shouldThrowCohortDownloadExceptionIfExceptionIsThrownByCohortService() throws CohortController.CohortDownloadException, IOException { doThrow(new IOException()).when(cohortService).downloadCohortsByNameAndSyncDate(StringUtils.EMPTY, null,null,null); when(lastSyncTimeService.getLastSyncTimeFor(DOWNLOAD_COHORTS)).thenReturn(null); controller.downloadAllCohorts(null); } @Test public void shouldSaveLastSyncTimeAfterDownloadingAllCohorts() throws Exception, CohortController.CohortDownloadException { ArgumentCaptor<LastSyncTime> lastSyncCaptor = ArgumentCaptor.forClass(LastSyncTime.class); when(lastSyncTimeService.getLastSyncTimeFor(DOWNLOAD_COHORTS)).thenReturn(anotherMockDate); when(sntpService.getTimePerDeviceTimeZone()).thenReturn(mockDate); controller.downloadAllCohorts(null); verify(lastSyncTimeService).saveLastSyncTime(lastSyncCaptor.capture()); verify(lastSyncTimeService).getLastSyncTimeFor(DOWNLOAD_COHORTS); LastSyncTime setLastSyncTime = lastSyncCaptor.getValue(); assertThat(setLastSyncTime.getApiName(), is(DOWNLOAD_COHORTS)); assertThat(setLastSyncTime.getLastSyncDate(), is(mockDate)); assertThat(setLastSyncTime.getParamSignature(), nullValue()); }
CohortController { public List<Cohort> downloadCohortsByPrefix(List<String> cohortPrefixes,String defaultLocation) throws CohortDownloadException { Provider loggedInProvider = getLoggedInProvider(); List<Cohort> filteredCohorts = new ArrayList<>(); try { Date lastSyncDateOfCohort; LastSyncTime lastSyncTime; for (String cohortPrefix : cohortPrefixes) { lastSyncDateOfCohort = lastSyncTimeService.getLastSyncTimeFor(DOWNLOAD_COHORTS, cohortPrefix); List<Cohort> cohorts = cohortService.downloadCohortsByNameAndSyncDate(cohortPrefix, lastSyncDateOfCohort, defaultLocation, loggedInProvider); List<Cohort> filteredCohortsForPrefix = filterCohortsByPrefix(cohorts, cohortPrefix); addUniqueCohorts(filteredCohorts, filteredCohortsForPrefix); lastSyncTime = new LastSyncTime(DOWNLOAD_COHORTS, sntpService.getTimePerDeviceTimeZone(), cohortPrefix); lastSyncTimeService.saveLastSyncTime(lastSyncTime); } } catch (IOException e) { throw new CohortDownloadException(e); } return filteredCohorts; } CohortController(CohortService cohortService, LastSyncTimeService lastSyncTimeService, SntpService sntpService, MuzimaApplication muzimaApplication); String getDefaultLocation(); Provider getLoggedInProvider(); List<Cohort> getAllCohorts(); int countAllCohorts(); List<Cohort> downloadAllCohorts(String defaultLocation); List<CohortData> downloadCohortData(String[] cohortUuids, String defaulLocation); List<CohortData> downloadRemovedCohortData(String[] cohortUuids); CohortData downloadCohortDataByUuid(String uuid,String defaultLocation); CohortData downloadRemovedCohortDataByUuid(String uuid); List<Cohort> downloadCohortsByPrefix(List<String> cohortPrefixes,String defaultLocation); void saveAllCohorts(List<Cohort> cohorts); void saveOrUpdateCohorts(List<Cohort> cohorts); void deleteAllCohorts(); void deleteCohorts(List<Cohort> cohorts); List<Cohort> getSyncedCohorts(); boolean isDownloaded(Cohort cohort); boolean isUpdateAvailable(); List<Cohort> getCohortsWithPendingUpdates(); void markAsUpToDate(String[] cohortUuids); void setSyncStatus(String[] cohortUuids); int countSyncedCohorts(); void deleteAllCohortMembers(String cohortUuid); void addCohortMembers(List<CohortMember> cohortMembers); int countCohortMembers(Cohort cohort); List<Cohort> downloadCohortByName(String name); List<Cohort> downloadCohortsByUuidList(String[] uuidList); List<CohortMember> getCohortMembershipByPatientUuid(String patientUuid); void deleteAllCohortMembers(List<Cohort> allCohorts); void deleteCohortMembers(List<CohortMember> cohortMembers); }
@Test public void shouldSaveLastSyncTimeAfterDownloadingAllCohortsWithPrefix() throws Exception, CohortController.CohortDownloadException { ArgumentCaptor<LastSyncTime> lastSyncCaptor = ArgumentCaptor.forClass(LastSyncTime.class); when(lastSyncTimeService.getLastSyncTimeFor(DOWNLOAD_COHORTS, "prefix1")).thenReturn(anotherMockDate); when(lastSyncTimeService.getLastSyncTimeFor(DOWNLOAD_COHORTS, "prefix2")).thenReturn(anotherMockDate); when(lastSyncTimeService.getLastSyncTimeFor(DOWNLOAD_COHORTS)).thenReturn(anotherMockDate); when(sntpService.getTimePerDeviceTimeZone()).thenReturn(mockDate); controller.downloadCohortsByPrefix(asList("prefix1", "prefix2"),null); verify(lastSyncTimeService, times(2)).saveLastSyncTime(lastSyncCaptor.capture()); verify(lastSyncTimeService).getLastSyncTimeFor(DOWNLOAD_COHORTS, "prefix1"); verify(lastSyncTimeService).getLastSyncTimeFor(DOWNLOAD_COHORTS, "prefix2"); LastSyncTime firstSetLastSyncTime = lastSyncCaptor.getAllValues().get(0); LastSyncTime secondSetLastSyncTime = lastSyncCaptor.getAllValues().get(1); assertThat(firstSetLastSyncTime.getApiName(), is(DOWNLOAD_COHORTS)); assertThat(firstSetLastSyncTime.getLastSyncDate(), is(mockDate)); assertThat(firstSetLastSyncTime.getParamSignature(), is("prefix1")); assertThat(secondSetLastSyncTime.getApiName(), is(DOWNLOAD_COHORTS)); assertThat(secondSetLastSyncTime.getLastSyncDate(), is(mockDate)); assertThat(secondSetLastSyncTime.getParamSignature(), is("prefix2")); } @Test public void downloadCohortsByPrefix_shouldDownloadAllCohortsForTheGivenPrefixes() throws IOException, CohortController.CohortDownloadException { List<String> cohortPrefixes = new ArrayList<String>() {{ add("Age"); add("age"); add("Encounter"); }}; Cohort cohort11 = new Cohort() {{ setUuid("uuid1"); setName("Age between 20 and 30"); }}; Cohort cohort12 = new Cohort() {{ setUuid("uuid1"); setName("Age between 20 and 30"); }}; Cohort cohort2 = new Cohort() {{ setUuid("uuid2"); setName("Patients with age over 65"); }}; Cohort cohort3 = new Cohort() {{ setUuid("uuid3"); setName("Encounter 1"); }}; Cohort cohort4 = new Cohort() {{ setUuid("uuid4"); setName("Encounter 2"); }}; ArrayList<Cohort> agePrefixedCohortList1 = new ArrayList<>(); agePrefixedCohortList1.add(cohort11); agePrefixedCohortList1.add(cohort2); ArrayList<Cohort> agePrefixedCohortList2 = new ArrayList<>(); agePrefixedCohortList2.add(cohort12); agePrefixedCohortList2.add(cohort2); ArrayList<Cohort> encounterPerfixedCohortList = new ArrayList<>(); encounterPerfixedCohortList.add(cohort3); encounterPerfixedCohortList.add(cohort4); when(cohortService.downloadCohortsByNameAndSyncDate(cohortPrefixes.get(0), mockDate, null, null)).thenReturn(agePrefixedCohortList1); when(cohortService.downloadCohortsByNameAndSyncDate(cohortPrefixes.get(1), anotherMockDate, null, null)).thenReturn(agePrefixedCohortList2); when(cohortService.downloadCohortsByNameAndSyncDate(cohortPrefixes.get(2), anotherMockDate, null, null)).thenReturn(encounterPerfixedCohortList); when(lastSyncTimeService.getLastSyncTimeFor(DOWNLOAD_COHORTS, cohortPrefixes.get(0))).thenReturn(anotherMockDate); when(lastSyncTimeService.getLastSyncTimeFor(DOWNLOAD_COHORTS, cohortPrefixes.get(1))).thenReturn(anotherMockDate); when(lastSyncTimeService.getLastSyncTimeFor(DOWNLOAD_COHORTS, cohortPrefixes.get(2))).thenReturn(anotherMockDate); when(lastSyncTimeService.getLastSyncTimeFor(DOWNLOAD_COHORTS)).thenReturn(anotherMockDate); when(sntpService.getTimePerDeviceTimeZone()).thenReturn(mockDate); List<Cohort> downloadedCohorts = controller.downloadCohortsByPrefix(cohortPrefixes,null); assertThat(downloadedCohorts.size(), is(3)); assertTrue(downloadedCohorts.contains(cohort11)); assertTrue(downloadedCohorts.contains(cohort3)); assertTrue(downloadedCohorts.contains(cohort4)); }
CohortController { public CohortData downloadCohortDataByUuid(String uuid,String defaultLocation) throws CohortDownloadException { try { Date lastSyncDate = lastSyncTimeService.getLastSyncTimeFor(DOWNLOAD_COHORTS_DATA, uuid); Provider loggedInProvider = getLoggedInProvider(); CohortData cohortData = cohortService.downloadCohortDataAndSyncDate(uuid, false, lastSyncDate, defaultLocation, loggedInProvider); LastSyncTime lastSyncTime = new LastSyncTime(DOWNLOAD_COHORTS_DATA, sntpService.getTimePerDeviceTimeZone(), uuid); lastSyncTimeService.saveLastSyncTime(lastSyncTime); return cohortData; } catch (IOException e) { throw new CohortDownloadException(e); } } CohortController(CohortService cohortService, LastSyncTimeService lastSyncTimeService, SntpService sntpService, MuzimaApplication muzimaApplication); String getDefaultLocation(); Provider getLoggedInProvider(); List<Cohort> getAllCohorts(); int countAllCohorts(); List<Cohort> downloadAllCohorts(String defaultLocation); List<CohortData> downloadCohortData(String[] cohortUuids, String defaulLocation); List<CohortData> downloadRemovedCohortData(String[] cohortUuids); CohortData downloadCohortDataByUuid(String uuid,String defaultLocation); CohortData downloadRemovedCohortDataByUuid(String uuid); List<Cohort> downloadCohortsByPrefix(List<String> cohortPrefixes,String defaultLocation); void saveAllCohorts(List<Cohort> cohorts); void saveOrUpdateCohorts(List<Cohort> cohorts); void deleteAllCohorts(); void deleteCohorts(List<Cohort> cohorts); List<Cohort> getSyncedCohorts(); boolean isDownloaded(Cohort cohort); boolean isUpdateAvailable(); List<Cohort> getCohortsWithPendingUpdates(); void markAsUpToDate(String[] cohortUuids); void setSyncStatus(String[] cohortUuids); int countSyncedCohorts(); void deleteAllCohortMembers(String cohortUuid); void addCohortMembers(List<CohortMember> cohortMembers); int countCohortMembers(Cohort cohort); List<Cohort> downloadCohortByName(String name); List<Cohort> downloadCohortsByUuidList(String[] uuidList); List<CohortMember> getCohortMembershipByPatientUuid(String patientUuid); void deleteAllCohortMembers(List<Cohort> allCohorts); void deleteCohortMembers(List<CohortMember> cohortMembers); }
@Test public void downloadCohortDataByUuid_shouldDownloadCohortByUuid() throws IOException, CohortController.CohortDownloadException { CohortData cohortData = new CohortData(); String uuid = "uuid"; when(cohortService.downloadCohortDataAndSyncDate(uuid, false, null, null, null)).thenReturn(cohortData); when(lastSyncTimeService.getLastSyncTimeFor(DOWNLOAD_COHORTS_DATA, uuid)).thenReturn(null); assertThat(controller.downloadCohortDataByUuid(uuid, null), is(cohortData)); } @Test public void shouldSaveLastSyncTimeOfCohortData() throws Exception, CohortController.CohortDownloadException { String uuid = "uuid"; when(lastSyncTimeService.getLastSyncTimeFor(DOWNLOAD_COHORTS_DATA, uuid)).thenReturn(mockDate); when(sntpService.getTimePerDeviceTimeZone()).thenReturn(anotherMockDate); controller.downloadCohortDataByUuid(uuid, null); ArgumentCaptor<LastSyncTime> captor = ArgumentCaptor.forClass(LastSyncTime.class); verify(lastSyncTimeService).saveLastSyncTime(captor.capture()); LastSyncTime savedLastSyncTime = captor.getValue(); assertThat(savedLastSyncTime.getApiName(), is(DOWNLOAD_COHORTS_DATA)); assertThat(savedLastSyncTime.getLastSyncDate(), is(anotherMockDate)); assertThat(savedLastSyncTime.getParamSignature(), is(uuid)); } @Test(expected = CohortController.CohortDownloadException.class) public void downloadCohortDataByUuid_shouldThrowCohortDownloadExceptionIfExceptionThrownByCohortService() throws IOException, CohortController.CohortDownloadException { String uuid = "uuid"; doThrow(new IOException()).when(cohortService).downloadCohortDataAndSyncDate(uuid, false, null, null, null); when(lastSyncTimeService.getLastSyncTimeFor(DOWNLOAD_COHORTS_DATA, uuid)).thenReturn(null); controller.downloadCohortDataByUuid(uuid, null); }
CohortController { public List<CohortData> downloadCohortData(String[] cohortUuids, String defaulLocation) throws CohortDownloadException { ArrayList<CohortData> allCohortData = new ArrayList<>(); for (String cohortUuid : cohortUuids) { allCohortData.add(downloadCohortDataByUuid(cohortUuid, defaulLocation)); } return allCohortData; } CohortController(CohortService cohortService, LastSyncTimeService lastSyncTimeService, SntpService sntpService, MuzimaApplication muzimaApplication); String getDefaultLocation(); Provider getLoggedInProvider(); List<Cohort> getAllCohorts(); int countAllCohorts(); List<Cohort> downloadAllCohorts(String defaultLocation); List<CohortData> downloadCohortData(String[] cohortUuids, String defaulLocation); List<CohortData> downloadRemovedCohortData(String[] cohortUuids); CohortData downloadCohortDataByUuid(String uuid,String defaultLocation); CohortData downloadRemovedCohortDataByUuid(String uuid); List<Cohort> downloadCohortsByPrefix(List<String> cohortPrefixes,String defaultLocation); void saveAllCohorts(List<Cohort> cohorts); void saveOrUpdateCohorts(List<Cohort> cohorts); void deleteAllCohorts(); void deleteCohorts(List<Cohort> cohorts); List<Cohort> getSyncedCohorts(); boolean isDownloaded(Cohort cohort); boolean isUpdateAvailable(); List<Cohort> getCohortsWithPendingUpdates(); void markAsUpToDate(String[] cohortUuids); void setSyncStatus(String[] cohortUuids); int countSyncedCohorts(); void deleteAllCohortMembers(String cohortUuid); void addCohortMembers(List<CohortMember> cohortMembers); int countCohortMembers(Cohort cohort); List<Cohort> downloadCohortByName(String name); List<Cohort> downloadCohortsByUuidList(String[] uuidList); List<CohortMember> getCohortMembershipByPatientUuid(String patientUuid); void deleteAllCohortMembers(List<Cohort> allCohorts); void deleteCohortMembers(List<CohortMember> cohortMembers); }
@Test public void downloadCohortDataAndSyncDate_shouldDownloadDeltaCohortDataBySyncDate() throws IOException, CohortController.CohortDownloadException, ProviderController.ProviderLoadException { String[] uuids = new String[]{"uuid1", "uuid2"}; CohortData cohortData1 = new CohortData(); CohortData cohortData2 = new CohortData(); when(cohortService.downloadCohortDataAndSyncDate(uuids[0], false, null, null, null)).thenReturn(cohortData1); when(cohortService.downloadCohortDataAndSyncDate(uuids[1], false, null, null ,null)).thenReturn(cohortData2); when(lastSyncTimeService.getLastSyncTimeFor(DOWNLOAD_COHORTS_DATA, "uuid1")).thenReturn(null); when(lastSyncTimeService.getLastSyncTimeFor(DOWNLOAD_COHORTS_DATA, "uuid2")).thenReturn(null); List<CohortData> allCohortData = controller.downloadCohortData(uuids, null); assertThat(allCohortData.size(), is(2)); assertThat(allCohortData, hasItem(cohortData1)); assertThat(allCohortData, hasItem(cohortData2)); }
CohortController { public void saveAllCohorts(List<Cohort> cohorts) throws CohortSaveException { try { cohortService.saveCohorts(cohorts); } catch (IOException e) { throw new CohortSaveException(e); } } CohortController(CohortService cohortService, LastSyncTimeService lastSyncTimeService, SntpService sntpService, MuzimaApplication muzimaApplication); String getDefaultLocation(); Provider getLoggedInProvider(); List<Cohort> getAllCohorts(); int countAllCohorts(); List<Cohort> downloadAllCohorts(String defaultLocation); List<CohortData> downloadCohortData(String[] cohortUuids, String defaulLocation); List<CohortData> downloadRemovedCohortData(String[] cohortUuids); CohortData downloadCohortDataByUuid(String uuid,String defaultLocation); CohortData downloadRemovedCohortDataByUuid(String uuid); List<Cohort> downloadCohortsByPrefix(List<String> cohortPrefixes,String defaultLocation); void saveAllCohorts(List<Cohort> cohorts); void saveOrUpdateCohorts(List<Cohort> cohorts); void deleteAllCohorts(); void deleteCohorts(List<Cohort> cohorts); List<Cohort> getSyncedCohorts(); boolean isDownloaded(Cohort cohort); boolean isUpdateAvailable(); List<Cohort> getCohortsWithPendingUpdates(); void markAsUpToDate(String[] cohortUuids); void setSyncStatus(String[] cohortUuids); int countSyncedCohorts(); void deleteAllCohortMembers(String cohortUuid); void addCohortMembers(List<CohortMember> cohortMembers); int countCohortMembers(Cohort cohort); List<Cohort> downloadCohortByName(String name); List<Cohort> downloadCohortsByUuidList(String[] uuidList); List<CohortMember> getCohortMembershipByPatientUuid(String patientUuid); void deleteAllCohortMembers(List<Cohort> allCohorts); void deleteCohortMembers(List<CohortMember> cohortMembers); }
@Test public void saveAllCohorts_shouldSaveAllCohorts() throws CohortController.CohortSaveException, IOException { ArrayList<Cohort> cohorts = new ArrayList<Cohort>() {{ add(new Cohort()); add(new Cohort()); add(new Cohort()); }}; controller.saveAllCohorts(cohorts); verify(cohortService).saveCohorts(cohorts); verifyNoMoreInteractions(cohortService); } @Test(expected = CohortController.CohortSaveException.class) public void saveAllCohorts_shouldThrowCohortSaveExceptionIfExceptionThrownByCohortService() throws IOException, CohortController.CohortSaveException { ArrayList<Cohort> cohorts = new ArrayList<Cohort>() {{ add(new Cohort()); }}; doThrow(new IOException()).when(cohortService).saveCohorts(cohorts); controller.saveAllCohorts(cohorts); }
CohortController { public int countAllCohorts() throws CohortFetchException { try { return cohortService.countAllCohorts(); } catch (IOException e) { throw new CohortFetchException(e); } } CohortController(CohortService cohortService, LastSyncTimeService lastSyncTimeService, SntpService sntpService, MuzimaApplication muzimaApplication); String getDefaultLocation(); Provider getLoggedInProvider(); List<Cohort> getAllCohorts(); int countAllCohorts(); List<Cohort> downloadAllCohorts(String defaultLocation); List<CohortData> downloadCohortData(String[] cohortUuids, String defaulLocation); List<CohortData> downloadRemovedCohortData(String[] cohortUuids); CohortData downloadCohortDataByUuid(String uuid,String defaultLocation); CohortData downloadRemovedCohortDataByUuid(String uuid); List<Cohort> downloadCohortsByPrefix(List<String> cohortPrefixes,String defaultLocation); void saveAllCohorts(List<Cohort> cohorts); void saveOrUpdateCohorts(List<Cohort> cohorts); void deleteAllCohorts(); void deleteCohorts(List<Cohort> cohorts); List<Cohort> getSyncedCohorts(); boolean isDownloaded(Cohort cohort); boolean isUpdateAvailable(); List<Cohort> getCohortsWithPendingUpdates(); void markAsUpToDate(String[] cohortUuids); void setSyncStatus(String[] cohortUuids); int countSyncedCohorts(); void deleteAllCohortMembers(String cohortUuid); void addCohortMembers(List<CohortMember> cohortMembers); int countCohortMembers(Cohort cohort); List<Cohort> downloadCohortByName(String name); List<Cohort> downloadCohortsByUuidList(String[] uuidList); List<CohortMember> getCohortMembershipByPatientUuid(String patientUuid); void deleteAllCohortMembers(List<Cohort> allCohorts); void deleteCohortMembers(List<CohortMember> cohortMembers); }
@Test public void getTotalCohortsCount_shouldReturnEmptyListOfNoCohortsHaveBeenSynced() throws IOException, CohortController.CohortFetchException { when(cohortService.countAllCohorts()).thenReturn(2); assertThat(controller.countAllCohorts(), is(2)); }
MuzimaProgressDialog { @JavascriptInterface public void show(String title) { dialog.setTitle(title); dialog.setMessage(dialog.getContext().getResources().getString(R.string.general_progress_message)); dialog.show(); } MuzimaProgressDialog(Activity activity); MuzimaProgressDialog(ProgressDialog dialog); @JavascriptInterface void show(String title); @JavascriptInterface void updateMessage(String message); @JavascriptInterface void dismiss(); }
@Test public void shouldShowProgressDialogWithGivenText() { dialog.show("title"); Mockito.verify(progressDialog).setCancelable(false); Mockito.verify(progressDialog).setTitle("title"); Mockito.verify(progressDialog).setMessage("This might take a while"); Mockito.verify(progressDialog).show(); }
MuzimaProgressDialog { @JavascriptInterface public void dismiss() { if (dialog.isShowing()) { dialog.dismiss(); } } MuzimaProgressDialog(Activity activity); MuzimaProgressDialog(ProgressDialog dialog); @JavascriptInterface void show(String title); @JavascriptInterface void updateMessage(String message); @JavascriptInterface void dismiss(); }
@Test public void shouldDismissADialogOnlyWhenVisible() { when(progressDialog.isShowing()).thenReturn(true); dialog.dismiss(); Mockito.verify(progressDialog).dismiss(); } @Test public void shouldNotCallDismissIfProgressBarISNotVisible() { when(progressDialog.isShowing()).thenReturn(false); dialog.dismiss(); Mockito.verify(progressDialog, Mockito.never()).dismiss(); }
HTMLFormDataStore { @JavascriptInterface public void saveHTML(String jsonPayload, String status) { saveHTML(jsonPayload, status, false); } HTMLFormDataStore(HTMLFormWebViewActivity formWebViewActivity, FormData formData, boolean isFormReload, MuzimaApplication application); @JavascriptInterface String getStatus(); @JavascriptInterface void saveHTML(String jsonPayload, String status); @JavascriptInterface void saveHTML(String jsonPayload, String status, boolean keepFormOpen); @JavascriptInterface String getLocationNamesFromDevice(); @JavascriptInterface String getRelationshipTypesFromDevice(); @JavascriptInterface String getPatientDetailsFromServerByUuid(String uuid); @JavascriptInterface String getPersonDetailsFromDeviceByUuid(String uuid); @JavascriptInterface String searchPersons(String searchTerm, boolean searchServer); @JavascriptInterface String searchPersonsLocally(String searchTerm); @JavascriptInterface String searchPatientOnServer(String searchTerm); @JavascriptInterface String getProviderNamesFromDevice(); @JavascriptInterface String getDefaultEncounterProvider(); @JavascriptInterface String getFontSizePreference(); Date getEncounterDateFromForm(String jsonPayload); @JavascriptInterface String getStringResource(String stringResourceName); @JavascriptInterface String getConcepts(); @JavascriptInterface String getEncountersByPatientUuid(String patientuuid); @JavascriptInterface String getEncounterTypes(String patientuuid); @JavascriptInterface String getObsByConceptId(String patientUuid, int conceptId); @JavascriptInterface String getObsByEncounterId(int encounterid); @JavascriptInterface String getObsByEncounterType(String patientUuid, String encounterType); @JavascriptInterface boolean isMedicalRecordNumberRequired(); @JavascriptInterface void checkForPossibleFormDuplicate(String formUuid, String encounterDateTime, String patientUuid, String encounterPayLoad); @JavascriptInterface boolean getDefaultEncounterLocationSetting(); @JavascriptInterface String getDefaultEncounterLocationPreference(); @JavascriptInterface String getLastKnowGPSLocation(String jsonReturnType); @JavascriptInterface void logEvent(String tag, String details); @JavascriptInterface String getCohortMembershipByPatientUuid(String patientUuid); @JavascriptInterface void createPersonAndDiscardHTML(String jsonPayload); }
@Test public void shouldNotParseIncompletedForm() throws SetupConfigurationController.SetupConfigurationFetchException { when(formWebViewActivity.getString(anyInt())).thenReturn("success"); SetupConfigurationTemplate setupConfigurationTemplate = new SetupConfigurationTemplate(); setupConfigurationTemplate.setUuid("dummySetupConfig"); when(setupConfigurationController.getActiveSetupConfigurationTemplate()).thenReturn(setupConfigurationTemplate); String jsonPayLoad = readFile(); htmlFormDataStore.saveHTML(jsonPayLoad, Constants.STATUS_INCOMPLETE); verify(htmlFormObservationCreator, times(0)).createAndPersistObservations(jsonPayLoad,formData.getUuid()); }
FormDataStore { @JavascriptInterface public void save(String jsonData, String xmlData, String status) { formData.setXmlPayload(xmlData); formData.setJsonPayload(jsonData); formData.setStatus(status); try { if (isRegistrationComplete(status)) { Patient newPatient = formController.createNewPatient(applicationContext,formData); formData.setPatientUuid(newPatient.getUuid()); formWebViewActivity.startPatientSummaryView(newPatient); } parseForm(xmlData, status); formController.saveFormData(formData); formWebViewActivity.setResult(FormsActivity.RESULT_OK); formWebViewActivity.finish(); } catch (FormController.FormDataSaveException e) { Toast.makeText(formWebViewActivity, formWebViewActivity.getString(R.string.error_form_save), Toast.LENGTH_SHORT).show(); Log.e(getClass().getSimpleName(), "Exception occurred while saving form data", e); } catch (ConceptController.ConceptSaveException e) { Toast.makeText(formWebViewActivity, formWebViewActivity.getString(R.string.error_observation_form_save), Toast.LENGTH_SHORT).show(); Log.e(getClass().getSimpleName(), "Exception occurred while saving a concept parsed from the form data", e); } catch (ObservationController.ParseObservationException e) { Toast.makeText(formWebViewActivity, formWebViewActivity.getString(R.string.error_observation_form_save), Toast.LENGTH_SHORT).show(); Log.e(getClass().getSimpleName(), "Exception occurred while saving an observation parsed from the form data", e); } catch (ConceptController.ConceptParseException e) { Toast.makeText(formWebViewActivity, formWebViewActivity.getString(R.string.error_concept_parse), Toast.LENGTH_SHORT).show(); Log.e(getClass().getSimpleName(), "Exception occurred while parsing a concept parsed from the form data", e); } catch (ParseException e) { Toast.makeText(formWebViewActivity, formWebViewActivity.getString(R.string.error_observation_form_save), Toast.LENGTH_SHORT).show(); Log.e(getClass().getSimpleName(), "Exception occurred while parsing the xml payload", e); } catch (XmlPullParserException e) { Toast.makeText(formWebViewActivity, formWebViewActivity.getString(R.string.error_observation_form_save), Toast.LENGTH_SHORT).show(); Log.e(getClass().getSimpleName(), "Exception occurred while exploring the xml payload", e); } catch (PatientController.PatientLoadException e) { Toast.makeText(formWebViewActivity, formWebViewActivity.getString(R.string.error_observation_form_save), Toast.LENGTH_SHORT).show(); Log.e(getClass().getSimpleName(), "Exception occurred while loading a patient parsed from the form data", e); } catch (ConceptController.ConceptFetchException e) { Toast.makeText(formWebViewActivity, formWebViewActivity.getString(R.string.error_observation_form_save), Toast.LENGTH_SHORT).show(); Log.e(getClass().getSimpleName(), "Exception occurred while fetching a concept parsed from the form data", e); } catch (IOException e) { Toast.makeText(formWebViewActivity,formWebViewActivity.getString(R.string.error_observation_form_save), Toast.LENGTH_SHORT).show(); Log.e(getClass().getSimpleName(), "IOException occurred while saving observations parsed from the form data", e); } } FormDataStore(FormWebViewActivity formWebViewActivity, FormController formController, FormData formData); @JavascriptInterface void save(String jsonData, String xmlData, String status); @JavascriptInterface String getFormPayload(); @JavascriptInterface String getFormStatus(); @JavascriptInterface void showSaveProgressBar(); }
@Test public void save_shouldSaveFormDataWithStatus() throws FormController.FormDataSaveException { store.save("data", "xmldata", "status"); verify(controller).saveFormData(formData); verify(activity).finish(); assertThat(formData.getJsonPayload(), is("data")); assertThat(formData.getStatus(), is("status")); } @Test public void save_shouldNotFinishTheActivityIfThereIsAnExceptionWhileSaving() throws FormController.FormDataSaveException { doThrow(new FormController.FormDataSaveException(null)).when(controller).saveFormData(formData); when(activity.getString(anyInt())).thenReturn("success"); store.save("data", "xmldata", "status"); verify(activity, times(0)).finish(); } @Test public void shouldCreateANewPatientAndStoreHisUUIDAsPatientUUID() { String tempUUIDAssignedByDevice = "newUUID"; formData.setPatientUuid(null); formData.setDiscriminator(FORM_DISCRIMINATOR_REGISTRATION); Patient patient = new Patient(); patient.setUuid(tempUUIDAssignedByDevice); when(controller.createNewPatient(muzimaApplication,formData)).thenReturn(patient); store.save("data", "xmlData", "complete"); assertThat(formData.getXmlPayload(), is("xmlData")); assertThat(formData.getPatientUuid(), is(tempUUIDAssignedByDevice)); } @Test public void shouldParseObservationsInProvidedPayloadWhenSavingAsFinal() throws ConceptController.ConceptSaveException, ParseException, XmlPullParserException, PatientController.PatientLoadException,ConceptController.ConceptFetchException, ConceptController.ConceptParseException, IOException, ObservationController.ParseObservationException { String xmlPayload = "xmldata"; store.save("data", xmlPayload, Constants.STATUS_COMPLETE); verify(formParser).parseAndSaveObservations(xmlPayload,formData.getUuid()); } @Test public void shouldNotParseObservationsForIncompleteForm() throws ConceptController.ConceptSaveException, ParseException, XmlPullParserException, PatientController.PatientLoadException, ConceptController.ConceptFetchException, ConceptController.ConceptParseException, ObservationController.ParseObservationException, IOException { store.save("data", "xmldata", Constants.STATUS_INCOMPLETE); verify(formParser, times(0)).parseAndSaveObservations(anyString(),anyString()); }
FormDataStore { @JavascriptInterface public String getFormPayload() { return formData.getJsonPayload(); } FormDataStore(FormWebViewActivity formWebViewActivity, FormController formController, FormData formData); @JavascriptInterface void save(String jsonData, String xmlData, String status); @JavascriptInterface String getFormPayload(); @JavascriptInterface String getFormStatus(); @JavascriptInterface void showSaveProgressBar(); }
@Test public void getFormPayload_shouldGetTheFormDataPayload() { formData.setJsonPayload("payload"); assertThat(store.getFormPayload(), is("payload")); }
HTMLPatientJSONMapper { public String map(Patient patient, FormData formData, User loggedInUser, boolean isLoggedInUserIsDefaultProvider) { JSONObject prepopulateJSON = new JSONObject(); JSONObject patientDetails = new JSONObject(); JSONObject encounterDetails = new JSONObject(); try { patientDetails.put("patient.medical_record_number", StringUtils.defaultString(patient.getIdentifier())); patientDetails.put("patient.given_name", StringUtils.defaultString(patient.getGivenName())); patientDetails.put("patient.middle_name", StringUtils.defaultString(patient.getMiddleName())); patientDetails.put("patient.family_name", StringUtils.defaultString(patient.getFamilyName())); patientDetails.put("patient.sex", StringUtils.defaultString(patient.getGender())); patientDetails.put("patient.uuid", StringUtils.defaultString(patient.getUuid())); if (patient.getBirthdate() != null) { patientDetails.put("patient.birth_date", DateUtils.getFormattedDate(patient.getBirthdate())); } encounterDetails.put("encounter.form_uuid", StringUtils.defaultString(formData.getTemplateUuid())); encounterDetails.put("encounter.user_system_id", StringUtils.defaultString(formData.getUserSystemId())); if (isLoggedInUserIsDefaultProvider) { encounterDetails.put("encounter.provider_id_select", loggedInUser.getSystemId()); encounterDetails.put("encounter.provider_id", loggedInUser.getSystemId()); } if (!patient.getIdentifiers().isEmpty()) { List<PatientIdentifier> patientIdentifiers = patient.getIdentifiers(); JSONArray identifierTypeName = new JSONArray(); JSONArray identifierValue = new JSONArray(); for (PatientIdentifier identifier : patientIdentifiers) { if (identifier.getIdentifier() != null && !(identifier.getIdentifier().equals(patient.getIdentifier()) || identifier.getIdentifier().equals(patient.getUuid()))) { identifierTypeName.put(StringUtils.defaultString(identifier.getIdentifierType().getName())); identifierValue.put(StringUtils.defaultString(identifier.getIdentifier())); } } prepopulateJSON.put("other_identifier_type", identifierTypeName); prepopulateJSON.put("other_identifier_value", identifierValue); } prepopulateJSON.put("patient", patientDetails); prepopulateJSON.put("encounter", encounterDetails); } catch (JSONException e) { Log.e(getClass().getSimpleName(), "Could not populate patient registration data to JSON", e); } return prepopulateJSON.toString(); } String map(Patient patient, FormData formData, User loggedInUser, boolean isLoggedInUserIsDefaultProvider); Patient getPatient(MuzimaApplication muzimaApplication, String jsonPayload); }
@Test public void shouldAddPatientDetailsOnJSONFromPatient() { Date birthdate = new Date(); SimpleDateFormat formattedDate = new SimpleDateFormat(STANDARD_DATE_FORMAT); Patient patient = patient(new Date()); HTMLPatientJSONMapper mapper = new HTMLPatientJSONMapper(); FormData formData = new FormData(); User user = new User(); formData.setTemplateUuid("formUuid"); String json = mapper.map(patient, formData, user, false); assertThat(json, containsString("\"patient\":{")); assertThat(json, containsString("\"encounter\":{")); assertThat(json, containsString("\"patient.given_name\":\"givenname\"")); assertThat(json, containsString("\"patient.middle_name\":\"middlename\"")); assertThat(json, containsString("\"patient.family_name\":\"familyname\"")); assertThat(json, containsString("\"patient.sex\":\"Female\"")); assertThat(json, containsString("\"patient.uuid\":\"uuid\"")); assertThat(json, containsString("\"patient.birth_date\":\"" + formattedDate.format(birthdate) + "\"")); assertThat(json, containsString("\"encounter.form_uuid\":\"formUuid\"")); } @Test public void shouldNotFailIFBirthDateIsNull() { Patient patient = patient(null); HTMLPatientJSONMapper htmlPatientJSONMapper = new HTMLPatientJSONMapper(); User user = new User(); String json = htmlPatientJSONMapper.map(patient, new FormData(), user, false); assertThat(json,not(containsString("\"patient.birth_date\""))); }
StringUtils { public static String getCommaSeparatedStringFromList(final List<String> values){ if(values == null){ return ""; } StringBuilder builder = new StringBuilder(); for (String next : values) { builder.append(next).append(","); } String commaSeparated = builder.toString(); return commaSeparated.substring(0, commaSeparated.length() - 1); } static String getCommaSeparatedStringFromList(final List<String> values); static List<String> getListFromCommaSeparatedString(String value); static boolean isEmpty(String string); static String defaultString(String string); static boolean equals(String str1, String str2); static boolean equalsIgnoreCase(String str1, String str2); static int nullSafeCompare(String str1, String str2); static final String EMPTY; }
@Test public void shouldReturnCommaSeparatedList(){ ArrayList<String> listOfStrings = new ArrayList<String>() {{ add("Patient"); add("Registration"); add("New Tag"); }}; String commaSeparatedValues = StringUtils.getCommaSeparatedStringFromList(listOfStrings); assertThat(commaSeparatedValues, is("Patient,Registration,New Tag")); }
PatientComparator implements Comparator<Patient> { @Override public int compare(Patient patient1, Patient patient2) { if (patient1 == null) { patient1 = new Patient(); } if (patient2 == null) { patient2 = new Patient(); } int familyNameCompareResult = StringUtils.nullSafeCompare(patient1.getFamilyName(), patient2.getFamilyName()); if (familyNameCompareResult != 0) { return familyNameCompareResult; } int givenNameCompareResult = StringUtils.nullSafeCompare(patient1.getGivenName(), patient2.getGivenName()); if (givenNameCompareResult != 0) { return givenNameCompareResult; } return StringUtils.nullSafeCompare(patient1.getMiddleName(), patient2.getMiddleName()); } @Override int compare(Patient patient1, Patient patient2); }
@Test public void shouldSortByFamilyName() { Patient obama = patient("Obama", "Barack", "Hussein", "id1"); Patient bush = patient("Bush", "George", "W", "id2"); assertTrue(patientComparator.compare(obama, bush) > 0); } @Test public void shouldSortByGivenNameIfFamilyNameIsSame() { Patient barack = patient("Obama", "Barack", "Hussein", "id1"); Patient george = patient("Obama", "George", "W", "id2"); assertTrue(patientComparator.compare(barack, george) < 0); } @Test public void shouldSortByMiddleNameIfGivenNameAndFamilyNameAreSame() { Patient hussein = patient("Obama", "Barack", "Hussein", "id1"); Patient william = patient("Obama", "Barack", "William", "id2"); assertTrue(patientComparator.compare(hussein, william) < 0); }
MuzimaSyncService { public int[] downloadForms() { int[] result = new int[3]; try { long startDownloadForms = System.currentTimeMillis(); List<Form> allDownloadedForms = formController.downloadAllForms(); List<Form> allForms = formController.getAllAvailableForms(); int deletedFormCount = getDeletedFormCount(allDownloadedForms, allForms); long endDownloadForms = System.currentTimeMillis(); List<Form> voidedForms = deleteVoidedForms(allDownloadedForms); allDownloadedForms.removeAll(voidedForms); formController.updateAllForms(allDownloadedForms); long endSaveForms = System.currentTimeMillis(); Log.d(getClass().getSimpleName(), "In downloading forms: " + (endDownloadForms - startDownloadForms) / 1000 + " sec\n" + "In replacing forms: " + (endDownloadForms - endSaveForms) / 1000 + " sec"); result[0] = SUCCESS; result[1] = allDownloadedForms.size(); result[2] = deletedFormCount; } catch (FormController.FormFetchException e) { Log.e(getClass().getSimpleName(), "Exception when trying to download forms", e); result[0] = SyncStatusConstants.DOWNLOAD_ERROR; return result; } catch (FormController.FormSaveException e) { Log.e(getClass().getSimpleName(), "Exception when trying to save forms", e); result[0] = SyncStatusConstants.SAVE_ERROR; return result; } catch (FormController.FormDeleteException e) { Log.e(getClass().getSimpleName(), "Exception when trying to delete forms", e); result[0] = SyncStatusConstants.DELETE_ERROR; return result; } return result; } MuzimaSyncService(MuzimaApplication muzimaContext); int authenticate(String[] credentials); int authenticate(String[] credentials, boolean isUpdatePasswordRequired); int[] downloadForms(); int[] downloadFormTemplatesAndRelatedMetadata(String[] formIds, boolean replaceExistingTemplates); int[] downloadFormTemplates(String[] formIds, boolean replaceExistingTemplates); int[] downloadLocations(String[] locationIds); int[] downloadProviders(String[] providerIds); int[] downloadConcepts(String[] conceptIds); int[] downloadCohorts(); int[] downloadCohorts(String[] cohortUuids); int[] downloadPatientsForCohortsWithUpdatesAvailable(); int[] downloadRemovedCohortMembershipData(String[] cohortUuids); int[] downloadPatientsForCohorts(String[] cohortUuids); int[] downloadPatients(String[] patientUUIDs); int[] downloadObservationsForPatientsByCohortUUIDs(String[] cohortUuids, boolean replaceExistingObservation); int[] downloadObservationsForPatientsByPatientUUIDs(List<String> patientUuids, boolean replaceExistingObservations); int[] downloadEncountersForPatientsByCohortUUIDs(String[] cohortUuids, boolean replaceExistingEncounters); int[] downloadEncountersForPatientsByPatientUUIDs(List<String> patientUuids, boolean replaceExistingEncounters); int[] uploadAllCompletedForms(); void consolidatePatients(); List<FormData> getArchivedFormData(); int[] checkAndDeleteTemporaryDataForProcessedFormData(List<FormData> archivedFormData); List<String> getUuidsForAllPatientsFromLocalStorage(); List<Patient> updatePatientsNotPartOfCohorts(); int[] downloadNotifications(String receiverUuid); int[] downloadPatientReportHeaders(String patientUuid); int[] downloadAllPatientReportHeadersAndReports(); int[] downloadPatientReportsByUuid(String[] reportUuids); void downloadSetupConfigurations(); int[] downloadSetupConfigurationTemplate(String uuid); int[] downloadAndSaveUpdatedSetupConfigurationTemplate(String uuid); int[] updateSetupConfigurationTemplates(); int[] downloadSetting(String property); int[] downloadNewSettings(); void updateSettingsPreferences(List<MuzimaSetting> muzimaSettings); int[] downloadRelationshipsTypes(); int[] downloadRelationshipsForPatientsByPatientUUIDs(List<String> patientUuids); int[] downloadRelationshipsForPatientsByCohortUUIDs(String[] cohortUuids); String getDefaultLocation(); }
@Test public void downloadForms_shouldReplaceOldForms() throws FormController.FormFetchException, FormController.FormSaveException { List<Form> forms = new ArrayList<>(); when(formController.downloadAllForms()).thenReturn(forms); muzimaSyncService.downloadForms(); verify(formController).downloadAllForms(); verify(formController).updateAllForms(forms); } @Test public void downloadForms_shouldReturnSuccessStatusAndDownloadCountIfSuccessful() throws FormController.FormFetchException { int[] result = new int[]{SyncStatusConstants.SUCCESS, 2, 0}; List<Form> forms = new ArrayList<Form>() {{ add(new Form()); add(new Form()); }}; when(formController.downloadAllForms()).thenReturn(forms); assertThat(muzimaSyncService.downloadForms(), is(result)); } @Test public void downloadForms_shouldReturnDeletedFormCount() throws FormController.FormFetchException { int[] result = new int[]{SyncStatusConstants.SUCCESS, 2, 1}; List<Form> downloadedForms = new ArrayList<>(); Form formToDelete = new Form(); formToDelete.setRetired(true); formToDelete.setUuid("123"); Form newForm = new Form(); newForm.setRetired(false); newForm.setUuid("456"); downloadedForms.add(formToDelete); downloadedForms.add(new Form()); downloadedForms.add(newForm); List<Form> allAvailableForms = new ArrayList<>(); Form formA = new Form(); formA.setUuid("789"); allAvailableForms.add(formToDelete); allAvailableForms.add(formA); when(formController.downloadAllForms()).thenReturn(downloadedForms); when(formController.getAllAvailableForms()).thenReturn(allAvailableForms); assertThat(muzimaSyncService.downloadForms(), is(result)); } @Test public void downloadForms_shouldReturnDownloadErrorIfDownloadExceptionOccur() throws FormController.FormFetchException { doThrow(new FormController.FormFetchException(null)).when(formController).downloadAllForms(); assertThat(muzimaSyncService.downloadForms()[0], is(SyncStatusConstants.DOWNLOAD_ERROR)); } @Test public void downloadForms_shouldReturnSaveErrorIfSaveExceptionOccur() throws FormController.FormSaveException { doThrow(new FormController.FormSaveException(null)).when(formController).updateAllForms(anyList()); assertThat(muzimaSyncService.downloadForms()[0], is(SyncStatusConstants.SAVE_ERROR)); }
MuzimaSyncService { public int[] downloadFormTemplates(String[] formIds, boolean replaceExistingTemplates) { int[] result = new int[4]; try { List<FormTemplate> formTemplates = formController.downloadFormTemplates(formIds); formTemplates.removeAll(Collections.singleton(null)); Log.i(getClass().getSimpleName(), formTemplates.size() + " form template download successful"); if (replaceExistingTemplates) { formController.replaceFormTemplates(formTemplates); } else { formController.saveFormTemplates(formTemplates); } Log.i(getClass().getSimpleName(), "Form templates replaced"); result[0] = SUCCESS; result[1] = formTemplates.size(); } catch (FormController.FormSaveException e) { Log.e(getClass().getSimpleName(), "Exception when trying to save forms", e); result[0] = SyncStatusConstants.SAVE_ERROR; return result; } catch (FormController.FormFetchException e) { Log.e(getClass().getSimpleName(), "Exception when trying to download forms", e); result[0] = SyncStatusConstants.DOWNLOAD_ERROR; return result; } return result; } MuzimaSyncService(MuzimaApplication muzimaContext); int authenticate(String[] credentials); int authenticate(String[] credentials, boolean isUpdatePasswordRequired); int[] downloadForms(); int[] downloadFormTemplatesAndRelatedMetadata(String[] formIds, boolean replaceExistingTemplates); int[] downloadFormTemplates(String[] formIds, boolean replaceExistingTemplates); int[] downloadLocations(String[] locationIds); int[] downloadProviders(String[] providerIds); int[] downloadConcepts(String[] conceptIds); int[] downloadCohorts(); int[] downloadCohorts(String[] cohortUuids); int[] downloadPatientsForCohortsWithUpdatesAvailable(); int[] downloadRemovedCohortMembershipData(String[] cohortUuids); int[] downloadPatientsForCohorts(String[] cohortUuids); int[] downloadPatients(String[] patientUUIDs); int[] downloadObservationsForPatientsByCohortUUIDs(String[] cohortUuids, boolean replaceExistingObservation); int[] downloadObservationsForPatientsByPatientUUIDs(List<String> patientUuids, boolean replaceExistingObservations); int[] downloadEncountersForPatientsByCohortUUIDs(String[] cohortUuids, boolean replaceExistingEncounters); int[] downloadEncountersForPatientsByPatientUUIDs(List<String> patientUuids, boolean replaceExistingEncounters); int[] uploadAllCompletedForms(); void consolidatePatients(); List<FormData> getArchivedFormData(); int[] checkAndDeleteTemporaryDataForProcessedFormData(List<FormData> archivedFormData); List<String> getUuidsForAllPatientsFromLocalStorage(); List<Patient> updatePatientsNotPartOfCohorts(); int[] downloadNotifications(String receiverUuid); int[] downloadPatientReportHeaders(String patientUuid); int[] downloadAllPatientReportHeadersAndReports(); int[] downloadPatientReportsByUuid(String[] reportUuids); void downloadSetupConfigurations(); int[] downloadSetupConfigurationTemplate(String uuid); int[] downloadAndSaveUpdatedSetupConfigurationTemplate(String uuid); int[] updateSetupConfigurationTemplates(); int[] downloadSetting(String property); int[] downloadNewSettings(); void updateSettingsPreferences(List<MuzimaSetting> muzimaSettings); int[] downloadRelationshipsTypes(); int[] downloadRelationshipsForPatientsByPatientUUIDs(List<String> patientUuids); int[] downloadRelationshipsForPatientsByCohortUUIDs(String[] cohortUuids); String getDefaultLocation(); }
@Test public void downloadFormTemplates_shouldReplaceDownloadedTemplates() throws FormController.FormFetchException, FormController.FormSaveException { String[] formTemplateUuids = new String[]{}; List<FormTemplate> formTemplates = new ArrayList<>(); when(formController.downloadFormTemplates(formTemplateUuids)).thenReturn(formTemplates); SharedPreferences.Editor editor = mock(SharedPreferences.Editor.class); when(sharedPref.edit()).thenReturn(editor); muzimaSyncService.downloadFormTemplates(formTemplateUuids,true); verify(formController).downloadFormTemplates(formTemplateUuids); verify(formController).replaceFormTemplates(formTemplates); } @Test public void downloadFormTemplates_shouldReturnSuccessStatusAndDownloadCountIfSuccessful() throws FormController.FormFetchException { int[] result = new int[]{SyncStatusConstants.SUCCESS, 2, 0, 0}; List<FormTemplate> formTemplates = new ArrayList<FormTemplate>() {{ FormTemplate formTemplate = new FormTemplate(); formTemplate.setHtml("<html></html>"); add(formTemplate); add(formTemplate); }}; String[] formIds = {}; when(formController.downloadFormTemplates(formIds)).thenReturn(formTemplates); SharedPreferences.Editor editor = mock(SharedPreferences.Editor.class); when(sharedPref.edit()).thenReturn(editor); assertThat(muzimaSyncService.downloadFormTemplates(formIds, true), is(result)); } @Test public void downloadFormTemplates_shouldReturnDownloadErrorIfDownloadExceptionOccur() throws FormController.FormFetchException { String[] formUuids = {}; doThrow(new FormController.FormFetchException(null)).when(formController).downloadFormTemplates(formUuids); assertThat(muzimaSyncService.downloadFormTemplates(formUuids,true)[0], is(SyncStatusConstants.DOWNLOAD_ERROR)); } @Test public void downloadFormTemplates_shouldReturnSaveErrorIfSaveExceptionOccur() throws FormController.FormSaveException { String[] formUuids = {}; doThrow(new FormController.FormSaveException(null)).when(formController).replaceFormTemplates(anyList()); assertThat(muzimaSyncService.downloadFormTemplates(formUuids,true)[0], is(SyncStatusConstants.SAVE_ERROR)); }
MuzimaSyncService { public int[] downloadCohorts() { int[] result = new int[3]; try { List<Cohort> cohorts = downloadCohortsList(); List<Cohort> voidedCohorts = deleteVoidedCohorts(cohorts); cohorts.removeAll(voidedCohorts); cohortController.saveOrUpdateCohorts(cohorts); Log.i(getClass().getSimpleName(), "New cohorts are saved"); result[0] = SUCCESS; result[1] = cohorts.size(); result[2] = voidedCohorts.size(); } catch (CohortController.CohortDownloadException e) { Log.e(getClass().getSimpleName(), "Exception when trying to download cohorts", e); result[0] = SyncStatusConstants.DOWNLOAD_ERROR; return result; } catch (CohortController.CohortSaveException e) { Log.e(getClass().getSimpleName(), "Exception when trying to save cohorts", e); result[0] = SyncStatusConstants.SAVE_ERROR; return result; } catch (CohortController.CohortDeleteException e) { Log.e(getClass().getSimpleName(), "Exception occurred while deleting voided cohorts", e); result[0] = SyncStatusConstants.DELETE_ERROR; return result; } return result; } MuzimaSyncService(MuzimaApplication muzimaContext); int authenticate(String[] credentials); int authenticate(String[] credentials, boolean isUpdatePasswordRequired); int[] downloadForms(); int[] downloadFormTemplatesAndRelatedMetadata(String[] formIds, boolean replaceExistingTemplates); int[] downloadFormTemplates(String[] formIds, boolean replaceExistingTemplates); int[] downloadLocations(String[] locationIds); int[] downloadProviders(String[] providerIds); int[] downloadConcepts(String[] conceptIds); int[] downloadCohorts(); int[] downloadCohorts(String[] cohortUuids); int[] downloadPatientsForCohortsWithUpdatesAvailable(); int[] downloadRemovedCohortMembershipData(String[] cohortUuids); int[] downloadPatientsForCohorts(String[] cohortUuids); int[] downloadPatients(String[] patientUUIDs); int[] downloadObservationsForPatientsByCohortUUIDs(String[] cohortUuids, boolean replaceExistingObservation); int[] downloadObservationsForPatientsByPatientUUIDs(List<String> patientUuids, boolean replaceExistingObservations); int[] downloadEncountersForPatientsByCohortUUIDs(String[] cohortUuids, boolean replaceExistingEncounters); int[] downloadEncountersForPatientsByPatientUUIDs(List<String> patientUuids, boolean replaceExistingEncounters); int[] uploadAllCompletedForms(); void consolidatePatients(); List<FormData> getArchivedFormData(); int[] checkAndDeleteTemporaryDataForProcessedFormData(List<FormData> archivedFormData); List<String> getUuidsForAllPatientsFromLocalStorage(); List<Patient> updatePatientsNotPartOfCohorts(); int[] downloadNotifications(String receiverUuid); int[] downloadPatientReportHeaders(String patientUuid); int[] downloadAllPatientReportHeadersAndReports(); int[] downloadPatientReportsByUuid(String[] reportUuids); void downloadSetupConfigurations(); int[] downloadSetupConfigurationTemplate(String uuid); int[] downloadAndSaveUpdatedSetupConfigurationTemplate(String uuid); int[] updateSetupConfigurationTemplates(); int[] downloadSetting(String property); int[] downloadNewSettings(); void updateSettingsPreferences(List<MuzimaSetting> muzimaSettings); int[] downloadRelationshipsTypes(); int[] downloadRelationshipsForPatientsByPatientUUIDs(List<String> patientUuids); int[] downloadRelationshipsForPatientsByCohortUUIDs(String[] cohortUuids); String getDefaultLocation(); }
@Test public void downloadCohort_shouldDownloadAllCohortsWhenNoPrefixesAreAvailableAndReplaceOldCohorts() throws CohortController.CohortDownloadException, CohortController.CohortDeleteException, CohortController.CohortSaveException { List<Cohort> cohorts = new ArrayList<>(); when(cohortController.downloadAllCohorts(null)).thenReturn(cohorts); when(muzimaApplication.getSharedPreferences(COHORT_PREFIX_PREF, android.content.Context.MODE_PRIVATE)).thenReturn(sharedPref); when(sharedPref.getStringSet(Constants.COHORT_PREFIX_PREF_KEY, new HashSet<String>())).thenReturn(new HashSet<String>()); muzimaSyncService.downloadCohorts(); verify(cohortController).downloadAllCohorts(null); verify(cohortController).saveOrUpdateCohorts(cohorts); verify(cohortController).deleteCohorts(new ArrayList<Cohort>()); verifyNoMoreInteractions(cohortController); } @Test public void shouldDeleteVoidedCohortsWhenDownloading() throws CohortController.CohortDownloadException, CohortController.CohortSaveException, CohortController.CohortDeleteException { List<Cohort> cohorts = new ArrayList<>(); Cohort aCohort = mock(Cohort.class); Cohort voidedCohort = mock(Cohort.class); when(voidedCohort.isVoided()).thenReturn(true); when(aCohort.isVoided()).thenReturn(false); cohorts.add(aCohort); cohorts.add(voidedCohort); when(cohortController.downloadAllCohorts(null)).thenReturn(cohorts); when(muzimaApplication.getSharedPreferences(COHORT_PREFIX_PREF, android.content.Context.MODE_PRIVATE)).thenReturn(sharedPref); when(sharedPref.getStringSet(Constants.COHORT_PREFIX_PREF_KEY, new HashSet<String>())).thenReturn(new HashSet<String>()); muzimaSyncService.downloadCohorts(); verify(cohortController).deleteCohorts(Collections.singletonList(voidedCohort)); verify(cohortController).saveOrUpdateCohorts(Collections.singletonList(aCohort)); } @Test public void downloadCohort_shouldDownloadOnlyPrefixedCohortsWhenPrefixesAreAvailableAndReplaceOldCohorts() throws CohortController.CohortDownloadException, CohortController.CohortDeleteException, CohortController.CohortSaveException { List<Cohort> cohorts = new ArrayList<>(); List<String> cohortPrefixes = new ArrayList<String>() {{ add("Pref1"); add("Pref2"); }}; when(cohortController.downloadAllCohorts(null)).thenReturn(cohorts); when(muzimaApplication.getSharedPreferences(COHORT_PREFIX_PREF, android.content.Context.MODE_PRIVATE)).thenReturn(sharedPref); when(prefixesPreferenceService.getCohortPrefixes()).thenReturn(cohortPrefixes); muzimaSyncService.downloadCohorts(); verify(cohortController).downloadCohortsByPrefix(cohortPrefixes,null); verify(cohortController).saveOrUpdateCohorts(cohorts); verify(cohortController).deleteCohorts(new ArrayList<Cohort>()); verifyNoMoreInteractions(cohortController); } @Test public void downloadCohort_shouldReturnSuccessStatusAndDownloadCountIfSuccessful() throws CohortController.CohortDownloadException { List<Cohort> cohorts = new ArrayList<Cohort>() {{ add(new Cohort()); add(new Cohort()); }}; int[] result = new int[]{SyncStatusConstants.SUCCESS, 2, 0}; when(muzimaApplication.getSharedPreferences(COHORT_PREFIX_PREF, android.content.Context.MODE_PRIVATE)).thenReturn(sharedPref); when(sharedPref.getStringSet(Constants.COHORT_PREFIX_PREF_KEY, new HashSet<String>())).thenReturn(new HashSet<String>()); when(cohortController.downloadAllCohorts(null)).thenReturn(cohorts); assertThat(muzimaSyncService.downloadCohorts(), is(result)); } @Test public void downloadCohort_shouldReturnDownloadErrorIfDownloadExceptionOccurs() throws CohortController.CohortDownloadException { when(muzimaApplication.getSharedPreferences(COHORT_PREFIX_PREF, android.content.Context.MODE_PRIVATE)).thenReturn(sharedPref); when(sharedPref.getStringSet(Constants.COHORT_PREFIX_PREF_KEY, new HashSet<String>())).thenReturn(new HashSet<String>()); doThrow(new CohortController.CohortDownloadException(null)).when(cohortController).downloadAllCohorts(null); assertThat(muzimaSyncService.downloadCohorts()[0], is(SyncStatusConstants.DOWNLOAD_ERROR)); } @Test public void downloadCohort_shouldReturnSaveErrorIfSaveExceptionOccurs() throws CohortController.CohortSaveException { when(muzimaApplication.getSharedPreferences(COHORT_PREFIX_PREF, android.content.Context.MODE_PRIVATE)).thenReturn(sharedPref); when(sharedPref.getStringSet(Constants.COHORT_PREFIX_PREF_KEY, new HashSet<String>())).thenReturn(new HashSet<String>()); doThrow(new CohortController.CohortSaveException(null)).when(cohortController).saveOrUpdateCohorts(new ArrayList<Cohort>()); assertThat(muzimaSyncService.downloadCohorts()[0], is(SyncStatusConstants.SAVE_ERROR)); }
Concepts extends ArrayList<ConceptWithObservations> { public void sortByDate() { Collections.sort(this, new Comparator<ConceptWithObservations>() { @Override public int compare(ConceptWithObservations lhs, ConceptWithObservations rhs) { return -(lhs.getObservations().get(0).getObservationDatetime() .compareTo(rhs.getObservations().get(0).getObservationDatetime())); } }); } Concepts(); Concepts(Observation... observations); Concepts(List<Observation> observationsByPatient); void sortByDate(); }
@Test public void shouldSortTheConceptsByDate() { final Observation observation1 = createObservation(createConcept("c1"), "01", new Date(1)); final Observation observation2 = createObservation(createConcept("c2"), "02", new Date(3)); final Observation observation3 = createObservation(createConcept("c1"), "03", new Date(2)); final Concepts concepts = new Concepts(observation1, observation2, observation3); concepts.sortByDate(); final Concepts expectedOrderedConcept = new Concepts() {{ add(conceptWithObservations(observation2)); add(conceptWithObservations(observation3, observation1)); }}; assertThat(concepts, is(expectedOrderedConcept)); }
MuzimaSyncService { public int[] downloadPatientsForCohorts(String[] cohortUuids) { int[] result = new int[4]; int patientCount = 0; try { long startDownloadCohortData = System.currentTimeMillis(); List<CohortData> cohortDataList = cohortController.downloadCohortData(cohortUuids, getDefaultLocation()); long endDownloadCohortData = System.currentTimeMillis(); Log.i(getClass().getSimpleName(), "Cohort data download successful with " + cohortDataList.size() + " cohorts"); ArrayList<Patient> voidedPatients = new ArrayList<>(); List<Patient> cohortPatients; for (CohortData cohortData : cohortDataList) { cohortController.addCohortMembers(cohortData.getCohortMembers()); cohortPatients = cohortData.getPatients(); getVoidedPatients(voidedPatients, cohortPatients); cohortPatients.removeAll(voidedPatients); patientController.replacePatients(cohortPatients); patientCount += cohortData.getPatients().size(); } patientController.deletePatient(voidedPatients); long cohortMemberAndPatientReplaceTime = System.currentTimeMillis(); Log.i(getClass().getSimpleName(), "Cohort data replaced"); Log.i(getClass().getSimpleName(), "Patients downloaded " + patientCount); Log.d(getClass().getSimpleName(), "In Downloading cohort data: " + (endDownloadCohortData - startDownloadCohortData) / 1000 + " sec\n" + "In Replacing cohort members and patients: " + (cohortMemberAndPatientReplaceTime - endDownloadCohortData) / 1000 + " sec"); result[0] = SUCCESS; result[1] = patientCount; result[2] = cohortDataList.size(); result[3] = voidedPatients.size(); downloadRemovedCohortMembershipData(cohortUuids); cohortController.markAsUpToDate(cohortUuids); cohortController.setSyncStatus(cohortUuids); } catch (CohortController.CohortDownloadException e) { Log.e(getClass().getSimpleName(), "Exception thrown while downloading cohort data.", e); result[0] = SyncStatusConstants.DOWNLOAD_ERROR; } catch (CohortController.CohortReplaceException e) { Log.e(getClass().getSimpleName(), "Exception thrown while replacing cohort data.", e); result[0] = SyncStatusConstants.REPLACE_ERROR; } catch (PatientController.PatientSaveException e) { Log.e(getClass().getSimpleName(), "Exception thrown while replacing patients.", e); result[0] = SyncStatusConstants.REPLACE_ERROR; } catch (PatientController.PatientDeleteException e) { Log.e(getClass().getSimpleName(), "Exception thrown while deleting patients.", e); result[0] = SyncStatusConstants.DELETE_ERROR; } catch (CohortController.CohortUpdateException e) { Log.e(getClass().getSimpleName(), "Exception thrown while marking cohorts as updated.", e); result[0] = SyncStatusConstants.SAVE_ERROR; } return result; } MuzimaSyncService(MuzimaApplication muzimaContext); int authenticate(String[] credentials); int authenticate(String[] credentials, boolean isUpdatePasswordRequired); int[] downloadForms(); int[] downloadFormTemplatesAndRelatedMetadata(String[] formIds, boolean replaceExistingTemplates); int[] downloadFormTemplates(String[] formIds, boolean replaceExistingTemplates); int[] downloadLocations(String[] locationIds); int[] downloadProviders(String[] providerIds); int[] downloadConcepts(String[] conceptIds); int[] downloadCohorts(); int[] downloadCohorts(String[] cohortUuids); int[] downloadPatientsForCohortsWithUpdatesAvailable(); int[] downloadRemovedCohortMembershipData(String[] cohortUuids); int[] downloadPatientsForCohorts(String[] cohortUuids); int[] downloadPatients(String[] patientUUIDs); int[] downloadObservationsForPatientsByCohortUUIDs(String[] cohortUuids, boolean replaceExistingObservation); int[] downloadObservationsForPatientsByPatientUUIDs(List<String> patientUuids, boolean replaceExistingObservations); int[] downloadEncountersForPatientsByCohortUUIDs(String[] cohortUuids, boolean replaceExistingEncounters); int[] downloadEncountersForPatientsByPatientUUIDs(List<String> patientUuids, boolean replaceExistingEncounters); int[] uploadAllCompletedForms(); void consolidatePatients(); List<FormData> getArchivedFormData(); int[] checkAndDeleteTemporaryDataForProcessedFormData(List<FormData> archivedFormData); List<String> getUuidsForAllPatientsFromLocalStorage(); List<Patient> updatePatientsNotPartOfCohorts(); int[] downloadNotifications(String receiverUuid); int[] downloadPatientReportHeaders(String patientUuid); int[] downloadAllPatientReportHeadersAndReports(); int[] downloadPatientReportsByUuid(String[] reportUuids); void downloadSetupConfigurations(); int[] downloadSetupConfigurationTemplate(String uuid); int[] downloadAndSaveUpdatedSetupConfigurationTemplate(String uuid); int[] updateSetupConfigurationTemplates(); int[] downloadSetting(String property); int[] downloadNewSettings(); void updateSettingsPreferences(List<MuzimaSetting> muzimaSettings); int[] downloadRelationshipsTypes(); int[] downloadRelationshipsForPatientsByPatientUUIDs(List<String> patientUuids); int[] downloadRelationshipsForPatientsByCohortUUIDs(String[] cohortUuids); String getDefaultLocation(); }
@Test public void downloadPatientsForCohorts_shouldDownloadAndReplaceCohortMembersAndPatients() throws CohortController.CohortDownloadException, CohortController.CohortReplaceException, PatientController.PatientSaveException, CohortController.CohortUpdateException, ProviderController.ProviderLoadException { String[] cohortUuids = new String[]{"uuid1", "uuid2"}; List<CohortData> cohortDataList = new ArrayList<CohortData>() {{ add(new CohortData() {{ addCohortMember(new CohortMember()); addPatient(new Patient()); }}); add(new CohortData() {{ addCohortMember(new CohortMember()); addPatient(new Patient()); }}); }}; when(cohortController.downloadCohortData(cohortUuids, null)).thenReturn(cohortDataList); when(cohortController.downloadRemovedCohortData(cohortUuids)).thenReturn(new ArrayList<CohortData>()); muzimaSyncService.downloadPatientsForCohorts(cohortUuids); verify(cohortController).downloadCohortData(cohortUuids, null ); verify(cohortController).addCohortMembers(cohortDataList.get(0).getCohortMembers()); verify(cohortController).addCohortMembers(cohortDataList.get(1).getCohortMembers()); verify(cohortController).downloadRemovedCohortData(cohortUuids); verify(cohortController).markAsUpToDate(cohortUuids); verify(cohortController).setSyncStatus(cohortUuids); verify(patientController).replacePatients(cohortDataList.get(0).getPatients()); verify(patientController).replacePatients(cohortDataList.get(1).getPatients()); verifyNoMoreInteractions(cohortController); } @Test public void shouldDeleteVoidedPatientsDuringPatientDownload() throws CohortController.CohortDownloadException, PatientController.PatientDeleteException, ProviderController.ProviderLoadException { String[] cohortUuids = new String[]{"uuid1", "uuid2"}; final Patient voidedPatient = mock(Patient.class); when(voidedPatient.isVoided()).thenReturn(true); List<CohortData> cohortDataList = new ArrayList<CohortData>() {{ add(new CohortData() {{ addCohortMember(new CohortMember()); addPatient(new Patient()); addPatient(voidedPatient); }}); add(new CohortData() {{ addCohortMember(new CohortMember()); addPatient(new Patient()); }}); }}; when(cohortController.downloadCohortData(cohortUuids, null)).thenReturn(cohortDataList); muzimaSyncService.downloadPatientsForCohorts(cohortUuids); verify(patientController).deletePatient(Collections.singletonList(voidedPatient)); } @Test public void downloadPatientsForCohorts_shouldReturnSuccessStatusAndCohortAndPatinetCountIfDownloadIsSuccessful() throws CohortController.CohortDownloadException { String[] cohortUuids = new String[]{"uuid1", "uuid2"}; List<CohortData> cohortDataList = new ArrayList<CohortData>() {{ add(new CohortData() {{ addCohortMember(new CohortMember()); addPatient(new Patient()); }}); add(new CohortData() {{ addCohortMember(new CohortMember()); addPatient(new Patient()); addPatient(new Patient()); }}); }}; when(cohortController.downloadCohortData(cohortUuids, null)).thenReturn(cohortDataList); int[] result = muzimaSyncService.downloadPatientsForCohorts(cohortUuids); assertThat(result[0], is(SyncStatusConstants.SUCCESS)); assertThat(result[1], is(3)); assertThat(result[2], is(2)); } @Test public void downloadPatientsForCohorts_shouldReturnDownloadErrorIfDownloadExceptionIsThrown() throws CohortController.CohortDownloadException, ProviderController.ProviderLoadException { String[] cohortUuids = new String[]{"uuid1", "uuid2"}; doThrow(new CohortController.CohortDownloadException(null)).when(cohortController).downloadCohortData(cohortUuids, null); assertThat(muzimaSyncService.downloadPatientsForCohorts(cohortUuids)[0], is(SyncStatusConstants.DOWNLOAD_ERROR)); } @Test public void downloadPatientsForCohorts_shouldReturnReplaceErrorIfReplaceExceptionIsThrownForCohorts() throws CohortController.CohortReplaceException, CohortController.CohortDownloadException, ProviderController.ProviderLoadException { String[] cohortUuids = new String[]{"uuid1", "uuid2"}; List<CohortData> cohortDataList = new ArrayList<CohortData>() {{ add(new CohortData() {{ addCohortMember(new CohortMember()); addPatient(new Patient()); }}); add(new CohortData() {{ addCohortMember(new CohortMember()); addPatient(new Patient()); addPatient(new Patient()); }}); }}; when(cohortController.downloadCohortData(cohortUuids, null)).thenReturn(cohortDataList); doThrow(new CohortController.CohortReplaceException(null)).when(cohortController).addCohortMembers(anyList()); assertThat(muzimaSyncService.downloadPatientsForCohorts(cohortUuids)[0], is(SyncStatusConstants.REPLACE_ERROR)); } @Test public void downloadPatientsForCohorts_shouldReturnReplaceErrorIfReplaceExceptionIsThrownForPatients() throws CohortController.CohortDownloadException, PatientController.PatientSaveException, ProviderController.ProviderLoadException { String[] cohortUuids = new String[]{"uuid1", "uuid2"}; List<CohortData> cohortDataList = new ArrayList<CohortData>() {{ add(new CohortData() {{ addCohortMember(new CohortMember()); addPatient(new Patient()); }}); add(new CohortData() {{ addCohortMember(new CohortMember()); addPatient(new Patient()); addPatient(new Patient()); }}); }}; when(cohortController.downloadCohortData(cohortUuids, null)).thenReturn(cohortDataList); doThrow(new PatientController.PatientSaveException(null)).when(patientController).replacePatients(anyList()); assertThat(muzimaSyncService.downloadPatientsForCohorts(cohortUuids)[0], is(SyncStatusConstants.REPLACE_ERROR)); }
MuzimaSyncService { public int[] downloadObservationsForPatientsByCohortUUIDs(String[] cohortUuids, boolean replaceExistingObservation) { int[] result = new int[4]; List<Patient> patients; try { patients = patientController.getPatientsForCohorts(cohortUuids); List<String> patientlist = new ArrayList(); for (Patient patient : patients) { patientlist.add(patient.getUuid()); } result = downloadObservationsForPatientsByPatientUUIDs(patientlist, replaceExistingObservation); if (result[0] != SUCCESS) { updateProgressDialog(muzimaApplication.getString(R.string.error_encounter_observation_download)); } } catch (PatientController.PatientLoadException e) { Log.e(getClass().getSimpleName(), "Exception thrown while loading patients.", e); result[0] = SyncStatusConstants.LOAD_ERROR; } return result; } MuzimaSyncService(MuzimaApplication muzimaContext); int authenticate(String[] credentials); int authenticate(String[] credentials, boolean isUpdatePasswordRequired); int[] downloadForms(); int[] downloadFormTemplatesAndRelatedMetadata(String[] formIds, boolean replaceExistingTemplates); int[] downloadFormTemplates(String[] formIds, boolean replaceExistingTemplates); int[] downloadLocations(String[] locationIds); int[] downloadProviders(String[] providerIds); int[] downloadConcepts(String[] conceptIds); int[] downloadCohorts(); int[] downloadCohorts(String[] cohortUuids); int[] downloadPatientsForCohortsWithUpdatesAvailable(); int[] downloadRemovedCohortMembershipData(String[] cohortUuids); int[] downloadPatientsForCohorts(String[] cohortUuids); int[] downloadPatients(String[] patientUUIDs); int[] downloadObservationsForPatientsByCohortUUIDs(String[] cohortUuids, boolean replaceExistingObservation); int[] downloadObservationsForPatientsByPatientUUIDs(List<String> patientUuids, boolean replaceExistingObservations); int[] downloadEncountersForPatientsByCohortUUIDs(String[] cohortUuids, boolean replaceExistingEncounters); int[] downloadEncountersForPatientsByPatientUUIDs(List<String> patientUuids, boolean replaceExistingEncounters); int[] uploadAllCompletedForms(); void consolidatePatients(); List<FormData> getArchivedFormData(); int[] checkAndDeleteTemporaryDataForProcessedFormData(List<FormData> archivedFormData); List<String> getUuidsForAllPatientsFromLocalStorage(); List<Patient> updatePatientsNotPartOfCohorts(); int[] downloadNotifications(String receiverUuid); int[] downloadPatientReportHeaders(String patientUuid); int[] downloadAllPatientReportHeadersAndReports(); int[] downloadPatientReportsByUuid(String[] reportUuids); void downloadSetupConfigurations(); int[] downloadSetupConfigurationTemplate(String uuid); int[] downloadAndSaveUpdatedSetupConfigurationTemplate(String uuid); int[] updateSetupConfigurationTemplates(); int[] downloadSetting(String property); int[] downloadNewSettings(); void updateSettingsPreferences(List<MuzimaSetting> muzimaSettings); int[] downloadRelationshipsTypes(); int[] downloadRelationshipsForPatientsByPatientUUIDs(List<String> patientUuids); int[] downloadRelationshipsForPatientsByCohortUUIDs(String[] cohortUuids); String getDefaultLocation(); }
@Test public void downloadObservationsForPatients_shouldDownloadObservationsForGiveCohortIdsAndSavedConcepts() throws PatientController.PatientLoadException, ObservationController.DownloadObservationException, ObservationController.ReplaceObservationException, ConceptController.ConceptFetchException, ObservationController.DeleteObservationException { String[] cohortUuids = new String[]{"uuid1", "uuid2"}; final Patient patient = new Patient() {{ setUuid("patient1"); }}; List<Patient> patients = new ArrayList<Patient>() {{ add(patient); }}; List<Observation> allObservations = new ArrayList<Observation>() {{ add(new Observation(){{setPerson(patient);}}); add(new Observation(){{setPerson(patient);}}); }}; when(patientController.getPatientsForCohorts(cohortUuids)).thenReturn(patients); when(muzimaApplication.getSharedPreferences(Constants.CONCEPT_PREF, android.content.Context.MODE_PRIVATE)).thenReturn(sharedPref); List<String> patientUuids = Collections.singletonList("patient1"); List<String> conceptUuids = asList("weight", "temp"); when(observationController.downloadObservationsByPatientUuidsAndConceptUuids(patientUuids, conceptUuids)) .thenReturn(allObservations); Concept conceptWeight = new Concept(); conceptWeight.setUuid("weight"); Concept conceptTemp = new Concept(); conceptTemp.setUuid("temp"); when(conceptController.getConcepts()).thenReturn(asList(conceptWeight, conceptTemp)); muzimaSyncService.downloadObservationsForPatientsByCohortUUIDs(cohortUuids,true); verify(observationController).downloadObservationsByPatientUuidsAndConceptUuids(patientUuids, conceptUuids); verify(observationController).deleteObservations(new ArrayList<Observation>()); verify(observationController).replaceObservations(allObservations); verifyNoMoreInteractions(observationController); } @Test public void downloadObservationsForPatients_shouldReturnSuccessAndCountWhenDownloadingObservationsForPatient() throws PatientController.PatientLoadException, ObservationController.DownloadObservationException, ConceptController.ConceptFetchException { String[] cohortUuids = new String[]{"uuid1"}; final Patient patient = new Patient() {{ setUuid("patient1"); }}; List<Patient> patients = new ArrayList<Patient>() {{ add(patient); }}; List<Observation> allObservations = new ArrayList<Observation>() {{ add(new Observation(){{setPerson(patient);}}); add(new Observation(){{setPerson(patient);}}); }}; when(patientController.getPatientsForCohorts(cohortUuids)).thenReturn(patients); List<String> conceptUuids = Collections.singletonList("weight"); Concept conceptWeight = new Concept(); conceptWeight.setUuid("weight"); when(conceptController.getConcepts()).thenReturn(Collections.singletonList(conceptWeight)); when(observationController.downloadObservationsByPatientUuidsAndConceptUuids(Collections.singletonList("patient1"), conceptUuids)) .thenReturn(allObservations); int[] result = muzimaSyncService.downloadObservationsForPatientsByCohortUUIDs(cohortUuids,true); assertThat(result[0], is(SyncStatusConstants.SUCCESS)); assertThat(result[1], is(2)); } @Test public void downloadObservationsForPatients_shouldReturnLoadErrorWhenLoadExceptionIsThrownForObservations() throws PatientController.PatientLoadException { String[] cohortUuids = new String[]{}; doThrow(new PatientController.PatientLoadException("")).when(patientController).getPatientsForCohorts(cohortUuids); int[] result = muzimaSyncService.downloadObservationsForPatientsByCohortUUIDs(cohortUuids,true); assertThat(result[0], is(SyncStatusConstants.LOAD_ERROR)); } @Test public void downloadObservationsForPatients_shouldReturnDownloadErrorWhenDownloadExceptionIsThrownForObservations() throws ObservationController.DownloadObservationException, PatientController.PatientLoadException, ConceptController.ConceptFetchException { String[] cohortUuids = new String[]{"uuid1"}; List<Patient> patients = new ArrayList<Patient>() {{ add(new Patient() {{ setUuid("patient1"); }}); }}; List<Concept> conceptList = new ArrayList<Concept>() {{ add(new Concept() {{ setUuid("concept1"); }}); }}; Set<String> concepts = new HashSet<String>() {{ add("weight"); }}; when(patientController.getPatientsForCohorts(cohortUuids)).thenReturn(patients); when(conceptController.getConcepts()).thenReturn(conceptList); when(muzimaApplication.getSharedPreferences(Constants.CONCEPT_PREF, android.content.Context.MODE_PRIVATE)).thenReturn(sharedPref); when(sharedPref.getStringSet(Constants.CONCEPT_PREF_KEY, new HashSet<String>())).thenReturn(concepts); doThrow(new ObservationController.DownloadObservationException(null)).when(observationController).downloadObservationsByPatientUuidsAndConceptUuids(anyList(), anyList()); int[] result = muzimaSyncService.downloadObservationsForPatientsByCohortUUIDs(cohortUuids,true); assertThat(result[0], is(SyncStatusConstants.DOWNLOAD_ERROR)); } @Test public void downloadObservationsForPatients_shouldReturnReplaceErrorWhenReplaceExceptionIsThrownForObservations() throws ReplaceObservationException, PatientController.PatientLoadException, ConceptController.ConceptFetchException { String[] cohortUuids = new String[]{}; List<Patient> patients = new ArrayList<Patient>() {{ add(new Patient() {{ setUuid("patient1"); }}); }}; List<Concept> concepts = new ArrayList<>(); concepts.add(new Concept(){{ setUuid("concept1"); }}); when(patientController.getPatientsForCohorts(cohortUuids)).thenReturn(patients); when(conceptController.getConcepts()).thenReturn(concepts); doThrow(new ObservationController.ReplaceObservationException(null)).when(observationController).replaceObservations(anyList()); int[] result = muzimaSyncService.downloadObservationsForPatientsByCohortUUIDs(cohortUuids,true); assertThat(result[0], is(SyncStatusConstants.REPLACE_ERROR)); }
Encounters extends ArrayList<EncounterWithObservations> { public void sortByDate() { Collections.sort(this, new Comparator<EncounterWithObservations>() { @Override public int compare(EncounterWithObservations lhs, EncounterWithObservations rhs) { if (lhs.getEncounter().getEncounterDatetime()==null) return -1; if (rhs.getEncounter().getEncounterDatetime()==null) return 1; return -(lhs.getEncounter().getEncounterDatetime() .compareTo(rhs.getEncounter().getEncounterDatetime())); } }); } Encounters(); Encounters(Observation... observations); Encounters(List<Observation> observationsByPatient); void sortByDate(); }
@Test public void shouldSortTheEncountersByDate() { final Observation observation1 = createObservation(createEncounter("c1", new Date(1)), "01"); final Observation observation2 = createObservation(createEncounter("c2", new Date(3)), "02"); final Encounters encounters = new Encounters(observation1, observation2); encounters.sortByDate(); final Encounters expectedOrderedConcept = new Encounters() {{ add(encounterWithObservations(observation2)); add(encounterWithObservations(observation1)); }}; assertThat(encounters, is(expectedOrderedConcept)); } @Test public void shouldPutEncounterWithNullDateAtTheTopWhenItsNotAtTheTop() { final Observation observation1 = createObservation(createEncounter("c1", new Date(1)), "01"); final Observation observation2 = createObservation(createEncounter("c2", null), "02"); final Encounters encounters = new Encounters(observation1, observation2); encounters.sortByDate(); final Encounters expectedOrderedConcept = new Encounters() {{ add(encounterWithObservations(observation2)); add(encounterWithObservations(observation1)); }}; assertThat(encounters, is(expectedOrderedConcept)); } @Test public void shouldPutEncounterWithNullDateAtTheTopWhenItsAtTheTop() { final Observation observation1 = createObservation(createEncounter("c1", null), "01"); final Observation observation2 = createObservation(createEncounter("c2", new Date(1)), "02"); final Encounters encounters = new Encounters(observation1, observation2); encounters.sortByDate(); final Encounters expectedOrderedConcept = new Encounters() {{ add(encounterWithObservations(observation1)); add(encounterWithObservations(observation2)); }}; assertThat(encounters, is(expectedOrderedConcept)); }
MuzimaSyncService { public int[] downloadEncountersForPatientsByCohortUUIDs(String[] cohortUuids, boolean replaceExistingEncounters) { int[] result = new int[4]; List<Patient> patients; try { patients = patientController.getPatientsForCohorts(cohortUuids); List<String> patientlist = new ArrayList(); for (Patient patient : patients) { patientlist.add(patient.getUuid()); } result = downloadEncountersForPatientsByPatientUUIDs(patientlist, replaceExistingEncounters); if (result[0] != SUCCESS) { Log.e(getClass().getSimpleName(), "Could not download encounters"); updateProgressDialog(muzimaApplication.getString(R.string.error_encounter_download)); } } catch (PatientController.PatientLoadException e) { Log.e(getClass().getSimpleName(), "Exception thrown while loading patients.", e); result[0] = SyncStatusConstants.LOAD_ERROR; } return result; } MuzimaSyncService(MuzimaApplication muzimaContext); int authenticate(String[] credentials); int authenticate(String[] credentials, boolean isUpdatePasswordRequired); int[] downloadForms(); int[] downloadFormTemplatesAndRelatedMetadata(String[] formIds, boolean replaceExistingTemplates); int[] downloadFormTemplates(String[] formIds, boolean replaceExistingTemplates); int[] downloadLocations(String[] locationIds); int[] downloadProviders(String[] providerIds); int[] downloadConcepts(String[] conceptIds); int[] downloadCohorts(); int[] downloadCohorts(String[] cohortUuids); int[] downloadPatientsForCohortsWithUpdatesAvailable(); int[] downloadRemovedCohortMembershipData(String[] cohortUuids); int[] downloadPatientsForCohorts(String[] cohortUuids); int[] downloadPatients(String[] patientUUIDs); int[] downloadObservationsForPatientsByCohortUUIDs(String[] cohortUuids, boolean replaceExistingObservation); int[] downloadObservationsForPatientsByPatientUUIDs(List<String> patientUuids, boolean replaceExistingObservations); int[] downloadEncountersForPatientsByCohortUUIDs(String[] cohortUuids, boolean replaceExistingEncounters); int[] downloadEncountersForPatientsByPatientUUIDs(List<String> patientUuids, boolean replaceExistingEncounters); int[] uploadAllCompletedForms(); void consolidatePatients(); List<FormData> getArchivedFormData(); int[] checkAndDeleteTemporaryDataForProcessedFormData(List<FormData> archivedFormData); List<String> getUuidsForAllPatientsFromLocalStorage(); List<Patient> updatePatientsNotPartOfCohorts(); int[] downloadNotifications(String receiverUuid); int[] downloadPatientReportHeaders(String patientUuid); int[] downloadAllPatientReportHeadersAndReports(); int[] downloadPatientReportsByUuid(String[] reportUuids); void downloadSetupConfigurations(); int[] downloadSetupConfigurationTemplate(String uuid); int[] downloadAndSaveUpdatedSetupConfigurationTemplate(String uuid); int[] updateSetupConfigurationTemplates(); int[] downloadSetting(String property); int[] downloadNewSettings(); void updateSettingsPreferences(List<MuzimaSetting> muzimaSettings); int[] downloadRelationshipsTypes(); int[] downloadRelationshipsForPatientsByPatientUUIDs(List<String> patientUuids); int[] downloadRelationshipsForPatientsByCohortUUIDs(String[] cohortUuids); String getDefaultLocation(); }
@Test public void downloadEncountersForPatients_shouldDownloadInBatch() throws PatientController.PatientLoadException, EncounterController.ReplaceEncounterException, EncounterController.DownloadEncounterException, SetupConfigurationController.SetupConfigurationFetchException { String[] cohortUuids = new String[]{"uuid1"}; final Patient patient = new Patient() {{ setUuid("patient1"); }}; List<Patient> patients = new ArrayList<Patient>() {{ add(patient); }}; List<Encounter> encounters = new ArrayList<Encounter>() {{ add(new Encounter(){{setPatient(patient);}}); }}; SetupConfigurationTemplate setupConfigurationTemplate = new SetupConfigurationTemplate(); setupConfigurationTemplate.setUuid("dummySetupConfig"); when(setupConfigurationController.getActiveSetupConfigurationTemplate()).thenReturn(setupConfigurationTemplate); when(patientController.getPatientsForCohorts(cohortUuids)).thenReturn(patients); List<String> patientUuids = Collections.singletonList("patient1"); when(encounterController.downloadEncountersByPatientUuids(patientUuids, setupConfigurationTemplate.getUuid())).thenReturn(encounters); muzimaSyncService.downloadEncountersForPatientsByCohortUUIDs(cohortUuids, true); verify(encounterController).downloadEncountersByPatientUuids(patientUuids, setupConfigurationTemplate.getUuid()); verify(encounterController).replaceEncounters(encounters); verifyNoMoreInteractions(observationController); }
MuzimaSyncService { public int[] downloadEncountersForPatientsByPatientUUIDs(List<String> patientUuids, boolean replaceExistingEncounters) { int[] result = new int[4]; try { String activeSetupConfigUuid = null; try { SetupConfigurationTemplate setupConfigurationTemplate = setupConfigurationController.getActiveSetupConfigurationTemplate(); if (setupConfigurationTemplate != null) { activeSetupConfigUuid = setupConfigurationTemplate.getUuid(); } } catch (SetupConfigurationController.SetupConfigurationFetchException e) { Log.e(getClass().getSimpleName(), "Could not obtain active setup config", e); } List<List<String>> slicedPatientUuids = split(patientUuids); Set<String> patientsForDownloadedEncounters = new HashSet(); long totalTimeDownloading = 0, totalTimeReplacing = 0, totalTimeSaving = 0; int i = 0; for (List<String> slicedPatientUuid : slicedPatientUuids) { Log.i(getClass().getSimpleName(), "Downloading encounters for " + slicedPatientUuid.size() + " patients"); long startDownloadEncounters = System.currentTimeMillis(); List<Encounter> allEncounters = new ArrayList<>(encounterController.downloadEncountersByPatientUuids(slicedPatientUuid, activeSetupConfigUuid)); long endDownloadObservations = System.currentTimeMillis(); Log.d(getClass().getSimpleName(), "In Downloading encounters : " + (endDownloadObservations - startDownloadEncounters) / 1000 + " sec\n"); totalTimeDownloading += endDownloadObservations - startDownloadEncounters; Log.i(getClass().getSimpleName(), "Encounters download successful with " + allEncounters.size() + " encounters"); for (Encounter encounter : allEncounters) { patientsForDownloadedEncounters.add(encounter.getPatient().getUuid()); } Log.i(getClass().getSimpleName(), "Downloaded Encounters for patient " + patientsForDownloadedEncounters.size() + " of " + patientUuids.size()); updateProgressDialog(muzimaApplication.getString(R.string.info_encounter_download_progress, patientsForDownloadedEncounters.size(), patientUuids.size())); ArrayList<Encounter> voidedEncounters = getVoidedEncounters(allEncounters); allEncounters.removeAll(voidedEncounters); encounterController.deleteEncounters(voidedEncounters); Log.i(getClass().getSimpleName(), "Voided encounters delete successful with " + voidedEncounters.size() + " encounters"); if (replaceExistingEncounters) { encounterController.replaceEncounters(allEncounters); long replacedEncounters = System.currentTimeMillis(); Log.d(getClass().getSimpleName(), "In Replacing encounters for patients: " + (replacedEncounters - endDownloadObservations) / 1000 + " sec"); totalTimeReplacing += replacedEncounters - endDownloadObservations; } else { encounterController.saveEncounters(allEncounters); long savedEncounters = System.currentTimeMillis(); Log.d(getClass().getSimpleName(), "In Saving encounters : " + (savedEncounters - endDownloadObservations) / 1000 + " sec\n"); totalTimeSaving += savedEncounters - endDownloadObservations; } result[1] += allEncounters.size(); result[2] += voidedEncounters.size(); } Log.d(getClass().getSimpleName(), "Total Downloading encounters : " + totalTimeDownloading / 1000 + " sec\n"); Log.d(getClass().getSimpleName(), "Total Replacing encounters : " + totalTimeReplacing / 1000 + " sec\n"); Log.d(getClass().getSimpleName(), "Total Saving encounters : " + totalTimeSaving / 1000 + " sec\n"); result[0] = SUCCESS; result[3] = patientsForDownloadedEncounters.size(); } catch (EncounterController.DownloadEncounterException e) { Log.e(getClass().getSimpleName(), "Exception thrown while downloading encounters.", e); result[0] = SyncStatusConstants.DOWNLOAD_ERROR; } catch (EncounterController.ReplaceEncounterException e) { Log.e(getClass().getSimpleName(), "Exception thrown while replacing encounters.", e); result[0] = SyncStatusConstants.REPLACE_ERROR; } catch (EncounterController.DeleteEncounterException e) { Log.e(getClass().getSimpleName(), "Exception thrown while deleting encounters.", e); result[0] = SyncStatusConstants.DELETE_ERROR; } catch (EncounterController.SaveEncounterException e) { Log.e(getClass().getSimpleName(), "Exception thrown while saving encounters.", e); result[0] = SyncStatusConstants.SAVE_ERROR; } return result; } MuzimaSyncService(MuzimaApplication muzimaContext); int authenticate(String[] credentials); int authenticate(String[] credentials, boolean isUpdatePasswordRequired); int[] downloadForms(); int[] downloadFormTemplatesAndRelatedMetadata(String[] formIds, boolean replaceExistingTemplates); int[] downloadFormTemplates(String[] formIds, boolean replaceExistingTemplates); int[] downloadLocations(String[] locationIds); int[] downloadProviders(String[] providerIds); int[] downloadConcepts(String[] conceptIds); int[] downloadCohorts(); int[] downloadCohorts(String[] cohortUuids); int[] downloadPatientsForCohortsWithUpdatesAvailable(); int[] downloadRemovedCohortMembershipData(String[] cohortUuids); int[] downloadPatientsForCohorts(String[] cohortUuids); int[] downloadPatients(String[] patientUUIDs); int[] downloadObservationsForPatientsByCohortUUIDs(String[] cohortUuids, boolean replaceExistingObservation); int[] downloadObservationsForPatientsByPatientUUIDs(List<String> patientUuids, boolean replaceExistingObservations); int[] downloadEncountersForPatientsByCohortUUIDs(String[] cohortUuids, boolean replaceExistingEncounters); int[] downloadEncountersForPatientsByPatientUUIDs(List<String> patientUuids, boolean replaceExistingEncounters); int[] uploadAllCompletedForms(); void consolidatePatients(); List<FormData> getArchivedFormData(); int[] checkAndDeleteTemporaryDataForProcessedFormData(List<FormData> archivedFormData); List<String> getUuidsForAllPatientsFromLocalStorage(); List<Patient> updatePatientsNotPartOfCohorts(); int[] downloadNotifications(String receiverUuid); int[] downloadPatientReportHeaders(String patientUuid); int[] downloadAllPatientReportHeadersAndReports(); int[] downloadPatientReportsByUuid(String[] reportUuids); void downloadSetupConfigurations(); int[] downloadSetupConfigurationTemplate(String uuid); int[] downloadAndSaveUpdatedSetupConfigurationTemplate(String uuid); int[] updateSetupConfigurationTemplates(); int[] downloadSetting(String property); int[] downloadNewSettings(); void updateSettingsPreferences(List<MuzimaSetting> muzimaSettings); int[] downloadRelationshipsTypes(); int[] downloadRelationshipsForPatientsByPatientUUIDs(List<String> patientUuids); int[] downloadRelationshipsForPatientsByCohortUUIDs(String[] cohortUuids); String getDefaultLocation(); }
@Test public void shouldDeleteVoidedEncountersWhenDownloadingEncounters() throws EncounterController.DeleteEncounterException, EncounterController.DownloadEncounterException, SetupConfigurationController.SetupConfigurationFetchException { String[] patientUuids = new String[]{"patientUuid1", "patientUuid2"}; final Patient patient = new Patient() {{ setUuid("patient1"); }}; SetupConfigurationTemplate setupConfigurationTemplate = new SetupConfigurationTemplate(); setupConfigurationTemplate.setUuid("dummySetupConfig"); when(setupConfigurationController.getActiveSetupConfigurationTemplate()).thenReturn(setupConfigurationTemplate); List<Encounter> encounters = new ArrayList<>(); encounters.add(new Encounter(){{setPatient(patient);}}); Encounter voidedEncounter = mock(Encounter.class); when(voidedEncounter.isVoided()).thenReturn(true); when(voidedEncounter.getPatient()).thenReturn(patient); encounters.add(voidedEncounter); when(encounterController.downloadEncountersByPatientUuids(asList(patientUuids), setupConfigurationTemplate.getUuid())).thenReturn(encounters); muzimaSyncService.downloadEncountersForPatientsByPatientUUIDs(asList(patientUuids),true); verify(encounterController).deleteEncounters(Collections.singletonList(voidedEncounter)); }
MuzimaSyncService { public void consolidatePatients() { List<Patient> allLocalPatients = patientController.getAllPatientsCreatedLocallyAndNotSynced(); for (Patient localPatient : allLocalPatients) { Patient patientFromServer = patientController.consolidateTemporaryPatient(localPatient); if (patientFromServer != null) { checkChangeInPatientId(localPatient, patientFromServer); patientFromServer.addIdentifier(localPatient.getIdentifier(LOCAL_PATIENT)); patientController.deletePatient(localPatient); try { patientController.savePatient(patientFromServer); } catch (PatientController.PatientSaveException e) { Log.e(getClass().getSimpleName(), "Error while saving patients.", e); } } } } MuzimaSyncService(MuzimaApplication muzimaContext); int authenticate(String[] credentials); int authenticate(String[] credentials, boolean isUpdatePasswordRequired); int[] downloadForms(); int[] downloadFormTemplatesAndRelatedMetadata(String[] formIds, boolean replaceExistingTemplates); int[] downloadFormTemplates(String[] formIds, boolean replaceExistingTemplates); int[] downloadLocations(String[] locationIds); int[] downloadProviders(String[] providerIds); int[] downloadConcepts(String[] conceptIds); int[] downloadCohorts(); int[] downloadCohorts(String[] cohortUuids); int[] downloadPatientsForCohortsWithUpdatesAvailable(); int[] downloadRemovedCohortMembershipData(String[] cohortUuids); int[] downloadPatientsForCohorts(String[] cohortUuids); int[] downloadPatients(String[] patientUUIDs); int[] downloadObservationsForPatientsByCohortUUIDs(String[] cohortUuids, boolean replaceExistingObservation); int[] downloadObservationsForPatientsByPatientUUIDs(List<String> patientUuids, boolean replaceExistingObservations); int[] downloadEncountersForPatientsByCohortUUIDs(String[] cohortUuids, boolean replaceExistingEncounters); int[] downloadEncountersForPatientsByPatientUUIDs(List<String> patientUuids, boolean replaceExistingEncounters); int[] uploadAllCompletedForms(); void consolidatePatients(); List<FormData> getArchivedFormData(); int[] checkAndDeleteTemporaryDataForProcessedFormData(List<FormData> archivedFormData); List<String> getUuidsForAllPatientsFromLocalStorage(); List<Patient> updatePatientsNotPartOfCohorts(); int[] downloadNotifications(String receiverUuid); int[] downloadPatientReportHeaders(String patientUuid); int[] downloadAllPatientReportHeadersAndReports(); int[] downloadPatientReportsByUuid(String[] reportUuids); void downloadSetupConfigurations(); int[] downloadSetupConfigurationTemplate(String uuid); int[] downloadAndSaveUpdatedSetupConfigurationTemplate(String uuid); int[] updateSetupConfigurationTemplates(); int[] downloadSetting(String property); int[] downloadNewSettings(); void updateSettingsPreferences(List<MuzimaSetting> muzimaSettings); int[] downloadRelationshipsTypes(); int[] downloadRelationshipsForPatientsByPatientUUIDs(List<String> patientUuids); int[] downloadRelationshipsForPatientsByCohortUUIDs(String[] cohortUuids); String getDefaultLocation(); }
@Test public void consolidatePatients_shouldGetAllPatientsConsolidateSavePatientFromServerAndDeleteLocalPatient() throws PatientController.PatientSaveException { Patient localPatient = mock(Patient.class); Patient remotePatient = mock(Patient.class); when(patientController.consolidateTemporaryPatient(localPatient)).thenReturn(remotePatient); when(patientController.getAllPatientsCreatedLocallyAndNotSynced()).thenReturn(Collections.singletonList(localPatient)); muzimaSyncService.consolidatePatients(); verify(patientController).getAllPatientsCreatedLocallyAndNotSynced(); verify(patientController).consolidateTemporaryPatient(localPatient); verify(patientController).savePatient(remotePatient); verify(patientController).deletePatient(localPatient); }
MuzimaSyncService { public List<Patient> updatePatientsNotPartOfCohorts() { List<Patient> patientsNotInCohorts = patientController.getPatientsNotInCohorts(); List<Patient> downloadedPatients = new ArrayList<>(); try { for (Patient patient : patientsNotInCohorts) { downloadedPatients.add(patientController.downloadPatientByUUID(patient.getUuid())); } downloadedPatients.removeAll(singleton(null)); patientController.replacePatients(downloadedPatients); } catch (PatientController.PatientSaveException e) { Log.e(getClass().getSimpleName(), "Exception thrown while updating patients from server.", e); } catch (PatientController.PatientDownloadException e) { Log.e(getClass().getSimpleName(), "Exception thrown while downloading patients from server.", e); } return downloadedPatients; } MuzimaSyncService(MuzimaApplication muzimaContext); int authenticate(String[] credentials); int authenticate(String[] credentials, boolean isUpdatePasswordRequired); int[] downloadForms(); int[] downloadFormTemplatesAndRelatedMetadata(String[] formIds, boolean replaceExistingTemplates); int[] downloadFormTemplates(String[] formIds, boolean replaceExistingTemplates); int[] downloadLocations(String[] locationIds); int[] downloadProviders(String[] providerIds); int[] downloadConcepts(String[] conceptIds); int[] downloadCohorts(); int[] downloadCohorts(String[] cohortUuids); int[] downloadPatientsForCohortsWithUpdatesAvailable(); int[] downloadRemovedCohortMembershipData(String[] cohortUuids); int[] downloadPatientsForCohorts(String[] cohortUuids); int[] downloadPatients(String[] patientUUIDs); int[] downloadObservationsForPatientsByCohortUUIDs(String[] cohortUuids, boolean replaceExistingObservation); int[] downloadObservationsForPatientsByPatientUUIDs(List<String> patientUuids, boolean replaceExistingObservations); int[] downloadEncountersForPatientsByCohortUUIDs(String[] cohortUuids, boolean replaceExistingEncounters); int[] downloadEncountersForPatientsByPatientUUIDs(List<String> patientUuids, boolean replaceExistingEncounters); int[] uploadAllCompletedForms(); void consolidatePatients(); List<FormData> getArchivedFormData(); int[] checkAndDeleteTemporaryDataForProcessedFormData(List<FormData> archivedFormData); List<String> getUuidsForAllPatientsFromLocalStorage(); List<Patient> updatePatientsNotPartOfCohorts(); int[] downloadNotifications(String receiverUuid); int[] downloadPatientReportHeaders(String patientUuid); int[] downloadAllPatientReportHeadersAndReports(); int[] downloadPatientReportsByUuid(String[] reportUuids); void downloadSetupConfigurations(); int[] downloadSetupConfigurationTemplate(String uuid); int[] downloadAndSaveUpdatedSetupConfigurationTemplate(String uuid); int[] updateSetupConfigurationTemplates(); int[] downloadSetting(String property); int[] downloadNewSettings(); void updateSettingsPreferences(List<MuzimaSetting> muzimaSettings); int[] downloadRelationshipsTypes(); int[] downloadRelationshipsForPatientsByPatientUUIDs(List<String> patientUuids); int[] downloadRelationshipsForPatientsByCohortUUIDs(String[] cohortUuids); String getDefaultLocation(); }
@Test public void shouldUpdatePatientsThatAreNotInCohorts() throws PatientController.PatientSaveException, PatientController.PatientDownloadException { Patient localPatient1 = patient("patientUUID1"); Patient localPatient2 = patient("patientUUID2"); Patient serverPatient1 = patient("patientUUID3"); when(patientController.getPatientsNotInCohorts()).thenReturn(asList(localPatient1, localPatient2)); when(patientController.downloadPatientByUUID("patientUUID1")).thenReturn(serverPatient1); when(patientController.downloadPatientByUUID("patientUUID2")).thenReturn(null); muzimaSyncService.updatePatientsNotPartOfCohorts(); verify(patientController).downloadPatientByUUID("patientUUID1"); verify(patientController).downloadPatientByUUID("patientUUID2"); verify(patientController).replacePatients(Collections.singletonList(serverPatient1)); }
MuzimaSyncService { public int[] downloadPatients(String[] patientUUIDs) { int[] result = new int[2]; List<Patient> downloadedPatients; try { downloadedPatients = downloadPatientsByUUID(patientUUIDs); patientController.savePatients(downloadedPatients); Log.e(getClass().getSimpleName(), "DOWNLOADED PATIENTS."); result[0] = SUCCESS; result[1] = downloadedPatients.size(); } catch (PatientController.PatientDownloadException e) { Log.e(getClass().getSimpleName(), "Error while downloading patients.", e); result[0] = SyncStatusConstants.DOWNLOAD_ERROR; } catch (PatientController.PatientSaveException e) { Log.e(getClass().getSimpleName(), "Error while saving patients.", e); result[0] = SyncStatusConstants.DOWNLOAD_ERROR; } return result; } MuzimaSyncService(MuzimaApplication muzimaContext); int authenticate(String[] credentials); int authenticate(String[] credentials, boolean isUpdatePasswordRequired); int[] downloadForms(); int[] downloadFormTemplatesAndRelatedMetadata(String[] formIds, boolean replaceExistingTemplates); int[] downloadFormTemplates(String[] formIds, boolean replaceExistingTemplates); int[] downloadLocations(String[] locationIds); int[] downloadProviders(String[] providerIds); int[] downloadConcepts(String[] conceptIds); int[] downloadCohorts(); int[] downloadCohorts(String[] cohortUuids); int[] downloadPatientsForCohortsWithUpdatesAvailable(); int[] downloadRemovedCohortMembershipData(String[] cohortUuids); int[] downloadPatientsForCohorts(String[] cohortUuids); int[] downloadPatients(String[] patientUUIDs); int[] downloadObservationsForPatientsByCohortUUIDs(String[] cohortUuids, boolean replaceExistingObservation); int[] downloadObservationsForPatientsByPatientUUIDs(List<String> patientUuids, boolean replaceExistingObservations); int[] downloadEncountersForPatientsByCohortUUIDs(String[] cohortUuids, boolean replaceExistingEncounters); int[] downloadEncountersForPatientsByPatientUUIDs(List<String> patientUuids, boolean replaceExistingEncounters); int[] uploadAllCompletedForms(); void consolidatePatients(); List<FormData> getArchivedFormData(); int[] checkAndDeleteTemporaryDataForProcessedFormData(List<FormData> archivedFormData); List<String> getUuidsForAllPatientsFromLocalStorage(); List<Patient> updatePatientsNotPartOfCohorts(); int[] downloadNotifications(String receiverUuid); int[] downloadPatientReportHeaders(String patientUuid); int[] downloadAllPatientReportHeadersAndReports(); int[] downloadPatientReportsByUuid(String[] reportUuids); void downloadSetupConfigurations(); int[] downloadSetupConfigurationTemplate(String uuid); int[] downloadAndSaveUpdatedSetupConfigurationTemplate(String uuid); int[] updateSetupConfigurationTemplates(); int[] downloadSetting(String property); int[] downloadNewSettings(); void updateSettingsPreferences(List<MuzimaSetting> muzimaSettings); int[] downloadRelationshipsTypes(); int[] downloadRelationshipsForPatientsByPatientUUIDs(List<String> patientUuids); int[] downloadRelationshipsForPatientsByCohortUUIDs(String[] cohortUuids); String getDefaultLocation(); }
@Test public void shouldDownloadAndSavePatientsGivenByUUID() throws PatientController.PatientDownloadException, PatientController.PatientSaveException { Patient patient1 = patient("patientUUID1"); Patient patient2 = patient("patientUUID2"); String[] patientUUIDs = new String[]{"patientUUID1", "patientUUID2"}; when(patientController.downloadPatientByUUID("patientUUID1")).thenReturn(patient1); when(patientController.downloadPatientByUUID("patientUUID2")).thenReturn(patient2); int[] result = muzimaSyncService.downloadPatients(patientUUIDs); assertThat(result[0], is(SyncStatusConstants.SUCCESS)); assertThat(result[1], is(2)); verify(patientController).savePatients(asList(patient1, patient2)); } @Test public void shouldReturnFailureIfDownloadFails() throws PatientController.PatientDownloadException, PatientController.PatientSaveException { Patient patient1 = patient("patientUUID1"); String[] patientUUIDs = new String[]{"patientUUID1"}; when(patientController.downloadPatientByUUID("patientUUID1")).thenReturn(patient1); doThrow(new PatientController.PatientSaveException(new Throwable())).when(patientController).savePatients(Collections.singletonList(patient1)); int[] result = muzimaSyncService.downloadPatients(patientUUIDs); assertThat(result[0], is(SyncStatusConstants.DOWNLOAD_ERROR)); assertThat(result[1], is(0)); verify(patientController).savePatients(Collections.singletonList(patient1)); }
MuzimaSyncService { public int[] downloadObservationsForPatientsByPatientUUIDs(List<String> patientUuids, boolean replaceExistingObservations) { int[] result = new int[4]; try { List<String> conceptUuidsFromConcepts = getConceptUuidsFromConcepts(conceptController.getConcepts()); List<List<String>> slicedPatientUuids = split(patientUuids); List<List<String>> slicedConceptUuids = split(conceptUuidsFromConcepts); Set<String> patientUuidsForDownloadedObs = new HashSet<>(); long totalTimeDownloading = 0, totalTimeReplacing = 0, totalTimeSaving = 0; int i = 0; for (List<String> slicedPatientUuid : slicedPatientUuids) { for (List<String> slicedConceptUuid : slicedConceptUuids) { long startDownloadObservations = System.currentTimeMillis(); List<Observation> allObservations = new ArrayList<>(observationController.downloadObservationsByPatientUuidsAndConceptUuids( slicedPatientUuid, slicedConceptUuid)); for (Observation observation : allObservations) { patientUuidsForDownloadedObs.add(observation.getPerson().getUuid()); } updateProgressDialog(muzimaApplication.getString(R.string.info_observations_download_progress, patientUuidsForDownloadedObs.size(), patientUuids.size())); Log.i(getClass().getSimpleName(), "Downloading observations for " + slicedPatientUuid.size() + " patients and " + slicedConceptUuid.size() + " concepts"); long endDownloadObservations = System.currentTimeMillis(); Log.i(getClass().getSimpleName(), "Observations download successful with " + allObservations.size() + " observations"); Log.d(getClass().getSimpleName(), "In Downloading observations : " + (endDownloadObservations - startDownloadObservations) / 1000 + " sec"); totalTimeDownloading += endDownloadObservations - startDownloadObservations; List<Observation> voidedObservations = getVoidedObservations(allObservations); observationController.deleteObservations(voidedObservations); allObservations.removeAll(voidedObservations); Log.i(getClass().getSimpleName(), "Voided observations delete successful with " + voidedObservations.size() + " observations"); if (replaceExistingObservations) { observationController.replaceObservations(allObservations); long replacedObservations = System.currentTimeMillis(); Log.d(getClass().getSimpleName(), "In Replacing observations for patients: " + (replacedObservations - endDownloadObservations) / 1000 + " sec"); totalTimeReplacing += replacedObservations - endDownloadObservations; } else { observationController.saveObservations(allObservations); long savedObservations = System.currentTimeMillis(); Log.d(getClass().getSimpleName(), "In saving observations : " + (savedObservations - endDownloadObservations) / 1000 + " sec\n"); totalTimeSaving += savedObservations - endDownloadObservations; } result[1] += allObservations.size(); result[2] += voidedObservations.size(); } } result[3] = patientUuidsForDownloadedObs.size(); result[0] = SUCCESS; Log.d(getClass().getSimpleName(), "Total Downloading observations : " + totalTimeDownloading / 1000 + " sec\n"); Log.d(getClass().getSimpleName(), "Total Replacing observations : " + totalTimeReplacing / 1000 + " sec\n"); Log.d(getClass().getSimpleName(), "Total Saving observations : " + totalTimeSaving / 1000 + " sec\n"); } catch (ObservationController.DownloadObservationException e) { Log.e(getClass().getSimpleName(), "Exception thrown while downloading observations.", e); result[0] = SyncStatusConstants.DOWNLOAD_ERROR; } catch (ObservationController.ReplaceObservationException e) { Log.e(getClass().getSimpleName(), "Exception thrown while replacing observations.", e); result[0] = SyncStatusConstants.REPLACE_ERROR; } catch (ConceptController.ConceptFetchException e) { Log.e(getClass().getSimpleName(), "Exception thrown while loading concepts.", e); result[0] = SyncStatusConstants.LOAD_ERROR; } catch (ObservationController.DeleteObservationException e) { Log.e(getClass().getSimpleName(), "Exception thrown while deleting observations.", e); result[0] = SyncStatusConstants.DELETE_ERROR; } catch (ObservationController.SaveObservationException e) { Log.e(getClass().getSimpleName(), "Exception thrown while saving observations.", e); result[0] = SyncStatusConstants.SAVE_ERROR; } return result; } MuzimaSyncService(MuzimaApplication muzimaContext); int authenticate(String[] credentials); int authenticate(String[] credentials, boolean isUpdatePasswordRequired); int[] downloadForms(); int[] downloadFormTemplatesAndRelatedMetadata(String[] formIds, boolean replaceExistingTemplates); int[] downloadFormTemplates(String[] formIds, boolean replaceExistingTemplates); int[] downloadLocations(String[] locationIds); int[] downloadProviders(String[] providerIds); int[] downloadConcepts(String[] conceptIds); int[] downloadCohorts(); int[] downloadCohorts(String[] cohortUuids); int[] downloadPatientsForCohortsWithUpdatesAvailable(); int[] downloadRemovedCohortMembershipData(String[] cohortUuids); int[] downloadPatientsForCohorts(String[] cohortUuids); int[] downloadPatients(String[] patientUUIDs); int[] downloadObservationsForPatientsByCohortUUIDs(String[] cohortUuids, boolean replaceExistingObservation); int[] downloadObservationsForPatientsByPatientUUIDs(List<String> patientUuids, boolean replaceExistingObservations); int[] downloadEncountersForPatientsByCohortUUIDs(String[] cohortUuids, boolean replaceExistingEncounters); int[] downloadEncountersForPatientsByPatientUUIDs(List<String> patientUuids, boolean replaceExistingEncounters); int[] uploadAllCompletedForms(); void consolidatePatients(); List<FormData> getArchivedFormData(); int[] checkAndDeleteTemporaryDataForProcessedFormData(List<FormData> archivedFormData); List<String> getUuidsForAllPatientsFromLocalStorage(); List<Patient> updatePatientsNotPartOfCohorts(); int[] downloadNotifications(String receiverUuid); int[] downloadPatientReportHeaders(String patientUuid); int[] downloadAllPatientReportHeadersAndReports(); int[] downloadPatientReportsByUuid(String[] reportUuids); void downloadSetupConfigurations(); int[] downloadSetupConfigurationTemplate(String uuid); int[] downloadAndSaveUpdatedSetupConfigurationTemplate(String uuid); int[] updateSetupConfigurationTemplates(); int[] downloadSetting(String property); int[] downloadNewSettings(); void updateSettingsPreferences(List<MuzimaSetting> muzimaSettings); int[] downloadRelationshipsTypes(); int[] downloadRelationshipsForPatientsByPatientUUIDs(List<String> patientUuids); int[] downloadRelationshipsForPatientsByCohortUUIDs(String[] cohortUuids); String getDefaultLocation(); }
@Test public void shouldDeleteVoidedObservationsWhenDownloadingObservations() throws ObservationController.DeleteObservationException, ObservationController.DownloadObservationException, ReplaceObservationException, ConceptController.ConceptFetchException { List<String> patientUuids = Collections.singletonList("patientUuid"); final Patient patient = new Patient() {{ setUuid("patientUuid"); }}; List<Observation> observations = new ArrayList<>(); Observation anObservation = mock(Observation.class); when(anObservation.isVoided()).thenReturn(false); when(anObservation.getPerson()).thenReturn(patient); observations.add(anObservation); Observation voidedObservation = mock(Observation.class); when(voidedObservation.isVoided()).thenReturn(true); when(voidedObservation.getPerson()).thenReturn(patient); observations.add(voidedObservation); List<Concept> conceptList = new ArrayList<Concept>() {{ add(new Concept() {{ setUuid("concept1"); }}); }}; when(conceptController.getConcepts()).thenReturn(conceptList); when(observationController.downloadObservationsByPatientUuidsAndConceptUuids (eq(patientUuids), eq(Collections.singletonList("concept1")))).thenReturn(observations); muzimaSyncService.downloadObservationsForPatientsByPatientUUIDs(patientUuids,true); verify(observationController).deleteObservations(Collections.singletonList(voidedObservation)); verify(observationController).replaceObservations(Collections.singletonList(anObservation)); }
ObservationParserUtility { public Encounter getEncounterEntity(Date encounterDateTime,String formUuid,String providerId, int locationId, String userSystemId, Patient patient, String formDataUuid) { Encounter encounter = new Encounter(); encounter.setProvider(getDummyProvider(providerId)); encounter.setUuid(getEncounterUUID()); encounter.setLocation(getDummyLocation(locationId)); encounter.setEncounterType(getDummyEncounterType(formUuid)); encounter.setEncounterDatetime(encounterDateTime); encounter.setUserSystemId(userSystemId); encounter.setFormDataUuid(formDataUuid); encounter.setPatient(patient); return encounter; } ObservationParserUtility(MuzimaApplication muzimaApplication, boolean createObservationsForConceptsNotAvailableLocally); Encounter getEncounterEntity(Date encounterDateTime,String formUuid,String providerId, int locationId, String userSystemId, Patient patient, String formDataUuid); Concept getConceptEntity(String rawConceptName, boolean isCoded, boolean createConceptIfNotAvailableLocally); Observation getObservationEntity(Concept concept, String value); List<Concept> getNewConceptList(); static boolean isFormattedAsConcept(String peek); String getObservationUuid(); }
@Test public void shouldCreateEncounterEntityWithAppropriateValues() throws ProviderController.ProviderLoadException, FormController.FormFetchException { Date encounterDateTime = new Date(); final String formUuid = "formUuid"; String providerId = "providerId"; int locationId = 1; String userSystemId = "userSystemId"; final EncounterType encounterType = new EncounterType(){{ setUuid("encounterTypeForObservationsCreatedOnPhone"); }}; Form form = new Form(){{ setUuid(formUuid); setEncounterType(encounterType); }}; List<Provider> providers = new ArrayList<Provider>() {{ add(new Provider() {{ setUuid("provider1"); }}); }}; when(providerController.getAllProviders()).thenReturn(providers); when(formController.getFormByUuid(formUuid)).thenReturn(form); Encounter encounter = observationParserUtility.getEncounterEntity(encounterDateTime, formUuid,providerId, locationId, userSystemId, patient, formDataUuid); assertTrue(encounter.getUuid().startsWith("encounterUuid")); assertThat(encounter.getEncounterType().getUuid(), is(form.getEncounterType().getUuid())); assertThat(encounter.getProvider().getUuid(), is("providerForObservationsCreatedOnPhone")); assertThat(encounter.getEncounterDatetime(), is(encounterDateTime)); }
ObservationParserUtility { public List<Concept> getNewConceptList() { return newConceptList; } ObservationParserUtility(MuzimaApplication muzimaApplication, boolean createObservationsForConceptsNotAvailableLocally); Encounter getEncounterEntity(Date encounterDateTime,String formUuid,String providerId, int locationId, String userSystemId, Patient patient, String formDataUuid); Concept getConceptEntity(String rawConceptName, boolean isCoded, boolean createConceptIfNotAvailableLocally); Observation getObservationEntity(Concept concept, String value); List<Concept> getNewConceptList(); static boolean isFormattedAsConcept(String peek); String getObservationUuid(); }
@Test public void shouldNotCreateNewConceptOrObservationForInvalidConceptName() { observationParserUtility = new ObservationParserUtility(muzimaApplication,true); assertThat(observationParserUtility.getNewConceptList().size(), is(0)); }
ObservationParserUtility { public Observation getObservationEntity(Concept concept, String value) throws ConceptController.ConceptFetchException, ConceptController.ConceptParseException, ObservationController.ParseObservationException{ if (concept == null) { throw new ObservationController.ParseObservationException("Could not create Observation entity." + " Reason: No Concept provided."); } if (StringUtils.isEmpty(value)) { throw new ObservationController.ParseObservationException("Could not create Observation entity for concept '" + concept.getName() + "'. Reason: No Observation value provided."); } Observation observation = new Observation(); observation.setUuid(getObservationUuid()); observation.setValueCoded(defaultValueCodedConcept()); if (concept.isCoded()) { try { Concept valueCoded = getConceptEntity(value,false, true); observation.setValueCoded(valueCoded); } catch (ConceptController.ConceptParseException e) { throw new ConceptController.ConceptParseException("Could not get value for coded concept '" + concept.getName() + "', from provided value '" + value + "'"); } } else if (concept.isNumeric()) { observation.setValueNumeric(getDoubleValue(value)); } else { observation.setValueText(value); } observation.setConcept(concept); return observation; } ObservationParserUtility(MuzimaApplication muzimaApplication, boolean createObservationsForConceptsNotAvailableLocally); Encounter getEncounterEntity(Date encounterDateTime,String formUuid,String providerId, int locationId, String userSystemId, Patient patient, String formDataUuid); Concept getConceptEntity(String rawConceptName, boolean isCoded, boolean createConceptIfNotAvailableLocally); Observation getObservationEntity(Concept concept, String value); List<Concept> getNewConceptList(); static boolean isFormattedAsConcept(String peek); String getObservationUuid(); }
@Test public void shouldCreateNumericObservation() throws ConceptController.ConceptFetchException, ConceptController.ConceptParseException, ObservationController.ParseObservationException{ Concept concept = mock(Concept.class); when(concept.isNumeric()).thenReturn(true); when(concept.isCoded()).thenReturn(false); Observation observation = observationParserUtility.getObservationEntity(concept, "20.0"); assertThat(observation.getValueNumeric(), is(20.0)); assertTrue(observation.getUuid().startsWith("observationFromPhoneUuid")); } @Test public void shouldCreateObsWithStringForNonNumericNonCodedConcept() throws ConceptController.ConceptFetchException, ConceptController.ConceptParseException, ObservationController.ParseObservationException{ observationParserUtility = new ObservationParserUtility(muzimaApplication,true); Concept concept = mock(Concept.class); when(concept.getName()).thenReturn("SomeConcept"); when(concept.isNumeric()).thenReturn(false); when(concept.isCoded()).thenReturn(false); Observation observation = observationParserUtility.getObservationEntity(concept, "someString"); assertThat(observation.getValueAsString(), is("someString")); }
HTMLFormObservationCreator { public void createAndPersistObservations(String jsonResponse,String formDataUuid) { parseJSONResponse(jsonResponse,formDataUuid); try { saveObservationsAndRelatedEntities(); } catch (ConceptController.ConceptSaveException e) { Log.e(getClass().getSimpleName(), "Error while saving concept", e); } catch (EncounterController.SaveEncounterException e) { Log.e(getClass().getSimpleName(), "Error while saving Encounter", e); } catch (ObservationController.SaveObservationException e) { Log.e(getClass().getSimpleName(), "Error while saving Observation", e); } catch (Exception e) { Log.e(getClass().getSimpleName(), "Unexpected Exception occurred", e); } } HTMLFormObservationCreator(MuzimaApplication muzimaApplication, boolean createObservationsForConceptsNotAvailableLocally); void createAndPersistObservations(String jsonResponse,String formDataUuid); void createObservationsAndRelatedEntities(String jsonResponse,String formDataUuid); List<Observation> getObservations(); Encounter getEncounter(); List<Concept> getNewConceptList(); Date getEncounterDateFromFormDate(String jsonResponse); }
@Test public void shouldVerifyAllObservationsAndRelatedEntitiesAreSaved() throws EncounterController.SaveEncounterException, ConceptController.ConceptSaveException, ObservationController.SaveObservationException { htmlFormObservationCreator.createAndPersistObservations(readFile(),formDataUuid); verify(encounterController).saveEncounters(encounterArgumentCaptor.capture()); assertThat(encounterArgumentCaptor.getValue().size(), is(1)); verify(conceptController).saveConcepts(conceptArgumentCaptor.capture()); List<Concept> value = conceptArgumentCaptor.getValue(); assertThat(value.size(), is(33)); verify(observationController).saveObservations(observationArgumentCaptor.capture()); assertThat(observationArgumentCaptor.getValue().size(), is(30)); }
HTMLConceptParser { public List<String> parse(String html) { Set<String> concepts = new HashSet<>(); Document htmlDoc = Jsoup.parse(html); Elements elements = htmlDoc.select("*:not(div)[" + DATA_CONCEPT_TAG + "]"); for (Element element : elements) { concepts.add(getConceptName(element.attr(DATA_CONCEPT_TAG))); } return new ArrayList<>(concepts); } List<String> parse(String html); }
@Test public void shouldReturnListOfConcepts() { String html = readFile(); List<String> concepts = new HTMLConceptParser().parse(html); assertThat(concepts.size(),is(7)); assertThat(concepts,hasItem("BODY PART")); assertThat(concepts,hasItem("PROCEDURES DONE THIS VISIT")); assertThat(concepts,hasItem("ANATOMIC LOCATION DESCRIPTION")); assertThat(concepts,hasItem("CLOCK FACE CERVICAL BIOPSY LOCATION ")); assertThat(concepts,hasItem("PATHOLOGICAL DIAGNOSIS ADDED")); assertThat(concepts,hasItem("FREETEXT GENERAL")); assertThat(concepts,hasItem("RETURN VISIT DATE")); }
ConceptParser { public List<String> parse(String model) { try { if (StringUtils.isEmpty(model)) { return new ArrayList<>(); } parser.setInput(new ByteArrayInputStream(model.getBytes()), null); parser.nextTag(); return readConceptName(parser); } catch (Exception e) { throw new ParseConceptException(e); } } ConceptParser(); ConceptParser(XmlPullParser parser); List<String> parse(String model); }
@Test public void shouldParseConcept() { List<String> conceptNames = utils.parse(getModel("concept.xml")); assertThat(conceptNames, hasItem("PULSE")); } @Test public void shouldParseConceptInObs() { List<String> conceptNames = utils.parse(getModel("concept_in_obs.xml")); assertThat(conceptNames, hasItem("WEIGHT (KG)")); } @Test public void shouldNotAddItToConceptUnLessBothDateAndTimeArePresentInChildren() { List<String> conceptNames = utils.parse(getModel("concepts_in_concept.xml")); assertThat(conceptNames.size(), is(2)); assertThat(conceptNames, hasItem("PROBLEM ADDED")); assertThat(conceptNames, hasItem("PROBLEM RESOLVED")); } @Test public void shouldNotConsiderOptionsAsConcepts() { List<String> conceptNames = utils.parse(getModel("concepts_with_options.xml")); assertThat(conceptNames.size(), is(1)); assertThat(conceptNames, hasItem("MOST RECENT PAPANICOLAOU SMEAR RESULT")); } @Test(expected = ConceptParser.ParseConceptException.class) public void shouldThrowParseConceptExceptionWhenTheModelHasNoEndTag() { utils.parse(getModel("concept_no_end_tag.xml")); } @Test public void shouldParseConceptTM() { List<String> conceptNames = utils.parse(getModel("dispensary_concept_in_obs.xml")); assertThat(conceptNames, hasItem("START TIME")); assertThat(conceptNames, hasItem("END TIME")); }
EncounterController { public List<Encounter> downloadEncountersByPatientUuids(List<String> patientUuids, String activeSetupConfigUuid) throws DownloadEncounterException { try { String paramSignature = StringUtils.getCommaSeparatedStringFromList(patientUuids); Date lastSyncTime = lastSyncTimeService.getLastSyncTimeFor(DOWNLOAD_ENCOUNTERS, paramSignature); List<Encounter> encounters = new ArrayList<>(); List<String> previousPatientsUuid = new ArrayList<>(); if (hasThisCallHappenedBefore(lastSyncTime)) { encounters.addAll(downloadEncounters(patientUuids, lastSyncTime, activeSetupConfigUuid)); } else { encounters.addAll(downloadEncounters(patientUuids, null, activeSetupConfigUuid)); } LastSyncTime newLastSyncTime = new LastSyncTime(DOWNLOAD_ENCOUNTERS, sntpService.getTimePerDeviceTimeZone(), paramSignature); lastSyncTimeService.saveLastSyncTime(newLastSyncTime); return encounters; } catch (IOException e) { throw new DownloadEncounterException(e); } } EncounterController(EncounterService encounterService, LastSyncTimeService lastSyncTimeService, SntpService sntpService); void replaceEncounters(List<Encounter> allEncounters); int getEncountersCountByPatient(String patientUuid); List<Encounter> getEncountersByPatientUuid(String patientUuid); List<Encounter> downloadEncountersByPatientUuids(List<String> patientUuids, String activeSetupConfigUuid); void saveEncounters(List<Encounter> encounters); List<EncounterType> getEncounterTypes(); List<Encounter> getEncountersByEncounterTypeNameAndPatientUuid(String name,String patientUuid); List<Encounter> getEncountersByEncounterTypeUuidAndPatientUuid(String encounterTypeUuid,String patientUuid); List<Encounter> getEncountersByEncounterTypeIdAndPatientUuid(int encounterTypeId,String patientUuid); Encounter getEncounterByUuid(String encounterUuid); void deleteEncounters(List<Encounter> encounters); void saveEncounter(Encounter encounter); }
@Test public void shouldGetLastSyncTimeOfEncounter() throws Exception, EncounterController.DownloadEncounterException { List<String> patientUuids = asList("patientUuid1", "patientUuid2"); Date aDate = mock(Date.class); when(lastSyncTimeService.getLastSyncTimeFor(DOWNLOAD_ENCOUNTERS,"patientUuid1,patientUuid2")).thenReturn(aDate); encounterController.downloadEncountersByPatientUuids(patientUuids, activeSetupConfigUuid); verify(lastSyncTimeService).getLastSyncTimeFor(DOWNLOAD_ENCOUNTERS,"patientUuid1,patientUuid2"); verify(lastSyncTimeService, never()).getFullLastSyncTimeInfoFor(DOWNLOAD_ENCOUNTERS); } @Test public void shouldUseTheLastSyncTimeWhenDownloadingEncounters() throws Exception, EncounterController.DownloadEncounterException { Date lastSyncDate = mock(Date.class); when(lastSyncTimeService.getLastSyncTimeFor(DOWNLOAD_ENCOUNTERS,"patientUuid1,patientUuid2")).thenReturn(lastSyncDate); List<String> patientUuids = asList("patientUuid1", "patientUuid2"); encounterController.downloadEncountersByPatientUuids(patientUuids, activeSetupConfigUuid); verify(encounterService, never()).downloadEncountersByPatientUuids(anyList()); verify(encounterService).downloadEncountersByPatientUuidsAndSyncDateAndSetupConfig(patientUuids, lastSyncDate, activeSetupConfigUuid); } @Test public void shouldSaveTheUpdatedLastSyncTime() throws Exception, EncounterController.DownloadEncounterException { List<String> patientUuids = asList("patientUuid1", "patientUuid2"); Date updatedDate = mock(Date.class); when(sntpService.getTimePerDeviceTimeZone()).thenReturn(updatedDate); Date lastSyncDate = mock(Date.class); when(lastSyncTimeService.getLastSyncTimeFor(DOWNLOAD_ENCOUNTERS,"patientUuid1,patientUuid2")).thenReturn(lastSyncDate); encounterController.downloadEncountersByPatientUuids(patientUuids, activeSetupConfigUuid); ArgumentCaptor<LastSyncTime> argumentCaptor = ArgumentCaptor.forClass(LastSyncTime.class); verify(lastSyncTimeService).saveLastSyncTime(argumentCaptor.capture()); LastSyncTime savedLastSyncTime = argumentCaptor.getValue(); assertThat(savedLastSyncTime.getApiName(), is(DOWNLOAD_ENCOUNTERS)); assertThat(savedLastSyncTime.getLastSyncDate(), is(updatedDate)); assertThat(savedLastSyncTime.getParamSignature(), is("patientUuid1,patientUuid2")); } @Test public void shouldRecognisedAnInitiallyNonInitialisedLastSyncTime() throws EncounterController.DownloadEncounterException, IOException { List<String> newPatients = asList("patientUuid2"); when(lastSyncTimeService.getLastSyncTimeFor(DOWNLOAD_ENCOUNTERS,"patientUuid1,patientUuid2")).thenReturn(null); when(lastSyncTimeService.getFullLastSyncTimeInfoFor(DOWNLOAD_ENCOUNTERS)).thenReturn(null); List<String> mPatientUuids = asList("patientUuid1", "patientUuid2"); encounterController.downloadEncountersByPatientUuids(mPatientUuids, activeSetupConfigUuid); verify(encounterService, never()).downloadEncountersByPatientUuidsAndSyncDate(newPatients, null); }
PatientController { public List<Patient> getAllPatients() throws PatientLoadException { try { return patientService.getAllPatients(); } catch (IOException e) { throw new PatientLoadException(e); } } PatientController(PatientService patientService, CohortService cohortService, FormService formService,PatientTagService patientTagService); void replacePatients(List<Patient> patients); List<Patient> getPatients(String cohortId); List<Patient> getPatients(String cohortId,int page, int pageSize); List<Patient> getAllPatients(); List<Patient> getPatients(int page, int pageSize); int countAllPatients(); int countPatients(String cohortId); Patient getPatientByUuid(String uuid); List<Patient> searchPatientLocally(String term, String cohortUuid); List<Patient> searchPatientLocally(String term, int page, int pageSize); List<Patient> getPatientsForCohorts(String[] cohortUuids); List<Patient> searchPatientOnServer(String name); List<Patient> getAllPatientsCreatedLocallyAndNotSynced(); Patient consolidateTemporaryPatient(Patient patient); void savePatient(Patient patient); void updatePatient(Patient patient); void savePatientTags(PatientTag tag); void savePatients(List<Patient> patients); void deletePatient(Patient localPatient); void deletePatient(List<Patient> localPatients); List<Patient> getPatientsNotInCohorts(); Patient downloadPatientByUUID(String uuid); void deleteAllPatients(); PatientIdentifierType getPatientIdentifierTypeByUuid(String uuid); List<PatientIdentifierType> getPatientIdentifierTypeByName(String name); PersonAttributeType getPersonAttributeTypeByUuid(String uuid); List<PersonAttributeType> getPersonAttributeTypeByName(String name); int getTagColor(String uuid); List<PatientTag> getSelectedTags(); void setSelectedTags(List<PatientTag> selectedTags); List<PatientTag> getAllTags(); List<String> getSelectedTagUuids(); List<Patient> filterPatientByTags(List<Patient> patients, List<String> tagsUuid); void deletePatientByCohortMembership(List<CohortMember> cohortMembers); void deletePatientsPendingDeletion(); int getFormDataCount(String patientUuid); }
@Test public void getAllPatients_shouldReturnAllAvailablePatients() throws IOException, PatientController.PatientLoadException { List<Patient> patients = new ArrayList<>(); when(patientService.getAllPatients()).thenReturn(patients); assertThat(patientController.getAllPatients(), is(patients)); } @Test(expected = PatientController.PatientLoadException.class) public void getAllForms_shouldThrowFormFetchExceptionIfExceptionThrownByFormService() throws IOException, PatientController.PatientLoadException { doThrow(new IOException()).when(patientService).getAllPatients(); patientController.getAllPatients(); }
PatientController { public int countAllPatients() throws PatientLoadException { try { return patientService.countAllPatients(); } catch (IOException e) { throw new PatientLoadException(e); } } PatientController(PatientService patientService, CohortService cohortService, FormService formService,PatientTagService patientTagService); void replacePatients(List<Patient> patients); List<Patient> getPatients(String cohortId); List<Patient> getPatients(String cohortId,int page, int pageSize); List<Patient> getAllPatients(); List<Patient> getPatients(int page, int pageSize); int countAllPatients(); int countPatients(String cohortId); Patient getPatientByUuid(String uuid); List<Patient> searchPatientLocally(String term, String cohortUuid); List<Patient> searchPatientLocally(String term, int page, int pageSize); List<Patient> getPatientsForCohorts(String[] cohortUuids); List<Patient> searchPatientOnServer(String name); List<Patient> getAllPatientsCreatedLocallyAndNotSynced(); Patient consolidateTemporaryPatient(Patient patient); void savePatient(Patient patient); void updatePatient(Patient patient); void savePatientTags(PatientTag tag); void savePatients(List<Patient> patients); void deletePatient(Patient localPatient); void deletePatient(List<Patient> localPatients); List<Patient> getPatientsNotInCohorts(); Patient downloadPatientByUUID(String uuid); void deleteAllPatients(); PatientIdentifierType getPatientIdentifierTypeByUuid(String uuid); List<PatientIdentifierType> getPatientIdentifierTypeByName(String name); PersonAttributeType getPersonAttributeTypeByUuid(String uuid); List<PersonAttributeType> getPersonAttributeTypeByName(String name); int getTagColor(String uuid); List<PatientTag> getSelectedTags(); void setSelectedTags(List<PatientTag> selectedTags); List<PatientTag> getAllTags(); List<String> getSelectedTagUuids(); List<Patient> filterPatientByTags(List<Patient> patients, List<String> tagsUuid); void deletePatientByCohortMembership(List<CohortMember> cohortMembers); void deletePatientsPendingDeletion(); int getFormDataCount(String patientUuid); }
@Test public void getTotalPatientsCount_shouldReturnPatientsCount() throws IOException, PatientController.PatientLoadException { when(patientService.countAllPatients()).thenReturn(2); assertThat(patientController.countAllPatients(), is(2)); }
PatientController { public void replacePatients(List<Patient> patients) throws PatientSaveException { try { patientService.updatePatients(patients); } catch (IOException e) { throw new PatientSaveException(e); } } PatientController(PatientService patientService, CohortService cohortService, FormService formService,PatientTagService patientTagService); void replacePatients(List<Patient> patients); List<Patient> getPatients(String cohortId); List<Patient> getPatients(String cohortId,int page, int pageSize); List<Patient> getAllPatients(); List<Patient> getPatients(int page, int pageSize); int countAllPatients(); int countPatients(String cohortId); Patient getPatientByUuid(String uuid); List<Patient> searchPatientLocally(String term, String cohortUuid); List<Patient> searchPatientLocally(String term, int page, int pageSize); List<Patient> getPatientsForCohorts(String[] cohortUuids); List<Patient> searchPatientOnServer(String name); List<Patient> getAllPatientsCreatedLocallyAndNotSynced(); Patient consolidateTemporaryPatient(Patient patient); void savePatient(Patient patient); void updatePatient(Patient patient); void savePatientTags(PatientTag tag); void savePatients(List<Patient> patients); void deletePatient(Patient localPatient); void deletePatient(List<Patient> localPatients); List<Patient> getPatientsNotInCohorts(); Patient downloadPatientByUUID(String uuid); void deleteAllPatients(); PatientIdentifierType getPatientIdentifierTypeByUuid(String uuid); List<PatientIdentifierType> getPatientIdentifierTypeByName(String name); PersonAttributeType getPersonAttributeTypeByUuid(String uuid); List<PersonAttributeType> getPersonAttributeTypeByName(String name); int getTagColor(String uuid); List<PatientTag> getSelectedTags(); void setSelectedTags(List<PatientTag> selectedTags); List<PatientTag> getAllTags(); List<String> getSelectedTagUuids(); List<Patient> filterPatientByTags(List<Patient> patients, List<String> tagsUuid); void deletePatientByCohortMembership(List<CohortMember> cohortMembers); void deletePatientsPendingDeletion(); int getFormDataCount(String patientUuid); }
@Test public void replacePatients_shouldReplaceAllExistingPatientsAndAddNewPatients() throws IOException, PatientController.PatientSaveException { List<Patient> patients = buildPatients(); patientController.replacePatients(patients); verify(patientService).updatePatients(patients); verifyNoMoreInteractions(patientService); } @Test(expected = PatientController.PatientSaveException.class) public void replacePatients_shouldThrowPatientReplaceExceptionIfExceptionThrownByService() throws IOException, PatientController.PatientSaveException { List<Patient> patients = buildPatients(); doThrow(new IOException()).when(patientService).updatePatients(patients); patientController.replacePatients(patients); }
PatientController { public List<Patient> getPatients(String cohortId) throws PatientLoadException { try { List<CohortMember> cohortMembers = cohortService.getCohortMembers(cohortId); return patientService.getPatientsFromCohortMembers(cohortMembers); } catch (IOException e) { throw new PatientLoadException(e); } } PatientController(PatientService patientService, CohortService cohortService, FormService formService,PatientTagService patientTagService); void replacePatients(List<Patient> patients); List<Patient> getPatients(String cohortId); List<Patient> getPatients(String cohortId,int page, int pageSize); List<Patient> getAllPatients(); List<Patient> getPatients(int page, int pageSize); int countAllPatients(); int countPatients(String cohortId); Patient getPatientByUuid(String uuid); List<Patient> searchPatientLocally(String term, String cohortUuid); List<Patient> searchPatientLocally(String term, int page, int pageSize); List<Patient> getPatientsForCohorts(String[] cohortUuids); List<Patient> searchPatientOnServer(String name); List<Patient> getAllPatientsCreatedLocallyAndNotSynced(); Patient consolidateTemporaryPatient(Patient patient); void savePatient(Patient patient); void updatePatient(Patient patient); void savePatientTags(PatientTag tag); void savePatients(List<Patient> patients); void deletePatient(Patient localPatient); void deletePatient(List<Patient> localPatients); List<Patient> getPatientsNotInCohorts(); Patient downloadPatientByUUID(String uuid); void deleteAllPatients(); PatientIdentifierType getPatientIdentifierTypeByUuid(String uuid); List<PatientIdentifierType> getPatientIdentifierTypeByName(String name); PersonAttributeType getPersonAttributeTypeByUuid(String uuid); List<PersonAttributeType> getPersonAttributeTypeByName(String name); int getTagColor(String uuid); List<PatientTag> getSelectedTags(); void setSelectedTags(List<PatientTag> selectedTags); List<PatientTag> getAllTags(); List<String> getSelectedTagUuids(); List<Patient> filterPatientByTags(List<Patient> patients, List<String> tagsUuid); void deletePatientByCohortMembership(List<CohortMember> cohortMembers); void deletePatientsPendingDeletion(); int getFormDataCount(String patientUuid); }
@Test public void getPatientsInCohort_shouldReturnThePatientsInTheCohort() throws IOException, PatientController.PatientLoadException { String cohortId = "cohortId"; List<CohortMember> members = buildCohortMembers(cohortId); when(cohortService.getCohortMembers(cohortId)).thenReturn(members); Patient patient = new Patient(); patient.setUuid(members.get(0).getPatientUuid()); when(patientService.getPatientsFromCohortMembers(members)).thenReturn(Collections.singletonList(patient)); List<Patient> patients = patientController.getPatients(cohortId); assertThat(patients.size(), is(1)); }
ConceptsByPatient extends ConceptAction { @Override Concepts get() throws ObservationController.LoadObservationException { return controller.getConceptWithObservations(patientUuid); } ConceptsByPatient(ConceptController conceptController, ObservationController controller, String patientUuid); @Override String toString(); }
@Test public void shouldGetObservationsByPatientUUID() throws ObservationController.LoadObservationException { ObservationController controller = mock(ObservationController.class); ConceptController conceptController = mock(ConceptController.class); ConceptsByPatient byPatient = new ConceptsByPatient(conceptController,controller, "uuid"); byPatient.get(); verify(controller).getConceptWithObservations("uuid"); }
PatientController { public List<Patient> searchPatientLocally(String term, String cohortUuid) throws PatientLoadException { try { return StringUtils.isEmpty(cohortUuid) ? patientService.searchPatients(term) : patientService.searchPatients(term, cohortUuid); } catch (IOException | ParseException e) { throw new PatientLoadException(e); } } PatientController(PatientService patientService, CohortService cohortService, FormService formService,PatientTagService patientTagService); void replacePatients(List<Patient> patients); List<Patient> getPatients(String cohortId); List<Patient> getPatients(String cohortId,int page, int pageSize); List<Patient> getAllPatients(); List<Patient> getPatients(int page, int pageSize); int countAllPatients(); int countPatients(String cohortId); Patient getPatientByUuid(String uuid); List<Patient> searchPatientLocally(String term, String cohortUuid); List<Patient> searchPatientLocally(String term, int page, int pageSize); List<Patient> getPatientsForCohorts(String[] cohortUuids); List<Patient> searchPatientOnServer(String name); List<Patient> getAllPatientsCreatedLocallyAndNotSynced(); Patient consolidateTemporaryPatient(Patient patient); void savePatient(Patient patient); void updatePatient(Patient patient); void savePatientTags(PatientTag tag); void savePatients(List<Patient> patients); void deletePatient(Patient localPatient); void deletePatient(List<Patient> localPatients); List<Patient> getPatientsNotInCohorts(); Patient downloadPatientByUUID(String uuid); void deleteAllPatients(); PatientIdentifierType getPatientIdentifierTypeByUuid(String uuid); List<PatientIdentifierType> getPatientIdentifierTypeByName(String name); PersonAttributeType getPersonAttributeTypeByUuid(String uuid); List<PersonAttributeType> getPersonAttributeTypeByName(String name); int getTagColor(String uuid); List<PatientTag> getSelectedTags(); void setSelectedTags(List<PatientTag> selectedTags); List<PatientTag> getAllTags(); List<String> getSelectedTagUuids(); List<Patient> filterPatientByTags(List<Patient> patients, List<String> tagsUuid); void deletePatientByCohortMembership(List<CohortMember> cohortMembers); void deletePatientsPendingDeletion(); int getFormDataCount(String patientUuid); }
@Test public void shouldSearchWithOutCohortUUIDIsNull() throws IOException, ParseException, PatientController.PatientLoadException { String searchString = "searchString"; List<Patient> patients = new ArrayList<>(); when(patientService.searchPatients(searchString)).thenReturn(patients); assertThat(patientController.searchPatientLocally(searchString, null), is(patients)); verify(patientService).searchPatients(searchString); } @Test public void shouldSearchWithOutCohortUUIDIsEmpty() throws IOException, ParseException, PatientController.PatientLoadException { String searchString = "searchString"; List<Patient> patients = new ArrayList<>(); when(patientService.searchPatients(searchString)).thenReturn(patients); assertThat(patientController.searchPatientLocally(searchString, StringUtils.EMPTY), is(patients)); verify(patientService).searchPatients(searchString); } @Test public void shouldCallSearchPatientWithCohortIDIfPresent() throws Exception, PatientController.PatientLoadException { String searchString = "searchString"; String cohortUUID = "cohortUUID"; List<Patient> patients = new ArrayList<>(); when(patientService.searchPatients(searchString, cohortUUID)).thenReturn(patients); assertThat(patientController.searchPatientLocally(searchString, cohortUUID), is(patients)); verify(patientService).searchPatients(searchString, cohortUUID); }
PatientController { public Patient getPatientByUuid(String uuid) throws PatientLoadException { try { return patientService.getPatientByUuid(uuid); } catch (IOException e) { throw new PatientLoadException(e); } } PatientController(PatientService patientService, CohortService cohortService, FormService formService,PatientTagService patientTagService); void replacePatients(List<Patient> patients); List<Patient> getPatients(String cohortId); List<Patient> getPatients(String cohortId,int page, int pageSize); List<Patient> getAllPatients(); List<Patient> getPatients(int page, int pageSize); int countAllPatients(); int countPatients(String cohortId); Patient getPatientByUuid(String uuid); List<Patient> searchPatientLocally(String term, String cohortUuid); List<Patient> searchPatientLocally(String term, int page, int pageSize); List<Patient> getPatientsForCohorts(String[] cohortUuids); List<Patient> searchPatientOnServer(String name); List<Patient> getAllPatientsCreatedLocallyAndNotSynced(); Patient consolidateTemporaryPatient(Patient patient); void savePatient(Patient patient); void updatePatient(Patient patient); void savePatientTags(PatientTag tag); void savePatients(List<Patient> patients); void deletePatient(Patient localPatient); void deletePatient(List<Patient> localPatients); List<Patient> getPatientsNotInCohorts(); Patient downloadPatientByUUID(String uuid); void deleteAllPatients(); PatientIdentifierType getPatientIdentifierTypeByUuid(String uuid); List<PatientIdentifierType> getPatientIdentifierTypeByName(String name); PersonAttributeType getPersonAttributeTypeByUuid(String uuid); List<PersonAttributeType> getPersonAttributeTypeByName(String name); int getTagColor(String uuid); List<PatientTag> getSelectedTags(); void setSelectedTags(List<PatientTag> selectedTags); List<PatientTag> getAllTags(); List<String> getSelectedTagUuids(); List<Patient> filterPatientByTags(List<Patient> patients, List<String> tagsUuid); void deletePatientByCohortMembership(List<CohortMember> cohortMembers); void deletePatientsPendingDeletion(); int getFormDataCount(String patientUuid); }
@Test public void getPatientByUuid_shouldReturnPatientForId() throws Exception, PatientController.PatientLoadException { Patient patient = new Patient(); String uuid = "uuid"; when(patientService.getPatientByUuid(uuid)).thenReturn(patient); assertThat(patientController.getPatientByUuid(uuid), is(patient)); }
PatientController { public List<Patient> searchPatientOnServer(String name) { try { return patientService.downloadPatientsByName(name); } catch (IOException e) { Log.e(getClass().getSimpleName(), "Error while searching for patients in the server", e); } return new ArrayList<>(); } PatientController(PatientService patientService, CohortService cohortService, FormService formService,PatientTagService patientTagService); void replacePatients(List<Patient> patients); List<Patient> getPatients(String cohortId); List<Patient> getPatients(String cohortId,int page, int pageSize); List<Patient> getAllPatients(); List<Patient> getPatients(int page, int pageSize); int countAllPatients(); int countPatients(String cohortId); Patient getPatientByUuid(String uuid); List<Patient> searchPatientLocally(String term, String cohortUuid); List<Patient> searchPatientLocally(String term, int page, int pageSize); List<Patient> getPatientsForCohorts(String[] cohortUuids); List<Patient> searchPatientOnServer(String name); List<Patient> getAllPatientsCreatedLocallyAndNotSynced(); Patient consolidateTemporaryPatient(Patient patient); void savePatient(Patient patient); void updatePatient(Patient patient); void savePatientTags(PatientTag tag); void savePatients(List<Patient> patients); void deletePatient(Patient localPatient); void deletePatient(List<Patient> localPatients); List<Patient> getPatientsNotInCohorts(); Patient downloadPatientByUUID(String uuid); void deleteAllPatients(); PatientIdentifierType getPatientIdentifierTypeByUuid(String uuid); List<PatientIdentifierType> getPatientIdentifierTypeByName(String name); PersonAttributeType getPersonAttributeTypeByUuid(String uuid); List<PersonAttributeType> getPersonAttributeTypeByName(String name); int getTagColor(String uuid); List<PatientTag> getSelectedTags(); void setSelectedTags(List<PatientTag> selectedTags); List<PatientTag> getAllTags(); List<String> getSelectedTagUuids(); List<Patient> filterPatientByTags(List<Patient> patients, List<String> tagsUuid); void deletePatientByCohortMembership(List<CohortMember> cohortMembers); void deletePatientsPendingDeletion(); int getFormDataCount(String patientUuid); }
@Test public void shouldSearchOnServerForPatientByNames() throws Exception { String name = "name"; List<Patient> patients = new ArrayList<>(); when(patientService.downloadPatientsByName(name)).thenReturn(patients); assertThat(patientController.searchPatientOnServer(name), is(patients)); verify(patientService).downloadPatientsByName(name); } @Test public void shouldReturnEmptyListIsExceptionThrown() throws Exception { String searchString = "name"; doThrow(new IOException()).when(patientService).downloadPatientsByName(searchString); assertThat(patientController.searchPatientOnServer(searchString).size(), is(0)); }
PatientController { public Patient consolidateTemporaryPatient(Patient patient) { try { return patientService.consolidateTemporaryPatient(patient); } catch (IOException e) { Log.e(getClass().getSimpleName(), "Error while consolidating the temporary patient.", e); } return null; } PatientController(PatientService patientService, CohortService cohortService, FormService formService,PatientTagService patientTagService); void replacePatients(List<Patient> patients); List<Patient> getPatients(String cohortId); List<Patient> getPatients(String cohortId,int page, int pageSize); List<Patient> getAllPatients(); List<Patient> getPatients(int page, int pageSize); int countAllPatients(); int countPatients(String cohortId); Patient getPatientByUuid(String uuid); List<Patient> searchPatientLocally(String term, String cohortUuid); List<Patient> searchPatientLocally(String term, int page, int pageSize); List<Patient> getPatientsForCohorts(String[] cohortUuids); List<Patient> searchPatientOnServer(String name); List<Patient> getAllPatientsCreatedLocallyAndNotSynced(); Patient consolidateTemporaryPatient(Patient patient); void savePatient(Patient patient); void updatePatient(Patient patient); void savePatientTags(PatientTag tag); void savePatients(List<Patient> patients); void deletePatient(Patient localPatient); void deletePatient(List<Patient> localPatients); List<Patient> getPatientsNotInCohorts(); Patient downloadPatientByUUID(String uuid); void deleteAllPatients(); PatientIdentifierType getPatientIdentifierTypeByUuid(String uuid); List<PatientIdentifierType> getPatientIdentifierTypeByName(String name); PersonAttributeType getPersonAttributeTypeByUuid(String uuid); List<PersonAttributeType> getPersonAttributeTypeByName(String name); int getTagColor(String uuid); List<PatientTag> getSelectedTags(); void setSelectedTags(List<PatientTag> selectedTags); List<PatientTag> getAllTags(); List<String> getSelectedTagUuids(); List<Patient> filterPatientByTags(List<Patient> patients, List<String> tagsUuid); void deletePatientByCohortMembership(List<CohortMember> cohortMembers); void deletePatientsPendingDeletion(); int getFormDataCount(String patientUuid); }
@Test public void shouldConsolidatePatients() throws Exception { Patient tempPatient = mock(Patient.class); Patient patient = mock(Patient.class); when(patientService.consolidateTemporaryPatient(tempPatient)).thenReturn(patient); assertThat(patient, is(patientController.consolidateTemporaryPatient(tempPatient))); }
FormController { public int getTotalFormCount() throws FormFetchException { try { return formService.countAllForms(); } catch (IOException e) { throw new FormFetchException(e); } } FormController(MuzimaApplication muzimaApplication); int getTotalFormCount(); Form getFormByUuid(String formId); FormTemplate getFormTemplateByUuid(String formId); AvailableForms getAvailableFormByTags(List<String> tagsUuid); List<Form> getAllAvailableForms(); AvailableForms getAvailableFormByTags(List<String> tagsUuid, boolean alwaysIncludeRegistrationForms); List<Tag> getAllTags(); List<Tag> getAllTagsExcludingRegistrationTag(); DownloadedForms getAllDownloadedForms(); List<Form> downloadAllForms(); List<FormTemplate> downloadFormTemplates(String[] formUuids); FormTemplate downloadFormTemplateByUuid(String uuid); void saveAllForms(List<Form> forms); void updateAllForms(List<Form> forms); void deleteAllForms(); void deleteAllFormTemplates(); void deleteForms(List<Form> forms); void deleteFormTemplatesByUUID(List<String> formTemplateUUIDs); void replaceFormTemplates(List<FormTemplate> formTemplates); void saveFormTemplates(List<FormTemplate> formTemplates); boolean isFormDownloaded(Form form); int getTagColor(String uuid); void resetTagColors(); List<Tag> getSelectedTags(); void setSelectedTags(List<Tag> selectedTags); FormData getFormDataByUuid(String formDataUuid); List<FormData> getFormDataByUuids(List<String> formDataUuids); CompleteFormWithPatientData getCompleteFormDataByUuid(String formDataUuid); void saveFormData(FormData formData); List<FormData> getAllFormData(String status); List<FormData> getAllFormDataByPatientUuid(String patientUuid, String status); IncompleteFormsWithPatientData getAllIncompleteFormsWithPatientData(); CompleteFormsWithPatientData getAllCompleteFormsWithPatientData(Context context); IncompleteForms getAllIncompleteFormsForPatientUuid(String patientUuid); CompleteForms getAllCompleteFormsForPatientUuid(String patientUuid); int countAllIncompleteForms(); int countAllCompleteForms(); int getCompleteFormsCountForPatient(String patientId); int getIncompleteFormsCountForPatient(String patientId); AvailableForms getDownloadedRegistrationForms(); Patient createNewPatient(MuzimaApplication muzimaApplication, FormData formData); boolean uploadAllCompletedForms(); AvailableForms getRecommendedForms(); AvailableForms getProviderReports(); int getRecommendedFormsCount(); void deleteCompleteAndIncompleteEncounterFormData(List<String> formDataUuids); List<FormData> getNonUploadedFormData(String templateUUID); void markFormDataAsIncompleteAndDeleteRelatedEncountersAndObs(final FormData formData); void deleteFormDataAndRelatedEncountersAndObs(List<FormData> formData); List<FormData> getArchivedFormData(); FormDataStatus downloadFormDataStatus(FormData formData); boolean isFormAlreadyExist(String jsonPayload, FormData formData); boolean isRegistrationFormDataWithEncounterForm(String formUuid); boolean isRegistrationFormData(FormData formData); boolean isGenericRegistrationHTMLFormData(FormData formData); boolean isEncounterFormData(FormData formData); Map<String, List<FormData>> getFormDataGroupedByPatient(List<String> uuids); Map<String, List<FormData>> deleteFormDataWithNoRelatedCompleteRegistrationFormDataInGroup( Map<String, List<FormData>> groupedFormData); Map<String, List<FormData>> deleteRegistrationFormDataWithAllRelatedEncountersInGroup(Map<String, List<FormData>> groupedFormData); AvailableForms getAvailableFormByTagsSortedByConfigOrder(List<String> tagsUuid, boolean alwaysIncludeRegistrationForms); AvailableForms getDownloadedRelationshipForms(); AvailableForm getAvailableFormByFormUuid(String uuid); ArrayList<String> getFormListAsPerConfigOrder(); AvailableForms getAvailableFormsPerConfigOrder(ArrayList<String> formUuids, List<Form> filteredForms); }
@Test public void getTotalFormCount_shouldReturnTotalAvailableForms() throws IOException, FormController.FormFetchException { when(formService.countAllForms()).thenReturn(2); assertThat(formController.getTotalFormCount(), is(2)); }
FormController { public AvailableForms getAvailableFormByTags(List<String> tagsUuid) throws FormFetchException { return getAvailableFormByTags(tagsUuid, false); } FormController(MuzimaApplication muzimaApplication); int getTotalFormCount(); Form getFormByUuid(String formId); FormTemplate getFormTemplateByUuid(String formId); AvailableForms getAvailableFormByTags(List<String> tagsUuid); List<Form> getAllAvailableForms(); AvailableForms getAvailableFormByTags(List<String> tagsUuid, boolean alwaysIncludeRegistrationForms); List<Tag> getAllTags(); List<Tag> getAllTagsExcludingRegistrationTag(); DownloadedForms getAllDownloadedForms(); List<Form> downloadAllForms(); List<FormTemplate> downloadFormTemplates(String[] formUuids); FormTemplate downloadFormTemplateByUuid(String uuid); void saveAllForms(List<Form> forms); void updateAllForms(List<Form> forms); void deleteAllForms(); void deleteAllFormTemplates(); void deleteForms(List<Form> forms); void deleteFormTemplatesByUUID(List<String> formTemplateUUIDs); void replaceFormTemplates(List<FormTemplate> formTemplates); void saveFormTemplates(List<FormTemplate> formTemplates); boolean isFormDownloaded(Form form); int getTagColor(String uuid); void resetTagColors(); List<Tag> getSelectedTags(); void setSelectedTags(List<Tag> selectedTags); FormData getFormDataByUuid(String formDataUuid); List<FormData> getFormDataByUuids(List<String> formDataUuids); CompleteFormWithPatientData getCompleteFormDataByUuid(String formDataUuid); void saveFormData(FormData formData); List<FormData> getAllFormData(String status); List<FormData> getAllFormDataByPatientUuid(String patientUuid, String status); IncompleteFormsWithPatientData getAllIncompleteFormsWithPatientData(); CompleteFormsWithPatientData getAllCompleteFormsWithPatientData(Context context); IncompleteForms getAllIncompleteFormsForPatientUuid(String patientUuid); CompleteForms getAllCompleteFormsForPatientUuid(String patientUuid); int countAllIncompleteForms(); int countAllCompleteForms(); int getCompleteFormsCountForPatient(String patientId); int getIncompleteFormsCountForPatient(String patientId); AvailableForms getDownloadedRegistrationForms(); Patient createNewPatient(MuzimaApplication muzimaApplication, FormData formData); boolean uploadAllCompletedForms(); AvailableForms getRecommendedForms(); AvailableForms getProviderReports(); int getRecommendedFormsCount(); void deleteCompleteAndIncompleteEncounterFormData(List<String> formDataUuids); List<FormData> getNonUploadedFormData(String templateUUID); void markFormDataAsIncompleteAndDeleteRelatedEncountersAndObs(final FormData formData); void deleteFormDataAndRelatedEncountersAndObs(List<FormData> formData); List<FormData> getArchivedFormData(); FormDataStatus downloadFormDataStatus(FormData formData); boolean isFormAlreadyExist(String jsonPayload, FormData formData); boolean isRegistrationFormDataWithEncounterForm(String formUuid); boolean isRegistrationFormData(FormData formData); boolean isGenericRegistrationHTMLFormData(FormData formData); boolean isEncounterFormData(FormData formData); Map<String, List<FormData>> getFormDataGroupedByPatient(List<String> uuids); Map<String, List<FormData>> deleteFormDataWithNoRelatedCompleteRegistrationFormDataInGroup( Map<String, List<FormData>> groupedFormData); Map<String, List<FormData>> deleteRegistrationFormDataWithAllRelatedEncountersInGroup(Map<String, List<FormData>> groupedFormData); AvailableForms getAvailableFormByTagsSortedByConfigOrder(List<String> tagsUuid, boolean alwaysIncludeRegistrationForms); AvailableForms getDownloadedRelationshipForms(); AvailableForm getAvailableFormByFormUuid(String uuid); ArrayList<String> getFormListAsPerConfigOrder(); AvailableForms getAvailableFormsPerConfigOrder(ArrayList<String> formUuids, List<Form> filteredForms); }
@Test public void getAllFormByTags_shouldFetchAllFormsWithGivenTags() throws IOException, FormController.FormFetchException { List<Form> forms = buildForms(); when(formService.getAllForms()).thenReturn(forms); when(formService.isFormTemplateDownloaded(forms.get(0).getUuid())).thenReturn(false); when(formService.isFormTemplateDownloaded(forms.get(1).getUuid())).thenReturn(true); when(formService.isFormTemplateDownloaded(forms.get(2).getUuid())).thenReturn(false); AvailableForms availableForms = formController.getAvailableFormByTags(Collections.singletonList("tag2")); assertThat(availableForms.size(), is(2)); assertTrue(containsFormWithUuid(availableForms, forms.get(0).getUuid())); assertTrue(containsFormWithUuid(availableForms, forms.get(2).getUuid())); availableForms = formController.getAvailableFormByTags(Collections.singletonList("tag1")); assertThat(availableForms.size(), is(2)); assertTrue(containsFormWithUuid(availableForms, forms.get(0).getUuid())); assertTrue(containsFormWithUuid(availableForms, forms.get(1).getUuid())); } @Test public void getAllFormByTags_shouldAssignDownloadStatusToForms() throws IOException, FormController.FormFetchException { List<Form> forms = buildForms(); when(formService.getAllForms()).thenReturn(forms); when(formService.isFormTemplateDownloaded(forms.get(0).getUuid())).thenReturn(false); when(formService.isFormTemplateDownloaded(forms.get(1).getUuid())).thenReturn(true); when(formService.isFormTemplateDownloaded(forms.get(2).getUuid())).thenReturn(false); AvailableForms availableForms = formController.getAvailableFormByTags(Collections.singletonList("tag2")); assertThat(getAvailableFormWithUuid(availableForms, forms.get(0).getUuid()).isDownloaded(), is(false)); assertThat(getAvailableFormWithUuid(availableForms, forms.get(2).getUuid()).isDownloaded(), is(false)); availableForms = formController.getAvailableFormByTags(Collections.singletonList("tag1")); assertThat(getAvailableFormWithUuid(availableForms, forms.get(0).getUuid()).isDownloaded(), is(false)); assertThat(getAvailableFormWithUuid(availableForms, forms.get(1).getUuid()).isDownloaded(), is(true)); } @Test public void getAllFormByTags_shouldFetchAllFormsIfNoTagsAreProvided() throws IOException, FormController.FormFetchException { List<Form> forms = buildForms(); when(formService.getAllForms()).thenReturn(forms); AvailableForms availableFormByTags = formController.getAvailableFormByTags(new ArrayList<String>()); assertThat(availableFormByTags.size(), is(5)); }
ConceptsBySearch extends ConceptAction { @Override Concepts get() throws ObservationController.LoadObservationException { return controller.searchObservationsGroupedByConcepts(term, patientUuid); } ConceptsBySearch(ConceptController conceptController, ObservationController controller, String patientUuid, String term); @Override String toString(); }
@Test public void shouldSearchObservationsByUuidAndTerm() throws ObservationController.LoadObservationException { ObservationController controller = mock(ObservationController.class); ConceptController conceptController = mock(ConceptController.class); ConceptsBySearch conceptsBySearch = new ConceptsBySearch(conceptController,controller, "uuid", "term"); conceptsBySearch.get(); verify(controller).searchObservationsGroupedByConcepts("term", "uuid"); }
FormController { public List<Form> downloadAllForms() throws FormFetchException { try { Date lastSyncDate = lastSyncTimeService.getLastSyncTimeFor(APIName.DOWNLOAD_FORMS); List<Form> forms = formService.downloadFormsByName(StringUtils.EMPTY, lastSyncDate); LastSyncTime lastSyncTime = new LastSyncTime(APIName.DOWNLOAD_FORMS, sntpService.getTimePerDeviceTimeZone()); lastSyncTimeService.saveLastSyncTime(lastSyncTime); return forms; } catch (IOException e) { throw new FormFetchException(e); } } FormController(MuzimaApplication muzimaApplication); int getTotalFormCount(); Form getFormByUuid(String formId); FormTemplate getFormTemplateByUuid(String formId); AvailableForms getAvailableFormByTags(List<String> tagsUuid); List<Form> getAllAvailableForms(); AvailableForms getAvailableFormByTags(List<String> tagsUuid, boolean alwaysIncludeRegistrationForms); List<Tag> getAllTags(); List<Tag> getAllTagsExcludingRegistrationTag(); DownloadedForms getAllDownloadedForms(); List<Form> downloadAllForms(); List<FormTemplate> downloadFormTemplates(String[] formUuids); FormTemplate downloadFormTemplateByUuid(String uuid); void saveAllForms(List<Form> forms); void updateAllForms(List<Form> forms); void deleteAllForms(); void deleteAllFormTemplates(); void deleteForms(List<Form> forms); void deleteFormTemplatesByUUID(List<String> formTemplateUUIDs); void replaceFormTemplates(List<FormTemplate> formTemplates); void saveFormTemplates(List<FormTemplate> formTemplates); boolean isFormDownloaded(Form form); int getTagColor(String uuid); void resetTagColors(); List<Tag> getSelectedTags(); void setSelectedTags(List<Tag> selectedTags); FormData getFormDataByUuid(String formDataUuid); List<FormData> getFormDataByUuids(List<String> formDataUuids); CompleteFormWithPatientData getCompleteFormDataByUuid(String formDataUuid); void saveFormData(FormData formData); List<FormData> getAllFormData(String status); List<FormData> getAllFormDataByPatientUuid(String patientUuid, String status); IncompleteFormsWithPatientData getAllIncompleteFormsWithPatientData(); CompleteFormsWithPatientData getAllCompleteFormsWithPatientData(Context context); IncompleteForms getAllIncompleteFormsForPatientUuid(String patientUuid); CompleteForms getAllCompleteFormsForPatientUuid(String patientUuid); int countAllIncompleteForms(); int countAllCompleteForms(); int getCompleteFormsCountForPatient(String patientId); int getIncompleteFormsCountForPatient(String patientId); AvailableForms getDownloadedRegistrationForms(); Patient createNewPatient(MuzimaApplication muzimaApplication, FormData formData); boolean uploadAllCompletedForms(); AvailableForms getRecommendedForms(); AvailableForms getProviderReports(); int getRecommendedFormsCount(); void deleteCompleteAndIncompleteEncounterFormData(List<String> formDataUuids); List<FormData> getNonUploadedFormData(String templateUUID); void markFormDataAsIncompleteAndDeleteRelatedEncountersAndObs(final FormData formData); void deleteFormDataAndRelatedEncountersAndObs(List<FormData> formData); List<FormData> getArchivedFormData(); FormDataStatus downloadFormDataStatus(FormData formData); boolean isFormAlreadyExist(String jsonPayload, FormData formData); boolean isRegistrationFormDataWithEncounterForm(String formUuid); boolean isRegistrationFormData(FormData formData); boolean isGenericRegistrationHTMLFormData(FormData formData); boolean isEncounterFormData(FormData formData); Map<String, List<FormData>> getFormDataGroupedByPatient(List<String> uuids); Map<String, List<FormData>> deleteFormDataWithNoRelatedCompleteRegistrationFormDataInGroup( Map<String, List<FormData>> groupedFormData); Map<String, List<FormData>> deleteRegistrationFormDataWithAllRelatedEncountersInGroup(Map<String, List<FormData>> groupedFormData); AvailableForms getAvailableFormByTagsSortedByConfigOrder(List<String> tagsUuid, boolean alwaysIncludeRegistrationForms); AvailableForms getDownloadedRelationshipForms(); AvailableForm getAvailableFormByFormUuid(String uuid); ArrayList<String> getFormListAsPerConfigOrder(); AvailableForms getAvailableFormsPerConfigOrder(ArrayList<String> formUuids, List<Form> filteredForms); }
@Test public void downloadAllForms_shouldDownloadAllForms() throws IOException, FormController.FormFetchException { List<Form> forms = new ArrayList<>(); when(formService.downloadFormsByName(StringUtils.EMPTY)).thenReturn(forms); when(lastSyncTimeService.getLastSyncTimeFor(DOWNLOAD_FORMS)).thenReturn(mockDate); assertThat(formController.downloadAllForms(), is(forms)); } @Test public void shouldCheckForLastSynTimeOfFormWhenDownloadingAllForms() throws Exception, FormController.FormFetchException { when(lastSyncTimeService.getLastSyncTimeFor(DOWNLOAD_FORMS)).thenReturn(mockDate); formController.downloadAllForms(); verify(lastSyncTimeService).getLastSyncTimeFor(DOWNLOAD_FORMS); verify(formService, never()).downloadFormsByName(StringUtils.EMPTY); verify(formService).downloadFormsByName(StringUtils.EMPTY, mockDate); } @Test public void shouldUpdateLastSyncTimeAfterDownloadingAllForms() throws Exception, FormController.FormFetchException { Date mockDate = mock(Date.class); when(lastSyncTimeService.getLastSyncTimeFor(DOWNLOAD_FORMS)).thenReturn(mockDate); Date otherMockDate = mock(Date.class); when(sntpService.getTimePerDeviceTimeZone()).thenReturn(otherMockDate); formController.downloadAllForms(); ArgumentCaptor<LastSyncTime> argumentCaptor = ArgumentCaptor.forClass(LastSyncTime.class); verify(lastSyncTimeService).saveLastSyncTime(argumentCaptor.capture()); LastSyncTime savedLastSyncTime = argumentCaptor.getValue(); assertThat(savedLastSyncTime.getApiName(), is(DOWNLOAD_FORMS)); assertThat(savedLastSyncTime.getParamSignature(), nullValue()); assertThat(savedLastSyncTime.getLastSyncDate(), is(otherMockDate)); } @Test(expected = FormController.FormFetchException.class) public void downloadAllForms_shouldThrowExceptionThrownByFormService() throws IOException, FormController.FormFetchException { when(lastSyncTimeService.getLastSyncTimeFor(DOWNLOAD_FORMS)).thenReturn(mockDate); doThrow(new IOException()).when(formService).downloadFormsByName(StringUtils.EMPTY, mockDate); formController.downloadAllForms(); }
FormController { public FormTemplate downloadFormTemplateByUuid(String uuid) throws FormFetchException { try { return formService.downloadFormTemplateByUuid(uuid); } catch (IOException e) { throw new FormFetchException(e); } } FormController(MuzimaApplication muzimaApplication); int getTotalFormCount(); Form getFormByUuid(String formId); FormTemplate getFormTemplateByUuid(String formId); AvailableForms getAvailableFormByTags(List<String> tagsUuid); List<Form> getAllAvailableForms(); AvailableForms getAvailableFormByTags(List<String> tagsUuid, boolean alwaysIncludeRegistrationForms); List<Tag> getAllTags(); List<Tag> getAllTagsExcludingRegistrationTag(); DownloadedForms getAllDownloadedForms(); List<Form> downloadAllForms(); List<FormTemplate> downloadFormTemplates(String[] formUuids); FormTemplate downloadFormTemplateByUuid(String uuid); void saveAllForms(List<Form> forms); void updateAllForms(List<Form> forms); void deleteAllForms(); void deleteAllFormTemplates(); void deleteForms(List<Form> forms); void deleteFormTemplatesByUUID(List<String> formTemplateUUIDs); void replaceFormTemplates(List<FormTemplate> formTemplates); void saveFormTemplates(List<FormTemplate> formTemplates); boolean isFormDownloaded(Form form); int getTagColor(String uuid); void resetTagColors(); List<Tag> getSelectedTags(); void setSelectedTags(List<Tag> selectedTags); FormData getFormDataByUuid(String formDataUuid); List<FormData> getFormDataByUuids(List<String> formDataUuids); CompleteFormWithPatientData getCompleteFormDataByUuid(String formDataUuid); void saveFormData(FormData formData); List<FormData> getAllFormData(String status); List<FormData> getAllFormDataByPatientUuid(String patientUuid, String status); IncompleteFormsWithPatientData getAllIncompleteFormsWithPatientData(); CompleteFormsWithPatientData getAllCompleteFormsWithPatientData(Context context); IncompleteForms getAllIncompleteFormsForPatientUuid(String patientUuid); CompleteForms getAllCompleteFormsForPatientUuid(String patientUuid); int countAllIncompleteForms(); int countAllCompleteForms(); int getCompleteFormsCountForPatient(String patientId); int getIncompleteFormsCountForPatient(String patientId); AvailableForms getDownloadedRegistrationForms(); Patient createNewPatient(MuzimaApplication muzimaApplication, FormData formData); boolean uploadAllCompletedForms(); AvailableForms getRecommendedForms(); AvailableForms getProviderReports(); int getRecommendedFormsCount(); void deleteCompleteAndIncompleteEncounterFormData(List<String> formDataUuids); List<FormData> getNonUploadedFormData(String templateUUID); void markFormDataAsIncompleteAndDeleteRelatedEncountersAndObs(final FormData formData); void deleteFormDataAndRelatedEncountersAndObs(List<FormData> formData); List<FormData> getArchivedFormData(); FormDataStatus downloadFormDataStatus(FormData formData); boolean isFormAlreadyExist(String jsonPayload, FormData formData); boolean isRegistrationFormDataWithEncounterForm(String formUuid); boolean isRegistrationFormData(FormData formData); boolean isGenericRegistrationHTMLFormData(FormData formData); boolean isEncounterFormData(FormData formData); Map<String, List<FormData>> getFormDataGroupedByPatient(List<String> uuids); Map<String, List<FormData>> deleteFormDataWithNoRelatedCompleteRegistrationFormDataInGroup( Map<String, List<FormData>> groupedFormData); Map<String, List<FormData>> deleteRegistrationFormDataWithAllRelatedEncountersInGroup(Map<String, List<FormData>> groupedFormData); AvailableForms getAvailableFormByTagsSortedByConfigOrder(List<String> tagsUuid, boolean alwaysIncludeRegistrationForms); AvailableForms getDownloadedRelationshipForms(); AvailableForm getAvailableFormByFormUuid(String uuid); ArrayList<String> getFormListAsPerConfigOrder(); AvailableForms getAvailableFormsPerConfigOrder(ArrayList<String> formUuids, List<Form> filteredForms); }
@Test public void downloadFormTemplateByUuid_shouldDownloadFormByUuid() throws IOException, FormController.FormFetchException { FormTemplate formTemplate = new FormTemplate(); String uuid = "uuid"; when(formService.downloadFormTemplateByUuid(uuid)).thenReturn(formTemplate); assertThat(formController.downloadFormTemplateByUuid(uuid), is(formTemplate)); } @Test(expected = FormController.FormFetchException.class) public void downloadFormTemplateByUuid_shouldThrowFormFetchExceptionIfExceptionThrownByFormService() throws IOException, FormController.FormFetchException { String uuid = "uuid"; doThrow(new IOException()).when(formService).downloadFormTemplateByUuid(uuid); formController.downloadFormTemplateByUuid(uuid); }
FormController { public void saveAllForms(List<Form> forms) throws FormSaveException { try { formService.saveForms(forms); } catch (IOException e) { throw new FormSaveException(e); } } FormController(MuzimaApplication muzimaApplication); int getTotalFormCount(); Form getFormByUuid(String formId); FormTemplate getFormTemplateByUuid(String formId); AvailableForms getAvailableFormByTags(List<String> tagsUuid); List<Form> getAllAvailableForms(); AvailableForms getAvailableFormByTags(List<String> tagsUuid, boolean alwaysIncludeRegistrationForms); List<Tag> getAllTags(); List<Tag> getAllTagsExcludingRegistrationTag(); DownloadedForms getAllDownloadedForms(); List<Form> downloadAllForms(); List<FormTemplate> downloadFormTemplates(String[] formUuids); FormTemplate downloadFormTemplateByUuid(String uuid); void saveAllForms(List<Form> forms); void updateAllForms(List<Form> forms); void deleteAllForms(); void deleteAllFormTemplates(); void deleteForms(List<Form> forms); void deleteFormTemplatesByUUID(List<String> formTemplateUUIDs); void replaceFormTemplates(List<FormTemplate> formTemplates); void saveFormTemplates(List<FormTemplate> formTemplates); boolean isFormDownloaded(Form form); int getTagColor(String uuid); void resetTagColors(); List<Tag> getSelectedTags(); void setSelectedTags(List<Tag> selectedTags); FormData getFormDataByUuid(String formDataUuid); List<FormData> getFormDataByUuids(List<String> formDataUuids); CompleteFormWithPatientData getCompleteFormDataByUuid(String formDataUuid); void saveFormData(FormData formData); List<FormData> getAllFormData(String status); List<FormData> getAllFormDataByPatientUuid(String patientUuid, String status); IncompleteFormsWithPatientData getAllIncompleteFormsWithPatientData(); CompleteFormsWithPatientData getAllCompleteFormsWithPatientData(Context context); IncompleteForms getAllIncompleteFormsForPatientUuid(String patientUuid); CompleteForms getAllCompleteFormsForPatientUuid(String patientUuid); int countAllIncompleteForms(); int countAllCompleteForms(); int getCompleteFormsCountForPatient(String patientId); int getIncompleteFormsCountForPatient(String patientId); AvailableForms getDownloadedRegistrationForms(); Patient createNewPatient(MuzimaApplication muzimaApplication, FormData formData); boolean uploadAllCompletedForms(); AvailableForms getRecommendedForms(); AvailableForms getProviderReports(); int getRecommendedFormsCount(); void deleteCompleteAndIncompleteEncounterFormData(List<String> formDataUuids); List<FormData> getNonUploadedFormData(String templateUUID); void markFormDataAsIncompleteAndDeleteRelatedEncountersAndObs(final FormData formData); void deleteFormDataAndRelatedEncountersAndObs(List<FormData> formData); List<FormData> getArchivedFormData(); FormDataStatus downloadFormDataStatus(FormData formData); boolean isFormAlreadyExist(String jsonPayload, FormData formData); boolean isRegistrationFormDataWithEncounterForm(String formUuid); boolean isRegistrationFormData(FormData formData); boolean isGenericRegistrationHTMLFormData(FormData formData); boolean isEncounterFormData(FormData formData); Map<String, List<FormData>> getFormDataGroupedByPatient(List<String> uuids); Map<String, List<FormData>> deleteFormDataWithNoRelatedCompleteRegistrationFormDataInGroup( Map<String, List<FormData>> groupedFormData); Map<String, List<FormData>> deleteRegistrationFormDataWithAllRelatedEncountersInGroup(Map<String, List<FormData>> groupedFormData); AvailableForms getAvailableFormByTagsSortedByConfigOrder(List<String> tagsUuid, boolean alwaysIncludeRegistrationForms); AvailableForms getDownloadedRelationshipForms(); AvailableForm getAvailableFormByFormUuid(String uuid); ArrayList<String> getFormListAsPerConfigOrder(); AvailableForms getAvailableFormsPerConfigOrder(ArrayList<String> formUuids, List<Form> filteredForms); }
@Test public void saveAllForms_shouldSaveAllForm() throws FormController.FormSaveException, IOException { List<Form> forms = buildForms(); formController.saveAllForms(forms); verify(formService).saveForms(forms); verifyNoMoreInteractions(formService); } @Test(expected = FormController.FormSaveException.class) public void saveAllForms_shouldThrowFormSaveExceptionIfExceptionThrownByFormService() throws FormController.FormSaveException, IOException { List<Form> forms = buildForms(); doThrow(new IOException()).when(formService).saveForms(forms); formController.saveAllForms(forms); }
FormController { public List<Tag> getAllTags() throws FormFetchException { List<Tag> allTags = new ArrayList<>(); List<Form> allForms = null; try { allForms = formService.getAllForms(); } catch (IOException e) { throw new FormFetchException(e); } for (Form form : allForms) { for (Tag tag : form.getTags()) { if (!allTags.contains(tag)) { allTags.add(tag); } } } return allTags; } FormController(MuzimaApplication muzimaApplication); int getTotalFormCount(); Form getFormByUuid(String formId); FormTemplate getFormTemplateByUuid(String formId); AvailableForms getAvailableFormByTags(List<String> tagsUuid); List<Form> getAllAvailableForms(); AvailableForms getAvailableFormByTags(List<String> tagsUuid, boolean alwaysIncludeRegistrationForms); List<Tag> getAllTags(); List<Tag> getAllTagsExcludingRegistrationTag(); DownloadedForms getAllDownloadedForms(); List<Form> downloadAllForms(); List<FormTemplate> downloadFormTemplates(String[] formUuids); FormTemplate downloadFormTemplateByUuid(String uuid); void saveAllForms(List<Form> forms); void updateAllForms(List<Form> forms); void deleteAllForms(); void deleteAllFormTemplates(); void deleteForms(List<Form> forms); void deleteFormTemplatesByUUID(List<String> formTemplateUUIDs); void replaceFormTemplates(List<FormTemplate> formTemplates); void saveFormTemplates(List<FormTemplate> formTemplates); boolean isFormDownloaded(Form form); int getTagColor(String uuid); void resetTagColors(); List<Tag> getSelectedTags(); void setSelectedTags(List<Tag> selectedTags); FormData getFormDataByUuid(String formDataUuid); List<FormData> getFormDataByUuids(List<String> formDataUuids); CompleteFormWithPatientData getCompleteFormDataByUuid(String formDataUuid); void saveFormData(FormData formData); List<FormData> getAllFormData(String status); List<FormData> getAllFormDataByPatientUuid(String patientUuid, String status); IncompleteFormsWithPatientData getAllIncompleteFormsWithPatientData(); CompleteFormsWithPatientData getAllCompleteFormsWithPatientData(Context context); IncompleteForms getAllIncompleteFormsForPatientUuid(String patientUuid); CompleteForms getAllCompleteFormsForPatientUuid(String patientUuid); int countAllIncompleteForms(); int countAllCompleteForms(); int getCompleteFormsCountForPatient(String patientId); int getIncompleteFormsCountForPatient(String patientId); AvailableForms getDownloadedRegistrationForms(); Patient createNewPatient(MuzimaApplication muzimaApplication, FormData formData); boolean uploadAllCompletedForms(); AvailableForms getRecommendedForms(); AvailableForms getProviderReports(); int getRecommendedFormsCount(); void deleteCompleteAndIncompleteEncounterFormData(List<String> formDataUuids); List<FormData> getNonUploadedFormData(String templateUUID); void markFormDataAsIncompleteAndDeleteRelatedEncountersAndObs(final FormData formData); void deleteFormDataAndRelatedEncountersAndObs(List<FormData> formData); List<FormData> getArchivedFormData(); FormDataStatus downloadFormDataStatus(FormData formData); boolean isFormAlreadyExist(String jsonPayload, FormData formData); boolean isRegistrationFormDataWithEncounterForm(String formUuid); boolean isRegistrationFormData(FormData formData); boolean isGenericRegistrationHTMLFormData(FormData formData); boolean isEncounterFormData(FormData formData); Map<String, List<FormData>> getFormDataGroupedByPatient(List<String> uuids); Map<String, List<FormData>> deleteFormDataWithNoRelatedCompleteRegistrationFormDataInGroup( Map<String, List<FormData>> groupedFormData); Map<String, List<FormData>> deleteRegistrationFormDataWithAllRelatedEncountersInGroup(Map<String, List<FormData>> groupedFormData); AvailableForms getAvailableFormByTagsSortedByConfigOrder(List<String> tagsUuid, boolean alwaysIncludeRegistrationForms); AvailableForms getDownloadedRelationshipForms(); AvailableForm getAvailableFormByFormUuid(String uuid); ArrayList<String> getFormListAsPerConfigOrder(); AvailableForms getAvailableFormsPerConfigOrder(ArrayList<String> formUuids, List<Form> filteredForms); }
@Test public void getAllTags_shouldFetchAllUsedTags() throws FormController.FormFetchException, IOException { when(formService.getAllForms()).thenReturn(buildForms()); List<Tag> allTags = formController.getAllTags(); assertThat(allTags.size(), is(5)); assertThat(allTags.get(0).getUuid(), is("tag1")); assertThat(allTags.get(1).getUuid(), is("tag2")); assertThat(allTags.get(2).getUuid(), is("tag3")); assertThat(allTags.get(3).getUuid(), is("tag4")); assertThat(allTags.get(4).getUuid(), is("tag5")); }
FormController { public DownloadedForms getAllDownloadedForms() throws FormFetchException { DownloadedForms downloadedFormsByTags = new DownloadedForms(); try { List<Form> allForms = formService.getAllForms(); ArrayList<String> formUuids = getFormListAsPerConfigOrder(); for (String formUuid : formUuids) { Form form = formService.getFormByUuid(formUuid); if (formService.isFormTemplateDownloaded(form.getUuid())) { downloadedFormsByTags.add(new DownloadedFormBuilder().withDownloadedForm(form).build()); } } for (Form form : allForms) { if (!formUuids.contains(form.getUuid())) { if (formService.isFormTemplateDownloaded(form.getUuid())) { downloadedFormsByTags.add(new DownloadedFormBuilder().withDownloadedForm(form).build()); } } } } catch (IOException e) { throw new FormFetchException(e); } return downloadedFormsByTags; } FormController(MuzimaApplication muzimaApplication); int getTotalFormCount(); Form getFormByUuid(String formId); FormTemplate getFormTemplateByUuid(String formId); AvailableForms getAvailableFormByTags(List<String> tagsUuid); List<Form> getAllAvailableForms(); AvailableForms getAvailableFormByTags(List<String> tagsUuid, boolean alwaysIncludeRegistrationForms); List<Tag> getAllTags(); List<Tag> getAllTagsExcludingRegistrationTag(); DownloadedForms getAllDownloadedForms(); List<Form> downloadAllForms(); List<FormTemplate> downloadFormTemplates(String[] formUuids); FormTemplate downloadFormTemplateByUuid(String uuid); void saveAllForms(List<Form> forms); void updateAllForms(List<Form> forms); void deleteAllForms(); void deleteAllFormTemplates(); void deleteForms(List<Form> forms); void deleteFormTemplatesByUUID(List<String> formTemplateUUIDs); void replaceFormTemplates(List<FormTemplate> formTemplates); void saveFormTemplates(List<FormTemplate> formTemplates); boolean isFormDownloaded(Form form); int getTagColor(String uuid); void resetTagColors(); List<Tag> getSelectedTags(); void setSelectedTags(List<Tag> selectedTags); FormData getFormDataByUuid(String formDataUuid); List<FormData> getFormDataByUuids(List<String> formDataUuids); CompleteFormWithPatientData getCompleteFormDataByUuid(String formDataUuid); void saveFormData(FormData formData); List<FormData> getAllFormData(String status); List<FormData> getAllFormDataByPatientUuid(String patientUuid, String status); IncompleteFormsWithPatientData getAllIncompleteFormsWithPatientData(); CompleteFormsWithPatientData getAllCompleteFormsWithPatientData(Context context); IncompleteForms getAllIncompleteFormsForPatientUuid(String patientUuid); CompleteForms getAllCompleteFormsForPatientUuid(String patientUuid); int countAllIncompleteForms(); int countAllCompleteForms(); int getCompleteFormsCountForPatient(String patientId); int getIncompleteFormsCountForPatient(String patientId); AvailableForms getDownloadedRegistrationForms(); Patient createNewPatient(MuzimaApplication muzimaApplication, FormData formData); boolean uploadAllCompletedForms(); AvailableForms getRecommendedForms(); AvailableForms getProviderReports(); int getRecommendedFormsCount(); void deleteCompleteAndIncompleteEncounterFormData(List<String> formDataUuids); List<FormData> getNonUploadedFormData(String templateUUID); void markFormDataAsIncompleteAndDeleteRelatedEncountersAndObs(final FormData formData); void deleteFormDataAndRelatedEncountersAndObs(List<FormData> formData); List<FormData> getArchivedFormData(); FormDataStatus downloadFormDataStatus(FormData formData); boolean isFormAlreadyExist(String jsonPayload, FormData formData); boolean isRegistrationFormDataWithEncounterForm(String formUuid); boolean isRegistrationFormData(FormData formData); boolean isGenericRegistrationHTMLFormData(FormData formData); boolean isEncounterFormData(FormData formData); Map<String, List<FormData>> getFormDataGroupedByPatient(List<String> uuids); Map<String, List<FormData>> deleteFormDataWithNoRelatedCompleteRegistrationFormDataInGroup( Map<String, List<FormData>> groupedFormData); Map<String, List<FormData>> deleteRegistrationFormDataWithAllRelatedEncountersInGroup(Map<String, List<FormData>> groupedFormData); AvailableForms getAvailableFormByTagsSortedByConfigOrder(List<String> tagsUuid, boolean alwaysIncludeRegistrationForms); AvailableForms getDownloadedRelationshipForms(); AvailableForm getAvailableFormByFormUuid(String uuid); ArrayList<String> getFormListAsPerConfigOrder(); AvailableForms getAvailableFormsPerConfigOrder(ArrayList<String> formUuids, List<Form> filteredForms); }
@Test public void getAllDownloadedForms_shouldReturnOnlyDownloadedForms() throws IOException, FormController.FormFetchException { List<Form> forms = buildForms(); when(formService.getAllForms()).thenReturn(forms); when(formService.isFormTemplateDownloaded(forms.get(0).getUuid())).thenReturn(true); DownloadedForms allDownloadedForms = formController.getAllDownloadedForms(); assertThat(allDownloadedForms.size(), is(1)); } @Test public void getAllDownloadedForms_shouldReturnNoFormsIfNoTemplateIsDownloaded() throws IOException, FormController.FormFetchException { List<Form> forms = buildForms(); when(formService.getAllForms()).thenReturn(forms); when(formService.isFormTemplateDownloaded(anyString())).thenReturn(false); DownloadedForms allDownloadedForms = formController.getAllDownloadedForms(); assertThat(allDownloadedForms.size(), is(0)); }
FormController { public boolean isFormDownloaded(Form form) throws FormFetchException { boolean downloaded; try { downloaded = formService.isFormTemplateDownloaded(form.getUuid()); } catch (IOException e) { throw new FormFetchException(e); } return downloaded; } FormController(MuzimaApplication muzimaApplication); int getTotalFormCount(); Form getFormByUuid(String formId); FormTemplate getFormTemplateByUuid(String formId); AvailableForms getAvailableFormByTags(List<String> tagsUuid); List<Form> getAllAvailableForms(); AvailableForms getAvailableFormByTags(List<String> tagsUuid, boolean alwaysIncludeRegistrationForms); List<Tag> getAllTags(); List<Tag> getAllTagsExcludingRegistrationTag(); DownloadedForms getAllDownloadedForms(); List<Form> downloadAllForms(); List<FormTemplate> downloadFormTemplates(String[] formUuids); FormTemplate downloadFormTemplateByUuid(String uuid); void saveAllForms(List<Form> forms); void updateAllForms(List<Form> forms); void deleteAllForms(); void deleteAllFormTemplates(); void deleteForms(List<Form> forms); void deleteFormTemplatesByUUID(List<String> formTemplateUUIDs); void replaceFormTemplates(List<FormTemplate> formTemplates); void saveFormTemplates(List<FormTemplate> formTemplates); boolean isFormDownloaded(Form form); int getTagColor(String uuid); void resetTagColors(); List<Tag> getSelectedTags(); void setSelectedTags(List<Tag> selectedTags); FormData getFormDataByUuid(String formDataUuid); List<FormData> getFormDataByUuids(List<String> formDataUuids); CompleteFormWithPatientData getCompleteFormDataByUuid(String formDataUuid); void saveFormData(FormData formData); List<FormData> getAllFormData(String status); List<FormData> getAllFormDataByPatientUuid(String patientUuid, String status); IncompleteFormsWithPatientData getAllIncompleteFormsWithPatientData(); CompleteFormsWithPatientData getAllCompleteFormsWithPatientData(Context context); IncompleteForms getAllIncompleteFormsForPatientUuid(String patientUuid); CompleteForms getAllCompleteFormsForPatientUuid(String patientUuid); int countAllIncompleteForms(); int countAllCompleteForms(); int getCompleteFormsCountForPatient(String patientId); int getIncompleteFormsCountForPatient(String patientId); AvailableForms getDownloadedRegistrationForms(); Patient createNewPatient(MuzimaApplication muzimaApplication, FormData formData); boolean uploadAllCompletedForms(); AvailableForms getRecommendedForms(); AvailableForms getProviderReports(); int getRecommendedFormsCount(); void deleteCompleteAndIncompleteEncounterFormData(List<String> formDataUuids); List<FormData> getNonUploadedFormData(String templateUUID); void markFormDataAsIncompleteAndDeleteRelatedEncountersAndObs(final FormData formData); void deleteFormDataAndRelatedEncountersAndObs(List<FormData> formData); List<FormData> getArchivedFormData(); FormDataStatus downloadFormDataStatus(FormData formData); boolean isFormAlreadyExist(String jsonPayload, FormData formData); boolean isRegistrationFormDataWithEncounterForm(String formUuid); boolean isRegistrationFormData(FormData formData); boolean isGenericRegistrationHTMLFormData(FormData formData); boolean isEncounterFormData(FormData formData); Map<String, List<FormData>> getFormDataGroupedByPatient(List<String> uuids); Map<String, List<FormData>> deleteFormDataWithNoRelatedCompleteRegistrationFormDataInGroup( Map<String, List<FormData>> groupedFormData); Map<String, List<FormData>> deleteRegistrationFormDataWithAllRelatedEncountersInGroup(Map<String, List<FormData>> groupedFormData); AvailableForms getAvailableFormByTagsSortedByConfigOrder(List<String> tagsUuid, boolean alwaysIncludeRegistrationForms); AvailableForms getDownloadedRelationshipForms(); AvailableForm getAvailableFormByFormUuid(String uuid); ArrayList<String> getFormListAsPerConfigOrder(); AvailableForms getAvailableFormsPerConfigOrder(ArrayList<String> formUuids, List<Form> filteredForms); }
@Test public void isFormDownloaded_shouldReturnTrueIfFromIsDownloaded() throws IOException, FormController.FormFetchException { List<Form> forms = buildForms(); List<FormTemplate> formTemplates = buildFormTemplates(); when(formService.isFormTemplateDownloaded(anyString())).thenReturn(true); assertThat(formController.isFormDownloaded(forms.get(0)), is(true)); } @Test public void isFormDownloaded_shouldReturnFalseIfFromIsNotDownloaded() throws IOException, FormController.FormFetchException { List<Form> forms = buildForms(); List<FormTemplate> formTemplates = buildFormTemplates(); when(formService.isFormTemplateDownloaded(anyString())).thenReturn(false); assertThat(formController.isFormDownloaded(forms.get(0)), is(false)); }
FormController { public FormTemplate getFormTemplateByUuid(String formId) throws FormFetchException { try { return formService.getFormTemplateByUuid(formId); } catch (IOException e) { throw new FormFetchException(e); } } FormController(MuzimaApplication muzimaApplication); int getTotalFormCount(); Form getFormByUuid(String formId); FormTemplate getFormTemplateByUuid(String formId); AvailableForms getAvailableFormByTags(List<String> tagsUuid); List<Form> getAllAvailableForms(); AvailableForms getAvailableFormByTags(List<String> tagsUuid, boolean alwaysIncludeRegistrationForms); List<Tag> getAllTags(); List<Tag> getAllTagsExcludingRegistrationTag(); DownloadedForms getAllDownloadedForms(); List<Form> downloadAllForms(); List<FormTemplate> downloadFormTemplates(String[] formUuids); FormTemplate downloadFormTemplateByUuid(String uuid); void saveAllForms(List<Form> forms); void updateAllForms(List<Form> forms); void deleteAllForms(); void deleteAllFormTemplates(); void deleteForms(List<Form> forms); void deleteFormTemplatesByUUID(List<String> formTemplateUUIDs); void replaceFormTemplates(List<FormTemplate> formTemplates); void saveFormTemplates(List<FormTemplate> formTemplates); boolean isFormDownloaded(Form form); int getTagColor(String uuid); void resetTagColors(); List<Tag> getSelectedTags(); void setSelectedTags(List<Tag> selectedTags); FormData getFormDataByUuid(String formDataUuid); List<FormData> getFormDataByUuids(List<String> formDataUuids); CompleteFormWithPatientData getCompleteFormDataByUuid(String formDataUuid); void saveFormData(FormData formData); List<FormData> getAllFormData(String status); List<FormData> getAllFormDataByPatientUuid(String patientUuid, String status); IncompleteFormsWithPatientData getAllIncompleteFormsWithPatientData(); CompleteFormsWithPatientData getAllCompleteFormsWithPatientData(Context context); IncompleteForms getAllIncompleteFormsForPatientUuid(String patientUuid); CompleteForms getAllCompleteFormsForPatientUuid(String patientUuid); int countAllIncompleteForms(); int countAllCompleteForms(); int getCompleteFormsCountForPatient(String patientId); int getIncompleteFormsCountForPatient(String patientId); AvailableForms getDownloadedRegistrationForms(); Patient createNewPatient(MuzimaApplication muzimaApplication, FormData formData); boolean uploadAllCompletedForms(); AvailableForms getRecommendedForms(); AvailableForms getProviderReports(); int getRecommendedFormsCount(); void deleteCompleteAndIncompleteEncounterFormData(List<String> formDataUuids); List<FormData> getNonUploadedFormData(String templateUUID); void markFormDataAsIncompleteAndDeleteRelatedEncountersAndObs(final FormData formData); void deleteFormDataAndRelatedEncountersAndObs(List<FormData> formData); List<FormData> getArchivedFormData(); FormDataStatus downloadFormDataStatus(FormData formData); boolean isFormAlreadyExist(String jsonPayload, FormData formData); boolean isRegistrationFormDataWithEncounterForm(String formUuid); boolean isRegistrationFormData(FormData formData); boolean isGenericRegistrationHTMLFormData(FormData formData); boolean isEncounterFormData(FormData formData); Map<String, List<FormData>> getFormDataGroupedByPatient(List<String> uuids); Map<String, List<FormData>> deleteFormDataWithNoRelatedCompleteRegistrationFormDataInGroup( Map<String, List<FormData>> groupedFormData); Map<String, List<FormData>> deleteRegistrationFormDataWithAllRelatedEncountersInGroup(Map<String, List<FormData>> groupedFormData); AvailableForms getAvailableFormByTagsSortedByConfigOrder(List<String> tagsUuid, boolean alwaysIncludeRegistrationForms); AvailableForms getDownloadedRelationshipForms(); AvailableForm getAvailableFormByFormUuid(String uuid); ArrayList<String> getFormListAsPerConfigOrder(); AvailableForms getAvailableFormsPerConfigOrder(ArrayList<String> formUuids, List<Form> filteredForms); }
@Test public void getFormTemplateByUuid_shouldReturnForm() throws IOException, FormController.FormFetchException { List<FormTemplate> formTemplates = buildFormTemplates(); String uuid = formTemplates.get(0).getUuid(); when(formService.getFormTemplateByUuid(uuid)).thenReturn(formTemplates.get(0)); assertThat(formController.getFormTemplateByUuid(uuid), is(formTemplates.get(0))); }
FormController { public Form getFormByUuid(String formId) throws FormFetchException { try { return formService.getFormByUuid(formId); } catch (IOException e) { throw new FormFetchException(e); } } FormController(MuzimaApplication muzimaApplication); int getTotalFormCount(); Form getFormByUuid(String formId); FormTemplate getFormTemplateByUuid(String formId); AvailableForms getAvailableFormByTags(List<String> tagsUuid); List<Form> getAllAvailableForms(); AvailableForms getAvailableFormByTags(List<String> tagsUuid, boolean alwaysIncludeRegistrationForms); List<Tag> getAllTags(); List<Tag> getAllTagsExcludingRegistrationTag(); DownloadedForms getAllDownloadedForms(); List<Form> downloadAllForms(); List<FormTemplate> downloadFormTemplates(String[] formUuids); FormTemplate downloadFormTemplateByUuid(String uuid); void saveAllForms(List<Form> forms); void updateAllForms(List<Form> forms); void deleteAllForms(); void deleteAllFormTemplates(); void deleteForms(List<Form> forms); void deleteFormTemplatesByUUID(List<String> formTemplateUUIDs); void replaceFormTemplates(List<FormTemplate> formTemplates); void saveFormTemplates(List<FormTemplate> formTemplates); boolean isFormDownloaded(Form form); int getTagColor(String uuid); void resetTagColors(); List<Tag> getSelectedTags(); void setSelectedTags(List<Tag> selectedTags); FormData getFormDataByUuid(String formDataUuid); List<FormData> getFormDataByUuids(List<String> formDataUuids); CompleteFormWithPatientData getCompleteFormDataByUuid(String formDataUuid); void saveFormData(FormData formData); List<FormData> getAllFormData(String status); List<FormData> getAllFormDataByPatientUuid(String patientUuid, String status); IncompleteFormsWithPatientData getAllIncompleteFormsWithPatientData(); CompleteFormsWithPatientData getAllCompleteFormsWithPatientData(Context context); IncompleteForms getAllIncompleteFormsForPatientUuid(String patientUuid); CompleteForms getAllCompleteFormsForPatientUuid(String patientUuid); int countAllIncompleteForms(); int countAllCompleteForms(); int getCompleteFormsCountForPatient(String patientId); int getIncompleteFormsCountForPatient(String patientId); AvailableForms getDownloadedRegistrationForms(); Patient createNewPatient(MuzimaApplication muzimaApplication, FormData formData); boolean uploadAllCompletedForms(); AvailableForms getRecommendedForms(); AvailableForms getProviderReports(); int getRecommendedFormsCount(); void deleteCompleteAndIncompleteEncounterFormData(List<String> formDataUuids); List<FormData> getNonUploadedFormData(String templateUUID); void markFormDataAsIncompleteAndDeleteRelatedEncountersAndObs(final FormData formData); void deleteFormDataAndRelatedEncountersAndObs(List<FormData> formData); List<FormData> getArchivedFormData(); FormDataStatus downloadFormDataStatus(FormData formData); boolean isFormAlreadyExist(String jsonPayload, FormData formData); boolean isRegistrationFormDataWithEncounterForm(String formUuid); boolean isRegistrationFormData(FormData formData); boolean isGenericRegistrationHTMLFormData(FormData formData); boolean isEncounterFormData(FormData formData); Map<String, List<FormData>> getFormDataGroupedByPatient(List<String> uuids); Map<String, List<FormData>> deleteFormDataWithNoRelatedCompleteRegistrationFormDataInGroup( Map<String, List<FormData>> groupedFormData); Map<String, List<FormData>> deleteRegistrationFormDataWithAllRelatedEncountersInGroup(Map<String, List<FormData>> groupedFormData); AvailableForms getAvailableFormByTagsSortedByConfigOrder(List<String> tagsUuid, boolean alwaysIncludeRegistrationForms); AvailableForms getDownloadedRelationshipForms(); AvailableForm getAvailableFormByFormUuid(String uuid); ArrayList<String> getFormListAsPerConfigOrder(); AvailableForms getAvailableFormsPerConfigOrder(ArrayList<String> formUuids, List<Form> filteredForms); }
@Test public void getFormByUuid_shouldReturnForm() throws IOException, FormController.FormFetchException { List<Form> forms = buildForms(); String uuid = forms.get(0).getUuid(); when(formService.getFormByUuid(uuid)).thenReturn(forms.get(0)); assertThat(formController.getFormByUuid(uuid), is(forms.get(0))); }
FormController { public FormData getFormDataByUuid(String formDataUuid) throws FormDataFetchException { try { return formService.getFormDataByUuid(formDataUuid); } catch (IOException e) { throw new FormDataFetchException(e); } } FormController(MuzimaApplication muzimaApplication); int getTotalFormCount(); Form getFormByUuid(String formId); FormTemplate getFormTemplateByUuid(String formId); AvailableForms getAvailableFormByTags(List<String> tagsUuid); List<Form> getAllAvailableForms(); AvailableForms getAvailableFormByTags(List<String> tagsUuid, boolean alwaysIncludeRegistrationForms); List<Tag> getAllTags(); List<Tag> getAllTagsExcludingRegistrationTag(); DownloadedForms getAllDownloadedForms(); List<Form> downloadAllForms(); List<FormTemplate> downloadFormTemplates(String[] formUuids); FormTemplate downloadFormTemplateByUuid(String uuid); void saveAllForms(List<Form> forms); void updateAllForms(List<Form> forms); void deleteAllForms(); void deleteAllFormTemplates(); void deleteForms(List<Form> forms); void deleteFormTemplatesByUUID(List<String> formTemplateUUIDs); void replaceFormTemplates(List<FormTemplate> formTemplates); void saveFormTemplates(List<FormTemplate> formTemplates); boolean isFormDownloaded(Form form); int getTagColor(String uuid); void resetTagColors(); List<Tag> getSelectedTags(); void setSelectedTags(List<Tag> selectedTags); FormData getFormDataByUuid(String formDataUuid); List<FormData> getFormDataByUuids(List<String> formDataUuids); CompleteFormWithPatientData getCompleteFormDataByUuid(String formDataUuid); void saveFormData(FormData formData); List<FormData> getAllFormData(String status); List<FormData> getAllFormDataByPatientUuid(String patientUuid, String status); IncompleteFormsWithPatientData getAllIncompleteFormsWithPatientData(); CompleteFormsWithPatientData getAllCompleteFormsWithPatientData(Context context); IncompleteForms getAllIncompleteFormsForPatientUuid(String patientUuid); CompleteForms getAllCompleteFormsForPatientUuid(String patientUuid); int countAllIncompleteForms(); int countAllCompleteForms(); int getCompleteFormsCountForPatient(String patientId); int getIncompleteFormsCountForPatient(String patientId); AvailableForms getDownloadedRegistrationForms(); Patient createNewPatient(MuzimaApplication muzimaApplication, FormData formData); boolean uploadAllCompletedForms(); AvailableForms getRecommendedForms(); AvailableForms getProviderReports(); int getRecommendedFormsCount(); void deleteCompleteAndIncompleteEncounterFormData(List<String> formDataUuids); List<FormData> getNonUploadedFormData(String templateUUID); void markFormDataAsIncompleteAndDeleteRelatedEncountersAndObs(final FormData formData); void deleteFormDataAndRelatedEncountersAndObs(List<FormData> formData); List<FormData> getArchivedFormData(); FormDataStatus downloadFormDataStatus(FormData formData); boolean isFormAlreadyExist(String jsonPayload, FormData formData); boolean isRegistrationFormDataWithEncounterForm(String formUuid); boolean isRegistrationFormData(FormData formData); boolean isGenericRegistrationHTMLFormData(FormData formData); boolean isEncounterFormData(FormData formData); Map<String, List<FormData>> getFormDataGroupedByPatient(List<String> uuids); Map<String, List<FormData>> deleteFormDataWithNoRelatedCompleteRegistrationFormDataInGroup( Map<String, List<FormData>> groupedFormData); Map<String, List<FormData>> deleteRegistrationFormDataWithAllRelatedEncountersInGroup(Map<String, List<FormData>> groupedFormData); AvailableForms getAvailableFormByTagsSortedByConfigOrder(List<String> tagsUuid, boolean alwaysIncludeRegistrationForms); AvailableForms getDownloadedRelationshipForms(); AvailableForm getAvailableFormByFormUuid(String uuid); ArrayList<String> getFormListAsPerConfigOrder(); AvailableForms getAvailableFormsPerConfigOrder(ArrayList<String> formUuids, List<Form> filteredForms); }
@Test public void getFormDataByUuid_shouldReturnFormDataForAGivenId() throws Exception, FormController.FormDataFetchException { FormData formData = new FormData(); String uuid = "uuid"; when(formService.getFormDataByUuid(uuid)).thenReturn(formData); assertThat(formController.getFormDataByUuid(uuid), is(formData)); } @Test(expected = FormController.FormDataFetchException.class) public void getFormDataByUuid_shouldThrowFormDataFetchExceptionIfFormServiceThrowAnException() throws Exception, FormController.FormDataFetchException { String uuid = "uuid"; doThrow(new IOException()).when(formService).getFormDataByUuid(uuid); formController.getFormDataByUuid(uuid); }
FormController { public void saveFormData(FormData formData) throws FormDataSaveException { try { formData.setSaveTime(new Date()); formService.saveFormData(formData); } catch (IOException e) { throw new FormDataSaveException(e); } } FormController(MuzimaApplication muzimaApplication); int getTotalFormCount(); Form getFormByUuid(String formId); FormTemplate getFormTemplateByUuid(String formId); AvailableForms getAvailableFormByTags(List<String> tagsUuid); List<Form> getAllAvailableForms(); AvailableForms getAvailableFormByTags(List<String> tagsUuid, boolean alwaysIncludeRegistrationForms); List<Tag> getAllTags(); List<Tag> getAllTagsExcludingRegistrationTag(); DownloadedForms getAllDownloadedForms(); List<Form> downloadAllForms(); List<FormTemplate> downloadFormTemplates(String[] formUuids); FormTemplate downloadFormTemplateByUuid(String uuid); void saveAllForms(List<Form> forms); void updateAllForms(List<Form> forms); void deleteAllForms(); void deleteAllFormTemplates(); void deleteForms(List<Form> forms); void deleteFormTemplatesByUUID(List<String> formTemplateUUIDs); void replaceFormTemplates(List<FormTemplate> formTemplates); void saveFormTemplates(List<FormTemplate> formTemplates); boolean isFormDownloaded(Form form); int getTagColor(String uuid); void resetTagColors(); List<Tag> getSelectedTags(); void setSelectedTags(List<Tag> selectedTags); FormData getFormDataByUuid(String formDataUuid); List<FormData> getFormDataByUuids(List<String> formDataUuids); CompleteFormWithPatientData getCompleteFormDataByUuid(String formDataUuid); void saveFormData(FormData formData); List<FormData> getAllFormData(String status); List<FormData> getAllFormDataByPatientUuid(String patientUuid, String status); IncompleteFormsWithPatientData getAllIncompleteFormsWithPatientData(); CompleteFormsWithPatientData getAllCompleteFormsWithPatientData(Context context); IncompleteForms getAllIncompleteFormsForPatientUuid(String patientUuid); CompleteForms getAllCompleteFormsForPatientUuid(String patientUuid); int countAllIncompleteForms(); int countAllCompleteForms(); int getCompleteFormsCountForPatient(String patientId); int getIncompleteFormsCountForPatient(String patientId); AvailableForms getDownloadedRegistrationForms(); Patient createNewPatient(MuzimaApplication muzimaApplication, FormData formData); boolean uploadAllCompletedForms(); AvailableForms getRecommendedForms(); AvailableForms getProviderReports(); int getRecommendedFormsCount(); void deleteCompleteAndIncompleteEncounterFormData(List<String> formDataUuids); List<FormData> getNonUploadedFormData(String templateUUID); void markFormDataAsIncompleteAndDeleteRelatedEncountersAndObs(final FormData formData); void deleteFormDataAndRelatedEncountersAndObs(List<FormData> formData); List<FormData> getArchivedFormData(); FormDataStatus downloadFormDataStatus(FormData formData); boolean isFormAlreadyExist(String jsonPayload, FormData formData); boolean isRegistrationFormDataWithEncounterForm(String formUuid); boolean isRegistrationFormData(FormData formData); boolean isGenericRegistrationHTMLFormData(FormData formData); boolean isEncounterFormData(FormData formData); Map<String, List<FormData>> getFormDataGroupedByPatient(List<String> uuids); Map<String, List<FormData>> deleteFormDataWithNoRelatedCompleteRegistrationFormDataInGroup( Map<String, List<FormData>> groupedFormData); Map<String, List<FormData>> deleteRegistrationFormDataWithAllRelatedEncountersInGroup(Map<String, List<FormData>> groupedFormData); AvailableForms getAvailableFormByTagsSortedByConfigOrder(List<String> tagsUuid, boolean alwaysIncludeRegistrationForms); AvailableForms getDownloadedRelationshipForms(); AvailableForm getAvailableFormByFormUuid(String uuid); ArrayList<String> getFormListAsPerConfigOrder(); AvailableForms getAvailableFormsPerConfigOrder(ArrayList<String> formUuids, List<Form> filteredForms); }
@Test public void saveFormData_shouldSaveFormData() throws Exception, FormController.FormDataSaveException { FormData formData = new FormData(); formController.saveFormData(formData); verify(formService).saveFormData(formData); } @Test(expected = FormController.FormDataSaveException.class) public void saveFormData_shouldThrowFormDataSaveExceptionIfExceptionThrownByFormService() throws Exception, FormController.FormDataSaveException { FormData formData = new FormData(); doThrow(new IOException()).when(formService).saveFormData(formData); formController.saveFormData(formData); }
EntityUtils { @SuppressWarnings({ "unchecked", "rawtypes" }) public static Class<? extends Serializable> primaryKeyClass(Class<?> entityClass) { if (entityClass.isAnnotationPresent(IdClass.class)) { return entityClass.getAnnotation(IdClass.class).value(); } Class clazz = PersistenceUnitDescriptorProvider.getInstance().primaryKeyIdClass(entityClass); if (clazz != null) { return clazz; } Property<Serializable> property = primaryKeyProperty(entityClass); return property.getJavaClass(); } private EntityUtils(); @SuppressWarnings({ "unchecked", "rawtypes" }) static Class<? extends Serializable> primaryKeyClass(Class<?> entityClass); static Object primaryKeyValue(Object entity); static Object primaryKeyValue(Object entity, Property<Serializable> primaryKeyProperty); static String entityName(Class<?> entityClass); static String tableName(Class<?> entityClass, EntityManager entityManager); static boolean isEntityClass(Class<?> entityClass); static Property<Serializable> primaryKeyProperty(Class<?> entityClass); static Property<Serializable> getVersionProperty(Class<?> entityClass); }
@Test public void should_find_id_property_class() { Class<? extends Serializable> pkClass = EntityUtils.primaryKeyClass(Tee.class); Assert.assertEquals(TeeId.class, pkClass); } @Test public void should_find_id_class() { Class<? extends Serializable> pkClass = EntityUtils.primaryKeyClass(Tee2.class); Assert.assertEquals(TeeId.class, pkClass); }
EntityRepositoryHandler implements EntityRepository<E, PK>, DelegateQueryHandler { @Override public E findBy(PK primaryKey) { Query query = context.getMethod().getAnnotation(Query.class); if (query != null && query.hints().length > 0) { Map<String, Object> hints = new HashMap<String, Object>(); for (QueryHint hint : query.hints()) { hints.put(hint.name(), hint.value()); } return entityManager().find(entityClass(), primaryKey, hints); } else { return entityManager().find(entityClass(), primaryKey); } } @Override @RequiresTransaction E save(E entity); @Override @RequiresTransaction E saveAndFlush(E entity); @Override @RequiresTransaction E saveAndFlushAndRefresh(E entity); @Override @RequiresTransaction void refresh(E entity); @Override E findBy(PK primaryKey); @Override Optional<E> findOptionalBy(PK primaryKey); @Override List<E> findBy(E example, SingularAttribute<E, ?>... attributes); @Override List<E> findBy(E example, int start, int max, SingularAttribute<E, ?>... attributes); @Override List<E> findByLike(E example, SingularAttribute<E, ?>... attributes); @Override List<E> findByLike(E example, int start, int max, SingularAttribute<E, ?>... attributes); @SuppressWarnings("unchecked") @Override List<E> findAll(); @SuppressWarnings("unchecked") @Override List<E> findAll(int start, int max); @Override Long count(); @Override Long count(E example, SingularAttribute<E, ?>... attributes); @Override Long countLike(E example, SingularAttribute<E, ?>... attributes); @SuppressWarnings("unchecked") @Override PK getPrimaryKey(E entity); @Override @RequiresTransaction void remove(E entity); @Override @RequiresTransaction void removeAndFlush(E entity); @Override @RequiresTransaction void attachAndRemove(E entity); @Override @RequiresTransaction void flush(); EntityManager entityManager(); CriteriaQuery<E> criteriaQuery(); TypedQuery<E> typedQuery(String qlString); @SuppressWarnings("unchecked") Class<E> entityClass(); String tableName(); String entityName(); }
@Test public void should_find_by_pk() throws Exception { Simple simple = testData.createSimple("testFindByPk"); Simple find = repo.findBy(simple.getId()); assertEquals(simple.getName(), find.getName()); } @Test @SuppressWarnings("unchecked") public void should_find_by_example() throws Exception { Simple simple = testData.createSimple("testFindByExample"); List<Simple> find = repo.findBy(simple, Simple_.name); assertNotNull(find); assertFalse(find.isEmpty()); assertEquals(simple.getName(), find.get(0).getName()); } @Test @SuppressWarnings("unchecked") public void should_find_by_example_with_start_and_max() throws Exception { Simple simple = testData.createSimple("testFindByExample1", Integer.valueOf(10)); testData.createSimple("testFindByExample1", Integer.valueOf(10)); List<Simple> find = repo.findBy(simple, 0, 1, Simple_.name, Simple_.counter); assertNotNull(find); assertFalse(find.isEmpty()); assertEquals(1, find.size()); assertEquals(simple.getName(), find.get(0).getName()); } @Test @SuppressWarnings("unchecked") public void should_find_by_example_with_no_attributes() throws Exception { Simple simple = testData.createSimple("testFindByExample"); SingularAttribute<Simple, ?>[] attributes = new SingularAttribute[] {}; List<Simple> find = repo.findBy(simple, attributes); assertNotNull(find); assertFalse(find.isEmpty()); assertEquals(simple.getName(), find.get(0).getName()); }
EntityRepositoryHandler implements EntityRepository<E, PK>, DelegateQueryHandler { @Override public Optional<E> findOptionalBy(PK primaryKey) { E found = null; try { found = findBy(primaryKey); } catch (Exception e) { } return Optional.ofNullable(found); } @Override @RequiresTransaction E save(E entity); @Override @RequiresTransaction E saveAndFlush(E entity); @Override @RequiresTransaction E saveAndFlushAndRefresh(E entity); @Override @RequiresTransaction void refresh(E entity); @Override E findBy(PK primaryKey); @Override Optional<E> findOptionalBy(PK primaryKey); @Override List<E> findBy(E example, SingularAttribute<E, ?>... attributes); @Override List<E> findBy(E example, int start, int max, SingularAttribute<E, ?>... attributes); @Override List<E> findByLike(E example, SingularAttribute<E, ?>... attributes); @Override List<E> findByLike(E example, int start, int max, SingularAttribute<E, ?>... attributes); @SuppressWarnings("unchecked") @Override List<E> findAll(); @SuppressWarnings("unchecked") @Override List<E> findAll(int start, int max); @Override Long count(); @Override Long count(E example, SingularAttribute<E, ?>... attributes); @Override Long countLike(E example, SingularAttribute<E, ?>... attributes); @SuppressWarnings("unchecked") @Override PK getPrimaryKey(E entity); @Override @RequiresTransaction void remove(E entity); @Override @RequiresTransaction void removeAndFlush(E entity); @Override @RequiresTransaction void attachAndRemove(E entity); @Override @RequiresTransaction void flush(); EntityManager entityManager(); CriteriaQuery<E> criteriaQuery(); TypedQuery<E> typedQuery(String qlString); @SuppressWarnings("unchecked") Class<E> entityClass(); String tableName(); String entityName(); }
@Test public void should_find__by_pk() throws Exception { Simple simple = testData.createSimple("testFindByPk"); Optional<Simple> find = repo.findOptionalBy(simple.getId()); assertEquals(simple.getName(), find.get().getName()); }
EntityRepositoryHandler implements EntityRepository<E, PK>, DelegateQueryHandler { @SuppressWarnings("unchecked") @Override public List<E> findAll() { return context.applyRestrictions(entityManager().createQuery(allQuery(), entityClass())).getResultList(); } @Override @RequiresTransaction E save(E entity); @Override @RequiresTransaction E saveAndFlush(E entity); @Override @RequiresTransaction E saveAndFlushAndRefresh(E entity); @Override @RequiresTransaction void refresh(E entity); @Override E findBy(PK primaryKey); @Override Optional<E> findOptionalBy(PK primaryKey); @Override List<E> findBy(E example, SingularAttribute<E, ?>... attributes); @Override List<E> findBy(E example, int start, int max, SingularAttribute<E, ?>... attributes); @Override List<E> findByLike(E example, SingularAttribute<E, ?>... attributes); @Override List<E> findByLike(E example, int start, int max, SingularAttribute<E, ?>... attributes); @SuppressWarnings("unchecked") @Override List<E> findAll(); @SuppressWarnings("unchecked") @Override List<E> findAll(int start, int max); @Override Long count(); @Override Long count(E example, SingularAttribute<E, ?>... attributes); @Override Long countLike(E example, SingularAttribute<E, ?>... attributes); @SuppressWarnings("unchecked") @Override PK getPrimaryKey(E entity); @Override @RequiresTransaction void remove(E entity); @Override @RequiresTransaction void removeAndFlush(E entity); @Override @RequiresTransaction void attachAndRemove(E entity); @Override @RequiresTransaction void flush(); EntityManager entityManager(); CriteriaQuery<E> criteriaQuery(); TypedQuery<E> typedQuery(String qlString); @SuppressWarnings("unchecked") Class<E> entityClass(); String tableName(); String entityName(); }
@Test public void should_find_all() { testData.createSimple("testFindAll1"); testData.createSimple("testFindAll2"); List<Simple> find = repo.findAll(); assertEquals(2, find.size()); } @Test public void should_find_by_all_with_start_and_max() { testData.createSimple("testFindAll1"); testData.createSimple("testFindAll2"); List<Simple> find = repo.findAll(0, 1); assertEquals(1, find.size()); }
EntityRepositoryHandler implements EntityRepository<E, PK>, DelegateQueryHandler { @Override public List<E> findByLike(E example, SingularAttribute<E, ?>... attributes) { return findByLike(example, -1, -1, attributes); } @Override @RequiresTransaction E save(E entity); @Override @RequiresTransaction E saveAndFlush(E entity); @Override @RequiresTransaction E saveAndFlushAndRefresh(E entity); @Override @RequiresTransaction void refresh(E entity); @Override E findBy(PK primaryKey); @Override Optional<E> findOptionalBy(PK primaryKey); @Override List<E> findBy(E example, SingularAttribute<E, ?>... attributes); @Override List<E> findBy(E example, int start, int max, SingularAttribute<E, ?>... attributes); @Override List<E> findByLike(E example, SingularAttribute<E, ?>... attributes); @Override List<E> findByLike(E example, int start, int max, SingularAttribute<E, ?>... attributes); @SuppressWarnings("unchecked") @Override List<E> findAll(); @SuppressWarnings("unchecked") @Override List<E> findAll(int start, int max); @Override Long count(); @Override Long count(E example, SingularAttribute<E, ?>... attributes); @Override Long countLike(E example, SingularAttribute<E, ?>... attributes); @SuppressWarnings("unchecked") @Override PK getPrimaryKey(E entity); @Override @RequiresTransaction void remove(E entity); @Override @RequiresTransaction void removeAndFlush(E entity); @Override @RequiresTransaction void attachAndRemove(E entity); @Override @RequiresTransaction void flush(); EntityManager entityManager(); CriteriaQuery<E> criteriaQuery(); TypedQuery<E> typedQuery(String qlString); @SuppressWarnings("unchecked") Class<E> entityClass(); String tableName(); String entityName(); }
@Test @SuppressWarnings({ "unchecked" }) public void should_find_by_like() { testData.createSimple("testFindAll1"); testData.createSimple("testFindAll2"); Simple example = new Simple("test"); List<Simple> find = repo.findByLike(example, Simple_.name); assertEquals(2, find.size()); } @Test @SuppressWarnings("unchecked") public void should_find_by_like_with_start_and_max() { testData.createSimple("testFindAll1"); testData.createSimple("testFindAll2"); Simple example = new Simple("test"); List<Simple> find = repo.findByLike(example, 1, 10, Simple_.name); assertEquals(1, find.size()); } @Test @SuppressWarnings("unchecked") public void should_find_by_like_non_string() { testData.createSimple("testFindAll1", 1); testData.createSimple("testFindAll2", 2); Simple example = new Simple("test"); example.setCounter(1); List<Simple> find = repo.findByLike(example, Simple_.name, Simple_.counter); assertEquals(1, find.size()); }
EntityRepositoryHandler implements EntityRepository<E, PK>, DelegateQueryHandler { @Override public Long count() { return (Long) context.applyRestrictions(entityManager().createQuery(countQuery(), Long.class)) .getSingleResult(); } @Override @RequiresTransaction E save(E entity); @Override @RequiresTransaction E saveAndFlush(E entity); @Override @RequiresTransaction E saveAndFlushAndRefresh(E entity); @Override @RequiresTransaction void refresh(E entity); @Override E findBy(PK primaryKey); @Override Optional<E> findOptionalBy(PK primaryKey); @Override List<E> findBy(E example, SingularAttribute<E, ?>... attributes); @Override List<E> findBy(E example, int start, int max, SingularAttribute<E, ?>... attributes); @Override List<E> findByLike(E example, SingularAttribute<E, ?>... attributes); @Override List<E> findByLike(E example, int start, int max, SingularAttribute<E, ?>... attributes); @SuppressWarnings("unchecked") @Override List<E> findAll(); @SuppressWarnings("unchecked") @Override List<E> findAll(int start, int max); @Override Long count(); @Override Long count(E example, SingularAttribute<E, ?>... attributes); @Override Long countLike(E example, SingularAttribute<E, ?>... attributes); @SuppressWarnings("unchecked") @Override PK getPrimaryKey(E entity); @Override @RequiresTransaction void remove(E entity); @Override @RequiresTransaction void removeAndFlush(E entity); @Override @RequiresTransaction void attachAndRemove(E entity); @Override @RequiresTransaction void flush(); EntityManager entityManager(); CriteriaQuery<E> criteriaQuery(); TypedQuery<E> typedQuery(String qlString); @SuppressWarnings("unchecked") Class<E> entityClass(); String tableName(); String entityName(); }
@Test public void should_count_all() { testData.createSimple("testCountAll"); Long result = repo.count(); assertEquals(Long.valueOf(1), result); } @Test @SuppressWarnings("unchecked") public void should_count_with_attributes() { Simple simple = testData.createSimple("testFindAll1", Integer.valueOf(55)); testData.createSimple("testFindAll2", Integer.valueOf(55)); Long result = repo.count(simple, Simple_.name, Simple_.counter); assertEquals(Long.valueOf(1), result); } @Test @SuppressWarnings("unchecked") public void should_count_with_no_attributes() { Simple simple = testData.createSimple("testFindAll1"); testData.createSimple("testFindAll2"); SingularAttribute<Simple, Object>[] attributes = new SingularAttribute[] {}; Long result = repo.count(simple, attributes); assertEquals(Long.valueOf(2), result); }
EntityRepositoryHandler implements EntityRepository<E, PK>, DelegateQueryHandler { @Override public Long countLike(E example, SingularAttribute<E, ?>... attributes) { return executeCountQuery(example, true, attributes); } @Override @RequiresTransaction E save(E entity); @Override @RequiresTransaction E saveAndFlush(E entity); @Override @RequiresTransaction E saveAndFlushAndRefresh(E entity); @Override @RequiresTransaction void refresh(E entity); @Override E findBy(PK primaryKey); @Override Optional<E> findOptionalBy(PK primaryKey); @Override List<E> findBy(E example, SingularAttribute<E, ?>... attributes); @Override List<E> findBy(E example, int start, int max, SingularAttribute<E, ?>... attributes); @Override List<E> findByLike(E example, SingularAttribute<E, ?>... attributes); @Override List<E> findByLike(E example, int start, int max, SingularAttribute<E, ?>... attributes); @SuppressWarnings("unchecked") @Override List<E> findAll(); @SuppressWarnings("unchecked") @Override List<E> findAll(int start, int max); @Override Long count(); @Override Long count(E example, SingularAttribute<E, ?>... attributes); @Override Long countLike(E example, SingularAttribute<E, ?>... attributes); @SuppressWarnings("unchecked") @Override PK getPrimaryKey(E entity); @Override @RequiresTransaction void remove(E entity); @Override @RequiresTransaction void removeAndFlush(E entity); @Override @RequiresTransaction void attachAndRemove(E entity); @Override @RequiresTransaction void flush(); EntityManager entityManager(); CriteriaQuery<E> criteriaQuery(); TypedQuery<E> typedQuery(String qlString); @SuppressWarnings("unchecked") Class<E> entityClass(); String tableName(); String entityName(); }
@Test @SuppressWarnings("unchecked") public void should_count_by_like() { testData.createSimple("testFindAll1"); testData.createSimple("testFindAll2"); Simple example = new Simple("test"); Long count = repo.countLike(example, Simple_.name); assertEquals(Long.valueOf(2), count); }
EntityRepositoryHandler implements EntityRepository<E, PK>, DelegateQueryHandler { @Override @RequiresTransaction public void removeAndFlush(E entity) { entityManager().remove(entity); flush(); } @Override @RequiresTransaction E save(E entity); @Override @RequiresTransaction E saveAndFlush(E entity); @Override @RequiresTransaction E saveAndFlushAndRefresh(E entity); @Override @RequiresTransaction void refresh(E entity); @Override E findBy(PK primaryKey); @Override Optional<E> findOptionalBy(PK primaryKey); @Override List<E> findBy(E example, SingularAttribute<E, ?>... attributes); @Override List<E> findBy(E example, int start, int max, SingularAttribute<E, ?>... attributes); @Override List<E> findByLike(E example, SingularAttribute<E, ?>... attributes); @Override List<E> findByLike(E example, int start, int max, SingularAttribute<E, ?>... attributes); @SuppressWarnings("unchecked") @Override List<E> findAll(); @SuppressWarnings("unchecked") @Override List<E> findAll(int start, int max); @Override Long count(); @Override Long count(E example, SingularAttribute<E, ?>... attributes); @Override Long countLike(E example, SingularAttribute<E, ?>... attributes); @SuppressWarnings("unchecked") @Override PK getPrimaryKey(E entity); @Override @RequiresTransaction void remove(E entity); @Override @RequiresTransaction void removeAndFlush(E entity); @Override @RequiresTransaction void attachAndRemove(E entity); @Override @RequiresTransaction void flush(); EntityManager entityManager(); CriteriaQuery<E> criteriaQuery(); TypedQuery<E> typedQuery(String qlString); @SuppressWarnings("unchecked") Class<E> entityClass(); String tableName(); String entityName(); }
@Test public void should_remove_and_flush() { Simple simple = testData.createSimple("testRemoveAndFlush"); repo.removeAndFlush(simple); Simple lookup = getEntityManager().find(Simple.class, simple.getId()); assertNull(lookup); }
EntityRepositoryHandler implements EntityRepository<E, PK>, DelegateQueryHandler { @SuppressWarnings("unchecked") @Override public PK getPrimaryKey(E entity) { return (PK) persistenceUnitUtil().getIdentifier(entity); } @Override @RequiresTransaction E save(E entity); @Override @RequiresTransaction E saveAndFlush(E entity); @Override @RequiresTransaction E saveAndFlushAndRefresh(E entity); @Override @RequiresTransaction void refresh(E entity); @Override E findBy(PK primaryKey); @Override Optional<E> findOptionalBy(PK primaryKey); @Override List<E> findBy(E example, SingularAttribute<E, ?>... attributes); @Override List<E> findBy(E example, int start, int max, SingularAttribute<E, ?>... attributes); @Override List<E> findByLike(E example, SingularAttribute<E, ?>... attributes); @Override List<E> findByLike(E example, int start, int max, SingularAttribute<E, ?>... attributes); @SuppressWarnings("unchecked") @Override List<E> findAll(); @SuppressWarnings("unchecked") @Override List<E> findAll(int start, int max); @Override Long count(); @Override Long count(E example, SingularAttribute<E, ?>... attributes); @Override Long countLike(E example, SingularAttribute<E, ?>... attributes); @SuppressWarnings("unchecked") @Override PK getPrimaryKey(E entity); @Override @RequiresTransaction void remove(E entity); @Override @RequiresTransaction void removeAndFlush(E entity); @Override @RequiresTransaction void attachAndRemove(E entity); @Override @RequiresTransaction void flush(); EntityManager entityManager(); CriteriaQuery<E> criteriaQuery(); TypedQuery<E> typedQuery(String qlString); @SuppressWarnings("unchecked") Class<E> entityClass(); String tableName(); String entityName(); }
@Test public void should_return_entity_primary_key() { Simple simple = testData.createSimple("should_return_entity_primary_key"); Long id = simple.getId(); Long primaryKey = repo.getPrimaryKey(simple); assertNotNull(primaryKey); assertEquals(id, primaryKey); } @Test public void should_return_null_primary_key() { Simple simple = new Simple("should_return_null_primary_key"); Long primaryKey = repo.getPrimaryKey(simple); assertNull(primaryKey); } @Test public void should_return_entity_primary_key_detached_entity() { Simple simple = testData.createSimple("should_return_entity_primary_key"); Long id = simple.getId(); getEntityManager().detach(simple); Long primaryKey = repo.getPrimaryKey(simple); assertNotNull(primaryKey); assertEquals(id, primaryKey); }
AuditEntityListener { @PrePersist public void persist(Object entity) { BeanManager beanManager = BeanManagerProvider.getInstance().getBeanManager(); Set<Bean<?>> beans = beanManager.getBeans(PrePersistAuditListener.class); for (Bean<?> bean : beans) { PrePersistAuditListener result = (PrePersistAuditListener) beanManager.getReference( bean, PrePersistAuditListener.class, beanManager.createCreationalContext(bean)); result.prePersist(entity); } } @PrePersist void persist(Object entity); @PreUpdate void update(Object entity); }
@Test public void should_set_creation_date() throws Exception { AuditedEntity entity = new AuditedEntity(); getEntityManager().persist(entity); getEntityManager().flush(); assertNotNull(entity.getCreated()); assertNotNull(entity.getModified()); assertEquals(entity.getCreated().getTime(), entity.getModified()); } @Test public void should_set_modification_date() throws Exception { AuditedEntity entity = new AuditedEntity(); getEntityManager().persist(entity); getEntityManager().flush(); entity = getEntityManager().find(AuditedEntity.class, entity.getId()); entity.setName("test"); getEntityManager().flush(); assertNotNull(entity.getGregorianModified()); assertNotNull(entity.getTimestamp()); } @Test public void should_set_changing_principal() { AuditedEntity entity = new AuditedEntity(); getEntityManager().persist(entity); getEntityManager().flush(); entity = getEntityManager().find(AuditedEntity.class, entity.getId()); entity.setName("test"); getEntityManager().flush(); assertNotNull(entity.getChanger()); assertEquals(who, entity.getChanger()); assertNotNull(entity.getPrincipal()); assertEquals(who, entity.getPrincipal().getName()); assertNotNull(entity.getChangerOnly()); assertEquals(who, entity.getChangerOnly()); assertNotNull(entity.getChangerOnlyPrincipal()); assertEquals(who, entity.getChangerOnlyPrincipal().getName()); } @Test public void should_set_creating_principal() { AuditedEntity entity = new AuditedEntity(); getEntityManager().persist(entity); getEntityManager().flush(); assertNotNull(entity.getCreator()); assertEquals(who, entity.getCreator()); assertNotNull(entity.getCreatorPrincipal()); assertEquals(who, entity.getCreatorPrincipal().getName()); assertNotNull(entity.getChanger()); assertEquals(who, entity.getChanger()); assertNotNull(entity.getPrincipal()); assertEquals(who, entity.getPrincipal().getName()); assertNull(entity.getChangerOnly()); assertNull(entity.getChangerOnlyPrincipal()); }