1. Monwara LLC
  2. Untitled project
  3. PyMSTranslator

Commits

Branko Vukelic  committed 6b71403

Added base endpoint class

  • Participants
  • Parent commits 06d1116
  • Branches master

Comments (0)

Files changed (3)

File mstranslator/endpoints/__init__.py

Empty file added.

File mstranslator/endpoints/base.py

View file
+"""Base classes for endpoint processing"""
+
+from urllib import urlencode
+
+class Endpoint(object):
+    endpoint = None
+    api_protocol = 'http'
+    api_host = 'api.microsofttranslator.com'
+    api_version = 'v2'
+    api_endpoint_base = 'Http.svc'
+    params = {}
+    data = None
+
+    def get_endpoint_url(self):
+        if not self.endpoint:
+            raise NotImplementedError('You must set endpoint attribute')
+
+        return '%s://%s/%s/%s/%s' % (
+            self.api_protocol,
+            self.api_host,
+            self.api_version,
+            self.api_endpoint_base,
+            self.endpoint
+        )
+
+    def get_quoted_params(self):
+        return urlencode(self.params)
+
+    def get_request_url(self):
+        return '%s?%s' % (self.get_endpoint_url(), self.get_quoted_params())
+
+    def store_data(self):
+        raise NotImplementedError('Please override this method in subclass')
+
+    def get_data(self):
+        return self.data
+
+    def process_response(self, response):
+        raise NotImplementedError('Please override this method in subclass')

File tests/test_base_endpoints.py

View file
+from unittest import TestCase
+
+from mstranslator.endpoints.base import Endpoint
+
+
+class BaseEndpoint(TestCase):
+    def setUp(self):
+        self.t = Endpoint()
+
+    def test_get_url(self):
+        self.t.endpoint = 'Foo'
+        self.assertEqual(
+            self.t.get_endpoint_url(),
+            'http://api.microsofttranslator.com/v2/Http.svc/Foo'
+        )
+
+    def test_get_quoted_params(self):
+        self.t.params = {'foo': 'bar', 'bar': 1}
+        self.assertEqual(
+            self.t.get_quoted_params(),
+            'foo=bar&bar=1'
+        )
+
+    def test_get_full_url(self):
+        self.t.endpoint = 'Translate'
+        self.t.params = {'text': 'foo'}
+        self.assertEqual(
+            self.t.get_request_url(),
+            'http://api.microsofttranslator.com/v2/Http.svc/Translate?text=foo'
+        )