<commit_before>import json
import os
import unittest

import responses
from requests.exceptions import HTTPError


from togglwrapper import api
from togglwrapper.exceptions import AuthError


FAKE_TOKEN = '<PASSWORD>'
FIXTURES_PATH = '%s/fixtures' % os.path.dirname(os.path.abspath(__file__))


class TestTogglBase(unittest.TestCase):
    """ Class to establish utility methods for Test classes. """

    api_token = FAKE_TOKEN
    focus_class = None

    def compile_full_url(self, id=None, ids=None, child_uri=None):
        """ Compile a full URL from the base url. """
        focus_class = self.focus_class
        uri = focus_class._compile_uri(id=id, ids=ids, child_uri=child_uri)
        return self.toggl.api_url + uri

    def setUp(self):
        self.toggl = api.Toggl(self.api_token)

    def get_json(self, filename):
        """ Return the JSON data in the .json file with the given filename. """
        file_path = '{path}/{filename}.json'.format(path=FIXTURES_PATH,
                                                    filename=filename)
        with open(file_path) as json_file:
            json_dict = json.load(json_file)
            json_file.close()
        raw_json = json.dumps(json_dict)
        return raw_json

    def responses_add(self, method, filename=None, id=None, ids=None,
                      child_uri=None, status_code=200, content_type=''):
        """ Adds a mock response for requests to a certain url. """
        body = None
        if filename is not None:
            body = self.get_json(filename)
            content_type = 'application/json'

        responses.add(
            getattr(responses, method),
            self.compile_full_url(id=id, ids=ids, child_uri=child_uri),
            body=body,
            status=status_code,
            content_type=content_type
        )


class TestToggl(TestTogglBase):

    @responses.activate
    def test_wrong_token(self):
        """ Should raise exception when wrong API token is provided. """
        full_url = self.toggl.api_url + self.toggl.User.uri
        responses.add(responses.GET, full_url, status=403)
        self.assertRaises(AuthError, self.toggl.User.get)
        self.assertEqual(len(responses.calls), 1)

    @responses.activate
    def test_failed_request(self):
        """ Should raise an HTTPError with status code 404. """
        full_url = self.toggl.api_url + self.toggl.TimeEntries.uri
        responses.add(
            responses.POST,
            full_url,
            body=self.get_json('failed_request'),
            status=404,
        )
        wrong_data = {"time_entry": {
            "description": "New time entry",
            "created_with": "API example code"
        }}
        self.assertRaises(HTTPError, self.toggl.TimeEntries.create,
                          data=wrong_data)
        # Ensure that the error message in the response is the exception reason
        reason = json.loads(self.get_json('failed_request'))
        try:
            self.toggl.TimeEntries.create(data=wrong_data)
        except HTTPError, e:
            self.assertEqual(e.response.reason, reason)
        else:
            raise Exception('Reason was not correct.')

        # Ensure that the mocked response was triggered twice
        self.assertEqual(len(responses.calls), 2)


class TestClients(TestTogglBase):
    focus_class = api.Clients

    @responses.activate
    def test_create(self):
        """ Should create a new Client. """
        self.responses_add('POST', filename='client_create')
        create_data = {"client": {"name": "Very Big Company", "wid": 777}}
        response = self.toggl.Clients.create(create_data)
        self.assertEqual(type(response), dict)
        self.assertEqual(len(responses.calls), 1)

    @responses.activate<commit_msg>Fixed old use of exception handling, to be Python3 compatible<commit_after>import json
import os
import unittest

import responses
from requests.exceptions import HTTPError


from togglwrapper import api
from togglwrapper.exceptions import AuthError


FAKE_TOKEN = 'fake_<PASSWORD>'
FIXTURES_PATH = '%s/fixtures' % os.path.dirname(os.path.abspath(__file__))


class TestTogglBase(unittest.TestCase):
    """ Class to establish utility methods for Test classes. """

    api_token = FAKE_TOKEN
    focus_class = None

    def compile_full_url(self, id=None, ids=None, child_uri=None):
        """ Compile a full URL from the base url. """
        focus_class = self.focus_class
        uri = focus_class._compile_uri(id=id, ids=ids, child_uri=child_uri)
        return self.toggl.api_url + uri

    def setUp(self):
        self.toggl = api.Toggl(self.api_token)

    def get_json(self, filename):
        """ Return the JSON data in the .json file with the given filename. """
        file_path = '{path}/{filename}.json'.format(path=FIXTURES_PATH,
                                                    filename=filename)
        with open(file_path) as json_file:
            json_dict = json.load(json_file)
            json_file.close()
        raw_json = json.dumps(json_dict)
        return raw_json

    def responses_add(self, method, filename=None, id=None, ids=None,
                      child_uri=None, status_code=200, content_type=''):
        """ Adds a mock response for requests to a certain url. """
        body = None
        if filename is not None:
            body = self.get_json(filename)
            content_type = 'application/json'

        responses.add(
            getattr(responses, method),
            self.compile_full_url(id=id, ids=ids, child_uri=child_uri),
            body=body,
            status=status_code,
            content_type=content_type
        )


class TestToggl(TestTogglBase):

    @responses.activate
    def test_wrong_token(self):
        """ Should raise exception when wrong API token is provided. """
        full_url = self.toggl.api_url + self.toggl.User.uri
        responses.add(responses.GET, full_url, status=403)
        self.assertRaises(AuthError, self.toggl.User.get)
        self.assertEqual(len(responses.calls), 1)

    @responses.activate
    def test_failed_request(self):
        """ Should raise an HTTPError with status code 404. """
        full_url = self.toggl.api_url + self.toggl.TimeEntries.uri
        responses.add(
            responses.POST,
            full_url,
            body=self.get_json('failed_request'),
            status=404,
        )
        wrong_data = {"time_entry": {
            "description": "New time entry",
            "created_with": "API example code"
        }}
        self.assertRaises(HTTPError, self.toggl.TimeEntries.create,
                          data=wrong_data)
        # Ensure that the error message in the response is the exception reason
        reason = json.loads(self.get_json('failed_request'))
        try:
            self.toggl.TimeEntries.create(data=wrong_data)
        except HTTPError as e:
            self.assertEqual(e.response.reason, reason)
        else:
            raise Exception('Reason was not correct.')

        # Ensure that the mocked response was triggered twice
        self.assertEqual(len(responses.calls), 2)


class TestClients(TestTogglBase):
    focus_class = api.Clients

    @responses.activate
    def test_create(self):
        """ Should create a new Client. """
        self.responses_add('POST', filename='client_create')
        create_data = {"client": {"name": "Very Big Company", "wid": 777}}
        response = self.toggl.Clients.create(create_data)
        self.assertEqual(type(response), dict)
        self.assertEqual(len(responses.calls), 1)

    @responses.activate
{'fraction_non_alphanumeric': 0.09977739950242241, 'fraction_numerical': 0.0048448343590415084, 'mean_word_length': 2.4639455782312925, 'pattern_counts': {'":': 12, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6374489', 'n_tokens_mistral': 2261, 'n_tokens_neox': 2230, 'n_words': 519}