# Path: pyhamtools/qsl.py
# def get_lotw_users(**kwargs):
#     """Download the latest offical list of `ARRL Logbook of the World (LOTW)`__ users.
# 
#         Args:
#             url (str, optional): Download URL
# 
#         Returns:
#             dict: Dictionary containing the callsign (unicode) date of the last LOTW upload (datetime)
# 
#         Raises:
#             IOError: When network is unavailable, file can't be downloaded or processed
# 
#             ValueError: Raised when data from file can't be read
# 
#         Example:
#            The following example downloads the LOTW user list and check when DH1TW has made his last LOTW upload:
# 
#            >>> from pyhamtools.qsl import get_lotw_users
#            >>> mydict = get_lotw_users()
#            >>> mydict['DH1TW']
#            datetime.datetime(2014, 9, 7, 0, 0)
# 
#     .. _ARRL: http://www.arrl.org/logbook-of-the-world
#     __ ARRL_
# 
#     """
# 
#     url = ""
# 
#     lotw = {}
# 
#     try:
#         url = kwargs['url']
#     except KeyError:
#         # url = "http://wd5eae.org/LoTW_Data.txt"
#         url = "https://lotw.arrl.org/lotw-user-activity.csv"
# 
#     try:
#         result = requests.get(url)
#     except (ConnectionError, HTTPError, Timeout) as e:
#         raise IOError(e)
# 
#     error_count = 0
# 
#     if result.status_code == requests.codes.ok:
#         for el in result.text.split():
#             data = el.split(",")
#             try:
#                 lotw[data[0]] = datetime.strptime(data[1], '%Y-%m-%d')
#             except ValueError as e:
#                 error_count += 1
#                 if error_count > 10:
#                     raise ValueError("more than 10 wrongly formatted datasets " + str(e))
# 
#     else:
#         raise IOError("HTTP Error: " + str(result.status_code))
# 
#     return lotw


import os
import sys
import datetime
import pytest
from past.builtins import execfile
from future.utils import iteritems
from pyhamtools.qsl import get_lotw_users

test_dir = os.path.dirname(os.path.abspath(__file__))
fix_dir = os.path.join(test_dir, 'fixtures')

class Test_lotw_methods:

    def test_check_content_with_mocked_http_server(self, httpserver):
        httpserver.serve_content(open(os.path.join(fix_dir, 'lotw-user-activity.csv')).read())

        namespace = {}
        execfile(os.path.join(fix_dir,"lotw_fixture.py"), namespace)
        assert get_lotw_users(url=httpserver.url) == namespace['lotw_fixture']

    def test_download_lotw_list_and_check_types(self):

        data = get_lotw_users()
        assert isinstance(data, dict)
        for key, value in iteritems(data):
            assert isinstance(key, unicode)
            assert isinstance(value, datetime.datetime )
        assert len(data) > 1000

    def test_with_invalid_url(self):
        with pytest.raises(IOError):
            get_lotw_users(url="https://lotw.arrl.org/lotw-user-activity_FAKE.csv")

    def test_with_more_than_10_invalid_dates(self, httpserver):
        httpserver.serve_content(open(os.path.join(fix_dir, 'lotw_data_with_errors.html')).read())

        with pytest.raises(ValueError):

# Path: pyhamtools/qsl.py
# def get_lotw_users(**kwargs):
#     """Download the latest offical list of `ARRL Logbook of the World (LOTW)`__ users.
# 
#         Args:
#             url (str, optional): Download URL
# 
#         Returns:
#             dict: Dictionary containing the callsign (unicode) date of the last LOTW upload (datetime)
# 
#         Raises:
#             IOError: When network is unavailable, file can't be downloaded or processed
# 
#             ValueError: Raised when data from file can't be read
# 
#         Example:
#            The following example downloads the LOTW user list and check when DH1TW has made his last LOTW upload:
# 
#            >>> from pyhamtools.qsl import get_lotw_users
#            >>> mydict = get_lotw_users()
#            >>> mydict['DH1TW']
#            datetime.datetime(2014, 9, 7, 0, 0)
# 
#     .. _ARRL: http://www.arrl.org/logbook-of-the-world
#     __ ARRL_
# 
#     """
# 
#     url = ""
# 
#     lotw = {}
# 
#     try:
#         url = kwargs['url']
#     except KeyError:
#         # url = "http://wd5eae.org/LoTW_Data.txt"
#         url = "https://lotw.arrl.org/lotw-user-activity.csv"
# 
#     try:
#         result = requests.get(url)
#     except (ConnectionError, HTTPError, Timeout) as e:
#         raise IOError(e)
# 
#     error_count = 0
# 
#     if result.status_code == requests.codes.ok:
#         for el in result.text.split():
#             data = el.split(",")
#             try:
#                 lotw[data[0]] = datetime.strptime(data[1], '%Y-%m-%d')
#             except ValueError as e:
#                 error_count += 1
#                 if error_count > 10:
#                     raise ValueError("more than 10 wrongly formatted datasets " + str(e))
# 
#     else:
#         raise IOError("HTTP Error: " + str(result.status_code))
# 
#     return lotw


# Path: test/test_lotw.py
import os
import sys
import datetime
import pytest
from past.builtins import execfile
from future.utils import iteritems
from pyhamtools.qsl import get_lotw_users


test_dir = os.path.dirname(os.path.abspath(__file__))
fix_dir = os.path.join(test_dir, 'fixtures')

class Test_lotw_methods:

    def test_check_content_with_mocked_http_server(self, httpserver):
        httpserver.serve_content(open(os.path.join(fix_dir, 'lotw-user-activity.csv')).read())

        namespace = {}
        execfile(os.path.join(fix_dir,"lotw_fixture.py"), namespace)
        assert get_lotw_users(url=httpserver.url) == namespace['lotw_fixture']

    def test_download_lotw_list_and_check_types(self):

        data = get_lotw_users()
        assert isinstance(data, dict)
        for key, value in iteritems(data):
            assert isinstance(key, unicode)
            assert isinstance(value, datetime.datetime )
        assert len(data) > 1000

    def test_with_invalid_url(self):
        with pytest.raises(IOError):
            get_lotw_users(url="https://lotw.arrl.org/lotw-user-activity_FAKE.csv")

    def test_with_more_than_10_invalid_dates(self, httpserver):
        httpserver.serve_content(open(os.path.join(fix_dir, 'lotw_data_with_errors.html')).read())

        with pytest.raises(ValueError):

            get_lotw_users(url=httpserver.url)