class TestApi(unittest.TestCase):

    def setUp(self):
        """Utility code shared among all tests."""
        self.api = Api('*****@*****.**', 'test_api_key')

    def test_init(self):
        """Test initialization of Api.

        Api is initialized on every test run and stored as self.sr. We just
        need to test stored values.
        """
        self.assertEquals(self.api.email_address, '*****@*****.**')
        self.assertEquals(self.api.api_key, 'test_api_key')

    @mock.patch('spinrewriter.urllib2')
    def test_send_request(self, urllib2):
        """Test that _send_requests correctly parses JSON response into a dict
        and that request parameters get encoded beforehand.
        """
        # mock response from connection
        urllib2.urlopen.return_value.read.return_value = '{"foo":"bär"}'

        # call it
        result = self.api._send_request({'foo': u'bär'.encode('utf-8')})

        # test response
        self.assertEquals(result['foo'], u'bär')

    @mock.patch('spinrewriter.urllib2')
    def test_api_quota_call(self, urllib2):
        """Test if Api.api_quota() correctly parses the response it gets from
        SpinRewriter API.
        """

        # mock response from urllib2
        mocked_response = u"""{
            "status":"OK",
            "response":"You made 0 API requests in the last 24 hours. 100 still available.",
            "api_requests_made":0,"api_requests_available":100
        }"""
        urllib2.urlopen.return_value.read.return_value = mocked_response

        # call API
        result = self.api.api_quota()

        # test responses
        self.assertEquals(result['status'], u'OK')
        self.assertEquals(result['api_requests_made'], 0)
        self.assertEquals(result['api_requests_available'], 100)
        self.assertEquals(
            result['response'],
            u'You made 0 API requests in the last 24 hours. 100 still available.'
        )

    @mock.patch('spinrewriter.urllib2')
    def test_text_with_spintax_call(self, urllib2):
        """Test if Api.text_with_spintax() correctly parses the response it gets
        from SpinRewriter API.
        """

        # mock response from urllib2
        mocked_response = u"""{
            "status":"OK",
            "response":"This is my über cute {dog|pet|animal}.",
            "api_requests_made":1,
            "api_requests_available":99,
            "protected_terms":"food, cat",
            "nested_spintax":"false",
            "confidence_level":"medium"
        }"""
        urllib2.urlopen.return_value.read.return_value = mocked_response

        # call API
        result = self.api.text_with_spintax(
            text=u"This is my über cute dog.",   # note the non-ascii character
            protected_terms=['food', 'cat']
        )

        # test results
        self.assertEquals(result['status'], u'OK')
        self.assertEquals(result['api_requests_made'], 1)
        self.assertEquals(result['api_requests_available'], 99)
        self.assertEquals(result['protected_terms'], u"food, cat")
        self.assertEquals(result['nested_spintax'], u"false")
        self.assertEquals(result['confidence_level'], u"medium")
        self.assertEquals(result['response'], u"This is my über cute {dog|pet|animal}.")

    @mock.patch('spinrewriter.urllib2')
    def test_unique_variation_call(self, urllib2):
        """Test if Api.unique_variation() correctly parses the response it gets
        from SpinRewriter API.
        """

        # mock response from urllib2
        mocked_response = u"""{
            "status":"OK",
            "response":"This is my über cute pet.",
            "api_requests_made":2,
            "api_requests_available":98,
            "protected_terms":"food, cat",
            "nested_spintax":"false",
            "confidence_level":"medium"
        }"""
        urllib2.urlopen.return_value.read.return_value = mocked_response

        # call API
        result = self.api.unique_variation(
            text=u"This is my über cute dog.",
            protected_terms=['food', 'cat']
        )

        # test results
        self.assertEquals(result['status'], u'OK')
        self.assertEquals(result['api_requests_made'], 2)
        self.assertEquals(result['api_requests_available'], 98)
        self.assertEquals(result['protected_terms'], u"food, cat")
        self.assertEquals(result['nested_spintax'], u"false")
        self.assertEquals(result['confidence_level'], u"medium")
        self.assertEquals(result['response'], u"This is my über cute pet.")

    @mock.patch('spinrewriter.urllib2')
    def test_unique_variation_from_spintax_call(self, urllib2):
        """Test if Api.unique_variation_from_spintax() correctly parses the response it gets
        from SpinRewriter API.
        """

        # mock response from urllib2
        mocked_response = u"""{
            "status":"OK",
            "response":"This is my über cute animal.",
            "api_requests_made":2,
            "api_requests_available":98,
            "confidence_level":"medium"
        }"""
        urllib2.urlopen.return_value.read.return_value = mocked_response

        # call API
        result = self.api.unique_variation_from_spintax(
            text=u"This is my über cute [dog|pet|animal].",
            nested_spintax=False,
            spintax_format=self.api.SPINTAX_FORMAT.pipe_square
        )

        # test results
        self.assertEquals(result['status'], u'OK')
        self.assertEquals(result['api_requests_made'], 2)
        self.assertEquals(result['api_requests_available'], 98)
        self.assertEquals(result['confidence_level'], u"medium")
        self.assertEquals(result['response'], u"This is my über cute animal.")

    @mock.patch('spinrewriter.urllib2')
    def test_transform_plain_text_call(self, urllib2):
        """Test if Api.transform_plain_text() correctly parses the response it
        gets from SpinRewriter API. This method is used by unique_variation()
        and text_with_spintax().
        """

        # mock response from urllib2
        mocked_response = u"""{
            "status":"OK",
            "response":"This is my über cute pet.",
            "api_requests_made":3,
            "api_requests_available":97,
            "protected_terms":"",
            "nested_spintax":"false",
            "confidence_level":"medium"
        }"""
        urllib2.urlopen.return_value.read.return_value = mocked_response

        # call API
        result = self.api._transform_plain_text(
            action=Api.ACTION.unique_variation,
            text=u"This is my über cute dog.",
            protected_terms=[],
            confidence_level=Api.CONFIDENCE_LVL.medium,
            nested_spintax=False,
            spintax_format=Api.SPINTAX_FORMAT.pipe_curly,
        )

        # test results
        self.assertEquals(result['status'], u'OK')
        self.assertEquals(result['api_requests_made'], 3)
        self.assertEquals(result['api_requests_available'], 97)
        self.assertEquals(result['protected_terms'], u"")
        self.assertEquals(result['nested_spintax'], u"false")
        self.assertEquals(result['confidence_level'], u"medium")
        self.assertEquals(result['response'], u"This is my über cute pet.")

    @mock.patch('spinrewriter.Api._send_request')
    def test_protected_terms_transformation(self, _send_request):
        """Test that protected_terms are correctly transformed into a string."""
        # prepare arguments for calling _transform_plain_text
        args = dict(
            action=Api.ACTION.unique_variation,
            text=u"This is my über tasty pet food.",
            protected_terms=['food', 'cat'],
            confidence_level=Api.CONFIDENCE_LVL.medium,
            nested_spintax=False,
            spintax_format=Api.SPINTAX_FORMAT.pipe_curly,
        )

        # we don't care what the response is
        _send_request.return_value = None

        # call it
        self.api._transform_plain_text(**args)

        # now test that protected_terms are in correct format
        _send_request.assert_called_with((
            ('email_address', '*****@*****.**'),
            ('api_key', 'test_api_key'),
            ('action', 'unique_variation'),
            ('text', u'This is my über tasty pet food.'.encode('utf-8')),
            # This is the only line we are interested in here,
            # it needs to be newline-separated
            ('protected_terms', 'food\ncat'),
            ('confidence_level', 'medium'),
            ('nested_spintax', False),
            ('spintax_format', '{|}'),
        ))

    @mock.patch('spinrewriter.Api._send_request')
    def test_protected_terms_empty(self, _send_request):
        """Test that correct default value is set for protected_terms if the
        list is empty.
        """
        # prepare arguments for calling _transform_plain_text
        args = dict(
            action=Api.ACTION.unique_variation,
            text=u"This is my über cute dog.",
            protected_terms=[],
            confidence_level=Api.CONFIDENCE_LVL.medium,
            nested_spintax=False,
            spintax_format=Api.SPINTAX_FORMAT.pipe_curly,
        )

        # we don't care what the response is
        _send_request.return_value = None

        # call it
        self.api._transform_plain_text(**args)

        # now test that protected_terms are in correct format
        _send_request.assert_called_with((
            ('email_address', '*****@*****.**'),
            ('api_key', 'test_api_key'),
            ('action', 'unique_variation'),
            ('text', u'This is my über cute dog.'.encode('utf-8')),
            # This is the only line we are interested in here,
            # it needs to be an empty string, not an empty list
            ('protected_terms', ''),
            ('confidence_level', 'medium'),
            ('nested_spintax', False),
            ('spintax_format', '{|}'),
        ))
 def setUp(self):
     """Utility code shared among all tests."""
     self.api = Api('*****@*****.**', 'test_api_key')
class TestErrors(unittest.TestCase):
    def setUp(self):
        """Utility code shared among all tests."""
        self.api = Api('*****@*****.**', 'test_api_key')

    def test_parsing_error_messages(self):
        """Go through all possible error messages and see that they are parsed
        correctly.
        """

        msg = u'Authentication with Spin Rewriter API failed.'
        with self.assertRaises(ex.AuthenticationError) as cm:
            self.api._raise_error({
                'response':
                'Authentication failed. Unique API key is not '
                'valid for this user.'
            })
        self.assertEqual(msg, str(cm.exception))

        with self.assertRaises(ex.AuthenticationError) as cm:
            self.api._raise_error({
                'response':
                'Authentication failed. No user with this email '
                'address found.'
            })
        self.assertEqual(msg, str(cm.exception))

        with self.assertRaises(ex.AuthenticationError) as cm:
            self.api._raise_error({
                'response':
                'This user does not have a valid Spin Rewriter '
                'subscription.'
            })
        self.assertEqual(msg, str(cm.exception))

        msg = u'Quota limit for API calls reached.'
        with self.assertRaises(ex.QuotaLimitError) as cm:
            self.api._raise_error({
                'response':
                'API quota exceeded. You can make 50 requests '
                'per day.'
            })
        self.assertEqual(msg, str(cm.exception))

        msg = u'Not enough time passed since last API request.'
        with self.assertRaises(ex.UsageFrequencyError) as cm:
            self.api._raise_error({
                'response':
                'You can only submit entirely new text for '
                'analysis once every 5 seconds.'
            })
        self.assertEqual(msg, str(cm.exception))

        msg = u'Unknown API action requested.'
        with self.assertRaises(ex.UnknownActionError) as cm:
            self.api._raise_error({
                'response':
                'Requested action does not exist. Please refer '
                'to the Spin Rewriter API documentation.'
            })
        self.assertEqual(msg, str(cm.exception))

        msg = u'Required parameter not present in API request.'
        with self.assertRaises(ex.MissingParameterError) as cm:
            self.api._raise_error({
                'response':
                'Email address and unique API key are both '
                'required. At least one is missing.'
            })
        self.assertEqual(msg, str(cm.exception))

        msg = u'Invalid parameter value passed to API.'
        with self.assertRaises(ex.ParamValueError) as cm:
            self.api._raise_error({'response': 'Original text too short.'})
        self.assertEqual(msg, str(cm.exception))

        with self.assertRaises(ex.ParamValueError) as cm:
            self.api._raise_error({
                'response':
                'Original text too long. '
                'Text can have up to 4,000 words.'
            })
        self.assertEqual(msg, str(cm.exception))

        with self.assertRaises(ex.ParamValueError) as cm:
            self.api._raise_error({
                'response':
                'Original text after analysis too long. '
                'Text can have up to 4,000 words.'
            })
        self.assertEqual(msg, str(cm.exception))

        with self.assertRaises(ex.ParamValueError) as cm:
            self.api._raise_error({
                'response':
                'Spinning syntax invalid. With this action you '
                'should provide text with existing valid '
                '{first option|second option} spintax.'
            })
        self.assertEqual(msg, str(cm.exception))

        with self.assertRaises(ex.ParamValueError) as cm:
            self.api._raise_error({
                'response':
                'The {first|second} spinning syntax invalid. '
                'Re-check the syntax, i.e. '
                'curly brackets and pipes.'
            })
        self.assertEqual(msg, str(cm.exception))

        with self.assertRaises(ex.ParamValueError) as cm:
            self.api._raise_error({'response': 'Spinning syntax invalid.'})
        self.assertEqual(msg, str(cm.exception))

        msg = u'Internal error occured on API server when processing request.'
        with self.assertRaises(ex.InternalApiError) as cm:
            self.api._raise_error({
                'response':
                'Analysis of your text failed. '
                'Please inform us about this.'
            })
        self.assertEqual(msg, str(cm.exception))

        with self.assertRaises(ex.InternalApiError) as cm:
            self.api._raise_error({
                'response':
                'Synonyms for your text could not be loaded. '
                'Please inform us about this.'
            })
        self.assertEqual(msg, str(cm.exception))

        with self.assertRaises(ex.InternalApiError) as cm:
            self.api._raise_error(
                {'response': 'Unable to load your new analyzed project.'})
        self.assertEqual(msg, str(cm.exception))

        with self.assertRaises(ex.InternalApiError) as cm:
            self.api._raise_error(
                {'response': 'Unable to load your existing analyzed project.'})
        self.assertEqual(msg, str(cm.exception))

        with self.assertRaises(ex.InternalApiError) as cm:
            self.api._raise_error(
                {'response': 'Unable to find your project in the database.'})
        self.assertEqual(msg, str(cm.exception))

        with self.assertRaises(ex.InternalApiError) as cm:
            self.api._raise_error(
                {'response': 'Unable to load your analyzed project.'})
        self.assertEqual(msg, str(cm.exception))

        with self.assertRaises(ex.InternalApiError) as cm:
            self.api._raise_error({'response': 'One-Click Rewrite failed.'})
        self.assertEqual(msg, str(cm.exception))

        msg = u'Unrecognized API error message received: foo'
        with self.assertRaises(ex.UnknownApiError) as cm:
            self.api._raise_error({'response': 'foo'})
        self.assertEqual(msg, str(cm.exception))
Exemple #4
0
class TestApi(unittest.TestCase):

    def setUp(self):
        """Utility code shared among all tests."""
        self.api = Api('*****@*****.**', 'test_api_key')

    def test_init(self):
        """Test initialization of Api.

        Api is initialized on every test run and stored as self.sr. We just
        need to test stored values.
        """
        self.assertEquals(self.api.email_address, '*****@*****.**')
        self.assertEquals(self.api.api_key, 'test_api_key')

    @mock.patch('spinrewriter.urllib2')
    def test_send_request(self, urllib2):
        """Test that _send_requests correctly parses JSON response into a dict
        and that request parameters get encoded beforehand.
        """
        # mock response from connection
        urllib2.urlopen.return_value.read.return_value = '{"foo":"bär"}'

        # call it
        result = self.api._send_request({'foo': u'bär'.encode('utf-8')})

        # test response
        self.assertEquals(result['foo'], u'bär')

    @mock.patch('spinrewriter.urllib2')
    def test_api_quota_call(self, urllib2):
        """Test if Api.api_quota() correctly parses the response it gets from
        SpinRewriter API.
        """

        # mock response from urllib2
        mocked_response = u"""{"status":"OK","response":"You made 0 API requests in the last 24 hours. 100 still available.","api_requests_made":0,"api_requests_available":100}"""  # noqa
        urllib2.urlopen.return_value.read.return_value = mocked_response

        # call API
        result = self.api.api_quota()

        # test responses
        self.assertEquals(result['status'], u'OK')
        self.assertEquals(result['api_requests_made'], 0)
        self.assertEquals(result['api_requests_available'], 100)
        self.assertEquals(
            result['response'],
            u'You made 0 API requests in the last 24 hours.'
            u' 100 still available.'
        )

    @mock.patch('spinrewriter.urllib2')
    def test_text_with_spintax_call(self, urllib2):
        """Test if Api.text_with_spintax() correctly parses the response it
        gets from SpinRewriter API.
        """

        # mock response from urllib2
        mocked_response = u"""{
            "status":"OK",
            "response":"This is my über cute {dog|pet|animal}.",
            "api_requests_made":1,
            "api_requests_available":99,
            "protected_terms":"food, cat",
            "nested_spintax":"false",
            "confidence_level":"medium"
        }"""
        urllib2.urlopen.return_value.read.return_value = mocked_response

        # call API
        result = self.api.text_with_spintax(
            text=u'This is my über cute dog.',  # note the non-ascii character
            protected_terms=['food', 'cat']
        )

        # test results
        self.assertEquals(result['status'], u'OK')
        self.assertEquals(result['api_requests_made'], 1)
        self.assertEquals(result['api_requests_available'], 99)
        self.assertEquals(result['protected_terms'], u'food, cat')
        self.assertEquals(result['nested_spintax'], u'false')
        self.assertEquals(result['confidence_level'], u'medium')
        self.assertEquals(
            result['response'], u'This is my über cute {dog|pet|animal}.')

    @mock.patch('spinrewriter.urllib2')
    def test_unique_variation_call(self, urllib2):
        """Test if Api.unique_variation() correctly parses the response it
        gets from SpinRewriter API.
        """

        # mock response from urllib2
        mocked_response = u"""{
            "status":"OK",
            "response":"This is my über cute pet.",
            "api_requests_made":2,
            "api_requests_available":98,
            "protected_terms":"food, cat",
            "nested_spintax":"false",
            "confidence_level":"medium"
        }"""
        urllib2.urlopen.return_value.read.return_value = mocked_response

        # call API
        result = self.api.unique_variation(
            text=u'This is my über cute dog.',
            protected_terms=['food', 'cat']
        )

        # test results
        self.assertEquals(result['status'], u'OK')
        self.assertEquals(result['api_requests_made'], 2)
        self.assertEquals(result['api_requests_available'], 98)
        self.assertEquals(result['protected_terms'], u'food, cat')
        self.assertEquals(result['nested_spintax'], u'false')
        self.assertEquals(result['confidence_level'], u'medium')
        self.assertEquals(result['response'], u'This is my über cute pet.')

    @mock.patch('spinrewriter.urllib2')
    def test_unique_variation_from_spintax_call(self, urllib2):
        """Test if Api.unique_variation_from_spintax() correctly parses the
        response it gets from SpinRewriter API.
        """

        # mock response from urllib2
        mocked_response = u"""{
            "status":"OK",
            "response":"This is my über cute animal.",
            "api_requests_made":2,
            "api_requests_available":98,
            "confidence_level":"medium"
        }"""
        urllib2.urlopen.return_value.read.return_value = mocked_response

        # call API
        result = self.api.unique_variation_from_spintax(
            text=u'This is my über cute [dog|pet|animal].',
            nested_spintax=False,
            spintax_format=self.api.SPINTAX_FORMAT.pipe_square
        )

        # test results
        self.assertEquals(result['status'], u'OK')
        self.assertEquals(result['api_requests_made'], 2)
        self.assertEquals(result['api_requests_available'], 98)
        self.assertEquals(result['confidence_level'], u'medium')
        self.assertEquals(result['response'], u'This is my über cute animal.')

    @mock.patch('spinrewriter.urllib2')
    def test_transform_plain_text_call(self, urllib2):
        """Test if Api.transform_plain_text() correctly parses the response it
        gets from SpinRewriter API. This method is used by unique_variation()
        and text_with_spintax().
        """

        # mock response from urllib2
        mocked_response = u"""{
            "status":"OK",
            "response":"This is my über cute pet.",
            "api_requests_made":3,
            "api_requests_available":97,
            "protected_terms":"",
            "nested_spintax":"false",
            "confidence_level":"medium"
        }"""
        urllib2.urlopen.return_value.read.return_value = mocked_response

        # call API
        result = self.api._transform_plain_text(
            action=Api.ACTION.unique_variation,
            text=u'This is my über cute dog.',
            protected_terms=[],
            confidence_level=Api.CONFIDENCE_LVL.medium,
            nested_spintax=False,
            spintax_format=Api.SPINTAX_FORMAT.pipe_curly,
        )

        # test results
        self.assertEquals(result['status'], u'OK')
        self.assertEquals(result['api_requests_made'], 3)
        self.assertEquals(result['api_requests_available'], 97)
        self.assertEquals(result['protected_terms'], u"")
        self.assertEquals(result['nested_spintax'], u'false')
        self.assertEquals(result['confidence_level'], u'medium')
        self.assertEquals(result['response'], u'This is my über cute pet.')

    @mock.patch('spinrewriter.Api._send_request')
    def test_protected_terms_transformation(self, _send_request):
        """Test that protected_terms are correctly transformed into
        a string."""
        # prepare arguments for calling _transform_plain_text
        args = dict(
            action=Api.ACTION.unique_variation,
            text=u'This is my über tasty pet food.',
            protected_terms=['food', 'cat'],
            confidence_level=Api.CONFIDENCE_LVL.medium,
            nested_spintax=False,
            spintax_format=Api.SPINTAX_FORMAT.pipe_curly,
        )

        # we don't care what the response is
        _send_request.return_value = None

        # call it
        self.api._transform_plain_text(**args)

        # now test that protected_terms are in correct format
        _send_request.assert_called_with((
            ('email_address', '*****@*****.**'),
            ('api_key', 'test_api_key'),
            ('action', 'unique_variation'),
            ('text', u'This is my über tasty pet food.'.encode('utf-8')),
            # This is the only line we are interested in here,
            # it needs to be newline-separated
            ('protected_terms', 'food\ncat'),
            ('confidence_level', 'medium'),
            ('nested_spintax', False),
            ('spintax_format', '{|}'),
        ))

    @mock.patch('spinrewriter.Api._send_request')
    def test_protected_terms_empty(self, _send_request):
        """Test that correct default value is set for protected_terms if the
        list is empty.
        """
        # prepare arguments for calling _transform_plain_text
        args = dict(
            action=Api.ACTION.unique_variation,
            text=u'This is my über cute dog.',
            protected_terms=[],
            confidence_level=Api.CONFIDENCE_LVL.medium,
            nested_spintax=False,
            spintax_format=Api.SPINTAX_FORMAT.pipe_curly,
        )

        # we don't care what the response is
        _send_request.return_value = None

        # call it
        self.api._transform_plain_text(**args)

        # now test that protected_terms are in correct format
        _send_request.assert_called_with((
            ('email_address', '*****@*****.**'),
            ('api_key', 'test_api_key'),
            ('action', 'unique_variation'),
            ('text', u'This is my über cute dog.'.encode('utf-8')),
            # This is the only line we are interested in here,
            # it needs to be an empty string, not an empty list
            ('protected_terms', ''),
            ('confidence_level', 'medium'),
            ('nested_spintax', False),
            ('spintax_format', '{|}'),
        ))

    @mock.patch('spinrewriter.urllib2')
    def test_unique_variation_from_spintax_error(self, urllib2):
        # mock response from SpinRewriter
        mocked_response = u"""{"status":"ERROR", "response":"Authentication failed. Unique API key is not valid for this user."}"""  # noqa
        urllib2.urlopen.return_value.read.return_value = mocked_response

        # test call
        with self.assertRaises(ex.AuthenticationError):
            self.api.unique_variation_from_spintax('This is my dog.')
Exemple #5
0
 def setUp(self):
     """Utility code shared among all tests."""
     self.api = Api('*****@*****.**', 'test_api_key')
Exemple #6
0
class TestErrors(unittest.TestCase):
    def setUp(self):
        """Utility code shared among all tests."""
        self.api = Api('*****@*****.**', 'test_api_key')

    def test_parsing_error_messages(self):
        """Go through all possible error messages and see that they are parsed
        correctly.
        """

        with self.assertRaises(ex.AuthenticationError):
            self.api._raise_error({
                'response':
                'Authentication failed. Unique API key is not valid for this user.'
            })

        with self.assertRaises(ex.AuthenticationError):
            self.api._raise_error({
                'response':
                'Authentication failed. No user with this email address found.'
            })

        with self.assertRaises(ex.AuthenticationError):
            self.api._raise_error({
                'response':
                'This user does not have a valid Spin Rewriter subscription.'
            })

        with self.assertRaises(ex.QuotaLimitError):
            self.api._raise_error({
                'response':
                'API quota exceeded. You can make 50 requests per day.'
            })

        with self.assertRaises(ex.UsageFrequencyError):
            self.api._raise_error({
                'response':
                'You can only submit entirely new text for analysis once every 5 seconds.'
            })

        with self.assertRaises(ex.UnknownActionError):
            self.api._raise_error({
                'response':
                'Requested action does not exist. Please refer to the Spin Rewriter API documentation.'
            })

        with self.assertRaises(ex.MissingParameterError):
            self.api._raise_error({
                'response':
                'Email address and unique API key are both required. At least one is missing.'
            })

        with self.assertRaises(ex.ParamValueError):
            self.api._raise_error({'response': 'Original text too short.'})

        with self.assertRaises(ex.ParamValueError):
            self.api._raise_error({
                'response':
                'Original text too long. Text can have up to 4,000 words.'
            })

        with self.assertRaises(ex.ParamValueError):
            self.api._raise_error({
                'response':
                'Original text after analysis too long. Text can have up to 4,000 words.'
            })

        with self.assertRaises(ex.ParamValueError):
            self.api._raise_error({
                'response':
                'Spinning syntax invalid. With this action you should provide text with existing valid {first option|second option} spintax.'
            })

        with self.assertRaises(ex.ParamValueError):
            self.api._raise_error({
                'response':
                'The {first|second} spinning syntax invalid. Re-check the syntax, i.e. curly brackets and pipes.'
            })

        with self.assertRaises(ex.ParamValueError):
            self.api._raise_error({'response': 'Spinning syntax invalid.'})

        with self.assertRaises(ex.InternalApiError):
            self.api._raise_error({
                'response':
                'Analysis of your text failed. Please inform us about this.'
            })

        with self.assertRaises(ex.InternalApiError):
            self.api._raise_error({
                'response':
                'Synonyms for your text could not be loaded. Please inform us about this.'
            })

        with self.assertRaises(ex.InternalApiError):
            self.api._raise_error(
                {'response': 'Unable to load your new analyzed project.'})

        with self.assertRaises(ex.InternalApiError):
            self.api._raise_error(
                {'response': 'Unable to load your existing analyzed project.'})

        with self.assertRaises(ex.InternalApiError):
            self.api._raise_error(
                {'response': 'Unable to find your project in the database.'})

        with self.assertRaises(ex.InternalApiError):
            self.api._raise_error(
                {'response': 'Unable to load your analyzed project.'})

        with self.assertRaises(ex.InternalApiError):
            self.api._raise_error({'response': 'One-Click Rewrite failed.'})

        with self.assertRaises(ex.UnknownApiError):
            self.api._raise_error({'response': 'foo'})
Exemple #7
0
class TestErrors(unittest.TestCase):

    def setUp(self):
        """Utility code shared among all tests."""
        self.api = Api('*****@*****.**', 'test_api_key')

    def test_parsing_error_messages(self):
        """Go through all possible error messages and see that they are parsed
        correctly.
        """

        msg = u'Authentication with Spin Rewriter API failed.'
        with self.assertRaises(ex.AuthenticationError) as cm:
            self.api._raise_error(
                {'response': 'Authentication failed. Unique API key is not '
                             'valid for this user.'})
        self.assertEqual(msg, str(cm.exception))

        with self.assertRaises(ex.AuthenticationError) as cm:
            self.api._raise_error(
                {'response': 'Authentication failed. No user with this email '
                             'address found.'})
        self.assertEqual(msg, str(cm.exception))

        with self.assertRaises(ex.AuthenticationError) as cm:
            self.api._raise_error(
                {'response': 'This user does not have a valid Spin Rewriter '
                             'subscription.'})
        self.assertEqual(msg, str(cm.exception))

        msg = u'Quota limit for API calls reached.'
        with self.assertRaises(ex.QuotaLimitError) as cm:
            self.api._raise_error(
                {'response': 'API quota exceeded. You can make 50 requests '
                             'per day.'})
        self.assertEqual(msg, str(cm.exception))

        msg = u'Not enough time passed since last API request.'
        with self.assertRaises(ex.UsageFrequencyError) as cm:
            self.api._raise_error(
                {'response': 'You can only submit entirely new text for '
                             'analysis once every 5 seconds.'})
        self.assertEqual(msg, str(cm.exception))

        msg = u'Unknown API action requested.'
        with self.assertRaises(ex.UnknownActionError) as cm:
            self.api._raise_error(
                {'response': 'Requested action does not exist. Please refer '
                             'to the Spin Rewriter API documentation.'})
        self.assertEqual(msg, str(cm.exception))

        msg = u'Required parameter not present in API request.'
        with self.assertRaises(ex.MissingParameterError) as cm:
            self.api._raise_error(
                {'response': 'Email address and unique API key are both '
                             'required. At least one is missing.'})
        self.assertEqual(msg, str(cm.exception))

        msg = u'Invalid parameter value passed to API.'
        with self.assertRaises(ex.ParamValueError) as cm:
            self.api._raise_error(
                {'response': 'Original text too short.'})
        self.assertEqual(msg, str(cm.exception))

        with self.assertRaises(ex.ParamValueError) as cm:
            self.api._raise_error(
                {'response': 'Original text too long. '
                             'Text can have up to 4,000 words.'})
        self.assertEqual(msg, str(cm.exception))

        with self.assertRaises(ex.ParamValueError) as cm:
            self.api._raise_error(
                {'response': 'Original text after analysis too long. '
                             'Text can have up to 4,000 words.'})
        self.assertEqual(msg, str(cm.exception))

        with self.assertRaises(ex.ParamValueError) as cm:
            self.api._raise_error(
                {'response': 'Spinning syntax invalid. With this action you '
                             'should provide text with existing valid '
                             '{first option|second option} spintax.'})
        self.assertEqual(msg, str(cm.exception))

        with self.assertRaises(ex.ParamValueError) as cm:
            self.api._raise_error(
                {'response': 'The {first|second} spinning syntax invalid. '
                             'Re-check the syntax, i.e. '
                             'curly brackets and pipes.'})
        self.assertEqual(msg, str(cm.exception))

        with self.assertRaises(ex.ParamValueError) as cm:
            self.api._raise_error(
                {'response': 'Spinning syntax invalid.'})
        self.assertEqual(msg, str(cm.exception))

        msg = u'Internal error occured on API server when processing request.'
        with self.assertRaises(ex.InternalApiError) as cm:
            self.api._raise_error(
                {'response': 'Analysis of your text failed. '
                             'Please inform us about this.'})
        self.assertEqual(msg, str(cm.exception))

        with self.assertRaises(ex.InternalApiError) as cm:
            self.api._raise_error(
                {'response': 'Synonyms for your text could not be loaded. '
                             'Please inform us about this.'})
        self.assertEqual(msg, str(cm.exception))

        with self.assertRaises(ex.InternalApiError) as cm:
            self.api._raise_error(
                {'response': 'Unable to load your new analyzed project.'})
        self.assertEqual(msg, str(cm.exception))

        with self.assertRaises(ex.InternalApiError) as cm:
            self.api._raise_error(
                {'response': 'Unable to load your existing analyzed project.'})
        self.assertEqual(msg, str(cm.exception))

        with self.assertRaises(ex.InternalApiError) as cm:
            self.api._raise_error(
                {'response': 'Unable to find your project in the database.'})
        self.assertEqual(msg, str(cm.exception))

        with self.assertRaises(ex.InternalApiError) as cm:
            self.api._raise_error(
                {'response': 'Unable to load your analyzed project.'})
        self.assertEqual(msg, str(cm.exception))

        with self.assertRaises(ex.InternalApiError) as cm:
            self.api._raise_error(
                {'response': 'One-Click Rewrite failed.'})
        self.assertEqual(msg, str(cm.exception))

        msg = u'Unrecognized API error message received: foo'
        with self.assertRaises(ex.UnknownApiError) as cm:
            self.api._raise_error(
                {'response': 'foo'})
        self.assertEqual(msg, str(cm.exception))