Ejemplo n.º 1
0
    def test_msg(self):
        """Set exception message successfully"""
        error1 = gTTSError('test')
        self.assertEqual('test', error1.msg)

        error2 = gTTSError()
        self.assertIsNone(error2.msg)
Ejemplo n.º 2
0
    def test_infer_msg(self):
        """Infer message sucessfully based on context"""

        # 403
        tts403 = Mock()
        response403 = Mock(status_code=403, reason='aaa')
        error403 = gTTSError(tts=tts403, response=response403)
        self.assertEqual(
            error403.msg,
            "403 (aaa) from TTS API. Probable cause: Bad token or upstream API changes")

        # 404 (and not lang_check)
        tts404 = Mock(lang='xx', lang_check=False)
        response404 = Mock(status_code=404, reason='bbb')
        error404 = gTTSError(tts=tts404, response=response404)
        self.assertEqual(
            error404.msg,
            "404 (bbb) from TTS API. Probable cause: Unsupported language 'xx'")

        # >= 500
        tts500 = Mock()
        response500 = Mock(status_code=500, reason='ccc')
        error500 = gTTSError(tts=tts500, response=response500)
        self.assertEqual(
            error500.msg,
            "500 (ccc) from TTS API. Probable cause: Uptream API error. Try again later.")

        # Unknown (ex. 100)
        tts100 = Mock()
        response100 = Mock(status_code=100, reason='ddd')
        error100 = gTTSError(tts=tts100, response=response100)
        self.assertEqual(
            error100.msg,
            "100 (ddd) from TTS API. Probable cause: Unknown")
Ejemplo n.º 3
0
def test_infer_msg():
    """Infer message sucessfully based on context"""

    # Without response:

    # Bad TLD
    ttsTLD = Mock(tld='invalid')
    errorTLD = gTTSError(tts=ttsTLD)
    assert errorTLD.msg == "Failed to connect. Probable cause: Host 'https://translate.google.invalid/' is not reachable"

    # With response:

    # 403
    tts403 = Mock()
    response403 = Mock(status_code=403, reason='aaa')
    error403 = gTTSError(tts=tts403, response=response403)
    assert error403.msg == "403 (aaa) from TTS API. Probable cause: Bad token or upstream API changes"

    # 404 (and not lang_check)
    tts404 = Mock(lang='xx', lang_check=False)
    response404 = Mock(status_code=404, reason='bbb')
    error404 = gTTSError(tts=tts404, response=response404)
    assert error404.msg == "404 (bbb) from TTS API. Probable cause: Unsupported language 'xx'"

    # >= 500
    tts500 = Mock()
    response500 = Mock(status_code=500, reason='ccc')
    error500 = gTTSError(tts=tts500, response=response500)
    assert error500.msg == "500 (ccc) from TTS API. Probable cause: Uptream API error. Try again later."

    # Unknown (ex. 100)
    tts100 = Mock()
    response100 = Mock(status_code=100, reason='ddd')
    error100 = gTTSError(tts=tts100, response=response100)
    assert error100.msg == "100 (ddd) from TTS API. Probable cause: Unknown"
Ejemplo n.º 4
0
def test_msg():
    """Test gTTsError internal exception handling
    Set exception message successfully"""
    error1 = gTTSError('test')
    assert 'test' == error1.msg

    error2 = gTTSError()
    assert error2.msg is None
Ejemplo n.º 5
0
    def write_to_fp_221(self, fp):
        """Do the TTS API request(s) and write bytes to a file-like object.
        Args:
            fp (file object): Any file-like object to write the ``mp3`` to.
        Raises:
            :class:`gTTSError`: When there's an error with the API request.
            TypeError: When ``fp`` is not a file-like object that takes bytes.
        """
        # When disabling ssl verify in requests (for proxies and firewalls),
        # urllib3 prints an insecure warning on stdout. We disable that.
        urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

        prepared_requests = self._prepare_requests()
        for idx, pr in enumerate(prepared_requests):
            try:
                with requests.Session() as s:
                    # Send request
                    r = s.send(request=pr,
                               # proxies=urllib.request.getproxies(),
                               proxies=proxies('tts_google'),
                               verify=False)

                log.debug("headers-%i: %s", idx, r.request.headers)
                log.debug("url-%i: %s", idx, r.request.url)
                log.debug("status-%i: %s", idx, r.status_code)

                r.raise_for_status()
            except requests.exceptions.HTTPError as e:  # pragma: no cover
                # Request successful, bad response
                log.debug(str(e))
                raise gTTSError(tts=self, response=r)
            except requests.exceptions.RequestException as e:  # pragma: no cover
                # Request failed
                log.debug(str(e))
                raise gTTSError(tts=self)

            try:
                # Write
                # for line in r.iter_lines(chunk_size=1024):
                for line in r.iter_lines(chunk_size=self._buff_size):
                    decoded_line = line.decode('utf-8')
                    if 'jQ1olc' in decoded_line:
                        audio_search = re.search(r'jQ1olc","\[\\"(.*)\\"]', decoded_line)
                        if audio_search:
                            as_bytes = audio_search.group(1).encode('ascii')
                            decoded = base64.b64decode(as_bytes)
                            fp.write(decoded)
                        else:
                            # Request successful, good response,
                            # no audio stream in response
                            raise gTTSError(tts=self, response=r)
                log.debug("part-%i written to %s", idx, fp)
            except (AttributeError, TypeError) as e:
                raise TypeError(
                    "'fp' is not a file-like object or it does not take bytes: %s" %
                    str(e))
def write_to_fp211(self, fp):
    """Do the TTS API request(s) and write bytes to a file-like object.
    Args:
        fp (file object): Any file-like object to write the ``mp3`` to.
    Raises:
        :class:`gTTSError`: When there's an error with the API request.
        TypeError: When ``fp`` is not a file-like object that takes bytes.
    """
    # When disabling ssl verify in requests (for proxies and firewalls),
    # urllib3 prints an insecure warning on stdout. We disable that.
    urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

    prepared_requests = self._prepare_requests()
    for idx, pr in enumerate(prepared_requests):
        try:
            with requests.Session() as s:
                # Send request
                r = s.send(
                    request=pr,
                    # proxies=urllib.request.getproxies(),
                    proxies=proxies('tts_google'),
                    verify=False)

            log.debug("headers-%i: %s", idx, r.request.headers)
            log.debug("url-%i: %s", idx, r.request.url)
            log.debug("status-%i: %s", idx, r.status_code)

            r.raise_for_status()
        except requests.exceptions.HTTPError as e:  # pragma: no cover
            # Request successful, bad response
            log.debug(str(e))
            raise gTTSError(tts=self, response=r)
        except requests.exceptions.RequestException as e:  # pragma: no cover
            # Request failed
            log.debug(str(e))
            raise gTTSError(tts=self)

        try:
            # Write
            # for chunk in r.iter_content(chunk_size=1024):
            for chunk in r.iter_content(chunk_size=self._buff_size):
                fp.write(chunk)
            log.debug("part-%i written to %s", idx, fp)
        except (AttributeError, TypeError) as e:
            raise TypeError(
                "'fp' is not a file-like object or it does not take bytes: %s"
                % str(e))
def write_to_fp_203(self, fp):
    """Do the TTS API request and write bytes to a file-like object.

    Args:
        fp (file object): Any file-like object to write the ``mp3`` to.

    Raises:
        :class:`gTTSError`: When there's an error with the API request.
        TypeError: When ``fp`` is not a file-like object that takes bytes.

    """
    # When disabling ssl verify in requests (for proxies and firewalls),
    # urllib3 prints an insecure warning on stdout. We disable that.
    urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

    text_parts = self._tokenize(self.text)
    log.debug("text_parts: %i", len(text_parts))
    assert text_parts, 'No text to send to TTS API'

    for idx, part in enumerate(text_parts):
        try:
            # Calculate token
            part_tk = self.token.calculate_token(part)
        except requests.exceptions.RequestException as e:  # pragma: no cover
            log.debug(str(e), exc_info=True)
            raise gTTSError("Connection error during token calculation: %s" %
                            str(e))

        payload = {
            'ie': 'UTF-8',
            'q': part,
            'tl': self.lang,
            'ttsspeed': self.speed,
            'total': len(text_parts),
            'idx': idx,
            'client': 'tw-ob',
            'textlen': _len(part),
            'tk': part_tk
        }

        log.debug("payload-%i: %s", idx, payload)

        try:
            # Request
            r = requests.get(
                self.GOOGLE_TTS_URL,
                params=payload,
                headers=self.GOOGLE_TTS_HEADERS,
                # proxies=urllib.request.getproxies(),
                proxies=proxies('tts_google'),
                verify=False)

            log.debug("headers-%i: %s", idx, r.request.headers)
            log.debug("url-%i: %s", idx, r.request.url)
            log.debug("status-%i: %s", idx, r.status_code)

            r.raise_for_status()
        except requests.exceptions.HTTPError:
            # Request successful, bad response
            raise gTTSError(tts=self, response=r)
        except requests.exceptions.RequestException as e:  # pragma: no cover
            # Request failed
            raise gTTSError(str(e))

        try:
            # Write
            # for chunk in r.iter_content(chunk_size=1024):
            for chunk in r.iter_content(chunk_size=self._buff_size):
                fp.write(chunk)
            log.debug("part-%i written to %s", idx, fp)
        except (AttributeError, TypeError) as e:
            raise TypeError(
                "'fp' is not a file-like object or it does not take bytes: %s"
                % str(e))