From c4177cf48755507efb350ed54cb9fede0de50387 Mon Sep 17 00:00:00 2001
From: Vladimir Eliezer Tokarev <vladimirelitokarev@gmail.com>
Date: Sat, 30 Jan 2016 09:19:25 -0800
Subject: [PATCH] Added testing to the SimpleRegistryTest class The Test
 checking that SetVoter AddVoter AddToGroup RemoveFromGroup methods working.

---
 .../src/main/java/meerkat/SimpleRegistry.java |  33 +++---
 .../java/meerkat/VoterRegistryMessage.java    |   3 +-
 .../java/util/CollectionMessagesUtils.java    |   7 +-
 .../src/test/java/SimpleRegistryTest.java     | 112 ++++++++++--------
 4 files changed, 86 insertions(+), 69 deletions(-)

diff --git a/voter-registry/src/main/java/meerkat/SimpleRegistry.java b/voter-registry/src/main/java/meerkat/SimpleRegistry.java
index 9f65967..9d2f473 100644
--- a/voter-registry/src/main/java/meerkat/SimpleRegistry.java
+++ b/voter-registry/src/main/java/meerkat/SimpleRegistry.java
@@ -70,19 +70,23 @@ public class SimpleRegistry  implements RegistryInstance{
      * Gets messages that have the wanted id tag and have or the ADD_TO_GROUP_TAG or REMOVE_FROM_GROUP_TAG
      *
      * @param tags the tags based on which the messages will be filtered
-     * @return List<BulletinBoardMessage>
+     * @return MessageFilterList.
      */
-    private List<BulletinBoardMessage> GetRelevantMessages(List<String> tags) {
-        MessageFilterList.Builder filters =
-                MessageFilterList.newBuilder();
+    public MessageFilterList GetRelevantMessages(List<String> tags) {
+        MessageFilterList.Builder filters = MessageFilterList.newBuilder();
+
+        if (tags == null){
+            return filters.build();
+        }
 
         for (String tag : tags) {
-            MessageFilter.Builder idFilter =
-                    MessageFilter.newBuilder().setTag(tag).setType(BulletinBoardAPI.FilterType.TAG);
+            MessageFilter.Builder filter =
+                    MessageFilter.newBuilder().setTag(tag)
+                            .setType(BulletinBoardAPI.FilterType.TAG);
 
-            filters.addFilter(idFilter);
+            filters.addFilter(filter);
         }
-        return communicator.readMessages(filters.build());
+        return filters.build();
     }
 
     /**
@@ -92,9 +96,8 @@ public class SimpleRegistry  implements RegistryInstance{
      * @return List<VoterRegistryMessage>
      */
     private List<VoterRegistryMessage> GetRelevantVoterRegistryMessages(List<String> tags) throws InvalidProtocolBufferException {
-        List<BulletinBoardMessage> relevantMessages = GetRelevantMessages(tags);
-        List<UnsignedBulletinBoardMessage> messages =
-                GetUnsignedBulletinBoardMessages(relevantMessages);
+        List<BulletinBoardMessage> relevantMessages = communicator.readMessages(GetRelevantMessages(tags));
+        List<UnsignedBulletinBoardMessage> messages = GetUnsignedBulletinBoardMessages(relevantMessages);
         return ConvertToVoterRegistryMessages(messages);
     }
 
@@ -141,7 +144,7 @@ public class SimpleRegistry  implements RegistryInstance{
                 UnsignedBulletinBoardMessage.newBuilder()
                         .addTag(RegistryTags.ID_TAG + voterID)
                         .addTag(RegistryTags.GROUP_ID_TAG + groupID)
-                        .addTag(RegistryTags.GROUP_ACTION_TAG .toString()+ RegistryTags.REMOVE_FROM_GROUP_TAG)
+                        .addTag(RegistryTags.GROUP_ACTION_TAG.toString()+ RegistryTags.REMOVE_FROM_GROUP_TAG)
                         .addTag(RegistryTags.ACTION_TIMESTAMP_TAG + AccurateTimestamp.GetCurrentTimestampString());
 
         callback.HandleVoterRemovedFromGroup(SafePost(CreateBulletinBoardMessage(basicMessage.build())));
@@ -160,9 +163,7 @@ public class SimpleRegistry  implements RegistryInstance{
     public void GetGroups(String id, RegistryCallBack callback) {
         try {
             List<String> GroupsActionsTags = new ArrayList<String>() {{
-                add(RegistryTags.ID_TAG + id);
-                add(RegistryTags.GROUP_ACTION_TAG .toString() + RegistryTags.REMOVE_FROM_GROUP_TAG);
-                add(RegistryTags.GROUP_ACTION_TAG.toString() + RegistryTags.ADD_TO_GROUP_TAG);
+               add(RegistryTags.GROUP_ID_TAG + id);
             }};
             List<VoterRegistryMessage> voterRegistryMessages = GetRelevantVoterRegistryMessages(GroupsActionsTags);
 
@@ -185,7 +186,7 @@ public class SimpleRegistry  implements RegistryInstance{
             VoterRegistryMessage LatestMessage = GetLatestMessage(voterRegistryMessages);
 
             callback.HandleVoterInfo(LatestMessage.tagsToStringList());
-        } catch (InvalidProtocolBufferException | ParseException e) {
+        } catch (InvalidProtocolBufferException | ParseException e ){
             callback.HandleVoterInfo(null);
         }
     }
diff --git a/voter-registry/src/main/java/meerkat/VoterRegistryMessage.java b/voter-registry/src/main/java/meerkat/VoterRegistryMessage.java
index b93cc73..052cd0f 100644
--- a/voter-registry/src/main/java/meerkat/VoterRegistryMessage.java
+++ b/voter-registry/src/main/java/meerkat/VoterRegistryMessage.java
@@ -47,7 +47,8 @@ public class VoterRegistryMessage {
         for (String tag : base.getTagList()) {
             if (tag.contains(RegistryTags.ACTION_TIMESTAMP_TAG.toString())) {
                 String[] tagParts = tag.split(" ");
-                String timestamp = tagParts[tagParts.length - 1];
+
+                String timestamp = tagParts[tagParts.length - 2] + " " + tagParts[tagParts.length - 1];
                 return AccurateTimestamp.GetTimestampFromString(timestamp);
             }
         }
diff --git a/voter-registry/src/main/java/util/CollectionMessagesUtils.java b/voter-registry/src/main/java/util/CollectionMessagesUtils.java
index 3586014..f0d454b 100644
--- a/voter-registry/src/main/java/util/CollectionMessagesUtils.java
+++ b/voter-registry/src/main/java/util/CollectionMessagesUtils.java
@@ -37,7 +37,6 @@ public abstract class CollectionMessagesUtils {
         Map<String, VoterRegistryMessage> groupIdToMessage = new HashMap<>();
 
         // iterate trough all the messages and put into the map the last updated groups actions
-
         for (VoterRegistryMessage message : messages) {
             String groupId = message.GetWantedTagFromBasicMessage(RegistryTags.GROUP_ID_TAG);
             VoterRegistryMessage temp = groupIdToMessage.get(groupId);
@@ -47,6 +46,7 @@ public abstract class CollectionMessagesUtils {
                     groupIdToMessage.put(groupId, message);
                 }
             }
+            groupIdToMessage.put(groupId, message);
         }
         return groupIdToMessage;
     }
@@ -57,7 +57,7 @@ public abstract class CollectionMessagesUtils {
      * @return List<String>
      */
      public static List<String> GetListOfGroupIds(Map<String, VoterRegistryMessage>  groupIdToMessage)  {
-        List<String> groupsIds = new ArrayList<>();
+         List<String> groupsIds = new ArrayList<>();
 
          groupIdToMessage.values().stream().filter(VoterRegistryMessage::IsGroupAdding).forEach(message -> {
              String groupId = message.GetWantedTagFromBasicMessage(RegistryTags.GROUP_ID_TAG);
@@ -78,6 +78,9 @@ public abstract class CollectionMessagesUtils {
     }
 
     public static VoterRegistryMessage GetLatestMessage(List<VoterRegistryMessage> messages) throws ParseException {
+        if (messages.size() == 0 ){
+            return null;
+        }
         VoterRegistryMessage LatestMessage = messages.get(0);
 
         for (VoterRegistryMessage message : messages) {
diff --git a/voter-registry/src/test/java/SimpleRegistryTest.java b/voter-registry/src/test/java/SimpleRegistryTest.java
index 868b57b..b75d8ad 100644
--- a/voter-registry/src/test/java/SimpleRegistryTest.java
+++ b/voter-registry/src/test/java/SimpleRegistryTest.java
@@ -36,6 +36,7 @@ public class SimpleRegistryTest extends TestCase {
     private SimpleBulletinBoardClient communicator;
     private static String BULLETIN_BOARD_SERVER_ADDRESS = "http://localhost:8081";
     private SecureRandom random = new SecureRandom();
+    private List<List<String>> votersData;
 
     /**
      * Creates the ElGamal encryption object
@@ -75,6 +76,7 @@ public class SimpleRegistryTest extends TestCase {
     public void setUp() {
         ElGamalSetup();
         CommunicatorSetup();
+        votersData = null;
     }
 
     /**
@@ -92,41 +94,23 @@ public class SimpleRegistryTest extends TestCase {
      * Creates list of lists of strings for different testing purposes
      * @param actionDataNumber number of string in a list
      * @param numberOfInstances number of lists in a list
-     * @return List<List<String>>
+     * @return
      */
-    private List<List<String>> getActionsData(int actionDataNumber, int numberOfInstances)
+    private void setActionsData(int actionDataNumber, int numberOfInstances)
     {
         System.out.println("-   Creating "+ numberOfInstances +" ids and personal data strings for adding different voters.");
+        if (votersData != null){
+            return;
+        }
 
-        List<List<String>> actionData = new ArrayList<>();
+        votersData = new ArrayList<>();
         for (int i = 0 ; i < numberOfInstances ; i++ ){
             List<String> data = new ArrayList<>();
             for (int j = 0 ; j < actionDataNumber ; j++){
                 data.add(new BigInteger(130, random).toString(32));
             }
-            actionData.add(data);
+            votersData.add(data);
         }
-        return actionData;
-    }
-
-    /**
-     * Create Message filter list from list of tags
-     * @param tags list of string with wanted tags
-     * @return MessageFilterList
-     */
-    private BulletinBoardAPI.MessageFilterList createFiltersFromTags(List<String> tags){
-        if (tags == null){
-            return BulletinBoardAPI.MessageFilterList.newBuilder().build();
-        }
-
-        BulletinBoardAPI.MessageFilterList.Builder filters =  BulletinBoardAPI.MessageFilterList.newBuilder();
-
-        for (String tag : tags) {
-            filters.addFilter(BulletinBoardAPI.MessageFilter.newBuilder()
-                    .setTag(tag).setType(BulletinBoardAPI.FilterType.TAG));
-        }
-
-        return filters.build();
     }
 
     /**
@@ -136,15 +120,14 @@ public class SimpleRegistryTest extends TestCase {
      * @return int
      * @throws InvalidProtocolBufferException
      */
-    private int countActualAddedMessages(List<List<String>> votersData, List<String> tags) throws InvalidProtocolBufferException {
+    private int countActualAddedMessages(List<List<String>> votersData, List<String> tags, SimpleRegistry registry) throws InvalidProtocolBufferException {
         System.out.println("-   Check that the server have the new voters data:");
 
-        BulletinBoardAPI.MessageFilterList filters = createFiltersFromTags(tags);
+        BulletinBoardAPI.MessageFilterList filters = registry.GetRelevantMessages(tags);
         List<VoterRegistryMessage> messages =
                 ConvertToVoterRegistryMessages(GetUnsignedBulletinBoardMessages(communicator.readMessages(filters)));
 
-        System.out.println(messages.size() + " asdasasdasdasasasdaasddas");
-
+        assert messages.size() > 0 : " The filtered messages are empty ( wrong filtering or server down)";
         int addedMessagesCounter = 0;
 
         for (List<String> voterData : votersData) {
@@ -199,12 +182,13 @@ public class SimpleRegistryTest extends TestCase {
      * @param numberOfParamsToPass the number of params to pass to the methodToCheck
      * @param numberOfChecks the amount of checks to run
      * @param tags list of String that represent the tags to filter on the messages
+     * @return Returns the information that was send in the created messages
      * @throws InvalidProtocolBufferException
      */
-    private  void checkMessagesPostedSuccessfully(String methodToCheck, int numberOfParamsToPass, int numberOfChecks, List<String> tags) throws InvalidProtocolBufferException {
+    private  List<List<String>> checkMessagesPostedSuccessfully(String methodToCheck, int numberOfParamsToPass, int numberOfChecks, List<String> tags) throws InvalidProtocolBufferException {
         SimpleRegistryCallBackHandler handler = RegistryAnswersHandlerSetup();
         System.out.println("Starting testing the " + methodToCheck + " capability.");
-        List<List<String>> votersData = getActionsData(numberOfParamsToPass, numberOfChecks);
+        setActionsData(numberOfParamsToPass, numberOfChecks);
 
         SimpleRegistry registry = new SimpleRegistry(signatory, communicator);
 
@@ -213,12 +197,13 @@ public class SimpleRegistryTest extends TestCase {
            CallWantedMethod(methodToCheck, numberOfParamsToPass, handler, registry, voterData);
         }
 
-        System.out.println("-   Check that for every voter added, the callback have been called:");
+        System.out.println("-   Check that for every data added, the callback have been called:");
         assertEquals(numberOfChecks, handler.counter);
-        int addedMessagesCounter = countActualAddedMessages(votersData, tags);
+        int addedMessagesCounter = countActualAddedMessages(votersData, tags, registry);
 
         assert addedMessagesCounter == numberOfChecks : "The number of added messages actually is " + addedMessagesCounter;
         System.out.println("Ended addVoter testing.");
+        return votersData;
     }
 
     /**
@@ -244,31 +229,58 @@ public class SimpleRegistryTest extends TestCase {
         checkMessagesPostedSuccessfully("RemoveFromGroup", 2, 3, null);
     }
 
-    /**
-     * Test that remove from group creates correct bulletin board message and removes the user from a group
-     */
-    public void testGetGroups() {
-        // print start of gorups testing
-        // Create Registry check creation
-        // Add to X groups remove y group and z group
-        // for every action check that it happened
-        // count the number of callback activated
-        // get the relevant groups
-        // check they are right
-        // print and of groups
-    }
-
     /**
      * Test that get groups retrieves the right groups the user are in
      */
     public void testAddToGroup() throws InvalidProtocolBufferException {
-        checkMessagesPostedSuccessfully("AddToGroup", 2, 3, null);
+        checkMessagesPostedSuccessfully("AddToGroup", 2, 4, null);
     }
 
+    /**
+     * Test that remove from group creates correct bulletin board message and removes the user from a group
+     */
+    public void testGetGroups() throws InvalidProtocolBufferException, InterruptedException {
+        System.out.println("Starting testing the GetGroups capability.");
+        List<List<String>> votersData = checkMessagesPostedSuccessfully("AddToGroup", 2, 3, null);
+
+        SimpleRegistry registry = new SimpleRegistry(signatory, communicator);
+        SimpleRegistryCallBackHandler handler = RegistryAnswersHandlerSetup();
+
+        System.out.println("-   Checks that every group id we added to every voter really exists:");
+        for (List<String> voterData : votersData){
+            registry.GetGroups(voterData.get(1), handler);
+
+            assert handler.ActionSucceed : " The SimpleRegistry could not complete the GetGroups action ";
+            assert handler.WantedInformation.contains(RegistryTags.GROUP_ID_TAG + voterData.get(1))
+                    : " The SimpleRegistry cloud not get the right group of the user " + voterData.get(1);
+        }
+        System.out.println("Ended GetGroups testing.");
+    }
+
+
+
     /**
      * Test that the personal data outputted about the user is right
      */
-    public void testGetPersonalIDDetails() {
-        assertEquals(1, null);
+    public void testGetPersonalIDDetails() throws InvalidProtocolBufferException, InterruptedException {
+        System.out.println("Starting testing the GetPersonIDDetails capability:");
+        List<List<String>> addedVotersInformation = checkMessagesPostedSuccessfully("AddVoter", 2, 3,
+                new ArrayList<String>(){{add(RegistryTags.VOTER_ENTRY_TAG.toString());}});
+
+        SimpleRegistry registry = new SimpleRegistry(signatory, communicator);
+        SimpleRegistryCallBackHandler handler = RegistryAnswersHandlerSetup();
+
+        System.out.println("-   Check that every added voter can be retrieved by SimpleRegistry:");
+
+        for (List<String> voterInformation : addedVotersInformation) {
+            registry.GetPersonIDDetails(voterInformation.get(0), handler);
+
+            assert handler.ActionSucceed : " Getting personal data for voter with id : "
+                    + voterInformation.get(0) + " failed";
+            assert handler.WantedInformation.get(0).contains(voterInformation.get(0))
+                    : " Voter with id " + voterInformation.get(0) + " have bot been added to the voter db.";
+        }
+       assert handler.counter == 3 : " The callback method have not been called 3 times";
+       System.out.println("Ended the GetPersonIDDetails capability");
     }
 }