def test_no_root_view_permissions(po_directory, nobody, default, admin, view, no_permission_sets, no_projects, project_foo, project_bar): """Tests user-accessible projects when there are no permissions set at the root. """ ALL_PROJECTS = [project_foo.code, project_bar.code] foo_user = UserFactory.create(username='******') bar_user = UserFactory.create(username='******') # By setting explicit `view` permissions for `foo_user` in `project_foo`, # only `foo_user` will be able to access that project _require_permission_set(foo_user, project_foo.directory, [view]) assert items_equal(Project.accessible_by_user(admin), ALL_PROJECTS) assert items_equal( Project.accessible_by_user(foo_user), [project_foo.code]) assert items_equal(Project.accessible_by_user(bar_user), []) assert items_equal(Project.accessible_by_user(default), []) assert items_equal(Project.accessible_by_user(nobody), []) # Now let's allow showing `project_bar` to all registered users, but keep # `project_foo` visible only to `foo_user`. _require_permission_set(default, project_bar.directory, [view]) assert items_equal(Project.accessible_by_user(admin), ALL_PROJECTS) assert items_equal(Project.accessible_by_user(foo_user), ALL_PROJECTS) assert items_equal( Project.accessible_by_user(bar_user), [project_bar.code]) assert items_equal(Project.accessible_by_user(default), [project_bar.code]) assert items_equal(Project.accessible_by_user(nobody), [])
def create_default_projects(): """Create the default projects that we host. You might want to add your projects here, although you can also add things through the web interface later. """ from pootle_project.models import Project en = require_english() criteria = { 'code': u"tutorial", 'source_language': en, 'fullname': u"Tutorial", 'checkstyle': "standard", 'localfiletype': "po", 'treestyle': "auto", } tutorial = Project(**criteria) tutorial.save() criteria = { 'active': True, 'title': "Project instructions", 'body': ('<div dir="ltr" lang="en">Tutorial project where users can ' 'play with Pootle and learn more about translation and ' 'localisation.<br />For more help on localisation, visit the ' '<a href="http://docs.translatehouse.org/projects/' 'localization-guide/en/latest/guide/start.html">localisation ' 'guide</a>.</div>'), 'virtual_path': "announcements/projects/"+tutorial.code, } ann = Announcement(**criteria) ann.save()
def create_default_projects(): """Create the default projects that we host. You might want to add your projects here, although you can also add things through the web interface later. """ from pootle_app.management import require_english from pootle_project.models import Project en = require_english() #pootle = Project(code=u"pootle", source_language=en) #pootle.fullname = u"Pootle" #pootle.description = ('<div dir="ltr" lang="en">Interface translations ' # 'for Pootle. <br /> See the <a href="http://' # 'pootle.locamotion.org">official Pootle server</a> ' # 'for the translations of Pootle.</div>') #pootle.checkstyle = "standard" #pootle.localfiletype = "po" #pootle.treestyle = "auto" #pootle.save() tutorial = Project(code=u"tutorial", source_language=en) tutorial.fullname = u"Tutorial" tutorial.description = ('<div dir="ltr" lang="en">Tutorial project where ' 'users can play with Pootle and learn more about ' 'translation and localisation.<br />For more help ' 'on localisation, visit the <a href="http://' 'translate.sourceforge.net/wiki/guide/start">' 'localisation guide</a>.</div>') tutorial.checkstyle = "standard" tutorial.localfiletype = "po" tutorial.treestyle = "auto" tutorial.save()
def import_projects(parsed_data): # This could prompt the user, asking: # "Want us to import projects? Say no if you have already # added the projects to the new Pootle DB in the web UI." data = parsed_data.__root__._assignments # Is this really the right way? prefix = 'Pootle.projects.' # Filter out unrelated keys keys = [key for key in data if key.startswith(prefix)] # Clean up 'pootle.fullname' into 'pootle' projs = set([key[len(prefix):].split('.')[0] for key in keys]) en = require_english() for proj in map(lambda s: unicode(s, 'utf-8'), projs): # id, for free # code: try: db_proj = Project.objects.get(code=proj) logging.log(logging.INFO, 'Already found a project named %s.\n'\ 'Data for this project are not imported.', proj) continue except Project.DoesNotExist: db_proj = Project(code=proj, source_language=en) # fullname db_proj.fullname = _get_attribute(data, proj, 'fullname', prefix=prefix) # description db_proj.description = _get_attribute(data, proj, 'description', prefix=prefix) # checkstyle db_proj.checkstyle = _get_attribute(data, proj, 'checkerstyle', unicode_me = False, prefix=prefix) # localfiletype db_proj.localfiletype = _get_attribute(data, proj, 'localfiletype', default='po', prefix=prefix) # treestyle db_proj.treestyle = _get_attribute(data, proj, 'treestyle', unicode_me = False, default='auto', prefix=prefix) # ignoredfiles db_proj.ignoredfiles = _get_attribute(data, proj, 'ignoredfiles', default=u'', prefix=prefix) logging.info("Creating project %s", db_proj) db_proj.save()
def wrapped(request, *args, **kwargs): language_code = kwargs.pop('language_code', None) project_code = kwargs.pop('project_code', None) pootle_path = request.GET.get('path', None) if pootle_path is not None: language_code, project_code, dir_path, filename = \ split_pootle_path(pootle_path) kwargs['dir_path'] = dir_path kwargs['filename'] = filename if language_code and project_code: try: path_obj = TranslationProject.objects.enabled().get( language__code=language_code, project__code=project_code, project__disabled=False ) except TranslationProject.DoesNotExist: path_obj = None if path_obj is None and not request.is_ajax(): # Explicit selection via the UI: redirect either to # ``/language_code/`` or ``/projects/project_code/``. user_choice = request.COOKIES.get('user-choice', None) if user_choice and user_choice in ('language', 'project',): url = { 'language': reverse('pootle-language-overview', args=[language_code]), 'project': reverse('pootle-project-overview', args=[project_code, '', '']), } response = redirect(url[user_choice]) response.delete_cookie('user-choice') return response raise Http404 elif language_code: path_obj = get_object_or_404(Language, code=language_code) elif project_code: path_obj = get_object_or_404(Project, code=project_code, disabled=False) else: # No arguments: all user-accessible projects user_projects = Project.accessible_by_user(request.user) user_projects = Project.objects.enabled() \ .filter(code__in=user_projects) path_obj = ProjectSet(user_projects, '/projects/') # HACKISH: inject directory so that permissions can be # queried directory = Directory.objects.get(pootle_path='/projects/') setattr(path_obj, 'directory', directory) request.ctx_obj = path_obj request.ctx_path = path_obj.pootle_path request.resource_obj = path_obj request.pootle_path = path_obj.pootle_path return func(request, path_obj, *args, **kwargs)
def is_accessible_by(self, user): """Returns `True` if the current translation project is accessible by `user`. """ if user.is_superuser: return True return self.project.code in Project.accessible_by_user(user)
def _require_project(code, name, source_language): """Helper to get/create a new project.""" # XXX: should accept more params, but is enough for now from pootle_project.models import Project criteria = { 'code': code, 'fullname': name, 'source_language': source_language, 'checkstyle': 'standard', 'localfiletype': 'po', 'treestyle': 'auto', } new_project = Project(**criteria) new_project.save() return new_project
def is_accessible_by(self, user): """Returns `True` if the current unit is accessible by `user`.""" if user.is_superuser: return True from pootle_project.models import Project user_projects = Project.accessible_by_user(user) return self.store.translation_project.project.code in user_projects
def test_view_projects_browse(client, request_users): user = request_users["user"] client.login( username=user.username, password=request_users["password"]) response = client.get(reverse("pootle-projects-browse")) assert response.cookies["pootle-language"].value == "projects" ctx = response.context request = response.wsgi_request user_projects = Project.accessible_by_user(request.user) user_projects = ( Project.objects.for_user(request.user) .filter(code__in=user_projects)) obj = ProjectSet(user_projects) items = [ make_project_list_item(project) for project in obj.children] items.sort(lambda x, y: locale.strcoll(x['title'], y['title'])) table_fields = [ 'name', 'progress', 'total', 'need-translation', 'suggestions', 'critical', 'last-updated', 'activity'] table = { 'id': 'projects', 'fields': table_fields, 'headings': get_table_headings(table_fields), 'items': items} if request.user.is_superuser: url_action_continue = obj.get_translate_url(state='incomplete') url_action_fixcritical = obj.get_critical_url() url_action_review = obj.get_translate_url(state='suggestions') url_action_view_all = obj.get_translate_url(state='all') else: (url_action_continue, url_action_fixcritical, url_action_review, url_action_view_all) = [None] * 4 User = get_user_model() top_scorers = User.top_scorers(limit=10) assertions = dict( page="browse", pootle_path="/projects/", resource_path="", resource_path_parts=[], object=obj, table=table, browser_extends="projects/all/base.html", stats=obj.data_tool.get_stats(user=request.user), checks=get_qualitycheck_list(obj), top_scorers=top_scorers, top_scorers_data=get_top_scorers_data(top_scorers, 10), translation_states=get_translation_states(obj), url_action_continue=url_action_continue, url_action_fixcritical=url_action_fixcritical, url_action_review=url_action_review, url_action_view_all=url_action_view_all) view_context_test(ctx, **assertions)
def test_view_projects_browse(client, request_users): user = request_users["user"] client.login( username=user.username, password=request_users["password"]) response = client.get(reverse("pootle-projects-browse")) assert response.cookies["pootle-language"].value == "projects" ctx = response.context request = response.wsgi_request user_projects = Project.accessible_by_user(request.user) user_projects = ( Project.objects.for_user(request.user) .filter(code__in=user_projects)) obj = ProjectSet(user_projects) stats = obj.data_tool.get_stats(user=request.user) if request.user.is_superuser: url_action_continue = obj.get_translate_url(state='incomplete') url_action_fixcritical = obj.get_critical_url() url_action_review = obj.get_translate_url(state='suggestions') url_action_view_all = obj.get_translate_url(state='all') else: (url_action_continue, url_action_fixcritical, url_action_review, url_action_view_all) = [None] * 4 checks = ChecksDisplay(obj).checks_by_category stats = StatsDisplay(obj, stats=stats).stats del stats["children"] chunk_size = TOP_CONTRIBUTORS_CHUNK_SIZE score_data = scores.get(ProjectSet)(obj) def scores_to_json(score): score["user"] = score["user"].to_dict() return score top_scorers = score_data.display( limit=chunk_size, formatter=scores_to_json) top_scorer_data = dict( items=list(top_scorers), has_more_items=len(score_data.top_scorers) > chunk_size) assertions = dict( page="browse", pootle_path="/projects/", resource_path="", resource_path_parts=[], object=obj, browser_extends="projects/all/base.html", top_scorers=top_scorer_data, translation_states=get_translation_states(obj), url_action_continue=url_action_continue, url_action_fixcritical=url_action_fixcritical, url_action_review=url_action_review, url_action_view_all=url_action_view_all, checks=checks, stats=stats) view_context_test(ctx, **assertions)
def test_view_projects_translate(client, settings, request_users): user = request_users["user"] client.login( username=user.username, password=request_users["password"]) response = client.get(reverse("pootle-projects-translate")) if not user.is_superuser: assert response.status_code == 403 return ctx = response.context request = response.wsgi_request user_projects = Project.accessible_by_user(request.user) user_projects = ( Project.objects.for_user(request.user) .filter(code__in=user_projects)) obj = ProjectSet(user_projects) checks = get_qualitychecks() schema = {sc["code"]: sc for sc in get_qualitycheck_schema()} check_data = obj.data_tool.get_checks() _checks = {} for check, checkid in checks.items(): if check not in check_data: continue _checkid = schema[checkid]["name"] _checks[_checkid] = _checks.get( _checkid, dict(checks=[], title=schema[checkid]["title"])) _checks[_checkid]["checks"].append( dict( code=check, title=check_names[check], count=check_data[check])) _checks = OrderedDict( (k, _checks[k]) for k in CATEGORY_IDS.keys() if _checks.get(k)) assertions = dict( page="translate", has_admin_access=user.is_superuser, language=None, project=None, pootle_path="/projects/", ctx_path="/projects/", resource_path="", resource_path_parts=[], editor_extends="projects/all/base.html", checks=_checks, previous_url=get_previous_url(request), display_priority=False, cantranslate=check_permission("translate", request), cansuggest=check_permission("suggest", request), canreview=check_permission("review", request), search_form=make_search_form(request=request), current_vfolder_pk="", POOTLE_MT_BACKENDS=settings.POOTLE_MT_BACKENDS, AMAGAMA_URL=settings.AMAGAMA_URL) view_context_test(ctx, **assertions)
def _require_project(code, name, source_language, **kwargs): """Helper to get/create a new project.""" from pootle_project.models import Project criteria = { 'code': code, 'fullname': name, 'source_language': source_language, 'checkstyle': 'standard', 'localfiletype': 'po', 'treestyle': 'auto', } criteria.update(kwargs) new_project = Project(**criteria) new_project.save() return new_project
def create_default_projects(): """Create the default projects that we host. You might want to add your projects here, although you can also add things through the web interface later. """ from pootle_project.models import Project en = require_english() #criteria = { # 'code': u"pootle", # 'source_language': en, # 'fullname': u"Pootle", # 'description': ('<div dir="ltr" lang="en">Interface translations for ' # 'Pootle.<br />See the <a href="http://' # 'pootle.locamotion.org">official Pootle server</a> ' # 'for the translations of Pootle.</div>') # 'checkstyle': "standard", # 'localfiletype': "po", # 'treestyle': "auto", #} #pootle = Project(**criteria) #pootle.save() criteria = { 'code': u"tutorial", 'source_language': en, 'fullname': u"Tutorial", 'description': ('<div dir="ltr" lang="en">Tutorial project where ' 'users can play with Pootle and learn more about ' 'translation and localisation.<br />For more help on ' 'localisation, visit the <a href="http://' 'docs.translatehouse.org/projects/localization-guide/' 'en/latest/guide/start.html">localisation guide</a>.' '</div>'), 'checkstyle': "standard", 'localfiletype': "po", 'treestyle': "auto", } tutorial = Project(**criteria) tutorial.save()
def test_no_root_hide_permissions(po_directory, nobody, default, admin, hide, view, no_projects, no_permission_sets, project_foo, project_bar, root): """Tests user-accessible projects when there are no `hide` permissions set at the root. """ ALL_PROJECTS = [project_foo.code, project_bar.code] foo_user = UserFactory.create(username='******') bar_user = UserFactory.create(username='******') # By default everyone has access to projects _require_permission_set(default, root, [view]) _require_permission_set(nobody, root, [view]) # At the same time, `project_foo` is inaccessible registered users... _require_permission_set(default, project_foo.directory, negative_permissions=[hide]) assert items_equal(Project.accessible_by_user(admin), ALL_PROJECTS) assert items_equal(Project.accessible_by_user(default), [project_bar.code]) assert items_equal(Project.accessible_by_user(nobody), [project_bar.code]) assert items_equal( Project.accessible_by_user(foo_user), [project_bar.code]) assert items_equal( Project.accessible_by_user(bar_user), [project_bar.code]) # ...and anonymous users as well _require_permission_set(nobody, project_foo.directory, negative_permissions=[hide]) assert items_equal(Project.accessible_by_user(nobody), [project_bar.code]) # Let's make `project_foo` accessible for `foo_user` _require_permission_set(foo_user, project_foo.directory, [view]) assert items_equal(Project.accessible_by_user(foo_user), ALL_PROJECTS) # `project_bar` is now inaccessible for anonymous users _require_permission_set(nobody, project_bar.directory, negative_permissions=[hide]) assert items_equal(Project.accessible_by_user(nobody), [])
def test_view_projects_browse(client, request_users): user = request_users["user"] client.login( username=user.username, password=request_users["password"]) response = client.get(reverse("pootle-projects-browse")) assert response.cookies["pootle-language"].value == "projects" ctx = response.context request = response.wsgi_request user_projects = Project.accessible_by_user(request.user) user_projects = ( Project.objects.for_user(request.user) .filter(code__in=user_projects)) obj = ProjectSet(user_projects) stats = obj.data_tool.get_stats(user=request.user) if request.user.is_superuser: url_action_continue = obj.get_translate_url(state='incomplete') url_action_fixcritical = obj.get_critical_url() url_action_review = obj.get_translate_url(state='suggestions') url_action_view_all = obj.get_translate_url(state='all') else: (url_action_continue, url_action_fixcritical, url_action_review, url_action_view_all) = [None] * 4 checks = ChecksDisplay(obj).checks_by_category stats = StatsDisplay(obj, stats=stats).stats del stats["children"] User = get_user_model() top_scorers = User.top_scorers(limit=10) assertions = dict( page="browse", pootle_path="/projects/", resource_path="", resource_path_parts=[], object=obj, browser_extends="projects/all/base.html", top_scorers=top_scorers, top_scorers_data=get_top_scorers_data(top_scorers, 10), translation_states=get_translation_states(obj), url_action_continue=url_action_continue, url_action_fixcritical=url_action_fixcritical, url_action_review=url_action_review, url_action_view_all=url_action_view_all, checks=checks, stats=stats) view_context_test(ctx, **assertions)
def notusedsource_to_pootle_project(self): """ Constructs a Pootle project from the article, if a project doesn't already exist. """ logging.debug ( "source_to_pootle_project" ) from pootle_app.models.signals import post_template_update if self.pootle_project_exists(): raise Exception("Project %s already exists!" % self.get_project_name()) # Fetch the source_language sl_set = Language.objects.filter(code = self.language) if len(sl_set) < 1: raise Exception("Language code %s does not exist!" % self.language) source_language = sl_set[0] logging.debug ( "source language" + source_language ) # Construct the project project = Project() project.fullname = self.get_project_name() project.code = self.get_project_code() project.source_language = source_language # Save the project project.save() logging.debug ( "project saved") # Export the article to .po and store in the templates "translation project". This will be used to generate translation requests for other languages. templatesProject = project.get_template_translationproject() po = self.sentences_to_po() poFilePath = "%s/article.pot" % (templatesProject.abs_real_path) oldstats = templatesProject.getquickstats() # Write the file with open(poFilePath, 'w') as f: f.write(po.__str__()) # Force the project to scan for changes. templatesProject.scan_files() templatesProject.update(conservative=False) # Log the changes newstats = templatesProject.getquickstats() post_template_update.send(sender=templatesProject, oldstats=oldstats, newstats=newstats) return project
def projects_index(request, root): """Page listing all projects.""" user_accessible_projects = Project.accessible_by_user(request.user) user_projects = Project.objects.filter(code__in=user_accessible_projects) items = [make_project_list_item(project) for project in user_projects] table_fields = ["name"] ctx = { "table": { "id": "projects", "fields": table_fields, "headings": get_table_headings(table_fields), "items": items, } } return render(request, "projects/list.html", ctx)
def create_default_projects(): """Create the default projects that we host. You might want to add your projects here, although you can also add things through the web interface later.""" from pootle_project.models import Project from pootle_app.management import require_english en = require_english() tutorial = Project(code=u"tutorial", source_language=en) tutorial.fullname = u"Tutorial" tutorial.description = "<div dir='ltr' lang='en'>Tutorial project " \ "where users can play with Pootle and learn " \ "more about translation and localisation." \ "<br />For more help on localisation, visit " \ "the <a href='http://translate.sourceforge.net/" \ "wiki/guide/start'>localisation guide</a>.</div>" tutorial.checkstyle = "standard" tutorial.localfiletype = "po" tutorial.treestyle = "auto" tutorial.save()
def test_get_contributors_projects(client, request_users): user = request_users["user"] if user.username != "nobody": client.login( username=user.username, password=request_users["password"]) directory = Directory.objects.projects response = client.get( "/xhr/stats/contributors/?path=%s" % directory.pootle_path, HTTP_X_REQUESTED_WITH='XMLHttpRequest') assert response.status_code == 200 result = json.loads(response.content) user_projects = Project.accessible_by_user(user) user_projects = ( Project.objects.for_user(user) .filter(code__in=user_projects)) top_scorers_data = get_top_scorers_test_data(ProjectSet(user_projects)) for k, v in result.items(): assert json.loads(json.dumps(top_scorers_data[k])) == v
def get_for_user(self, user): """Filters units for a specific user. - Admins always get all non-obsolete units - Regular users only get units from enabled projects accessible to them. :param user: The user for whom units need to be retrieved for. :return: A filtered queryset with `Unit`s for `user`. """ from pootle_project.models import Project if user.is_superuser: return self.live() user_projects = Project.accessible_by_user(user) filter_by = { "store__translation_project__project__disabled": False, "store__translation_project__project__code__in": user_projects } return self.live().filter(**filter_by)
def pootle_context(request): """Exposes settings to templates.""" # FIXME: maybe we should expose relevant settings only? return { 'settings': { 'POOTLE_TITLE': settings.POOTLE_TITLE, 'POOTLE_INSTANCE_ID': settings.POOTLE_INSTANCE_ID, 'POOTLE_CONTACT_ENABLED': (settings.POOTLE_CONTACT_ENABLED and settings.POOTLE_CONTACT_EMAIL), 'POOTLE_MARKUP_FILTER': get_markup_filter_name(), 'POOTLE_SIGNUP_ENABLED': settings.POOTLE_SIGNUP_ENABLED, 'SCRIPT_NAME': settings.SCRIPT_NAME, 'POOTLE_CACHE_TIMEOUT': settings.POOTLE_CACHE_TIMEOUT, 'DEBUG': settings.DEBUG, }, 'custom': settings.POOTLE_CUSTOM_TEMPLATE_CONTEXT, 'ALL_LANGUAGES': Language.live.cached_dict(translation.get_language()), 'ALL_PROJECTS': Project.accessible_by_user(request.user), 'SOCIAL_AUTH_PROVIDERS': jsonify(_get_social_auth_providers(request)), 'display_agreement': _agreement_context(request), }
def for_user(self, user, select_related=None): """Filters translation projects for a specific user. - Admins always get all translation projects. - Regular users only get enabled translation projects accessible to them. :param user: The user for whom the translation projects need to be retrieved for. :return: A filtered queryset with `TranslationProject`s for `user`. """ qs = self.live() if select_related is not None: qs = qs.select_related(*select_related) if user.is_superuser: return qs return qs.filter( project__disabled=False, project__code__in=Project.accessible_by_user(user))
def test_view_projects_browse(site_permissions, site_matrix_with_vfolders, site_matrix_with_announcements, client, nobody, default): response = client.get(reverse("pootle-projects-browse")) assert response.cookies["pootle-language"].value == "projects" ctx = response.context request = response.wsgi_request user_projects = Project.accessible_by_user(request.user) user_projects = ( Project.objects.for_user(request.user) .filter(code__in=user_projects)) ob = ProjectSet(user_projects) items = [ make_project_list_item(project) for project in ob.children] items.sort(lambda x, y: locale.strcoll(x['title'], y['title'])) table_fields = [ 'name', 'progress', 'total', 'need-translation', 'suggestions', 'critical', 'last-updated', 'activity'] table = { 'id': 'projects', 'fields': table_fields, 'headings': get_table_headings(table_fields), 'items': items} assertions = dict( page="browse", pootle_path="/projects/", resource_path="", resource_path_parts=[], object=ob, table=table, browser_extends="projects/all/base.html", stats=jsonify(ob.get_stats()), check_categories=get_qualitycheck_schema(ob), translation_states=get_translation_states(ob), url_action_continue=ob.get_translate_url(state='incomplete'), url_action_fixcritical=ob.get_critical_url(), url_action_review=ob.get_translate_url(state='suggestions'), url_action_view_all=ob.get_translate_url(state='all')) view_context_test(ctx, **assertions)
def test_view_projects_browse( site_permissions, site_matrix_with_vfolders, site_matrix_with_announcements, client, nobody, default ): response = client.get(reverse("pootle-projects-browse")) assert response.cookies["pootle-language"].value == "projects" ctx = response.context request = response.wsgi_request user_projects = Project.accessible_by_user(request.user) user_projects = Project.objects.for_user(request.user).filter(code__in=user_projects) ob = ProjectSet(user_projects) items = [make_project_list_item(project) for project in ob.children] items.sort(lambda x, y: locale.strcoll(x["title"], y["title"])) table_fields = [ "name", "progress", "total", "need-translation", "suggestions", "critical", "last-updated", "activity", ] table = {"id": "projects", "fields": table_fields, "headings": get_table_headings(table_fields), "items": items} assertions = dict( page="browse", pootle_path="/projects/", resource_path="", resource_path_parts=[], resource_obj=ob, table=table, browser_extends="projects/all/base.html", stats=jsonify(ob.get_stats()), check_categories=get_qualitycheck_schema(ob), translation_states=get_translation_states(ob), url_action_continue=ob.get_translate_url(state="incomplete"), url_action_fixcritical=ob.get_critical_url(), url_action_review=ob.get_translate_url(state="suggestions"), url_action_view_all=ob.get_translate_url(state="all"), ) view_context_test(ctx, **assertions)
def _source_to_pootle_project(article): # Fetch the source_language sl_set = Language.objects.filter(code=article.language) if len(sl_set) < 1: return false source_language = sl_set[0] # Construct the project project = Project() project.fullname = u"%s:%s" % (article.language, article.title) project.code = project.fullname.replace(" ", "_").replace(":", "_") # PO filetype # project.localfiletype = "po" # filetype_choices[0] project.source_language = source_language # Save the project project.save() return project
def create_pootle_project(self): ''' Creates a project to be used in Pootle. A templates language is created and a .pot template is generated from the SourceSentences in the article. ''' import logging from django.utils.encoding import smart_str from pootle_app.models.signals import post_template_update # Fetch the source_language sl_set = Language.objects.filter(code = self.language.code) if len(sl_set) < 1: return False source_language = sl_set[0] # 1. Construct the project project = Project() project.fullname = u"%s:%s" % (self.language.code, self.title) project.code = project.fullname.replace(" ", "_").replace(":", "_") # PO filetype #project.localfiletype = "po" # filetype_choices[0] project.source_language = source_language # Save the project project.save() templates_language = Language.objects.get_by_natural_key('templates') # Check to see if the templates language exists. If not, add it. #if not project.language_exists(templates_language): if len(project.translationproject_set.filter(language=templates_language)) == 0: project.add_language(templates_language) project.save() #code copied for wt_articles logging.debug ( "project saved") # 2. Export the article to .po and store in the templates "translation project". This will be used to generate translation requests for other languages. templatesProject = project.get_template_translationproject() po = self.sentences_to_po() poFilePath = "%s/article.pot" % (templatesProject.abs_real_path) oldstats = templatesProject.getquickstats() # Write the file with open(poFilePath, 'w') as f: f.write(smart_str(po.__str__())) # Force the project to scan for changes. templatesProject.scan_files() templatesProject.update(conservative=False) # Log the changes newstats = templatesProject.getquickstats() post_template_update.send(sender=templatesProject, oldstats=oldstats, newstats=newstats) # Add a reference to the project in the SourceArticle self.pootle_project = project self.save() return project
def test_create_project_bad(english): """Tests projects are not created with bad arguments.""" with pytest.raises(ValidationError): Project().save() with pytest.raises(ValidationError): Project(code="hello").save() with pytest.raises(ValidationError): Project(fullname="world").save() with pytest.raises(ValidationError): Project(source_language=english).save() with pytest.raises(ValidationError): Project(code="hello", fullname="world").save() with pytest.raises(ValidationError): Project(code="hello", source_language=english).save() with pytest.raises(ValidationError): Project(fullname="world", source_language=english).save() with pytest.raises(ValidationError): Project(code="", fullname="world", source_language=english).save() with pytest.raises(ValidationError): Project(code="hello", fullname="", source_language=english).save() with pytest.raises(ValidationError): Project(code=" ", fullname="world", source_language=english).save() with pytest.raises(ValidationError): Project(code="hello", fullname=" ", source_language=english).save()
def wrapped(request, *args, **kwargs): if request.is_ajax(): pootle_path = request.GET.get('path', None) if pootle_path is None: raise Http400(_('Arguments missing.')) language_code, project_code, dir_path, filename = \ split_pootle_path(pootle_path) kwargs['dir_path'] = dir_path kwargs['filename'] = filename # Remove potentially present but unwanted args try: del kwargs['language_code'] del kwargs['project_code'] except KeyError: pass else: language_code = kwargs.pop('language_code', None) project_code = kwargs.pop('project_code', None) if language_code and project_code: try: path_obj = TranslationProject.objects.get_for_user( user=request.user, language_code=language_code, project_code=project_code, ) except TranslationProject.DoesNotExist: path_obj = None if path_obj is None: if not request.is_ajax(): # Explicit selection via the UI: redirect either to # ``/language_code/`` or ``/projects/project_code/`` user_choice = request.COOKIES.get('user-choice', None) if user_choice and user_choice in ('language', 'project',): url = { 'language': reverse('pootle-language-browse', args=[language_code]), 'project': reverse('pootle-project-browse', args=[project_code, '', '']), } response = redirect(url[user_choice]) response.delete_cookie('user-choice') return response raise Http404 elif language_code: user_projects = Project.accessible_by_user(request.user) language = get_object_or_404(Language, code=language_code) children = language.children \ .filter(project__code__in=user_projects) language.set_children(children) path_obj = language elif project_code: try: path_obj = Project.objects.get_for_user(project_code, request.user) except Project.DoesNotExist: raise Http404 else: # No arguments: all user-accessible projects user_projects = Project.accessible_by_user(request.user) user_projects = Project.objects.for_user(request.user) \ .filter(code__in=user_projects) path_obj = ProjectSet(user_projects) request.ctx_obj = path_obj request.ctx_path = path_obj.pootle_path request.resource_obj = path_obj request.pootle_path = path_obj.pootle_path return func(request, path_obj, *args, **kwargs)
def test_root_hide_permissions(po_directory, nobody, default, admin, hide, view, no_permission_sets, no_projects, project_foo, project_bar, root): """Tests user-accessible projects when there are `hide` permissions set at the root. """ ALL_PROJECTS = [project_foo.code, project_bar.code] foo_user = UserFactory.create(username='******') bar_user = UserFactory.create(username='******') # By default all projects are not accessible _require_permission_set(default, root, negative_permissions=[hide]) _require_permission_set(nobody, root, negative_permissions=[hide]) assert items_equal(Project.accessible_by_user(admin), ALL_PROJECTS) assert items_equal(Project.accessible_by_user(default), []) assert items_equal(Project.accessible_by_user(nobody), []) assert items_equal(Project.accessible_by_user(foo_user), []) assert items_equal(Project.accessible_by_user(bar_user), []) # Now let's make `project_foo` accessible to `foo_user`. _require_permission_set(foo_user, project_foo.directory, [view]) assert items_equal(Project.accessible_by_user(admin), ALL_PROJECTS) assert items_equal(Project.accessible_by_user(default), []) assert items_equal(Project.accessible_by_user(nobody), []) assert items_equal( Project.accessible_by_user(foo_user), [project_foo.code]) assert items_equal(Project.accessible_by_user(bar_user), []) # Making projects accessible for anonymous users should open the door for # everyone _require_permission_set(nobody, root, [view]) assert items_equal(Project.accessible_by_user(admin), ALL_PROJECTS) assert items_equal(Project.accessible_by_user(default), ALL_PROJECTS) assert items_equal(Project.accessible_by_user(nobody), ALL_PROJECTS) assert items_equal(Project.accessible_by_user(foo_user), ALL_PROJECTS) assert items_equal(Project.accessible_by_user(bar_user), ALL_PROJECTS)
def wrapped(request, *args, **kwargs): if request.is_ajax(): pootle_path = request.GET.get('path', None) if pootle_path is None: raise Http400(_('Arguments missing.')) language_code, project_code, dir_path, filename = \ split_pootle_path(pootle_path) kwargs['dir_path'] = dir_path kwargs['filename'] = filename else: language_code = kwargs.pop('language_code', None) project_code = kwargs.pop('project_code', None) if language_code and project_code: try: path_obj = TranslationProject.objects.live().get( language__code=language_code, project__code=project_code, ) except TranslationProject.DoesNotExist: path_obj = None if path_obj is None and not request.is_ajax(): # Explicit selection via the UI: redirect either to # ``/language_code/`` or ``/projects/project_code/`` user_choice = request.COOKIES.get('user-choice', None) if user_choice and user_choice in ( 'language', 'project', ): url = { 'language': reverse('pootle-language-overview', args=[language_code]), 'project': reverse('pootle-project-overview', args=[project_code, '', '']), } response = redirect(url[user_choice]) response.delete_cookie('user-choice') return response raise Http404 elif language_code: user_projects = Project.accessible_by_user(request.user) language = get_object_or_404(Language, code=language_code) children = language.children \ .filter(project__code__in=user_projects) language.set_children(children) path_obj = language elif project_code: try: path_obj = Project.objects.get_for_user( project_code, request.user) except Project.DoesNotExist: raise Http404 else: # No arguments: all user-accessible projects user_projects = Project.accessible_by_user(request.user) user_projects = Project.objects.for_user(request.user) \ .filter(code__in=user_projects) path_obj = ProjectSet(user_projects) request.ctx_obj = path_obj request.ctx_path = path_obj.pootle_path request.resource_obj = path_obj request.pootle_path = path_obj.pootle_path return func(request, path_obj, *args, **kwargs)
def test_create_project_good(english): """Tests projects are created with valid arguments only.""" proj = Project(code="hello", fullname="world", source_language=english) proj.save() proj.delete() code_with_padding = " hello " fullname_with_padding = " world " proj = Project(code=code_with_padding, fullname="world", source_language=english) proj.save() assert proj.code == code_with_padding.strip() proj.delete() proj = Project(code="hello", fullname=fullname_with_padding, source_language=english) proj.save() assert proj.fullname == fullname_with_padding.strip() proj.delete() proj = Project(code=code_with_padding, fullname=fullname_with_padding, source_language=english) proj.save() assert proj.code == code_with_padding.strip() assert proj.fullname == fullname_with_padding.strip() proj.delete()
def test_root_view_permissions(po_directory, nobody, default, admin, view, no_projects, no_permission_sets, project_foo, project_bar, root): """Tests user-accessible projects with view permissions at the root.""" ALL_PROJECTS = [project_foo.code, project_bar.code] foo_user = UserFactory.create(username='******') bar_user = UserFactory.create(username='******') # We'll only give `bar_user` access to all projects server-wide _require_permission_set(bar_user, root, [view]) assert items_equal(Project.accessible_by_user(admin), ALL_PROJECTS) assert items_equal(Project.accessible_by_user(bar_user), ALL_PROJECTS) assert items_equal(Project.accessible_by_user(foo_user), []) assert items_equal(Project.accessible_by_user(default), []) assert items_equal(Project.accessible_by_user(nobody), []) # Now we'll also allow `foo_user` access `project_foo` _require_permission_set(foo_user, project_foo.directory, [view]) assert items_equal( Project.accessible_by_user(foo_user), [project_foo.code]) # Let's change server-wide defaults: all registered users have access to # all projects. `foo_user`, albeit having explicit access for # `project_foo`, will be able to access any project because they fall back # and extend with the defaults. _require_permission_set(default, root, [view]) assert items_equal(Project.accessible_by_user(admin), ALL_PROJECTS) assert items_equal(Project.accessible_by_user(foo_user), ALL_PROJECTS) assert items_equal(Project.accessible_by_user(bar_user), ALL_PROJECTS) assert items_equal(Project.accessible_by_user(default), ALL_PROJECTS) assert items_equal(Project.accessible_by_user(nobody), []) # Let's give anonymous users access to all projects too _require_permission_set(nobody, root, [view]) assert items_equal(Project.accessible_by_user(nobody), ALL_PROJECTS)
def test_root_view_permissions(nobody, default, admin, view, project_foo, project_bar, root): """Tests user-accessible projects with view permissions at the root.""" ALL_PROJECTS = [project_foo.code, project_bar.code] foo_user = UserFactory.create(username='******') bar_user = UserFactory.create(username='******') # We'll only give `bar_user` access to all projects server-wide _require_permission_set(bar_user, root, [view]) assert items_equal(Project.accessible_by_user(admin), ALL_PROJECTS) assert items_equal(Project.accessible_by_user(bar_user), ALL_PROJECTS) assert items_equal(Project.accessible_by_user(foo_user), []) assert items_equal(Project.accessible_by_user(default), []) assert items_equal(Project.accessible_by_user(nobody), []) # Now we'll also allow `foo_user` access `project_foo` _require_permission_set(foo_user, project_foo.directory, [view]) assert items_equal(Project.accessible_by_user(foo_user), [project_foo.code]) # Let's change server-wide defaults: all registered users have access # to all projects. `foo_user`, albeit having explicit access for # `project_foo`, will be able to access any project because they fall # back and extend with the defaults. _require_permission_set(default, root, [view]) assert items_equal(Project.accessible_by_user(admin), ALL_PROJECTS) assert items_equal(Project.accessible_by_user(foo_user), ALL_PROJECTS) assert items_equal(Project.accessible_by_user(bar_user), ALL_PROJECTS) assert items_equal(Project.accessible_by_user(default), ALL_PROJECTS) assert items_equal(Project.accessible_by_user(nobody), []) # Let's give anonymous users access to all projects too _require_permission_set(nobody, root, [view]) assert items_equal(Project.accessible_by_user(nobody), ALL_PROJECTS)
def test_root_hide_permissions(nobody, default, admin, hide, view, no_permission_sets, no_projects, project_foo, project_bar, root): """Tests user-accessible projects when there are `hide` permissions set at the root. """ ALL_PROJECTS = [project_foo.code, project_bar.code] foo_user = UserFactory.create(username='******') bar_user = UserFactory.create(username='******') # By default all projects are not accessible _require_permission_set(default, root, negative_permissions=[hide]) _require_permission_set(nobody, root, negative_permissions=[hide]) assert items_equal(Project.accessible_by_user(admin), ALL_PROJECTS) assert items_equal(Project.accessible_by_user(default), []) assert items_equal(Project.accessible_by_user(nobody), []) assert items_equal(Project.accessible_by_user(foo_user), []) assert items_equal(Project.accessible_by_user(bar_user), []) # Now let's make `project_foo` accessible to `foo_user`. _require_permission_set(foo_user, project_foo.directory, [view]) assert items_equal(Project.accessible_by_user(admin), ALL_PROJECTS) assert items_equal(Project.accessible_by_user(default), []) assert items_equal(Project.accessible_by_user(nobody), []) assert items_equal(Project.accessible_by_user(foo_user), [project_foo.code]) assert items_equal(Project.accessible_by_user(bar_user), []) # Making projects accessible for anonymous users should open the door for # everyone _require_permission_set(nobody, root, [view]) assert items_equal(Project.accessible_by_user(admin), ALL_PROJECTS) assert items_equal(Project.accessible_by_user(default), ALL_PROJECTS) assert items_equal(Project.accessible_by_user(nobody), ALL_PROJECTS) assert items_equal(Project.accessible_by_user(foo_user), ALL_PROJECTS) assert items_equal(Project.accessible_by_user(bar_user), ALL_PROJECTS)