Exemplo n.º 1
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.myGengo = MyGengo(public_key=public_key,
                               private_key=private_key,
                               sandbox=SANDBOX)
        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.myGengo.postTranslationJob(job=single_job)
        self.assertEqual(job['opstat'], 'ok')
        self.assertIsNotNone(job['response']['job']['job_id'])
        self.created_job_ids.append(job['response']['job']['job_id'])
 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, uid, 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 = MyGengo(
             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)
    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, uid, uid, context=context)
        if not user.company_id.gengo_public_key or not user.company_id.gengo_private_key:
            return (False, _("Invalid Gengo configuration. Gengo authentication `Public Key` or `Private Key` is missing. Complete Gengo authentication parameters under `Settings > Companies > Gengo Parameters`."))
        try:
            gengo = MyGengo(
                public_key=user.company_id.gengo_public_key.encode('ascii'),
                private_key=user.company_id.gengo_private_key.encode('ascii'),
                sandbox=True,
            )
            gengo.getAccountStats()

            return (True, gengo)
        except Exception, e:
            return (False, _("Gengo Connection Error\n%s") %e)
Exemplo n.º 4
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.myGengo = MyGengo(public_key=public_key,
                               private_key=private_key,
                               sandbox=SANDBOX)
Exemplo n.º 5
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.myGengo = MyGengo(public_key=public_key,
                               private_key=private_key,
                               api_version='2',
                               sandbox=SANDBOX)
        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 job, let's go ahead and see how much it'll cost.
        cost_assessment = self.myGengo.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': 0,
                'force': 1
            }

        jobs = self.myGengo.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(30)
        resp = self.myGengo.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'])
Exemplo n.º 6
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.myGengo = MyGengo(public_key = public_key, private_key = private_key, api_version = '2', sandbox = SANDBOX)
		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.myGengo.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',
						'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.myGengo.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( 30 )
		resp = self.myGengo.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'])
Exemplo n.º 7
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.myGengo = MyGengo(public_key = public_key,
                               private_key = private_key, sandbox = SANDBOX)
Exemplo n.º 8
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.myGengo = MyGengo(public_key = public_key, private_key = private_key, sandbox = SANDBOX)		
		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,
		}
		
		multiple_jobs = {
			'job_1': {
				'type': 'text',
				'slug': 'Multiple :: English to Japanese',
				'body_src': 'H%dow i%ds th%de weather?' % (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',
			},
			'job_2': {
				'type': 'text',
				'slug': 'Multiple :: Japanese To English',
				'body_src': '天%d気%dはど%dうですか' % (int(random.randrange(1,226,1)), int(random.randrange(1,226,1)), int(random.randrange(1,226,1))),
				'lc_src': 'ja',
				'lc_tgt': 'en',
				'tier': 'ultra',
			},
		}
		
		# Now that we've got the job, let's go ahead and see how much it'll cost.
		cost_assessment = self.myGengo.determineTranslationCost(jobs = {'jobs': multiple_jobs})
		self.assertEqual(cost_assessment['opstat'], 'ok')
		
		# If that method worked, sweet. Move on and create three jobs, store their IDs. Make sure we got an ID
		# back, since these methods are otherwise largely useless without that returned data. These tests walk a fine
		# line between testing myGengo and the myGengo API functionality as a whole - watch yourself if you add to this. :)
		job = self.myGengo.postTranslationJob(job = single_job)
		self.assertEqual(job['opstat'], 'ok')
		self.assertIsNotNone(job['response']['job']['job_id'])
		self.created_job_ids.append(job['response']['job']['job_id'])
		
		jobs = self.myGengo.postTranslationJobs(jobs = {'jobs': multiple_jobs})
		self.assertEqual(job['opstat'], 'ok')
		
		# This is a fairly ugly way to check for and retrieve job IDs; in an ideal system you know the keys, and... well,
		# truthfully we do here too. I suppose this is moreso here as an example of how to get IDs in a situation where you
		# don't know the keys. May or may not be useful to some.
		for job_obj in jobs['response']['jobs']:
			for job in job_obj:
				self.assertIsNotNone(job_obj[job]['job_id'])
				self.created_job_ids.append(job_obj[job]['job_id'])
Exemplo n.º 9
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.myGengo = MyGengo(public_key = public_key,
                               private_key = private_key, sandbox = SANDBOX)

	def test_getGlossaryList( self ):
		resp = self.myGengo.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.myGengo.getGlossary( id = 42 )
Exemplo n.º 10
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.myGengo = MyGengo(public_key=public_key,
                               private_key=private_key,
                               sandbox=SANDBOX)

    def test_getGlossaryList(self):
        resp = self.myGengo.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.myGengo.getGlossary(id=42)
Exemplo n.º 11
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.myGengo = MyGengo(public_key = public_key, private_key = private_key, api_version = '2', sandbox = SANDBOX)
		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 job, let's go ahead and see how much it'll cost.
		cost_assessment = self.myGengo.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': 0,
					'force': 1
				}

		jobs = self.myGengo.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( 30 )
		resp = self.myGengo.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'])
Exemplo n.º 12
0
def translate(text):
    gengo = MyGengo(
        public_key=secret.GENGO_PUBLIC_KEY,
        private_key=secret.GENGO_PRIVATE_KEY,
        sandbox=False
    )
    counter = 0
    to_lang = 'en'
    from_lang = 'ja'
    while counter < 4:  # even number = English result
        translation = gengo.postTranslationJob(job={
            'type': 'text',
            'slug': 'the_game',
            'body_src': text,
            'lc_src': to_lang,
            'lc_tgt': from_lang,
            'tier': 'machine'
        })
        text = translation['response']['job']['body_tgt']
        swap = to_lang
        to_lang = from_lang
        from_lang = swap
        counter += 1
    return text
Exemplo n.º 13
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.myGengo = MyGengo(public_key = public_key, private_key = private_key, sandbox = SANDBOX)
		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.myGengo.postTranslationJob(job = single_job)
		self.assertEqual(job['opstat'], 'ok')
		self.assertIsNotNone(job['response']['job']['job_id'])
		self.created_job_ids.append(job['response']['job']['job_id'])
Exemplo n.º 14
0
# -*- coding: utf-8 -*-
#!/usr/bin/python

from mygengo import MyGengo

# Get an instance of MyGengo to work with...
gengo = MyGengo(
    public_key = 'your_public_key',
    private_key = 'your_private_key',
    sandbox = True, # possibly false, depending on your dev needs
)

# Think of this as a "search my jobs" method, and it becomes very self-explanatory.
print gengo.getTranslationJobs(status = "upaid", count = 15)
Exemplo n.º 15
0
# -*- coding: utf-8 -*-
#!/usr/bin/python

from mygengo import MyGengo

# Get an instance of MyGengo to work with...
gengo = MyGengo(
    public_key = 'your_public_key',
    private_key = 'your_private_key'
    sandbox = False, # possibly false, depending on your dev needs
	debug = True
)

# Retrieve and print the account balance. Properties ahoy!
print gengo.getAccountBalance()
# -*- coding: utf-8 -*-
#!/usr/bin/python

from mygengo import MyGengo

# Get an instance of MyGengo to work with...
gengo = MyGengo(
    public_key = 'your_public_key',
    private_key = 'your_private_key',
    sandbox = True, # possibly false, depending on your dev needs
)

# Exhaustive view, chances are your code will never be quite this verbose (programatically build this).
jobs_data = {
	'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 myGengo 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")
      
       	'auto_approve': 0, # OPTIONAL. Hopefully self explanatory (1 = yes, 0 = no),
        'comment': 'HEY THERE TRANSLATOR', # OPTIONAL. Comment to leave for translator.
        'callback_url': 'http://...', # OPTIONAL. Callback URL that updates are sent to.
		'custom_data': 'your optional custom data, limited to 1kb.' # OPTIONAL
	},
    'job_2': {
      	'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 myGengo API library calls.', # REQUIRED. The text you're translating. ;P
Exemplo n.º 17
0
class TestTranslationJobFlow(unittest.TestCase):
	"""
		Tests the flow of creating a job, updating it, getting the details, and then 
		deleting the job. This is the thick of it!
		
		Flow is as follows:
		
			1: Create a mock job and get an estimate for it (setUp)
			2: Create three jobs - 1 single, 2 batched
			3: Update the first job with some arbitrary information or something
			4: Post a comment on the first job
			6: Perform a hell of a lot of GETs to the myGengo API to check stuff
			7: Delete the job if all went well (teardown phase)
	"""
	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.myGengo = MyGengo(public_key = public_key, private_key = private_key, sandbox = SANDBOX)		
		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,
		}
		
		multiple_jobs = {
			'job_1': {
				'type': 'text',
				'slug': 'Multiple :: English to Japanese',
				'body_src': 'H%dow i%ds th%de weather?' % (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',
			},
			'job_2': {
				'type': 'text',
				'slug': 'Multiple :: Japanese To English',
				'body_src': '天%d気%dはど%dうですか' % (int(random.randrange(1,226,1)), int(random.randrange(1,226,1)), int(random.randrange(1,226,1))),
				'lc_src': 'ja',
				'lc_tgt': 'en',
				'tier': 'ultra',
			},
		}
		
		# Now that we've got the job, let's go ahead and see how much it'll cost.
		cost_assessment = self.myGengo.determineTranslationCost(jobs = {'jobs': multiple_jobs})
		self.assertEqual(cost_assessment['opstat'], 'ok')
		
		# If that method worked, sweet. Move on and create three jobs, store their IDs. Make sure we got an ID
		# back, since these methods are otherwise largely useless without that returned data. These tests walk a fine
		# line between testing myGengo and the myGengo API functionality as a whole - watch yourself if you add to this. :)
		job = self.myGengo.postTranslationJob(job = single_job)
		self.assertEqual(job['opstat'], 'ok')
		self.assertIsNotNone(job['response']['job']['job_id'])
		self.created_job_ids.append(job['response']['job']['job_id'])
		
		jobs = self.myGengo.postTranslationJobs(jobs = {'jobs': multiple_jobs})
		self.assertEqual(job['opstat'], 'ok')
		
		# This is a fairly ugly way to check for and retrieve job IDs; in an ideal system you know the keys, and... well,
		# truthfully we do here too. I suppose this is moreso here as an example of how to get IDs in a situation where you
		# don't know the keys. May or may not be useful to some.
		for job_obj in jobs['response']['jobs']:
			for job in job_obj:
				self.assertIsNotNone(job_obj[job]['job_id'])
				self.created_job_ids.append(job_obj[job]['job_id'])
	
	@unittest.skip("We don't test myGengo.getTranslationJobPreviewImage() because it's potentially resource heavy on the myGengo API.")
	def test_getTranslationJobPreviewImage(self):
		"""
			This test could be a bit more granular, but I'm undecided at the moment - testing the response stream
			of this method is more of a Unit Test for myGengo than myGengo. Someone can extend if they see fit, but I 
			currently see no reason to mess with this further.
		"""
		img = self.myGengo.getTranslationJobPreviewImage(id = self.created_job_ids[0])
		self.assertIsNotNone(img)
	
	def test_postJobDataMethods(self):
		"""
			Tests all the myGengo methods that deal with updating jobs, posting comments, etc. test_getJobDataMethods() checks things,
			but they need to exist first - think of this as the alcoholic mother to _getJobDataMethods().
		"""
		# The 'update' method can't really be tested, as it requires the translator having actually done something before
		# it's of any use. Thing is, in automated testing, we don't really have a method to flip the switch on the myGengo end. If we
		# WERE to test this method, it'd look a little something like this:
		#	
		#	updated_job = self.myGengo.updateTranslationJob(id = self.created_job_ids[0], action = {
		#		'action': 'purchase',
		#	})
		#	self.assertEqual(updated_job['opstat'], 'ok')
		
		posted_comment = self.myGengo.postTranslationJobComment(id = self.created_job_ids[0], comment = {
			'body': 'I love lamp oh mai gawd',
		})
		self.assertEqual(posted_comment['opstat'], 'ok')
	
	def test_getJobDataMethods(self):
		"""
			Test a ton of methods that GET data from the myGengo 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.myGengo.getTranslationJob(id = self.created_job_ids[0])
		self.assertEqual(job['opstat'], 'ok')
		
		# Pull down the 10 most recently submitted jobs.
		jobs = self.myGengo.getTranslationJobs()
		self.assertEqual(jobs['opstat'], 'ok')
		
		# Test getting the batch that a job is in...
		job_batch = self.myGengo.getTranslationJobBatch(id = self.created_job_ids[1])
		self.assertEqual(job_batch['opstat'], 'ok')
		
		# Pull down the comment(s) we created earlier in this test suite.
		job_comments = self.myGengo.getTranslationJobComments(id = self.created_job_ids[0])
		self.assertEqual(job_comments['opstat'], 'ok')
		
		# Pull down feedback. This should work fine, but there'll be no feedback or anything, so... meh.
		feedback = self.myGengo.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.myGengo.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.myGengo.deleteTranslationJob(id = id)
			self.assertEqual(deleted_job['opstat'], 'ok')
Exemplo n.º 18
0
 def test_getAccountStats(self):
     myGengo = MyGengo(public_key=public_key,
                       private_key=private_key,
                       sandbox=SANDBOX)
     stats = myGengo.getAccountStats()
     self.assertEqual(stats['opstat'], 'ok')
Exemplo n.º 19
0
class TestTranslationSingleJobFlow(unittest.TestCase):
    """
		Tests the flow of creating a job, updating it, getting the details, and then
		deleting the job. This is the thick of it!

		Flow is as follows:

			1: Create a mock job and get an estimate for it (setUp)
			2: Create three jobs - 1 single, 2 batched
			3: Update the first job with some arbitrary information or something
			4: Post a comment on the first job
			6: Perform a hell of a lot of GETs to the Gengo API to check stuff
			7: Delete the job if all went well (teardown phase)
	"""
    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.myGengo = MyGengo(public_key=public_key,
                               private_key=private_key,
                               sandbox=SANDBOX)
        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.myGengo.postTranslationJob(job=single_job)
        self.assertEqual(job['opstat'], 'ok')
        self.assertIsNotNone(job['response']['job']['job_id'])
        self.created_job_ids.append(job['response']['job']['job_id'])

    @unittest.skip(
        "We don't test Gengo.getTranslationJobPreviewImage() because it's potentially resource heavy on the Gengo API."
    )
    def test_getTranslationJobPreviewImage(self):
        """
			This test could be a bit more granular, but I'm undecided at the moment - testing the response stream
			of this method is more of a Unit Test for Gengo than Gengo. Someone can extend if they see fit, but I
			currently see no reason to mess with this further.
		"""
        img = self.myGengo.getTranslationJobPreviewImage(
            id=self.created_job_ids[0])
        self.assertIsNotNone(img)

    def test_postJobDataMethods(self):
        """
			Tests all the Gengo methods that deal with updating jobs, posting comments, etc. test_getJobDataMethods() checks things,
			but they need to exist first - think of this as the alcoholic mother to _getJobDataMethods().
		"""
        # The 'update' method can't really be tested, as it requires the translator having actually done something before
        # it's of any use. Thing is, in automated testing, we don't really have a method to flip the switch on the Gengo end. If we
        # WERE to test this method, it'd look a little something like this:
        #
        #	updated_job = self.myGengo.updateTranslationJob(id = self.created_job_ids[0], action = {
        #		'action': 'purchase',
        #	})
        #	self.assertEqual(updated_job['opstat'], 'ok')

        posted_comment = self.myGengo.postTranslationJobComment(
            id=self.created_job_ids[0],
            comment={
                'body': 'I love lamp oh mai gawd',
            })
        self.assertEqual(posted_comment['opstat'], 'ok')

    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.myGengo.getTranslationJob(id=self.created_job_ids[0])
        self.assertEqual(job['opstat'], 'ok')

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

        # Pull down the comment(s) we created earlier in this test suite.
        job_comments = self.myGengo.getTranslationJobComments(
            id=self.created_job_ids[0])
        self.assertEqual(job_comments['opstat'], 'ok')

        # Pull down feedback. This should work fine, but there'll be no feedback or anything, so... meh.
        feedback = self.myGengo.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.myGengo.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.myGengo.deleteTranslationJob(id=id)
            self.assertEqual(deleted_job['opstat'], 'ok')
Exemplo n.º 20
0
# -*- coding: utf-8 -*-
#!/usr/bin/python

from mygengo import MyGengo

# Get an instance of MyGengo to work with...
gengo = MyGengo(
    public_key='your_public_key',
    private_key='your_private_key',
    sandbox=True,  # possibly false, depending on your dev needs
)

# Post a comment on a specific job; perhaps you have an update for the translator
# or something of the sort.
gengo.postTranslationJobComment(id=42, comment={
    'body': 'I love lamp!',
})
Exemplo n.º 21
0
    print "<url>"
    exit()


def out_lang_codes():
    for lang in gengo.getServiceLanguages().values()[1]:
        print '{0:<10}{1:}'.format(lang.values()[2], lang.values()[3])


def findkeys(directory, regexp):
    fileList = os.listdir(directory)
    return [f for f in fileList if f.find(regexp) > -1]


gengo = MyGengo(
    public_key=open(KEYS[0]).read(),
    private_key=open(KEYS[1]).read(),
)


def translate_line(line, src_lang, trg_lang):
    translation = gengo.postTranslationJob(
        job={
            'type': 'text',
            'slug': 'Translating Subtitles',
            'body_src': line,
            'lc_src': src_lang,
            'lc_tgt': trg_lang,
            'tier': 'machine',
            'auto_approve': 0,
            'comment': 'Machine Subtitle Translation',
            'callback_url': 'http://www.jaist.ac.jp/~s1010205/'
Exemplo n.º 22
0
# -*- coding: utf-8 -*-
#!/usr/bin/python

from mygengo import MyGengo

# Get an instance of MyGengo to work with...
gengo = MyGengo(
    public_key='your_public_key',
    private_key='your_private_key',
    sandbox=True,  # possibly false, depending on your dev needs
)

# Think of this as a "search my jobs" method, and it becomes very self-explanatory.
print gengo.getTranslationJobs(status="upaid", count=15)
Exemplo n.º 23
0
# -*- coding: utf-8 -*-
#!/usr/bin/python

from mygengo import MyGengo

# Get an instance of MyGengo to work with...
gengo = MyGengo(
    public_key='your_public_key',
    private_key='your_private_key',
    sandbox=True,  # possibly false, depending on your dev needs
)

# Post over a job for translation.
gengo.postTranslationJob(
    job={
        '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 myGengo 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")
        'auto_approve':
        0,  # OPTIONAL. Hopefully self explanatory (1 = yes, 0 = no),
        'comment':
        'HEY THERE TRANSLATOR',  # OPTIONAL. Comment to leave for translator.
# -*- coding: utf-8 -*-
#!/usr/bin/python

from mygengo import MyGengo

# Get an instance of MyGengo to work with...
gengo = MyGengo(
    public_key = 'your_public_key',
    private_key = 'your_private_key',
    sandbox = True, # possibly false, depending on your dev needs
)

# 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)
Exemplo n.º 25
0
 def test_getServiceLanguagePairs(self):
     myGengo = MyGengo(public_key=public_key,
                       private_key=private_key,
                       sandbox=SANDBOX)
     resp = myGengo.getServiceLanguagePairs()
     self.assertEqual(resp['opstat'], 'ok')
Exemplo n.º 26
0
 def test_getAccountBalance(self):
     myGengo = MyGengo(public_key=public_key,
                       private_key=private_key,
                       sandbox=SANDBOX)
     balance = myGengo.getAccountBalance()
     self.assertEqual(balance['opstat'], 'ok')
Exemplo n.º 27
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.myGengo = MyGengo(public_key=public_key,
                               private_key=private_key,
                               api_version='2',
                               sandbox=SANDBOX)
        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.myGengo.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',
                    '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.myGengo.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(30)
        resp = self.myGengo.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'])
# -*- coding: utf-8 -*-
#!/usr/bin/python

from mygengo import MyGengo

# Get an instance of MyGengo to work with...
gengo = MyGengo(
    public_key = 'your_public_key',
    private_key = 'your_private_key',
    sandbox = True, # possibly false, depending on your dev needs
)

# This method is a bit tricky; you can call it like below, but how you treat
# the returned data is very much up to you.
gengo.getTranslationJobPreviewImage(id = 42)
# -*- coding: utf-8 -*-
#!/usr/bin/python

from mygengo import MyGengo

# Get an instance of MyGengo to work with...
gengo = MyGengo(
    public_key=
    'z~DfqWAxBP#tiuu=A|x0s7PDFdGX#eLldqssiSvl)VK6]gbqJls{9xBxS{W1U|$[',
    private_key=
    'wXCC}Wdh1smuGEAWT8VuM6Jb]Sh|Z[D04^nBZGV7G1njU0a0m=-i0xqlp|6V$4h^',
    sandbox=True,  # possibly false, depending on your dev needs
    debug=True)

# Get the job group in question
print gengo.getTranslationJobGroup(id=16973)
# -*- coding: utf-8 -*-
#!/usr/bin/python

from mygengo import MyGengo

# Get an instance of MyGengo to work with...
gengo = MyGengo(
    public_key = 'z~DfqWAxBP#tiuu=A|x0s7PDFdGX#eLldqssiSvl)VK6]gbqJls{9xBxS{W1U|$[',
    private_key = 'wXCC}Wdh1smuGEAWT8VuM6Jb]Sh|Z[D04^nBZGV7G1njU0a0m=-i0xqlp|6V$4h^',

    sandbox = True, # possibly false, depending on your dev needs
    debug = True
)

# Get the job group in question
print gengo.getTranslationJobGroup(id = 16973)
Exemplo n.º 31
0
# -*- coding: utf-8 -*-
#!/usr/bin/python

from mygengo import MyGengo

# Get an instance of MyGengo to work with...
gengo = MyGengo(
    public_key='your_public_key',
    private_key='your_private_key',
    sandbox=True,  # possibly false, depending on your dev needs
)

# 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. :)
gengo.updateTranslationJob(id=42,
                           action={
                               'action': 'reject',
                               'reason': 'quality',
                               'comment': 'My grandmother does better.',
                               'captcha': 'bert'
                           })
Exemplo n.º 32
0
	def test_getAccountBalance(self):
		myGengo = MyGengo(public_key = public_key, private_key = private_key, sandbox = SANDBOX)
		balance = myGengo.getAccountBalance()
		self.assertEqual(balance['opstat'], 'ok')
# -*- coding: utf-8 -*-
#!/usr/bin/python

from mygengo import MyGengo

# Get an instance of MyGengo to work with...
gengo = MyGengo(
    public_key = 'your_public_key',
    private_key = 'your_private_key',
    sandbox = True, # possibly false, depending on your dev needs
)

# This method is a bit tricky; you can call it like below, but how you treat
# the returned data is very much up to you.
gengo.getTranslationJobPreview(id = 42)
Exemplo n.º 34
0
 def test_MyGengoAuthBadCredentials(self):
     myGengo = MyGengo(public_key='bert',
                       private_key='beeeerrrttttt',
                       sandbox=SANDBOX)
     self.assertRaises(MyGengoAuthError, myGengo.getAccountStats)
# -*- coding: utf-8 -*-
#!/usr/bin/python

from mygengo import MyGengo

# Get an instance of MyGengo to work with...
gengo = MyGengo(
    public_key='your_public_key',
    private_key='your_private_key',
    sandbox=True,  # possibly false, depending on your dev needs
)

# This method is a bit tricky; you can call it like below, but how you treat
# the returned data is very much up to you.
gengo.getTranslationJobPreviewImage(id=42)
Exemplo n.º 36
0
class TestTranslationJobFlowMixedOrder(unittest.TestCase):
	"""
	Tests the flow of creating a job, updating it, getting the details, and then
	deleting the job for an order with mixed file/text jobs.

	Flow is as follows:

	1: Create a mock job and get an estimate for it (setUp)
	2: Create three jobs - 1 single, 2 batched
	3: Update the first job with some arbitrary information or something
	4: Post a comment on the first job
	6: Perform a hell of a lot of GETs to the Gengo API to check stuff
	7: Delete the job if all went well (teardown phase)
	"""
	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.myGengo = MyGengo(public_key = public_key, private_key = private_key, api_version = '2', sandbox = SANDBOX)
		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.myGengo.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',
						'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.myGengo.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( 30 )
		resp = self.myGengo.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'])

	@unittest.skip("We don't test Gengo.getTranslationJobPreviewImage() because it's potentially resource heavy on the Gengo API.")
	def test_getTranslationJobPreviewImage(self):
		"""
			This test could be a bit more granular, but I'm undecided at the moment - testing the response stream
			of this method is more of a Unit Test for Gengo than Gengo. Someone can extend if they see fit, but I
			currently see no reason to mess with this further.
		"""
		img = self.myGengo.getTranslationJobPreviewImage(id = self.created_job_ids[0])
		self.assertIsNotNone(img)

	def test_postJobDataMethods(self):
		"""
			Tests all the Gengo methods that deal with updating jobs, posting comments, etc. test_getJobDataMethods() checks things,
			but they need to exist first - think of this as the alcoholic mother to _getJobDataMethods().
		"""
		# The 'update' method can't really be tested, as it requires the translator having actually done something before
		# it's of any use. Thing is, in automated testing, we don't really have a method to flip the switch on the Gengo end. If we
		# WERE to test this method, it'd look a little something like this:
		#
		#	updated_job = self.myGengo.updateTranslationJob(id = self.created_job_ids[0], action = {
		#		'action': 'purchase',
		#	})
		#	self.assertEqual(updated_job['opstat'], 'ok')

		posted_comment = self.myGengo.postTranslationJobComment(id = self.created_job_ids[0], comment = {
			'body': 'I love lamp oh mai gawd',
		})
		self.assertEqual(posted_comment['opstat'], 'ok')

	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.myGengo.getTranslationJob(id = self.created_job_ids[0])
		self.assertEqual(job['opstat'], 'ok')

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

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

		# Pull down the comment(s) we created earlier in this test suite.
		job_comments = self.myGengo.getTranslationJobComments(id = self.created_job_ids[0])
		self.assertEqual(job_comments['opstat'], 'ok')

		# Pull down feedback. This should work fine, but there'll be no feedback or anything, so... meh.
		feedback = self.myGengo.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.myGengo.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.myGengo.deleteTranslationJob(id = id)
			self.assertEqual(deleted_job['opstat'], 'ok')
Exemplo n.º 37
0
	def test_getAccountStats(self):
		myGengo = MyGengo(public_key = public_key, private_key = private_key, sandbox = SANDBOX)
		stats = myGengo.getAccountStats()
		self.assertEqual(stats['opstat'], 'ok')
Exemplo n.º 38
0
class TestTranslationJobFlowMixedOrder(unittest.TestCase):
    """
	Tests the flow of creating a job, updating it, getting the details, and then
	deleting the job for an order with mixed file/text jobs.

	Flow is as follows:

	1: Create a mock job and get an estimate for it (setUp)
	2: Create three jobs - 1 single, 2 batched
	3: Update the first job with some arbitrary information or something
	4: Post a comment on the first job
	6: Perform a hell of a lot of GETs to the Gengo API to check stuff
	7: Delete the job if all went well (teardown phase)
	"""
    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.myGengo = MyGengo(public_key=public_key,
                               private_key=private_key,
                               api_version='2',
                               sandbox=SANDBOX)
        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.myGengo.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',
                    '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.myGengo.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(30)
        resp = self.myGengo.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'])

    @unittest.skip(
        "We don't test Gengo.getTranslationJobPreviewImage() because it's potentially resource heavy on the Gengo API."
    )
    def test_getTranslationJobPreviewImage(self):
        """
			This test could be a bit more granular, but I'm undecided at the moment - testing the response stream
			of this method is more of a Unit Test for Gengo than Gengo. Someone can extend if they see fit, but I
			currently see no reason to mess with this further.
		"""
        img = self.myGengo.getTranslationJobPreviewImage(
            id=self.created_job_ids[0])
        self.assertIsNotNone(img)

    def test_postJobDataMethods(self):
        """
			Tests all the Gengo methods that deal with updating jobs, posting comments, etc. test_getJobDataMethods() checks things,
			but they need to exist first - think of this as the alcoholic mother to _getJobDataMethods().
		"""
        # The 'update' method can't really be tested, as it requires the translator having actually done something before
        # it's of any use. Thing is, in automated testing, we don't really have a method to flip the switch on the Gengo end. If we
        # WERE to test this method, it'd look a little something like this:
        #
        #	updated_job = self.myGengo.updateTranslationJob(id = self.created_job_ids[0], action = {
        #		'action': 'purchase',
        #	})
        #	self.assertEqual(updated_job['opstat'], 'ok')

        posted_comment = self.myGengo.postTranslationJobComment(
            id=self.created_job_ids[0],
            comment={
                'body': 'I love lamp oh mai gawd',
            })
        self.assertEqual(posted_comment['opstat'], 'ok')

    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.myGengo.getTranslationJob(id=self.created_job_ids[0])
        self.assertEqual(job['opstat'], 'ok')

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

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

        # Pull down the comment(s) we created earlier in this test suite.
        job_comments = self.myGengo.getTranslationJobComments(
            id=self.created_job_ids[0])
        self.assertEqual(job_comments['opstat'], 'ok')

        # Pull down feedback. This should work fine, but there'll be no feedback or anything, so... meh.
        feedback = self.myGengo.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.myGengo.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.myGengo.deleteTranslationJob(id=id)
            self.assertEqual(deleted_job['opstat'], 'ok')
Exemplo n.º 39
0
	def test_getServiceLanguages(self):
		myGengo = MyGengo(public_key = public_key, private_key = private_key, sandbox = SANDBOX)
		resp = myGengo.getServiceLanguages()
		self.assertEqual(resp['opstat'], 'ok')
# -*- coding: utf-8 -*-
#!/usr/bin/python

from mygengo import MyGengo

# Get an instance of MyGengo to work with...
gengo = MyGengo(
    public_key="your_public_key",
    private_key="your_private_key",
    sandbox=True,  # possibly false, depending on your dev needs
)

# Grab a specific revision - you could liken this to querying version control
# on the myGengo side. :)
print gengo.getTranslationJobRevision(id=42, revision_id=1)
Exemplo n.º 41
0
# -*- coding: utf-8 -*-
#!/usr/bin/python

from mygengo import MyGengo

# Get an instance of MyGengo to work with...
gengo = MyGengo(
    public_key = 'your_public_key',
    private_key = 'your_private_key',
    sandbox = True, # possibly false, depending on your dev needs
)

# 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 myGengo 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")
			
			'auto_approve': 0, # OPTIONAL. Hopefully self explanatory (1 = yes, 0 = no),
			'comment': 'HEY THERE TRANSLATOR', # OPTIONAL. Comment to leave for translator.
			'callback_url': 'http://...', # OPTIONAL. Callback URL that updates are sent to.
			'custom_data': 'your optional custom data, limited to 1kb.' # OPTIONAL
		},
		'job_2': {
			'type': 'text', # REQUIRED. Type to translate, you'll probably always put 'text' here. ;P
Exemplo n.º 42
0
# -*- coding: utf-8 -*-
#!/usr/bin/python

from mygengo import MyGengo

# This method doesn't require an instance of MyGengo, it's
# purely utility. You'll possibly end up using it to ensure
# that your data is utf-8 encoded before submitting it to myGengo;
# if your method calls fail, this is probably the first thing you should
# check!
MyGengo.unicode2utf8("私は")
Exemplo n.º 43
0
# -*- coding: utf-8 -*-
#!/usr/bin/python

from mygengo import MyGengo

# Get an instance of MyGengo to work with...
gengo = MyGengo(
    public_key = 'xpU@jqEzqnXCb#OOsAeR4z49IX|j}#dwyliMp2RIq1vM9OIKq-K#{mg~sVBUX^91',
    private_key = '~Q9hI|sV(I^iX7|8WQ=l5=CvUmEWx3[=c5ms09|$JIuT-$aiTIYkS4~1F7^C9dw3',
    sandbox = False, # possibly false, depending on your dev needs
)

# Print the account stats...
print gengo.getAccountStats()
Exemplo n.º 44
0
# -*- coding: utf-8 -*-
#!/usr/bin/python

from mygengo import MyGengo

# Get an instance of MyGengo to work with...
gengo = MyGengo(
    public_key='your_public_key',
    private_key='your_private_key',
    sandbox=True,  # possibly false, depending on your dev needs
)

# Very much like grabbing a comment history. Returns a data set, iterate
# if you want specifics!
print gengo.getTranslationJobFeedback(id=42)
# -*- coding: utf-8 -*-
#!/usr/bin/python

from mygengo import MyGengo

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

gengo = MyGengo(
    public_key = 'your_public_key',
    private_key = 'your_private_key',
    sandbox = False, # possibly false, depending on your dev needs
	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')
Exemplo n.º 46
0
# -*- coding: utf-8 -*-
#!/usr/bin/python

from mygengo import MyGengo
from pprint import pprint

mygengo = MyGengo(public_key='your public key',
                  private_key='your private key',
                  sandbox=False)

# Pretty-print a list of every supported language
pprint(mygengo.getServiceLanguages())
# -*- coding: utf-8 -*-
#!/usr/bin/python

from mygengo import MyGengo

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

gengo = MyGengo(
    public_key = 'xpU@jqEzqnXCb#OOsAeR4z49IX|j}#dwyliMp2RIq1vM9OIKq-K#{mg~sVBUX^91',
    private_key = '~Q9hI|sV(I^iX7|8WQ=l5=CvUmEWx3[=c5ms09|$JIuT-$aiTIYkS4~1F7^C9dw3',
    sandbox = False, # possibly false, depending on your dev needs
	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')
Exemplo n.º 48
0
 def test_MethodDoesNotExist(self):
     myGengo = MyGengo(public_key=public_key,
                       private_key=private_key,
                       sandbox=SANDBOX)
     # With how we do functions, AttributeError is a bit tricky to catch...
     self.assertRaises(AttributeError, getattr, myGengo, 'bert')
# -*- coding: utf-8 -*-
#!/usr/bin/python

from mygengo import MyGengo

# Get an instance of MyGengo to work with...
gengo = MyGengo(
    public_key = 'your_public_key',
    private_key = 'your_private_key',
    sandbox = True, # possibly false, depending on your dev needs
)

# Get every revision on a job. Returns a data set, iterate if need be!
print gengo.getTranslationJobRevisions(id = 42) 
Exemplo n.º 50
0
class TestTranslationSingleJobFlow(unittest.TestCase):
	"""
		Tests the flow of creating a job, updating it, getting the details, and then
		deleting the job. This is the thick of it!

		Flow is as follows:

			1: Create a mock job and get an estimate for it (setUp)
			2: Create three jobs - 1 single, 2 batched
			3: Update the first job with some arbitrary information or something
			4: Post a comment on the first job
			6: Perform a hell of a lot of GETs to the Gengo API to check stuff
			7: Delete the job if all went well (teardown phase)
	"""
	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.myGengo = MyGengo(public_key = public_key, private_key = private_key, sandbox = SANDBOX)
		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.myGengo.postTranslationJob(job = single_job)
		self.assertEqual(job['opstat'], 'ok')
		self.assertIsNotNone(job['response']['job']['job_id'])
		self.created_job_ids.append(job['response']['job']['job_id'])

	@unittest.skip("We don't test Gengo.getTranslationJobPreviewImage() because it's potentially resource heavy on the Gengo API.")
	def test_getTranslationJobPreviewImage(self):
		"""
			This test could be a bit more granular, but I'm undecided at the moment - testing the response stream
			of this method is more of a Unit Test for Gengo than Gengo. Someone can extend if they see fit, but I
			currently see no reason to mess with this further.
		"""
		img = self.myGengo.getTranslationJobPreviewImage(id = self.created_job_ids[0])
		self.assertIsNotNone(img)

	def test_postJobDataMethods(self):
		"""
			Tests all the Gengo methods that deal with updating jobs, posting comments, etc. test_getJobDataMethods() checks things,
			but they need to exist first - think of this as the alcoholic mother to _getJobDataMethods().
		"""
		# The 'update' method can't really be tested, as it requires the translator having actually done something before
		# it's of any use. Thing is, in automated testing, we don't really have a method to flip the switch on the Gengo end. If we
		# WERE to test this method, it'd look a little something like this:
		#
		#	updated_job = self.myGengo.updateTranslationJob(id = self.created_job_ids[0], action = {
		#		'action': 'purchase',
		#	})
		#	self.assertEqual(updated_job['opstat'], 'ok')

		posted_comment = self.myGengo.postTranslationJobComment(id = self.created_job_ids[0], comment = {
			'body': 'I love lamp oh mai gawd',
		})
		self.assertEqual(posted_comment['opstat'], 'ok')

	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.myGengo.getTranslationJob(id = self.created_job_ids[0])
		self.assertEqual(job['opstat'], 'ok')

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

		# Pull down the comment(s) we created earlier in this test suite.
		job_comments = self.myGengo.getTranslationJobComments(id = self.created_job_ids[0])
		self.assertEqual(job_comments['opstat'], 'ok')

		# Pull down feedback. This should work fine, but there'll be no feedback or anything, so... meh.
		feedback = self.myGengo.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.myGengo.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.myGengo.deleteTranslationJob(id = id)
			self.assertEqual(deleted_job['opstat'], 'ok')
Exemplo n.º 51
0
# -*- coding: utf-8 -*-
#!/usr/bin/python

from mygengo import MyGengo

# Get an instance of MyGengo to work with...
gengo = MyGengo(
    public_key='your_public_key',
    private_key='your_private_key',
    sandbox=True,  # possibly false, depending on your dev needs
)

# Exhaustive view, chances are your code will never be quite this verbose (programatically build this).
jobs_data = {
    '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 myGengo 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")
        'auto_approve':
        0,  # OPTIONAL. Hopefully self explanatory (1 = yes, 0 = no),
        'comment':
        'HEY THERE TRANSLATOR',  # OPTIONAL. Comment to leave for translator.
Exemplo n.º 52
0
def gengo_tm(text, sl, tl, tier='standard', auto_approve=True, public_key='', private_key='', sandbox = False, comment='', machine=True, ttl=300, callback_url=''):
    tt = cacheGet('/gengo/' + sl + '/' + tl + '/' + text)
    if tt is not None:
        return tt
    #
    # I didn't want to make this utility too App Engine specific, however, this is a place where the task queues come in handy.
    # You can use taskqueue.add(url=worker_url, params=p) to initiate a background task that queries the Gengo API and requests
    # a callback when the translation is done. The request handler that processes the callback would, in turn, write to the cache
    # so subsequent cacheGet() calls would return the now completed translation. I'll add this option in an update in the next week
    # or so, but am sticking with synchronous polling for now (its simple and doesn't depend on an App Engine specific resources). 
    #
    if auto_approve:
        auto_approve = 1
    else:
        auto_approve = 0
    if machine:
        machine = 1
    else:
        machine = 0
    #try:
    gengo = MyGengo(
        public_key = public_key,
        private_key = private_key,
        sandbox = sandbox, # possibly false, depending on your dev needs
    )
    if string.count(callback_url, 'http://') < 1 and string.count(callback_url, 'https://') < 1:
        response = gengo.postTranslationJob(job = {
            'type': 'text', # REQUIRED. Type to translate, you'll probably always put 'text' here. ;P
            'slug': 'Single :: Text Translation', # REQUIRED. Slug for internally storing, can be generic.
            'body_src': text, # REQUIRED. The text you're translating. ;P
            'lc_src': sl, # REQUIRED. source_language_code (see getServiceLanguages() for a list of codes)  
            'lc_tgt': tl, # REQUIRED. target_language_code (see getServiceLanguages() for a list of codes)
            'tier': tier, # REQUIRED. tier type ("machine", "standard", "pro", or "ultra")
            'machine': machine, # OPTIONAL. allow machine translation
            'auto_approve': 1, # OPTIONAL. Hopefully self explanatory (1 = yes, 0 = no),
            'comment': comment, # OPTIONAL. Comment to leave for translator.
            #'callback_url': '', # OPTIONAL. Callback URL that updates are sent to.
            #    'custom_data': 'your optional custom data, limited to 1kb.' # OPTIONAL
        })
    else:
        response = gengo.postTranslationJob(job = {
            'type': 'text', # REQUIRED. Type to translate, you'll probably always put 'text' here. ;P
            'slug': 'Single :: Text Translation', # REQUIRED. Slug for internally storing, can be generic.
            'body_src': text, # REQUIRED. The text you're translating. ;P
            'lc_src': sl, # REQUIRED. source_language_code (see getServiceLanguages() for a list of codes)  
            'lc_tgt': tl, # REQUIRED. target_language_code (see getServiceLanguages() for a list of codes)
            'tier': tier, # REQUIRED. tier type ("machine", "standard", "pro", or "ultra")
            'machine': machine, # OPTIONAL. allow machine translation
            'auto_approve': 1, # OPTIONAL. Hopefully self explanatory (1 = yes, 0 = no),
            'comment': comment, # OPTIONAL. Comment to leave for translator.
            'callback_url': callback_url, # OPTIONAL. Callback URL that updates are sent to.
            #    'custom_data': 'your optional custom data, limited to 1kb.' # OPTIONAL
        })        
    #try:
    tt = utf8(response['response']['job']['body_tgt'])
    if len(tt) > 0:
        cacheSet('/gengo/' + sl + '/' + tl + '/' + text, tt, ttl)
        text = tt
    return tt
        #except:
        #    tt = text
    ##except:
    #    return text
# -*- coding: utf-8 -*-
#!/usr/bin/python

from mygengo import MyGengo

# Get an instance of MyGengo to work with...
gengo = MyGengo(
    public_key = 'your_public_key',
    private_key = 'your_private_key',
    sandbox = True, # possibly false, depending on your dev needs
)

# Post a comment on a specific job; perhaps you have an update for the translator
# or something of the sort.
gengo.postTranslationJobComment(id = 42, comment = {
	'body': 'I love lamp!',
})
Exemplo n.º 54
0
# -*- coding: utf-8 -*-
#!/usr/bin/python

from mygengo import MyGengo

# Get an instance of MyGengo to work with...
gengo = MyGengo(
    public_key="your_public_key",
    private_key="your_private_key",
    sandbox=True,  # possibly false, depending on your dev needs
)

# 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 myGengo 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")
            "auto_approve": 0,  # OPTIONAL. Hopefully self explanatory (1 = yes, 0 = no),
            "comment": "HEY THERE TRANSLATOR",  # OPTIONAL. Comment to leave for translator.
            "callback_url": "http://...",  # OPTIONAL. Callback URL that updates are sent to.
            "custom_data": "your optional custom data, limited to 1kb.",  # OPTIONAL
        },
        "job_2": {
            "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.
Exemplo n.º 55
0
# -*- coding: utf-8 -*-
#!/usr/bin/python

from mygengo import MyGengo

# Get an instance of MyGengo to work with...
gengo = MyGengo(
    public_key='your_public_key',
    private_key='your_private_key',
    sandbox=True,  # possibly false, depending on your dev needs
)

# Delete a job!
gengo.deleteTranslationJob(id=42)
# -*- coding: utf-8 -*-
#!/usr/bin/python

from mygengo import MyGengo

# Get an instance of MyGengo to work with...
gengo = MyGengo(
    public_key = 'your_public_key',
    private_key = 'your_private_key',
    sandbox = True, # possibly false, depending on your dev needs
)

# Grab a specific revision - you could liken this to querying version control
# on the myGengo side. :)
print gengo.getTranslationJobRevision(id = 42, revision_id = 1)
Exemplo n.º 57
0
# -*- coding: utf-8 -*-
#!/usr/bin/python

from mygengo import MyGengo

# Get an instance of MyGengo to work with...
gengo = MyGengo(
    public_key = 'your_public_key',
    private_key = 'your_private_key',
    sandbox = True, # possibly false, depending on your dev needs
)

# 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)
Exemplo n.º 58
0
class TestTranslationJobFlow(unittest.TestCase):
    """
		Tests the flow of creating a job, updating it, getting the details, and then 
		deleting the job. This is the thick of it!
		
		Flow is as follows:
		
			1: Create a mock job and get an estimate for it (setUp)
			2: Create three jobs - 1 single, 2 batched
			3: Update the first job with some arbitrary information or something
			4: Post a comment on the first job
			6: Perform a hell of a lot of GETs to the myGengo API to check stuff
			7: Delete the job if all went well (teardown phase)
	"""
    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.myGengo = MyGengo(public_key=public_key,
                               private_key=private_key,
                               sandbox=SANDBOX)
        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,
        }

        multiple_jobs = {
            'job_1': {
                'type':
                'text',
                'slug':
                'Multiple :: English to Japanese',
                'body_src':
                'H%dow i%ds th%de weather?' % (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',
            },
            'job_2': {
                'type':
                'text',
                'slug':
                'Multiple :: Japanese To English',
                'body_src':
                '天%d気%dはど%dうですか' % (int(random.randrange(
                    1, 226, 1)), int(random.randrange(
                        1, 226, 1)), int(random.randrange(1, 226, 1))),
                'lc_src':
                'ja',
                'lc_tgt':
                'en',
                'tier':
                'ultra',
            },
        }

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

        # If that method worked, sweet. Move on and create three jobs, store their IDs. Make sure we got an ID
        # back, since these methods are otherwise largely useless without that returned data. These tests walk a fine
        # line between testing myGengo and the myGengo API functionality as a whole - watch yourself if you add to this. :)
        job = self.myGengo.postTranslationJob(job=single_job)
        self.assertEqual(job['opstat'], 'ok')
        self.assertIsNotNone(job['response']['job']['job_id'])
        self.created_job_ids.append(job['response']['job']['job_id'])

        jobs = self.myGengo.postTranslationJobs(jobs={'jobs': multiple_jobs})
        self.assertEqual(job['opstat'], 'ok')

        # This is a fairly ugly way to check for and retrieve job IDs; in an ideal system you know the keys, and... well,
        # truthfully we do here too. I suppose this is moreso here as an example of how to get IDs in a situation where you
        # don't know the keys. May or may not be useful to some.
        for job_obj in jobs['response']['jobs']:
            for job in job_obj:
                self.assertIsNotNone(job_obj[job]['job_id'])
                self.created_job_ids.append(job_obj[job]['job_id'])

    @unittest.skip(
        "We don't test myGengo.getTranslationJobPreviewImage() because it's potentially resource heavy on the myGengo API."
    )
    def test_getTranslationJobPreviewImage(self):
        """
			This test could be a bit more granular, but I'm undecided at the moment - testing the response stream
			of this method is more of a Unit Test for myGengo than myGengo. Someone can extend if they see fit, but I 
			currently see no reason to mess with this further.
		"""
        img = self.myGengo.getTranslationJobPreviewImage(
            id=self.created_job_ids[0])
        self.assertIsNotNone(img)

    def test_postJobDataMethods(self):
        """
			Tests all the myGengo methods that deal with updating jobs, posting comments, etc. test_getJobDataMethods() checks things,
			but they need to exist first - think of this as the alcoholic mother to _getJobDataMethods().
		"""
        # The 'update' method can't really be tested, as it requires the translator having actually done something before
        # it's of any use. Thing is, in automated testing, we don't really have a method to flip the switch on the myGengo end. If we
        # WERE to test this method, it'd look a little something like this:
        #
        #	updated_job = self.myGengo.updateTranslationJob(id = self.created_job_ids[0], action = {
        #		'action': 'purchase',
        #	})
        #	self.assertEqual(updated_job['opstat'], 'ok')

        posted_comment = self.myGengo.postTranslationJobComment(
            id=self.created_job_ids[0],
            comment={
                'body': 'I love lamp oh mai gawd',
            })
        self.assertEqual(posted_comment['opstat'], 'ok')

    def test_getJobDataMethods(self):
        """
			Test a ton of methods that GET data from the myGengo 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.myGengo.getTranslationJob(id=self.created_job_ids[0])
        self.assertEqual(job['opstat'], 'ok')

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

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

        # Pull down the comment(s) we created earlier in this test suite.
        job_comments = self.myGengo.getTranslationJobComments(
            id=self.created_job_ids[0])
        self.assertEqual(job_comments['opstat'], 'ok')

        # Pull down feedback. This should work fine, but there'll be no feedback or anything, so... meh.
        feedback = self.myGengo.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.myGengo.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.myGengo.deleteTranslationJob(id=id)
            self.assertEqual(deleted_job['opstat'], 'ok')