# Path: wham/httmock.py
# class HTTMock(object):
#     """
#     Acts as a context manager to allow mocking
#     """
#     STATUS_CODE = 200
# 
#     def __init__(self, *handlers):
#         self.handlers = handlers
# 
#     def __enter__(self):
#         self._real_session_send = requests.Session.send
# 
#         def _fake_send(session, request, **kwargs):
#             response = self.intercept(request)
#             if isinstance(response, requests.Response):
#                 # this is pasted from requests to handle redirects properly:
#                 kwargs.setdefault('stream', session.stream)
#                 kwargs.setdefault('verify', session.verify)
#                 kwargs.setdefault('cert', session.cert)
#                 kwargs.setdefault('proxies', session.proxies)
# 
#                 allow_redirects = kwargs.pop('allow_redirects', True)
#                 stream = kwargs.get('stream')
#                 timeout = kwargs.get('timeout')
#                 verify = kwargs.get('verify')
#                 cert = kwargs.get('cert')
#                 proxies = kwargs.get('proxies')
# 
#                 gen = session.resolve_redirects(
#                     response,
#                     request,
#                     stream=stream,
#                     timeout=timeout,
#                     verify=verify,
#                     cert=cert,
#                     proxies=proxies)
# 
#                 history = [resp for resp in gen] if allow_redirects else []
# 
#                 if history:
#                     history.insert(0, response)
#                     response = history.pop()
#                     response.history = tuple(history)
#                 return response
# 
#             return self._real_session_send(session, request, **kwargs)
#         requests.Session.send = _fake_send
#         return self
# 
#     def __exit__(self, exc_type, exc_val, exc_tb):
#         requests.Session.send = self._real_session_send
# 
#     def intercept(self, request):
#         url = urlparse.urlsplit(request.url)
#         res = first_of(self.handlers, url, request)
#         if isinstance(res, requests.Response):
#             return res
#         elif isinstance(res, dict):
#             return response(res.get('status_code'),
#                             res.get('content'),
#                             res.get('headers'),
#                             res.get('reason'),
#                             res.get('elapsed', 0),
#                             request)
#         elif isinstance(res, basestring):
#             return response(content=res)
#         elif res is None:
#             return None
#         else:
#             raise TypeError(
#                 "Dont know how to handle response of type {}".format(type(res)))
# 
# Path: wham/apis/spotify/models.py
# class SpotifyTrack(WhamModel):
# 
#     id = WhamCharField(max_length=255, primary_key=True)
#     name = WhamTextField()
# 
#     href = WhamTextField(null=True)
#     popularity = WhamIntegerField(null=True)
#     track_number = WhamIntegerField(null=True)
#     uri = WhamTextField(null=True)
#     type = WhamTextField(null=True)
#     preview_url = WhamTextField(null=True)
#     artists = WhamManyToManyField('SpotifyArtist', related_name='tracks')
# 
#     class WhamMeta(SpotifyMeta):
#         endpoint = 'tracks'
# 
#         class Search:
#             endpoint = 'search'
#             params = {'type': 'track'}
#             results_path = ('tracks', 'items')
# 
#     class Meta:
#         db_table = 'spotify_track'
# 
#     def __unicode__(self):
#         return self.name
# 
# class SpotifyArtist(WhamModel):
# 
#     id = WhamCharField(max_length=255, primary_key=True)
#     name = WhamTextField()
# 
#     href = WhamTextField(null=True)
#     popularity = WhamIntegerField(null=True)
#     uri = WhamTextField(null=True)
# 
#     albums = WhamManyToManyField(
#         'SpotifyAlbum',
#         related_name='artists',
#         wham_endpoint='artists/{{id}}/albums',
#         wham_results_path=('items',)
#     )
# 
#     # TODO:
#     # tracks = WhamManyToManyField(
#     #     'SpotifyTrack',
#     #     # related_name='artists',
#     #     wham_endpoint='artists/{{id}}/albums',
#     #     wham_results_path=('items',)
#     # )
# 
#     class Meta:
#         db_table = 'spotify_artist'
# 
#     class WhamMeta(SpotifyMeta):
#         endpoint = 'artists'
# 
#         # i reckon this stuff should really be in Manager, as it has more to do with filter()
#         # which is a Manager method
# 
#         class Search:
#             endpoint = 'search'
#             params = {'type': 'artist'}
#             results_path = ('artists', 'items')
# 
#     def __unicode__(self):
#         return self.name
# 
# Path: wham/tests.py
# def build_httmock_functions(mock_response_dir):
#     print 'building mock functions'
#     functions = []
#     for filename in listdir(mock_response_dir):
#         filepath = join(mock_response_dir,filename)
#         if isfile(filepath):
#             method = None
#             for _method in ('GET', 'POST', 'PUT', 'DELETE', 'PATCH'):
#                 if filename.startswith(_method):
#                     filename = filename[len(_method):]
#                     method = _method
# 
#             url = urllib2.unquote(filename)
# 
#             parts = urlparse(url)
#             params = {}
#             if parts.query:
#                 print parts.query
#                 params = dict(parse_qsl(parts.query))
#                 print params
#             with open(filepath) as f:
#                 content = f.read()
#                 functions.append(build_httmock_function(
#                     parts.scheme, parts.netloc, parts.path, content, params=params, method=method))
#     return functions


from os.path import join
from django.test import TestCase
from wham.httmock import HTTMock
from wham.apis.spotify.models import SpotifyTrack, SpotifyArtist
from wham.tests import build_httmock_functions
import os


APP_DIR = os.path.dirname(__file__)
MOCK_RESPONSES_DIR = join(APP_DIR, 'mock_responses')

mock_functions = build_httmock_functions(MOCK_RESPONSES_DIR)

class TestCase(TestCase):

    def test_spotify(self):


# Path: wham/httmock.py
# class HTTMock(object):
#     """
#     Acts as a context manager to allow mocking
#     """
#     STATUS_CODE = 200
# 
#     def __init__(self, *handlers):
#         self.handlers = handlers
# 
#     def __enter__(self):
#         self._real_session_send = requests.Session.send
# 
#         def _fake_send(session, request, **kwargs):
#             response = self.intercept(request)
#             if isinstance(response, requests.Response):
#                 # this is pasted from requests to handle redirects properly:
#                 kwargs.setdefault('stream', session.stream)
#                 kwargs.setdefault('verify', session.verify)
#                 kwargs.setdefault('cert', session.cert)
#                 kwargs.setdefault('proxies', session.proxies)
# 
#                 allow_redirects = kwargs.pop('allow_redirects', True)
#                 stream = kwargs.get('stream')
#                 timeout = kwargs.get('timeout')
#                 verify = kwargs.get('verify')
#                 cert = kwargs.get('cert')
#                 proxies = kwargs.get('proxies')
# 
#                 gen = session.resolve_redirects(
#                     response,
#                     request,
#                     stream=stream,
#                     timeout=timeout,
#                     verify=verify,
#                     cert=cert,
#                     proxies=proxies)
# 
#                 history = [resp for resp in gen] if allow_redirects else []
# 
#                 if history:
#                     history.insert(0, response)
#                     response = history.pop()
#                     response.history = tuple(history)
#                 return response
# 
#             return self._real_session_send(session, request, **kwargs)
#         requests.Session.send = _fake_send
#         return self
# 
#     def __exit__(self, exc_type, exc_val, exc_tb):
#         requests.Session.send = self._real_session_send
# 
#     def intercept(self, request):
#         url = urlparse.urlsplit(request.url)
#         res = first_of(self.handlers, url, request)
#         if isinstance(res, requests.Response):
#             return res
#         elif isinstance(res, dict):
#             return response(res.get('status_code'),
#                             res.get('content'),
#                             res.get('headers'),
#                             res.get('reason'),
#                             res.get('elapsed', 0),
#                             request)
#         elif isinstance(res, basestring):
#             return response(content=res)
#         elif res is None:
#             return None
#         else:
#             raise TypeError(
#                 "Dont know how to handle response of type {}".format(type(res)))
# 
# Path: wham/apis/spotify/models.py
# class SpotifyTrack(WhamModel):
# 
#     id = WhamCharField(max_length=255, primary_key=True)
#     name = WhamTextField()
# 
#     href = WhamTextField(null=True)
#     popularity = WhamIntegerField(null=True)
#     track_number = WhamIntegerField(null=True)
#     uri = WhamTextField(null=True)
#     type = WhamTextField(null=True)
#     preview_url = WhamTextField(null=True)
#     artists = WhamManyToManyField('SpotifyArtist', related_name='tracks')
# 
#     class WhamMeta(SpotifyMeta):
#         endpoint = 'tracks'
# 
#         class Search:
#             endpoint = 'search'
#             params = {'type': 'track'}
#             results_path = ('tracks', 'items')
# 
#     class Meta:
#         db_table = 'spotify_track'
# 
#     def __unicode__(self):
#         return self.name
# 
# class SpotifyArtist(WhamModel):
# 
#     id = WhamCharField(max_length=255, primary_key=True)
#     name = WhamTextField()
# 
#     href = WhamTextField(null=True)
#     popularity = WhamIntegerField(null=True)
#     uri = WhamTextField(null=True)
# 
#     albums = WhamManyToManyField(
#         'SpotifyAlbum',
#         related_name='artists',
#         wham_endpoint='artists/{{id}}/albums',
#         wham_results_path=('items',)
#     )
# 
#     # TODO:
#     # tracks = WhamManyToManyField(
#     #     'SpotifyTrack',
#     #     # related_name='artists',
#     #     wham_endpoint='artists/{{id}}/albums',
#     #     wham_results_path=('items',)
#     # )
# 
#     class Meta:
#         db_table = 'spotify_artist'
# 
#     class WhamMeta(SpotifyMeta):
#         endpoint = 'artists'
# 
#         # i reckon this stuff should really be in Manager, as it has more to do with filter()
#         # which is a Manager method
# 
#         class Search:
#             endpoint = 'search'
#             params = {'type': 'artist'}
#             results_path = ('artists', 'items')
# 
#     def __unicode__(self):
#         return self.name
# 
# Path: wham/tests.py
# def build_httmock_functions(mock_response_dir):
#     print 'building mock functions'
#     functions = []
#     for filename in listdir(mock_response_dir):
#         filepath = join(mock_response_dir,filename)
#         if isfile(filepath):
#             method = None
#             for _method in ('GET', 'POST', 'PUT', 'DELETE', 'PATCH'):
#                 if filename.startswith(_method):
#                     filename = filename[len(_method):]
#                     method = _method
# 
#             url = urllib2.unquote(filename)
# 
#             parts = urlparse(url)
#             params = {}
#             if parts.query:
#                 print parts.query
#                 params = dict(parse_qsl(parts.query))
#                 print params
#             with open(filepath) as f:
#                 content = f.read()
#                 functions.append(build_httmock_function(
#                     parts.scheme, parts.netloc, parts.path, content, params=params, method=method))
#     return functions


# Path: wham/apis/spotify/tests.py
from os.path import join
from django.test import TestCase
from wham.httmock import HTTMock
from wham.apis.spotify.models import SpotifyTrack, SpotifyArtist
from wham.tests import build_httmock_functions
import os



APP_DIR = os.path.dirname(__file__)
MOCK_RESPONSES_DIR = join(APP_DIR, 'mock_responses')

mock_functions = build_httmock_functions(MOCK_RESPONSES_DIR)

class TestCase(TestCase):

    def test_spotify(self):


        with HTTMock(*mock_functions):