Example #1
0
 def setUp(self):
     """Set up project variables for testing."""
     self.rocket2 = Project(
         '12345',
         ['https://www.github.com/ubclaunchpad/rocket2'])
     self.p0 = Project('12345', ['https://www.github.com/'])
     self.p1 = Project('12345', ['https://www.github.com/'])
     self.p2 = Project('1234', ['https://www.github.com/'])
Example #2
0
 def test_handle_view(self):
     """Test project command view parser."""
     project = Project("GTID", ["a", "b"])
     project_id = project.project_id
     project_attach = [project.get_attachment()]
     self.mock_facade.retrieve.return_value = project
     with self.app.app_context():
         resp, code = self.testcommand.handle(
             "project view %s" % project_id, user)
         expect = {'attachments': project_attach}
         self.assertDictEqual(resp, expect)
         self.assertEqual(code, 200)
     self.mock_facade.retrieve.assert_called_once_with(Project, project_id)
Example #3
0
    def create_helper(self,
                      gh_repo: str,
                      github_team_name: str,
                      param_list: Dict[str, str],
                      user_id: str) -> ResponseTuple:
        """
        Create a project and store it in the database.

        :param gh_repo: link to the GitHub repository this project describes
        :param github_team_name: GitHub team name of the team to assign this
                                 project to
        :param param_list: Dict of project parameters that are to
                           be initialized
        :param user_id: user ID of the calling user
        :return: lookup error if the specified GitHub team name does not match
                 a team in the database or if the calling user could not be
                 found, else permission error if the calling user is not a
                 team lead of the team to initially assign the
                 project to, else information about the project
        """
        logging.debug("Handling project create subcommand")
        team_list = self.facade.query(Team,
                                      [("github_team_name",
                                        github_team_name)])
        if len(team_list) != 1:
            error = f"{len(team_list)} teams found with " \
                f"GitHub team name {github_team_name}"
            logging.error(error)
            return error, 200

        team = team_list[0]
        try:
            user = self.facade.retrieve(User, user_id)

            if not (user_id in team.team_leads or
                    user.permissions_level is Permissions.admin):
                logging.error(f"User with user ID {user_id} is not "
                              "a team lead of the specified team or an admin")
                return self.permission_error, 200

            project = Project(team.github_team_id, [gh_repo])

            if param_list["display_name"]:
                project.display_name = param_list["display_name"]

            self.facade.store(project)

            return {'attachments': [project.get_attachment()]}, 200
        except LookupError as e:
            logging.error(str(e))
            return str(e), 200
Example #4
0
def video_manage():
    username = request.args.get('username', None)
    projectName = request.args.get('projectName', None)
    page = int(request.args.get('page', 1)) - 1

    select = {}
    data = []
    videos: List[Video] = []
    projects_name: List[str] = []
    if username:
        select['owner'] = username
    if projectName:
        _projects: List[Project] = Project.objects(projectName=projectName)
        for project in _projects:
            select['belongTo'] = str(project.id)
            videos += Video.objects(**select)
        for i in range(len(videos)):
            projects_name.append(projectName)

    else:
        videos: List[Video] = Video.objects(**select)
        # print(videos)
        for i in range(len(videos)):
            projects_name.append(
                Project.get_project_by_id(videos[i].belongTo,
                                          deep=True).projectName)
            # print(videos[i].projectName)

    total_page = math.ceil(len(videos) / number_per_page)
    video_list = []
    for i, video in enumerate(
            videos[page * number_per_page:page * number_per_page +
                   number_per_page]):
        owner = username if username else User.get_user_by_id(
            video.owner).username
        video_list.append({
            'videoId': str(video.id),
            'videoName': video.videoName,
            'videoUrl': video.url,
            'owner': owner,
            'belongTo': projects_name[i],
            'comment': video.comment,
            'alive': video.alive,
            'cover': video.cover[0]
        })

    data = {'totalPage': total_page, 'videoList': video_list}
    return jsonify(build_response(data=data))
Example #5
0
 def test_handle_unassign_team_lookup_error(self):
     proj = Project('rando', [])
     self.db.projs[proj.project_id] = proj
     self.assertEqual(
         self.testcommand.handle(f'project unassign {proj.project_id}',
                                 self.admin.slack_id),
         ('Team(id=rando) not found', 200))
Example #6
0
def project_manage():
    projectName = request.args.get('projectName', None)
    owner = request.args.get('owner', None)
    page = int(request.args.get('page', 1)) - 1

    select = {}
    if projectName:
        select['projectName'] = projectName
    if owner:
        user = User.objects(username=owner).first()
        if not user:
            return jsonify(build_response(data=[]))
        select['owner'] = str(user.id)

    project_list = []
    projects: List[Project] = Project.objects(**select)
    total_page = math.ceil(len(projects) / number_per_page)
    for project in projects[page * number_per_page:page * number_per_page +
                            number_per_page]:
        owner_name = User.get_user_by_id(
            project.owner).username if not owner else owner
        project_list.append({
            'projectId': str(project.id),
            'projectName': project.projectName,
            'owner': owner_name,
            'memberNum': len(project.member) + 1,
            'videoNum': len(project.hasVideo),
            'meetingNum': len(project.hasMeeting),
            'alive': project.alive
        })

    data = {'totalPage': total_page, 'projectList': project_list}
    return jsonify(build_response(data=data))
Example #7
0
 def test_handle_assign_project_team_lookup_error(self):
     """Test project command assign with team lookup error."""
     self.mock_facade.retrieve.return_value = Project("", [])
     self.mock_facade.query.return_value = []
     self.assertTupleEqual(
         self.testcommand.handle("project assign ID team-name", user),
         ("0 teams found with GitHub team name team-name", 200))
Example #8
0
 def facade_retrieve_side_effect(*args, **kwargs):
     """Return a side effect for the mock facade."""
     if args[0] == Project:
         return Project("", [])
     else:
         calling_user = User(user)
         return calling_user
Example #9
0
 def test_handle_edit_name(self):
     """Test project command edit parser with name property."""
     project = Project("GTID", ["a", "b"])
     project.display_name = "name1"
     project_id = project.project_id
     self.mock_facade.retrieve.return_value = project
     with self.app.app_context():
         resp, code = self.testcommand.handle(
             "project edit %s --name name2" % project_id, user)
         project.display_name = "name2"
         project_attach = [project.get_attachment()]
         expect = {'attachments': project_attach}
         self.assertDictEqual(resp, expect)
         self.assertEqual(code, 200)
     self.mock_facade.retrieve.assert_called_once_with(Project, project_id)
     self.mock_facade.store.assert_called_once_with(project)
Example #10
0
 def facade_retrieve_side_effect(*args, **kwargs):
     """Return a side effect for the mock facade."""
     if args[0] == Project:
         return Project("", [])
     else:
         calling_user = User(user)
         calling_user.permissions_level = Permissions.admin
         return calling_user
Example #11
0
 def facade_retrieve_side_effect(*args, **kwargs):
     """Return a side effect for the mock facade."""
     if args[0] == Project:
         return Project("GTID", [])
     elif args[0] == Team:
         return Team("GTID", "team-name", "display-name")
     else:
         return User(user)
Example #12
0
 def test_handle_force_assign(self):
     """Test project command force assign."""
     self.mock_facade.retrieve.return_value = Project("GTID", [])
     team = Team("GTID", "team-name", "display-name")
     team.team_leads.add(user)
     self.mock_facade.query.return_value = [team]
     self.assertTupleEqual(
         self.testcommand.handle("project assign ID team-name -f", user),
         ("Project successfully assigned!", 200))
Example #13
0
 def test_handle_assign_assign_error(self):
     """Test project command assign with assignment error."""
     self.mock_facade.retrieve.return_value = Project("GTID", [])
     team = Team("GTID", "team-name", "display-name")
     team.team_leads.add(user)
     self.mock_facade.query.return_value = [team]
     self.assertTupleEqual(
         self.testcommand.handle("project assign ID team-name", user),
         (self.testcommand.assigned_error, 200))
Example #14
0
 def facade_retrieve_side_effect(*args, **kwargs):
     """Return a side effect for the mock facade."""
     if args[0] == Project:
         return Project("", [])
     elif args[0] == Team:
         raise LookupError("user lookup error")
     else:
         calling_user = User(user)
         return calling_user
Example #15
0
 def facade_retrieve_side_effect(*args, **kwargs):
     """Return a side effect for the mock facade."""
     if args[0] == Project:
         return Project("", [])
     elif args[0] == Team:
         team = Team("GTID", "team-name", "display-name")
         return team
     else:
         raise LookupError("team lookup error")
Example #16
0
 def test_handle_create_as_team_lead(self, mock_uuid):
     """Test project command create parser as a team lead."""
     mock_uuid.uuid4.return_value = "1"
     team = Team("GTID", "team-name", "name")
     team.team_leads.add(user)
     self.mock_facade.query.return_value = [team]
     project = Project("GTID", ["repo-link"])
     project_attach = [project.get_attachment()]
     with self.app.app_context():
         resp, code = \
             self.testcommand.handle("project create repo-link team-name",
                                     user)
         expect = {'attachments': project_attach}
         self.assertDictEqual(resp, expect)
         self.assertEqual(code, 200)
     self.mock_facade.query.assert_called_once_with(
         Team, [("github_team_name", "team-name")])
     self.mock_facade.store.assert_called_once_with(project)
Example #17
0
def add():
    res = Project()
    res.name = request.form.get('name')
    res.description = request.form.get('description')
    res.userId = 1
    res.status = 'Y'
    db.session.add(res)
    db.session.commit()
    return jsonify({'code': 200, 'msg': res.to_json()})
Example #18
0
 def facade_retrieve_side_effect(*args, **kwargs):
     """Return a side effect for the mock facade."""
     if args[0] == Project:
         return Project("", [])
     elif args[0] == Team:
         team = Team("GTID", "team-name", "display-name")
         return team
     else:
         calling_user = User(user)
         calling_user.permissions_level = Permissions.admin
         return calling_user
Example #19
0
 def facade_retrieve_side_effect(*args, **kwargs):
     """Return a side effect for the mock facade."""
     if args[0] == Project:
         return Project("", [])
     elif args[0] == Team:
         team = Team("GTID", "team-name", "display-name")
         team.team_leads.add(user)
         return team
     else:
         calling_user = User(user)
         return calling_user
Example #20
0
def meeting_manage():
    project_name = request.args.get('projectName', None)
    page = int(request.args.get('page', 1)) - 1

    select = {}
    if project_name:
        project = Project.objects(projectName=project_name)
        if not project:
            return jsonify(build_response(data=[]))
        select['belongTo'] = str(project.id)

    meetings: List[Meeting] = Meeting.objects(**select)
    total_page = math.ceil(len(meetings) / number_per_page)
    meeting_list = []
    for meeting in meetings:
        belongTo = project_name if project_name else Project.get_project_by_id(
            meeting.belongTo).projectName
        meeting_list.append({
            'title':
            meeting.title,
            'belongTo':
            belongTo,
            'onlineNum':
            0 if str(meeting.id) not in sid_manager.rooms else len(
                sid_manager.get_meetingRoom_by_meetingId(str(
                    meeting.id)).member_list),
            'currentVideo':
            '' if str(meeting.id) not in sid_manager.rooms else
            sid_manager.get_meetingRoom_by_meetingId(str(
                meeting.id)).player.video.videoName,
            'alive':
            meeting.alive
        })

    data = {'totalPage': total_page, 'meetingList': meeting_list}
    return jsonify(build_response(data=data))
Example #21
0
def create_test_project(github_team_id: str,
                        github_urls: List[str]) -> Project:
    r"""
    Create a test project with project ID, URLs, and all other attributes set.

    ===============   =============================
    Property          Preset
    ===============   =============================
    ID                ``SHA1(github_urls[0], time.time())``
    Team ID           ``github_team_id``
    Github URLs       ``github_urls``
    Display Name      Rocket2
    Short Descrip.    Slack bot, team management, and onboarding system for...
    Long Descrip.     Slack bot, team management, and onboarding system for...
    Tags              python, docker, pipenv, waterboarding
    Website           https://github.com/ubclaunchpad/rocket2
    Appstore URL      ¯\\_(ツ)_/¯
    Playstore URL     ¯\\_(ツ)_/¯
    ===============   =============================

    :param github_team_id: The Github team ID
    :param github_urls: The URLs to all connected projects
    :return: a filled-in project model (no empty strings)
    """
    p = Project(github_team_id, github_urls)
    p.display_name = 'Rocket2'
    p.short_description = \
        'Slack bot, team management, and onboarding system for UBC Launch Pad'
    p.long_description = '''
        Slack bot, team management, and onboarding system for UBC Launch Pad
    '''
    p.tags = ['python', 'docker', 'pipenv', 'waterboarding']
    p.website_url = 'https://github.com/ubclaunchpad/rocket2'
    p.appstore_url = '¯\\_(ツ)_/¯'
    p.playstore_url = '¯\\_(ツ)_/¯'

    return p
Example #22
0
 def test_handle_list(self, mock_uuid):
     """Test project command list parser."""
     mock_uuid.uuid4.return_value = "1"
     project1 = Project("GTID1", ["a", "b"])
     project1.display_name = "project1"
     project2 = Project("GTID2", ["c", "d"])
     project2.display_name = "project2"
     self.mock_facade.query.return_value = [project1, project2]
     with self.app.app_context():
         resp, code = self.testcommand.handle("project list", user)
         expect = \
             "*PROJECT ID : GITHUB TEAM ID : PROJECT NAME*\n" \
             "1 : GTID1 : project1\n" \
             "1 : GTID2 : project2\n"
         self.assertEqual(resp, expect)
         self.assertEqual(code, 200)
     self.mock_facade.query.assert_called_once_with(Project)
Example #23
0
 def save(self):
     current_user = json.loads(get_jwt_claims())
     # 创建数据库
     project = Project()
     project.created_by = current_user.get('id')
     project.name = self.name
     project.path = self.path
     project.description = self.description
     project.visibility = self.visibility
     project.setting_auth_content = self.generate_setting_auth_content(
         current_user)
     project.final_auth_content = self.generate_final_auth_content(project)
     project.last_activity_on = datetime.now()
     project.save()
     try:
         MemberService().save_project_member(project.id, project.created_by,
                                             project.created_by, 50)
         # 创建仓库
         create_repository(project)
         # 初始化目录
         if self.initDirs:
             init_repo_dirs(project)
         # 保存权限
         save_authz(project)
     except SvnOperateException as e:
         delete_repository(project)
         project.delete_self()
         raise InvalidUsage(payload=(e.status, e.output))
     self.add_external_field(project)
     return project.to_json()
Example #24
0
def test_store_invalid_project(ddb):
    """Test handling of invalid project."""
    project = Project('12456', [''])
    project.github_urls = []
    success = ddb.store(project)
    assert not success
Example #25
0
 def facade_retrieve_side_effect(*args, **kwargs):
     """Return a side effect for the mock facade."""
     if args[0] == Project:
         return Project("GTID", [])
     else:
         raise LookupError("team lookup error")
Example #26
0
 def test_handle_delete_assign_error(self):
     """Test project command delete with assignment error."""
     self.mock_facade.retrieve.return_value = Project("GTID", [])
     self.assertTupleEqual(
         self.testcommand.handle("project delete ID", user),
         (self.testcommand.assigned_error, 200))
Example #27
0
 def test_store_invalid_project(self):
     project = Project('12456', [''])
     project.github_urls = []
     self.assertFalse(self.ddb.store(project))
Example #28
0
def index():
    return '<a href="/admin/">Click me to get to Admin!</a>'


def build_db():
    db.drop_all()
    db.create_all()
    case_list = []
    for i in range(10):
        case = Case()
        case.name = 'test_'+str(i+1)

        case.info.append(CaseInfo(key="foo", value="bar"))
        # case_list.append(case)
        db.session.add(case)
    # projects = list()
    for i in range(3):
        project = Project()
        project.name = 'project_' + str(i+1)
        db.session.add(project)
    db.session.commit()
    return


if __name__ == '__main__':

    app_dir = op.realpath(os.path.dirname(__file__))
    # database_path = op.join(app_dir, app.config['DATABASE_FILE'])
    # if not os.path.exists(database_path):
    #     build_db()
    app.run(debug = True,host='0.0.0.0')
Example #29
0
 def test_valid_project(self):
     """Test the Project static method is_valid()."""
     self.assertTrue(Project.is_valid(self.rocket2))