Exemple #1
0
 def set_score(self, tourney_id: str, match_id: str, p1_score: int,
               p2_score: int, winner_id: str):
     util.make_request(CHALLONGE_API,
                       f'/tournaments/{tourney_id}/matches/{match_id}.json',
                       params={'api_key': self._api_key},
                       data={
                           'match': {
                               'scores_csv': f'{p1_score}-{p2_score}',
                               'winner_id': winner_id,
                           }
                       },
                       method='PUT',
                       raise_exception_on_http_error=True)
Exemple #2
0
    def create_tournament(self,
                          name,
                          tournament_type=TourneyType.DOUBLE_ELIM,
                          is_unlisted=True) -> Tuple[str, str]:
        """
        Creates a tournament with the given name.
        Returns the tournament ID and url.
        """
        payload = {
            'tournament': {
                'name': f'{name}',
                # We add unique-ish gibberish to the end to make sure that the url is available.
                # The TO can always change the URL later.
                'url': f'{name}_{str(uuid.uuid1()).replace("-", "_")}',
                'tournament_type': tournament_type.value,
                'private': is_unlisted,
            }
        }
        resp = util.make_request(CHALLONGE_API,
                                 '/tournaments.json',
                                 params={'api_key': self._api_key},
                                 data=payload,
                                 raise_exception_on_http_error=False)

        if 'tournament' not in resp:
            raise ValueError(
                "Bracket creation unsuccessful. Challonge returned the following error(s): \n * "
                + '\n * '.join(resp['errors']))

        return resp['tournament']['id'], resp['tournament'][
            'full_challonge_url']
def get_projects(base_url, ticket):
    url = base_url + "/alfresco/service/projects?alf_ticket=%s" % (ticket)
    print(url)
    headers = {"Content-Type": "application/json"}
    projects = json.load(util.make_request(url, headers)).get('projects')
    project_elastic = {}
    project_ids = []
    project_instances = {}
    for project in projects:
        projectId = project['id']
        project_elastic[project['id']] = project['_elasticId']
        project_ids.append(projectId)
        viewInstanceBinUrl = base_url + '/alfresco/service/projects/%s/refs/master/elements/%s?alf_ticket=%s' % (
            projectId, 'view_instances_bin_' + projectId, ticket)
        viewInstanceBin = json.load(
            util.make_request(viewInstanceBinUrl, headers)).get('elements')[0]
        project_instances[projectId] = viewInstanceBin['_elasticId']
    return set(project_ids), project_elastic, project_instances
def test_case04(the_cfg):
    """testcase04-实名认证结果查询接口"""
    test_code = click.prompt('\n>>> 请输入《testcase04-实名认证结果查询接口》测试码', type=str)
    url = URL % test_code

    data = {"ai": "100000000000000001"}

    response = make_request(url, data, the_cfg, method="GET")
    result = response.json()
    assert result["errcode"] == 0 and result["data"]["result"]["status"] == 0
Exemple #5
0
    def list_matches(self, tourney_id: str) -> List[Match]:
        matches = util.make_request(CHALLONGE_API,
                                    f'/tournaments/{tourney_id}/matches.json',
                                    params={
                                        'api_key': self._api_key,
                                        'state': "open"
                                    },
                                    raise_exception_on_http_error=True)

        # Strip out the useless envelope-ish object
        # (an abject with 1 property, "match", and that's it.)
        return [_to_match(m) for m in matches]
Exemple #6
0
    def update_username(self, tourney_id: str, player: data.Player, name: str):
        """
        Updates a player's username in challonge.
        Returns true iff the user was present in the tournament.

        Note that the "username" is not the display name - it is the actual
        username of the account, so they can update their own scores.
        """

        payload = {
            'participant': {
                'challonge_username': name,
            }
        }
        util.make_request(
            CHALLONGE_API,
            f'/tournaments/{tourney_id}/participants/{player.challonge_id}.json',
            params={'api_key': self._api_key},
            data=payload,
            raise_exception_on_http_error=True,
            method='PUT',
        )
def get_commits_by_ref(base_url, ticket, projectId, refs):
    # http://localhost:8080/alfresco/service/projects/PA/refs/master/history
    commits = []
    for ref in refs:
        url = base_url + "/alfresco/service/projects/%s/refs/%s/history?alf_ticket=%s" % (
            projectId, ref, ticket)
        headers = {"Content-Type": "application/json"}
        # :TODO check for project or ref object and add elasticId instead
        for commit in json.load(util.make_request(url,
                                                  headers)).get('commits'):
            commits.append(commit['id'])
    # set should guarantee uniqueness
    return set(commits)
def test_case01(the_cfg):
    """testcase01-实名认证接口

    实名认证结果(认证成功) data.result.status == 0
    """
    test_code = click.prompt('\n>>> 请输入《testcase01-实名认证接口》测试码', type=str)
    url = URL % test_code
    data = {
        "ai": "100000000000000001",
        "name": "某一一",
        "idNum": "110000190101010001"
    }
    response = make_request(url, data, the_cfg)
    result = response.json()
    assert result["errcode"] == 0 and result["data"]["result"]["status"] == 0
def get_refs_by_project(base_url, ticket, projects):
    project_refs = {}
    refs_elastic_ids = {}
    for projectId in projects:
        url = base_url + "/alfresco/service/projects/%s/refs?alf_ticket=%s" % (
            projectId, ticket)
        headers = {"Content-Type": "application/json"}
        refs = json.load(util.make_request(url, headers)).get('refs')
        refIds = []
        refsElastic = []
        for ref in refs:
            refId = ref['id'].replace('-', '_')
            refIds.append(refId)
            refsElastic.append(ref['_elasticId'])
        project_refs[projectId] = refIds
        refs_elastic_ids[projectId] = (refsElastic)
    return project_refs, refs_elastic_ids
Exemple #10
0
def get_contributors(token):
    """
    Parameters:
    token: authorization token

    Returns:
    list of Contributor objects
    """

    i = 1
    contributors_list = []

    while True:
        params = {"per_page": "100", "page": str(i), "anon": "1"}
        url = "https://api.github.com/repos/facebook/react/contributors"
        contributors = make_request(url, token, params=params)

        print("REQUEST FOR " + str(i) + " PAGE OK")

        if not contributors:
            break

        i += 1

        for contributor in contributors:
            print(contributor)
            if contributor["type"] == "User" or contributor["type"] == "Bot":
                login = contributor["login"]
                id = contributor["id"]
                url = contributor["url"]
                repos_url = contributor["repos_url"]
                site_admin = contributor["site_admin"]
                contributions = contributor["contributions"]
                contributor_obj = UserContributor(login, id, url, repos_url,
                                                  site_admin, contributions)
            elif contributor["type"] == "Anonymous":
                email = contributor["email"]
                name = contributor["name"]
                contributions = contributor["contributions"]
                contributor_obj = AnonymousContributor(email, name,
                                                       contributions)

                contributors_list.append(contributor_obj)

    return contributors_list
Exemple #11
0
def write_to_json_commits_per_day(token, day):
    """
    Parameters:
    token: authorization token
    day: day of commits we want to retrieve
    """

    begin = day.replace(hour=0, minute=0, second=0)
    begin = begin.strftime("%Y-%m-%dT%H:%M:%SZ")
    end = day.replace(hour=23, minute=59, second=59)
    end = end.strftime("%Y-%m-%dT%H:%M:%SZ")

    file_output = day.strftime("%Y%m%d")

    commits_list = []

    i = 1
    while True: 
        params = {
            "per_page": "100",
            "page": str(i), 
            "since": begin,
            "until": end
        }
        url = "https://api.github.com/repos/facebook/react/commits"
        commits = make_request(url, token, params=params)
        print(commits)
        if not commits: 
            break
        
        i += 1
        nb_commits = 0
        for commit in commits:
            sha = commit["sha"]
            date = commit["commit"]["author"]["date"]
            contributor = get_contributor_from_dict(commit["author"])
            commit_obj = Commit(sha, date, contributor)
            commits_list.append(commit_obj)
            nb_commits += 1

        if nb_commits < 100: 
            break

    write_to_json("commits/" + file_output + ".json", commits_list)
Exemple #12
0
    def add_players(self, tourney_id, names: List[str]) -> Dict[str, str]:
        """
        Adds the list of participant names to the tournament with the given tourney_id.
        Returns a map of the given names to their challonge participant IDs.
        """
        payload = {
            'participants': [{
                "name": n
            } for n in names],
        }
        resp = util.make_request(
            CHALLONGE_API,
            f'/tournaments/{tourney_id}/participants/bulk_add.json',
            params={'api_key': self._api_key},
            data=payload,
            raise_exception_on_http_error=True)

        # Response format is a list of dicts, all with one property "participant".
        # Convert into dict of players by name.
        return {p['participant']['name']: p['participant']['id'] for p in resp}
Exemple #13
0
 def request_and_verify(case):
     vul = case.vul
     method = case.method
     url = case.url
     headers = case.headers
     body = case.body
     args = case.args
     old_param = args[2]
     old_value = args[3]
     print 'Verify case use:\n%s' % url
     # time out
     with gevent.Timeout(20, False) as t:
         resp = make_request(method, url, headers, body)
         if resp:
             if Verify.verify(resp, args):
                 poc = gen_poc(method, url, body, old_param, old_value)
                 print_warn('Found %s in %s' % (vul, poc))
                 result = (vul, url, poc)
                 return result
         # count++ when error happened
         else:
             Verify.ERROR_COUNT += 1
Exemple #14
0
    def list_player_names_by_id(self, tourney_id: str) -> Dict[str, str]:
        """
        Returns a map of player IDs to player names in challonge.

        Uses the official challonge username for a player if it is set.
        If the challonge username is not set, returns the nickname used by that player in the bracket.
        """
        player_objs = util.make_request(
            CHALLONGE_API,
            f'/tournaments/{tourney_id}/participants.json',
            {'api_key': self._api_key},
            raise_exception_on_http_error=True)

        names_by_id = {}
        for p in player_objs:
            # Each player object has only one key, 'participant',
            # mapped to another object that actually has the info we want.
            p = p['participant']
            name = p['challonge_username'] if p['challonge_username'] else p[
                'name']
            names_by_id[p['id']] = name

        return names_by_id
Exemple #15
0
def test_case08(the_cfg):
    """testcase08-游戏用户行为数据上报接口

    认证用户行为上报
    """
    test_code = click.prompt('\n>>> 请输入《testcase08-游戏用户行为数据上报接口》测试码', type=str)
    url = URL % test_code

    data = {
        "collections": [{
            "no": 1,
            "si": "sessionid_1000101",
            "bt": 0,  # 0 下线 1 上线
            "ot": int(time.time()),
            "ct": 0,  # 2 已认证用户
            "di": "youke_10010231",
            "pi": "1fffbjzos82bs9cnyj1dna7d6d29zg4esnh99u",
        }]
    }

    response = make_request(url, data, the_cfg)
    result = response.json()
    assert result["errcode"] == 0
Exemple #16
0
 def request_and_verify(case):
     vul = case.vul
     method = case.method
     url = case.url
     headers = case.headers
     body = case.body
     args = case.args
     old_param = args[2]
     old_value = args[3]
     LOGGER.info('Verify: %s' % url)
     # time out
     with gevent.Timeout(20, False) as t:
         resp = make_request(method, url, headers, body)
         if resp:
             if Verify.verify(resp, args):
                 poc = gen_poc(method, url, body, old_param, old_value)
                 LOGGER.critical(
                     'Found cross-site script vulnerability(%s) in %s' %
                     (vul, poc))
                 result = (vul, url, poc)
                 return result
         # count++ when error happened
         else:
             Verify.ERROR_COUNT += 1
Exemple #17
0
def get_projects(base_url, ticket):
    url = base_url + "/alfresco/service/projects?alf_ticket=%s" % (ticket)
    print(url)
    headers = {"Content-Type": "application/json"}
    return util.make_request(url, headers)