requests_cache.CachedSession

Here are the examples of the python api requests_cache.CachedSession taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

22 Examples 7

Example 1

Project: requests-cache Source File: test_cache.py
    def test_ignore_parameters_post_raw(self):
        url = httpbin("post")
        ignored_param = "ignored"
        raw_data = "raw test data"

        s = CachedSession(CACHE_NAME, CACHE_BACKEND,
                          allowable_methods=('POST'),
                          ignored_parameters=[ignored_param])

        self.assertFalse(s.post(url, data=raw_data).from_cache)
        self.assertTrue(s.post(url, data=raw_data).from_cache)

        raw_data = "new raw data"
        self.assertFalse(s.post(url, data=raw_data).from_cache)

Example 2

Project: requests-cache Source File: test_cache.py
    def test_expire_cache(self):
        delay = 1
        url = httpbin('delay/%s' % delay)
        s = CachedSession(CACHE_NAME, backend=CACHE_BACKEND, expire_after=0.06)
        t = time.time()
        r = s.get(url)
        delta = time.time() - t
        self.assertGreaterEqual(delta, delay)
        time.sleep(0.5)
        t = time.time()
        r = s.get(url)
        delta = time.time() - t
        self.assertGreaterEqual(delta, delay)

Example 3

Project: requests-cache Source File: test_cache.py
    @mock.patch('requests_cache.backends.registry')
    def test_missing_backend_dependency(self, mocked_registry):
        # Testing that the correct error is thrown when a user does not have
        # the Python package `redis` installed.  We mock out the registry
        # to simulate `redis` not being installed.
        mocked_registry.__getitem__.side_effect = KeyError
        with self.assertRaises(ImportError):
            CachedSession(CACHE_NAME, backend='redis')

Example 4

Project: requests-cache Source File: test_cache.py
Function: test_post_params
    def test_post_params(self):
        # issue #2
        self.s = CachedSession(CACHE_NAME, CACHE_BACKEND,
                               allowable_methods=('GET', 'POST'))

        d = {'param1': 'test1'}
        for _ in range(2):
            self.assertEqual(self.post(d)['form'], d)
            d = {'param1': 'test1', 'param3': 'test3'}
            self.assertEqual(self.post(d)['form'], d)

        self.assertTrue(self.s.post(httpbin('post'), data=d).from_cache)
        d.update({'something': 'else'})
        self.assertFalse(self.s.post(httpbin('post'), data=d).from_cache)

Example 5

Project: requests-cache Source File: test_cache.py
    def test_post_parameters_normalization(self):
        params = {"a": "a", "b": ["1", "2", "3"], "c": "4"}
        url = httpbin("post")
        s = CachedSession(CACHE_NAME, CACHE_BACKEND,
                          allowable_methods=('GET', 'POST'))
        self.assertFalse(s.post(url, data=params).from_cache)
        self.assertTrue(s.post(url, data=params).from_cache)
        self.assertTrue(s.post(url, data=sorted(params.items())).from_cache)
        self.assertFalse(s.post(url, data=sorted(params.items(), reverse=True)).from_cache)

Example 6

Project: requests-cache Source File: test_cache.py
    def test_headers_in_get_query(self):
        url = httpbin("get")
        s = CachedSession(CACHE_NAME, CACHE_BACKEND, include_get_headers=True)
        headers = {"Accept": "text/json"}
        self.assertFalse(s.get(url, headers=headers).from_cache)
        self.assertTrue(s.get(url, headers=headers).from_cache)

        headers["Accept"] = "text/xml"
        self.assertFalse(s.get(url, headers=headers).from_cache)
        self.assertTrue(s.get(url, headers=headers).from_cache)

        headers["X-custom-header"] = "custom"
        self.assertFalse(s.get(url, headers=headers).from_cache)
        self.assertTrue(s.get(url, headers=headers).from_cache)

        self.assertFalse(s.get(url).from_cache)
        self.assertTrue(s.get(url).from_cache)

Example 7

Project: requests-cache Source File: test_monkey_patch.py
    def test_passing_backend_instance_support(self):

        class MyCache(BaseCache):
            pass

        backend = MyCache()
        requests_cache.install_cache(name=CACHE_NAME, backend=backend)
        self.assertIs(requests.Session().cache, backend)

        session = CachedSession(backend=backend)
        self.assertIs(session.cache, backend)

Example 8

Project: qstrader Source File: pandas_bar_display_prices_backtest.py
Function: init_session
def init_session(cache_name, cache_backend, expire_after):
    if expire_after == '0':
        expire_after = None
        print("expire_after==0 no cache")
        return None
    else:
        if expire_after == '-1':
            expire_after = 0
            print("Installing cache '%s.sqlite' without expiration" % cache_name)
        else:
            expire_after = pd.to_timedelta(expire_after, unit='s')
            print("Installing cache '%s.sqlite' with expire_after=%s (d days hh:mm:ss)" % (cache_name, expire_after))
        session = requests_cache.CachedSession(cache_name=cache_name, backend=cache_backend, expire_after=expire_after)
        return session

Example 9

Project: tvdb_api Source File: tvdb_api.py
    def __init__(self,
                interactive = False,
                select_first = False,
                debug = False,
                cache = True,
                banners = False,
                actors = False,
                custom_ui = None,
                language = None,
                search_all_languages = False,
                apikey = None,
                forceConnect=False,
                useZip=False,
                dvdorder=False):

        """interactive (True/False):
            When True, uses built-in console UI is used to select the correct show.
            When False, the first search result is used.

        select_first (True/False):
            Automatically selects the first series search result (rather
            than showing the user a list of more than one series).
            Is overridden by interactive = False, or specifying a custom_ui

        debug (True/False) DEPRECATED:
             Replaced with proper use of logging module. To show debug messages:

                 >>> import logging
                 >>> logging.basicConfig(level = logging.DEBUG)

        cache (True/False/str/unicode/urllib2 opener):
            Retrieved XML are persisted to to disc. If true, stores in
            tvdb_api folder under your systems TEMP_DIR, if set to
            str/unicode instance it will use this as the cache
            location. If False, disables caching.  Can also be passed
            an arbitrary Python object, which is used as a urllib2
            opener, which should be created by urllib2.build_opener

            In Python 3, True/False enable or disable default
            caching. Passing string specified directory where to store
            the "tvdb.sqlite3" cache file. Also a custom
            requests.Session instance can be passed (e.g maybe a
            customised instance of requests_cache.CachedSession)

        banners (True/False):
            Retrieves the banners for a show. These are accessed
            via the _banners key of a Show(), for example:

            >>> Tvdb(banners=True)['scrubs']['_banners'].keys()
            ['fanart', 'poster', 'series', 'season']

        actors (True/False):
            Retrieves a list of the actors for a show. These are accessed
            via the _actors key of a Show(), for example:

            >>> t = Tvdb(actors=True)
            >>> t['scrubs']['_actors'][0]['name']
            u'Zach Braff'

        custom_ui (tvdb_ui.BaseUI subclass):
            A callable subclass of tvdb_ui.BaseUI (overrides interactive option)

        language (2 character language abbreviation):
            The language of the returned data. Is also the language search
            uses. Default is "en" (English). For full list, run..

            >>> Tvdb().config['valid_languages'] #doctest: +ELLIPSIS
            ['da', 'fi', 'nl', ...]

        search_all_languages (True/False):
            By default, Tvdb will only search in the language specified using
            the language option. When this is True, it will search for the
            show in and language
        
        apikey (str/unicode):
            Override the default thetvdb.com API key. By default it will use
            tvdb_api's own key (fine for small scripts), but you can use your
            own key if desired - this is recommended if you are embedding
            tvdb_api in a larger application)
            See http://thetvdb.com/?tab=apiregister to get your own key

        forceConnect (bool):
            If true it will always try to connect to theTVDB.com even if we
            recently timed out. By default it will wait one minute before
            trying again, and any requests within that one minute window will
            return an exception immediately.

        useZip (bool):
            Download the zip archive where possibale, instead of the xml.
            This is only used when all episodes are pulled.
            And only the main language xml is used, the actor and banner xml are lost.
        """
        

        global lastTimeout
        
        # if we're given a lastTimeout that is less than 1 min just give up
        if not forceConnect and lastTimeout != None and datetime.datetime.now() - lastTimeout < datetime.timedelta(minutes=1):
            raise tvdb_error("We recently timed out, so giving up early this time")
        
        self.shows = ShowContainer() # Holds all Show classes
        self.corrections = {} # Holds show-name to show_id mapping

        self.config = {}

        if apikey is not None:
            self.config['apikey'] = apikey
        else:
            self.config['apikey'] = "0629B785CE550C8D" # tvdb_api's API key

        self.config['debug_enabled'] = debug # show debugging messages

        self.config['custom_ui'] = custom_ui

        self.config['interactive'] = interactive # prompt for correct series?

        self.config['select_first'] = select_first

        self.config['search_all_languages'] = search_all_languages

        self.config['useZip'] = useZip

        self.config['dvdorder'] = dvdorder

        if not IS_PY2: # FIXME: Allow using requests in Python 2?
            import requests_cache
            if cache is True:
                self.session = requests_cache.CachedSession(
                    expire_after=21600, # 6 hours
                    backend='sqlite',
                    cache_name=self._getTempDir(),
                    )
                self.config['cache_enabled'] = True
            elif cache is False:
                self.session = requests.Session()
                self.config['cache_enabled'] = False
            elif isinstance(cache, text_type):
                # Specified cache path
                self.session = requests_cache.CachedSession(
                    expire_after=21600, # 6 hours
                    backend='sqlite',
                    cache_name=os.path.join(cache, "tvdb_api"),
                    )
            else:
                self.session = cache
                try:
                    self.session.get
                except AttributeError:
                    raise ValueError("cache argument must be True/False, string as cache path or requests.Session-type object (e.g from requests_cache.CachedSession)")
        else:
            # For backwards compatibility in Python 2.x
            if cache is True:
                self.config['cache_enabled'] = True
                self.config['cache_location'] = self._getTempDir()
                self.urlopener = urllib2.build_opener(
                    CacheHandler(self.config['cache_location'])
                )

            elif cache is False:
                self.config['cache_enabled'] = False
                self.urlopener = urllib2.build_opener() # default opener with no caching

            elif isinstance(cache, basestring):
                self.config['cache_enabled'] = True
                self.config['cache_location'] = cache
                self.urlopener = urllib2.build_opener(
                    CacheHandler(self.config['cache_location'])
                )

            elif isinstance(cache, urllib2.OpenerDirector):
                # If passed something from urllib2.build_opener, use that
                log().debug("Using %r as urlopener" % cache)
                self.config['cache_enabled'] = True
                self.urlopener = cache

            else:
                raise ValueError("Invalid value for Cache %r (type was %s)" % (cache, type(cache)))

        self.config['banners_enabled'] = banners
        self.config['actors_enabled'] = actors

        if self.config['debug_enabled']:
            warnings.warn("The debug argument to tvdb_api.__init__ will be removed in the next version. "
            "To enable debug messages, use the following code before importing: "
            "import logging; logging.basicConfig(level=logging.DEBUG)")
            logging.basicConfig(level=logging.DEBUG)


        # List of language from http://thetvdb.com/api/0629B785CE550C8D/languages.xml
        # Hard-coded here as it is realtively static, and saves another HTTP request, as
        # recommended on http://thetvdb.com/wiki/index.php/API:languages.xml
        self.config['valid_languages'] = [
            "da", "fi", "nl", "de", "it", "es", "fr","pl", "hu","el","tr",
            "ru","he","ja","pt","zh","cs","sl", "hr","ko","en","sv","no"
        ]

        # thetvdb.com should be based around numeric language codes,
        # but to link to a series like http://thetvdb.com/?tab=series&id=79349&lid=16
        # requires the language ID, thus this mapping is required (mainly
        # for usage in tvdb_ui - internally tvdb_api will use the language abbreviations)
        self.config['langabbv_to_id'] = {'el': 20, 'en': 7, 'zh': 27,
        'it': 15, 'cs': 28, 'es': 16, 'ru': 22, 'nl': 13, 'pt': 26, 'no': 9,
        'tr': 21, 'pl': 18, 'fr': 17, 'hr': 31, 'de': 14, 'da': 10, 'fi': 11,
        'hu': 19, 'ja': 25, 'he': 24, 'ko': 32, 'sv': 8, 'sl': 30}

        if language is None:
            self.config['language'] = 'en'
        else:
            if language not in self.config['valid_languages']:
                raise ValueError("Invalid language %s, options are: %s" % (
                    language, self.config['valid_languages']
                ))
            else:
                self.config['language'] = language

        # The following url_ configs are based of the
        # http://thetvdb.com/wiki/index.php/Programmers_API
        self.config['base_url'] = "http://thetvdb.com"

        if self.config['search_all_languages']:
            self.config['url_getSeries'] = u"%(base_url)s/api/GetSeries.php?seriesname=%%s&language=all" % self.config
        else:
            self.config['url_getSeries'] = u"%(base_url)s/api/GetSeries.php?seriesname=%%s&language=%(language)s" % self.config

        self.config['url_epInfo'] = u"%(base_url)s/api/%(apikey)s/series/%%s/all/%%s.xml" % self.config
        self.config['url_epInfo_zip'] = u"%(base_url)s/api/%(apikey)s/series/%%s/all/%%s.zip" % self.config

        self.config['url_seriesInfo'] = u"%(base_url)s/api/%(apikey)s/series/%%s/%%s.xml" % self.config
        self.config['url_actorsInfo'] = u"%(base_url)s/api/%(apikey)s/series/%%s/actors.xml" % self.config

        self.config['url_seriesBanner'] = u"%(base_url)s/api/%(apikey)s/series/%%s/banners.xml" % self.config
        self.config['url_artworkPrefix'] = u"%(base_url)s/banners/%%s" % self.config

Example 10

Project: requests-cache Source File: test_cache.py
Function: set_up
    def setUp(self):
        self.s = CachedSession(CACHE_NAME, backend=CACHE_BACKEND, fast_save=FAST_SAVE)
        self.s.cache.clear()
        requests_cache.uninstall_cache()

Example 11

Project: requests-cache Source File: test_cache.py
    def test_unregistered_backend(self):
        with self.assertRaises(ValueError):
            CachedSession(CACHE_NAME, backend='nonexistent')

Example 12

Project: requests-cache Source File: test_cache.py
Function: test_post_data
    def test_post_data(self):
        # issue #2, raw payload
        self.s = CachedSession(CACHE_NAME, CACHE_BACKEND,
                               allowable_methods=('GET', 'POST'))
        d1 = json.dumps({'param1': 'test1'})
        d2 = json.dumps({'param1': 'test1', 'param2': 'test2'})
        d3 = str('some unicode data')
        if is_py3:
            bin_data = bytes('some binary data', 'utf8')
        else:
            bin_data = bytes('some binary data')

        for d in (d1, d2, d3):
            self.assertEqual(self.post(d)['data'], d)
            r = self.s.post(httpbin('post'), data=d)
            self.assert_(hasattr(r, 'from_cache'))

        self.assertEqual(self.post(bin_data)['data'],
                         bin_data.decode('utf8'))
        r = self.s.post(httpbin('post'), data=bin_data)
        self.assert_(hasattr(r, 'from_cache'))

Example 13

Project: requests-cache Source File: test_cache.py
Function: test_str_and_repr
    def test_str_and_repr(self):
        s = repr(CachedSession(CACHE_NAME, CACHE_BACKEND, expire_after=10))
        self.assertIn(CACHE_NAME, s)
        self.assertIn("10", s)

Example 14

Project: requests-cache Source File: test_cache.py
    @mock.patch("requests_cache.core.datetime")
    def test_return_old_data_on_error(self, datetime_mock):
        datetime_mock.utcnow.return_value = datetime.utcnow()
        expire_after = 100
        url = httpbin("get")
        s = CachedSession(CACHE_NAME, CACHE_BACKEND, old_data_on_error=True, expire_after=expire_after)
        header = "X-Tst"

        def get(n):
            return s.get(url, headers={header: n}).json()["headers"][header]

        get("expired")
        self.assertEquals(get("2"), "expired")
        datetime_mock.utcnow.return_value = datetime.utcnow() + timedelta(seconds=expire_after * 2)

        with mock.patch.object(s.cache, "save_response", side_effect=Exception):
            self.assertEquals(get("3"), "expired")

        with mock.patch("requests_cache.core.OriginalSession.send") as send_mock:
            resp_mock = requests.Response()
            request = requests.Request("GET", url)
            resp_mock.request = request.prepare()
            resp_mock.status_code = 400
            resp_mock._content = '{"other": "content"}'
            send_mock.return_value = resp_mock
            self.assertEquals(get("3"), "expired")

            resp_mock.status_code = 200
            self.assertIs(s.get(url).content, resp_mock.content)

        # default behaviour
        datetime_mock.return_value = datetime.utcnow() + timedelta(seconds=expire_after * 2)
        s = CachedSession(CACHE_NAME, CACHE_BACKEND, old_data_on_error=False, expire_after=100)
        with mock.patch.object(s.cache, "save_response", side_effect=Exception):
            with self.assertRaises(Exception):
                s.get(url)

Example 15

Project: requests-cache Source File: test_cache.py
    def test_ignore_parameters_get(self):
        url = httpbin("get")
        ignored_param = "ignored"
        usual_param = "some"
        params = {ignored_param: "1", usual_param: "1"}

        s = CachedSession(CACHE_NAME, CACHE_BACKEND,
                          ignored_parameters=[ignored_param])

        r = s.get(url, params=params)
        self.assertIn(ignored_param, r.json()['args'].keys())
        self.assertFalse(r.from_cache)

        self.assertTrue(s.get(url, params=params).from_cache)

        params[ignored_param] = "new"
        self.assertTrue(s.get(url, params=params).from_cache)

        params[usual_param] = "new"
        self.assertFalse(s.get(url, params=params).from_cache)

Example 16

Project: requests-cache Source File: test_cache.py
    def test_ignore_parameters_post(self):
        url = httpbin("post")
        ignored_param = "ignored"
        usual_param = "some"
        d = {ignored_param: "1", usual_param: "1"}

        s = CachedSession(CACHE_NAME, CACHE_BACKEND,
                          allowable_methods=('POST'),
                          ignored_parameters=[ignored_param])

        r = s.post(url, data=d)
        self.assertIn(ignored_param, r.json()['form'].keys())
        self.assertFalse(r.from_cache)

        self.assertTrue(s.post(url, data=d).from_cache)

        d[ignored_param] = "new"
        self.assertTrue(s.post(url, data=d).from_cache)

        d[usual_param] = "new"
        self.assertFalse(s.post(url, data=d).from_cache)

Example 17

Project: requests-cache Source File: test_cache.py
    def test_ignore_parameters_post_json(self):
        url = httpbin("post")
        ignored_param = "ignored"
        usual_param = "some"
        d = {ignored_param: "1", usual_param: "1"}

        s = CachedSession(CACHE_NAME, CACHE_BACKEND,
                          allowable_methods=('POST'),
                          ignored_parameters=[ignored_param])

        r = s.post(url, json=d)
        self.assertIn(ignored_param, json.loads(r.json()['data']).keys())
        self.assertFalse(r.from_cache)

        self.assertTrue(s.post(url, json=d).from_cache)

        d[ignored_param] = "new"
        self.assertTrue(s.post(url, json=d).from_cache)

        d[usual_param] = "new"
        self.assertFalse(s.post(url, json=d).from_cache)

Example 18

Project: requests-cache Source File: test_cache.py
Function: test_remove_expired_entries
    @mock.patch("requests_cache.backends.base.datetime")
    @mock.patch("requests_cache.core.datetime")
    def test_remove_expired_entries(self, datetime_mock, datetime_mock2):
        expire_after = timedelta(minutes=10)
        start_time = datetime.utcnow().replace(year=2010, minute=0)
        datetime_mock.utcnow.return_value = start_time
        datetime_mock2.utcnow.return_value = start_time

        s = CachedSession(CACHE_NAME, CACHE_BACKEND, expire_after=expire_after)
        s.get(httpbin('get'))
        s.get(httpbin('relative-redirect/3'))
        datetime_mock.utcnow.return_value = start_time + expire_after * 2
        datetime_mock2.utcnow.return_value = datetime_mock.utcnow.return_value

        ok_url = 'get?x=1'
        s.get(httpbin(ok_url))
        self.assertEqual(len(s.cache.responses), 3)
        self.assertEqual(len(s.cache.keys_map), 3)
        s.remove_expired_responses()
        self.assertEqual(len(s.cache.responses), 1)
        self.assertEqual(len(s.cache.keys_map), 0)
        self.assertIn(ok_url, list(s.cache.responses.values())[0][0].url)

Example 19

Project: requests-cache Source File: test_thread_safety.py
    def test_caching_with_threads(self):

        def do_tests_for(backend):
            s = CachedSession(CACHE_NAME, backend)
            s.cache.clear()
            n_threads = 10
            url = 'http://httpbin.org/get'
            def do_requests(url, params):
                for i in range(10):  # for testing write and read from cache
                    s.get(url, params=params)

            for _ in range(20): # stress test
                threads = [Thread(target=do_requests, args=(url, {'param': i})) for i in range(n_threads)]
                for t in threads:
                    t.start()
                for t in threads:
                    t.join()

                for i in range(n_threads):
                    self.assert_(s.cache.has_url('%s?param=%s' % (url, i)))

        for backend in ('sqlite', 'mongodb'):
            try:
                do_tests_for(backend)
            except Exception:
                print("Failed to test %s" % backend)

Example 20

Project: oldnyc Source File: url_fetcher.py
Function: init
    def __init__(self, throttle_secs=1.0):
        self._session = requests_cache.CachedSession('.url_fetcher_cache')
        self._throttle_secs = throttle_secs
        self._last_fetch = 0.0

Example 21

Project: ig-markets-api-python-library Source File: rest_ig.py
def main():
    logging.basicConfig(level=logging.DEBUG)

    expire_after = timedelta(hours=1)
    session = requests_cache.CachedSession(cache_name='cache', backend='sqlite', expire_after=expire_after)
    # set expire_after=None if you don't want cache expiration
    # set expire_after=0 if you don't want to cache queries

    #config = IGServiceConfig()

    # no cache
    ig_service = IGService(config.username, config.password, config.api_key, config.acc_type)

    # if you want to globally cache queries
    #ig_service = IGService(config.username, config.password, config.api_key, config.acc_type, session)

    ig_service.create_session()

    accounts = ig_service.fetch_accounts()
    print("accounts:\n%s" % accounts)

    #account_info = ig_service.switch_account(config.acc_number, False)
    #print(account_info)

    #open_positions = ig_service.fetch_open_positions()
    #print("open_positions:\n%s" % open_positions)

    print("")

    #working_orders = ig_service.fetch_working_orders()
    #print("working_orders:\n%s" % working_orders)

    print("")

    #epic = 'CS.D.EURUSD.MINI.IP'
    epic = 'IX.D.ASX.IFM.IP' # US (SPY) - mini

    resolution = 'D'
    # see from pandas.tseries.frequencies import to_offset
    #resolution = 'H'
    #resolution = '1Min'

    num_points = 10
    response = ig_service.fetch_historical_prices_by_epic_and_num_points(epic, resolution, num_points)

Example 22

Project: ig-markets-api-python-library Source File: test_ig_service.py
def test_ig_service():

    delay_for_ig = 30

    def wait(delay):
        print("Wait %s s to avoid 'error.public-api.exceeded-account-allowance'"
              % delay)
        time.sleep(delay)

    session_cached = requests_cache.CachedSession(cache_name=CACHE_NAME,
                                                  backend='sqlite',
                                                  expire_after=timedelta(
                                                      hours=1))
    session_not_cached = requests.Session()

    for i, session in enumerate([session_cached, session_cached, session_not_cached]):

        # pp = pprint.PrettyPrinter(indent=4)

        assert(isinstance(trading_ig.__version__, six.string_types))

        # ig_service = IGService(config.username, config.password,
        #                        config.api_key, config.acc_type)
        ig_service = IGService(config.username, config.password, config.api_key,
                               config.acc_type, session)
        ig_service.create_session()

        print("%d - fetch_accounts" % i)
        response = ig_service.fetch_accounts()
        print(response)
        # assert(response['balance'][0]['available']>0)
        assert(response['balance'][0] > 0)

        print("")

        print("fetch_account_activity_by_period")
        response = ig_service.fetch_account_activity_by_period(10000)
        print(response)
        assert(isinstance(response, pd.DataFrame))

        print("")

        print("fetch_account_activity_by_period")
        response = ig_service.fetch_account_activity_by_period(10000)
        print(response)
        assert(isinstance(response, pd.DataFrame))

        print("")

        print("fetch_transaction_history_by_type_and_period")
        response = ig_service.\
            fetch_transaction_history_by_type_and_period(10000, "ALL")
        print(response)
        assert(isinstance(response, pd.DataFrame))

        wait(delay_for_ig)
        print("")

        print("fetch_open_positions")
        response = ig_service.fetch_open_positions()
        print(response)
        assert(isinstance(response, pd.DataFrame))

        print("")

        print("fetch_working_orders")
        response = ig_service.fetch_working_orders()
        print(response)
        assert(isinstance(response, pd.DataFrame))

        print("")

        print("fetch_top_level_navigation_nodes")
        response = ig_service.fetch_top_level_navigation_nodes()
        print(response)  # dict with nodes and markets
        assert(isinstance(response, dict))
        market_id = response['nodes']['id'].iloc[0]

        print("")

        print("fetch_client_sentiment_by_instrument")
        response = ig_service.fetch_client_sentiment_by_instrument(market_id)
        print(response)
        assert(isinstance(response, dict))

        print("")

        print("fetch_related_client_sentiment_by_instrument")
        response = ig_service.\
            fetch_related_client_sentiment_by_instrument(market_id)
        print(response)
        assert(isinstance(response, pd.DataFrame))

        print("")

        print("fetch_sub_nodes_by_node")
        node = market_id
        response = ig_service.fetch_sub_nodes_by_node(node)
        print(response)
        assert(isinstance(response['markets'], pd.DataFrame))
        assert(isinstance(response['nodes'], pd.DataFrame))

        print("")
        wait(delay_for_ig)

        print("fetch_all_watchlists")
        response = ig_service.fetch_all_watchlists()
        print(response)
        assert(isinstance(response, pd.DataFrame))
        watchlist_id = response['id'].iloc[0]  # u'Popular Markets'

        print("")

        print("fetch_watchlist_markets")
        response = ig_service.fetch_watchlist_markets(watchlist_id)
        print(response)
        assert(isinstance(response, pd.DataFrame))
        # epic = 'CS.D.EURUSD.MINI.IP'
        # epic = u'IX.D.CAC.IDF.IP'
        epic = response['epic'].iloc[0]

        print("")

        print("fetch_market_by_epic")
        response = ig_service.fetch_market_by_epic(epic)
        print(response)
        # pp.pprint(response)
        assert(isinstance(response, dict))

        print("")

        print("search_markets")
        search_term = 'EURUSD'
        # search_term = 'SPY'
        response = ig_service.search_markets(search_term)
        print(response)
        assert(isinstance(response, pd.DataFrame))

        print("")
        wait(delay_for_ig)
        wait(delay_for_ig)

        print("fetch_historical_prices_by_epic_and_num_points")

        # epic = 'CS.D.EURUSD.MINI.IP'
        # epic = 'IX.D.ASX.IFM.IP' # US 500 (SPY)
        # epic = 'IX.D.ASX.IFM.IP' # US (SPY) - mini
        # MINUTE, MINUTE_2, MINUTE_3, MINUTE_5, MINUTE_10, MINUTE_15,
        # MINUTE_30, HOUR, HOUR_2, HOUR_3, HOUR_4, DAY, WEEK, MONTH
        # resolution = 'HOUR'
        # http://pandas.pydata.org/pandas-docs/stable/timeseries.html#dateoffset-objects
        resolution = 'H'
        num_points = 10
        response = ig_service.\
            fetch_historical_prices_by_epic_and_num_points(epic,
                                                           resolution,
                                                           num_points)
        print(response)
        # print(response['prices']['price'])
        # print(response['prices']['price']['ask'])
        # print(response['prices']['volume'])
        assert(isinstance(response['allowance'], dict))
        # assert(isinstance(response['prices']['volume'], pd.Series))
        # assert(isinstance(response['prices']['price'], pd.Panel))
        assert(isinstance(response['prices'], pd.DataFrame))

        print("")
        wait(delay_for_ig)

        print("fetch_historical_prices_by_epic_and_date_range")
        end_date = datetime.utcnow().replace(hour=0, minute=0, second=0, microsecond=0)
        start_date = end_date - timedelta(days=3)
        response = ig_service.\
            fetch_historical_prices_by_epic_and_date_range(epic, resolution,
                                                           start_date, end_date)
        print(response)
        assert(isinstance(response['allowance'], dict))
        # assert(isinstance(response['prices']['volume'], pd.Series))
        # assert(isinstance(response['prices']['price'], pd.Panel))
        assert(isinstance(response['prices'], pd.DataFrame))

        print("")
        wait(delay_for_ig)