Exemplo n.º 1
0
def test_livesite_main():
    """Tests main when live site is not None"""
    team_map = {
        'team_part_id': '1234',
        'team_admin_id': '2345',
        'team_prereg_id': '3456',
        'team_org_id': '4567'
    }
    teamid = str(uuid.uuid1())
    project = str(uuid.uuid1())
    chalid = str(uuid.uuid1())
    etag = str(uuid.uuid1())
    challenge_obj = Challenge(id=chalid,
                              projectId=project,
                              etag=etag,
                              participantTeamId=teamid)
    proj = synapseclient.Project(project, id="syn1234")
    wiki = synapseclient.Wiki(title='', owner=proj, markdown='')
    challenge_name = str(uuid.uuid1())
    with patch.object(createchallenge, "_create_teams",
                      return_value=team_map),\
         patch.object(createchallenge, "create_project",
                      return_value=proj) as patch_create_proj,\
         patch.object(SYN, "get", return_value=proj),\
         patch.object(permissions,
                      "set_entity_permissions") as patch_set_perms,\
         patch.object(createchallenge, "create_challenge_widget",
                      return_value=challenge_obj),\
         patch.object(createchallenge, "create_evaluation_queue"),\
         patch.object(createchallenge, "check_existing_and_delete_wiki"),\
         patch.object(synapseutils, "copyWiki",
                      return_value=[{'id': 'foo'}]),\
         patch.object(SYN, "getWiki", return_value=wiki),\
         patch.object(createchallenge, "_update_wikipage_string",
                      return_value=wiki),\
         patch.object(SYN, "store"):
        components = createchallenge.main(SYN,
                                          challenge_name,
                                          live_site="syn123")
        assert patch_set_perms.call_count == 2
        assert patch_create_proj.call_count == 1
        assert components == {
            "live_projectid": proj.id,
            "staging_projectid": proj.id,
            "admin_teamid": '2345',
            "organizer_teamid": '4567',
            "participant_teamid": '1234',
            "preregistrantrant_teamid": '3456'
        }
Exemplo n.º 2
0
 def test_pull_wiki(self):
     """Testing pulling of wiki"""
     wiki_headers = [{"id": "2", "title": "EchoesTest", "parentId": "1"}]
     expected_header = [{
         "id": "2",
         "title": "EchoesTest",
         "parentId": "1",
         "markdown_path": "2-EchoesTest.md"
     }]
     wiki = synapseclient.Wiki(title="Echoes Test",
                               owner="syn22",
                               markdown="test",
                               id="2")
     with patch.object(self.syn, "getWikiHeaders",
                       return_value=wiki_headers) as patch_get_headers,\
          patch.object(self.syn, "getWiki",
                       return_value=wiki) as patch_get_wiki:
         header = challengeutils.wiki.pull_wiki(
             self.syn, "syn1234", workdir=tempfile.gettempdir())
         assert header == expected_header
         patch_get_headers.assert_called_once_with("syn1234")
         patch_get_wiki.assert_called_once_with("syn1234", subpageId="2")
Exemplo n.º 3
0
    def test_push_wiki(self):
        """Testing push wiki"""
        wiki_obj = synapseclient.Wiki(title="Echoes",
                                      owner="syn22",
                                      markdown="test",
                                      id="44")
        self.wiki_config.append({
            'title': 'Time',
            'parentId': '1',
            'markdown_path': self.file2.name
        })

        expected_header = [{
            'id': '44',
            'title': 'Wish You Were Here',
            'markdown_path': self.file1.name
        }, {
            'id': '2',
            'title': 'Echoes',
            'parentId': '1',
            'markdown_path': self.file2.name
        }, {
            'title': 'Time',
            'parentId': '1',
            'markdown_path': self.file2.name,
            'id': '44'
        }]
        with patch.object(challengeutils.wiki, "read_wiki_config",
                          return_value=self.wiki_config) as patch_read,\
             patch.object(self.syn, "store",
                          return_value=wiki_obj) as patch_store:
            header = challengeutils.wiki.push_wiki(
                self.syn, "syn1234", workdir=tempfile.gettempdir())
            assert header == expected_header
            patch_read.assert_called_once_with(tempfile.gettempdir())
            assert patch_store.call_count == 2
Exemplo n.º 4
0
def test_livesitenone_main():
    """Tests main when live site is None"""
    team_map = {
        'team_part_id': str(uuid.uuid1()),
        'team_admin_id': str(uuid.uuid1()),
        'team_prereg_id': str(uuid.uuid1()),
        'team_org_id': str(uuid.uuid1())
    }
    project = str(uuid.uuid1())
    chalid = str(uuid.uuid1())
    etag = str(uuid.uuid1())
    challenge_name = str(uuid.uuid1())

    challenge_obj = Challenge(id=chalid,
                              projectId=project,
                              etag=etag,
                              participantTeamId=team_map['team_part_id'])
    proj = synapseclient.Project(challenge_name, id=project)
    wiki = synapseclient.Wiki(title='', owner=proj, markdown='')
    # Mock calls
    admin_permission_call = mock.call(SYN,
                                      proj,
                                      team_map['team_admin_id'],
                                      permission_level="admin")
    org_permission_call = mock.call(SYN,
                                    proj,
                                    team_map['team_org_id'],
                                    permission_level="download")
    org_permission_edit = mock.call(SYN,
                                    proj,
                                    team_map['team_org_id'],
                                    permission_level="edit")
    with patch.object(createchallenge, "_create_teams",
                      return_value=team_map) as patch_create_team,\
         patch.object(createchallenge, "create_project",
                      return_value=proj) as patch_create_proj,\
         patch.object(permissions,
                      "set_entity_permissions") as patch_set_perms,\
         patch.object(createchallenge, "create_challenge_widget",
                      return_value=challenge_obj) as patch_create_chal,\
         patch.object(createchallenge,
                      "create_evaluation_queue") as patch_create_queue,\
         patch.object(createchallenge,
                      "check_existing_and_delete_wiki") as patch_exist,\
         patch.object(synapseutils, "copyWiki",
                      return_value=[{'id': 'foo'}]) as patch_synucopywiki,\
         patch.object(SYN, "getWiki", return_value=wiki),\
         patch.object(createchallenge, "_update_wikipage_string",
                      return_value=wiki),\
         patch.object(SYN, "store"):
        createchallenge.main(SYN, challenge_name, live_site=None)
        patch_set_perms.assert_has_calls([
            admin_permission_call, org_permission_call, admin_permission_call,
            org_permission_edit
        ])
        assert patch_create_proj.call_count == 2

        patch_create_chal.assert_called_once_with(SYN, proj,
                                                  team_map['team_part_id'])
        patch_create_queue.assert_called_once_with(
            SYN, '%s Project Submission' % challenge_name,
            'Project Submission', proj.id)
        patch_exist.assert_called_once_with(SYN, proj.id)
        patch_synucopywiki.assert_called_once_with(
            SYN, createchallenge.DREAM_CHALLENGE_TEMPLATE_SYNID, proj.id)
        patch_create_team.assert_called_once_with(SYN, challenge_name)
Exemplo n.º 5
0
def create_live_page(syn, project, teamid):
    live_page_markdown = '## Banner\n\n\n**Pre-Registration Open:**\n**Launch:**\n**Close:**\n\n\n\n${jointeam?teamId=%s&isChallenge=true&isMemberMessage=You are Pre-registered&text=Pre-register&successMessage=Successfully joined&isSimpleRequestButton=true}\n> Number of Pre-registered Participants: ${teammembercount?teamId=%s} \n> Click [here](http://s3.amazonaws.com/geoloc.sagebase.org/%s.html) to see where in the world solvers are coming from. \n\n#### OVERVIEW - high level (same as DREAM website?) - for journalists, funders, and participants\n\n\n#### Challenge Organizers / Scientific Advisory Board:\n\n#### Data Contributors:\n\n#### Journal Partners:\n\n#### Funders and Sponsors:' % (teamid, teamid, teamid)
    syn.store(synapseclient.Wiki(title='', owner=project, markdown=live_page_markdown))
Exemplo n.º 6
0
)
def test__get_obj__entity(obj):
    """Test getting of entities"""
    with patch.object(GET_CLS, "_find_entity_by_name",
                      return_value=obj) as patch_get:
        return_obj = GET_CLS._get_obj(obj)
        patch_get.assert_called_once_with(
            parentid=obj.properties.get("parentId", None),
            entity_name=obj.name,
            concrete_type=obj.properties.concreteType)
        assert obj == return_obj


@pytest.mark.parametrize("obj,get_func",
                         [(synapseclient.Team(name="foo"), "getTeam"),
                          (synapseclient.Wiki(owner="foo"), "getWiki"),
                          (synapseclient.Evaluation(name="foo",
                                                    contentSource="syn123"),
                           "getEvaluationByName")])
def test__get_obj__nonentity(obj, get_func):
    """Test getting of entities"""
    with patch.object(SYN, get_func, return_value=obj) as patch_get:
        return_obj = GET_CLS._get_obj(obj)
        if isinstance(obj, (synapseclient.Team, synapseclient.Evaluation)):
            patch_get.assert_called_once_with(obj.name)
        elif isinstance(obj, synapseclient.Wiki):
            patch_get.assert_called_once_with(obj.ownerId)
        assert return_obj == obj


def test_get_or_create_project__call():
Exemplo n.º 7
0
def createSprint(syn,
                 rallyNumber,
                 sprintLetter,
                 config=CONFIG,
                 otherPermissions=None):

    # Sprint Configuration
    sprintNumber = "%s%s" % (rallyNumber, sprintLetter)
    sprintTitle = "Sprint %s" % (sprintNumber, )
    sprintName = "ki %s" % (sprintTitle, )

    consortium = config.get('consortium', None)
    sprintStart = config.get('sprintStart', None)
    sprintEnd = config.get('sprintEnd', None)

    # Get locations of templates, team IDs, etc.
    rallyAdminProject = syn.get(config['rallyAdminProjectId'])

    rallyAdminTeamId = rallyAdminProject.annotations.rallyAdminTeamId[0]
    rallyTableId = rallyAdminProject.annotations.rallyTableId[0]
    sprintTableId = rallyAdminProject.annotations.sprintTableId[0]
    wikiMasterTemplateId = rallyAdminProject.annotations.wikiMasterTemplateId[
        0]
    taskTableTemplateId = rallyAdminProject.annotations.taskTableTemplateId[0]

    teamPermissionsDict = {
        rallyAdminTeamId: config['rallyAdminTeamPermissions']
    }

    if otherPermissions:
        teamPermissionsDict.update(otherPermissions)

    # This is a Project View (table) of a list of rallies
    # in the HBGDki Working Group Project
    rallyTableSchema = syn.get(rallyTableId)

    # This is a Project View (table) of a list of sprints
    # in the HBGDki Working Group Project and in the Rally Project
    rallySprintTableSchema = syn.get(sprintTableId)

    # The columns in this table for reuse when creating a new one
    # in the Project space
    rallySprintTableColumns = list(syn.getColumns(sprintTableId))

    # all files table in the hbgdki rally working group project
    allFilesWorkingGroupSchema = syn.get(config['allFilesSchemaId'])

    # The columns for a file view that lists all files in a project.
    # This is used for a file view in the HBGDki working group, in the rally
    # project, and in the sprint project
    allFilesTableColumns = list(syn.getColumns(config['allFilesSchemaId']))

    rallyProject = createRally(syn,
                               rallyNumber=rallyNumber,
                               config=config,
                               otherPermissions=otherPermissions)

    # Get the rally team.
    rallyTeam = syn.getTeam(rallyProject.annotations.get('rallyTeam', None)[0])

    # Add the rally team with it's default permissions to
    # the list of permissions to add
    teamPermissionsDict.update(
        {rallyTeam.id: ['DOWNLOAD', 'READ', 'UPDATE', 'CREATE']})

    sprintProject = getSprint(syn,
                              config['rallyAdminProjectId'],
                              rallyNumber=rallyNumber,
                              sprintLetter=sprintLetter)

    if not sprintProject:
        # Create the sprint project
        sprintProject = synapseclient.Project(name=sprintName,
                                              annotations=dict(
                                                  sprintTitle=sprintTitle,
                                                  sprintNumber=sprintNumber,
                                                  rally=rallyNumber,
                                                  rallyId=rallyProject.id,
                                                  sprintStart=sprintStart,
                                                  sprintEnd=sprintEnd,
                                                  consortium=consortium,
                                                  rallyTeam=rallyTeam.id))

        try:
            sprintProject = syn.store(sprintProject, createOrUpdate=False)
        except synapseclient.exceptions.SynapseHTTPError:
            sprintProjectObj = syn.restPOST(
                "/entity/child",
                body=json.dumps({"entityName": sprintProject.name}))
            sprintProject = syn.get(sprintProjectObj['id'])

        # Set permissions for the sprint project
        for teamId, permissions in list(teamPermissionsDict.items()):
            syn.setPermissions(sprintProject,
                               principalId=teamId,
                               accessType=permissions)

        try:
            sprintWiki = syn.getWiki(owner=sprintProject)
        except synapseclient.exceptions.SynapseHTTPError:
            sprintWikiMasterTemplate = syn.get(wikiMasterTemplateId)
            sprintWiki = syn.store(
                synapseclient.Wiki(owner=sprintProject,
                                   markdownFile=sprintWikiMasterTemplate.path))
            sprintWiki.markdown = sprintWiki.markdown.replace(
                'id=123', 'id=%s' % rallyTeam.id)
            sprintWiki.markdown = sprintWiki.markdown.replace(
                'teamId=123', 'teamId=%s' % rallyTeam.id)
            sprintWiki = syn.store(sprintWiki)

        # Add a task table
        templateTaskSchema = syn.get(taskTableTemplateId)  # Template schema

        newTaskSchema = getOrCreateSchema(
            syn,
            parent=sprintProject,
            name="Tasks",
            columns=templateTaskSchema.properties.columnIds)

        wikiHeaders = syn.getWikiHeaders(sprintProject)
        wikiHeaders = [
            x for x in wikiHeaders if x.get('parentId', None) == sprintWiki.id
            and x.get('title', None) == 'Tasks'
        ]

        if not wikiHeaders:
            taskWikiTemplate = syn.get(config['wikiTaskTemplateId'])
            sprintTaskSubwiki = syn.store(
                synapseclient.Wiki(title="Tasks",
                                   owner=sprintProject,
                                   parentWikiId=sprintWiki.id,
                                   markdownFile=taskWikiTemplate.path))
            sprintTaskSubwiki.markdown = sprintTaskSubwiki.markdown.replace(
                'syn00000000', newTaskSchema.id)
            sprintTaskSubwiki = syn.store(sprintTaskSubwiki)

        # Create folders
        for folderName in config['sprintFolders']:
            folder = syn.store(
                synapseclient.Folder(name=folderName, parent=sprintProject))

        # Create a daily checkin discussion post
        forum = syn.restGET("/project/%(projectId)s/forum" %
                            dict(projectId=sprintProject.id))

        for p in config['posts']:
            p['forumId'] = forum.get('id', None)
            try:
                post = syn.restPOST("/thread", body=json.dumps(p))
            except Exception as e:
                logger.error("Error with post: %s (%s)" % (post, e))

        # Add the sprint to the all sprints table in the ki working group project
        rallyAdminSprintTable = syn.get(sprintTableId)
        addToViewScope(rallyAdminSprintTable, sprintProject.id)
        rallyAdminSprintTable = syn.store(rallyAdminSprintTable)

        # Add the files in the rally project to the working group all files view
        allFilesWorkingGroupSchema = syn.get(config['allFilesSchemaId'])
        addToViewScope(allFilesWorkingGroupSchema, rallyProject.id)
        allFilesWorkingGroupSchema = syn.store(allFilesWorkingGroupSchema)

        addToViewScope(allFilesWorkingGroupSchema, sprintProject.id)
        allFilesWorkingGroupSchema = syn.store(allFilesWorkingGroupSchema)

        # make sure all tables are triggered to be refreshed
        touch = syn.tableQuery('select id from %(id)s limit 1' %
                               dict(id=rallyAdminSprintTable.id))
        touch = syn.tableQuery('select id from %(id)s limit 1' %
                               dict(id=allFilesWorkingGroupSchema.id))
Exemplo n.º 8
0
def createRally(syn, rallyNumber, config=CONFIG, otherPermissions=None):

    rallyProject = getRally(syn,
                            config['rallyAdminProjectId'],
                            rallyNumber=rallyNumber)

    if rallyProject:
        return rallyProject

    consortium = config.get('consortium', None)
    rallyStart = config.get('rallyStart', None)
    rallyEnd = config.get('rallyEnd', None)

    rallyTitle = "ki Rally %s" % (rallyNumber, )
    rallyTeamName = "HBGDki Rally %s" % (rallyNumber, )

    # Get locations of templates, team IDs, etc.
    rallyAdminProject = syn.get(config['rallyAdminProjectId'])

    rallyAdminTeamId = rallyAdminProject.annotations.rallyAdminTeamId[0]
    rallyTableId = rallyAdminProject.annotations.rallyTableId[0]
    wikiMasterTemplateId = rallyAdminProject.annotations.wikiMasterTemplateId[
        0]
    taskTableTemplateId = rallyAdminProject.annotations.taskTableTemplateId[0]

    teamPermissionsDict = {
        rallyAdminTeamId: config['rallyAdminTeamPermissions']
    }

    if otherPermissions:
        teamPermissionsDict.update(otherPermissions)

    # This is a Project View (table) of a list of rallies
    # in the HBGDki Working Group Project
    rallyTableSchema = syn.get(rallyTableId)

    # all files table in the hbgdki rally working group project
    allFilesWorkingGroupSchema = syn.get(config['allFilesSchemaId'])

    # The columns for a file view that lists all files in a project.
    # This is used for a file view in the HBGDki working group, in the rally
    # project, and in the sprint project
    allFilesTableColumns = list(syn.getColumns(config['allFilesSchemaId']))

    # Create a rally team.
    rallyTeam = createRallyTeam(
        syn=syn,
        teamName=rallyTeamName,
        defaultMembers=config['defaultRallyTeamMembers'])

    # Add the rally team with it's default permissions to
    # the list of permissions to add
    teamPermissionsDict.update(
        {rallyTeam.id: ['DOWNLOAD', 'READ', 'UPDATE', 'CREATE']})

    # Create the Rally Project
    rallyProject = synapseclient.Project(name=rallyTitle,
                                         annotations=dict(
                                             rally=rallyNumber,
                                             consortium=consortium,
                                             rallyStart=rallyStart,
                                             rallyEnd=rallyEnd,
                                             rallyTeam=rallyTeam.id))

    try:
        rallyProject = syn.store(rallyProject, createOrUpdate=False)
    except synapseclient.exceptions.SynapseHTTPError:
        rallyProjectObj = syn.restPOST("/entity/child",
                                       body=json.dumps(
                                           {"entityName": rallyTitle}))
        rallyProject = syn.get(rallyProjectObj['id'])

    # Set permissions to the rally project
    for teamId, permissions in list(teamPermissionsDict.items()):
        syn.setPermissions(rallyProject,
                           principalId=teamId,
                           accessType=permissions)

    # Add the wiki, only if it doesn't already exist
    try:
        wiki = syn.getWiki(owner=rallyProject)
    except synapseclient.exceptions.SynapseHTTPError:
        rallyWikiMasterTemplate = syn.get(config['wikiRallyTemplateId'])
        wiki = syn.store(
            synapseclient.Wiki(owner=rallyProject,
                               markdownFile=rallyWikiMasterTemplate.path))
        # wiki.markdown = wiki.markdown.replace('syn00000000', rallySprintTable.id)
        wiki.markdown = wiki.markdown.replace('id=0000000',
                                              'id=%s' % rallyTeam.id)
        wiki.markdown = wiki.markdown.replace('teamId=0000000',
                                              'teamId=%s' % rallyTeam.id)
        wiki = syn.store(wiki)

    # Add the Rally Project to the list of rallies in the working group project view
    rallyTableSchema = syn.get(rallyTableId)
    addToViewScope(rallyTableSchema, rallyProject.id)
    rallyTableSchema = syn.store(rallyTableSchema)

    # Force refresh of the table
    touch = syn.tableQuery('select id from %(id)s limit 1' %
                           dict(id=rallyTableSchema.id))

    return rallyProject
Exemplo n.º 9
0
def create_sprint(rally_number,
                  sprint_letter,
                  sprint_title=None,
                  config=configuration.DEFAULT_CONFIG):
    """Create a sprint project.

    Args:
        rally_number: Integer rally number.
        sprint_letter: A single character letter for the sprint.
        sprint_title: Optional sprint title used as the project name.
        config: A dictionary with configuration options.
    Returns:
        A synapseclient.Project object.

    """

    syn = Synapse().client()

    # Sprint Configuration
    sprint_number = "%s%s" % (rally_number, sprint_letter)
    if not sprint_title:
        sprint_title = "ki Sprint %s" % (sprint_number, )

    consortium = config.get('consortium', None)

    rally_admin_team_id = config['rally_admin_team_id']
    wiki_master_template_id = config['wiki_master_template_id']
    sprint_table_id = config['sprint_table_id']

    team_permissions = {rally_admin_team_id: config['rallyAdminTeamPermissions']}  # pylint: disable=line-too-long

    # all files table in the Ki rally working group project
    all_files_working_group_schema = syn.get(config['allFilesSchemaId'])

    rally_project = get_rally(config['root_project_id'],
                              rally_number=rally_number)

    if rally_project is None:
        raise ValueError(f"No rally {rally_number}. Please create it first.")

    # Get the rally team.
    rally_team = syn.getTeam(
        rally_project.annotations.get('rallyTeam', None)[0])

    rally_project_acl = syn._getACL(rally_project)

    sprint_project = get_sprint(config['root_project_id'],
                                rally_number=rally_number,
                                sprint_letter=sprint_letter)

    if not sprint_project:
        LOGGER.info(f"Creating a new sprint {sprint_number}")
        # Create the sprint project
        annotations = dict(sprintTitle=sprint_title,
                           sprintNumber=sprint_number,
                           sprint_letter=sprint_letter,
                           rally=rally_number,
                           rallyId=rally_project.id,
                           sprintStart=None,
                           sprintEnd=None,
                           consortium=consortium,
                           rallyTeam=rally_team.id)

        sprint_project = synapseclient.Project(name=sprint_title,
                                               annotations=annotations)

        try:
            sprint_project = syn.store(sprint_project, createOrUpdate=False)
            LOGGER.info(f"Created sprint project {sprint_project.id}")
        except synapseclient.exceptions.SynapseHTTPError:
            body = json.dumps({"entityName": sprint_project.name})
            sprint_project_obj = syn.restPOST("/entity/child", body=body)
            sprint_project = syn.get(sprint_project_obj['id'])

        # Set permissions for the sprint project
        for resource_access in rally_project_acl['resourceAccess']:
            syn.setPermissions(sprint_project, **resource_access)

        try:
            wiki = syn.getWiki(owner=sprint_project)
        except synapseclient.exceptions.SynapseHTTPError:
            wiki_template = syn.get(wiki_master_template_id)
            wiki = synapseclient.Wiki(owner=sprint_project,
                                      markdownFile=wiki_template.path)  # pylint: disable=line-too-long
            wiki = syn.store(wiki)
            wiki.markdown = wiki.markdown.replace('id=123',
                                                  f'id={rally_team.id}')  # pylint: disable=line-too-long
            wiki.markdown = wiki.markdown.replace('teamId=123',
                                                  f'teamId={rally_team.id}')  # pylint: disable=line-too-long
            wiki = syn.store(wiki)

        LOGGER.info("Set sprint project wiki.")

        # Create folders
        _ = create_folders(root=sprint_project,
                           folder_list=config['sprintFolders'])

        LOGGER.info("Created sprint project folder structure.")

        # Create a daily checkin discussion post
        forum = syn.restGET(f"/project/{sprint_project.id}/forum")

        for discussion_post in config['posts']:
            discussion_post['forumId'] = forum.get('id', None)
            try:
                post = syn.restPOST("/thread",
                                    body=json.dumps(discussion_post))
            except Exception as exception:
                LOGGER.error(f"Error with discussion post: {post} ({exception})")  # pylint: disable=line-too-long
        LOGGER.info("Created sprint project forum posts.")

        # Add the sprint to the all sprints table in the
        # ki working group project
        rally_admin_sprint_table = syn.get(sprint_table_id)
        add_to_view_scope(rally_admin_sprint_table, [sprint_project.id])
        rally_admin_sprint_table = syn.store(rally_admin_sprint_table)

        # Add the files in the rally project to the
        # working group all files view
        all_files_working_group_schema = syn.get(config['allFilesSchemaId'])
        add_to_view_scope(all_files_working_group_schema, [rally_project.id])
        all_files_working_group_schema = syn.store(all_files_working_group_schema)  # pylint: disable=line-too-long

        add_to_view_scope(all_files_working_group_schema, [sprint_project.id])
        all_files_working_group_schema = syn.store(all_files_working_group_schema)  # pylint: disable=line-too-long

        # make sure all tables are triggered to be refreshed
        _ = syn.tableQuery(f'select id from {rally_admin_sprint_table.id} limit 1')  # pylint: disable=line-too-long
        _ = syn.tableQuery(f'select id from {all_files_working_group_schema.id} limit 1')  # pylint: disable=line-too-long

        LOGGER.info("Registered sprint project in project and file views.")
    return sprint_project
Exemplo n.º 10
0
def create_rally(rally_number,
                 rally_title=None,
                 config=configuration.DEFAULT_CONFIG):
    """Create a rally project.

    Args:
        rally_number: Integer rally number.
        rally_title: Optional rally title used as the project name.
        config: A dictionary with configuration options.
    Returns:
        A synapseclient.Project object.

    """
    syn = Synapse().client()

    rally_project = get_rally(config['root_project_id'],
                              rally_number=rally_number)

    if rally_project:
        LOGGER.info(f"Rally {rally_number} already exists.")
        return rally_project

    consortium = config.get('consortium', None)

    if not rally_title:
        rally_title = "ki Rally %s" % (rally_number, )

    rally_team_name = "ki Rally %s" % (rally_number, )
    rally_power_users_team_name = f"{rally_team_name} Power Users"

    rally_admin_team_id = config['rally_admin_team_id']
    rally_table_id = config['rally_table_id']
    team_permissions = {rally_admin_team_id: config['rallyAdminTeamPermissions']}  # pylint: disable=line-too-long

    # Create a rally team.
    rally_team = create_team_and_invite(
        team_name=rally_team_name,
        default_members=config['defaultRallyTeamMembers'])

    # Add the rally team with it's default permissions to
    # the list of permissions to add to the rally project ACL
    team_permissions.update({rally_team.id: DEFAULT_PERMISSIONS})

    # Create a power users team.
    rally_power_users_team = create_team_and_invite(
        team_name=rally_power_users_team_name,
        default_members=config['defaultPowerUserTeamMembers'])

    # Add the power users team with it's permissions to
    # the list of permissions to add to the rally project ACL
    team_permissions.update(
        {rally_power_users_team.id: POWER_USER_PERMISSIONS})

    # Create the Rally Project
    annotations = dict(rally=rally_number,
                       consortium=consortium,
                       rallyStart=None,
                       rallyEnd=None,
                       rallyTeam=rally_team.id)

    rally_project = synapseclient.Project(name=rally_title,
                                          annotations=annotations)

    try:
        rally_project = syn.store(rally_project, createOrUpdate=False)
        LOGGER.info("Rally project created.")
    except synapseclient.exceptions.SynapseHTTPError:
        body = json.dumps({"entityName": rally_title})
        rally_proj_obj = syn.restPOST("/entity/child", body=body)
        rally_project = syn.get(rally_proj_obj['id'])

    # Set permissions to the rally project
    for team_id, permissions in list(team_permissions.items()):
        syn.setPermissions(rally_project,
                           principalId=team_id,
                           accessType=permissions)

    # Add the wiki, only if it doesn't already exist
    try:
        wiki = syn.getWiki(owner=rally_project)
    except synapseclient.exceptions.SynapseHTTPError:
        rally_wiki_master_template = syn.get(config['wikiRallyTemplateId'])
        wiki = synapseclient.Wiki(owner=rally_project,
                                  markdownFile=rally_wiki_master_template.path)
        wiki = syn.store(wiki)
        wiki.markdown = wiki.markdown.replace('RALLY_ID', str(rally_number))
        wiki.markdown = wiki.markdown.replace('id=0000000',
                                              f'id={rally_team.id}')
        wiki.markdown = wiki.markdown.replace('teamId=0000000',
                                              f'teamId={rally_team.id}')
        wiki = syn.store(wiki)

    LOGGER.info("Set the project wiki.")

    # Add the Rally Project to the list of rallies
    # in the working group project view
    rally_table_schema = syn.get(rally_table_id)
    add_to_view_scope(rally_table_schema, [rally_project.id])
    rally_table_schema = syn.store(rally_table_schema)

    # Force refresh of the table
    _ = syn.tableQuery(f'select id from {rally_table_schema.id} limit 1')
    LOGGER.debug("Updated rally project view.")

    return rally_project
Exemplo n.º 11
0
import os

import synapseclient

syn = synapseclient.login()
synid = os.getenv("INPUT_SYNID")

wiki_content = ""
if os.path.exists("README.md"):
    # wiki_content += "# Description\n\n"
    with open("README.md") as readme_f:
        wiki_content += readme_f.read()

if os.path.exists("Dockerfile"):
    wiki_content += "\n\n"
    wiki_content += "# Dockerfile\n\n"
    wiki_content += "```dockerfile\n"
    with open("Dockerfile") as readme_f:
        wiki_content += readme_f.read()
    wiki_content += "\n```"

wiki = synapseclient.Wiki(owner=synid, markdown=wiki_content)
syn.store(wiki)