Ejemplo n.º 1
0
 def gengo_authentication(self, cr, uid, context=None):
     '''
     This method tries to open a connection with Gengo. For that, it uses the Public and Private
     keys that are linked to the company (given by Gengo on subscription). It returns a tuple with
      * as first element: a boolean depicting if the authentication was a success or not
      * as second element: the connection, if it was a success, or the error message returned by
         Gengo when the connection failed.
         This error message can either be displayed in the server logs (if the authentication was called
         by the cron) or in a dialog box (if requested by the user), thus it's important to return it
         translated.
     '''
     user = self.pool.get('res.users').browse(cr, 1, uid, context=context)
     if not user.company_id.gengo_public_key or not user.company_id.gengo_private_key:
         return (False, _("Gengo `Public Key` or `Private Key` are missing. Enter your Gengo authentication parameters under `Settings > Companies > Gengo Parameters`."))
     try:
         gengo = Gengo(
             public_key=user.company_id.gengo_public_key.encode('ascii'),
             private_key=user.company_id.gengo_private_key.encode('ascii'),
             sandbox=user.company_id.gengo_sandbox,
         )
         gengo.getAccountStats()
         return (True, gengo)
     except Exception, e:
         _logger.exception('Gengo connection failed')
         return (False, _("Gengo connection failed with this message:\n``%s``") % e)
Ejemplo n.º 2
0
class TestAccountMethods(unittest.TestCase):

    """
    Tests the methods that deal with retrieving basic information about
    the account you're authenticating as. Checks for one property on
    each method.
    """
    def setUp(self):
        self.gengo = Gengo(public_key=API_PUBKEY,
                           private_key=API_PRIVKEY,
                           sandbox=True)

        from gengo import requests
        self.json_mock = mock.Mock()
        self.json_mock.json.return_value = {'opstat': 'ok'}
        self.getMock = RequestsMock(return_value=self.json_mock)
        self.requestsPatch = mock.patch.object(requests, 'get', self.getMock)
        self.requestsPatch.start()

    def tearDown(self):
        self.requestsPatch.stop()

    def test_getAccountStats(self):
        stats = self.gengo.getAccountStats()
        self.assertEqual(stats['opstat'], 'ok')
        self.getMock.assert_path_contains(
            mockdb.apihash['getAccountStats']['url'])

    def test_getAccountBalance(self):
        balance = self.gengo.getAccountBalance()
        self.assertEqual(balance['opstat'], 'ok')
        self.getMock.assert_path_contains(
            mockdb.apihash['getAccountBalance']['url'])
Ejemplo n.º 3
0
class TestLanguageServiceMethods(unittest.TestCase):

    """
    Tests the methods that deal with getting information about language-
    translation service support from Gengo.
    """

    def setUp(self):
        self.gengo = Gengo(public_key=API_PUBKEY, private_key=API_PRIVKEY, sandbox=True)

        from gengo import requests

        self.json_mock = mock.Mock()
        self.json_mock.json.return_value = {"opstat": "ok"}
        self.getMock = RequestsMock(return_value=self.json_mock)
        self.requestsPatch = mock.patch.object(requests, "get", self.getMock)
        self.requestsPatch.start()

    def tearDown(self):
        self.requestsPatch.stop()

    def test_getServiceLanguagePairs(self):
        resp = self.gengo.getServiceLanguagePairs()
        self.assertEqual(resp["opstat"], "ok")
        self.getMock.assert_path_contains(mockdb.apihash["getServiceLanguagePairs"]["url"])

    def test_getServiceLanguages(self):
        resp = self.gengo.getServiceLanguages()
        self.assertEqual(resp["opstat"], "ok")
        self.getMock.assert_path_contains(mockdb.apihash["getServiceLanguages"]["url"])

    def test_getServiceLanguageMatrix(self):
        resp = self.gengo.getServiceLanguageMatrix()
        self.assertEqual(resp["opstat"], "ok")
        self.getMock.assert_path_contains(mockdb.apihash["getServiceLanguageMatrix"]["url"])
Ejemplo n.º 4
0
	def post(self, request, *args, **kwargs):
		gengo = Gengo(
			public_key=settings.GENGO_PUBLIC_KEY,
			private_key=settings.GENGO_PRIVATE_KEY,
			sandbox=settings.GENGO_SANDBOX,
			debug=settings.GENGO_DEBUG)

		app_id = request.DATA.get('app')
		lang_code = request.DATA.get('lang', '')
		tier = request.DATA.get('tier', 'standard')
		comment = request.DATA.get('comment', '')

		app = App.objects.filter(pk=app_id).first()
		if not app:
			return Response({'errors': 'app_id is not valid.'}, status=status.HTTP_400_BAD_REQUEST)

		if lang_code and lang_code not in [lang[0] for lang in LANG_CHOICES]:
			return Response({'errors': 'lang code is not valid.'}, status=status.HTTP_400_BAD_REQUEST)
		lang_code = lang_code.lower()
		if lang_code in not_supported:
			return Response({'errors': 'Not Supported Language.'}, status=status.HTTP_400_BAD_REQUEST)

		if lang_code in variation:
			lang_code = variation[lang_code]

		if tier not in ['standard', 'pro']:
			return Response({'errors': 'tier is not valid.'}, status=status.HTTP_400_BAD_REQUEST)

		words = Word.objects.filter(app=app).all()

		jobs = {}
		for i in range(len(words)):
			k = 'job_%s' % (i + 1)
			word = words[i]
			cb = settings.DOMAIN + reverse('gengo-callback', kwargs=dict(app_id=app.id, word_id=word.id,
			                                                             lang_code=request.DATA.get('lang', '')))

			job = {
				'type': 'text',
				'slug': slugify(word.name),
				'body_src': word.name,
				'lc_src': 'en',
				'lc_tgt': lang_code,
				'tier': tier,
				'auto_approve': 1,
				'comment': '',
				'attachments': [],
				'callback_url': cb,
				'custom_data': '',
				'force': 0,
				'use_preferred': 0
			}
			jobs[k] = job

		jobs['comment'] = comment
		res = gengo.postTranslationJobs(jobs=jobs)

		return Response(data=res)
Ejemplo n.º 5
0
class TestResponseHandling(unittest.TestCase):
    def setUp(self):
        self.gengo = Gengo(public_key=API_PUBKEY, private_key=API_PRIVKEY)
        self.response = mock.Mock()

    def test_handleResponse(self):
        expect = {
            'opstat': 'ok',
        }
        self.response.json.return_value = expect
        self.assertEqual(expect, self.gengo._handleResponse(self.response))

    def test_raiseForErrorResponse(self):
        self.response.json.return_value = {
            'opstat': 'error',
            'err': {
                'msg': 'Not Found',
                'code': 404,
            }
        }

        self.assertRaises(
            gengo.GengoError,
            lambda: self.gengo._handleResponse(self.response)
        )

    def test_raiseForMultipleErrorResponse(self):
        self.response.json.return_value = {
            'opstat': 'error',
            'err': {
                'job_1': [
                    {
                        'code': 1350,
                        'msg': '"body_src" is a required field'
                    },
                    {
                        'code': 1400,
                        'msg': '"lc_src" is a required field'
                    },
                    {
                        'code': 1450,
                        'msg': '"lc_tgt" is a required field'
                    },
                    {
                        'code': 1500,
                        'msg': '"tier" is a required field'
                    }
                ]
            }
        }

        self.assertRaises(
            gengo.GengoError,
            lambda: self.gengo._handleResponse(self.response)
        )
Ejemplo n.º 6
0
class TestGlossaryFunctions(unittest.TestCase):

    """
    """

    def setUp(self):
        """
        Creates the initial batch of jobs for the other test functions here
        to operate on.
        """
        self.gengo = Gengo(public_key=API_PUBKEY, private_key=API_PRIVKEY, sandbox=True)

        from gengo import requests

        self.json_mock = mock.Mock()
        self.json_mock.json.return_value = {"opstat": "ok"}
        self.getMock = RequestsMock(return_value=self.json_mock)
        self.requestsPatch = mock.patch.object(requests, "get", self.getMock)
        self.requestsPatch.start()

    def tearDown(self):
        self.requestsPatch.stop()

    def test_getGlossaryList(self):
        resp = self.gengo.getGlossaryList()
        self.assertEqual(resp["opstat"], "ok")
        self.getMock.assert_path_contains(mockdb.apihash["getGlossaryList"]["url"])
Ejemplo n.º 7
0
class TestPreferredTranslatorsFunction(unittest.TestCase):

    """
    """
    def setUp(self):
        """
        Creates the initial batch of jobs for the other test functions here
        to operate on.
        """
        self.gengo = Gengo(public_key=API_PUBKEY,
                           private_key=API_PRIVKEY,
                           sandbox=True,
                           )

        from gengo import requests
        self.json_mock = mock.Mock()
        self.json_mock.json.return_value = {'opstat': 'ok'}
        self.getMock = RequestsMock(return_value=self.json_mock)
        self.requestsPatch = mock.patch.object(requests, 'get', self.getMock)
        self.requestsPatch.start()

    def tearDown(self):
        self.requestsPatch.stop()

    def test_getPreferredTranslators(self):
        resp = self.gengo.getPreferredTranslators()
        self.assertEqual(resp['opstat'], 'ok')
        # self.getMock.assert_any_call()
        self.getMock.assert_path_contains(
            mockdb.apihash['getPreferredTranslators']['url'])
Ejemplo n.º 8
0
    def setUp(self):
        """
        Creates the initial batch of jobs for the other test functions here
        to operate on.
        """
        self.gengo = Gengo(public_key=API_PUBKEY,
                           private_key=API_PRIVKEY,
                           sandbox=True)
        self.created_job_ids = []

        multiple_jobs_quote = {
            'job_1': {
                'type': 'file',
                'file_path': './examples/testfiles/test_file1.txt',
                'lc_src': 'en',
                'lc_tgt': 'ja',
                'tier': 'standard',
            },
            'job_2': {
                'type': 'file',
                'file_path': './examples/testfiles/test_file2.txt',
                'lc_src': 'ja',
                'lc_tgt': 'en',
                'tier': 'standard',
            },
        }

        # Now that we've got the jobs, let's go ahead and see how much it'll
        # cost.
        cost_assessment = self.gengo.determineTranslationCost(
            jobs=multiple_jobs_quote)
        self.assertEqual(cost_assessment['opstat'], 'ok')

        self.multiple_jobs = {}
        for k, j in cost_assessment['response']['jobs'].iteritems():
            self.multiple_jobs[k] = {
                'type': 'file',
                'identifier': j['identifier'],
                'comment': 'Test comment for %s' % (k,),
                'glossary_id': None,
                'use_preferred': 1,
                'force': 1,
            }

        jobs = self.gengo.postTranslationJobs(
            jobs={'jobs': self.multiple_jobs, 'as_group': 0})
        self.assertEqual(jobs['opstat'], 'ok')
        self.assertTrue('order_id' in jobs['response'])
        self.assertTrue('credits_used' in jobs['response'])
        self.assertEqual(jobs['response']['job_count'], 2)

        # get some order information - in v2 the jobs need to have gone
        # through a queueing system so we wait a little bit
        time.sleep(20)
        resp = self.gengo.getTranslationOrderJobs(
            id=jobs['response']['order_id'])
        self.assertEqual(resp['response']['order']['as_group'], 0)
        self.assertEqual(len(resp['response']['order']['jobs_available']), 2)
        self.created_job_ids.\
            extend(resp['response']['order']['jobs_available'])
Ejemplo n.º 9
0
class TestPostTranslationJobComment(unittest.TestCase):

    """
    Tests the flow of creating a job, updating one of them, getting the
    details, and then deleting the jobs.
    """

    def setUp(self):
        """
        Creates the initial batch of jobs for the other test functions here
        to operate on.
        """
        self.gengo = Gengo(public_key=API_PUBKEY, private_key=API_PRIVKEY, sandbox=True)

        from gengo import requests

        self.json_mock = mock.Mock()
        self.json_mock.json.return_value = {"opstat": "ok"}
        self.getMock = RequestsMock(return_value=self.json_mock)
        self.requestsPatch = mock.patch.object(requests, "post", self.getMock)
        self.requestsPatch.start()

    def tearDown(self):
        self.requestsPatch.stop()

    def test_postJobComment(self):
        """
        Tests posting a comment to a job.
        """
        posted_comment = self.gengo.postTranslationJobComment(id=123, comment={"body": "I love lamp oh mai gawd"})
        self.assertEqual(posted_comment["opstat"], "ok")
        self.getMock.assert_path_contains(mockdb.apihash["postTranslationJobComment"]["url"].replace("{{id}}", "123"))
Ejemplo n.º 10
0
class TestPostTranslationJobComment(unittest.TestCase):

    """
    Tests the flow of creating a job, updating one of them, getting the
    details, and then deleting the jobs.
    """
    def setUp(self):
        """
        Creates the initial batch of jobs for the other test functions here
        to operate on.
        """
        self.gengo = Gengo(public_key=API_PUBKEY,
                           private_key=API_PRIVKEY,
                           sandbox=True)

        self.json_mock = mock.Mock()
        self.json_mock.json.return_value = {'opstat': 'ok'}
        self.getMock = RequestsMock(return_value=self.json_mock)
        self.requestsPatch = mock.patch.object(requests, 'post', self.getMock)
        self.requestsPatch.start()

    def tearDown(self):
        self.requestsPatch.stop()

    def test_postJobComment(self):
        """
        Tests posting a comment to a job.
        """
        posted_comment = self.gengo.postTranslationJobComment(
            id=123,
            comment={'body': 'I love lamp oh mai gawd'})
        self.assertEqual(posted_comment['opstat'], 'ok')
        self.getMock.assert_path_contains(
            gengo.mockdb.apihash['postTranslationJobComment']['url']
            .replace('{{id}}', '123'))
Ejemplo n.º 11
0
class TestGlossaryFunctions(unittest.TestCase):

    """
    """
    def setUp(self):
        """
        Creates the initial batch of jobs for the other test functions here
        to operate on.
        """
        self.gengo = Gengo(public_key=API_PUBKEY,
                           private_key=API_PRIVKEY,
                           sandbox=True)

        self.json_mock = mock.Mock()
        self.json_mock.json.return_value = {'opstat': 'ok'}
        self.getMock = RequestsMock(return_value=self.json_mock)
        self.requestsPatch = mock.patch.object(requests, 'get', self.getMock)
        self.requestsPatch.start()

    def tearDown(self):
        self.requestsPatch.stop()

    def test_getGlossaryList(self):
        resp = self.gengo.getGlossaryList()
        self.assertEqual(resp['opstat'], 'ok')
        self.getMock.assert_path_contains(
            gengo.mockdb.apihash['getGlossaryList']['url'])
Ejemplo n.º 12
0
class TestAccountMethods(unittest.TestCase):
    """
    Tests the methods that deal with retrieving basic information about
    the account you're authenticating as. Checks for one property on
    each method.
    """
    def setUp(self):
        self.gengo = Gengo(public_key=API_PUBKEY, private_key=API_PRIVKEY)
        self.gengo.api_url = 'http://api.staging.gengo.com/%(version)s'

    def test_getAccountStats(self):
        stats = self.gengo.getAccountStats()
        self.assertEqual(stats['opstat'], 'ok')

    def test_getAccountBalance(self):
        balance = self.gengo.getAccountBalance()
        self.assertEqual(balance['opstat'], 'ok')
Ejemplo n.º 13
0
class TestLanguageServiceMethods(unittest.TestCase):
    """
    Tests the methods that deal with getting information about language-
    translation service support from Gengo.
    """
    def setUp(self):
        self.gengo = Gengo(public_key=API_PUBKEY,
                           private_key=API_PRIVKEY,
                           sandbox=True)

    def test_getServiceLanguagePairs(self):
        resp = self.gengo.getServiceLanguagePairs()
        self.assertEqual(resp['opstat'], 'ok')

    def test_getServiceLanguages(self):
        resp = self.gengo.getServiceLanguages()
        self.assertEqual(resp['opstat'], 'ok')
Ejemplo n.º 14
0
    def setUp(self):
        """
        Creates the initial batch of jobs for the other test functions here
        to operate on.
        """
        # First we'll create three jobs - one regular, and two at the same
        # time...
        self.gengo = Gengo(public_key=API_PUBKEY,
                           private_key=API_PRIVKEY,
                           sandbox=True)

        from gengo import requests
        self.json_mock = mock.Mock()
        self.json_mock.json.return_value = {'opstat': 'ok'}
        self.getMock = RequestsMock(return_value=self.json_mock)
        self.requestsPatch = mock.patch.object(requests, 'get', self.getMock)
        self.requestsPatch.start()
Ejemplo n.º 15
0
 def setUp(self):
     """
     Creates the initial batch of jobs for the other test functions here
     to operate on.
     """
     self.gengo = Gengo(public_key=API_PUBKEY,
                        private_key=API_PRIVKEY,
                        sandbox=True)
Ejemplo n.º 16
0
class TestLanguageServiceMethods(unittest.TestCase):
    """
    Tests the methods that deal with getting information about language-
    translation service support from Gengo.
    """
    def setUp(self):
        self.gengo = Gengo(public_key=API_PUBKEY,
                           private_key=API_PRIVKEY,
                           sandbox=True)

    def test_getServiceLanguagePairs(self):
        resp = self.gengo.getServiceLanguagePairs()
        self.assertEqual(resp['opstat'], 'ok')

    def test_getServiceLanguages(self):
        resp = self.gengo.getServiceLanguages()
        self.assertEqual(resp['opstat'], 'ok')
Ejemplo n.º 17
0
class TestAccountMethods(unittest.TestCase):
    """
    Tests the methods that deal with retrieving basic information about
    the account you're authenticating as. Checks for one property on
    each method.
    """
    def setUp(self):
        self.gengo = Gengo(public_key=API_PUBKEY,
                           private_key=API_PRIVKEY,
                           sandbox=True)

    def test_getAccountStats(self):
        stats = self.gengo.getAccountStats()
        self.assertEqual(stats['opstat'], 'ok')

    def test_getAccountBalance(self):
        balance = self.gengo.getAccountBalance()
        self.assertEqual(balance['opstat'], 'ok')
Ejemplo n.º 18
0
    def setUp(self):
        self.gengo = Gengo(public_key=API_PUBKEY,
                           private_key=API_PRIVKEY,
                           sandbox=True)

        self.json_mock = mock.Mock()
        self.json_mock.json.return_value = {'opstat': 'ok'}
        self.getMock = RequestsMock(return_value=self.json_mock)
        self.requestsPatch = mock.patch.object(requests, 'get', self.getMock)
        self.requestsPatch.start()
Ejemplo n.º 19
0
    def setUp(self):
        self.gengo = Gengo(public_key=API_PUBKEY, private_key=API_PRIVKEY, sandbox=True)

        from gengo import requests

        self.json_mock = mock.Mock()
        self.json_mock.json.return_value = {"opstat": "ok"}
        self.getMock = RequestsMock(return_value=self.json_mock)
        self.requestsPatch = mock.patch.object(requests, "get", self.getMock)
        self.requestsPatch.start()
Ejemplo n.º 20
0
 def setUp(self):
     """
     Creates the initial batch of jobs for the other test functions here
     to operate on.
     """
     # First we'll create three jobs - one regular, and two at the same
     # time...
     self.gengo = Gengo(public_key=API_PUBKEY,
                        private_key=API_PRIVKEY)
     self.gengo.api_url = 'http://api.staging.gengo.com/%(version)s'
Ejemplo n.º 21
0
 def setUp(self):
     """
     Creates the initial batch of jobs for the other test functions here
     to operate on.
     """
     # First we'll create three jobs - one regular, and two at the same
     # time...
     self.gengo = Gengo(public_key=API_PUBKEY,
                        private_key=API_PRIVKEY,
                        sandbox=True)
Ejemplo n.º 22
0
    def setUp(self):
        """
        Creates the initial batch of jobs for the other test functions here
        to operate on.
        """
        """
        Creates the initial batch of jobs for the other test functions here
        to operate on.
        """
        self.gengo = Gengo(public_key=API_PUBKEY,
                           private_key=API_PRIVKEY,
                           sandbox=True)
        self.created_job_ids = []

        self.json_mock = mock.Mock()
        self.json_mock.json.return_value = {'opstat': 'ok'}
        self.getMock = RequestsMock(return_value=self.json_mock)
        self.requestsPatch = mock.patch.object(requests, 'get', self.getMock)
        self.requestsPatch.start()
Ejemplo n.º 23
0
class TestLanguageServiceMethods(unittest.TestCase):

    """
    Tests the methods that deal with getting information about language-
    translation service support from Gengo.
    """
    def setUp(self):
        self.gengo = Gengo(public_key=API_PUBKEY,
                           private_key=API_PRIVKEY,
                           sandbox=True)

        from gengo import requests
        self.json_mock = mock.Mock()
        self.json_mock.json.return_value = {'opstat': 'ok'}
        self.getMock = RequestsMock(return_value=self.json_mock)
        self.requestsPatch = mock.patch.object(requests, 'get', self.getMock)
        self.requestsPatch.start()

    def tearDown(self):
        self.requestsPatch.stop()

    def test_getServiceLanguagePairs(self):
        resp = self.gengo.getServiceLanguagePairs()
        self.assertEqual(resp['opstat'], 'ok')
        self.getMock.assert_path_contains(
            mockdb.apihash['getServiceLanguagePairs']['url'])

    def test_getServiceLanguages(self):
        resp = self.gengo.getServiceLanguages()
        self.assertEqual(resp['opstat'], 'ok')
        self.getMock.assert_path_contains(
            mockdb.apihash['getServiceLanguages']['url'])

    def test_getServiceLanguageMatrix(self):
        resp = self.gengo.getServiceLanguageMatrix()
        self.assertEqual(resp['opstat'], 'ok')
        self.getMock.assert_path_contains(
            mockdb.apihash['getServiceLanguageMatrix']['url'])
Ejemplo n.º 24
0
    def setUp(self):
        """
        Creates the initial batch of jobs for the other test functions here
        to operate on.
        """
        self.gengo = Gengo(public_key=API_PUBKEY,
                           private_key=API_PRIVKEY,
                           sandbox=True)

        self.json_mock = mock.Mock()
        self.json_mock.json.return_value = {'opstat': 'ok'}
        self.getMock = RequestsMock(return_value=self.json_mock)
        self.requestsPatch = mock.patch.object(requests, 'get', self.getMock)
        self.requestsPatch.start()
Ejemplo n.º 25
0
class TestLanguageServiceMethods(unittest.TestCase):

    """
    Tests the methods that deal with getting information about language-
    translation service support from Gengo.
    """
    def setUp(self):
        self.gengo = Gengo(public_key=API_PUBKEY,
                           private_key=API_PRIVKEY,
                           sandbox=True)

        self.json_mock = mock.Mock()
        self.json_mock.json.return_value = {'opstat': 'ok'}
        self.getMock = RequestsMock(return_value=self.json_mock)
        self.requestsPatch = mock.patch.object(requests, 'get', self.getMock)
        self.requestsPatch.start()

    def tearDown(self):
        self.requestsPatch.stop()

    def test_getServiceLanguagePairs(self):
        resp = self.gengo.getServiceLanguagePairs()
        self.assertEqual(resp['opstat'], 'ok')
        self.getMock.assert_path_contains(
            gengo.mockdb.apihash['getServiceLanguagePairs']['url'])

    def test_getServiceLanguages(self):
        resp = self.gengo.getServiceLanguages()
        self.assertEqual(resp['opstat'], 'ok')
        self.getMock.assert_path_contains(
            gengo.mockdb.apihash['getServiceLanguages']['url'])

    def test_getServiceLanguageMatrix(self):
        resp = self.gengo.getServiceLanguageMatrix()
        self.assertEqual(resp['opstat'], 'ok')
        self.getMock.assert_path_contains(
            gengo.mockdb.apihash['getServiceLanguageMatrix']['url'])
Ejemplo n.º 26
0
class TestGlossaryFunctions(unittest.TestCase):
    """
    """
    def setUp(self):
        """
        Creates the initial batch of jobs for the other test functions here
        to operate on.
        """
        self.gengo = Gengo(public_key=API_PUBKEY,
                           private_key=API_PRIVKEY,
                           sandbox=True)

    def test_getGlossaryList(self):
        resp = self.gengo.getGlossaryList()
        self.assertEqual(resp['opstat'], 'ok')
Ejemplo n.º 27
0
class TestGlossaryFunctions(unittest.TestCase):
    """
    """
    def setUp(self):
        """
        Creates the initial batch of jobs for the other test functions here
        to operate on.
        """
        # First we'll create three jobs - one regular, and two at the same
        # time...
        self.gengo = Gengo(public_key=API_PUBKEY,
                           private_key=API_PRIVKEY)
        self.gengo.api_url = 'http://api.staging.gengo.com/%(version)s'

    def test_getGlossaryList(self):
        resp = self.gengo.getGlossaryList()
        self.assertEqual(resp['opstat'], 'ok')

    @unittest.skip("unless you created a glossary on the site (not yet " +
                   "supported via the API) this test does not make a " +
                   " lot of sense.")
    def test_getGlossary(self):
        resp = self.gengo.getGlossary(id=42)
        resp
Ejemplo n.º 28
0
class TestGlossaryFunctions(unittest.TestCase):
    """
    """
    def setUp(self):
        """
        Creates the initial batch of jobs for the other test functions here
        to operate on.
        """
        # First we'll create three jobs - one regular, and two at the same
        # time...
        self.gengo = Gengo(public_key=API_PUBKEY, private_key=API_PRIVKEY)
        self.gengo.api_url = 'http://api.staging.gengo.com/%(version)s'

    def test_getGlossaryList(self):
        resp = self.gengo.getGlossaryList()
        self.assertEqual(resp['opstat'], 'ok')
Ejemplo n.º 29
0
class TestGlossaryFunctions(unittest.TestCase):

    """
    """
    def setUp(self):
        """
        Creates the initial batch of jobs for the other test functions here
        to operate on.
        """
        self.gengo = Gengo(public_key=API_PUBKEY,
                           private_key=API_PRIVKEY,
                           sandbox=True)

    def test_getGlossaryList(self):
        resp = self.gengo.getGlossaryList()
        self.assertEqual(resp['opstat'], 'ok')
Ejemplo n.º 30
0
    def setUp(self):
        """
        Creates the initial batch of jobs for the other test functions here
        to operate on.
        """
        # First we'll create three jobs - one regular, and two at the same
        # time...
        self.gengo = Gengo(public_key=API_PUBKEY, private_key=API_PRIVKEY, sandbox=True)

        from gengo import requests

        self.json_mock = mock.Mock()
        self.json_mock.json.return_value = {"opstat": "ok"}
        self.getMock = RequestsMock(return_value=self.json_mock)
        self.requestsPatch = mock.patch.object(requests, "get", self.getMock)
        self.requestsPatch.start()
Ejemplo n.º 31
0
    def setUp(self):
        """
        Creates the initial batch of jobs for the other test functions here
        to operate on.
        """
        """
        Creates the initial batch of jobs for the other test functions here
        to operate on.
        """
        self.gengo = Gengo(public_key=API_PUBKEY,
                           private_key=API_PRIVKEY,
                           sandbox=True)
        self.created_job_ids = []

        multiple_jobs_quote = {
            'job_3': {
                'type': 'text',
                'body_src': 'This is a group job test job 1.',
                'lc_src': 'en',
                'lc_tgt': 'zh',
                'tier': 'standard',
            },
            'job_4': {
                'type': 'text',
                'body_src': 'This is a group job test job 2.',
                'lc_src': 'en',
                'lc_tgt': 'zh',
                'tier': 'standard',
            },
        }

        # Now that we've got the jobs, let's go ahead and see how much it'll
        # cost.
        self.jobs = jobs = self.gengo.postTranslationJobs(
            jobs={'jobs': multiple_jobs_quote, 'as_group': 1})

        self.assertEqual(jobs['opstat'], 'ok')
        self.assertTrue('order_id' in jobs['response'])
        self.assertTrue('credits_used' in jobs['response'])
        self.assertEqual(jobs['response']['job_count'], 2)

        time.sleep(20)
        resp = self.gengo.getTranslationOrderJobs(
            id=self.jobs['response']['order_id'])

        self.created_job_ids.\
            extend(resp['response']['order']['jobs_available'])
Ejemplo n.º 32
0
class TestGlossaryFunctions(unittest.TestCase):
    """
    """
    def setUp(self):
        """
        Creates the initial batch of jobs for the other test functions here
        to operate on.
        """
        # First we'll create three jobs - one regular, and two at the same
        # time...
        self.gengo = Gengo(public_key=API_PUBKEY,
                           private_key=API_PRIVKEY)
        self.gengo.api_url = 'http://api.staging.gengo.com/%(version)s'

    def test_getGlossaryList(self):
        resp = self.gengo.getGlossaryList()
        self.assertEqual(resp['opstat'], 'ok')
Ejemplo n.º 33
0
    def __init__(self):
        """Constructs a FjordGengo wrapper around the Gengo class

        We do this to make using the API a little easier in the
        context for Fjord as it includes the business logic around
        specific use cases we have.

        Also, having all the Gengo API stuff in one place makes it
        easier for mocking when testing.

        """
        if settings.GENGO_PUBLIC_KEY and settings.GENGO_PRIVATE_KEY:
            gengo_api = Gengo(public_key=settings.GENGO_PUBLIC_KEY,
                              private_key=settings.GENGO_PRIVATE_KEY)
        else:
            gengo_api = None

        self.gengo_api = gengo_api
Ejemplo n.º 34
0
    def setUp(self):
        """
        Creates the initial batch of jobs for the other test functions here
        to operate on.
        """
        """
        Creates the initial batch of jobs for the other test functions here
        to operate on.
        """
        self.gengo = Gengo(public_key=API_PUBKEY, private_key=API_PRIVKEY, sandbox=True)
        self.created_job_ids = []

        from gengo import requests

        self.json_mock = mock.Mock()
        self.json_mock.json.return_value = {"opstat": "ok"}
        self.getMock = RequestsMock(return_value=self.json_mock)
        self.requestsPatch = mock.patch.object(requests, "get", self.getMock)
        self.requestsPatch.start()
Ejemplo n.º 35
0
class TestPostTranslationJobCommentWithAttachments(unittest.TestCase):

    """
    Tests the flow of creating a job, updating one of them, getting the
    details, and then deleting the jobs.
    """
    def setUp(self):
        """
        Creates the initial batch of jobs for the other test functions here
        to operate on.
        """
        self.gengo = Gengo(public_key=API_PUBKEY,
                           private_key=API_PRIVKEY,
                           sandbox=True)

        self.json_mock = mock.Mock()
        self.json_mock.json.return_value = {'opstat': 'ok'}
        self.getMock = RequestsMock(return_value=self.json_mock)
        self.requestsPatch = mock.patch.object(requests, 'post', self.getMock)
        self.requestsPatch.start()

    def tearDown(self):
        self.requestsPatch.stop()

    def test_postJobCommentWithAttachments(self):
        """
        Tests posting a comment with attachments to a job.
        """
        posted_comment = self.gengo.postTranslationJobComment(
            id=123,
            comment={
                'body': 'I love lamp oh mai gawd'
            },
            file_attachments=[
                './examples/testfiles/test_file1.txt',
                './examples/testfiles/test_file2.txt'
            ]
        )
        self.assertEqual(posted_comment['opstat'], 'ok')
        self.getMock.assert_path_contains(
            gengo.mockdb.apihash['postTranslationJobComment']['url']
            .replace('{{id}}', '123'))
Ejemplo n.º 36
0
class TestTranslationJobFlowGroupJob(unittest.TestCase):

    """
    Tests the flow of creating a job, updating one of them, getting the
    details, and then deleting the jobs.
    """
    def setUp(self):
        """
        Creates the initial batch of jobs for the other test functions here
        to operate on.
        """
        """
        Creates the initial batch of jobs for the other test functions here
        to operate on.
        """
        self.gengo = Gengo(public_key=API_PUBKEY,
                           private_key=API_PRIVKEY,
                           sandbox=True)
        self.created_job_ids = []

        from gengo import requests
        self.json_mock = mock.Mock()
        self.json_mock.json.return_value = {'opstat': 'ok'}
        self.getMock = RequestsMock(return_value=self.json_mock)
        self.requestsPatch = mock.patch.object(requests, 'get', self.getMock)
        self.requestsPatch.start()

    def tearDown(self):
        self.requestsPatch.stop()

    def test_postTranslationJobs_as_group(self):
        """
        Make sure that the as_group setting gets interpreted by the API
        correctly.
        """
        resp = self.gengo.getTranslationOrderJobs(id=321)
        self.assertEqual(resp['opstat'], 'ok')
        self.getMock.assert_path_contains(
            mockdb.apihash['getTranslationOrderJobs']['url']
            .replace('{{id}}', '321'))
Ejemplo n.º 37
0
class TestTranslationJobFlowGroupJob(unittest.TestCase):

    """
    Tests the flow of creating a job, updating one of them, getting the
    details, and then deleting the jobs.
    """
    def setUp(self):
        """
        Creates the initial batch of jobs for the other test functions here
        to operate on.
        """
        """
        Creates the initial batch of jobs for the other test functions here
        to operate on.
        """
        self.gengo = Gengo(public_key=API_PUBKEY,
                           private_key=API_PRIVKEY,
                           sandbox=True)
        self.created_job_ids = []

        from gengo import requests
        self.json_mock = mock.Mock()
        self.json_mock.json.return_value = {'opstat': 'ok'}
        self.getMock = RequestsMock(return_value=self.json_mock)
        self.requestsPatch = mock.patch.object(requests, 'get', self.getMock)
        self.requestsPatch.start()

    def tearDown(self):
        self.requestsPatch.stop()

    def test_postTranslationJobs_as_group(self):
        """
        Make sure that the as_group setting gets interpreted by the API
        correctly.
        """
        resp = self.gengo.getTranslationOrderJobs(id=321)
        self.assertEqual(resp['opstat'], 'ok')
        self.getMock.assert_path_contains(
            mockdb.apihash['getTranslationOrderJobs']['url']
            .replace('{{id}}', '321'))
Ejemplo n.º 38
0
    def setUp(self):
        self.gengo = Gengo(public_key=API_PUBKEY,
                           private_key=API_PRIVKEY,
                           sandbox=True)
        self.created_job_ids = []

        single_job = {
            'type': 'text',
            'slug': 'Single :: English to Japanese',
            'body_src': 'Test%ding Ge%dngo A%dPI li%dbrary calls.' %
                    (int(random.randrange(1, 226, 1)),
                     int(random.randrange(1, 226, 1)),
                     int(random.randrange(1, 226, 1)),
                     int(random.randrange(1, 226, 1))),
            'lc_src': 'en',
            'lc_tgt': 'ja',
            'tier': 'standard',
            'auto_approve': 0,
        }

        job = self.gengo.postTranslationJob(job=single_job)
        self.assertEqual(job['opstat'], 'ok')
        self.assertTrue(job['response']['job']['job_id'] is not None)
        self.created_job_ids.append(job['response']['job']['job_id'])
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# Neither the name of myGengo, Inc. nor the names of its contributors may
# be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

from gengo import Gengo

# Get an instance of Gengo to work with...
gengo = Gengo(
    public_key='your_public_key',
    private_key='your_private_key',
    sandbox=True,
)

# Grab a specific revision - you could liken this to querying version control
# on the Gengo side. :)
print gengo.getTranslationJobRevision(id=42, revision_id=1)
Ejemplo n.º 40
0
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# Neither the name of myGengo, Inc. nor the names of its contributors may
# be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

from gengo import Gengo

# Get an instance of Gengo to work with...
gengo = Gengo(
    public_key='your_public_key',
    private_key='your_private_key',
    sandbox=True,
)

# Get the job in question; pre_mt set to 1 will give you a machine translation
# if the human translation isn't available yet. ;)
gengo.getTranslationJob(id=42, pre_mt=1)
Ejemplo n.º 41
0
#
# Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# Neither the name of myGengo, Inc. nor the names of its contributors may
# be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

from gengo import Gengo

# This method doesn't require an instance of Gengo, it's
# purely utility. You'll possibly end up using it to ensure
# that your data is utf-8 encoded before submitting it to Gengo;
# if your method calls fail, this is probably the first thing you should
# check!
Gengo.unicode2utf8("私は")
Ejemplo n.º 42
0
 def test_GengoAuthBadCredentials(self):
     gengo = Gengo(public_key='bert', private_key='beeeerrrttttt')
     self.assertRaises(GengoAuthError, gengo.getAccountStats)
Ejemplo n.º 43
0
 def setUp(self):
     self.gengo = Gengo(public_key=API_PUBKEY,
                        private_key=API_PRIVKEY,
                        sandbox=True)
Ejemplo n.º 44
0
    def setUp(self):
        """
        Creates the initial batch of jobs for the other test functions here
        to operate on.
        """
        # First we'll create three jobs - one regular, and two at the same
        # time...
        self.gengo = Gengo(public_key=API_PUBKEY,
                           private_key=API_PRIVKEY,
                           sandbox=True)
        self.created_job_ids = []

        multiple_jobs_quote = {
            'job_1': {
                'type': 'file',
                'file_path': './examples/testfiles/test_file1.txt',
                'lc_src': 'en',
                'lc_tgt': 'ja',
                'tier': 'standard',
            },
            'job_2': {
                'type': 'text',
                'body_src': '''Liverpool Football Club is an English
                Premier League football club based in Liverpool,
                Merseyside. Liverpool is awesome and is the best club
                around. Liverpool was founded in 1892 and admitted into the
                Football League the following year. The club has played at
                its home ground, Anfield, since its founding, and the team
                has played in an all-red home strip since 1964.
                Domestically, Liverpool has won eighteen league titles -
                the second most in English football - as well as seven FA
                Cups, a record eight League Cups and fifteen FA Community
                Shields. Liverpool has also won more European titles than
                any other English club, with five European Cups, three UEFA
                Cups and three UEFA Super Cups. The most successful period
                in Liverpool''',
                'lc_src': 'en',
                'lc_tgt': 'ja',
                'tier': 'standard',
            },
        }

        # Now that we've got the job, let's go ahead and see how much it'll
        # cost.
        cost_assessment = self.gengo.determineTranslationCost(
            jobs={'jobs': multiple_jobs_quote})
        self.assertEqual(cost_assessment['opstat'], 'ok')

        multiple_jobs = {}
        for k, j in cost_assessment['response']['jobs'].iteritems():
            if j['type'] == 'file':
                multiple_jobs[k] = {
                    'type': 'file',
                    'file_path': './examples/testfiles/test_file1.txt',
                    'identifier': j['identifier'],
                    'comment': 'Test comment for filejob %s' % (k, ),
                    'glossary_id': None,
                    'use_preferred': 0,
                    'force': 1
                }
            else:
                multiple_jobs[k] = multiple_jobs_quote[k]
                multiple_jobs[k]['comment'] = \
                    'Test comment for textjob %s' % (k,)
                multiple_jobs[k]['glossary_id'] = None
                multiple_jobs[k]['use_preferred'] = 0
                multiple_jobs[k]['force'] = 1

        jobs = self.gengo.postTranslationJobs(jobs={'jobs': multiple_jobs})
        self.assertEqual(jobs['opstat'], 'ok')
        self.assertTrue('order_id' in jobs['response'])
        self.assertTrue('credits_used' in jobs['response'])
        self.assertEqual(jobs['response']['job_count'], 2)

        # get some order information - in v2 the jobs need to have gone
        # through a queueing system so we wait a little bit
        time.sleep(10)
        resp = self.gengo.getTranslationOrderJobs(
            id=jobs['response']['order_id'])
        self.assertEqual(len(resp['response']['order']['jobs_available']), 2)
        self.created_job_ids.\
            extend(resp['response']['order']['jobs_available'])
Ejemplo n.º 45
0
 def test_GengoAuthNoCredentials(self):
     gengo = Gengo(public_key='', private_key='')
     self.assertRaises(GengoError, gengo.getAccountStats)
Ejemplo n.º 46
0
class TestTranslationJobFlowFileUpload(unittest.TestCase):
    """
    Tests the flow of creating a job, updating one of them, getting the
    details, and then deleting the jobs.
    """
    def setUp(self):
        """
        Creates the initial batch of jobs for the other test functions here
        to operate on.
        """
        self.gengo = Gengo(public_key=API_PUBKEY,
                           private_key=API_PRIVKEY,
                           sandbox=True)
        self.created_job_ids = []

        multiple_jobs_quote = {
            'job_1': {
                'type': 'file',
                'file_path': './examples/testfiles/test_file1.txt',
                'lc_src': 'en',
                'lc_tgt': 'ja',
                'tier': 'standard',
            },
            'job_2': {
                'type': 'file',
                'file_path': './examples/testfiles/test_file2.txt',
                'lc_src': 'ja',
                'lc_tgt': 'en',
                'tier': 'standard',
            },
        }

        # Now that we've got the jobs, let's go ahead and see how much it'll
        # cost.
        cost_assessment = self.gengo.determineTranslationCost(
            jobs={'jobs': multiple_jobs_quote})
        self.assertEqual(cost_assessment['opstat'], 'ok')

        multiple_jobs = {}
        for k, j in cost_assessment['response']['jobs'].iteritems():
            multiple_jobs[k] = {
                'type': 'file',
                'identifier': j['identifier'],
                'comment': 'Test comment for %s' % (k, ),
                'glossary_id': None,
                'use_preferred': 1,
                'force': 1,
            }

        jobs = self.gengo.postTranslationJobs(jobs={'jobs': multiple_jobs})
        self.assertEqual(jobs['opstat'], 'ok')
        self.assertTrue('order_id' in jobs['response'])
        self.assertTrue('credits_used' in jobs['response'])
        self.assertEqual(jobs['response']['job_count'], 2)

        # get some order information - in v2 the jobs need to have gone
        # through a queueing system so we wait a little bit
        time.sleep(10)
        resp = self.gengo.getTranslationOrderJobs(
            id=jobs['response']['order_id'])
        self.assertEqual(len(resp['response']['order']['jobs_available']), 2)
        self.created_job_ids.\
            extend(resp['response']['order']['jobs_available'])

    def test_postJobComment(self):
        """
        Tests posting a comment to a job.
        """
        posted_comment = self.gengo.postTranslationJobComment(
            id=self.created_job_ids[0],
            comment={'body': 'I love lamp oh mai gawd'})
        self.assertEqual(posted_comment['opstat'], 'ok')
        job_comments = self.gengo.getTranslationJobComments(
            id=self.created_job_ids[0])
        self.assertEqual(posted_comment['opstat'], 'ok')
        self.assertEqual(job_comments['opstat'], 'ok')
        self.assertEqual(job_comments['response']['thread'][0]['body'],
                         'Test comment for job_2')
        self.assertEqual(job_comments['response']['thread'][1]['body'],
                         'I love lamp oh mai gawd')

    def test_getJobDataMethods(self):
        """
        Test a ton of methods that GET data from the Gengo API, based on
        the jobs we've created and such.

        These are separate from the other GET request methods because this
        might be a huge nuisance to their API,
        and I figure it's worth separating out the pain-point test cases so
        they could be disabled easily in a
        distribution or something.
        """
        # Pull down data about one specific job.
        job = self.gengo.getTranslationJob(id=self.created_job_ids[0])
        self.assertEqual(job['opstat'], 'ok')

        # Pull down the 10 most recently submitted jobs.
        jobs = self.gengo.getTranslationJobs()
        self.assertEqual(jobs['opstat'], 'ok')

        # Test getting the batch that a job is in.
        job_batch = self.gengo.getTranslationJobBatch(
            id=self.created_job_ids[1])
        self.assertEqual(job_batch['opstat'], 'ok')

        # Pull down feedback. This should work fine, but there'll be no
        # feedback.
        feedback = self.gengo.getTranslationJobFeedback(
            id=self.created_job_ids[0])
        self.assertEqual(feedback['opstat'], 'ok')

        # Lastly, pull down any revisions that definitely didn't occur due
        # to this being a simulated test.
        revisions = self.gengo.getTranslationJobRevisions(
            id=self.created_job_ids[0])
        self.assertEqual(revisions['opstat'], 'ok')

        # So it's worth noting here that we can't really test
        # getTranslationJobRevision(), because no real revisions
        # exist at this point, and a revision ID is required to pull that
        # method off successfully. Bai now.

    def tearDown(self):
        """
        Delete every job we've created.
        """
        for id in self.created_job_ids:
            deleted_job = self.gengo.deleteTranslationJob(id=id)
            self.assertEqual(deleted_job['opstat'], 'ok')
Ejemplo n.º 47
0
class TestTranslationJobFlowMixedOrder(unittest.TestCase):
    """
    Tests the flow of creating a file job and a text job, updating one of them,
    getting the details, and then deleting the job.
    """
    def setUp(self):
        """
        Creates the initial batch of jobs for the other test functions here
        to operate on.
        """
        # First we'll create three jobs - one regular, and two at the same
        # time...
        self.gengo = Gengo(public_key=API_PUBKEY,
                           private_key=API_PRIVKEY,
                           sandbox=True)
        self.created_job_ids = []

        multiple_jobs_quote = {
            'job_1': {
                'type': 'file',
                'file_path': './examples/testfiles/test_file1.txt',
                'lc_src': 'en',
                'lc_tgt': 'ja',
                'tier': 'standard',
            },
            'job_2': {
                'type': 'text',
                'body_src': '''Liverpool Football Club is an English
                Premier League football club based in Liverpool,
                Merseyside. Liverpool is awesome and is the best club
                around. Liverpool was founded in 1892 and admitted into the
                Football League the following year. The club has played at
                its home ground, Anfield, since its founding, and the team
                has played in an all-red home strip since 1964.
                Domestically, Liverpool has won eighteen league titles -
                the second most in English football - as well as seven FA
                Cups, a record eight League Cups and fifteen FA Community
                Shields. Liverpool has also won more European titles than
                any other English club, with five European Cups, three UEFA
                Cups and three UEFA Super Cups. The most successful period
                in Liverpool''',
                'lc_src': 'en',
                'lc_tgt': 'ja',
                'tier': 'standard',
            },
        }

        # Now that we've got the job, let's go ahead and see how much it'll
        # cost.
        cost_assessment = self.gengo.determineTranslationCost(
            jobs={'jobs': multiple_jobs_quote})
        self.assertEqual(cost_assessment['opstat'], 'ok')

        multiple_jobs = {}
        for k, j in cost_assessment['response']['jobs'].iteritems():
            if j['type'] == 'file':
                multiple_jobs[k] = {
                    'type': 'file',
                    'file_path': './examples/testfiles/test_file1.txt',
                    'identifier': j['identifier'],
                    'comment': 'Test comment for filejob %s' % (k, ),
                    'glossary_id': None,
                    'use_preferred': 0,
                    'force': 1
                }
            else:
                multiple_jobs[k] = multiple_jobs_quote[k]
                multiple_jobs[k]['comment'] = \
                    'Test comment for textjob %s' % (k,)
                multiple_jobs[k]['glossary_id'] = None
                multiple_jobs[k]['use_preferred'] = 0
                multiple_jobs[k]['force'] = 1

        jobs = self.gengo.postTranslationJobs(jobs={'jobs': multiple_jobs})
        self.assertEqual(jobs['opstat'], 'ok')
        self.assertTrue('order_id' in jobs['response'])
        self.assertTrue('credits_used' in jobs['response'])
        self.assertEqual(jobs['response']['job_count'], 2)

        # get some order information - in v2 the jobs need to have gone
        # through a queueing system so we wait a little bit
        time.sleep(10)
        resp = self.gengo.getTranslationOrderJobs(
            id=jobs['response']['order_id'])
        self.assertEqual(len(resp['response']['order']['jobs_available']), 2)
        self.created_job_ids.\
            extend(resp['response']['order']['jobs_available'])

    def test_postJobComment(self):
        """
        Tests posting a comment to a job.
        """
        posted_comment = self.gengo.postTranslationJobComment(
            id=self.created_job_ids[0],
            comment={'body': 'I love lamp oh mai gawd'})
        self.assertEqual(posted_comment['opstat'], 'ok')
        job_comments = self.gengo.getTranslationJobComments(
            id=self.created_job_ids[0])
        self.assertEqual(posted_comment['opstat'], 'ok')
        self.assertEqual(job_comments['opstat'], 'ok')
        self.assertEqual(job_comments['response']['thread'][0]['body'],
                         'Test comment for textjob job_2')
        self.assertEqual(job_comments['response']['thread'][1]['body'],
                         'I love lamp oh mai gawd')

    def test_getJobDataMethods(self):
        """
        Test a ton of methods that GET data from the Gengo API, based on
        the jobs we've created and such.

        These are separate from the other GET request methods because this
        might be a huge nuisance to their API,
        and I figure it's worth separating out the pain-point test cases so
        they could be disabled easily in a
        distribution or something.
        """
        # Pull down data about one specific job...
        job = self.gengo.getTranslationJob(id=self.created_job_ids[0])
        self.assertEqual(job['opstat'], 'ok')

        # Pull down the 10 most recently submitted jobs.
        jobs = self.gengo.getTranslationJobs()
        self.assertEqual(jobs['opstat'], 'ok')

        # Test getting the batch that a job is in...
        job_batch = self.gengo.getTranslationJobBatch(
            id=self.created_job_ids[1])
        self.assertEqual(job_batch['opstat'], 'ok')

        # Pull down feedback. This should work fine, but there'll be no
        # feedback.
        feedback = self.gengo.getTranslationJobFeedback(
            id=self.created_job_ids[0])
        self.assertEqual(feedback['opstat'], 'ok')

        # Lastly, pull down any revisions that definitely didn't occur due
        # to this being a simulated test.
        revisions = self.gengo.getTranslationJobRevisions(
            id=self.created_job_ids[0])
        self.assertEqual(revisions['opstat'], 'ok')

        # So it's worth noting here that we can't really test
        # getTranslationJobRevision(), because no real revisions
        # exist at this point, and a revision ID is required to pull that
        # method off successfully. Bai now.

    def tearDown(self):
        """
        Delete every job we've created for this somewhat ridiculously
        thorough testing scenario.
        """
        for id in self.created_job_ids:
            deleted_job = self.gengo.deleteTranslationJob(id=id)
            self.assertEqual(deleted_job['opstat'], 'ok')
Ejemplo n.º 48
0
class TestTranslationSingleJobFlow(unittest.TestCase):
    """
    Tests the flow of creating a job, adding a comment, getting the details,
    and then deleting the job.
    """
    def setUp(self):
        self.gengo = Gengo(public_key=API_PUBKEY,
                           private_key=API_PRIVKEY,
                           sandbox=True)
        self.created_job_ids = []

        single_job = {
            'type':
            'text',
            'slug':
            'Single :: English to Japanese',
            'body_src':
            'Test%ding myGe%dngo A%dPI li%dbrary calls.' %
            (int(random.randrange(1, 226, 1)), int(random.randrange(
                1, 226, 1)), int(random.randrange(
                    1, 226, 1)), int(random.randrange(1, 226, 1))),
            'lc_src':
            'en',
            'lc_tgt':
            'ja',
            'tier':
            'standard',
            'auto_approve':
            0,
        }

        job = self.gengo.postTranslationJob(job=single_job)
        self.assertEqual(job['opstat'], 'ok')
        self.assertTrue(job['response']['job']['job_id'] is not None)
        self.created_job_ids.append(job['response']['job']['job_id'])

    def test_postJobComment(self):
        """
        Tests posting a comment to a job.
        """
        posted_comment = self.gengo.postTranslationJobComment(
            id=self.created_job_ids[0],
            comment={'body': 'I love lamp oh mai gawd'})
        job_comments = self.gengo.getTranslationJobComments(
            id=self.created_job_ids[0])
        self.assertEqual(posted_comment['opstat'], 'ok')
        self.assertEqual(job_comments['opstat'], 'ok')
        self.assertEqual(job_comments['response']['thread'][0]['body'],
                         'I love lamp oh mai gawd')

    def test_getJobDataMethods(self):
        """
        Test a ton of methods that GET data from the Gengo API, based
        on the job we've created.

        These are separate from the other GET request methods because this
        might be a huge nuisance to their API,
        and I figure it's worth separating out the pain-point test cases so
        they could be disabled easily in a distribution or something.
        """
        # Pull down data about one specific job...
        job = self.gengo.getTranslationJob(id=self.created_job_ids[0])
        self.assertEqual(job['opstat'], 'ok')

        # Pull down the 10 most recently submitted jobs.
        jobs = self.gengo.getTranslationJobs()
        self.assertEqual(jobs['opstat'], 'ok')

        # Pull down feedback. This should work fine, but there'll be no
        # feedback.
        feedback = self.gengo.getTranslationJobFeedback(
            id=self.created_job_ids[0])
        self.assertEqual(feedback['opstat'], 'ok')

        # Lastly, pull down any revisions that definitely didn't occur due
        # to this being a simulated test.
        revisions = self.gengo.getTranslationJobRevisions(
            id=self.created_job_ids[0])
        self.assertEqual(revisions['opstat'], 'ok')

        # So it's worth noting here that we can't really test
        # getTranslationJobRevision(), because no real revisions
        # exist at this point, and a revision ID is required to pull that
        # method off successfully. Bai now.

    def tearDown(self):
        """
        Delete every job we've created.
        """
        for id in self.created_job_ids:
            deleted_job = self.gengo.deleteTranslationJob(id=id)
            self.assertEqual(deleted_job['opstat'], 'ok')
Ejemplo n.º 49
0
# and/or other materials provided with the distribution.
# Neither the name of myGengo, Inc. nor the names of its contributors may
# be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

from gengo import Gengo

# Get an instance of Gengo to work with...
gengo = Gengo(
    public_key='your_public_key',
    private_key='your_private_key',
    sandbox=True,
)

# Get all the comments on a specific job.
# Note that this returns a data set, so while we just print it below, you'll
# inevitably want to iterate over it and such.
print gengo.getTranslationJobComments(id=42)
Ejemplo n.º 50
0
    def post(self, request, *args, **kwargs):
        gengo = Gengo(public_key=settings.GENGO_PUBLIC_KEY,
                      private_key=settings.GENGO_PRIVATE_KEY,
                      sandbox=settings.GENGO_SANDBOX,
                      debug=settings.GENGO_DEBUG)

        app_id = request.DATA.get('app')
        lang_code = request.DATA.get('lang', '')
        tier = request.DATA.get('tier', 'standard')
        comment = request.DATA.get('comment', '')

        app = App.objects.filter(pk=app_id).first()
        if not app:
            return Response({'errors': 'app_id is not valid.'},
                            status=status.HTTP_400_BAD_REQUEST)

        if lang_code and lang_code not in [lang[0] for lang in LANG_CHOICES]:
            return Response({'errors': 'lang code is not valid.'},
                            status=status.HTTP_400_BAD_REQUEST)
        lang_code = lang_code.lower()
        if lang_code in not_supported:
            return Response({'errors': 'Not Supported Language.'},
                            status=status.HTTP_400_BAD_REQUEST)

        if lang_code in variation:
            lang_code = variation[lang_code]

        if tier not in ['standard', 'pro']:
            return Response({'errors': 'tier is not valid.'},
                            status=status.HTTP_400_BAD_REQUEST)

        words = Word.objects.filter(app=app).all()

        jobs = {}
        for i in range(len(words)):
            k = 'job_%s' % (i + 1)
            word = words[i]
            cb = settings.DOMAIN + reverse(
                'gengo-callback',
                kwargs=dict(app_id=app.id,
                            word_id=word.id,
                            lang_code=request.DATA.get('lang', '')))

            job = {
                'type': 'text',
                'slug': slugify(word.name),
                'body_src': word.name,
                'lc_src': 'en',
                'lc_tgt': lang_code,
                'tier': tier,
                'auto_approve': 1,
                'comment': '',
                'attachments': [],
                'callback_url': cb,
                'custom_data': '',
                'force': 0,
                'use_preferred': 0
            }
            jobs[k] = job

        jobs['comment'] = comment
        res = gengo.postTranslationJobs(jobs=jobs)

        return Response(data=res)
Ejemplo n.º 51
0
# this list of conditions and the following disclaimer.
# Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# Neither the name of Gengo, Inc. nor the names of its contributors may
# be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

from gengo import Gengo

# Get an instance of Gengo to work with...
gengo = Gengo(public_key='your_public_key',
              private_key='your_private_key',
              sandbox=True,
              debug=True)

# Get every revision on a job. Returns a data set, iterate if need be!
print(gengo.getTranslationJobRevisions(id=42))
Ejemplo n.º 52
0
# Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# Neither the name of myGengo, Inc. nor the names of its contributors may
# be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

from gengo import Gengo

# Get an instance of Gengo to work with...
gengo = Gengo(
    public_key='your_public_key',
    private_key='your_private_key',
    sandbox=False,
)

# Print the account stats...
print gengo.getAccountStats()
Ejemplo n.º 53
0
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

from gengo import Gengo

# Get an instance of Gengo to work with...
gengo = Gengo(public_key='your_public_key',
              private_key='your_private_key',
              sandbox=True,
              debug=True)

# Update a job that has an id of 42, and reject it, cite the reason,
# add a comment, and throw up some captcha stuff. See the docs for
# more information pertaining to this method, it can do quite a bit. :)
print(
    gengo.updateTranslationJob(id=42,
                               action={
                                   'action': 'reject',
                                   'reason': 'quality',
                                   'comment': 'My grandmother does better.',
                                   'captcha': 'bert'
                               }))
Ejemplo n.º 54
0
class TestTranslationJobFlowMixedOrder(unittest.TestCase):
    """
    Tests the flow of creating a file job and a text job, updating one of them,
    getting the details, and then deleting the job.
    """
    def setUp(self):
        """
        Creates the initial batch of jobs for the other test functions here
        to operate on.
        """
        # First we'll create three jobs - one regular, and two at the same
        # time...
        self.gengo = Gengo(public_key=API_PUBKEY,
                           private_key=API_PRIVKEY,
                           sandbox=True)

        import requests
        self.json_mock = mock.Mock()
        self.json_mock.json.return_value = {'opstat': 'ok'}
        self.getMock = RequestsMock(return_value=self.json_mock)
        self.requestsPatch = mock.patch.object(requests, 'get', self.getMock)
        self.requestsPatch.start()

    def tearDown(self):
        self.requestsPatch.stop()

    def test_postJobComment(self):
        """
        Tests posting a comment to a job.
        """
        job_comments = self.gengo.getTranslationJobComments(id=1)
        self.assertEqual(job_comments['opstat'], 'ok')
        self.getMock.assert_path_contains(
            gengo.mockdb.apihash['getTranslationJobComments']['url'].replace(
                '{{id}}', '1'))

    def test_getJobDataMethods(self):
        """
        Test a ton of methods that GET data from the Gengo API, based on
        the jobs we've created and such.

        These are separate from the other GET request methods because this
        might be a huge nuisance to their API,
        and I figure it's worth separating out the pain-point test cases so
        they could be disabled easily in a
        distribution or something.
        """
        # Pull down data about one specific job...
        job = self.gengo.getTranslationJob(id=1)
        self.assertEqual(job['opstat'], 'ok')
        self.getMock.assert_path_contains(
            gengo.mockdb.apihash['getTranslationJob']['url'].replace(
                '{{id}}', '1'))

        # Pull down the 10 most recently submitted jobs.
        jobs = self.gengo.getTranslationJobs()
        self.assertEqual(jobs['opstat'], 'ok')
        self.getMock.assert_path_contains(
            gengo.mockdb.apihash['getTranslationJobs']['url'])

        # Test getting the batch that a job is in...
        job_batch = self.gengo.getTranslationJobBatch(id=1)
        self.assertEqual(job_batch['opstat'], 'ok')
        self.getMock.assert_path_contains(
            gengo.mockdb.apihash['getTranslationJobBatch']['url'].replace(
                '{{id}}', '1'))

        # Pull down feedback. This should work fine, but there'll be no
        # feedback.
        feedback = self.gengo.getTranslationJobFeedback(id=1)
        self.assertEqual(feedback['opstat'], 'ok')
        self.getMock.assert_path_contains(
            gengo.mockdb.apihash['getTranslationJobFeedback']['url'].replace(
                '{{id}}', '1'))

        # Lastly, pull down any revisions that definitely didn't occur due
        # to this being a simulated test.
        revisions = self.gengo.getTranslationJobRevisions(id=1)
        self.assertEqual(revisions['opstat'], 'ok')
        self.getMock.assert_path_contains(
            gengo.mockdb.apihash['getTranslationJobRevisions']['url'].replace(
                '{{id}}', '1'))
Ejemplo n.º 55
0
    with open(path + '/' + lang + "/raw.txt", "w") as f:
        f.write(content.encode("utf-8"))


def fetch_job(job_id):
    resp = gengo.getTranslationJob(id=job_id)
    print resp
    translation = resp['response']['job']['body_tgt']
    lang = resp['response']['job']['lc_tgt']
    # custom formatting already applied
    if lang not in ("ar", "es", "ja", "ru", "zh-tw", "sk"):
        write_translation(lang, translation)


gengo = Gengo(public_key=PUBLIC_KEY,
              private_key=PRIVATE_KEY,
              sandbox=False,
              debug=False)

jobs = gengo.getTranslationOrderJobs(id=ORDER_ID)
orders = jobs['response']['order']

print "Total Jobs:", orders["total_jobs"]
print "Jobs pending:", len(orders["jobs_pending"])
print "Jobs reviewable", len(orders["jobs_reviewable"])
print "Jobs approved", len(orders["jobs_approved"])

# approve all reviewable jobs and grab text
for job_id in orders["jobs_reviewable"]:
    gengo.updateTranslationJob(id=job_id, action={"action": "approve"})
    fetch_job(job_id)
Ejemplo n.º 56
0
class TestResponseHandling(unittest.TestCase):
    def setUp(self):
        self.gengo = Gengo(public_key=API_PUBKEY, private_key=API_PRIVKEY)
        self.response = mock.Mock()

    def test_handleResponse(self):
        expect = {
            'opstat': 'ok',
        }
        self.response.json.return_value = expect
        self.assertEqual(expect, self.gengo._handleResponse(self.response))

    def test_raiseForErrorResponse(self):
        self.response.json.return_value = {
            'opstat': 'error',
            'err': {
                'msg': 'Not Found',
                'code': 404,
            }
        }

        self.assertRaises(gengo.GengoError,
                          lambda: self.gengo._handleResponse(self.response))

    def test_handleNoCodeGiven(self):
        self.response.json.return_value = {
            'opstat': 'error',
            'err': {
                'msg': 'no rows in result set',
            }
        }

        self.assertRaises(gengo.GengoError,
                          lambda: self.gengo._handleResponse(self.response))

    def test_handleNoMessageAndCodeGiven(self):
        self.response.json.return_value = {'opstat': 'error', 'err': {}}

        self.assertRaises(gengo.GengoError,
                          lambda: self.gengo._handleResponse(self.response))

    def test_handleNoErrorAttributeGiven(self):
        self.response.json.return_value = {'opstat': 'error'}

        self.assertRaises(gengo.GengoError,
                          lambda: self.gengo._handleResponse(self.response))

    def test_raiseForMultipleErrorResponse(self):
        self.response.json.return_value = {
            'opstat': 'error',
            'err': {
                'job_1': [{
                    'code': 1350,
                    'msg': '"body_src" is a required field'
                }, {
                    'code': 1400,
                    'msg': '"lc_src" is a required field'
                }, {
                    'code': 1450,
                    'msg': '"lc_tgt" is a required field'
                }, {
                    'code': 1500,
                    'msg': '"tier" is a required field'
                }]
            }
        }

        self.assertRaises(gengo.GengoError,
                          lambda: self.gengo._handleResponse(self.response))
Ejemplo n.º 57
0
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

from __future__ import absolute_import

from gengo import Gengo

# Get an instance of Gengo to work with...
gengo = Gengo(
    public_key='your_public_key',
    private_key='your_private_key',
    sandbox=True,
    debug=True
)

# This is an exhaustive view of this object; chances are your code will never
# have to be this verbose because you'd want to build it up programmatically.
data = {
    'jobs': {
        'job_1': {
            'type': 'text',  # REQUIRED. Type to translate, you'll probably always put 'text' here. ;P
            'slug': 'Single :: English to Japanese',  # REQUIRED. Slug for internally storing, can be generic.
            'body_src': 'Testing Gengo API library calls.',  # REQUIRED. The text you're translating. ;P
            'lc_src': 'en',  # REQUIRED. source_language_code (see getServiceLanguages() for a list of codes)
            'lc_tgt': 'ja',  # REQUIRED. target_language_code (see getServiceLanguages() for a list of codes)
            'tier': 'standard',  # REQUIRED. tier type ("machine", "standard", "pro", or "ultra")
Ejemplo n.º 58
0
 def setUp(self):
     self.gengo = Gengo(public_key=API_PUBKEY, private_key=API_PRIVKEY)
     self.response = mock.Mock()
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

from __future__ import absolute_import

from gengo import Gengo

# Get an instance of Gengo to work with...
gengo = Gengo(
    public_key='your_public_key',
    private_key='your_private_key',
    sandbox=True,
    debug=True
)

# Archive all jobs
gengo.updateTranslationJobs(action={
    'job_ids': [4020, 1082],
    'action': 'archive'
})

# Revise a group of jobs
gengo.updateTranslationJobs(action={
    'action': 'revise',
    'job_ids': [{
        'job_id': 556,
        'comment': 'Please change the word banana to gorilla'
Ejemplo n.º 60
0
# Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# Neither the name of Gengo, Inc. nor the names of its contributors may
# be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

from gengo import Gengo

# Get an instance of Gengo to work with...

gengo = Gengo(public_key='your_public_key',
              private_key='your_private_key',
              sandbox=False,
              debug=True)
# Useful for figuring out what language paths are supported - e.g, if
# we use 'en' below, we'll see what languages we can translate TO from 'en'.
print(gengo.getServiceLanguagePairs(lc_src='en'))