Exemple #1
0
 def __init__(self, config, sql_echo=False):
     self.engine = create_engine(config['database'], echo=sql_echo)
     self.blizzard_api = WowApi(**config['api']['blizzard'],
                                retry_conn_failures=True)
     self.request_session = requests.Session()
     self.config_characters = config['characters']
     self.make_session = sessionmaker(self.engine)
Exemple #2
0
    def __init__(self, bot):
        bot.log.info(f"loaded {__name__}")

        self.bot = bot
        self.config = self.bot.config["wow"]
        self.api = WowApi(self.config["wow_id"], self.config["wow_secret"])
        self.regions = ["eu", "us"]
Exemple #3
0
async def checkServer(offChecking):
    api = WowApi(bnet_cid, bnet_secret)
    realm = api.get_connected_realm(region='us',
                                    namespace='dynamic-us',
                                    locale='pt_BR',
                                    id=realmID)
    if 'UP' not in str(realm) and "Online" in realmStatus:
        await client.get_channel(announcementChannel).send(
            "Parace que o servidor caiu, pessoal, vou avisar aqui quando voltar, mas qualquer coisa podem pedir pra eu avisar por DM."
        )
        realmStatus.pop()
        realmStatus.append("Offline")
        if offChecking:
            return False
    elif 'UP' in str(realm) and "Offline" in realmStatus:
        await client.get_channel(announcementChannel).send(
            "O servidor voltou, pessoal!")
        for player in warnList:
            await player.send("O servidor voltou, bro, bora lá.")
        warnList.clear()
        realmStatus.pop()
        realmStatus.append("Online")
        if offChecking:
            return False
    elif offChecking:
        return True
    if 'UP' not in str(realm):
        return False
    else:
        return True
Exemple #4
0
    def test_get_resource_no_api_key(self):
        del os.environ['WOWAPI_APIKEY']

        with pytest.raises(WowApiConfigException) as exc:
            WowApi.get_resource('foo/', 'us')

        assert "WOWAPI_APIKEY is missing from your env variables" in str(exc)
    def setup(self):
        self.params = {'access_token': 'secret'}

        self.api = WowApi('client-id', 'client-secret')
        self.api._access_tokens = {
            'us': {
                'token': 'secret',
                'expiration': datetime.utcnow() + timedelta(hours=1)
            }
        }
Exemple #6
0
    def __init__(self):
        self.config = self.read_config()
        self.api = WowApi(
            client_id=self.config['API']['id'],
            client_secret=self.config['API']['key']
        )

        # Game data
        # self.regions = self.get_regions()
        # self.realms = self.get_realms()
        self.auctions = self.get_auctions()
Exemple #7
0
 def get_resource_with_filters(self, get_mock):
     WowApi.get_resource('foo/{0}', 'us', 1, locale='en_US', fields='pets,stats', breedId=9999)
     get_mock.assert_called_with(
         'https://us.api.battle.net/wow/foo/1/',
         params={
             'apikey': 'foo',
             'locale': 'en_US',
             'fields': 'pets,stats',
             'breedId': 9999
         }
     )
Exemple #8
0
def get_mounts(user, realm):
    mounts = WowApi.get_character_profile('us', realm, user, fields=['mounts'])
    user_mount_list = []
    for x in range(len(mounts['mounts']['collected'])):
        mount_name = mounts['mounts']['collected'][x]['name']
        user_mount_list.append(mount_name)
    return user_mount_list
Exemple #9
0
class Singleton: #singleton class - copied right out of the class notes, This object contains variables that should only be read and so only one singleton should exist

	__instance = None #class variable hidden, set to none
	r = redis.Redis( #this is the required information for using the redis wrapper.
	host="redis-14585.c11.us-east-1-3.ec2.cloud.redislabs.com",
	port="14585",
	password="******",
	decode_responses=True
	)
	w = WowApi('d8ce5f1aecbd4edb800cbd753ac529a6', 'eZtkVNmDUxqjHd8Pn0msignc3xvBh5v5') #these are my personal API codes for the battlenet API

	@staticmethod
	def getInstance():
		if Singleton.__instance == None: #if its set to none - return the singleton class
			Singleton()
		else:
			return Singleton.__instance #if its not == none, return the instance of the singleton that was made before


	def __init__(self):
		if Singleton.__instance != None: #if instance is not = to None
			raise Exception("singleton already created") #display error 

		else:
			Singleton.__instance = self #if we dont have it created, set the instance to itself

	def cls(self):
		os.system('cls' if os.name=='nt' else 'clear')
Exemple #10
0
def update_realms():
    api = WowApi(APIconfig.CLIENT_ID, APIconfig.CLIENT_SECRET)
    cnx = mysql.connector.connect(
        host=MySQLconfig.MYSQL_HOST,
        user=MySQLconfig.MYSQL_USER,
        passwd=MySQLconfig.MYSQL_PASSWORD,
        database=MySQLconfig.MYSQL_DATABASE,
    )
    cursor = cnx.cursor()
    realms = api.get_realm_status("eu")
    for realm_n in realms["realms"]:
        print("Inserting:", realm_n["name"], "into database!")
        sql = """INSERT INTO realms (name)
        VALUES (%s) ON DUPLICATE KEY UPDATE name = VALUES(name);"""
        val = (realm_n["name"],)
        cursor.execute(sql, val)
        cnx.commit()
        print(cursor.rowcount, "records inserted/updated.")
    cnx.close()
Exemple #11
0
    def setup(self):
        self.params = {'access_token': 'secret'}

        self.api = WowApi('client-id', 'client-secret')

        self.authorized_api = WowApi('client-id', 'client-secret')
        self.authorized_api._access_tokens = {
            'us': {
                'token': 'secret',
                'expiration': datetime.utcnow() + timedelta(hours=1)
            },
            'cn': {
                'token': 'secret',
                'expiration': datetime.utcnow() + timedelta(hours=1)
            }
        }

        self.test_url = 'http://example.com'
        self.default_region = 'us'
Exemple #12
0
    def setup(self):
        self.params = {'access_token': 'secret'}

        self.api = WowApi('client-id', 'client-secret')

        self.authorized_api = WowApi('client-id', 'client-secret')
        self.authorized_api._access_tokens = {
            'us': {
                'token': 'secret',
                'expiration': datetime.utcnow() + timedelta(hours=1)
            },
            'cn': {
                'token': 'secret',
                'expiration': datetime.utcnow() + timedelta(hours=1)
            }
        }

        self.test_url = 'http://example.com'

        self.default_region = 'us'
Exemple #13
0
async def char(char_name: str, char_realm: str):
    char_profile = wow.get_character_profile('us', char_realm, char_name, fields='guild')
    char_url = "https://worldofwarcraft.com/en-us/character/" + char_realm.lower() + "/" + char_name.lower()

    char_avatar = "http://render-us.worldofwarcraft.com/character/" + char_profile['thumbnail']
    char_main = char_avatar.replace('avatar', 'main')
    char_inset = char_avatar.replace('avatar', 'inset')

    embed = discord.Embed(title="<" + char_profile['guild']['name'] + ">, " + char_realm.capitalize(),
                          colour=discord.Colour(0x457b86),
                          url=char_url,
                          description="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque blandit est est, id tincidunt ipsum porttitor nec. Pellentesque laoreet ligula ut lorem tempus, quis sagittis mauris sollicitudin.",
                          timestamp=datetime.datetime.now(pytz.timezone('US/Pacific')))

    embed.set_image(url=char_main)
    embed.set_thumbnail(url=char_inset)
    embed.set_author(name=char_name.capitalize() + " (" + str(char_profile['level']) + ")", url=char_url,
                     icon_url=char_avatar)
    embed.set_footer(text="butts", icon_url="https://i.imgur.com/JhcBs0o.png")

    embed.add_field(name="<:alliance:472975393872150542>", value="ding", inline=True)
    embed.add_field(name="<:horde:472975380299644959>", value="dong", inline=True)

    await client.say(embed=embed)
from wowapi import WowApi
import csv


client = document_client.DocumentClient(config_cosmos_db.COSMOSDB_HOST, {'masterKey': config_cosmos_db.COSMOSDB_KEY})

# Create database
db = client.CreateDatabase({ 'id': config_cosmos_db.COSMOSDB_DATABASE })

# Create collections
realm_collection = client.CreateCollection(db['_self'],{ 'id': config_cosmos_db.COSMOSDB__REALM_COLLECTION })
mount_collection = client.CreateCollection(db['_self'],{ 'id': config_cosmos_db.COSMOSDB__MOUNT_COLLECTION })
model_collection = client.CreateCollection(db['_self'],{ 'id': config_cosmos_db.COSMOSDB__MODEL_COLLECTION })

#Gets a list of realms from the wowapi. Creats a document for each realm. 
realms = WowApi.get_realm_status('us')
realm_counter = 0
for realm in realms['realms']:
    realm_name = realms["realms"][realm_counter]['name']
    realm_counter +=1
    realm_document = client.CreateDocument(realm_collection['_self'],
        { 'id': realm_name,
          'realm_name': realm_name + " (US)",
          'name': realm_name 
        })      
      
#Gets a list of mounts from the wowapi. Creats a document for each realm. Using mount name + itemID for document ID. 
mounts = WowApi.get_mounts('us')
mount_counter = 0
for mount in mounts['mounts']:
    mount_name = mounts["mounts"][mount_counter]['name']
import logging
import os
from pprint import pprint

from wowapi import WowApi


logger = logging.getLogger('wowapi')
logger.setLevel(logging.INFO)
handler = logging.StreamHandler()
handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)

logger.info('Community API Example')

api = WowApi(os.environ['WOW_CLIENT_ID'], os.environ['WOW_CLIENT_SECRET'])
data = api.get_auctions('eu', 'silvermoon', locale='de_DE')
pprint(data)

data = api.get_realm_status('us')
pprint(data)
Exemple #16
0
 def test_get_region_leaderboard(self, get_mock):
     WowApi.get_region_leaderboard('us')
     get_mock.assert_called_with(
         'https://us.api.battle.net/wow/challenge/region', params=self.params)
Exemple #17
0
 def test_get_auctions(self, get_mock):
     WowApi.get_auctions('us', 'khadgar')
     get_mock.assert_called_with(
         'https://us.api.battle.net/wow/auction/data/khadgar', params=self.params)
Exemple #18
0
 def test_get_achievement(self, get_mock):
     WowApi.get_achievement('us', 1234)
     get_mock.assert_called_with(
         'https://us.api.battle.net/wow/achievement/1234', params=self.params)
Exemple #19
0
 def test_get_character_classes(self, get_mock):
     WowApi.get_character_classes('us')
     get_mock.assert_called_with(
         'https://us.api.battle.net/wow/data/character/classes', params=self.params)
Exemple #20
0
 def test_get_boss(self, get_mock):
     WowApi.get_boss('us', 24723)
     get_mock.assert_called_with(
         'https://us.api.battle.net/wow/boss/24723', params=self.params)
Exemple #21
0
    def test_get_resource_wrong_region_arg(self):
        with pytest.raises(WowApiConfigException) as exc:
            WowApi.get_resource('foo/', 'za')

        assert "Region 'za' not a valid region" in str(exc)
Exemple #22
0
 def test_get_character_profile(self, get_mock):
     WowApi.get_character_profile('eu', 'khadgar', 'patchwerk')
     get_mock.assert_called_with(
         'https://eu.api.battle.net/wow/character/khadgar/patchwerk', params=self.params)
Exemple #23
0
 def test_get_guild_achievements(self, get_mock):
     WowApi.get_guild_achievements('us')
     get_mock.assert_called_with(
         'https://us.api.battle.net/wow/data/guild/achievements', params=self.params)
Exemple #24
0
class TestWowApi(object):
    def setup(self):
        self.params = {'access_token': 'secret'}

        self.api = WowApi('client-id', 'client-secret')

        self.authorized_api = WowApi('client-id', 'client-secret')
        self.authorized_api._access_tokens = {
            'us': {
                'token': 'secret',
                'expiration': datetime.utcnow() + timedelta(hours=1)
            },
            'cn': {
                'token': 'secret',
                'expiration': datetime.utcnow() + timedelta(hours=1)
            }
        }

        self.test_url = 'http://example.com'
        self.default_region = 'us'

    def test_instance(self):
        assert not self.api._access_tokens

    def test_handle_request_success(self, session_get_mock):
        session_get_mock.return_value = ResponseMock()(200, b'{}')
        data = self.api._handle_request(self.test_url)
        assert data == {}
        session_get_mock.assert_called_with(self.test_url)

    def test_handle_request_request_exception(self, session_get_mock):
        session_get_mock.side_effect = RequestException('Error')
        with pytest.raises(WowApiException) as exc:
            self.api._handle_request(self.test_url)

        assert 'Error' in str(exc.value)

    def test_handle_request_invalid_json(self, session_get_mock):
        session_get_mock.return_value = ResponseMock()(200, b'{"foo": "bar"},')
        with pytest.raises(WowApiException) as exc:
            self.api._handle_request(self.test_url)

        assert 'Invalid Json' in str(exc.value)

    def test_handle_request_404(self, session_get_mock):
        session_get_mock.return_value = ResponseMock()(404, b'{}')
        with pytest.raises(WowApiException) as exc:
            self.api._handle_request(self.test_url)

        assert '404' in str(exc.value)

    def test_get_data_resource_authorized(self, session_get_mock):
        session_get_mock.return_value = ResponseMock()(200, b'{}')
        self.authorized_api.get_data_resource(
            'https://us.api.blizzard.com/profile/wow/test', 'us')
        session_get_mock.assert_called_with(
            'https://us.api.blizzard.com/profile/wow/test',
            params={'access_token': 'secret'})

    def test_get_data_resource_unauthorized(self, session_get_mock):
        session_get_mock.return_value = ResponseMock()(200, b'{}')
        self.api.get_data_resource(
            'https://us.api.blizzard.com/profile/wow/test', 'us')
        session_get_mock.assert_called_with(
            'https://us.api.blizzard.com/profile/wow/test', params={})

    def test_get_data_resource_filters(self, session_get_mock):
        session_get_mock.return_value = ResponseMock()(200, b'{}')
        self.authorized_api.get_data_resource(
            'https://us.api.blizzard.com/profile/wow/test',
            'us',
            locale='de_DE',
        )

        session_get_mock.assert_called_with(
            'https://us.api.blizzard.com/profile/wow/test',
            params={
                'access_token': 'secret',
                'locale': 'de_DE',
            })

    def test_get_resource_call(self, response_mock):
        self.authorized_api.get_resource('resource/{0}',
                                         'us',
                                         1,
                                         locale='en_US',
                                         fields='pets,stats',
                                         breedId=9999)

        response_mock.assert_called_with(
            'https://us.api.blizzard.com/resource/1',
            params={
                'access_token': 'secret',
                'locale': 'en_US',
                'fields': 'pets,stats',
                'breedId': 9999
            })

    def test_get_resource_call_china(self, response_mock):
        self.authorized_api.get_resource('resource/{0}', 'cn', 1)

        response_mock.assert_called_with(
            'https://www.gateway.battlenet.com.cn/resource/1',
            params={
                'access_token': 'secret',
            })

    def test_get_resource_no_access_token(self, session_get_mock, utc_mock):
        now = datetime.utcnow()
        utc_mock.return_value = now

        session_get_mock.side_effect = [
            ResponseMock()(200, b'{"access_token": "111", "expires_in": 60}'),
            ResponseMock()(200, b'{"response": "ok"}'),
        ]
        with pytest.raises(WowApiOauthException):
            data = self.api.get_resource('foo', 'eu')

            assert data == {'response': 'ok'}
            assert self.api._access_tokens == {
                'eu': {
                    'token': '111',
                    'expiration': now + timedelta(seconds=60)
                }
            }

    def test_get_resource_no_access_expired(self, session_get_mock, utc_mock):
        now = datetime.utcnow()
        utc_mock.return_value = now

        self.api._access_tokens = {'eu': {'token': '222', 'expiration': now}}

        session_get_mock.side_effect = [
            ResponseMock()(200, b'{"access_token": "333", "expires_in": 60}'),
            ResponseMock()(200, b'{"response": "ok"}'),
        ]
        with pytest.raises(WowApiOauthException):
            data = self.api.get_resource('foo', 'eu')

            assert data == {'response': 'ok'}
            assert self.api._access_tokens == {
                'eu': {
                    'token': '333',
                    'expiration': now + timedelta(seconds=60)
                }
            }

    def test_format_base_url(self):
        assert self.api._format_base_url(
            'test', 'us') == 'https://us.api.blizzard.com/test'
        assert self.api._format_base_url(
            'test', 'cn') == ('https://www.gateway.battlenet.com.cn/test')
Exemple #25
0
 def test_get_pet_types(self, get_mock):
     WowApi.get_pet_types('us')
     get_mock.assert_called_with(
         'https://us.api.battle.net/wow/data/pet/types', params=self.params)
Exemple #26
0
class Audit:
    """
    Top-Level class Responsible for managing the system.

    This class will hold all necessary data across multiple refreshes
    """
    def __init__(self, config, sql_echo=False):
        self.engine = create_engine(config['database'], echo=sql_echo)
        self.blizzard_api = WowApi(**config['api']['blizzard'],
                                   retry_conn_failures=True)
        self.request_session = requests.Session()
        self.config_characters = config['characters']
        self.make_session = sessionmaker(self.engine)

    def setup_database(self):
        # Tables should be created via alembic, not here, as that will prevent
        # database migrations from working
        # Run 'alembic upgrade head' from command-line to create tables

        session = self.make_session()

        try:
            self._create_classes(session)
            self._create_races(session)
            self._create_gems(session)

            self._remove_old_characters(session)
            self._add_missing_characters(session)

            self._remove_empty_realms(session)
            self._remove_empty_regions(session)

            session.commit()
        except:
            session.rollback()
            raise
        finally:
            session.close()

    def _create_classes(self, session):
        session.query(Class).delete()
        classes = self.blizzard_api.get_playable_class_index(
            BLIZZARD_REGION,
            'static-' + BLIZZARD_REGION,
            locale=BLIZZARD_LOCALE)['classes']
        session.add_all([Class(c['name'], id=c['id']) for c in classes])

    def _create_races(self, session):
        session.query(Race).delete()
        session.query(Faction).delete()
        races = self.blizzard_api.get_playable_race_index(
            BLIZZARD_REGION,
            'static-' + BLIZZARD_REGION,
            locale=BLIZZARD_LOCALE)['races']

        for r in races:
            details = self.blizzard_api.get_data_resource(
                "{}&locale={}".format(r['key']['href'], BLIZZARD_LOCALE),
                BLIZZARD_REGION)

            race_faction = session.query(Faction).filter_by(
                name=details['faction']['name']).first()

            if not race_faction:
                race_faction = Faction(details['faction']['name'])

            session.add(
                Race(details['name'], id=details['id'], faction=race_faction))

    def _create_gems(self, session):
        for id, details in gem_lookup.items():
            if session.query(Gem).filter_by(id=id).first() == None:
                g = Gem(id, **details)
                session.add(g)

    def _remove_old_characters(self, session):
        logger = logging.getLogger('altaudit')

        config_characters = [{
            'name': character,
            'realm': realm,
            'region': region
        } for region, realms in self.config_characters.items()
                             for realm, characters in realms.items()
                             for character in characters]

        stored_characters = session.query(Character).all()

        for char in stored_characters:
            if not {
                    'name': char.name,
                    'realm': char.realm_slug,
                    'region': char.region_name
            } in config_characters:
                logger.info("Could not find %s:%s:%s in config, delete",
                            char.region_name, char.realm_slug, char.name)
                session.delete(char)

    def _add_missing_characters(self, session):
        logger = logging.getLogger('altaudit')

        for region, realms in self.config_characters.items():
            region_model = session.query(Region).filter_by(name=region).first()
            if not region_model:
                logger.info("Add region %s", region)
                region_model = Region(region)
                session.add(region_model)

            for realm, characters in realms.items():
                realm_model = session.query(Realm).filter_by(
                    name=realm).join(Region).filter_by(name=region).first()
                if not realm_model:
                    logger.info("Add realm %s:%s", region, realm)
                    realm_model = Realm(realm, region_model)
                    session.add(realm_model)

                for character in characters:
                    character_model = session.query(Character).\
                            filter_by(name=character).join(Realm).\
                            filter_by(name=realm).join(Region).\
                            filter_by(name=region).first()

                    if not character_model:
                        logger.info("Add character %s:%s:%s", region, realm,
                                    character)
                        character_model = Character(character,
                                                    realm=realm_model)
                        session.add(character_model)

    def _remove_empty_realms(self, session):
        empty = session.query(Realm).filter(~Realm.characters.any()).all()
        for r in empty:
            session.delete(r)

    def _remove_empty_regions(self, session):
        empty = session.query(Region).filter(~Region.realms.any()).all()
        for r in empty:
            session.delete(r)

    def refresh(self, dt, force_refresh=False):
        """
        Refresh each character

        @param dt The datetime.datetime module
        """
        Utility.set_refresh_timestamp(dt.utcnow())

        session = self.make_session()

        logger = logging.getLogger('altaudit')

        try:
            characters = session.query(Character).all()

            output = [Section.metadata()]
            for character in characters:
                logger.debug("%s:%s:%s", character.region_name,
                             character.realm_slug, character.name)
                try:
                    profile = {
                        'summary':
                        self.blizzard_api.get_character_profile_summary(
                            **_character_as_dict(character),
                            namespace="profile-{}".format(
                                character.region_name),
                            locale=BLIZZARD_LOCALE)
                    }
                    rio_resp = self.request_session.get(
                        RAIDERIO_URL.format(
                            **_character_as_dict_rio(character)))

                    update_snapshots(character)
                    process_blizzard(character, profile, session,
                                     self.blizzard_api, force_refresh)
                    process_raiderio(character, rio_resp)
                    session.commit()
                except:
                    logger.exception("%s Failed", character.name)
                    session.rollback()
                finally:
                    output.append(serialize(character))

        except:
            logger.error('Critical failure in character processing')
            session.rollback()
            raise
        finally:
            session.close()

        return output
Exemple #27
0
    def test_get_resource_requests_exception(self, request_exception_mock):
        with pytest.raises(RequestException) as exc:
            WowApi.get_resource('foo/', 'us')

        assert 'Problem' in str(exc)
from wowapi import WowApi

# Downloading old data if you have it
try:

    with open("dict_of_items.json", "r", encoding="utf=8") as item_id_in_file:
        item_id_in_file = json.load(item_id_in_file)

except Exception as error:
    print("Error, old data can't be downloaded")
    print(traceback.format_exc())
    item_id_in_file = {}

# Recieving actual auction list of items (for Ravencrest-eu realm in this example)
try:
    api = WowApi('a2221c916652442bad3fbd0b1581a43d',
                 '3QqAr3a7gJY2Q1PihAUAfwmuRA2SRQFy')
    wow = api.get_auctions('eu', 'ravencrest', locale='en_GB')
    auction = wow['files'][0]['url']
    r = requests.get(auction)
    with open('/aucproject/mybot/auctions-ravencrest.json', 'wb') as f:
        f.write(r.content)

except Exception as error:
    print("Error occured while donwloading data from API")
    print(traceback.format_exc())

# Adding missing keys to our dictionary
with open("auctions-ravencrest.json", "r",
          encoding="utf=8") as item_compare_in_file:
    item_compare_in_file = json.load(item_compare_in_file)
Exemple #29
0
    def test_get_resource_json_invalid(self, invalid_json_mock):
        with pytest.raises(WowApiException) as exc:
            WowApi.get_resource('foo/', 'us')

        assert 'Invalid Json' in str(exc)
Exemple #30
0
class WorldofWarcraft(Cog):
    """WOW API"""
    def __init__(self, bot):
        bot.log.info(f"loaded {__name__}")

        self.bot = bot
        self.config = self.bot.config["wow"]
        self.api = WowApi(self.config["wow_id"], self.config["wow_secret"])
        self.regions = ["eu", "us"]

    # noinspection PyMethodMayBeStatic
    def _get_link(self, site, profile):
        url = None

        if site == "armory":
            url = "https://worldofwarcraft.com/en-us/character"
        elif site == "raiderio":
            url = "https://raider.io/characters"
        elif site == "warcraftlogs":
            url = "https://www.warcraftlogs.com/character"
        elif site == "wowprogress":
            url = "https://www.wowprogress.com/character"

        return f"{url}/{profile}"

    async def _get_character(self, ctx, realm, region, name):
        namespace = f"profile-{region}"

        self.api.get_character_profile_status(region, namespace, realm, name)
        character = self.api.get_character_profile_summary(
            region, f"profile-{region}", realm, name)
        assets = self.api.get_character_media_summary(region,
                                                      f"profile-{region}",
                                                      realm, name)["assets"]
        profile_picture = [
            asset for asset in assets if asset["key"] == "avatar"
        ][0]["value"]

        return character, profile_picture

    # noinspection PyMethodMayBeStatic
    def _get_raiderio_score(self, region, realm, name):
        base_url = "https://raider.io/api/v1/characters/profile"
        args = f"?region={region}&realm={realm}&name={name}&fields=mythic_plus_scores_by_season:current"

        req = requests.get(f"{base_url}{args}")

        if req.status_code == 200:
            resp = req.json()

            if len(resp["mythic_plus_scores_by_season"]) > 0:
                return resp["mythic_plus_scores_by_season"][0]["scores"]["all"]
            else:
                return None

    # noinspection PyMethodMayBeStatic
    def _get_best_mythic_keys(self, region, realm, name):
        base_url = "https://raider.io/api/v1/characters/profile"
        args = f"?region={region}&realm={realm}&name={name}&fields=mythic_plus_best_runs"

        req = requests.get(f"{base_url}{args}")

        if req.status_code == 200:
            resp = req.json()

            keys = []
            for key in resp["mythic_plus_best_runs"]:
                base_datetime = dt(1970, 1, 1)
                delta = td(milliseconds=key["clear_time_ms"])
                target_date = base_datetime + delta
                keys.append({
                    "dungeon": key["short_name"],
                    "level": key["mythic_level"],
                    "clear_time": target_date.strftime("%M:%S"),
                })

            return keys

    @group(invoke_without_command=True)
    async def wow(self, ctx):
        """Get ALL the Infos about WoW"""
        if ctx.invoked_subcommand is None:
            await ctx.send_help(ctx.command)

    @wow.command(aliases=["search", "char"])
    async def armory(self, ctx, name: str, realm: str, region: str = None):
        """
        search for character

        name and realm are required parameters.
        region is optional, but if you want to search on another realm than your discord server runs on, you need to set it.
        """
        try:
            async with ctx.typing():
                if region is None:
                    region = ctx.guild.region[0][:2]

                realm = realm.lower()
                name = name.lower()
                profile = f"{region}/{realm}/{name}"

                character, profile_picture = await self._get_character(
                    ctx, realm, region, name)

                best_keys = self._get_best_mythic_keys(region, realm, name)
                rio_score = self._get_raiderio_score(region, realm, name)

                armory = self._get_link("armory", profile)
                raiderio = self._get_link("raiderio", profile)
                warcraftlogs = self._get_link("warcraftlogs", profile)
                wowprogress = self._get_link("wowprogress", profile)

                emb = discord.Embed(
                    title=
                    f'{character["name"]} | {realm.capitalize()} | {region.upper()} | {character["active_spec"]["name"]["en_US"]} {character["character_class"]["name"]["en_US"]} | {character["equipped_item_level"]} ilvl',
                    url=armory,
                    color=discord.Color(value=int("0099ff", 16)),
                    description=
                    f'{character["gender"]["name"]["en_US"]} {character["race"]["name"]["en_US"]}',
                )
                emb.set_thumbnail(url=profile_picture)
                emb.add_field(name="Level",
                              value=character["level"],
                              inline=True)
                emb.add_field(name="Faction",
                              value=character["faction"]["name"]["en_US"],
                              inline=True)
                if "guild" in character:
                    emb.add_field(name="Guild",
                                  value=character["guild"]["name"],
                                  inline=True)
                emb.add_field(name="\u200b", value="\u200b", inline=False)

                if len(best_keys) > 0:
                    keys = ""
                    for key in best_keys:
                        keys += f'+{key["level"]} - {key["dungeon"]} - {key["clear_time"]}\n'

                    emb.add_field(name="Best M+ Keys", value=keys, inline=True)
                if rio_score is not None:
                    emb.add_field(name="M+ Score",
                                  value=rio_score,
                                  inline=True)

                emb.add_field(name="\u200b", value="\u200b", inline=False)
                emb.add_field(
                    name="External Sites",
                    value=
                    f"[Raider.io]({raiderio}) | [Armory]({armory}) | [WarcraftLogs]({warcraftlogs}) | [WoWProgress]({wowprogress})",
                    inline=True,
                )

            await self.bot.sendc(ctx, "", emb)
        except WowApiException:
            await self.bot.sendc(ctx, "No Character with this name found.")
Exemple #31
0
    def test_get_resource_response_404(self, get_404_mock):
        with pytest.raises(WowApiException) as exc:
            WowApi.get_resource('foo/', 'us')

        assert 'https://us.api.battle.net/wow/foo/ - 404' in str(exc)
Exemple #32
0
from wowapi import WowApi

logger = logging.getLogger('wowapi')
logger.setLevel(logging.INFO)
handler = logging.StreamHandler()
handler.setLevel(logging.INFO)
formatter = logging.Formatter(
    '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)

logger.info('Game Data API Example')

# fetch token price for region
api = WowApi(os.environ['WOW_CLIENT_ID'], os.environ['WOW_CLIENT_SECRET'])
data = api.get_token('eu', namespace='dynamic-eu', locale='de_DE')
pprint(data)

# get realm list and request detail href with the get_data_resource method
data = api.get_realms('us', namespace='dynamic-us')
detail_url = data['realms'][0]['key']['href']
detail_data = api.get_data_resource(detail_url, region='us')
pprint(detail_data)

# get playable specializations list and fetch a single specialization with the api
data = api.get_playable_specializations('us', namespace='static-us')
spec_id = data['character_specializations'][0]['id']
specialization = api.get_playable_specialization('us',
                                                 namespace='static-us',
                                                 spec_id=spec_id)
Exemple #33
0
class TestWowApi(object):

    def setup(self):
        self.params = {'access_token': 'secret'}

        self.api = WowApi('client-id', 'client-secret')

        self.authorized_api = WowApi('client-id', 'client-secret')
        self.authorized_api._access_tokens = {
            'us': {
                'token': 'secret',
                'expiration': datetime.utcnow() + timedelta(hours=1)
            },
            'cn': {
                'token': 'secret',
                'expiration': datetime.utcnow() + timedelta(hours=1)
            }
        }

        self.test_url = 'http://example.com'

        self.default_region = 'us'

    def test_instance(self):
        assert not self.api._access_tokens

    def test_handle_request_success(self, session_get_mock):
        session_get_mock.return_value = ResponseMock()(200, b'{}')
        data = self.api._handle_request(self.test_url, self.default_region)
        assert data == {}
        session_get_mock.assert_called_with(self.test_url)

    def test_handle_request_request_exception(self, session_get_mock):
        session_get_mock.side_effect = RequestException('Error')
        with pytest.raises(WowApiException) as exc:
            self.api._handle_request(self.test_url, self.default_region)

        assert 'Error' in str(exc)

    def test_handle_request_invalid_json(self, session_get_mock):
        session_get_mock.return_value = ResponseMock()(200, b'{"foo": "bar"},')
        with pytest.raises(WowApiException) as exc:
            self.api._handle_request(self.test_url, self.default_region)

        assert 'Invalid Json' in str(exc)

    def test_handle_request_404(self, session_get_mock):
        session_get_mock.return_value = ResponseMock()(404, b'{}')
        with pytest.raises(WowApiException) as exc:
            self.api._handle_request(self.test_url, self.default_region)

        assert '404' in str(exc)

    def test_handle_request_401(self, session_get_mock, utc_mock):
        """ Tests no client token present """
        now = datetime.utcnow()
        utc_mock.return_value = now

        session_get_mock.side_effect = [
            ResponseMock()(401, b'{}'),
            ResponseMock()(200, b'{"access_token": "123", "expires_in": 120}'),
            ResponseMock()(200, b'{"response": "ok"}'),
        ]
        data = self.api._handle_request(self.test_url, self.default_region)

        assert data == {'response': 'ok'}
        assert self.api._access_tokens == {
            'us': {
                'token': '123',
                'expiration': now + timedelta(seconds=120)
            }
        }

    def test_handle_request_cannot_authorize(self, session_get_mock):
        session_get_mock.side_effect = [
            ResponseMock()(401, b'{}'),
            ResponseMock()(401, b'{}'),
        ]

        with pytest.raises(WowApiException) as exc:
            self.api._handle_request(self.test_url, self.default_region)

        assert '401 for https://us.battle.net/oauth/token' in str(exc)

    def test_get_resource_call(self, response_mock):
        self.authorized_api.get_resource(
            'resource/{0}', 'us', 1, locale='en_US', fields='pets,stats', breedId=9999)

        response_mock.assert_called_with(
            'https://us.api.blizzard.com/resource/1',
            params={
                'access_token': 'secret',
                'locale': 'en_US',
                'fields': 'pets,stats',
                'breedId': 9999
            }
        )

    def test_get_resource_call_china(self, response_mock):
        self.authorized_api.get_resource('resource/{0}', 'cn', 1)

        response_mock.assert_called_with(
            'https://www.gateway.battlenet.com.cn/resource/1',
            params={
                'access_token': 'secret',
            }
        )

    def test_get_resource_no_access_token(self, session_get_mock, utc_mock):
        now = datetime.utcnow()
        utc_mock.return_value = now

        session_get_mock.side_effect = [
            ResponseMock()(200, b'{"access_token": "111", "expires_in": 60}'),
            ResponseMock()(200, b'{"response": "ok"}'),
        ]
        data = self.api.get_resource('foo', 'eu')

        assert data == {'response': 'ok'}
        assert self.api._access_tokens == {
            'eu': {
                'token': '111',
                'expiration': now + timedelta(seconds=60)
            }
        }

    def test_get_resource_no_access_expired(self, session_get_mock, utc_mock):
        now = datetime.utcnow()
        utc_mock.return_value = now

        self.api._access_tokens = {
            'eu': {
                'token': '222',
                'expiration': now
            }
        }

        session_get_mock.side_effect = [
            ResponseMock()(200, b'{"access_token": "333", "expires_in": 60}'),
            ResponseMock()(200, b'{"response": "ok"}'),
        ]
        data = self.api.get_resource('foo', 'eu')

        assert data == {'response': 'ok'}
        assert self.api._access_tokens == {
            'eu': {
                'token': '333',
                'expiration': now + timedelta(seconds=60)
            }
        }

    def test_get_achievement(self, response_mock):
        self.authorized_api.get_achievement('us', 1234)
        response_mock.assert_called_with(
            'https://us.api.blizzard.com/wow/achievement/1234', params=self.params)

    def test_get_auctions(self, response_mock):
        self.authorized_api.get_auctions('us', 'khadgar')
        response_mock.assert_called_with(
            'https://us.api.blizzard.com/wow/auction/data/khadgar', params=self.params)

    def test_get_bosses(self, response_mock):
        self.authorized_api.get_bosses('us')
        response_mock.assert_called_with(
            'https://us.api.blizzard.com/wow/boss/', params=self.params)

    def test_get_boss(self, response_mock):
        self.authorized_api.get_boss('us', 24723)
        response_mock.assert_called_with(
            'https://us.api.blizzard.com/wow/boss/24723', params=self.params)

    def test_get_realm_leaderboard(self, response_mock):
        self.authorized_api.get_realm_leaderboard('us', 'silvermoon')
        response_mock.assert_called_with(
            'https://us.api.blizzard.com/wow/challenge/silvermoon', params=self.params)

    def test_get_region_leaderboard(self, response_mock):
        self.authorized_api.get_region_leaderboard('us')
        response_mock.assert_called_with(
            'https://us.api.blizzard.com/wow/challenge/region', params=self.params)

    def test_get_character_profile(self, response_mock):
        self.authorized_api.get_character_profile('us', 'khadgar', 'patchwerk')
        response_mock.assert_called_with(
            'https://us.api.blizzard.com/wow/character/khadgar/patchwerk', params=self.params)

    def test_get_guild_profile(self, response_mock):
        self.authorized_api.get_guild_profile('us', 'draenor', 'topguild')
        response_mock.assert_called_with(
            'https://us.api.blizzard.com/wow/guild/draenor/topguild', params=self.params)

    def test_get_item(self, response_mock):
        self.authorized_api.get_item('us', 9999)
        response_mock.assert_called_with(
            'https://us.api.blizzard.com/wow/item/9999', params=self.params)

    def test_get_item_set(self, response_mock):
        self.authorized_api.get_item_set('us', 1060)
        response_mock.assert_called_with(
            'https://us.api.blizzard.com/wow/item/set/1060', params=self.params)

    def test_get_mounts(self, response_mock):
        self.authorized_api.get_mounts('us')
        response_mock.assert_called_with(
            'https://us.api.blizzard.com/wow/mount/', params=self.params)

    def test_get_pets(self, response_mock):
        self.authorized_api.get_pets('us')
        response_mock.assert_called_with(
            'https://us.api.blizzard.com/wow/pet/', params=self.params)

    def test_get_pet_ability(self, response_mock):
        self.authorized_api.get_pet_ability('us', 640)
        response_mock.assert_called_with(
            'https://us.api.blizzard.com/wow/pet/ability/640', params=self.params)

    def test_get_pet_species(self, response_mock):
        self.authorized_api.get_pet_species('us', 258)
        response_mock.assert_called_with(
            'https://us.api.blizzard.com/wow/pet/species/258', params=self.params)

    def test_get_pet_stats(self, response_mock):
        self.authorized_api.get_pet_stats('us', 258)
        response_mock.assert_called_with(
            'https://us.api.blizzard.com/wow/pet/stats/258', params=self.params)

    def test_get_leaderboards(self, response_mock):
        self.authorized_api.get_leaderboards('us', '5v5')
        response_mock.assert_called_with(
            'https://us.api.blizzard.com/wow/leaderboard/5v5', params=self.params)

    def test_get_quest(self, response_mock):
        self.authorized_api.get_quest('us', 13146)
        response_mock.assert_called_with(
            'https://us.api.blizzard.com/wow/quest/13146', params=self.params)

    def test_get_realm_status(self, response_mock):
        self.authorized_api.get_realm_status('us')
        response_mock.assert_called_with(
            'https://us.api.blizzard.com/wow/realm/status', params=self.params)

    def test_get_recipe(self, response_mock):
        self.authorized_api.get_recipe('us', 33994)
        response_mock.assert_called_with(
            'https://us.api.blizzard.com/wow/recipe/33994', params=self.params)

    def test_get_spell(self, response_mock):
        self.authorized_api.get_spell('us', 8056)
        response_mock.assert_called_with(
            'https://us.api.blizzard.com/wow/spell/8056', params=self.params)

    def test_get_zones(self, response_mock):
        self.authorized_api.get_zones('us')
        response_mock.assert_called_with(
            'https://us.api.blizzard.com/wow/zone/', params=self.params)

    def test_get_zone(self, response_mock):
        self.authorized_api.get_zone('us', 4131)
        response_mock.assert_called_with(
            'https://us.api.blizzard.com/wow/zone/4131', params=self.params)

    def test_get_battlegroups(self, response_mock):
        self.authorized_api.get_battlegroups('us')
        response_mock.assert_called_with(
            'https://us.api.blizzard.com/wow/data/battlegroups/', params=self.params)

    def test_get_character_races(self, response_mock):
        self.authorized_api.get_character_races('us')
        response_mock.assert_called_with(
            'https://us.api.blizzard.com/wow/data/character/races', params=self.params)

    def test_get_character_classes(self, response_mock):
        self.authorized_api.get_character_classes('us')
        response_mock.assert_called_with(
            'https://us.api.blizzard.com/wow/data/character/classes', params=self.params)

    def test_get_character_achievements(self, response_mock):
        self.authorized_api.get_character_achievements('us')
        response_mock.assert_called_with(
            'https://us.api.blizzard.com/wow/data/character/achievements', params=self.params)

    def test_get_guild_rewards(self, response_mock):
        self.authorized_api.get_guild_rewards('us')
        response_mock.assert_called_with(
            'https://us.api.blizzard.com/wow/data/guild/rewards', params=self.params)

    def test_get_guild_perks(self, response_mock):
        self.authorized_api.get_guild_perks('us')
        response_mock.assert_called_with(
            'https://us.api.blizzard.com/wow/data/guild/perks', params=self.params)

    def test_get_guild_achievements(self, response_mock):
        self.authorized_api.get_guild_achievements('us')
        response_mock.assert_called_with(
            'https://us.api.blizzard.com/wow/data/guild/achievements', params=self.params)

    def test_get_item_classes(self, response_mock):
        self.authorized_api.get_item_classes('us')
        response_mock.assert_called_with(
            'https://us.api.blizzard.com/wow/data/item/classes', params=self.params)

    def test_get_talents(self, response_mock):
        self.authorized_api.get_talents('us')
        response_mock.assert_called_with(
            'https://us.api.blizzard.com/wow/data/talents', params=self.params)

    def test_get_pet_types(self, response_mock):
        self.authorized_api.get_pet_types('us')
        response_mock.assert_called_with(
            'https://us.api.blizzard.com/wow/data/pet/types', params=self.params)

    # ---------------------------------------------------------------------------------------------
    # Game Data API tests
    # ---------------------------------------------------------------------------------------------

    # Connected Realm API

    def test_get_connected_realms(self, response_mock):
        self.authorized_api.get_connected_realms('us', 'dynamic-us')
        params = copy.deepcopy(self.params)
        params['namespace'] = 'dynamic-us'
        response_mock.assert_called_with(
            'https://us.api.blizzard.com/data/wow/connected-realm/index', params=params)

    def test_get_connected_realm(self, response_mock):
        self.authorized_api.get_connected_realm('us', 'dynamic-us', 1)
        params = copy.deepcopy(self.params)
        params['namespace'] = 'dynamic-us'
        response_mock.assert_called_with(
            'https://us.api.blizzard.com/data/wow/connected-realm/1', params=params)

    # Mythic Keystone Affix API

    def test_get_mythic_keystone_affixes(self, response_mock):
        self.authorized_api.get_mythic_keystone_affixes('us', 'dynamic-us')
        params = copy.deepcopy(self.params)
        params['namespace'] = 'dynamic-us'
        response_mock.assert_called_with(
            'https://us.api.blizzard.com/data/wow/keystone-affix/index', params=params)

    def test_get_mythic_keystone_affix(self, response_mock):
        self.authorized_api.get_mythic_keystone_affix('us', 'dynamic-us', 3)
        params = copy.deepcopy(self.params)
        params['namespace'] = 'dynamic-us'
        response_mock.assert_called_with(
            'https://us.api.blizzard.com/data/wow/keystone-affix/3', params=params)

    # Mythic Raid Leaderboard API

    def test_get_mythic_raid_leaderboard(self, response_mock):
        self.authorized_api.get_mythic_raid_leaderboard('us', 'dynamic-us', 'uldir', 'horde')
        params = copy.deepcopy(self.params)
        params['namespace'] = 'dynamic-us'
        response_mock.assert_called_with(
            'https://us.api.blizzard.com/data/wow/leaderboard/hall-of-fame/uldir/horde',
            params=params
        )

    # Mythic Keystone Dungeon API

    def test_get_mythic_keystone_dungeons(self, response_mock):
        self.authorized_api.get_mythic_keystone_dungeons('us', 'dynamic-us')
        params = copy.deepcopy(self.params)
        params['namespace'] = 'dynamic-us'
        response_mock.assert_called_with(
            'https://us.api.blizzard.com/data/wow/mythic-keystone/dungeon/index', params=params)

    def test_get_mythic_keystone_dungeon(self, response_mock):
        self.authorized_api.get_mythic_keystone_dungeon('us', 'dynamic-us', 5)
        params = copy.deepcopy(self.params)
        params['namespace'] = 'dynamic-us'
        response_mock.assert_called_with(
            'https://us.api.blizzard.com/data/wow/mythic-keystone/dungeon/5', params=params)

    def test_get_mythic_keystones(self, response_mock):
        self.authorized_api.get_mythic_keystones('us', 'dynamic-us')
        params = copy.deepcopy(self.params)
        params['namespace'] = 'dynamic-us'
        response_mock.assert_called_with(
            'https://us.api.blizzard.com/data/wow/mythic-keystone/index', params=params)

    def test_get_mythic_keystone_periods(self, response_mock):
        self.authorized_api.get_mythic_keystone_periods('us', 'dynamic-us')
        params = copy.deepcopy(self.params)
        params['namespace'] = 'dynamic-us'
        response_mock.assert_called_with(
            'https://us.api.blizzard.com/data/wow/mythic-keystone/period/index', params=params)

    def test_get_mythic_keystone_period(self, response_mock):
        self.authorized_api.get_mythic_keystone_period('us', 'dynamic-us', 641)
        params = copy.deepcopy(self.params)
        params['namespace'] = 'dynamic-us'
        response_mock.assert_called_with(
            'https://us.api.blizzard.com/data/wow/mythic-keystone/period/641', params=params)

    def test_get_mythic_keystone_seasons(self, response_mock):
        self.authorized_api.get_mythic_keystone_seasons('us', 'dynamic-us')
        params = copy.deepcopy(self.params)
        params['namespace'] = 'dynamic-us'
        response_mock.assert_called_with(
            'https://us.api.blizzard.com/data/wow/mythic-keystone/season/index', params=params)

    def test_get_mythic_keystone_season(self, response_mock):
        self.authorized_api.get_mythic_keystone_season('us', 'dynamic-us', 1)
        params = copy.deepcopy(self.params)
        params['namespace'] = 'dynamic-us'
        response_mock.assert_called_with(
            'https://us.api.blizzard.com/data/wow/mythic-keystone/season/1', params=params)

    # Mythic Keystone Leaderboard API

    def test_get_mythic_keystone_leaderboards(self, response_mock):
        self.authorized_api.get_mythic_keystone_leaderboards('us', 'dynamic-us', 1)
        params = copy.deepcopy(self.params)
        params['namespace'] = 'dynamic-us'
        response_mock.assert_called_with(
            'https://us.api.blizzard.com/data/wow/connected-realm/1/mythic-leaderboard/index',
            params=params
        )

    def test_get_mythic_keystone_leaderboard(self, response_mock):
        self.authorized_api.get_mythic_keystone_leaderboard('us', 'dynamic-us', 1, 2, 3)
        params = copy.deepcopy(self.params)
        params['namespace'] = 'dynamic-us'
        response_mock.assert_called_with(
            'https://us.api.blizzard.com/data/wow/connected-realm/1/mythic-leaderboard/2/period/3',
            params=params
        )

    # Playable Class API

    def test_get_playable_classes(self, response_mock):
        self.authorized_api.get_playable_classes('us', 'static-us')
        params = copy.deepcopy(self.params)
        params['namespace'] = 'static-us'
        response_mock.assert_called_with(
            'https://us.api.blizzard.com/data/wow/playable-class/index',
            params=params
        )

    def test_get_playable_class(self, response_mock):
        self.authorized_api.get_playable_class('us', 'static-us', 7)
        params = copy.deepcopy(self.params)
        params['namespace'] = 'static-us'
        response_mock.assert_called_with(
            'https://us.api.blizzard.com/data/wow/playable-class/7',
            params=params
        )

    def test_get_playable_class_pvp_talent_slots(self, response_mock):
        self.authorized_api.get_playable_class_pvp_talent_slots('us', 'static-us', 7)
        params = copy.deepcopy(self.params)
        params['namespace'] = 'static-us'
        response_mock.assert_called_with(
            'https://us.api.blizzard.com/data/wow/playable-class/7/pvp-talent-slots',
            params=params
        )

    # Playable Specialization API

    def test_get_playable_specializations(self, response_mock):
        self.authorized_api.get_playable_specializations('us', 'static-us')
        params = copy.deepcopy(self.params)
        params['namespace'] = 'static-us'
        response_mock.assert_called_with(
            'https://us.api.blizzard.com/data/wow/playable-specialization/index',
            params=params
        )

    def test_get_playable_specialization(self, response_mock):
        self.authorized_api.get_playable_specialization('us', 'static-us', 262)
        params = copy.deepcopy(self.params)
        params['namespace'] = 'static-us'
        response_mock.assert_called_with(
            'https://us.api.blizzard.com/data/wow/playable-specialization/262',
            params=params
        )

    # Power Type API

    def test_get_power_types(self, response_mock):
        self.authorized_api.get_power_types('us', 'static-us')
        params = copy.deepcopy(self.params)
        params['namespace'] = 'static-us'
        response_mock.assert_called_with(
            'https://us.api.blizzard.com/data/wow/power-type/index',
            params=params
        )

    def test_get_power_type(self, response_mock):
        self.authorized_api.get_power_type('us', 'static-us', 0)
        params = copy.deepcopy(self.params)
        params['namespace'] = 'static-us'
        response_mock.assert_called_with(
            'https://us.api.blizzard.com/data/wow/power-type/0',
            params=params
        )

    # Playable Race API

    def test_get_races(self, response_mock):
        self.authorized_api.get_races('us', 'static-us')
        params = copy.deepcopy(self.params)
        params['namespace'] = 'static-us'
        response_mock.assert_called_with(
            'https://us.api.blizzard.com/data/wow/race/index',
            params=params
        )

    def test_get_race(self, response_mock):
        self.authorized_api.get_race('us', 'static-us', 2)
        params = copy.deepcopy(self.params)
        params['namespace'] = 'static-us'
        response_mock.assert_called_with(
            'https://us.api.blizzard.com/data/wow/race/2',
            params=params
        )

    # Realm API

    def test_get_realms(self, response_mock):
        self.authorized_api.get_realms('us', 'dynamic-us')
        params = copy.deepcopy(self.params)
        params['namespace'] = 'dynamic-us'
        response_mock.assert_called_with(
            'https://us.api.blizzard.com/data/wow/realm/index',
            params=params
        )

    def test_get_realm(self, response_mock):
        self.authorized_api.get_realm('us', 'dynamic-us', 'tichondrius')
        params = copy.deepcopy(self.params)
        params['namespace'] = 'dynamic-us'
        response_mock.assert_called_with(
            'https://us.api.blizzard.com/data/wow/realm/tichondrius',
            params=params
        )

    # Region API

    def test_get_regions(self, response_mock):
        self.authorized_api.get_regions('us', 'dynamic-us')
        params = copy.deepcopy(self.params)
        params['namespace'] = 'dynamic-us'
        response_mock.assert_called_with(
            'https://us.api.blizzard.com/data/wow/region/index',
            params=params
        )

    def test_get_region(self, response_mock):
        self.authorized_api.get_region('us', 'dynamic-us', 1)
        params = copy.deepcopy(self.params)
        params['namespace'] = 'dynamic-us'
        response_mock.assert_called_with(
            'https://us.api.blizzard.com/data/wow/region/1',
            params=params
        )

    # WoW Token API

    def test_get_token(self, response_mock):
        self.authorized_api.get_token('us', 'dynamic-us')
        params = copy.deepcopy(self.params)
        params['namespace'] = 'dynamic-us'
        response_mock.assert_called_with(
            'https://us.api.blizzard.com/data/wow/token/index', params=params)

    # ---------------------------------------------------------------------------------------------
    # Profile API tests
    # ---------------------------------------------------------------------------------------------

    # WoW Mythic Keystone Character Profile API

    def test_get_character_mythic_keystone_profile(self, response_mock):
        self.authorized_api.get_character_mythic_keystone_profile(
            'us', 'blackmoore', 'ayanda', 'profile-us')

        params = copy.deepcopy(self.params)
        params['namespace'] = 'profile-us'

        base_url = 'https://us.api.blizzard.com'
        response_mock.assert_called_with(
            '{0}/profile/wow/character/blackmoore/ayanda/mythic-keystone-profile'.format(base_url),
            params=params)

    def test_get_character_mythic_keystone_profile_season(self, response_mock):
        self.authorized_api.get_character_mythic_keystone_profile_season(
            'us', 'blackmoore', 'ayanda', 'profile-us',  '1')

        params = copy.deepcopy(self.params)
        params['namespace'] = 'profile-us'

        response_mock.assert_called_with(
            '{0}/profile/wow/character/blackmoore/ayanda/mythic-keystone-profile/season/1'.format(
                'https://us.api.blizzard.com'
            ),
            params=params
        )