示例#1
0
def test_is_member():
    """Test the Team class method is_member(github_id)."""
    team = Team("1", "brussel-sprouts", "Brussel Sprouts")
    new_github_id = "U0G9QF9C6"
    assert team.has_member(new_github_id) is False
    team.add_member(new_github_id)
    assert team.has_member(new_github_id)
示例#2
0
 def mem_remove(self,
                github_id: str,
                selected_team: Team,
                team_name: str) -> ResponseTuple:
     """Help membership function if payload action is removal."""
     member_list = self._facade. \
         query(User, [('github_user_id', github_id)])
     slack_ids_string = ""
     if len(member_list) == 1:
         slack_id = member_list[0].slack_id
         if selected_team.has_member(github_id):
             selected_team.discard_member(github_id)
             self._facade.store(selected_team)
             logging.info(f"deleted slack user {slack_id} "
                          f"from {team_name}")
             slack_ids_string += f" {slack_id}"
             return (f"deleted slack ID{slack_ids_string} "
                     f"from {team_name}", 200)
         else:
             logging.error(f"slack user {slack_id} not in {team_name}")
             return (f"slack user {slack_id} not in {team_name}", 200)
     elif len(member_list) > 1:
         logging.error("Error: found github ID connected to"
                       " multiple slack IDs")
         return ("Error: found github ID connected to multiple"
                 " slack IDs", 200)
     else:
         logging.error(f"could not find user {github_id}")
         return f"could not find user {github_id}", 200
示例#3
0
def test_handle_mem_event_rm_single_member(mock_logging, mem_rm_payload):
    """Test that members removed from the mem are deleted from rocket's db."""
    mock_facade = mock.MagicMock(DBFacade)
    return_user = User("SLACKID")
    return_team = Team("2723476", "rocket", "rocket")
    return_team.add_member("21031067")
    mock_facade.query.return_value = [return_user]
    mock_facade.retrieve.return_value = return_team
    webhook_handler = MembershipEventHandler(mock_facade)
    (rsp, code) = webhook_handler.handle(mem_rm_payload)
    mock_facade.query\
        .assert_called_once_with(User, [('github_user_id', "21031067")])
    mock_facade.retrieve \
        .assert_called_once_with(Team, "2723476")
    mock_facade.store.assert_called_once_with(return_team)
    mock_logging.info.assert_called_once_with("deleted slack user SLACKID"
                                              " from rocket")
    assert not return_team.has_member("21031067")
    assert rsp == "deleted slack ID SLACKID from rocket"
    assert code == 200
示例#4
0
    def refresh_all_team(self):
        """
        Refresh the 'all' team - this team is used to track all members.

        Should only be called after the teams have all synced, or bugs will
        probably occur. See https://github.com/orgs/ubclaunchpad/teams/all
        """
        all_name = self.config.github_team_all
        team_all = None
        if len(all_name) == 0:
            logging.info('no "all" team configured, skipping refresh')
            return

        logging.info(f'refreshing all team {all_name}')
        try:
            team_all = get_team_by_name(self.facade, all_name)
        except LookupError:
            t_id = str(self.gh.org_create_team(all_name))
            logging.info(f'team {all_name} created')
            team_all = Team(t_id, all_name, all_name)

        if team_all is not None:
            all_members = self.facade.query(User)
            for m in all_members:
                if len(m.github_id) > 0 and\
                        not team_all.has_member(m.github_id):
                    # The only way for this to be true is if both locally and
                    # remotely the member (who is part of launchpad) is not
                    # part of the 'all' team.
                    self.gh.add_team_member(m.github_username,
                                            team_all.github_team_id)
                    team_all.add_member(m.github_id)

            self.facade.store(team_all)
        else:
            logging.error(f'Could not create {all_name}. Aborting.')
示例#5
0
class TestTeamCommandApis(TestCase):
    """Test Case for TeamCommandApi methods."""

    def setUp(self) -> None:
        """Set up the test case environment."""
        self.mock_facade = mock.MagicMock(DBFacade)
        self.mock_github = mock.MagicMock(GithubInterface)
        self.mock_slack = mock.MagicMock(Bot)
        self.testapi = CommandApis(self.mock_facade,
                                   self.mock_github,
                                   self.mock_slack)

        self.regular_user = User("regular")
        self.regular_user.permissions_level = Permissions.member
        self.regular_user.github_id = "reg_gh_id"
        self.regular_user.github_username = "******"
        self.lead_user = User("lead")
        self.lead_user.permissions_level = Permissions.team_lead
        self.lead_user.github_id = "lead_gh_id"
        self.lead_user.github_username = "******"
        self.admin_user = User("admin")
        self.admin_user.permissions_level = Permissions.admin
        self.admin_user.github_id = "admin_gh_id"
        self.admin_user.github_username = "******"

        self.team1 = Team("1", "gh1", "name1")
        self.team2 = Team("2", "gh2", "name2")
        self.team3 = Team("3", "gh3", "name3")
        self.team3_dup = Team("4", "gh3", "name4")

        def mock_facade_retrieve_side_effect(*args, **kwargs):
            """Mock behavior of the retrieve mock facade function."""
            slack_id = args[1]
            if slack_id == self.regular_user.slack_id:
                return self.regular_user
            elif slack_id == self.lead_user.slack_id:
                return self.lead_user
            elif slack_id == self.admin_user.slack_id:
                return self.admin_user
            else:
                raise LookupError

        self.mock_facade.retrieve.side_effect = \
            mock_facade_retrieve_side_effect

        def mock_facade_query_side_effect(*args, **kwargs):
            """Mock behavior of the query mock facade function."""
            query_teams = []
            try:
                params = args[1]
            except IndexError:
                query_teams = [
                    self.team1,
                    self.team2,
                    self.team3,
                    self.team3_dup
                ]
            else:
                assert len(params) == 1, \
                    "Woops, too many parameters for this mock query!"
                attribute, value = params[0]
                assert attribute == "github_team_name", \
                    "Woops, this mock can only handle `github_team_name`!"

                if value == "gh1":
                    query_teams = [self.team1]
                elif value == "gh2":
                    query_teams = [self.team2]
                elif value == "gh3":
                    query_teams = [
                        self.team3,
                        self.team3_dup
                    ]

            return query_teams

        self.mock_facade.query.side_effect = \
            mock_facade_query_side_effect

        # In most cases, store will need to return True for tests
        self.mock_facade.store.return_value = True

    def test_list(self) -> None:
        """Test list team command API."""
        all_teams = self.testapi.team_list()
        self.assertListEqual(all_teams,
                             [
                                 self.team1,
                                 self.team2,
                                 self.team3,
                                 self.team3_dup
                             ])

    def test_view_missing_team(self) -> None:
        """Test view team command API with missing team."""
        self.mock_facade.query.return_value = []
        try:
            self.testapi.team_view("no_team")
        except LookupError:
            pass
        else:
            self.assertTrue(False)

    def test_view_multiple_teams(self) -> None:
        """Test view team command API with multiple matching teams."""
        try:
            self.testapi.team_view("gh3")
        except RuntimeError:
            pass
        else:
            self.assertTrue(False)

    def test_view_single_team(self) -> None:
        """Test view team command API with singular matching team."""
        team = self.testapi.team_view("gh1")
        self.assertEqual(team, self.team1)

    def test_create_missing_creator(self) -> None:
        """Test create team command API with missing calling user."""
        try:
            self.testapi.team_create("no_user", "team_name")
        except LookupError:
            pass
        else:
            self.assertTrue(False)

    def test_create_non_lead_creator(self) -> None:
        """Test create team command API with non lead calling user."""
        try:
            self.testapi.team_create("regular", "team_name")
        except PermissionError:
            pass
        else:
            self.assertTrue(False)

    def test_create_gh_team_creation_error(self) -> None:
        """Test create team command API with Github team creation error."""
        self.mock_github.org_create_team.side_effect = GithubAPIException("")
        try:
            self.testapi.team_create("lead", "team_name")
        except GithubAPIException:
            pass
        else:
            self.assertTrue(False)

    def test_create_gh_team_add_member_error(self) -> None:
        """Test create team command API with Github team member add error."""
        self.mock_github.add_team_member.side_effect = GithubAPIException("")
        try:
            self.testapi.team_create("lead", "team_name")
        except GithubAPIException:
            pass
        else:
            self.assertTrue(False)

    def test_create_success(self) -> None:
        """Test create team command API with successful creation."""
        self.mock_github.org_create_team.return_value = "team_gh_id"
        created = self.testapi.team_create("lead", "team_name")
        self.assertTrue(created)
        stored_team = Team("team_gh_id", "team_name", "")
        stored_team.add_member(self.lead_user.github_id)
        stored_team.add_team_lead(self.lead_user.github_id)
        self.mock_github.add_team_member.assert_called_once_with(
            self.lead_user.github_username, "team_gh_id")
        self.mock_facade.store.assert_called_once_with(stored_team)

    def test_create_with_display_name(self) -> None:
        """Test create team command API with display name."""
        self.mock_github.org_create_team.return_value = "team_gh_id"
        created = self.testapi.team_create("lead",
                                           "team_name",
                                           display_name="display_name")
        self.assertTrue(created)
        stored_team = Team("team_gh_id", "team_name", "display_name")
        stored_team.add_member(self.lead_user.github_id)
        stored_team.add_team_lead(self.lead_user.github_id)
        self.mock_facade.store.assert_called_with(stored_team)

    def test_create_with_platform(self) -> None:
        """Test create team command API with platform."""
        self.mock_github.org_create_team.return_value = "team_gh_id"
        created = self.testapi.team_create("lead",
                                           "team_name",
                                           platform="platform")
        self.assertTrue(created)
        stored_team = Team("team_gh_id", "team_name", "")
        stored_team.platform = "platform"
        stored_team.add_member(self.lead_user.github_id)
        stored_team.add_team_lead(self.lead_user.github_id)
        self.mock_facade.store.assert_called_with(stored_team)

    def test_create_get_channel_members_error(self) -> None:
        """Test create team command API with error getting channel users."""
        self.mock_slack.get_channel_users.side_effect = SlackAPIError("")
        try:
            self.testapi.team_create("lead", "team_name", channel="channel")
        except SlackAPIError:
            pass
        else:
            self.assertTrue(False)

    def test_create_missing_slack_user_from_channel(self) -> None:
        """Test create team command API with missing channel member."""
        self.mock_slack.get_channel_users.return_value = {"missing": None}
        try:
            self.testapi.team_create("lead", "team_name", channel="channel")
        except LookupError:
            self.assertTrue(False)
        else:
            self.assertEqual(self.mock_github.add_team_member.call_count, 0)

    def test_create_add_channel_member_gh_team_error(self) -> None:
        """Test create team command API adding channel member to Github."""
        self.mock_slack.get_channel_users.return_value = \
            {self.regular_user.slack_id: self.regular_user}
        self.mock_facade.bulk_retrieve.return_value = [self.regular_user]

        self.mock_github.add_team_member.side_effect = GithubAPIException("")

        try:
            self.testapi.team_create("lead", "team_name", channel="channel")
        except GithubAPIException:
            pass
        else:
            self.assertTrue(False)

    def test_create_add_channel_members(self) -> None:
        """Test create team command API with specified channel."""
        self.mock_slack.get_channel_users.return_value = \
            {self.regular_user.slack_id: self.regular_user}
        self.mock_facade.bulk_retrieve.return_value = [self.regular_user]
        self.mock_github.org_create_team.return_value = "team_gh_id"
        created = self.testapi.team_create(
            "lead", "team_name", channel="channel")
        self.assertTrue(created)
        stored_team = Team("team_gh_id", "team_name", "")
        stored_team.add_member(self.regular_user.github_id)
        stored_team.add_team_lead(self.lead_user.github_id)
        self.mock_github.add_team_member.assert_called_with(
            self.regular_user.github_username, "team_gh_id")
        self.mock_facade.store.assert_called_once_with(stored_team)

    def test_create_missing_lead(self) -> None:
        """Test create team command API with missing team lead."""
        try:
            self.testapi.team_create(
                "lead", "team_name", lead_id="missing")
        except LookupError:
            pass
        else:
            self.assertTrue(False)

    def test_create_with_lead_check_team_error(self) -> None:
        """Test create team command API with error from checking team."""
        self.mock_github.has_team_member.side_effect = GithubAPIException("")
        try:
            self.testapi.team_create(
                "admin", "team_name", lead_id="lead")
        except GithubAPIException:
            pass
        else:
            self.assertTrue(False)

    def test_create_with_lead_not_in_gh_team(self) -> None:
        """Test create team command API with lead not in Github team."""
        self.mock_github.org_create_team.return_value = "team_gh_id"
        self.mock_github.has_team_member.return_value = False
        self.testapi.team_create(
            "admin", "team_name", lead_id="lead")
        self.mock_github.add_team_member.assert_called_with(
            self.lead_user.github_username, "team_gh_id")

    def test_create_with_lead_in_gh_team(self) -> None:
        """Test create team command API with lead in Github team."""
        self.mock_github.org_create_team.return_value = "team_gh_id"
        self.mock_github.has_team_member.return_value = True
        self.testapi.team_create(
            "admin", "team_name", lead_id="lead")
        self.assertEqual(self.mock_github.add_team_member.call_count, 1)

    def test_create_with_non_lead_lead(self) -> None:
        """Test create team command API with non-lead lead."""
        self.mock_github.org_create_team.return_value = "team_gh_id"
        try:
            self.testapi.team_create("admin",
                                     "team_name",
                                     lead_id="regular")
        except PermissionError:
            pass
        else:
            self.assertTrue(False)

    def test_create_with_lead(self) -> None:
        """Test create team command API with lead."""
        self.mock_github.org_create_team.return_value = "team_gh_id"
        created = self.testapi.team_create(
            "admin", "team_name", lead_id="lead")
        self.assertTrue(created)
        stored_team = Team("team_gh_id", "team_name", "")
        stored_team.add_member(self.admin_user.github_id)
        stored_team.add_member(self.lead_user.github_id)
        stored_team.add_team_lead(self.lead_user.github_id)
        self.mock_facade.store.assert_called_once_with(stored_team)

    def test_create_store_fail(self) -> None:
        """Test create team command API with failing store."""
        self.mock_facade.store.return_value = False
        self.mock_github.org_create_team.return_value = "team_gh_id"
        created = self.testapi.team_create("lead", "team_name")
        self.assertFalse(created)
        stored_team = Team("team_gh_id", "team_name", "")
        stored_team.add_member(self.lead_user.github_id)
        stored_team.add_team_lead(self.lead_user.github_id)
        self.mock_github.add_team_member.assert_called_once_with(
            self.lead_user.github_username, "team_gh_id")
        self.mock_facade.store.assert_called_once_with(stored_team)

    def test_add_missing_adder(self) -> None:
        """Test add team command API with missing calling user."""
        try:
            self.testapi.team_add("no_user", "no_user_2", "team_name")
        except LookupError:
            pass
        else:
            self.assertTrue(False)

    def test_add_missing_team(self) -> None:
        """Test add team command API with missing team to add to."""
        try:
            self.testapi.team_add("lead", "regular", "missing_team")
        except LookupError:
            pass
        else:
            self.assertTrue(False)

    def test_add_non_unique_team(self) -> None:
        """Test add team command API with non unique Github team name."""
        try:
            self.testapi.team_add("lead", "regular", "gh3")
        except RuntimeError:
            pass
        else:
            self.assertTrue(False)

    def test_add_permission_error(self) -> None:
        """Test add team command API with caller without permissions."""
        try:
            self.testapi.team_add("regular", "lead", "gh1")
        except PermissionError:
            pass
        else:
            self.assertTrue(False)

    def test_add_missing_new_member(self) -> None:
        """Test add team command API with missing user."""
        self.team1.add_team_lead(self.lead_user.github_id)
        try:
            self.testapi.team_add("lead", "no_user", "gh1")
        except LookupError:
            pass
        else:
            self.assertTrue(False)

    def test_add_gh_team_add_member_error(self) -> None:
        """Test add team command API w/ error adding to Github team."""
        self.team1.add_team_lead(self.lead_user.github_id)
        self.mock_github.add_team_member.side_effect = GithubAPIException("")
        try:
            self.testapi.team_add("lead", "regular", "gh1")
        except GithubAPIException:
            pass
        else:
            self.assertTrue(False)

    def test_add_success(self) -> None:
        """Test add team command API successful execution."""
        self.team1.add_team_lead(self.lead_user.github_id)
        added = self.testapi.team_add("lead", "regular", "gh1")
        self.assertTrue(added)
        self.assertTrue(self.team1.has_member(self.regular_user.github_id))
        self.mock_github.add_team_member.assert_called_once_with(
            self.regular_user.github_username,
            self.team1.github_team_id
        )

    def test_add_fail(self) -> None:
        """Test add team command API when store fails."""
        self.team1.add_team_lead(self.lead_user.github_id)
        self.mock_facade.store.return_value = False
        added = self.testapi.team_add("lead", "regular", "gh1")
        self.assertFalse(added)

    def test_remove_missing_remover(self) -> None:
        """Test remove team command API with missing remover."""
        try:
            self.testapi.team_remove("no_user", "gh1", "regular")
        except LookupError:
            pass
        else:
            self.assertTrue(False)

    def test_remove_missing_team(self) -> None:
        """Test remove team command API with missing team."""
        try:
            self.testapi.team_remove("lead", "no_team", "regular")
        except LookupError:
            pass
        else:
            self.assertTrue(False)

    def test_remove_non_unique_team(self) -> None:
        """Test remove team command API with non unique Github team name."""
        try:
            self.testapi.team_remove("lead", "gh3", "regular")
        except RuntimeError:
            pass
        else:
            self.assertTrue(False)

    def test_remove_permission_error(self) -> None:
        """Test remove team command API with caller without permissions."""
        try:
            self.testapi.team_remove("regular", "gh1", "lead")
        except PermissionError:
            pass
        else:
            self.assertTrue(False)

    def test_remove_missing_user_to_remove(self) -> None:
        """Test remove team command API with missing member to remove."""
        try:
            self.testapi.team_remove("lead", "gh1", "no_user")
        except PermissionError:
            pass
        else:
            self.assertTrue(False)

    def test_remove_gh_team_not_has_member(self) -> None:
        """Test remove team command API when member not in Github team."""
        self.team1.add_team_lead(self.lead_user.github_id)
        self.mock_github.has_team_member.return_value = False
        try:
            self.testapi.team_remove("lead", "gh1", "regular")
        except GithubAPIException:
            pass
        else:
            self.assertTrue(False)

    def test_remove_gh_team_gh_exception(self) -> None:
        """Test remove team command API when GithubAPIException is raised."""
        self.team1.add_team_lead(self.lead_user.github_id)
        self.mock_github.has_team_member.side_effect = GithubAPIException("")
        try:
            self.testapi.team_remove("lead", "gh1", "regular")
        except GithubAPIException:
            pass
        else:
            self.assertTrue(False)

    def test_remove_store_fail(self) -> None:
        """Test remove team command API when db store fails."""
        self.team1.add_team_lead(self.lead_user.github_id)
        self.mock_github.has_team_member.return_value = True
        self.mock_facade.store.return_value = False
        removed = self.testapi.team_remove("lead", "gh1", "regular")
        self.assertFalse(removed)

    def test_remove_success(self) -> None:
        """Test remove team command API successful execution."""
        self.team1.add_team_lead(self.lead_user.github_id)
        self.mock_github.has_team_member.return_value = True
        removed = self.testapi.team_remove("lead", "gh1", "regular")
        self.assertTrue(removed)
        self.assertFalse(self.team1.has_member(self.regular_user.github_id))
        self.mock_github.remove_team_member.assert_called_once_with(
            self.regular_user.github_username,
            self.team1.github_team_id
        )

    def test_remove_lead_success(self) -> None:
        """Test remove team command API on lead successful execution."""
        self.team1.add_team_lead(self.lead_user.github_id)
        self.mock_github.has_team_member.return_value = True
        removed = self.testapi.team_remove("lead", "gh1", "lead")
        self.assertTrue(removed)
        self.assertFalse(self.team1.has_member(self.lead_user.github_id))
        self.assertFalse(self.team1.has_team_lead(self.lead_user.github_id))
        self.mock_github.remove_team_member.assert_called_once_with(
            self.lead_user.github_username,
            self.team1.github_team_id
        )

    def test_edit_missing_editor(self) -> None:
        """Test edit team command API with missing calling user."""
        try:
            self.testapi.team_edit("no_user", "gh1")
        except LookupError:
            pass
        else:
            self.assertTrue(False)

    def test_edit_missing_team(self) -> None:
        """Test edit team command API with missing team."""
        try:
            self.testapi.team_edit("lead", "no_team")
        except LookupError:
            pass
        else:
            self.assertTrue(False)

    def test_edit_non_unique_team(self) -> None:
        """Test edit team command API with non unique Github team name."""
        try:
            self.testapi.team_edit("lead", "gh3")
        except RuntimeError:
            pass
        else:
            self.assertTrue(False)

    def test_edit_permission_error(self) -> None:
        """Test edit team command API with caller without permissions."""
        try:
            self.testapi.team_edit("regular", "gh1")
        except PermissionError:
            pass
        else:
            self.assertTrue(False)

    def test_edit_store_fail(self) -> None:
        """Test edit team command API when db store fails."""
        self.mock_facade.store.return_value = False
        self.team1.add_team_lead(self.lead_user.github_id)
        edited = self.testapi.team_edit("lead",
                                        "gh1",
                                        display_name="tempname")
        self.assertFalse(edited)

    def test_edit_display_name(self) -> None:
        """Test edit team command API to edit team display name."""
        self.team1.add_team_lead(self.lead_user.github_id)
        edited = self.testapi.team_edit("lead",
                                        "gh1",
                                        display_name="tempname")
        self.assertTrue(edited)
        self.assertEqual("tempname", self.team1.display_name)

    def test_edit_platform(self) -> None:
        """Test edit team command API to edit platform."""
        self.team1.add_team_lead(self.lead_user.github_id)
        edited = self.testapi.team_edit("lead",
                                        "gh1",
                                        platform="tempplat")
        self.assertTrue(edited)
        self.assertEqual("tempplat", self.team1.platform)

    def test_lead_missing_lead_assigner(self) -> None:
        """Test lead team command API with missing calling user."""
        try:
            self.testapi.team_lead("no_user", "lead", "gh1")
        except LookupError:
            pass
        else:
            self.assertTrue(False)

    def test_lead_missing_team(self) -> None:
        """Test lead team command API with missing team."""
        try:
            self.testapi.team_lead("lead", "regular", "no_team")
        except LookupError:
            pass
        else:
            self.assertTrue(False)

    def test_lead_non_unique_team(self) -> None:
        """Test lead team command API with non unique Github team name."""
        try:
            self.testapi.team_lead("lead", "regular", "gh3")
        except RuntimeError:
            pass
        else:
            self.assertTrue(False)

    def test_lead_permission_error(self) -> None:
        """Test lead team command API with caller without permissions."""
        try:
            self.testapi.team_lead("regular", "lead", "gh1")
        except PermissionError:
            pass
        else:
            self.assertTrue(False)

    def test_lead_missing_intended_lead(self) -> None:
        """Test lead team command API with missing intended lead."""
        self.team1.add_team_lead(self.lead_user.github_id)
        try:
            self.testapi.team_lead("lead", "no_user", "gh1")
        except LookupError:
            pass
        else:
            self.assertTrue(False)

    def test_lead_gh_team_add_member_error(self) -> None:
        """Test lead team command API with Github team member add error."""
        self.mock_github.add_team_member.side_effect = GithubAPIException("")
        self.team1.add_team_lead(self.lead_user.github_id)
        try:
            self.testapi.team_lead("lead", "regular", "gh1")
        except GithubAPIException:
            pass
        else:
            self.assertTrue(False)

    def test_lead_store_fail(self) -> None:
        """Test lead command API failing store."""
        self.mock_facade.store.return_value = False
        self.team1.add_team_lead(self.lead_user.github_id)
        lead_assigned = self.testapi.team_lead("lead", "regular", "gh1")
        self.assertFalse(lead_assigned)

    def test_lead_successful(self) -> None:
        """Test lead team command API setting team lead successfully."""
        self.team1.add_team_lead(self.lead_user.github_id)
        lead_assigned = self.testapi.team_lead("lead", "regular", "gh1")
        self.mock_github.add_team_member.assert_called_once_with(
            self.regular_user.github_username,
            self.team1.github_team_id
        )
        self.assertTrue(lead_assigned)
        self.assertTrue(self.team1.has_member(self.regular_user.github_id))
        self.assertTrue(self.team1.has_team_lead(self.regular_user.github_id))

    def test_lead_remove_not_in_team(self) -> None:
        """Test lead team command API remove a member not in a team."""
        self.team1.add_team_lead(self.lead_user.github_id)
        try:
            self.testapi.team_lead("lead", "regular", "gh1", remove=True)
        except LookupError:
            pass
        else:
            self.assertTrue(False)

    def test_lead_remove_not_lead_of_team(self) -> None:
        """Test lead team command API remove a member not lead of team."""
        self.team1.add_team_lead(self.lead_user.github_id)
        self.team1.add_member(self.regular_user.github_id)
        try:
            self.testapi.team_lead("lead", "regular", "gh1", remove=True)
        except LookupError:
            pass
        else:
            self.assertTrue(False)

    def test_lead_remove_store_fail(self) -> None:
        """Test lead command API removal failing store."""
        self.mock_facade.store.return_value = False
        self.team1.add_team_lead(self.lead_user.github_id)
        self.team1.add_member(self.regular_user.github_id)
        self.team1.add_team_lead(self.regular_user.github_id)
        lead_removed = self.testapi.team_lead("lead", "regular", "gh1",
                                              remove=True)
        self.assertFalse(lead_removed)

    def test_lead_remove_successful(self) -> None:
        """Test lead team command API successfully remove lead from team."""
        self.team1.add_team_lead(self.lead_user.github_id)
        self.team1.add_member(self.regular_user.github_id)
        self.team1.add_team_lead(self.regular_user.github_id)
        lead_removed = self.testapi.team_lead("lead", "regular", "gh1",
                                              remove=True)
        self.assertTrue(lead_removed)
        self.assertTrue(self.team1.has_member(self.regular_user.github_id))
        self.assertFalse(self.team1.has_team_lead(self.regular_user.github_id))

    def test_delete_missing_deleter(self) -> None:
        """Test delete team command API with missing calling user."""
        try:
            self.testapi.team_delete("no_user", "gh1")
        except LookupError:
            pass
        else:
            self.assertTrue(False)

    def test_delete_missing_team(self) -> None:
        """Test delete team command API with missing team."""
        try:
            self.testapi.team_delete("lead", "no_team")
        except LookupError:
            pass
        else:
            self.assertTrue(False)

    def test_delete_non_unique_team(self) -> None:
        """Test delete team command API with non unique Github team name."""
        try:
            self.testapi.team_delete("lead", "gh3")
        except RuntimeError:
            pass
        else:
            self.assertTrue(False)

    def test_delete_permission_error(self) -> None:
        """Test delete team command API with caller without permissions."""
        try:
            self.testapi.team_delete("regular", "gh1")
        except PermissionError:
            pass
        else:
            self.assertTrue(False)

    def test_delete_gh_team_delete_team_error(self) -> None:
        """Test delete team command API with Github team delete error."""
        self.mock_github.org_delete_team.side_effect = GithubAPIException("")
        self.team1.add_team_lead(self.lead_user.github_id)
        try:
            self.testapi.team_delete("lead", "gh1")
        except GithubAPIException:
            pass
        else:
            self.assertTrue(False)

    def test_delete_successful(self) -> None:
        """Test delete team command API deleting team successfully."""
        self.team1.add_team_lead(self.lead_user.github_id)
        self.testapi.team_delete("lead", "gh1")
        self.mock_github.org_delete_team.assert_called_once_with(
            int(self.team1.github_team_id))
        self.mock_facade.delete.assert_called_once_with(
            Team,
            self.team1.github_team_id)

    def test_refresh_missing_refresher(self) -> None:
        """Test refresh team command API with missing calling user."""
        try:
            self.testapi.team_refresh("no_user")
        except LookupError:
            pass
        else:
            self.assertTrue(False)

    def test_refresh_permission_error(self) -> None:
        """Test refresh team command API with caller without permissions."""
        try:
            self.testapi.team_refresh("regular")
        except PermissionError:
            pass
        else:
            self.assertTrue(False)

    def test_refresh_gh_get_teams_error(self) -> None:
        """Test refresh team command API with Github error getting teams."""
        self.mock_github.org_get_teams.side_effect = GithubAPIException("")
        try:
            self.testapi.team_refresh("admin")
        except GithubAPIException:
            pass
        else:
            self.assertTrue(False)

    def test_refresh_github_deleted(self) -> None:
        """Test refresh team command API with teams removed from Github."""
        self.mock_github.org_get_teams.return_value = [
            self.team2,
            self.team3,
            self.team3_dup
        ]
        refreshed = self.testapi.team_refresh("admin")
        self.assertTrue(refreshed)
        self.mock_facade.delete.assert_called_once_with(
            Team, self.team1.github_team_id)

    def test_refresh_github_added_failed_store(self) -> None:
        """Test refresh team command API unable to store new Github teams."""
        team5 = Team("5", "gh5", "name5")
        self.mock_github.org_get_teams.return_value = [
            self.team1,
            self.team2,
            self.team3,
            self.team3_dup,
            team5
        ]
        self.mock_facade.store.return_value = False
        refreshed = self.testapi.team_refresh("admin")
        self.assertFalse(refreshed)
        self.mock_facade.store.assert_called_once_with(team5)

    def test_refresh_github_added_success(self) -> None:
        """Test refresh team command API storing new Github teams."""
        team5 = Team("5", "gh5", "name5")
        self.mock_github.org_get_teams.return_value = [
            self.team1,
            self.team2,
            self.team3,
            self.team3_dup,
            team5
        ]
        refreshed = self.testapi.team_refresh("admin")
        self.assertTrue(refreshed)
        self.mock_facade.store.assert_called_once_with(team5)

    def test_refresh_github_changed_failed_store(self) -> None:
        """Test refresh team command API unable to edit teams."""
        new_team1 = Team("1", "newgh1", "name1")
        new_team1.add_member(self.regular_user.github_id)
        self.mock_github.org_get_teams.return_value = [
            new_team1,
            self.team2,
            self.team3,
            self.team3_dup,
        ]
        self.mock_facade.store.return_value = False
        refreshed = self.testapi.team_refresh("admin")
        self.assertFalse(refreshed)
        self.team1.github_team_name = "newgh1"
        self.team1.add_member(self.regular_user.github_id)
        self.mock_facade.store.assert_called_once_with(self.team1)

    def test_refresh_github_changed_success(self) -> None:
        """Test refresh team command API to edit teams."""
        new_team1 = Team("1", "newgh1", "name1")
        new_team1.add_member(self.regular_user.github_id)
        self.mock_github.org_get_teams.return_value = [
            new_team1,
            self.team2,
            self.team3,
            self.team3_dup,
        ]
        refreshed = self.testapi.team_refresh("admin")
        self.assertTrue(refreshed)
        self.team1.github_team_name = "newgh1"
        self.team1.add_member(self.regular_user.github_id)
        self.mock_facade.store.assert_called_once_with(self.team1)
示例#6
0
class TestMembershipHandles(TestCase):
    def setUp(self):
        self.team = 'rocket'
        self.teamid = 395830
        self.member = 'theflatearth'
        self.memberid = 3058493
        self.add_payload = mem_default_payload(self.team, self.teamid,
                                               self.member, self.memberid)
        self.rm_payload = mem_default_payload(self.team, self.teamid,
                                              self.member, self.memberid)
        self.empty_payload = mem_default_payload(self.team, self.teamid,
                                                 self.member, self.memberid)

        self.add_payload['action'] = 'added'
        self.rm_payload['action'] = 'removed'
        self.empty_payload['action'] = ''

        self.u = User('U4058409')
        self.u.github_id = str(self.memberid)
        self.u.github_username = self.member
        self.t = Team(str(self.teamid), self.team, self.team.capitalize())
        self.db = MemoryDB(users=[self.u], teams=[self.t])

        self.gh = mock.Mock()
        self.conf = mock.Mock()
        self.conf.github_team_all = 'all'
        self.webhook_handler = MembershipEventHandler(self.db, self.gh,
                                                      self.conf)

    def test_handle_mem_event_add_member(self):
        rsp, code = self.webhook_handler.handle(self.add_payload)
        self.assertEqual(rsp, f'added slack ID {self.u.slack_id}')
        self.assertEqual(code, 200)

    def test_handle_mem_event_add_member_not_found_in_db(self):
        self.db.users = {}
        rsp, code = self.webhook_handler.handle(self.add_payload)
        self.assertEqual(rsp, f'could not find user {self.member}')
        self.assertEqual(code, 200)

    def test_handle_mem_event_rm_member(self):
        self.t.add_member(self.u.github_id)
        rsp, code = self.webhook_handler.handle(self.rm_payload)
        self.assertFalse(self.t.has_member(self.u.github_id))
        self.assertIn(self.u.slack_id, rsp)
        self.assertEqual(code, 200)

    def test_handle_mem_event_rm_member_missing_from_team(self):
        rsp, code = self.webhook_handler.handle(self.rm_payload)
        self.assertEqual(rsp,
                         f'slack user {self.u.slack_id} not in {self.team}')
        self.assertEqual(code, 200)

    def test_handle_mem_event_rm_member_missing_from_db(self):
        self.db.users = {}
        rsp, code = self.webhook_handler.handle(self.rm_payload)
        self.assertEqual(rsp, f'could not find user {self.memberid}')
        self.assertEqual(code, 200)

    def test_handle_mem_event_rm_multiple_members(self):
        clone = User('Uclones')
        clone.github_id = str(self.memberid)
        clone.github_username = self.member
        self.db.users['Uclones'] = clone
        rsp, code = self.webhook_handler.handle(self.rm_payload)
        self.assertEqual(
            rsp, 'Error: found github ID connected to multiple slack IDs')
        self.assertEqual(code, 200)

    def test_handle_mem_event_invalid_action(self):
        rsp, code = self.webhook_handler.handle(self.empty_payload)
        self.assertEqual(rsp, 'Unsupported action triggered, ignoring.')
        self.assertEqual(code, 202)
示例#7
0
class TestTeamModel(TestCase):
    def setUp(self):
        self.brussel_sprouts = Team('1', 'brussel-sprouts', 'Brussel Sprouts')
        self.brussel_sprouts_copy =\
            Team('1', 'brussel-sprouts', 'Brussel Sprouts')
        self.brussel_trouts = Team('1', 'brussel-trouts', 'Brussel Trouts')

    def test_team_equality(self):
        """Test the Team class method __eq__() and __ne__()."""
        self.assertEqual(self.brussel_sprouts, self.brussel_sprouts_copy)
        self.assertNotEqual(self.brussel_sprouts, self.brussel_trouts)

    def test_valid_team(self):
        """Test the Team static class method is_valid()."""
        self.assertTrue(Team.is_valid(self.brussel_sprouts))
        self.brussel_sprouts.github_team_name = ''
        self.assertFalse(Team.is_valid(self.brussel_sprouts))

    def test_add_member(self):
        """Test the Team class method add_member(github_id)."""
        new_github_id = "U0G9QF9C6"
        self.brussel_sprouts.add_member(new_github_id)
        self.assertIn(new_github_id, self.brussel_sprouts.members)

    def test_discard_member(self):
        """Test the Team class method discard_member(github_id)."""
        new_github_id = "U0G9QF9C6"
        self.brussel_sprouts.add_member(new_github_id)
        self.brussel_sprouts.discard_member(new_github_id)
        self.assertSetEqual(self.brussel_sprouts.members, set())

    def test_is_member(self):
        """Test the Team class method is_member(github_id)."""
        new_github_id = "U0G9QF9C6"
        self.assertFalse(self.brussel_sprouts.has_member(new_github_id))
        self.brussel_sprouts.add_member(new_github_id)
        assert self.brussel_sprouts.has_member(new_github_id)

    def test_add_lead(self):
        """Test the Team class method add_team_lead(github_id)."""
        new_github_id = "U0G9QF9C6"
        self.brussel_sprouts.add_team_lead(new_github_id)
        self.assertIn(new_github_id, self.brussel_sprouts.team_leads)

    def test_is_lead(self):
        """Test the Team class method is_team_lead(github_id)."""
        new_github_id = "U0G9QF9C6"
        self.assertFalse(self.brussel_sprouts.has_team_lead(new_github_id))
        self.brussel_sprouts.add_team_lead(new_github_id)
        self.assertTrue(self.brussel_sprouts.has_team_lead(new_github_id))

    def test_print(self):
        """Test print team class."""
        new_slack_id = "U0G9QF9C6"
        self.brussel_sprouts.add_member(new_slack_id)
        self.brussel_sprouts.add_team_lead(new_slack_id)
        self.brussel_sprouts.platform = "web"
        expected = "{'github_team_id': '1'," \
            " 'github_team_name': 'brussel-sprouts'," \
            " 'display_name': 'Brussel Sprouts'," \
            " 'platform': 'web'," \
            " 'team_leads': {'U0G9QF9C6'}," \
            " 'members': {'U0G9QF9C6'}," \
            " 'folder': ''}"
        self.assertEqual(str(self.brussel_sprouts), expected)
示例#8
0
class TestTeamCommand(TestCase):
    def setUp(self):
        self.app = Flask(__name__)
        self.config = mock.MagicMock()
        self.gh = mock.MagicMock()

        self.u0 = User('U123456789')
        self.u1 = User('U234567891')
        self.admin = create_test_admin('Uadmin')
        self.t0 = Team("BRS", "brs", "web")
        self.t1 = Team("OTEAM", "other team", "android")
        self.t2 = Team("LEADS", "leads", "")
        self.t3 = Team("ADMIN", "admin", "")
        self.db = MemoryDB(users=[self.u0, self.u1, self.admin],
                           teams=[self.t0, self.t1, self.t2, self.t3])

        self.sc = mock.MagicMock()
        self.testcommand = TeamCommand(self.config, self.db, self.gh, self.sc)
        self.help_text = self.testcommand.help
        self.maxDiff = None

        self.config.github_team_all = 'all'
        self.config.github_team_leads = 'leads'
        self.config.github_team_admin = 'admin'

    def test_get_help(self):
        subcommands = list(self.testcommand.subparser.choices.keys())
        help_message = self.testcommand.get_help()
        self.assertEqual(len(subcommands), help_message.count("usage"))

    def test_get_subcommand_help(self):
        subcommands = list(self.testcommand.subparser.choices.keys())
        for subcommand in subcommands:
            help_message = self.testcommand.get_help(subcommand=subcommand)
            self.assertEqual(1, help_message.count("usage"))

    def test_get_invalid_subcommand_help(self):
        """Test team command get_help method for invalid subcommands."""
        self.assertEqual(self.testcommand.get_help(),
                         self.testcommand.get_help(subcommand="foo"))

    def test_handle_help(self):
        ret, code = self.testcommand.handle("team help", self.u0.slack_id)
        self.assertEqual(ret, self.testcommand.get_help())
        self.assertEqual(code, 200)

    def test_handle_multiple_subcommands(self):
        """Test handling multiple observed subcommands."""
        ret, code = self.testcommand.handle("team list edit", self.u0.slack_id)
        self.assertEqual(ret, self.testcommand.get_help())
        self.assertEqual(code, 200)

    def test_handle_subcommand_help(self):
        """Test team subcommand help text."""
        subcommands = list(self.testcommand.subparser.choices.keys())
        for subcommand in subcommands:
            for arg in ['--help', '-h', '--invalid argument']:
                command = f"team {subcommand} {arg}"
                ret, code = self.testcommand.handle(command, self.u0.slack_id)
                self.assertEqual(1, ret.count("usage"))
                self.assertEqual(code, 200)

    def test_handle_list(self):
        attachment = [
            self.t0.get_basic_attachment(),
            self.t1.get_basic_attachment(),
            self.t2.get_basic_attachment(),
            self.t3.get_basic_attachment(),
        ]
        with self.app.app_context():
            resp, code = self.testcommand.handle('team list', self.u0.slack_id)
            expect = {'attachments': attachment}
            self.assertDictEqual(resp, expect)
            self.assertEqual(code, 200)

    def test_handle_list_no_teams(self):
        self.db.teams = {}
        self.assertTupleEqual(
            self.testcommand.handle('team list', self.u0.slack_id),
            ('No Teams Exist!', 200))

    def test_handle_view(self):
        with self.app.app_context():
            resp, code = self.testcommand.handle('team view brs',
                                                 self.u0.slack_id)
            expect = {'attachments': [self.t0.get_attachment()]}
            self.assertDictEqual(resp, expect)
            self.assertEqual(code, 200)

    def test_handle_view_lookup_error(self):
        self.assertTupleEqual(
            self.testcommand.handle('team view iesesebrs', self.u0.slack_id),
            (self.testcommand.lookup_error, 200))

    def test_handle_view_noleads(self):
        resp, code = self.testcommand.handle('team view brs', self.u0.slack_id)
        self.assertDictEqual(resp['attachments'][0], self.t0.get_attachment())
        self.assertEqual(code, 200)

    def test_handle_delete_not_admin(self):
        self.assertTupleEqual(
            self.testcommand.handle('team delete brs', self.u0.slack_id),
            (self.testcommand.permission_error, 200))
        self.gh.org_delete_team.assert_not_called()

    def test_handle_delete_lookup_error(self):
        self.assertTupleEqual(
            self.testcommand.handle('team delete brs', 'ioenairsetno'),
            (self.testcommand.lookup_error, 200))
        self.gh.org_delete_team.assert_not_called()

    def test_handle_delete_github_error(self):
        self.t0.github_team_id = '123452'
        self.gh.org_delete_team.side_effect = GithubAPIException('error')
        self.assertTupleEqual(
            self.testcommand.handle('team delete brs', self.admin.slack_id),
            ('Team delete was unsuccessful with '
             'the following error: '
             'error', 200))

    def test_handle_delete(self):
        self.t0.github_team_id = '12345'
        self.u0.github_id = '132432'
        self.u0.permissions_level = Permissions.team_lead
        self.t0.add_team_lead(self.u0.github_id)
        self.assertTupleEqual(
            self.testcommand.handle('team delete brs', self.u0.slack_id),
            ('Team brs deleted', 200))
        self.gh.org_delete_team.assert_called_once_with(int('12345'))

    def test_handle_create(self):
        self.gh.org_create_team.return_value = '8934095'
        inputstring = "team create b-s --name 'B S'"
        outputstring = 'New team created: b-s, name: B S, '
        self.assertTupleEqual(
            self.testcommand.handle(inputstring, self.admin.slack_id),
            (outputstring, 200))
        inputstring += ' --platform web'
        outputstring += 'platform: web, '
        self.assertTupleEqual(
            self.testcommand.handle(inputstring, self.admin.slack_id),
            (outputstring, 200))
        self.gh.org_create_team.assert_called()
        self.gh.add_team_member.assert_called_with(self.admin.github_username,
                                                   '8934095')

        inputstring += " --channel 'channelID'"
        outputstring += "added channel, "
        self.sc.get_channel_users.return_value = ['someID', 'otherID']
        self.assertTupleEqual(
            self.testcommand.handle(inputstring, self.admin.slack_id),
            (outputstring, 200))
        self.sc.get_channel_users.assert_called_once_with('channelID')
        self.gh.add_team_member.assert_called()
        inputstring += f' --lead {self.u0.slack_id}'
        outputstring += 'added lead'
        self.gh.has_team_member.return_value = False
        self.assertTupleEqual(
            self.testcommand.handle(inputstring, self.admin.slack_id),
            (outputstring, 200))

    def test_handle_create_not_admin(self):
        self.u0.github_username = '******'
        self.u0.github_id = '12'
        self.gh.org_create_team.return_value = 'team_id'
        inputstring = "team create b-s --name 'B S'"
        self.assertTupleEqual(
            self.testcommand.handle(inputstring, self.u0.slack_id),
            (self.testcommand.permission_error, 200))

    def test_handle_create_not_ghuser(self):
        self.u0.permissions_level = Permissions.admin
        self.gh.org_create_team.return_value = 'team_id'
        s = 'team create someting'
        ret, val = self.testcommand.handle(s, self.u0.slack_id)
        self.assertEqual(val, 200)
        self.assertIn('yet to register', ret)

    def test_handle_create_github_error(self):
        self.gh.org_create_team.return_value = 'team_id'
        inputstring = "team create b-s --name 'B S'"
        self.gh.add_team_member.side_effect = GithubAPIException('error')
        self.assertTupleEqual(
            self.testcommand.handle(inputstring, self.admin.slack_id),
            ('Team creation unsuccessful with the '
             'following error: error', 200))

    def test_handle_create_lookup_error(self):
        inputstring = "team create b-s --name 'B S'"
        self.assertTupleEqual(self.testcommand.handle(inputstring, 'rando'),
                              (self.testcommand.lookup_error, 200))

    def test_handle_add(self):
        self.t0.github_team_id = 'githubid'
        self.u0.github_username = '******'
        self.u0.github_id = 'otherID'
        with self.app.app_context():
            resp, code = self.testcommand.handle(
                f'team add brs {self.u0.slack_id}', self.admin.slack_id)
            expect = {
                'attachments': [self.t0.get_attachment()],
                'text': 'Added User to brs'
            }
            self.assertDictEqual(resp, expect)
            self.assertEqual(code, 200)
        self.assertTrue(self.t0.has_member("otherID"))
        self.gh.add_team_member.assert_called_once_with('myuser', 'githubid')

    def test_handle_add_but_forgot_githubid(self):
        self.t0.github_team_id = 'githubid'
        self.gh.add_team_member.side_effect = GithubAPIException('error')
        self.assertTupleEqual(
            self.testcommand.handle(f'team add brs {self.u0.slack_id}',
                                    self.admin.slack_id),
            (TeamCommand.no_ghusername_error, 200))

    def test_handle_add_not_admin(self):
        """Test team command add parser with insufficient permission."""
        self.t0.github_team_id = 'githubid'
        self.assertTupleEqual(
            self.testcommand.handle(f'team add brs {self.u1.slack_id}',
                                    self.u0.slack_id),
            (self.testcommand.permission_error, 200))
        self.gh.add_team_member.assert_not_called()

    def test_handle_add_github_error(self):
        self.t0.github_team_id = 'githubid'
        self.u0.github_id = 'myuser'
        self.gh.add_team_member.side_effect = GithubAPIException('error')
        self.assertTupleEqual(
            self.testcommand.handle(f'team add brs {self.u0.slack_id}',
                                    self.admin.slack_id),
            ('User added unsuccessfully with the'
             ' following error: error', 200))

    def test_handle_add_lookup_error(self):
        self.assertTupleEqual(
            self.testcommand.handle('team add brs ID', 'rando'),
            (self.testcommand.lookup_error, 200))
        self.gh.add_team_member.assert_not_called()

    def test_handle_add_promote(self):
        self.u0.github_username = '******'
        self.u0.github_id = 'otherID'
        self.t2.github_team_id = 'githubid'
        with self.app.app_context():
            resp, code = self.testcommand.handle(
                f'team add leads {self.u0.slack_id}', self.admin.slack_id)
            expect_msg = 'Added User to leads and promoted user to team_lead'
            expect = {
                'attachments': [self.t2.get_attachment()],
                'text': expect_msg
            }
            self.assertDictEqual(resp, expect)
            self.assertEqual(code, 200)
        self.assertTrue(self.t2.has_member("otherID"))
        self.assertEquals(self.u0.permissions_level, Permissions.team_lead)
        self.gh.add_team_member.assert_called_once_with('myuser', 'githubid')

    def test_handle_add_promote_current_admin(self):
        self.u0.github_username = '******'
        self.u0.github_id = 'otherID'
        self.t2.github_team_id = 'githubid'
        # existing admin member should not be "promoted" to lead
        self.u0.permissions_level = Permissions.admin
        self.t3.add_member(self.u0.github_id)
        with self.app.app_context():
            resp, code = self.testcommand.handle(
                f'team add leads {self.u0.slack_id}', self.admin.slack_id)
            expect_msg = 'Added User to leads'
            expect = {
                'attachments': [self.t2.get_attachment()],
                'text': expect_msg
            }
            self.assertDictEqual(resp, expect)
            self.assertEqual(code, 200)
        self.assertTrue(self.t2.has_member("otherID"))
        self.assertEquals(self.u0.permissions_level, Permissions.admin)
        self.gh.add_team_member.assert_called_once_with('myuser', 'githubid')

    def test_handle_remove(self):
        self.u0.github_id = 'githubID'
        self.u0.github_username = '******'
        self.t0.add_member(self.u0.github_id)
        with self.app.app_context():
            resp, code = self.testcommand.handle(
                f'team remove {self.t0.github_team_name} {self.u0.slack_id}',
                self.admin.slack_id)
            expect = {
                'attachments': [self.t0.get_attachment()],
                'text': f'Removed User from {self.t0.github_team_name}'
            }
            self.assertDictEqual(resp, expect)
            self.assertEqual(code, 200)
        self.gh.remove_team_member.assert_called_once_with(
            self.u0.github_username, self.t0.github_team_id)

    def test_handle_remove_user_not_in_team(self):
        """Test team command remove parser when user is not in team."""
        self.u0.github_id = 'githubID'
        self.u0.github_username = '******'
        self.gh.has_team_member.return_value = False
        with self.app.app_context():
            self.assertTupleEqual(
                self.testcommand.handle(
                    f'team remove {self.t0.github_team_name} {self.u0.slack_id}',
                    self.admin.slack_id), ("User not in team!", 200))
        self.gh.has_team_member.assert_called_once_with(
            self.u0.github_username, self.t0.github_team_id)
        self.gh.remove_team_member.assert_not_called()

    def test_handle_remove_demote(self):
        self.u0.github_username = '******'
        self.u0.github_id = 'otherID'
        self.t2.add_member(self.u0.github_id)
        with self.app.app_context():
            resp, code = self.testcommand.handle(
                f'team remove leads {self.u0.slack_id}', self.admin.slack_id)
            expect_msg = 'Removed User from leads and demoted user'
            expect = {
                'attachments': [self.t2.get_attachment()],
                'text': expect_msg
            }
            self.assertDictEqual(resp, expect)
            self.assertEqual(code, 200)
        self.assertEquals(self.u0.permissions_level, Permissions.member)
        self.gh.remove_team_member.assert_called_once_with(
            self.u0.github_username, self.t2.github_team_id)

    def test_handle_remove_demote_to_team_lead(self):
        self.u0.github_username = '******'
        self.u0.github_id = 'otherID'
        self.t2.add_member(self.u0.github_id)
        self.t3.add_member(self.u0.github_id)
        with self.app.app_context():
            resp, code = self.testcommand.handle(
                f'team remove admin {self.u0.slack_id}', self.admin.slack_id)
            expect_msg = 'Removed User from admin and demoted user'
            expect = {
                'attachments': [self.t3.get_attachment()],
                'text': expect_msg
            }
            self.assertDictEqual(resp, expect)
            self.assertEqual(code, 200)
        self.assertEquals(self.u0.permissions_level, Permissions.team_lead)
        self.gh.remove_team_member.assert_called_once_with(
            self.u0.github_username, self.t3.github_team_id)

    def test_handle_remove_demote_to_admin(self):
        self.u0.github_username = '******'
        self.u0.github_id = 'otherID'
        self.u0.permissions_level = Permissions.admin
        self.t2.add_member(self.u0.github_id)
        self.t3.add_member(self.u0.github_id)
        with self.app.app_context():
            # Leads member should not be demoted if they are also a admin
            # member
            resp, code = self.testcommand.handle(
                f'team remove leads {self.u0.slack_id}', self.admin.slack_id)
            expect_msg = 'Removed User from leads'
            expect = {
                'attachments': [self.t2.get_attachment()],
                'text': expect_msg
            }
            self.assertDictEqual(resp, expect)
            self.assertEqual(code, 200)
        self.assertEquals(self.u0.permissions_level, Permissions.admin)
        self.gh.remove_team_member.assert_called_once_with(
            self.u0.github_username, self.t2.github_team_id)

    def test_handle_remove_not_admin(self):
        with self.app.app_context():
            self.assertTupleEqual(
                self.testcommand.handle(
                    f'team remove {self.t0.github_team_name} {self.u0.slack_id}',
                    self.u1.slack_id),
                (self.testcommand.permission_error, 200))
        self.gh.remove_team_member.assert_not_called()

    def test_handle_remove_lookup_error(self):
        with self.app.app_context():
            self.assertTupleEqual(
                self.testcommand.handle(
                    f'team remove {self.t0.github_team_name} {self.u0.slack_id}',
                    'another.rando'), (self.testcommand.lookup_error, 200))
        self.gh.remove_team_member.assert_not_called()

    def test_handle_remove_github_error(self):
        self.gh.has_team_member.side_effect = GithubAPIException('error')
        with self.app.app_context():
            self.assertTupleEqual(
                self.testcommand.handle(
                    f'team remove {self.t0.github_team_name} {self.u0.slack_id}',
                    self.admin.slack_id),
                ('User removed unsuccessfully with the '
                 'following error: error', 200))
        self.gh.remove_team_member.assert_not_called()

    def test_handle_lead_add(self):
        self.u0.github_id = 'githubID'
        self.u0.github_username = '******'
        with self.app.app_context():
            self.assertFalse(self.t0.has_team_lead(self.u0.github_id))
            self.assertFalse(self.t0.has_member(self.u0.github_id))
            _, code = self.testcommand.handle(
                f'team lead {self.t0.github_team_name} {self.u0.slack_id}',
                self.admin.slack_id)
            self.assertEqual(code, 200)
            self.assertTrue(self.t0.has_team_lead(self.u0.github_id))
            self.assertTrue(self.t0.has_member(self.u0.github_id))
            self.gh.add_team_member.assert_called_once_with(
                self.u0.github_username, self.t0.github_team_id)

    def test_handle_lead_remove(self):
        self.u0.github_id = 'githubID'
        self.u0.github_username = '******'
        self.t0.add_member(self.u0.github_id)
        self.t0.add_team_lead(self.u0.github_id)
        with self.app.app_context():
            self.assertTrue(self.t0.has_team_lead(self.u0.github_id))
            _, code = self.testcommand.handle(
                f'team lead --remove {self.t0.github_team_name}'
                f' {self.u0.slack_id}', self.admin.slack_id)
            self.assertEqual(code, 200)
            self.assertFalse(self.t0.has_team_lead(self.u0.github_id))

    def test_handle_lead_not_admin(self):
        with self.app.app_context():
            self.assertTupleEqual(
                self.testcommand.handle(
                    f'team lead {self.t0.github_team_name} {self.u0.slack_id}',
                    self.u1.slack_id),
                (self.testcommand.permission_error, 200))

    def test_handle_lead_lookup_error(self):
        with self.app.app_context():
            self.assertTupleEqual(
                self.testcommand.handle(
                    f'team lead {self.t0.github_team_name} {self.u0.slack_id}',
                    'rando.rand'), (self.testcommand.lookup_error, 200))

    def test_handle_lead_github_error(self):
        self.gh.add_team_member.side_effect = GithubAPIException('error')
        with self.app.app_context():
            self.assertTupleEqual(
                self.testcommand.handle(
                    f'team lead {self.t0.github_team_name} {self.u0.slack_id}',
                    self.admin.slack_id),
                ('Edit team lead was unsuccessful with the '
                 'following error: error', 200))

    def test_handle_lead_user_error(self):
        with self.app.app_context():
            self.assertTupleEqual(
                self.testcommand.handle(
                    f'team lead --remove {self.t0.github_team_name}'
                    f' {self.u0.slack_id}', self.admin.slack_id),
                ('User not in team!', 200))

    def test_handle_edit(self):
        with self.app.app_context():
            _, code = self.testcommand.handle(
                f'team edit {self.t0.github_team_name}'
                ' --name brS --platform web', self.admin.slack_id)
            self.assertEqual(self.t0.display_name, 'brS')
            self.assertEqual(self.t0.platform, 'web')
            self.assertEqual(code, 200)

    def test_handle_edit_not_admin(self):
        with self.app.app_context():
            self.assertTupleEqual(
                self.testcommand.handle(
                    f'team edit {self.t0.github_team_name}', self.u0.slack_id),
                (self.testcommand.permission_error, 200))

    def test_handle_edit_lookup_error(self):
        with self.app.app_context():
            self.assertTupleEqual(
                self.testcommand.handle('team edit rando.team',
                                        self.admin.slack_id),
                (self.testcommand.lookup_error, 200))

    def test_handle_refresh_not_admin(self):
        with self.app.app_context():
            self.assertTupleEqual(
                self.testcommand.handle('team refresh', self.u0.slack_id),
                (self.testcommand.permission_error, 200))

    def test_handle_refresh_lookup_error(self):
        """Test team command refresh parser with lookup error."""
        with self.app.app_context():
            self.assertTupleEqual(
                self.testcommand.handle('team refresh', 'rando.randy'),
                (self.testcommand.lookup_error, 200))

    def test_handle_refresh_github_error(self):
        self.gh.org_get_teams.side_effect = GithubAPIException('error')
        with self.app.app_context():
            self.assertTupleEqual(
                self.testcommand.handle('team refresh', self.admin.slack_id),
                ('Refresh teams was unsuccessful with '
                 'the following error: error', 200))

    def test_handle_refresh_changed(self):
        """Test team command refresh parser if team edited in github."""
        team = Team('TeamID', 'TeamName', 'android')
        team_update = Team('TeamID', 'new team name', 'android')
        team_update.add_member(self.admin.github_id)
        team2 = Team('OTEAM', 'other team2', 'ios')

        self.db.teams = {}
        self.db.teams['TeamID'] = team
        self.db.teams['OTEAM'] = team2

        self.gh.org_get_teams.return_value = [team_update, team2]
        attach = team_update.get_attachment()

        status = '1 teams changed, 0 added, 0 deleted. Wonderful.'
        with self.app.app_context():
            resp, code = self.testcommand.handle('team refresh',
                                                 self.admin.slack_id)
            expect = {'attachments': [attach], 'text': status}
            self.assertDictEqual(resp, expect)
            self.assertEqual(code, 200)
            self.assertEqual(team, team_update)

    def test_handle_refresh_addition_and_deletion(self):
        """Test team command refresh parser if local differs from github."""
        team = Team('TeamID', 'TeamName', '')
        team2 = Team('OTEAM', 'other team', 'android')

        self.db.teams = {}
        self.db.teams['OTEAM'] = team2

        # In this case, github does not have team2!
        self.gh.org_get_teams.return_value = [team]
        self.gh.org_create_team.return_value = 12345
        attach = team.get_attachment()
        attach2 = team2.get_attachment()

        status = '0 teams changed, 1 added, 1 deleted. Wonderful.'
        with self.app.app_context():
            resp, code = self.testcommand.handle('team refresh',
                                                 self.admin.slack_id)
            expect = {'attachments': [attach2, attach], 'text': status}
            self.assertDictEqual(resp, expect)
            self.assertEqual(code, 200)
            self.assertEqual(len(self.db.teams), 2)