예제 #1
0
    def bt_connect(self):
        username = self.entry_username.text
        password = self.entry_password.text  # DO NOT remember password (not safe)
        project = self.combo_projects.text
        try:
            # Todo: make connection in separate thread
            self.tx = TransifexAPI(username, password, 'https://www.transifex.com')
            assert self.tx.ping(), 'No connection to the server'
            assert self.tx.project_exists(project), "Project %r does not exist" % project
            self.resources = self.tx.list_resources(project)
            languages = self.tx.list_languages(project, resource_slug=self.resources[0]['slug'])
        except (TransifexAPIException, requests.exceptions.ConnectionError, AssertionError) as err:
            messagebox.showerror('Error', err)
        except:
            messagebox.showerror('Unexpected error', traceback.format_exc())
        else:
            self.combo_languages.values = sorted(languages)
            last_language = self.config.get('language', None)
            if last_language and last_language in languages:
                self.combo_languages.text = last_language
            else:
                self.combo_languages.current(0)
            
            self.listbox_resources.clear()
            self.listbox_resources.values = tuple(res['name'] for res in self.resources)
            
            self.config['username'] = username

            recent_projects = self.config['recent_projects']
            if recent_projects or project != recent_projects[0]:
                if project in recent_projects:
                    recent_projects.remove(project)
                recent_projects.insert(0, project)
            self.combo_projects.values = recent_projects
예제 #2
0
 def setUp(self):
     data = {
         'username': '******',
         'password': '******',
         'host': 'http://www.mydomain.com'
     }
     self.api = TransifexAPI(**data)
예제 #3
0
def get_translation_transifix(lang,
                              username="******",
                              password="******"):
    # print args.language
    t = TransifexAPI(username, password, 'https://www.transifex.com')
    # check success connection to transefix database
    print t.ping()
    print "connected to database"
    #check if project exists
    print t.project_exists("via-operational-center")
    print "found the via translations project"
    list1 = t.list_resources("via-operational-center")
    print list1

    t.get_translation('via-operational-center', "voc-fe-en-usjson", lang,
                      "/translation.json")

    with open("translation.json", "a") as f:
        f.write("; \n export default translations")

    with open("translation.json", "r+") as f:
        origin = f.read()  # read everything in the file
        f.seek(0)  # rewind
        f.write(
            "import {Translations} from \"src/constants/locales/translations\"; "
            "\n\nconst translations: Translations = " + origin)
    print "finished successfully!"
    return
예제 #4
0
class TransifexAPITest(TestCase):
    
    def setUp(self):
        data = {
            'username': '******', 'password': '******',
            'host': 'http://www.mydomain.com'
        }
        self.api = TransifexAPI(**data)
        
    @patch('requests.post')
    def test_new_project_with_required_args(self, mock_requests):
        """
        Test creating a new project with only the required arguments
        """

        def side_effect(*args, **kwargs):
            response = Mock()
            data = json.loads(kwargs.get('data', "{}"))
            if 'source_language_code' in data and 'name' in data and 'slug' in \
            data:
                response.status_code = 201
            else:
                response.status_code = 400
                
            return response
        
        mock_requests.side_effect = side_effect 
        self.api.new_project(slug='abc')
    
    def test_new_project_bad_slug(self):
        """
        Test the `new_project` api call when the slug is invalid
        """
        self.assertRaises(TransifexAPIException, self.api.new_project,
            slug='.'
        )
        self.assertRaises(TransifexAPIException, self.api.new_project,
            slug='/'
        )
        self.assertRaises(TransifexAPIException, self.api.new_project,
            slug='%@$'
        )
        
    @patch('requests.post')
    def test_new_project_with_optional_args(self, mock_requests):
        """
        Test creating a new project with the optional arguments
        """

        def side_effect(*args, **kwargs):
            response = Mock()
            data = json.loads(kwargs.get('data', "{}"))
            if 'source_language_code' in data and 'name' in data and 'slug' in \
            data:
                response.status_code = 201
            else:
                response.status_code = 400
                
            return response
        
        mock_requests.side_effect = side_effect 
        self.api.new_project(
            slug='abc', name='abc', source_language_code='pt',
            outsource_project_name='anotherproject'
        )
        
    @patch('requests.post')
    def test_new_project_with_http_response_400(self, mock_requests):
        """
        Test creating a new project when the transifex server returns a
        '400 BAD REQUEST' response 
        """

        def side_effect(*args, **kwargs):
            response = Mock()
            response.status_code = 400
            return response
        
        mock_requests.side_effect = side_effect 
        self.assertRaises(
            TransifexAPIException, self.api.new_project, slug='abc'
        )
        
    @patch('requests.get')
    def test_list_resources(self, mock_requests):
        """
        Test the `list_resources` api call
        """
        response_content = [{'a':1}, {'b':2}]

        def side_effect(*args, **kwargs):
            response = Mock()
            response.status_code = 200
            response.content = json.dumps(response_content)
            return response
        
        mock_requests.side_effect = side_effect 
        resources = self.api.list_resources(project_slug='abc')
        self.assertEqual(resources, response_content)
        
    @patch('requests.get')
    def test_list_resources_with_bad_project_name(self, mock_requests):
        """
        Test the 'list resources' api call, when the project name given
        doesn't exist on the transifex server
        """
        def side_effect(*args, **kwargs):
            response = Mock()
            response.status_code = 404
            return response
        
        mock_requests.side_effect = side_effect 
        self.assertRaises(
            TransifexAPIException, self.api.list_resources, project_slug='abc'
        )
                
    @patch('__builtin__.open', create=True)
    @patch('requests.post')
    def test_new_resource(self, mock_requests, mock_open):
        """
        Test the `new_resource` api call
        """
        file_contents = 'aaaaaa\nggggg'
        mock_open.return_value = MagicMock(spec=file)
        mock_open.return_value.read = lambda: file_contents
        
        required_post_params = ['name', 'slug', 'content', 'i18n_type']
        def side_effect(*args, **kwargs):
            response = Mock()
            response.status_code = 201
            data = json.loads(kwargs.get('data', "{}"))
            for param in required_post_params:
                if param not in data:
                    response.status_code = 400
                    response.content = '%r is required'
                    break
                
            return response

        mock_requests.side_effect = side_effect

        self.api.new_resource(
            project_slug='abc', path_to_pofile='/abc/pofile.po'
        )
        self.assertTrue(mock_requests.called)
        __, kwargs = mock_requests.call_args
        self.assertTrue('data' in kwargs)
        data = json.loads(kwargs['data'])
        self.assertEqual(data['content'], file_contents)
        
    
    @patch('__builtin__.open', create=True)
    def test_new_resource_file_not_found(self, mock_open):
        """
        Test the `new_resource` api call when the pofile cannot be found
        """
        def side_effect(*args, **kwargs):
            raise IOError('File not found')
        
        mock_open.side_effect = side_effect
        self.assertRaises(IOError, self.api.new_resource,
            project_slug='abc', path_to_pofile='/aaa/file.po'
        )
    
    @patch('__builtin__.open', create=True)
    def test_new_resource_bad_slug(self, mock_open):
        """
        Test the `new_resource` api call when the slug is invalid
        """
        file_contents = 'aaaaaa\nggggg'
        mock_open.return_value = MagicMock(spec=file)
        mock_open.return_value.read = lambda: file_contents
        
        self.assertRaises(TransifexAPIException, self.api.new_resource,
            project_slug='aaa', resource_slug='.', path_to_pofile='/aaa/file.po'
        )
        self.assertRaises(TransifexAPIException, self.api.new_resource,
            project_slug='aaa', resource_slug='/', path_to_pofile='/aaa/file.po'
        )
        self.assertRaises(TransifexAPIException, self.api.new_resource,
            project_slug='aaa', resource_slug='%@$',
            path_to_pofile='/aaa/file.po'
        )
        
    @patch('__builtin__.open', create=True)
    @patch('requests.post')
    def test_new_resource_server_error(self, mock_requests, mock_open):
        """
        Test the `new_resource` api call when the transifex server returns an
        error 
        """
        file_contents = 'aaaaaa\nggggg'
        mock_open.return_value = MagicMock(spec=file)
        mock_open.return_value.read = lambda: file_contents
        
        def side_effect(*args, **kwargs):
            response = Mock()
            response.status_code = 404
            return response
        
        mock_requests.side_effect = side_effect
        self.assertRaises(
            TransifexAPIException, self.api.new_resource,
            project_slug='abc', path_to_pofile='/aaa/file.po'
        )
        
    @patch('__builtin__.open', create=True)
    @patch('requests.post')
    def test_new_resource_with_optional_args(self, mock_requests, mock_open):
        """
        Test the `new_resource` api call with the optional args
        """
        file_contents = 'aaaaaa\nggggg'
        mock_open.return_value = MagicMock(spec=file)
        mock_open.return_value.read = lambda: file_contents
        
        required_post_params = ['name', 'slug', 'content', 'i18n_type']
        def side_effect(*args, **kwargs):
            response = Mock()
            response.status_code = 201
            data = json.loads(kwargs.get('data', "{}"))
            for param in required_post_params:
                if param not in data:
                    response.status_code = 400
                    response.content = '%r is required'
                    break
                
            return response

        mock_requests.side_effect = side_effect

        self.api.new_resource(
            project_slug='abc', path_to_pofile='/abc/pofile.po',
            resource_slug='def', resource_name='A Name'
        )
        self.assertTrue(mock_requests.called)
                
    @patch('__builtin__.open', create=True)
    @patch('requests.put')
    def test_update_source_translation(self, mock_requests, mock_open):
        """
        Test the `update_source_translation` api call
        """
        file_contents = 'aaaaaa\nggggg'
        mock_open.return_value = MagicMock(spec=file)
        mock_open.return_value.read = lambda: file_contents
        
        required_post_params = ['content', ]
        def side_effect(*args, **kwargs):
            response = Mock()
            data = json.loads(kwargs.get('data', "{}"))
            for param in required_post_params:
                if param not in data:
                    response.status_code = 400
                    response.content = '%r is required'
                    return response
                
            response.status_code = 200
            response.content = json.dumps({'a':1})
            return response

        mock_requests.side_effect = side_effect

        self.api.update_source_translation(
            project_slug='abc', resource_slug='def',
            path_to_pofile='/abc/pofile.po'
        )
        self.assertTrue(mock_requests.called)
        
    
    @patch('__builtin__.open', create=True)
    def test_update_source_translation_file_not_found(self, mock_open):
        """
        Test the `update_source_translation` api call when the pofile cannot be found
        """
        def side_effect(*args, **kwargs):
            raise IOError('File not found')
        
        mock_open.side_effect = side_effect
        self.assertRaises(IOError, self.api.update_source_translation,
            project_slug='abc', resource_slug='def',
            path_to_pofile='/aaa/file.po'
        )
        
    @patch('__builtin__.open', create=True)
    @patch('requests.put')
    def test_update_source_translation_server_error(self, mock_requests,
                                                    mock_open):
        """
        Test the `update_source_translation` api call when the transifex server
        returns an error 
        """
        file_contents = 'aaaaaa\nggggg'
        mock_open.return_value = MagicMock(spec=file)
        mock_open.return_value.read = lambda: file_contents
        
        def side_effect(*args, **kwargs):
            response = Mock()
            response.status_code = 404
            return response
        
        mock_requests.side_effect = side_effect
        self.assertRaises(
            TransifexAPIException, self.api.update_source_translation,
            project_slug='abc', resource_slug='def',
            path_to_pofile='/aaa/file.po'
        )
        
    @patch('__builtin__.open', create=True)
    @patch('requests.put')
    def test_new_translation(self, mock_requests, mock_open):
        """
        Test the `new_translation` api call
        """
        file_contents = 'aaaaaa\nggggg'
        mock_open.return_value = MagicMock(spec=file)
        mock_open.return_value.read = lambda: file_contents
        
        required_post_params = ['content', ]
        def side_effect(*args, **kwargs):
            response = Mock()
            data = json.loads(kwargs.get('data', "{}"))
            for param in required_post_params:
                if param not in data:
                    response.status_code = 400
                    response.content = '%r is required'
                    return response
                
            response.status_code = 200
            response.content = json.dumps({'s':1})
            return response

        mock_requests.side_effect = side_effect
        
        self.api.new_translation(
            project_slug='abc', resource_slug='def', language_code='pt',
            path_to_pofile='/abc/pofile.po'
        )
        self.assertTrue(mock_requests.called)
        
    
    @patch('__builtin__.open', create=True)
    def test_new_translation_file_not_found(self, mock_open):
        """
        Test the `new_translation` api call when the pofile cannot be found
        """
        def side_effect(*args, **kwargs):
            raise IOError('File not found')
        
        mock_open.side_effect = side_effect
        self.assertRaises(IOError, self.api.new_translation,
            project_slug='abc', resource_slug='def', language_code='pt',
            path_to_pofile='/aaa/file.po'
        )
        
    @patch('__builtin__.open', create=True)
    @patch('requests.put')
    def test_new_translation_server_error(self, mock_requests,
                                                    mock_open):
        """
        Test the `new_translation` api call when the transifex server
        returns an error 
        """
        file_contents = 'aaaaaa\nggggg'
        mock_open.return_value = MagicMock(spec=file)
        mock_open.return_value.read = lambda: file_contents
        
        def side_effect(*args, **kwargs):
            response = Mock()
            response.status_code = 404
            return response
        
        mock_requests.side_effect = side_effect
        self.assertRaises(
            TransifexAPIException, self.api.new_translation,
            project_slug='abc', resource_slug='def', language_code='pt',
            path_to_pofile='/aaa/file.po'
        )
        
    @patch('__builtin__.open', create=True)
    @patch('requests.get')
    def test_get_translation(self, mock_requests, mock_open):
        """
        Test the `get_translation` api call
        """
        mock_open.return_value = MagicMock(spec=file)
        
        def side_effect(*args, **kwargs):
            mock_response = Mock()
            mock_response.status_code = 200
            mock_response.iter_content = lambda: 'abc\ndef\n'
            return mock_response

        mock_requests.side_effect = side_effect
        
        self.api.get_translation(
            project_slug='abc', resource_slug='def', language_code='pt',
            path_to_pofile='/abc/pofile.po'
        )
        self.assertTrue(mock_requests.called)
        
    
    @patch('__builtin__.open', create=True)
    @patch('requests.get')
    def test_get_translation_file_not_found(self, mock_requests, mock_open):
        """
        Test the `get_translation` api call when the pofile cannot be found
        """
        def open_side_effect(*args, **kwargs):
            raise IOError('File not found')
        
        mock_open.side_effect = open_side_effect
        
        def requests_side_effect(*args, **kwargs):
            mock_response = Mock()
            mock_response.status_code = 200
            mock_response.iter_content = lambda: 'abc\ndef\n'
            return mock_response

        mock_requests.side_effect = requests_side_effect
        
        self.assertRaises(IOError, self.api.get_translation,
            project_slug='abc', resource_slug='def', language_code='pt',
            path_to_pofile='/abc/pofile.po'
        )
        
    @patch('requests.get')
    def test_get_translation_server_error(self, mock_requests):
        """
        Test the `get_translation` api call when the transifex server
        returns an error 
        """
        
        def side_effect(*args, **kwargs):
            response = Mock()
            response.status_code = 404
            return response
        
        mock_requests.side_effect = side_effect
        self.assertRaises(
            TransifexAPIException, self.api.get_translation,
            project_slug='abc', resource_slug='def', language_code='pt',
            path_to_pofile='/abc/pofile.po'
        )
        
        
        
    @patch('requests.delete')
    def test_delete_resource(self, mock_requests):
        """
        Test the `delete_resource` api call
        """
        
        def side_effect(*args, **kwargs):
            mock_response = Mock()
            mock_response.status_code = 204
            return mock_response

        mock_requests.side_effect = side_effect
        
        self.api.delete_resource(project_slug='abc', resource_slug='def')
        self.assertTrue(mock_requests.called)
        
    
        
    @patch('requests.delete')
    def test_delete_resource_server_error(self, mock_requests):
        """
        Test the `delete_resource` api call when the transifex server
        returns an error 
        """
        
        def side_effect(*args, **kwargs):
            response = Mock()
            response.status_code = 404
            return response
        
        mock_requests.side_effect = side_effect
        self.assertRaises(
            TransifexAPIException, self.api.delete_resource,
            project_slug='abc', resource_slug='def'
        )

    @patch('requests.get')
    def test_list_languages(self, mock_requests):
        """
        Test the `list_languages` api call
        """
        expected_languages = ['en_GB', 'it']
        response_content = {
            'slug': 'txo',
            'mimetype': 'text/x-po',
            'source_language_code': 'en',
            'wordcount': 6160,
            'total_entities': 1017,
            'last_update': '2011-12-05 19:59:55',
            'available_languages': [
                {
                    'code_aliases': ' ',
                    'code': 'it',
                    'name': 'Italian'
                },
                {
                    'code_aliases': 'en-gb',
                    'code': 'en_GB',
                    'name': 'English (Great Britain)'
                },
            ],
        }

        def side_effect(*args, **kwargs):
            response = Mock()
            response.status_code = 200
            response.content = json.dumps(response_content)
            return response
        
        mock_requests.side_effect = side_effect 
        languages = self.api.list_languages(
            project_slug='abc', resource_slug='def'
        )
        self.assertEqual(sorted(expected_languages), sorted(languages))

    @patch('requests.get')
    def test_list_languages_404(self, mock_requests):
        """
        Test the `list_languages` api call when the project or resource is not
        found
        """
        def side_effect(*args, **kwargs):
            response = Mock()
            response.status_code = 404
            return response
        
        mock_requests.side_effect = side_effect 
        self.assertRaises(
            TransifexAPIException, self.api.list_languages, project_slug='abc',
            resource_slug='defg'
        )
        
    @patch('requests.get')
    def test_project_exists(self, mock_requests):
        """
        Test the `test_project_exists` api call
        """
        def side_effect(*args, **kwargs):
            response = Mock()
            response.status_code = 200
            return response

        mock_requests.side_effect = side_effect
        self.assertTrue(self.api.project_exists(project_slug='abc'))
        
    @patch('requests.get')
    def test_project_exists_with_no_project(self, mock_requests):
        """
        Test the `test_project_exists` api call when the project doesn't exist
        """
        def side_effect(*args, **kwargs):
            response = Mock()
            response.status_code = 404
            return response
        
        mock_requests.side_effect = side_effect
        self.assertFalse(self.api.project_exists(project_slug='abc'))

    @patch('requests.get')
    def test_project_exists_with_error(self, mock_requests):
        """
        Test the `test_project_exists` api call when the api returns an error
        """
        def side_effect(*args, **kwargs):
            response = Mock()
            response.status_code = 400
            return response
        
        mock_requests.side_effect = side_effect         
        self.assertRaises(
            TransifexAPIException, self.api.project_exists, project_slug='abc'
        )
예제 #5
0
 def setUp(self):
     data = {
         'username': '******', 'password': '******',
         'host': 'http://www.mydomain.com'
     }
     self.api = TransifexAPI(**data)
예제 #6
0
    while True:
        sys.stdout.write(question + prompt)
        choice = raw_input().lower()
        if default is not None and choice == '':
            return valid[default]
        elif choice in valid:
            return valid[choice]
        else:
            sys.stdout.write(
                "Please respond with 'yes' or 'no' (or 'y' or 'n').\n")


# # Create the basic object
print 'Uploading strings to the Transifex server'
transifexAPI = TransifexAPI(USERNAME, PASSWORD, SERVER_URL)
if (transifexAPI.ping()):
    print 'Connected to the server'
else:
    print 'Error connecting to the server'

PROJECT_SLUG = 'math-calculator'
RESOURCE_SLUG = 'stringsxml'
LOCAL_STRING_LOCATION = './app/src/main/res/values/strings.xml'
SOURCE_LANGUAGE = 'en'
TEMP_STRINGS = 'strings.temp.xml'

# # 1. Download the english translation
print 'Comparing the local string with the string on the Transifex server'
transifexAPI.get_translation(PROJECT_SLUG, RESOURCE_SLUG, SOURCE_LANGUAGE,
                             TEMP_STRINGS)
class DownloadTranslationsFrame(tk.Frame):
    def bt_connect(self):
        username = self.entry_username.text
        password = self.entry_password.text  # DO NOT remember password (not safe)
        project = self.combo_projects.text
        try:
            # Todo: make connection in separate thread
            self.tx = TransifexAPI(username, password,
                                   'https://www.transifex.com')
            assert self.tx.ping(), 'No connection to the server'
            assert self.tx.project_exists(
                project), "Project %r does not exist" % project
            self.resources = self.tx.list_resources(project)
            languages = self.tx.list_languages(
                project, resource_slug=self.resources[0]['slug'])
        except (TransifexAPIException, requests.exceptions.ConnectionError,
                AssertionError) as err:
            messagebox.showerror('Error', err)
        except:
            messagebox.showerror('Unexpected error', traceback.format_exc())
        else:
            self.combo_languages.values = sorted(languages)
            last_language = self.config.get('language', None)
            if last_language and last_language in languages:
                self.combo_languages.text = last_language
            else:
                self.combo_languages.current(0)

            self.listbox_resources.clear()
            self.listbox_resources.values = tuple(res['name']
                                                  for res in self.resources)

            self.config['username'] = username

            recent_projects = self.config['recent_projects']
            if recent_projects or project != recent_projects[0]:
                if project in recent_projects:
                    recent_projects.remove(project)
                recent_projects.insert(0, project)
            self.combo_projects.values = recent_projects

    def download_waiter(self,
                        resources,
                        language,
                        project,
                        download_dir,
                        parent_conn=None,
                        initial_names=None,
                        resource_names=None,
                        i=0):
        if initial_names is None:
            initial_names = [res['name'] for res in self.resources]
            resource_names = initial_names.copy()

        if self.download_process is None:
            parent_conn, child_conn = mp.Pipe()

            self.download_process = mp.Process(
                target=downloader,
                kwargs=dict(conn=child_conn,
                            tx=self.tx,
                            project=project,
                            language=language,
                            resources=resources,
                            file_path_pattern=path.join(
                                download_dir, '%s_' + language + '.po')))
            self.download_process.start()

        while parent_conn.poll() or not self.download_process.is_alive():
            if parent_conn.poll():
                i, message = parent_conn.recv()
            else:
                i, message = i, 'stopped'

            if message == 'completed':
                # Everything is downloaded
                self.download_process.join()
                self.download_process = None
                self.button_download.reset_state()
                self.download_started = False

                self.config['language'] = language

                if sys.platform == 'win32':
                    subprocess.Popen('explorer "%s"' %
                                     (download_dir.replace('/', '\\')))
                else:
                    pass  # Todo: open the directory in a file manager on linux

                return

            resource_names[i] = '{} - {}'.format(initial_names[i], message)
            self.listbox_resources.values = resource_names
            self.update()

            if message == 'ok!':
                self.progressbar.step()
                break
            elif message == 'failed':
                error = parent_conn.recv()
                self.download_process.join()
                self.download_process = None
                self.button_download.reset_state()
                self.download_started = False
                messagebox.showerror('Downloading error', error)
                return
            elif message == 'stopped':
                self.download_process = None
                self.button_download.reset_state()
                self.download_started = False
                return

        self.after(100, self.download_waiter, resources, language, project,
                   download_dir, parent_conn, initial_names, resource_names, i)

    def bt_download(self):
        if self.tx and self.resources and not self.download_started:
            self.progressbar['maximum'] = len(self.resources) * 1.001
            self.progressbar['value'] = 0

            download_dir = self.fileentry_download_to.text
            if not download_dir:
                messagebox.showwarning('Directory not specified',
                                       'Specify download directory first')
                return
            else:
                self.config['download_to'] = download_dir

            if not path.exists(download_dir):
                messagebox.showerror('Directory does not exist',
                                     'Specify existing directory first')
                return

            project = self.combo_projects.get()
            language = self.combo_languages.get()

            initial_names = [res['name'] for res in self.resources]
            resource_names = list(initial_names)

            self.listbox_resources.values = resource_names
            self.download_started = True
            self.download_waiter(self.resources, language, project,
                                 download_dir)
            return True

    def bt_stop_downloading(self):
        r = messagebox.showwarning('Are you sure?',
                                   'Stop downloading?',
                                   type=messagebox.OKCANCEL)
        if r == 'cancel':
            return False
        else:
            self.download_process.terminate()
            return True

    def kill_processes(self, _):
        if self.download_process and self.download_process.is_alive():
            self.download_process.terminate()

    def __init__(self, master, config: Config):
        super().__init__(master)

        self.config = init_section(
            config,
            section_name='download_translations',
            defaults=dict(recent_projects=['dwarf-fortress']))

        tk.Label(self, text='Transifex project:').grid()

        self.combo_projects = ComboboxCustom(
            self, values=self.config['recent_projects'])
        self.combo_projects.current(0)
        self.combo_projects.grid(column=1, row=0, sticky=tk.W + tk.E)

        tk.Label(self, text='Username:'******'username', '')
        self.entry_username.grid(column=1, row=1, sticky=tk.W + tk.E)

        tk.Label(self, text='Password:'******'\u2022')  # 'bullet' symbol
        self.entry_password.grid(column=1, row=2, sticky=tk.W + tk.E)

        button_connect = ttk.Button(self,
                                    text='Connect...',
                                    command=self.bt_connect)
        button_connect.grid(row=0,
                            column=2,
                            rowspan=3,
                            sticky=tk.N + tk.S + tk.W + tk.E)

        ttk.Separator(self, orient=tk.HORIZONTAL).grid(columnspan=3,
                                                       sticky=tk.W + tk.E,
                                                       pady=5)

        tk.Label(self, text='Choose language:').grid(column=0)

        self.combo_languages = ComboboxCustom(self)
        self.combo_languages.grid(column=1, row=4, sticky=tk.W + tk.E)

        # self.chk_all_languages = CheckbuttonVar(self, text='All languages (backup)')
        # self.chk_all_languages.grid(column=1)

        ttk.Separator(self, orient=tk.HORIZONTAL).grid(columnspan=3,
                                                       sticky=tk.W + tk.E,
                                                       pady=5)

        tk.Label(self, text='Download to:').grid()

        self.fileentry_download_to = FileEntry(
            self,
            dialogtype='askdirectory',
            default_path=self.config.get('download_to', ''),
            on_change=lambda text: check_and_save_path(self.config,
                                                       'download_to', text),
        )

        self.fileentry_download_to.grid(column=1,
                                        row=6,
                                        columnspan=2,
                                        sticky='WE')

        self.button_download = TwoStateButton(
            self,
            text='Download translations',
            command=self.bt_download,
            text2='Stop',
            command2=self.bt_stop_downloading)
        self.button_download.grid(sticky=tk.W + tk.E)

        self.progressbar = ttk.Progressbar(self)
        self.progressbar.grid(column=1,
                              row=7,
                              columnspan=2,
                              sticky=tk.W + tk.E)

        tk.Label(self, text='Resources:').grid(columnspan=3)

        self.listbox_resources = ListboxCustom(self)
        self.listbox_resources.grid(column=0,
                                    columnspan=3,
                                    sticky=tk.E + tk.W + tk.N + tk.S)

        self.grid_columnconfigure(1, weight=1)
        self.grid_rowconfigure(9, weight=1)

        self.resources = None
        self.tx = None
        self.download_started = False
        self.download_process = None

        self.bind('<Destroy>', self.kill_processes)
예제 #8
0
class TransifexAPITest(TestCase):
    def setUp(self):
        data = {
            'username': '******',
            'password': '******',
            'host': 'http://www.mydomain.com'
        }
        self.api = TransifexAPI(**data)

    @patch('requests.post')
    def test_new_public_project_with_required_args(self, mock_requests):
        """
        Test creating a new project with only the required arguments
        """
        mock_requests.side_effect = _check_for_new_project_kwargs
        self.api.new_project(slug='abc', repository_url='http://abc.com')

    def test_new_project_bad_slug(self):
        """
        Test the `new_project` api call when the slug is invalid
        """
        self.assertRaises(InvalidSlugException, self.api.new_project, slug='.')
        self.assertRaises(InvalidSlugException, self.api.new_project, slug='/')
        self.assertRaises(InvalidSlugException,
                          self.api.new_project,
                          slug='%@$')

    def test_new_project_no_repository_url(self):
        """
        Test the `new_project` api call when no repository_url is passed to a
        public project
        """
        self.assertRaises(TransifexAPIException,
                          self.api.new_project,
                          slug='fdsfs',
                          private=False)

    @patch('requests.post')
    def test_new_project_with_optional_args(self, mock_requests):
        """
        Test creating a new project with the optional arguments
        """
        def side_effect(*args, **kwargs):
            response = Mock()
            data = json.loads(kwargs.get('data', "{}"))
            if 'source_language_code' in data and 'name' in data and 'slug' in \
            data:
                response.status_code = 201
            else:
                response.status_code = 400

            return response

        mock_requests.side_effect = side_effect
        self.api.new_project(slug='abc',
                             name='abc',
                             source_language_code='pt',
                             outsource_project_name='anotherproject')

    @patch('requests.post')
    def test_new_project_with_http_response_400(self, mock_requests):
        """
        Test creating a new project when the transifex server returns a
        '400 BAD REQUEST' response
        """
        def side_effect(*args, **kwargs):
            response = Mock()
            response.status_code = 400
            return response

        mock_requests.side_effect = side_effect
        self.assertRaises(TransifexAPIException,
                          self.api.new_project,
                          slug='abc')

    @patch('requests.get')
    def test_list_resources(self, mock_requests):
        """
        Test the `list_resources` api call
        """
        response_content = [{'a': 1}, {'b': 2}]

        def side_effect(*args, **kwargs):
            response = Mock()
            response.status_code = 200
            response.content = json.dumps(response_content)
            return response

        mock_requests.side_effect = side_effect
        resources = self.api.list_resources(project_slug='abc')
        self.assertEqual(resources, response_content)

    @patch('requests.get')
    def test_list_resources_with_bad_project_name(self, mock_requests):
        """
        Test the 'list resources' api call, when the project name given
        doesn't exist on the transifex server
        """
        def side_effect(*args, **kwargs):
            response = Mock()
            response.status_code = 404
            return response

        mock_requests.side_effect = side_effect
        self.assertRaises(TransifexAPIException,
                          self.api.list_resources,
                          project_slug='abc')

    @patch('__builtin__.open', create=True)
    @patch('requests.post')
    def test_new_resource(self, mock_requests, mock_open):
        """
        Test the `new_resource` api call
        """
        file_contents = 'aaaaaa\nggggg'
        mock_open.return_value = MagicMock(spec=file)
        mock_open.return_value.read = lambda: file_contents

        required_post_params = ['name', 'slug', 'content', 'i18n_type']

        def side_effect(*args, **kwargs):
            response = Mock()
            response.status_code = 201
            data = json.loads(kwargs.get('data', "{}"))
            for param in required_post_params:
                if param not in data:
                    response.status_code = 400
                    response.content = '%r is required'
                    break

            return response

        mock_requests.side_effect = side_effect

        self.api.new_resource(project_slug='abc',
                              path_to_pofile='/abc/pofile.po')
        self.assertTrue(mock_requests.called)
        __, kwargs = mock_requests.call_args
        self.assertTrue('data' in kwargs)
        data = json.loads(kwargs['data'])
        self.assertEqual(data['content'], file_contents)

    @patch('__builtin__.open', create=True)
    def test_new_resource_file_not_found(self, mock_open):
        """
        Test the `new_resource` api call when the pofile cannot be found
        """
        def side_effect(*args, **kwargs):
            raise IOError('File not found')

        mock_open.side_effect = side_effect
        self.assertRaises(IOError,
                          self.api.new_resource,
                          project_slug='abc',
                          path_to_pofile='/aaa/file.po')

    @patch('__builtin__.open', create=True)
    def test_new_resource_bad_slug(self, mock_open):
        """
        Test the `new_resource` api call when the slug is invalid
        """
        file_contents = 'aaaaaa\nggggg'
        mock_open.return_value = MagicMock(spec=file)
        mock_open.return_value.read = lambda: file_contents

        self.assertRaises(InvalidSlugException,
                          self.api.new_resource,
                          project_slug='aaa',
                          resource_slug='.',
                          path_to_pofile='/aaa/file.po')
        self.assertRaises(InvalidSlugException,
                          self.api.new_resource,
                          project_slug='aaa',
                          resource_slug='/',
                          path_to_pofile='/aaa/file.po')
        self.assertRaises(InvalidSlugException,
                          self.api.new_resource,
                          project_slug='aaa',
                          resource_slug='%@$',
                          path_to_pofile='/aaa/file.po')

    @patch('__builtin__.open', create=True)
    @patch('requests.post')
    def test_new_resource_server_error(self, mock_requests, mock_open):
        """
        Test the `new_resource` api call when the transifex server returns an
        error
        """
        file_contents = 'aaaaaa\nggggg'
        mock_open.return_value = MagicMock(spec=file)
        mock_open.return_value.read = lambda: file_contents

        def side_effect(*args, **kwargs):
            response = Mock()
            response.status_code = 404
            return response

        mock_requests.side_effect = side_effect
        self.assertRaises(TransifexAPIException,
                          self.api.new_resource,
                          project_slug='abc',
                          path_to_pofile='/aaa/file.po')

    @patch('__builtin__.open', create=True)
    @patch('requests.post')
    def test_new_resource_with_optional_args(self, mock_requests, mock_open):
        """
        Test the `new_resource` api call with the optional args
        """
        file_contents = 'aaaaaa\nggggg'
        mock_open.return_value = MagicMock(spec=file)
        mock_open.return_value.read = lambda: file_contents

        required_post_params = ['name', 'slug', 'content', 'i18n_type']

        def side_effect(*args, **kwargs):
            response = Mock()
            response.status_code = 201
            data = json.loads(kwargs.get('data', "{}"))
            for param in required_post_params:
                if param not in data:
                    response.status_code = 400
                    response.content = '%r is required'
                    break

            return response

        mock_requests.side_effect = side_effect

        self.api.new_resource(project_slug='abc',
                              path_to_pofile='/abc/pofile.po',
                              resource_slug='def',
                              resource_name='A Name')
        self.assertTrue(mock_requests.called)

    @patch('__builtin__.open', create=True)
    @patch('requests.put')
    def test_update_source_translation(self, mock_requests, mock_open):
        """
        Test the `update_source_translation` api call
        """
        file_contents = 'aaaaaa\nggggg'
        mock_open.return_value = MagicMock(spec=file)
        mock_open.return_value.read = lambda: file_contents

        required_post_params = [
            'content',
        ]

        def side_effect(*args, **kwargs):
            response = Mock()
            data = json.loads(kwargs.get('data', "{}"))
            for param in required_post_params:
                if param not in data:
                    response.status_code = 400
                    response.content = '%r is required'
                    return response

            response.status_code = 200
            response.content = json.dumps({'a': 1})
            return response

        mock_requests.side_effect = side_effect

        self.api.update_source_translation(project_slug='abc',
                                           resource_slug='def',
                                           path_to_pofile='/abc/pofile.po')
        self.assertTrue(mock_requests.called)

    @patch('__builtin__.open', create=True)
    def test_update_source_translation_file_not_found(self, mock_open):
        """
        Test the `update_source_translation` api call when the pofile cannot be found
        """
        def side_effect(*args, **kwargs):
            raise IOError('File not found')

        mock_open.side_effect = side_effect
        self.assertRaises(IOError,
                          self.api.update_source_translation,
                          project_slug='abc',
                          resource_slug='def',
                          path_to_pofile='/aaa/file.po')

    @patch('__builtin__.open', create=True)
    @patch('requests.put')
    def test_update_source_translation_server_error(self, mock_requests,
                                                    mock_open):
        """
        Test the `update_source_translation` api call when the transifex server
        returns an error
        """
        file_contents = 'aaaaaa\nggggg'
        mock_open.return_value = MagicMock(spec=file)
        mock_open.return_value.read = lambda: file_contents

        def side_effect(*args, **kwargs):
            response = Mock()
            response.status_code = 404
            return response

        mock_requests.side_effect = side_effect
        self.assertRaises(TransifexAPIException,
                          self.api.update_source_translation,
                          project_slug='abc',
                          resource_slug='def',
                          path_to_pofile='/aaa/file.po')

    @patch('__builtin__.open', create=True)
    @patch('requests.put')
    def test_new_translation(self, mock_requests, mock_open):
        """
        Test the `new_translation` api call
        """
        file_contents = 'aaaaaa\nggggg'
        mock_open.return_value = MagicMock(spec=file)
        mock_open.return_value.read = lambda: file_contents

        required_post_params = [
            'content',
        ]

        def side_effect(*args, **kwargs):
            response = Mock()
            data = json.loads(kwargs.get('data', "{}"))
            for param in required_post_params:
                if param not in data:
                    response.status_code = 400
                    response.content = '%r is required'
                    return response

            response.status_code = 200
            response.content = json.dumps({'s': 1})
            return response

        mock_requests.side_effect = side_effect

        self.api.new_translation(project_slug='abc',
                                 resource_slug='def',
                                 language_code='pt',
                                 path_to_pofile='/abc/pofile.po')
        self.assertTrue(mock_requests.called)

    @patch('__builtin__.open', create=True)
    def test_new_translation_file_not_found(self, mock_open):
        """
        Test the `new_translation` api call when the pofile cannot be found
        """
        def side_effect(*args, **kwargs):
            raise IOError('File not found')

        mock_open.side_effect = side_effect
        self.assertRaises(IOError,
                          self.api.new_translation,
                          project_slug='abc',
                          resource_slug='def',
                          language_code='pt',
                          path_to_pofile='/aaa/file.po')

    @patch('__builtin__.open', create=True)
    @patch('requests.put')
    def test_new_translation_server_error(self, mock_requests, mock_open):
        """
        Test the `new_translation` api call when the transifex server
        returns an error
        """
        file_contents = 'aaaaaa\nggggg'
        mock_open.return_value = MagicMock(spec=file)
        mock_open.return_value.read = lambda: file_contents

        def side_effect(*args, **kwargs):
            response = Mock()
            response.status_code = 404
            return response

        mock_requests.side_effect = side_effect
        self.assertRaises(TransifexAPIException,
                          self.api.new_translation,
                          project_slug='abc',
                          resource_slug='def',
                          language_code='pt',
                          path_to_pofile='/aaa/file.po')

    @patch('__builtin__.open', create=True)
    @patch('requests.get')
    def test_get_translation(self, mock_requests, mock_open):
        """
        Test the `get_translation` api call
        """
        mock_open.return_value = MagicMock(spec=file)

        def side_effect(*args, **kwargs):
            mock_response = Mock()
            mock_response.status_code = 200
            mock_response.iter_content = lambda: 'abc\ndef\n'
            return mock_response

        mock_requests.side_effect = side_effect

        self.api.get_translation(project_slug='abc',
                                 resource_slug='def',
                                 language_code='pt',
                                 path_to_pofile='/abc/pofile.po')
        self.assertTrue(mock_requests.called)

    @patch('__builtin__.open', create=True)
    @patch('requests.get')
    def test_get_translation_file_not_found(self, mock_requests, mock_open):
        """
        Test the `get_translation` api call when the pofile cannot be found
        """
        def open_side_effect(*args, **kwargs):
            raise IOError('File not found')

        mock_open.side_effect = open_side_effect

        def requests_side_effect(*args, **kwargs):
            mock_response = Mock()
            mock_response.status_code = 200
            mock_response.iter_content = lambda: 'abc\ndef\n'
            return mock_response

        mock_requests.side_effect = requests_side_effect

        self.assertRaises(IOError,
                          self.api.get_translation,
                          project_slug='abc',
                          resource_slug='def',
                          language_code='pt',
                          path_to_pofile='/abc/pofile.po')

    @patch('requests.get')
    def test_get_translation_server_error(self, mock_requests):
        """
        Test the `get_translation` api call when the transifex server
        returns an error
        """
        def side_effect(*args, **kwargs):
            response = Mock()
            response.status_code = 404
            return response

        mock_requests.side_effect = side_effect
        self.assertRaises(TransifexAPIException,
                          self.api.get_translation,
                          project_slug='abc',
                          resource_slug='def',
                          language_code='pt',
                          path_to_pofile='/abc/pofile.po')

    @patch('requests.delete')
    def test_delete_resource(self, mock_requests):
        """
        Test the `delete_resource` api call
        """
        def side_effect(*args, **kwargs):
            mock_response = Mock()
            mock_response.status_code = 204
            return mock_response

        mock_requests.side_effect = side_effect

        self.api.delete_resource(project_slug='abc', resource_slug='def')
        self.assertTrue(mock_requests.called)

    @patch('requests.delete')
    def test_delete_resource_server_error(self, mock_requests):
        """
        Test the `delete_resource` api call when the transifex server
        returns an error
        """
        def side_effect(*args, **kwargs):
            response = Mock()
            response.status_code = 404
            return response

        mock_requests.side_effect = side_effect
        self.assertRaises(TransifexAPIException,
                          self.api.delete_resource,
                          project_slug='abc',
                          resource_slug='def')

    @patch('requests.get')
    def test_list_languages(self, mock_requests):
        """
        Test the `list_languages` api call
        """
        expected_languages = ['en_GB', 'it']
        response_content = {
            'slug':
            'txo',
            'mimetype':
            'text/x-po',
            'source_language_code':
            'en',
            'wordcount':
            6160,
            'total_entities':
            1017,
            'last_update':
            '2011-12-05 19:59:55',
            'available_languages': [
                {
                    'code_aliases': ' ',
                    'code': 'it',
                    'name': 'Italian'
                },
                {
                    'code_aliases': 'en-gb',
                    'code': 'en_GB',
                    'name': 'English (Great Britain)'
                },
            ],
        }

        def side_effect(*args, **kwargs):
            response = Mock()
            response.status_code = 200
            response.content = json.dumps(response_content)
            return response

        mock_requests.side_effect = side_effect
        languages = self.api.list_languages(project_slug='abc',
                                            resource_slug='def')
        self.assertEqual(sorted(expected_languages), sorted(languages))

    @patch('requests.get')
    def test_list_languages_404(self, mock_requests):
        """
        Test the `list_languages` api call when the project or resource is not
        found
        """
        def side_effect(*args, **kwargs):
            response = Mock()
            response.status_code = 404
            return response

        mock_requests.side_effect = side_effect
        self.assertRaises(TransifexAPIException,
                          self.api.list_languages,
                          project_slug='abc',
                          resource_slug='defg')

    @patch('requests.get')
    def test_project_exists(self, mock_requests):
        """
        Test the `test_project_exists` api call
        """
        def side_effect(*args, **kwargs):
            response = Mock()
            response.status_code = 200
            return response

        mock_requests.side_effect = side_effect
        self.assertTrue(self.api.project_exists(project_slug='abc'))

    @patch('requests.get')
    def test_project_exists_with_no_project(self, mock_requests):
        """
        Test the `test_project_exists` api call when the project doesn't exist
        """
        def side_effect(*args, **kwargs):
            response = Mock()
            response.status_code = 404
            return response

        mock_requests.side_effect = side_effect
        self.assertFalse(self.api.project_exists(project_slug='abc'))

    @patch('requests.get')
    def test_project_exists_with_error(self, mock_requests):
        """
        Test the `test_project_exists` api call when the api returns an error
        """
        def side_effect(*args, **kwargs):
            response = Mock()
            response.status_code = 400
            return response

        mock_requests.side_effect = side_effect
        self.assertRaises(TransifexAPIException,
                          self.api.project_exists,
                          project_slug='abc')

    @patch('requests.get')
    def test_list_translation_strings(self, mock_requests):
        """
        Test the `list_translation_strings` api call
        """
        response_content = [{'a': 1}, {'b': 2}]

        def side_effect(*args, **kwargs):
            response = Mock()
            response.status_code = 200
            response.content = json.dumps(response_content)
            return response

        mock_requests.side_effect = side_effect
        resources = self.api.list_translation_strings(project_slug='abc',
                                                      resource_slug='abc',
                                                      language_code='FR')
        self.assertEqual(resources, response_content)

    @patch('requests.get')
    def test_list_translation_strings_with_bad_project_name(
            self, mock_requests):
        """
        Test the 'list_translation_strings' api call, when the project name given
        doesn't exist on the transifex server
        """
        def side_effect(*args, **kwargs):
            response = Mock()
            response.status_code = 404
            return response

        mock_requests.side_effect = side_effect
        self.assertRaises(TransifexAPIException,
                          self.api.list_translation_strings,
                          project_slug='abc',
                          resource_slug='abc',
                          language_code='FR')

    @patch('requests.get')
    def test_get_translation_string(self, mock_requests):
        """
        Test the `get_translation_string` api call
        """
        response_content = [{'a': 1}, {'b': 2}]

        def side_effect(*args, **kwargs):
            response = Mock()
            response.status_code = 200
            response.content = json.dumps(response_content)
            return response

        mock_requests.side_effect = side_effect
        resources = self.api.get_translation_string(project_slug='abc',
                                                    resource_slug='abc',
                                                    language_code='FR',
                                                    entity="Jar Jar")
        self.assertEqual(resources, response_content)

    @patch('requests.get')
    def test_get_translation_string_with_bad_project_name(self, mock_requests):
        """
        Test the 'list resources' api call, when the project name given
        doesn't exist on the transifex server
        """
        def side_effect(*args, **kwargs):
            response = Mock()
            response.status_code = 404
            return response

        mock_requests.side_effect = side_effect
        self.assertRaises(TransifexAPIException,
                          self.api.get_translation_string,
                          project_slug='abc',
                          resource_slug='abc',
                          language_code='FR',
                          entity="Jar Jar")

    @patch('requests.put')
    def test_put_translation_string(self, mock_requests):
        """
        Test the `put_translation_string` api call
        """
        response_content = True

        def side_effect(*args, **kwargs):
            response = Mock()
            response.status_code = 200
            response.content = json.dumps(response_content)
            return response

        mock_requests.side_effect = side_effect
        resources = self.api.put_translation_string(project_slug='abc',
                                                    resource_slug='abc',
                                                    language_code='FR',
                                                    entity="Jar Jar",
                                                    translation="Binks")
        self.assertEqual(resources, response_content)

    @patch('requests.put')
    def test_put_translation_string_with_bad_project_name(self, mock_requests):
        """
        Test the 'list resources' api call, when the project name given
        doesn't exist on the transifex server
        """
        def side_effect(*args, **kwargs):
            response = Mock()
            response.status_code = 404
            return response

        mock_requests.side_effect = side_effect
        self.assertRaises(TransifexAPIException,
                          self.api.put_translation_string,
                          project_slug='abc',
                          resource_slug='abc',
                          language_code='FR',
                          entity="Jar Jar",
                          translation="Binks")
예제 #9
0
 def __init__(self, transuser, transpass, url):
     TransifexAPI.__init__(self, transuser, transpass, url)
예제 #10
0
 def __init__(self, username: str, password: str, project_slug: str):
     self.transifex_api = TransifexAPI(username, password,
                                       "https://www.transifex.com")
     self.project_slug = project_slug
예제 #11
0
 def setUp(self):
     data = {"username": "******", "password": "******", "host": "http://www.mydomain.com"}
     self.api = TransifexAPI(**data)
예제 #12
0
class TransifexAPITest(TestCase):
    def setUp(self):
        data = {"username": "******", "password": "******", "host": "http://www.mydomain.com"}
        self.api = TransifexAPI(**data)

    @patch("requests.post")
    def test_new_public_project_with_required_args(self, mock_requests):
        """
        Test creating a new project with only the required arguments
        """
        mock_requests.side_effect = _check_for_new_project_kwargs
        self.api.new_project(slug="abc", repository_url="http://abc.com")

    def test_new_project_bad_slug(self):
        """
        Test the `new_project` api call when the slug is invalid
        """
        self.assertRaises(InvalidSlugException, self.api.new_project, slug=".")
        self.assertRaises(InvalidSlugException, self.api.new_project, slug="/")
        self.assertRaises(InvalidSlugException, self.api.new_project, slug="%@$")

    def test_new_project_no_repository_url(self):
        """
        Test the `new_project` api call when no repository_url is passed to a
        public project
        """
        self.assertRaises(TransifexAPIException, self.api.new_project, slug="fdsfs", private=False)

    @patch("requests.post")
    def test_new_project_with_optional_args(self, mock_requests):
        """
        Test creating a new project with the optional arguments
        """

        def side_effect(*args, **kwargs):
            response = Mock()
            data = json.loads(kwargs.get("data", "{}"))
            if "source_language_code" in data and "name" in data and "slug" in data:
                response.status_code = 201
            else:
                response.status_code = 400

            return response

        mock_requests.side_effect = side_effect
        self.api.new_project(slug="abc", name="abc", source_language_code="pt", outsource_project_name="anotherproject")

    @patch("requests.post")
    def test_new_project_with_http_response_400(self, mock_requests):
        """
        Test creating a new project when the transifex server returns a
        '400 BAD REQUEST' response 
        """

        def side_effect(*args, **kwargs):
            response = Mock()
            response.status_code = 400
            return response

        mock_requests.side_effect = side_effect
        self.assertRaises(TransifexAPIException, self.api.new_project, slug="abc")

    @patch("requests.get")
    def test_list_resources(self, mock_requests):
        """
        Test the `list_resources` api call
        """
        response_content = [{"a": 1}, {"b": 2}]

        def side_effect(*args, **kwargs):
            response = Mock()
            response.status_code = 200
            response.content = json.dumps(response_content)
            return response

        mock_requests.side_effect = side_effect
        resources = self.api.list_resources(project_slug="abc")
        self.assertEqual(resources, response_content)

    @patch("requests.get")
    def test_list_resources_with_bad_project_name(self, mock_requests):
        """
        Test the 'list resources' api call, when the project name given
        doesn't exist on the transifex server
        """

        def side_effect(*args, **kwargs):
            response = Mock()
            response.status_code = 404
            return response

        mock_requests.side_effect = side_effect
        self.assertRaises(TransifexAPIException, self.api.list_resources, project_slug="abc")

    @patch("__builtin__.open", create=True)
    @patch("requests.post")
    def test_new_resource(self, mock_requests, mock_open):
        """
        Test the `new_resource` api call
        """
        file_contents = "aaaaaa\nggggg"
        mock_open.return_value = MagicMock(spec=file)
        mock_open.return_value.read = lambda: file_contents

        required_post_params = ["name", "slug", "content", "i18n_type"]

        def side_effect(*args, **kwargs):
            response = Mock()
            response.status_code = 201
            data = json.loads(kwargs.get("data", "{}"))
            for param in required_post_params:
                if param not in data:
                    response.status_code = 400
                    response.content = "%r is required"
                    break

            return response

        mock_requests.side_effect = side_effect

        self.api.new_resource(project_slug="abc", path_to_pofile="/abc/pofile.po")
        self.assertTrue(mock_requests.called)
        __, kwargs = mock_requests.call_args
        self.assertTrue("data" in kwargs)
        data = json.loads(kwargs["data"])
        self.assertEqual(data["content"], file_contents)

    @patch("__builtin__.open", create=True)
    def test_new_resource_file_not_found(self, mock_open):
        """
        Test the `new_resource` api call when the pofile cannot be found
        """

        def side_effect(*args, **kwargs):
            raise IOError("File not found")

        mock_open.side_effect = side_effect
        self.assertRaises(IOError, self.api.new_resource, project_slug="abc", path_to_pofile="/aaa/file.po")

    @patch("__builtin__.open", create=True)
    def test_new_resource_bad_slug(self, mock_open):
        """
        Test the `new_resource` api call when the slug is invalid
        """
        file_contents = "aaaaaa\nggggg"
        mock_open.return_value = MagicMock(spec=file)
        mock_open.return_value.read = lambda: file_contents

        self.assertRaises(
            InvalidSlugException,
            self.api.new_resource,
            project_slug="aaa",
            resource_slug=".",
            path_to_pofile="/aaa/file.po",
        )
        self.assertRaises(
            InvalidSlugException,
            self.api.new_resource,
            project_slug="aaa",
            resource_slug="/",
            path_to_pofile="/aaa/file.po",
        )
        self.assertRaises(
            InvalidSlugException,
            self.api.new_resource,
            project_slug="aaa",
            resource_slug="%@$",
            path_to_pofile="/aaa/file.po",
        )

    @patch("__builtin__.open", create=True)
    @patch("requests.post")
    def test_new_resource_server_error(self, mock_requests, mock_open):
        """
        Test the `new_resource` api call when the transifex server returns an
        error 
        """
        file_contents = "aaaaaa\nggggg"
        mock_open.return_value = MagicMock(spec=file)
        mock_open.return_value.read = lambda: file_contents

        def side_effect(*args, **kwargs):
            response = Mock()
            response.status_code = 404
            return response

        mock_requests.side_effect = side_effect
        self.assertRaises(
            TransifexAPIException, self.api.new_resource, project_slug="abc", path_to_pofile="/aaa/file.po"
        )

    @patch("__builtin__.open", create=True)
    @patch("requests.post")
    def test_new_resource_with_optional_args(self, mock_requests, mock_open):
        """
        Test the `new_resource` api call with the optional args
        """
        file_contents = "aaaaaa\nggggg"
        mock_open.return_value = MagicMock(spec=file)
        mock_open.return_value.read = lambda: file_contents

        required_post_params = ["name", "slug", "content", "i18n_type"]

        def side_effect(*args, **kwargs):
            response = Mock()
            response.status_code = 201
            data = json.loads(kwargs.get("data", "{}"))
            for param in required_post_params:
                if param not in data:
                    response.status_code = 400
                    response.content = "%r is required"
                    break

            return response

        mock_requests.side_effect = side_effect

        self.api.new_resource(
            project_slug="abc", path_to_pofile="/abc/pofile.po", resource_slug="def", resource_name="A Name"
        )
        self.assertTrue(mock_requests.called)

    @patch("__builtin__.open", create=True)
    @patch("requests.put")
    def test_update_source_translation(self, mock_requests, mock_open):
        """
        Test the `update_source_translation` api call
        """
        file_contents = "aaaaaa\nggggg"
        mock_open.return_value = MagicMock(spec=file)
        mock_open.return_value.read = lambda: file_contents

        required_post_params = ["content"]

        def side_effect(*args, **kwargs):
            response = Mock()
            data = json.loads(kwargs.get("data", "{}"))
            for param in required_post_params:
                if param not in data:
                    response.status_code = 400
                    response.content = "%r is required"
                    return response

            response.status_code = 200
            response.content = json.dumps({"a": 1})
            return response

        mock_requests.side_effect = side_effect

        self.api.update_source_translation(project_slug="abc", resource_slug="def", path_to_pofile="/abc/pofile.po")
        self.assertTrue(mock_requests.called)

    @patch("__builtin__.open", create=True)
    def test_update_source_translation_file_not_found(self, mock_open):
        """
        Test the `update_source_translation` api call when the pofile cannot be found
        """

        def side_effect(*args, **kwargs):
            raise IOError("File not found")

        mock_open.side_effect = side_effect
        self.assertRaises(
            IOError,
            self.api.update_source_translation,
            project_slug="abc",
            resource_slug="def",
            path_to_pofile="/aaa/file.po",
        )

    @patch("__builtin__.open", create=True)
    @patch("requests.put")
    def test_update_source_translation_server_error(self, mock_requests, mock_open):
        """
        Test the `update_source_translation` api call when the transifex server
        returns an error 
        """
        file_contents = "aaaaaa\nggggg"
        mock_open.return_value = MagicMock(spec=file)
        mock_open.return_value.read = lambda: file_contents

        def side_effect(*args, **kwargs):
            response = Mock()
            response.status_code = 404
            return response

        mock_requests.side_effect = side_effect
        self.assertRaises(
            TransifexAPIException,
            self.api.update_source_translation,
            project_slug="abc",
            resource_slug="def",
            path_to_pofile="/aaa/file.po",
        )

    @patch("__builtin__.open", create=True)
    @patch("requests.put")
    def test_new_translation(self, mock_requests, mock_open):
        """
        Test the `new_translation` api call
        """
        file_contents = "aaaaaa\nggggg"
        mock_open.return_value = MagicMock(spec=file)
        mock_open.return_value.read = lambda: file_contents

        required_post_params = ["content"]

        def side_effect(*args, **kwargs):
            response = Mock()
            data = json.loads(kwargs.get("data", "{}"))
            for param in required_post_params:
                if param not in data:
                    response.status_code = 400
                    response.content = "%r is required"
                    return response

            response.status_code = 200
            response.content = json.dumps({"s": 1})
            return response

        mock_requests.side_effect = side_effect

        self.api.new_translation(
            project_slug="abc", resource_slug="def", language_code="pt", path_to_pofile="/abc/pofile.po"
        )
        self.assertTrue(mock_requests.called)

    @patch("__builtin__.open", create=True)
    def test_new_translation_file_not_found(self, mock_open):
        """
        Test the `new_translation` api call when the pofile cannot be found
        """

        def side_effect(*args, **kwargs):
            raise IOError("File not found")

        mock_open.side_effect = side_effect
        self.assertRaises(
            IOError,
            self.api.new_translation,
            project_slug="abc",
            resource_slug="def",
            language_code="pt",
            path_to_pofile="/aaa/file.po",
        )

    @patch("__builtin__.open", create=True)
    @patch("requests.put")
    def test_new_translation_server_error(self, mock_requests, mock_open):
        """
        Test the `new_translation` api call when the transifex server
        returns an error 
        """
        file_contents = "aaaaaa\nggggg"
        mock_open.return_value = MagicMock(spec=file)
        mock_open.return_value.read = lambda: file_contents

        def side_effect(*args, **kwargs):
            response = Mock()
            response.status_code = 404
            return response

        mock_requests.side_effect = side_effect
        self.assertRaises(
            TransifexAPIException,
            self.api.new_translation,
            project_slug="abc",
            resource_slug="def",
            language_code="pt",
            path_to_pofile="/aaa/file.po",
        )

    @patch("__builtin__.open", create=True)
    @patch("requests.get")
    def test_get_translation(self, mock_requests, mock_open):
        """
        Test the `get_translation` api call
        """
        mock_open.return_value = MagicMock(spec=file)

        def side_effect(*args, **kwargs):
            mock_response = Mock()
            mock_response.status_code = 200
            mock_response.iter_content = lambda: "abc\ndef\n"
            return mock_response

        mock_requests.side_effect = side_effect

        self.api.get_translation(
            project_slug="abc", resource_slug="def", language_code="pt", path_to_pofile="/abc/pofile.po"
        )
        self.assertTrue(mock_requests.called)

    @patch("__builtin__.open", create=True)
    @patch("requests.get")
    def test_get_translation_file_not_found(self, mock_requests, mock_open):
        """
        Test the `get_translation` api call when the pofile cannot be found
        """

        def open_side_effect(*args, **kwargs):
            raise IOError("File not found")

        mock_open.side_effect = open_side_effect

        def requests_side_effect(*args, **kwargs):
            mock_response = Mock()
            mock_response.status_code = 200
            mock_response.iter_content = lambda: "abc\ndef\n"
            return mock_response

        mock_requests.side_effect = requests_side_effect

        self.assertRaises(
            IOError,
            self.api.get_translation,
            project_slug="abc",
            resource_slug="def",
            language_code="pt",
            path_to_pofile="/abc/pofile.po",
        )

    @patch("requests.get")
    def test_get_translation_server_error(self, mock_requests):
        """
        Test the `get_translation` api call when the transifex server
        returns an error 
        """

        def side_effect(*args, **kwargs):
            response = Mock()
            response.status_code = 404
            return response

        mock_requests.side_effect = side_effect
        self.assertRaises(
            TransifexAPIException,
            self.api.get_translation,
            project_slug="abc",
            resource_slug="def",
            language_code="pt",
            path_to_pofile="/abc/pofile.po",
        )

    @patch("requests.delete")
    def test_delete_resource(self, mock_requests):
        """
        Test the `delete_resource` api call
        """

        def side_effect(*args, **kwargs):
            mock_response = Mock()
            mock_response.status_code = 204
            return mock_response

        mock_requests.side_effect = side_effect

        self.api.delete_resource(project_slug="abc", resource_slug="def")
        self.assertTrue(mock_requests.called)

    @patch("requests.delete")
    def test_delete_resource_server_error(self, mock_requests):
        """
        Test the `delete_resource` api call when the transifex server
        returns an error 
        """

        def side_effect(*args, **kwargs):
            response = Mock()
            response.status_code = 404
            return response

        mock_requests.side_effect = side_effect
        self.assertRaises(TransifexAPIException, self.api.delete_resource, project_slug="abc", resource_slug="def")

    @patch("requests.get")
    def test_list_languages(self, mock_requests):
        """
        Test the `list_languages` api call
        """
        expected_languages = ["en_GB", "it"]
        response_content = {
            "slug": "txo",
            "mimetype": "text/x-po",
            "source_language_code": "en",
            "wordcount": 6160,
            "total_entities": 1017,
            "last_update": "2011-12-05 19:59:55",
            "available_languages": [
                {"code_aliases": " ", "code": "it", "name": "Italian"},
                {"code_aliases": "en-gb", "code": "en_GB", "name": "English (Great Britain)"},
            ],
        }

        def side_effect(*args, **kwargs):
            response = Mock()
            response.status_code = 200
            response.content = json.dumps(response_content)
            return response

        mock_requests.side_effect = side_effect
        languages = self.api.list_languages(project_slug="abc", resource_slug="def")
        self.assertEqual(sorted(expected_languages), sorted(languages))

    @patch("requests.get")
    def test_list_languages_404(self, mock_requests):
        """
        Test the `list_languages` api call when the project or resource is not
        found
        """

        def side_effect(*args, **kwargs):
            response = Mock()
            response.status_code = 404
            return response

        mock_requests.side_effect = side_effect
        self.assertRaises(TransifexAPIException, self.api.list_languages, project_slug="abc", resource_slug="defg")

    @patch("requests.get")
    def test_project_exists(self, mock_requests):
        """
        Test the `test_project_exists` api call
        """

        def side_effect(*args, **kwargs):
            response = Mock()
            response.status_code = 200
            return response

        mock_requests.side_effect = side_effect
        self.assertTrue(self.api.project_exists(project_slug="abc"))

    @patch("requests.get")
    def test_project_exists_with_no_project(self, mock_requests):
        """
        Test the `test_project_exists` api call when the project doesn't exist
        """

        def side_effect(*args, **kwargs):
            response = Mock()
            response.status_code = 404
            return response

        mock_requests.side_effect = side_effect
        self.assertFalse(self.api.project_exists(project_slug="abc"))

    @patch("requests.get")
    def test_project_exists_with_error(self, mock_requests):
        """
        Test the `test_project_exists` api call when the api returns an error
        """

        def side_effect(*args, **kwargs):
            response = Mock()
            response.status_code = 400
            return response

        mock_requests.side_effect = side_effect
        self.assertRaises(TransifexAPIException, self.api.project_exists, project_slug="abc")
예제 #13
0
import os
import sys
import json

import requests
from transifex.api import TransifexAPI

pathname = os.path.dirname(sys.argv[0])
local_dir = os.path.abspath(pathname)

username = os.getenv('TRANSIFEX_USERNAME')
password = os.getenv('TRANSIFEX_PASSWORD')

t = TransifexAPI(username, password, 'http://www.transifex.com')

def get_statistics(project, resource):
    url = 'https://www.transifex.com/api/2/project/{}/resource/{}/stats/'.format(
        project, resource
    )
    response = requests.get(url, auth=(username, password))
    return json.loads(response.content)

def printProgress (iteration, total, prefix = '', suffix = '', decimals = 2, barLength = 100):
    filledLength    = int(round(barLength * iteration / float(total)))
    percents        = round(100.00 * (iteration / float(total)), decimals)
    bar             = '#' * filledLength + '-' * (barLength - filledLength)
    return '%s [%s] %s%s %s' % (prefix, bar, percents, '%', suffix)

resources = t.list_resources('mifm')
progress_data = 'Language translation progress:\n'
예제 #14
0
#!/usr/bin/env python
# Transifex script to upload the strings from the local computer to the server. Note this is dangerous since it could remove existent strings
# Import the library from third-party https://github.com/jakul/python-transifex
from transifex.api import TransifexAPI

SERVER_URL = 'https://www.transifex.com'
USERNAME = '******'
PASSWORD = '******'

# Create the basic object
transifexAPI = TransifexAPI(USERNAME, PASSWORD, SERVER_URL)

print 'Is it connected? ' + str(transifexAPI.ping())

print 'Downloading strings from the Transifex server'

PROJECT_SLUG = 'math-calculator'
RESOURCE_SLUG = 'stringsxml'

LANGUAGES = ['en', 'zh']  # English, Arabic, French, Turkish and Urdu

# Download new strings
for language in LANGUAGES:
    print "Downloading translations for " + language
    if language == 'en':
        transifexAPI.get_translation(PROJECT_SLUG, RESOURCE_SLUG, language,
                                     './app/src/main/res/values/strings.xml')
    else:
        transifexAPI.get_translation(
            PROJECT_SLUG, RESOURCE_SLUG, language,
            './app/src/main/res/values-' + language + '/strings.xml')
#!/usr/bin/env python
# Transifex script to upload the strings from the local computer to the server. Note this is dangerous since it could remove existent strings
# Import the library from third-party https://github.com/jakul/python-transifex
from transifex.api import TransifexAPI
from subprocess import call

SERVER_URL = 'https://www.transifex.com'
USERNAME = '******'
PASSWORD = '******'

# Create the basic object
transifexAPI = TransifexAPI(USERNAME, PASSWORD, SERVER_URL)

print 'Is it connected? ' + str(transifexAPI.ping())

print 'Uploading strings to the Transifex server'

PROJECT_SLUG = 'math-calculator'
RESOURCE_SLUG = 'stringsxml'
ORIGINAL_STRING_LOCATION = './scripts/original_resource.xml'

# Restore the source
print 'Restoring the server strings'
print transifexAPI.update_source_translation(PROJECT_SLUG, RESOURCE_SLUG,
                                             ORIGINAL_STRING_LOCATION)