コード例 #1
0
def test_process_current_war_warday():
    config = load_config_file(False)

    war = ProcessedCurrentWar(config=config,
                              current_war=pyroyale.WarCurrent(
                                  state='warDay',
                                  war_end_time='20190209T212846.354Z',
                                  clan=__fake_war_clan__,
                                  participants=__fake_war_participants__,
                                  clans=[__fake_war_clan__]))

    assert war.state_label == 'War Day'
    assert war.collection_end_time_label == 'Complete'
    assert war.end_label
コード例 #2
0
def test_donations_score(tmpdir):
    config_file = tmpdir.mkdir('test_donations_score').join('testfile')
    config_file.write(__config_file_score__)
    config = load_config_file(config_file.realpath())

    calc = ScoreCalculator(config)

    war = ProcessedCurrentWar(
        config=config, current_war=pyroyale.WarCurrent(state='notInWar'))
    member_history = history.get_member_history(__fake_member_list__,
                                                config['crtools']['timestamp'],
                                                '{}', war)
    date = datetime(2019, 2, 12, 7, 32, 1, 0)

    member_6 = MemberFactory(config=config,
                             current_war=war,
                             clan=__fake_clan__,
                             member_history=member_history,
                             warlog=pyroyale.WarLog(items=[]),
                             days_from_donation_reset=6).get_processed_member(
                                 __fake_member_list__[0])
    member_3 = MemberFactory(config=config,
                             current_war=war,
                             clan=__fake_clan__,
                             member_history=member_history,
                             warlog=pyroyale.WarLog(items=[]),
                             days_from_donation_reset=3).get_processed_member(
                                 __fake_member_list__[0])
    member_0 = MemberFactory(config=config,
                             current_war=war,
                             clan=__fake_clan__,
                             member_history=member_history,
                             warlog=pyroyale.WarLog(items=[]),
                             days_from_donation_reset=0).get_processed_member(
                                 __fake_member_list__[0])

    assert calc.get_member_donations_score(member_6) == 11
    assert calc.get_member_donations_score(member_3) == 18
    assert calc.get_member_donations_score(member_0) == 31
コード例 #3
0
def test_get_suggestions_nosuggestions(tmpdir):
    config_file = tmpdir.mkdir('test_get_suggestions').join('testfile')
    config_file.write(
        __config_file_score__ +
        '\nthreshold_demote=-999999\nthreshold_promote=9999999\nmin_clan_size={}'
        .format(crtools.MAX_CLAN_SIZE))
    config = load_config_file(config_file.realpath())

    war = ProcessedCurrentWar(
        config=config, current_war=pyroyale.WarCurrent(state='notInWar'))
    factory = MemberFactory(config=config,
                            member_history=history.get_member_history(
                                __fake_clan__.member_list,
                                config['crtools']['timestamp'], '{}', war),
                            current_war=war,
                            clan=__fake_clan__,
                            warlog=pyroyale.WarLog(items=[]))

    members = []
    for i in range(0, crtools.MAX_CLAN_SIZE):
        member = factory.get_processed_member(
            pyroyale.ClanMember(tag="#AAAAAA",
                                name="LeaderPerson",
                                role="leader",
                                exp_level=13,
                                trophies=9999,
                                donations=9999,
                                arena=pyroyale.Arena(id=54000012,
                                                     name='Legendary Arena'),
                                last_seen="20190802T154619.000Z"))
        member.safe = True
        members.append(member)

    suggestions = crtools.get_suggestions(config, members,
                                          __fake_clan__.required_trophies)

    assert len(suggestions) == 1
    assert suggestions[-1] == config['strings']['suggestionNone']
コード例 #4
0
            "events": [
                {
                    "event": "join",
                    "status": "new",
                    "role": "member",
                    "date": 0
                }
            ]
        }

    }
}

__fake_currentwar__ = ProcessedCurrentWar(config=load_config_file(False), current_war=pyroyale.WarCurrent(
        state               = 'collectionDay',
        collection_end_time = '20190209T212846.354Z',
        participants        = [pyroyale.WarParticipant(tag='#AAAAAA', cards_earned=0)]
    ))

def test_get_role_change_status():
    assert history.get_role_change_status('foo',                 'foo')                 == False
    assert history.get_role_change_status('foo',                 'bar')                 == False
    assert history.get_role_change_status('foo',                 history.ROLE_MEMBER)   == False
    assert history.get_role_change_status(history.ROLE_MEMBER,   'foo')                 == False
    assert history.get_role_change_status('foo',                 'foo')                 == False
    assert history.get_role_change_status(history.ROLE_LEADER,   history.ROLE_LEADER)   == 'unchanged'
    assert history.get_role_change_status(history.ROLE_LEADER,   history.ROLE_COLEADER) == 'demotion'
    assert history.get_role_change_status(history.ROLE_LEADER,   history.ROLE_ELDER)    == 'demotion'
    assert history.get_role_change_status(history.ROLE_LEADER,   history.ROLE_MEMBER)   == 'demotion'
    assert history.get_role_change_status(history.ROLE_COLEADER, history.ROLE_COLEADER) == 'unchanged'
    assert history.get_role_change_status(history.ROLE_COLEADER, history.ROLE_LEADER)   == 'promotion'
コード例 #5
0
def build_dashboard(config):  # pragma: no coverage
    """Compile and render clan dashboard."""

    # Create temporary directory. All file writes, until the very end,
    # will happen in this directory, so that no matter what we do, it
    # won't hose existing stuff.
    tempdir = tempfile.mkdtemp(config['paths']['temp_dir_name'])

    # get API instance
    configuration = pyroyale.Configuration()
    configuration.api_key['authorization'] = config['api']['api_key']
    if config['api']['proxy']:
        configuration.proxy = config['api']['proxy']
    if config['api']['proxy_headers']:
        configuration.proxy_headers = config['api']['proxy_headers']
    api = pyroyale.ClansApi(pyroyale.ApiClient(configuration))

    print('- requesting info for clan id: {}'.format(config['api']['clan_id']))

    # Putting everything in a `try`...`finally` to ensure `tempdir` is removed
    # when we're done. We don't want to pollute the user's disk.
    try:
        output_path = os.path.expanduser(config['paths']['out'])

        # Get clan data and war log from API.
        clan = api.get_clan(config['api']['clan_id'])
        warlog = api.get_clan_war_log(config['api']['clan_id'])
        current_war = api.get_current_war(config['api']['clan_id'])

        print('- clan: {} ({})'.format(clan.name, clan.tag))

        # process data from API
        current_war_processed = ProcessedCurrentWar(current_war, config)
        clan_processed = ProcessedClan(clan, current_war_processed, config)

        member_history = history.get_member_history(
            clan.member_list, io.get_previous_history(output_path),
            current_war_processed)

        members_processed = process_members(config, clan, warlog,
                                            current_war_processed,
                                            member_history)
        recent_wars = process_recent_wars(config, warlog)
        former_members = process_absent_members(config,
                                                member_history['members'])

        io.parse_templates(
            config, member_history, tempdir, clan_processed, members_processed,
            former_members, current_war_processed, recent_wars,
            get_suggestions(config, members_processed,
                            clan_processed.required_trophies),
            get_scoring_rules(config))

        if (config['crtools']['debug'] == True):
            # archive outputs of API for debugging
            io.dump_debug_logs(
                tempdir, {
                    'clan':
                    clan.to_dict(),
                    'warlog':
                    warlog.to_dict(),
                    'current_war':
                    current_war.to_dict(),
                    'clan-processed':
                    clan_processed,
                    'members-processed':
                    members_processed,
                    'current_war-processed':
                    current_war_processed,
                    'recentwars-processed':
                    list(map(lambda war: war.to_dict(), recent_wars))
                })

        # if fankit is previously downloaded, it will copy fankit. Otherwise,
        # if fankit is enabled, it will download it.
        fankit.get_fankit(tempdir, output_path, config['paths']['use_fankit'])

        io.copy_static_assets(tempdir, config['paths']['clan_logo'],
                              config['paths']['favicon'])

        io.move_temp_to_output_dir(tempdir, output_path)

        discord.trigger_webhooks(config, current_war.to_dict(),
                                 members_processed)

    except ApiException as e:
        logger.error('error: {}'.format(e))

    finally:
        # Ensure that temporary directory gets deleted no matter what
        shutil.rmtree(tempdir)
コード例 #6
0
def build_dashboard(config):  # pragma: no coverage
    """Compile and render clan dashboard."""

    print('- requesting info for clan id: {}'.format(config['api']['clan_id']))

    api = ApiWrapper(config)

    clan = api.get_data_from_api()

    warlog = pyroyale.WarLog(items=[])
    current_war = pyroyale.WarCurrent(state='notInWar')

    war_readiness_map = {}
    if config['member_table']['calc_war_readiness'] == True:
        war_readiness_map = api.get_war_readiness_map(clan.member_list,
                                                      clan.clan_war_trophies)

    # Create temporary directory. All file writes, until the very end,
    # will happen in this directory, so that no matter what we do, it
    # won't hose existing stuff.
    tempdir = tempfile.mkdtemp(config['paths']['temp_dir_name'])

    # Putting everything in a `try`...`finally` to ensure `tempdir` is removed
    # when we're done. We don't want to pollute the user's disk.
    try:
        output_path = os.path.expanduser(config['paths']['out'])

        # process data from API
        current_war_processed = ProcessedCurrentWar(current_war, config)
        clan_processed = ProcessedClan(clan, current_war_processed, config)

        member_history = history.get_member_history(
            clan.member_list, config['crtools']['timestamp'],
            io.get_previous_history(output_path), current_war_processed)

        members_processed = process_members(config, clan, warlog,
                                            current_war_processed,
                                            member_history, war_readiness_map)
        recent_wars = process_recent_wars(config, warlog)
        former_members = process_absent_members(config,
                                                member_history['members'])

        io.parse_templates(
            config, member_history, tempdir, clan_processed, members_processed,
            former_members, current_war_processed, recent_wars,
            get_suggestions(config, members_processed,
                            clan_processed.required_trophies),
            get_scoring_rules(config))

        if (config['crtools']['debug'] == True):
            # archive outputs of API for debugging
            io.dump_debug_logs(
                tempdir, {
                    'clan':
                    clan.to_dict(),
                    'warlog':
                    warlog.to_dict(),
                    'current_war':
                    current_war.to_dict(),
                    'clan-processed':
                    clan_processed,
                    'members-processed':
                    members_processed,
                    'current_war-processed':
                    current_war_processed,
                    'recentwars-processed':
                    list(map(lambda war: war.to_dict(), recent_wars))
                })

        # if fankit is previously downloaded, it will copy fankit. Otherwise,
        # if fankit is enabled, it will download it.
        fankit.get_fankit(tempdir, output_path, config['paths']['use_fankit'])

        io.copy_static_assets(tempdir, config['paths']['clan_logo'],
                              config['paths']['favicon'])

        io.move_temp_to_output_dir(tempdir, output_path)

        discord.trigger_webhooks(config, current_war, members_processed)

    except Exception as e:
        logger.error('error: {}'.format(e))

        if (config['crtools']['debug'] == True):
            logger.error(traceback.format_exc())

    finally:
        # Ensure that temporary directory gets deleted no matter what
        shutil.rmtree(tempdir)
コード例 #7
0
def test_war_score(tmpdir):

    config_file = tmpdir.mkdir('test_war_score').join('testfile')
    config_file.write(__config_file_score__)
    config = load_config_file(config_file.realpath())

    calc = ScoreCalculator(config)

    war_complete = ProcessedCurrentWar(config=config,
                                       current_war=__fake_current_war__)
    war_complete.status = 'na'
    war_complete.battles_played = 1
    war_complete.wins = 1
    war_complete.collection_day_battles_played = 3
    war_complete.collection_battle_wins = 2
    war_complete.collection_battle_losses = 0
    assert calc.get_war_score(war_complete) == 24

    war_incomplete = ProcessedCurrentWar(config=config,
                                         current_war=__fake_current_war__)
    war_incomplete.status = 'na'
    war_incomplete.battles_played = 0
    war_incomplete.wins = 0
    war_incomplete.collection_day_battles_played = 3
    war_incomplete.collection_battle_wins = 2
    war_incomplete.collection_battle_losses = 0
    assert calc.get_war_score(war_incomplete) == -26

    war_na = WarParticipation(config=config,
                              member=ProcessedMember(__fake_member_list__[4]),
                              war=__fake_war__)
    assert calc.get_war_score(war_na) == -1

    war_new = WarParticipation(config=config,
                               member=ProcessedMember(__fake_member_list__[4]),
                               war=__fake_war__)
    war_new.status = 'not-in-clan'
    assert calc.get_war_score(war_new) == 0