<commit_before>package org.sagebionetworks.bridge.sdk.integration;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.sagebionetworks.bridge.rest.model.ContactRole.PRINCIPAL_INVESTIGATOR;
import static org.sagebionetworks.bridge.rest.model.ContactRole.TECHNICAL_SUPPORT;
import static org.sagebionetworks.bridge.rest.model.Role.STUDY_COORDINATOR;
import static org.sagebionetworks.bridge.rest.model.StudyPhase.DESIGN;
import static org.sagebionetworks.bridge.rest.model.StudyPhase.IN_FLIGHT;
import static org.sagebionetworks.bridge.sdk.integration.Tests.ORG_ID_1;
import static org.sagebionetworks.bridge.sdk.integration.Tests.ORG_ID_2;
import static org.sagebionetworks.bridge.sdk.integration.Tests.PASSWORD;
import static org.sagebionetworks.bridge.sdk.integration.Tests.STUDY_ID_1;
import static org.sagebionetworks.bridge.sdk.integration.Tests.STUDY_ID_2;
import static org.sagebionetworks.bridge.util.IntegTestUtils.SAGE_ID;
import static org.sagebionetworks.bridge.util.IntegTestUtils.TEST_APP_ID;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.joda.time.DateTime;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import org.sagebionetworks.bridge.rest.RestUtils;
import org.sagebionetworks.bridge.rest.api.ForAdminsApi;
import org.sagebionetworks.bridge.rest.api.OrganizationsApi;
import org.sagebionetworks.bridge.rest.api.ParticipantsApi;
import org.sagebionetworks.bridge.rest.api.StudiesApi;
import org.sagebionetworks.bridge.rest.exceptions.EntityNotFoundException;
import org.sagebionetworks.bridge.rest.exceptions.UnauthorizedException;
import org.sagebionetworks.bridge.rest.model.Contact;
import org.sagebionetworks.bridge.rest.model.OrganizationList;
import org.sagebionetworks.bridge.rest.model.Role;
import org.sagebionetworks.bridge.rest.model.SignUp;
import org.sagebionetworks.bridge.rest.model.Study;
import org.sagebionetworks.bridge.rest.model.StudyList;
import org.sagebionetworks.bridge.rest.model.StudyPhase;
import org.sagebionetworks.bridge.rest.model.VersionHolder;
import org.sagebionetworks.bridge.user.TestUserHelper;
import org.sagebionetworks.bridge.user.TestUserHelper.TestUser;
import org.sagebionetworks.bridge.util.IntegTestUtils;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;

public class StudyTest {
    
    private List<String> studyIdsToDelete = new ArrayList<>();
    private List<String> userIdsToDelete = new ArrayList<>();
    private TestUser testResearcher;
    private TestUser admin;
    
    @Before
    public void before() throws Exception {
        admin = TestUserHelper.getSignedInAdmin();
        testResearcher = TestUserHelper.createAndSignInUser(StudyTest.class, false, Role.RESEARCHER);
    }
    
    @After
    public void deleteResearcher() throws Exception {
        if (testResearcher != null) {
            testResearcher.signOutAndDeleteUser();
        }
    }
    
    @After
    public void after() throws Exception {
        ForAdminsApi adminsApi = admin.getClient(ForAdminsApi.class);
        for (String userId : userIdsToDelete) {
            try {
                adminsApi.deleteUser(userId).execute();
            } catch(EntityNotFoundException e) {
            }
        }
        for (String studyId : studyIdsToDelete) {
            try {
                adminsApi.deleteStudy(studyId, true).execute();    
            } catch(EntityNotFoundException e) {
            }
        }
    }

    @Test
    public void existingStudiesAreLegacy() throws Exception {
        StudiesApi studiesApi = admin.getClient(StudiesApi.class);

        Study study = studiesApi.getStudy(STUDY_ID_1).execute().body();
        assertEquals(StudyPhase.LEGACY, study.getPhase());
    }
    
    @SuppressWarnings("unchecked")
    @Test
    public void test() throws IOException {
        StudiesApi studiesApi = admin.getClient(StudiesApi.class);
        
        int initialCount = studiesApi.getStudies(null, null, false).execute().body().getItems().size();
        
        Map<String,String> map = new HashMap<>();
        map.put("enrollmentType", "byExternalId");
        
        String id = Tests.randomIdentifier(StudyTest.class);
        Study study = new Study().identifier(id).clientData(map).name("Study " + id);
        
        // We had an issue where you could not store two contacts with the same
        // name; verify this restriction has been fixed.
        String contactEmail = IntegTestUtils.makeEmail(StudyTest.class);
        Contact contact1 = new Contact()
                .role(PRINCIPAL_INVESTIGATOR)
                .name("<NAME>")
                .affiliation("Miskatonic University")
                .email(contactEmail);
        Contact contact2 = new Contact()
                .role(TECHNICAL_SUPPORT)
                .name("<NAME>")
                .affiliation("Miskatonic University")
                .email(contactEmail);
        study.contacts(ImmutableList.of(contact1, contact2));
        
        VersionHolder holder = studiesApi.createStudy(study).execute().body();
        study.setVersion(holder.getVersion());
        studyIdsToDelete.add(id);
        
        Study retrieved = studiesApi.getStudy(id).execute().body();
        assertEquals(id, retrieved.getIdentifier());
        assertEquals("Study " + id, retrieved.getName());
        assertEquals(DESIGN, retrieved.getPhase());
        assertTrue(retrieved.getCreatedOn().isAfter(DateTime.now().minusHours(1)));
        assertTrue(retrieved.getModifiedOn().isAfter(DateTime.now().minusHours(1)));
        
        Contact retrievedContact1 = retrieved.getContacts().get(0);
        assertEquals(PRINCIPAL_INVESTIGATOR, retrievedContact1.getRole());
        assertEquals("<NAME>", retrievedContact1.getName());
        assertEquals("Miskatonic University", retrievedContact1.getAffiliation());
        assertEquals(contactEmail, retrievedContact1.getEmail());
        
        Contact retrievedContact2 = retrieved.getContacts().get(1);
        assertEquals(TECHNICAL_SUPPORT, retrievedContact2.getRole());
        assertEquals("<NAME>", retrievedContact2.getName());
        assertEquals("Miskatonic University", retrievedContact2.getAffiliation());
        assertEquals(contactEmail, retrievedContact2.getEmail());
        
        Map<String,String> theMap = RestUtils.toType(study.getClientData(), Map.class);
        assertEquals("byExternalId", theMap.get("enrollmentType"));
        
        OrganizationList orgList = studiesApi.getSponsors(id, 0, 100).execute().body();
        assertTrue(orgList.getItems().stream().anyMatch(org -> org.getIdentifier().equals(SAGE_ID)));
        
        DateTime lastModified1 = retrieved.getModifiedOn();
        
        study.name("New test name " + id);
        study.phase(IN_FLIGHT); // this cannot be changed
        VersionHolder holder2 = studiesApi.updateStudy(id, study).execute().body();
        assertNotEquals(holder.getVersion(), holder2.getVersion());
        
        Study retrieved2 = studiesApi.getStudy(id).execute().body();
        assertEquals("New test name " + id, retrieved2.getName());
        assertEquals(DESIGN, retrieved2.getPhase());
        assertNotEquals(lastModified1, retrieved2.getModifiedOn());
        <commit_msg>Add more field tests<commit_after>package org.sagebionetworks.bridge.sdk.integration;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.sagebionetworks.bridge.rest.model.ContactRole.PRINCIPAL_INVESTIGATOR;
import static org.sagebionetworks.bridge.rest.model.ContactRole.TECHNICAL_SUPPORT;
import static org.sagebionetworks.bridge.rest.model.IrbDecisionType.EXEMPT;
import static org.sagebionetworks.bridge.rest.model.Role.STUDY_COORDINATOR;
import static org.sagebionetworks.bridge.rest.model.StudyPhase.DESIGN;
import static org.sagebionetworks.bridge.rest.model.StudyPhase.IN_FLIGHT;
import static org.sagebionetworks.bridge.sdk.integration.Tests.ORG_ID_1;
import static org.sagebionetworks.bridge.sdk.integration.Tests.ORG_ID_2;
import static org.sagebionetworks.bridge.sdk.integration.Tests.PASSWORD;
import static org.sagebionetworks.bridge.sdk.integration.Tests.STUDY_ID_1;
import static org.sagebionetworks.bridge.sdk.integration.Tests.STUDY_ID_2;
import static org.sagebionetworks.bridge.util.IntegTestUtils.SAGE_ID;
import static org.sagebionetworks.bridge.util.IntegTestUtils.TEST_APP_ID;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import org.sagebionetworks.bridge.rest.RestUtils;
import org.sagebionetworks.bridge.rest.api.ForAdminsApi;
import org.sagebionetworks.bridge.rest.api.OrganizationsApi;
import org.sagebionetworks.bridge.rest.api.ParticipantsApi;
import org.sagebionetworks.bridge.rest.api.StudiesApi;
import org.sagebionetworks.bridge.rest.exceptions.EntityNotFoundException;
import org.sagebionetworks.bridge.rest.exceptions.UnauthorizedException;
import org.sagebionetworks.bridge.rest.model.Contact;
import org.sagebionetworks.bridge.rest.model.OrganizationList;
import org.sagebionetworks.bridge.rest.model.Role;
import org.sagebionetworks.bridge.rest.model.SignUp;
import org.sagebionetworks.bridge.rest.model.Study;
import org.sagebionetworks.bridge.rest.model.StudyList;
import org.sagebionetworks.bridge.rest.model.StudyPhase;
import org.sagebionetworks.bridge.rest.model.VersionHolder;
import org.sagebionetworks.bridge.user.TestUserHelper;
import org.sagebionetworks.bridge.user.TestUserHelper.TestUser;
import org.sagebionetworks.bridge.util.IntegTestUtils;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;

public class StudyTest {
    
    private List<String> studyIdsToDelete = new ArrayList<>();
    private List<String> userIdsToDelete = new ArrayList<>();
    private TestUser testResearcher;
    private TestUser admin;
    
    @Before
    public void before() throws Exception {
        admin = TestUserHelper.getSignedInAdmin();
        testResearcher = TestUserHelper.createAndSignInUser(StudyTest.class, false, Role.RESEARCHER);
    }
    
    @After
    public void deleteResearcher() throws Exception {
        if (testResearcher != null) {
            testResearcher.signOutAndDeleteUser();
        }
    }
    
    @After
    public void after() throws Exception {
        ForAdminsApi adminsApi = admin.getClient(ForAdminsApi.class);
        for (String userId : userIdsToDelete) {
            try {
                adminsApi.deleteUser(userId).execute();
            } catch(EntityNotFoundException e) {
            }
        }
        for (String studyId : studyIdsToDelete) {
            try {
                adminsApi.deleteStudy(studyId, true).execute();    
            } catch(EntityNotFoundException e) {
            }
        }
    }

    @Test
    public void existingStudiesAreLegacy() throws Exception {
        StudiesApi studiesApi = admin.getClient(StudiesApi.class);

        Study study = studiesApi.getStudy(STUDY_ID_1).execute().body();
        assertEquals(StudyPhase.LEGACY, study.getPhase());
    }
    
    @SuppressWarnings("unchecked")
    @Test
    public void test() throws IOException {
        StudiesApi studiesApi = admin.getClient(StudiesApi.class);
        
        int initialCount = studiesApi.getStudies(null, null, false).execute().body().getItems().size();
        
        Map<String,String> map = new HashMap<>();
        map.put("enrollmentType", "byExternalId");
        
        String id = Tests.randomIdentifier(StudyTest.class);
        Study study = new Study().identifier(id).clientData(map).name("Study " + id);
        
        // IRB information
        study.setIrbName("IRB Name");
        study.setIrbProtocolName("IRB Protocol Name");
        study.setIrbProtocolId("123");
        study.setIrbDecisionType(EXEMPT);
        study.setIrbDecisionOn(LocalDate.parse("2012-12-12"));
        study.setIrbExpiresOn(LocalDate.parse("2013-12-12"));
        
        // We had an issue where you could not store two contacts with the same
        // name; verify this restriction has been fixed.
        String contactEmail = IntegTestUtils.makeEmail(StudyTest.class);
        Contact contact1 = new Contact()
                .role(PRINCIPAL_INVESTIGATOR)
                .name("<NAME>")
                .affiliation("Miskatonic University")
                .email(contactEmail);
        Contact contact2 = new Contact()
                .role(TECHNICAL_SUPPORT)
                .name("<NAME>")
                .affiliation("Miskatonic University")
                .email(contactEmail);
        study.contacts(ImmutableList.of(contact1, contact2));
        
        VersionHolder holder = studiesApi.createStudy(study).execute().body();
        study.setVersion(holder.getVersion());
        studyIdsToDelete.add(id);
        
        Study retrieved = studiesApi.getStudy(id).execute().body();
        assertEquals(id, retrieved.getIdentifier());
        assertEquals("Study " + id, retrieved.getName());
        assertEquals(DESIGN, retrieved.getPhase());
        assertTrue(retrieved.getCreatedOn().isAfter(DateTime.now().minusHours(1)));
        assertTrue(retrieved.getModifiedOn().isAfter(DateTime.now().minusHours(1)));
        
        assertEquals("IRB Name", retrieved.getIrbName());
        assertEquals("IRB Protocol Name", retrieved.getIrbProtocolName());
        assertEquals(retrieved.getIrbProtocolId(), "123");
        assertEquals(retrieved.getIrbDecisionType(), EXEMPT);
        assertEquals(retrieved.getIrbDecisionOn(), LocalDate.parse("2012-12-12"));
        assertEquals(retrieved.getIrbExpiresOn(), LocalDate.parse("2013-12-12"));
        
        Contact retrievedContact1 = retrieved.getContacts().get(0);
        assertEquals(PRINCIPAL_INVESTIGATOR, retrievedContact1.getRole());
        assertEquals("<NAME>", retrievedContact1.getName());
        assertEquals("Miskatonic University", retrievedContact1.getAffiliation());
        assertEquals(contactEmail, retrievedContact1.getEmail());
        
        Contact retrievedContact2 = retrieved.getContacts().get(1);
        assertEquals(TECHNICAL_SUPPORT, retrievedContact2.getRole());
        assertEquals("<NAME>", retrievedContact2.getName());
        assertEquals("Miskatonic University", retrievedContact2.getAffiliation());
        assertEquals(contactEmail, retrievedContact2.getEmail());
        
        Map<String,String> theMap = RestUtils.toType(study.getClientData(), Map.class);
        assertEquals("byExternalId", theMap.get("enrollmentType"));
        
        OrganizationList orgList = studiesApi.getSponsors(id, 0, 100).execute().body();
        assertTrue(orgList.getItems().stream().anyMatch(org -> org.getIdentifier().equals(SAGE_ID)));
        
        DateTime lastModified1 = retrieved.getModifiedOn();
        
        study.name("New test name " + id);
        study.phase(IN_FLIGHT); // this cannot be changed
        VersionHolder holder2 = studiesApi.updateStudy(id, study).execute().body();
        assertNotEquals(holder.getVersion(), holder2.getVersion());
        
        Study retrieved2 = studiesApi.getStudy(id).execute().body();
        assertEquals("New test name " + id, retrieved2.getName());
        assertEquals(DESIGN, retrieved2.getPhase());
        assertNotEquals(lastModified1, retrieved2.getModifiedOn());
        
{'fraction_non_alphanumeric': 0.11100699650174913, 'fraction_numerical': 0.006746626686656672, 'mean_word_length': 3.5570737261599774, 'pattern_counts': {'":': 0, '<': 25, '<?xml version=': 0, '>': 27, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1566843', 'n_tokens_mistral': 4765, 'n_tokens_neox': 4599, 'n_words': 740}