nidhal baccouri commited on
Commit
70f6ed6
·
1 Parent(s): 4524f4c

global refactoring

Browse files
deep_translator/constants.py CHANGED
@@ -6,9 +6,9 @@ BASE_URLS = {
6
  "YANDEX": "https://translate.yandex.net/api/{version}/tr.json/{endpoint}",
7
  "LINGUEE": "https://www.linguee.com/",
8
  "MYMEMORY": "http://api.mymemory.translated.net/get",
9
- "QcriTranslator": "https://mt.qcri.org/api/v1/{endpoint}?",
10
  "DEEPL": "https://api.deepl.com/{version}/",
11
- "DEEPL_FREE": "https://api-free.deepl.com/v2/",
12
  "MICROSOFT_TRANSLATE": "https://api.cognitive.microsofttranslator.com/translate?api-version=3.0",
13
  "PAPAGO": "https://papago.naver.com/",
14
  "PAPAGO_API": "https://openapi.naver.com/v1/papago/n2mt",
 
6
  "YANDEX": "https://translate.yandex.net/api/{version}/tr.json/{endpoint}",
7
  "LINGUEE": "https://www.linguee.com/",
8
  "MYMEMORY": "http://api.mymemory.translated.net/get",
9
+ "QCRI": "https://mt.qcri.org/api/v1/{endpoint}?",
10
  "DEEPL": "https://api.deepl.com/{version}/",
11
+ "DEEPL_FREE": "https://api-free.deepl.com/{version}/",
12
  "MICROSOFT_TRANSLATE": "https://api.cognitive.microsofttranslator.com/translate?api-version=3.0",
13
  "PAPAGO": "https://papago.naver.com/",
14
  "PAPAGO_API": "https://openapi.naver.com/v1/papago/n2mt",
deep_translator/deepl.py CHANGED
@@ -1,11 +1,11 @@
1
  import requests
2
 
3
- from .validate import is_empty
4
- from .constants import BASE_URLS, DEEPL_LANGUAGE_TO_CODE
5
- from .exceptions import (ServerException,
6
  TranslationNotFound,
7
  AuthorizationException)
8
- from .base import BaseTranslator
9
 
10
 
11
  class DeeplTranslator(BaseTranslator):
@@ -24,49 +24,50 @@ class DeeplTranslator(BaseTranslator):
24
  raise ServerException(401)
25
  self.version = 'v2'
26
  self.api_key = api_key
27
- if use_free_api:
28
- self._base_url = BASE_URLS.get(
29
- "DEEPL_FREE").format(version=self.version)
30
- else:
31
- self._base_url = BASE_URLS.get(
32
  "DEEPL").format(version=self.version)
33
- super().__init__(source=source,
34
- target=target,
35
- languages=DEEPL_LANGUAGE_TO_CODE)
 
 
 
36
 
37
  def translate(self, text, **kwargs):
38
  """
39
  @param text: text to translate
40
  @return: translated text
41
  """
42
- if self._same_source_target() or is_empty(text):
43
- return text
 
44
 
45
- # Create the request parameters.
46
- translate_endpoint = 'translate'
47
- params = {
48
- "auth_key": self.api_key,
49
- "source_lang": self._source,
50
- "target_lang": self._target,
51
- "text": text
52
- }
53
- # Do the request and check the connection.
54
- try:
55
- response = requests.get(
56
- self._base_url + translate_endpoint, params=params)
57
- except ConnectionError:
58
- raise ServerException(503)
59
- # If the answer is not success, raise server exception.
60
- if response.status_code == 403:
61
- raise AuthorizationException(self.api_key)
62
- elif response.status_code != 200:
63
- raise ServerException(response.status_code)
64
- # Get the response and check is not empty.
65
- res = response.json()
66
- if not res:
67
- raise TranslationNotFound(text)
68
- # Process and return the response.
69
- return res['translations'][0]['text']
70
 
71
  def translate_file(self, path, **kwargs):
72
  return self._translate_file(path, **kwargs)
@@ -80,6 +81,6 @@ class DeeplTranslator(BaseTranslator):
80
 
81
 
82
  if __name__ == '__main__':
83
- d = DeeplTranslator(target="de")
84
- t = d.translate("I have no idea")
85
  print("text: ", t)
 
1
  import requests
2
 
3
+ from deep_translator.validate import is_empty, validate_input
4
+ from deep_translator.constants import BASE_URLS, DEEPL_LANGUAGE_TO_CODE
5
+ from deep_translator.exceptions import (ServerException,
6
  TranslationNotFound,
7
  AuthorizationException)
8
+ from deep_translator.base import BaseTranslator
9
 
10
 
11
  class DeeplTranslator(BaseTranslator):
 
24
  raise ServerException(401)
25
  self.version = 'v2'
26
  self.api_key = api_key
27
+ url = BASE_URLS.get(
28
+ "DEEPL_FREE").format(version=self.version) if use_free_api else BASE_URLS.get(
 
 
 
29
  "DEEPL").format(version=self.version)
30
+ super().__init__(
31
+ base_url=url,
32
+ source=source,
33
+ target=target,
34
+ languages=DEEPL_LANGUAGE_TO_CODE,
35
+ **kwargs)
36
 
37
  def translate(self, text, **kwargs):
38
  """
39
  @param text: text to translate
40
  @return: translated text
41
  """
42
+ if validate_input(text):
43
+ if self._same_source_target() or is_empty(text):
44
+ return text
45
 
46
+ # Create the request parameters.
47
+ translate_endpoint = 'translate'
48
+ params = {
49
+ "auth_key": self.api_key,
50
+ "source_lang": self._source,
51
+ "target_lang": self._target,
52
+ "text": text
53
+ }
54
+ # Do the request and check the connection.
55
+ try:
56
+ response = requests.get(
57
+ self._base_url + translate_endpoint, params=params)
58
+ except ConnectionError:
59
+ raise ServerException(503)
60
+ # If the answer is not success, raise server exception.
61
+ if response.status_code == 403:
62
+ raise AuthorizationException(self.api_key)
63
+ elif response.status_code != 200:
64
+ raise ServerException(response.status_code)
65
+ # Get the response and check is not empty.
66
+ res = response.json()
67
+ if not res:
68
+ raise TranslationNotFound(text)
69
+ # Process and return the response.
70
+ return res['translations'][0]['text']
71
 
72
  def translate_file(self, path, **kwargs):
73
  return self._translate_file(path, **kwargs)
 
81
 
82
 
83
  if __name__ == '__main__':
84
+ d = DeeplTranslator(target="en", api_key="some-key")
85
+ t = d.translate("Ich habe keine ahnung")
86
  print("text: ", t)
deep_translator/google.py CHANGED
@@ -37,11 +37,10 @@ class GoogleTranslator(BaseTranslator):
37
  @param text: desired text to translate
38
  @return: str: translated text
39
  """
40
- if self._same_source_target() or is_empty(text):
41
- return text
42
-
43
  if validate_input(text):
44
  text = text.strip()
 
 
45
  self._url_params['tl'] = self._target
46
  self._url_params['sl'] = self._source
47
 
 
37
  @param text: desired text to translate
38
  @return: str: translated text
39
  """
 
 
 
40
  if validate_input(text):
41
  text = text.strip()
42
+ if self._same_source_target() or is_empty(text):
43
+ return text
44
  self._url_params['tl'] = self._target
45
  self._url_params['sl'] = self._source
46
 
deep_translator/libre.py CHANGED
@@ -4,7 +4,7 @@ LibreTranslate API
4
 
5
  import requests
6
 
7
- from .validate import is_empty
8
  from .base import BaseTranslator
9
  from .constants import BASE_URLS,LIBRE_LANGUAGES_TO_CODES
10
  from .exceptions import (ServerException,
@@ -38,36 +38,37 @@ class LibreTranslator(BaseTranslator):
38
  @param text: desired text to translate
39
  @return: str: translated text
40
  """
41
- if self._same_source_target() or is_empty(text):
42
- return text
 
43
 
44
- translate_endpoint = 'translate'
45
- params = {
46
- "q": text,
47
- "source": self._source,
48
- "target": self._target,
49
- "format": 'text'
50
- }
51
- # Add API Key if required
52
- if self.api_key:
53
- params["api_key"] = self.api_key
54
- # Do the request and check the connection.
55
- try:
56
- response = requests.post(self._base_url + translate_endpoint, params=params)
57
- except ConnectionError:
58
- raise ServerException(503)
59
- # If the answer is not success, raise server exception.
60
 
61
- if response.status_code == 403:
62
- raise AuthorizationException(self.api_key)
63
- elif response.status_code != 200:
64
- raise ServerException(response.status_code)
65
- # Get the response and check is not empty.
66
- res = response.json()
67
- if not res:
68
- raise TranslationNotFound(text)
69
- # Process and return the response.
70
- return res['translatedText']
71
 
72
  def translate_file(self, path, **kwargs):
73
  """
 
4
 
5
  import requests
6
 
7
+ from .validate import is_empty, validate_input
8
  from .base import BaseTranslator
9
  from .constants import BASE_URLS,LIBRE_LANGUAGES_TO_CODES
10
  from .exceptions import (ServerException,
 
38
  @param text: desired text to translate
39
  @return: str: translated text
40
  """
41
+ if validate_input(text):
42
+ if self._same_source_target() or is_empty(text):
43
+ return text
44
 
45
+ translate_endpoint = 'translate'
46
+ params = {
47
+ "q": text,
48
+ "source": self._source,
49
+ "target": self._target,
50
+ "format": 'text'
51
+ }
52
+ # Add API Key if required
53
+ if self.api_key:
54
+ params["api_key"] = self.api_key
55
+ # Do the request and check the connection.
56
+ try:
57
+ response = requests.post(self._base_url + translate_endpoint, params=params)
58
+ except ConnectionError:
59
+ raise ServerException(503)
60
+ # If the answer is not success, raise server exception.
61
 
62
+ if response.status_code == 403:
63
+ raise AuthorizationException(self.api_key)
64
+ elif response.status_code != 200:
65
+ raise ServerException(response.status_code)
66
+ # Get the response and check is not empty.
67
+ res = response.json()
68
+ if not res:
69
+ raise TranslationNotFound(text)
70
+ # Process and return the response.
71
+ return res['translatedText']
72
 
73
  def translate_file(self, path, **kwargs):
74
  """
deep_translator/microsoft.py CHANGED
@@ -6,6 +6,7 @@ import sys
6
  from .constants import BASE_URLS
7
  from .exceptions import ServerException, MicrosoftAPIerror
8
  from .base import BaseTranslator
 
9
 
10
 
11
  class MicrosoftTranslator(BaseTranslator):
@@ -61,29 +62,30 @@ class MicrosoftTranslator(BaseTranslator):
61
  # a body must be a list of dicts to process multiple texts;
62
  # I have not added multiple text processing here since it is covered by the translate_batch method
63
 
64
- self._url_params['from'] = self._source
65
- self._url_params['to'] = self._target
66
-
67
- valid_microsoft_json = [{'text': text}]
68
- try:
69
- requested = requests.post(self._base_url,
70
- params=self._url_params,
71
- headers=self.headers,
72
- json=valid_microsoft_json,
73
- proxies=self.proxies)
74
- except requests.exceptions.RequestException:
75
- exc_type, value, traceback = sys.exc_info()
76
- logging.warning(f"Returned error: {exc_type.__name__}")
77
-
78
- # Where Microsoft API responds with an api error, it returns a dict in response.json()
79
- if type(requested.json()) is dict:
80
- error_message = requested.json()['error']
81
- raise MicrosoftAPIerror(error_message)
82
- # Where it responds with a translation, its response.json() is a list e.g. [{'translations': [{'text': 'Hello world!', 'to': 'en'}]}]
83
- elif type(requested.json()) is list:
84
- all_translations = [i['text']
85
- for i in requested.json()[0]['translations']]
86
- return "\n".join(all_translations)
 
87
 
88
  def translate_file(self, path, **kwargs):
89
  """
 
6
  from .constants import BASE_URLS
7
  from .exceptions import ServerException, MicrosoftAPIerror
8
  from .base import BaseTranslator
9
+ from .validate import validate_input
10
 
11
 
12
  class MicrosoftTranslator(BaseTranslator):
 
62
  # a body must be a list of dicts to process multiple texts;
63
  # I have not added multiple text processing here since it is covered by the translate_batch method
64
 
65
+ if validate_input(text):
66
+ self._url_params['from'] = self._source
67
+ self._url_params['to'] = self._target
68
+
69
+ valid_microsoft_json = [{'text': text}]
70
+ try:
71
+ requested = requests.post(self._base_url,
72
+ params=self._url_params,
73
+ headers=self.headers,
74
+ json=valid_microsoft_json,
75
+ proxies=self.proxies)
76
+ except requests.exceptions.RequestException:
77
+ exc_type, value, traceback = sys.exc_info()
78
+ logging.warning(f"Returned error: {exc_type.__name__}")
79
+
80
+ # Where Microsoft API responds with an api error, it returns a dict in response.json()
81
+ if type(requested.json()) is dict:
82
+ error_message = requested.json()['error']
83
+ raise MicrosoftAPIerror(error_message)
84
+ # Where it responds with a translation, its response.json() is a list e.g. [{'translations': [{'text': 'Hello world!', 'to': 'en'}]}]
85
+ elif type(requested.json()) is list:
86
+ all_translations = [i['text']
87
+ for i in requested.json()[0]['translations']]
88
+ return "\n".join(all_translations)
89
 
90
  def translate_file(self, path, **kwargs):
91
  """
deep_translator/mymemory.py CHANGED
@@ -22,11 +22,11 @@ class MyMemoryTranslator(BaseTranslator):
22
  """
23
  self.proxies = proxies
24
  self.email = kwargs.get('email', None)
25
- super(MyMemoryTranslator, self).__init__(base_url=BASE_URLS.get("MYMEMORY"),
26
- source=self._source,
27
- target=self._target,
28
- payload_key='q',
29
- langpair='{}|{}'.format(self._source, self._target))
30
 
31
  def translate(self, text, return_all=False, **kwargs):
32
  """
@@ -36,13 +36,12 @@ class MyMemoryTranslator(BaseTranslator):
36
  @param return_all: set to True to return all synonym/similars of the translated text
37
  @return: str or list
38
  """
39
-
40
- if self._same_source_target() or is_empty(text):
41
- return text
42
-
43
  if validate_input(text, max_chars=500):
44
  text = text.strip()
 
 
45
 
 
46
  if self.payload_key:
47
  self._url_params[self.payload_key] = text
48
  if self.email:
 
22
  """
23
  self.proxies = proxies
24
  self.email = kwargs.get('email', None)
25
+ super().__init__(base_url=BASE_URLS.get("MYMEMORY"),
26
+ source=source,
27
+ target=target,
28
+ payload_key='q',
29
+ )
30
 
31
  def translate(self, text, return_all=False, **kwargs):
32
  """
 
36
  @param return_all: set to True to return all synonym/similars of the translated text
37
  @return: str or list
38
  """
 
 
 
 
39
  if validate_input(text, max_chars=500):
40
  text = text.strip()
41
+ if self._same_source_target() or is_empty(text):
42
+ return text
43
 
44
+ self._url_params['langpair'] = '{}|{}'.format(self._source, self._target)
45
  if self.payload_key:
46
  self._url_params[self.payload_key] = text
47
  if self.email:
deep_translator/papago.py CHANGED
@@ -7,6 +7,8 @@ from .exceptions import TranslationNotFound
7
  from .base import BaseTranslator
8
  import requests
9
 
 
 
10
 
11
  class PapagoTranslator(BaseTranslator):
12
  """
@@ -38,32 +40,32 @@ class PapagoTranslator(BaseTranslator):
38
  @param text: desired text to translate
39
  @return: str: translated text
40
  """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
 
42
- payload = {
43
- "source": self._source,
44
- "target": self._target,
45
- "text": text
46
- }
47
- headers = {
48
- 'X-Naver-Client-Id': self.client_id,
49
- 'X-Naver-Client-Secret': self.secret_key,
50
- 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
51
- }
52
- response = requests.post(
53
- self._base_url, headers=headers, data=payload)
54
- if response.status_code != 200:
55
- raise Exception(
56
- f'Translation error! -> status code: {response.status_code}')
57
- res_body = json.loads(response.text)
58
- if "message" not in res_body:
59
- raise TranslationNotFound(text)
60
-
61
- msg = res_body.get("message")
62
- result = msg.get("result", None)
63
- if not result:
64
- raise TranslationNotFound(text)
65
- translated_text = result.get("translatedText")
66
- return translated_text
67
 
68
  def translate_file(self, path, **kwargs):
69
  """
 
7
  from .base import BaseTranslator
8
  import requests
9
 
10
+ from .validate import validate_input
11
+
12
 
13
  class PapagoTranslator(BaseTranslator):
14
  """
 
40
  @param text: desired text to translate
41
  @return: str: translated text
42
  """
43
+ if validate_input(text):
44
+ payload = {
45
+ "source": self._source,
46
+ "target": self._target,
47
+ "text": text
48
+ }
49
+ headers = {
50
+ 'X-Naver-Client-Id': self.client_id,
51
+ 'X-Naver-Client-Secret': self.secret_key,
52
+ 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
53
+ }
54
+ response = requests.post(
55
+ self._base_url, headers=headers, data=payload)
56
+ if response.status_code != 200:
57
+ raise Exception(
58
+ f'Translation error! -> status code: {response.status_code}')
59
+ res_body = json.loads(response.text)
60
+ if "message" not in res_body:
61
+ raise TranslationNotFound(text)
62
 
63
+ msg = res_body.get("message")
64
+ result = msg.get("result", None)
65
+ if not result:
66
+ raise TranslationNotFound(text)
67
+ translated_text = result.get("translatedText")
68
+ return translated_text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
 
70
  def translate_file(self, path, **kwargs):
71
  """
deep_translator/pons.py CHANGED
@@ -46,10 +46,9 @@ class PonsTranslator(BaseTranslator):
46
  @type return_all: bool
47
  @return: str: translated word
48
  """
49
- if self._same_source_target() or is_empty(word):
50
- return word
51
-
52
  if validate_input(word, max_chars=50):
 
 
53
  url = "{}{}-{}/{}".format(self._base_url, self._source, self._target, word)
54
  url = requote_uri(url)
55
  response = requests.get(url, proxies=self.proxies)
 
46
  @type return_all: bool
47
  @return: str: translated word
48
  """
 
 
 
49
  if validate_input(word, max_chars=50):
50
+ if self._same_source_target() or is_empty(word):
51
+ return word
52
  url = "{}{}-{}/{}".format(self._base_url, self._source, self._target, word)
53
  url = requote_uri(url)
54
  response = requests.get(url, proxies=self.proxies)
deep_translator/validate.py CHANGED
@@ -4,10 +4,10 @@ import string
4
 
5
 
6
  def is_empty(text: str):
7
- return text.strip() == ""
8
 
9
 
10
- def validate_input(text: str, min_chars: int = 1, max_chars: int = 5000):
11
  """
12
  validate the target text to translate
13
  @param min_chars: min characters
@@ -16,13 +16,8 @@ def validate_input(text: str, min_chars: int = 1, max_chars: int = 5000):
16
  @return: bool
17
  """
18
 
19
- if not isinstance(text, str) or not text.strip() or text.isdigit():
20
  raise NotValidPayload(text)
21
-
22
- # check if payload contains only symbols
23
- if all(i in string.punctuation for i in text):
24
- raise NotValidPayload(text)
25
-
26
  if not min_chars <= len(text) < max_chars:
27
  raise NotValidLength(text, min_chars, max_chars)
28
 
 
4
 
5
 
6
  def is_empty(text: str):
7
+ return text == ""
8
 
9
 
10
+ def validate_input(text: str, min_chars: int = 0, max_chars: int = 5000):
11
  """
12
  validate the target text to translate
13
  @param min_chars: min characters
 
16
  @return: bool
17
  """
18
 
19
+ if not isinstance(text, str) or text.isdigit():
20
  raise NotValidPayload(text)
 
 
 
 
 
21
  if not min_chars <= len(text) < max_chars:
22
  raise NotValidLength(text, min_chars, max_chars)
23
 
deep_translator/yandex.py CHANGED
@@ -87,31 +87,32 @@ class YandexTranslator(BaseTranslator):
87
  return language
88
 
89
  def translate(self, text, proxies=None, **kwargs):
90
- params = {
91
- "text": text,
92
- "format": "plain",
93
- "lang": self._target if self._source == "auto" else "{}-{}".format(self._source, self._target),
94
- "key": self.api_key
95
- }
96
- try:
97
- url = self._base_url.format(
98
- version=self.api_version, endpoint="translate")
99
- response = requests.post(url, data=params, proxies=proxies)
100
- except ConnectionError:
101
- raise ServerException(503)
102
- else:
103
- response = response.json()
104
-
105
- if response['code'] == 429:
106
- raise TooManyRequests()
107
-
108
- if response['code'] != 200:
109
- raise ServerException(response['code'])
110
-
111
- if not response['text']:
112
- raise TranslationNotFound()
113
-
114
- return response['text']
 
115
 
116
  def translate_file(self, path, **kwargs):
117
  """
 
87
  return language
88
 
89
  def translate(self, text, proxies=None, **kwargs):
90
+ if validate_input(text):
91
+ params = {
92
+ "text": text,
93
+ "format": "plain",
94
+ "lang": self._target if self._source == "auto" else "{}-{}".format(self._source, self._target),
95
+ "key": self.api_key
96
+ }
97
+ try:
98
+ url = self._base_url.format(
99
+ version=self.api_version, endpoint="translate")
100
+ response = requests.post(url, data=params, proxies=proxies)
101
+ except ConnectionError:
102
+ raise ServerException(503)
103
+ else:
104
+ response = response.json()
105
+
106
+ if response['code'] == 429:
107
+ raise TooManyRequests()
108
+
109
+ if response['code'] != 200:
110
+ raise ServerException(response['code'])
111
+
112
+ if not response['text']:
113
+ raise TranslationNotFound()
114
+
115
+ return response['text']
116
 
117
  def translate_file(self, path, **kwargs):
118
  """
tests/test_libre.py CHANGED
@@ -9,29 +9,24 @@ from deep_translator.constants import LIBRE_CODES_TO_LANGUAGES
9
 
10
  @pytest.fixture
11
  def libre():
12
- return LibreTranslator(source="en", target='fr')
13
-
14
-
15
- def test_content(libre):
16
- """Sample pytest test function with the pytest fixture as an argument."""
17
- assert libre.translate(text='good') is not None
18
 
19
 
20
  def test_inputs():
21
  with pytest.raises(exceptions.InvalidSourceOrTargetLanguage):
22
- LibreTranslator(source="", target="")
23
 
24
  with pytest.raises(exceptions.InvalidSourceOrTargetLanguage):
25
- LibreTranslator(source="auto", target="")
26
 
27
  with pytest.raises(exceptions.InvalidSourceOrTargetLanguage):
28
- LibreTranslator(source="", target="en")
29
 
30
 
31
  def test_abbreviations_and_languages_mapping():
32
  for abb, lang in LIBRE_CODES_TO_LANGUAGES.items():
33
- l1 = LibreTranslator(abb)
34
- l2 = LibreTranslator(lang)
35
  assert l1._source == l2._source
36
 
37
 
@@ -44,19 +39,3 @@ def test_payload(libre):
44
 
45
  with pytest.raises(exceptions.NotValidPayload):
46
  libre.translate([])
47
-
48
-
49
- def test_one_character_words():
50
- assert LibreTranslator(source='es', target='en').translate('y') == 'and'
51
-
52
-
53
- def test_translate_batch():
54
- words_to_translate = ['How are you', 'Good', 'Thank You']
55
- translated_words = ['¿Cómo estás?', 'Bien.', 'Gracias.']
56
- assert LibreTranslator(source='en', target='es').translate_batch((words_to_translate)) == translated_words
57
-
58
-
59
- def test_translate_file():
60
- filePath = 'examples/test.txt'
61
- translatedText = 'Un párrafo es una serie de frases relacionadas que desarrollan una idea central, llamada el tema. Trate de pensar en los párrafos en términos de unidad temática: un párrafo es una frase o un grupo de oraciones que apoya una idea central y unificada. Los párrafos añaden una idea a la vez a su argumento más amplio.'
62
- assert LibreTranslator(source='en', target='es').translate_file(filePath) == translatedText
 
9
 
10
  @pytest.fixture
11
  def libre():
12
+ return LibreTranslator(source="en", target='fr', api_key='some_key')
 
 
 
 
 
13
 
14
 
15
  def test_inputs():
16
  with pytest.raises(exceptions.InvalidSourceOrTargetLanguage):
17
+ LibreTranslator(source="", target="", api_key='some_key')
18
 
19
  with pytest.raises(exceptions.InvalidSourceOrTargetLanguage):
20
+ LibreTranslator(source="auto", target="", api_key='some_key')
21
 
22
  with pytest.raises(exceptions.InvalidSourceOrTargetLanguage):
23
+ LibreTranslator(source="", target="en", api_key='some_key')
24
 
25
 
26
  def test_abbreviations_and_languages_mapping():
27
  for abb, lang in LIBRE_CODES_TO_LANGUAGES.items():
28
+ l1 = LibreTranslator(abb, api_key='some_key')
29
+ l2 = LibreTranslator(lang, api_key='some_key')
30
  assert l1._source == l2._source
31
 
32
 
 
39
 
40
  with pytest.raises(exceptions.NotValidPayload):
41
  libre.translate([])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tests/test_linguee.py CHANGED
@@ -8,7 +8,7 @@ from deep_translator import exceptions, LingueeTranslator
8
 
9
  @pytest.fixture
10
  def linguee():
11
- return LingueeTranslator(source="english", target='french')
12
 
13
 
14
  def test_content(linguee):
 
8
 
9
  @pytest.fixture
10
  def linguee():
11
+ return LingueeTranslator(source="english", target='german')
12
 
13
 
14
  def test_content(linguee):
tests/test_microsoft_trans.py CHANGED
@@ -20,12 +20,12 @@ def test_microsoft_successful_post_mock(mock_request_post):
20
  r.json = json_func
21
  return r
22
  mock_request_post.return_value = res()
23
- assert MicrosoftTranslator(api_key="an_api_key", target="en").translate("auf wiedersehen!") == "See you later!"
24
 
25
 
26
  def test_MicrosoftAPIerror():
27
  with pytest.raises(exceptions.MicrosoftAPIerror):
28
- MicrosoftTranslator(api_key="empty", target="en").translate("text")
29
 
30
 
31
  # the remaining tests are actual requests to Microsoft API and use an api key
 
20
  r.json = json_func
21
  return r
22
  mock_request_post.return_value = res()
23
+ assert MicrosoftTranslator(api_key="an_api_key", source='de', target="en").translate("auf wiedersehen!") == "See you later!"
24
 
25
 
26
  def test_MicrosoftAPIerror():
27
  with pytest.raises(exceptions.MicrosoftAPIerror):
28
+ MicrosoftTranslator(api_key="empty", source='de', target="en").translate("text")
29
 
30
 
31
  # the remaining tests are actual requests to Microsoft API and use an api key
tests/test_mymemory.py CHANGED
@@ -36,9 +36,6 @@ def test_inputs():
36
 
37
  def test_payload(mymemory):
38
 
39
- with pytest.raises(exceptions.NotValidPayload):
40
- mymemory.translate(text="")
41
-
42
  with pytest.raises(exceptions.NotValidPayload):
43
  mymemory.translate(text=123)
44
 
 
36
 
37
  def test_payload(mymemory):
38
 
 
 
 
39
  with pytest.raises(exceptions.NotValidPayload):
40
  mymemory.translate(text=123)
41