id
int64 0
458k
| file_name
stringlengths 4
119
| file_path
stringlengths 14
227
| content
stringlengths 24
9.96M
| size
int64 24
9.96M
| language
stringclasses 1
value | extension
stringclasses 14
values | total_lines
int64 1
219k
| avg_line_length
float64 2.52
4.63M
| max_line_length
int64 5
9.91M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 7
101
| repo_stars
int64 100
139k
| repo_forks
int64 0
26.4k
| repo_open_issues
int64 0
2.27k
| repo_license
stringclasses 12
values | repo_extraction_date
stringclasses 433
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
15,000
|
util.py
|
translate_pootle/tests/formats/util.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import pytest
from pytest_pootle.factories import ProjectDBFactory, TranslationProjectFactory
from pootle.core.delegate import formats
from pootle_format.exceptions import UnrecognizedFiletype
from pootle_format.models import Format
from pootle_store.models import Store
@pytest.mark.django_db
def test_format_util(project0):
filetype_tool = project0.filetype_tool
assert list(filetype_tool.filetypes.all()) == list(project0.filetypes.all())
assert filetype_tool.filetype_extensions == [u"po"]
assert filetype_tool.template_extensions == [u"pot"]
assert filetype_tool.valid_extensions == [u"po", u"pot"]
xliff = Format.objects.get(name="xliff")
project0.filetypes.add(xliff)
del project0.__dict__["filetype_tool"]
filetype_tool = project0.filetype_tool
assert filetype_tool.filetype_extensions == [u"po", u"xliff"]
assert filetype_tool.template_extensions == [u"pot", u"xliff"]
assert filetype_tool.valid_extensions == [u"po", u"xliff", u"pot"]
ts = Format.objects.get(name="ts")
filetype_tool.add_filetype(ts)
del project0.__dict__["filetype_tool"]
filetype_tool = project0.filetype_tool
assert filetype_tool.filetype_extensions == [u"po", u"xliff", u"ts"]
assert filetype_tool.template_extensions == [u"pot", u"xliff", u"ts"]
assert (
sorted(filetype_tool.valid_extensions)
== [u"po", u"pot", u"ts", u"xliff"])
@pytest.mark.django_db
def test_format_chooser(project0):
registry = formats.get()
po = Format.objects.get(name="po")
po2 = registry.register("special_po_2", "po")
po3 = registry.register("special_po_3", "po")
xliff = Format.objects.get(name="xliff")
project0.filetypes.add(xliff)
project0.filetypes.add(po2)
project0.filetypes.add(po3)
filetype_tool = project0.filetype_tool
assert filetype_tool.choose_filetype("foo.po") == po
assert filetype_tool.choose_filetype("foo.pot") == po
assert filetype_tool.choose_filetype("foo.xliff") == xliff
# push po to the back of the queue
project0.filetypes.remove(po)
project0.filetypes.add(po)
assert filetype_tool.choose_filetype("foo.po") == po2
assert filetype_tool.choose_filetype("foo.pot") == po
assert filetype_tool.choose_filetype("foo.xliff") == xliff
with pytest.raises(UnrecognizedFiletype):
filetype_tool.choose_filetype("foo.bar")
@pytest.mark.django_db
def test_format_add_project_filetype(project0, po2):
project = project0
project.filetype_tool.add_filetype(po2)
assert po2 in project.filetypes.all()
# adding a 2nd time does nothing
project.filetype_tool.add_filetype(po2)
assert project.filetypes.filter(pk=po2.pk).count() == 1
@pytest.mark.django_db
def test_format_set_store_filetype(project0):
project = project0
store = Store.objects.exclude(is_template=True).filter(
translation_project__project=project).first()
store_name = store.name
registry = formats.get()
filetypes = project.filetype_tool
# register po2
po2 = registry.register(
"special_po_2", "po", template_extension="pot2")
# filetype must be recognized for project
with pytest.raises(UnrecognizedFiletype):
filetypes.set_store_filetype(store, po2)
# add the filetype to the project
filetypes.add_filetype(po2)
# set the store's filetype
filetypes.set_store_filetype(store, po2)
# the filetype is changed, but the extension is the same
store = Store.objects.get(pk=store.pk)
assert store.filetype == po2
assert store.name == store_name
# register po3 - different extension
po3 = registry.register(
"special_po_3", "po3", template_extension="pot3")
filetypes.add_filetype(po3)
filetypes.set_store_filetype(store, po3)
# the filetype is changed, and the extension
store = Store.objects.get(pk=store.pk)
assert store.filetype == po3
assert store.name.endswith(".po3")
assert store.pootle_path.endswith(".po3")
@pytest.mark.django_db
def test_format_set_template_store_filetype(po_directory, templates, po):
project = ProjectDBFactory(source_language=templates)
filetypes = project.filetype_tool
tp = TranslationProjectFactory(language=templates, project=project)
registry = formats.get()
store = Store.objects.create(
name="mystore.pot",
translation_project=tp,
parent=tp.directory)
store_name = store.name
assert store.filetype == po
assert store.is_template
assert store.name.endswith(".pot")
# register po2 - same template extension
po2 = registry.register(
"special_po_2", "po2", template_extension="pot")
filetypes.add_filetype(po2)
filetypes.set_store_filetype(store, po2)
# the filetype is changed, but the extension is the same
store = Store.objects.get(pk=store.pk)
assert store.filetype == po2
assert store.name == store_name
# register po3 - same template extension
po3 = registry.register(
"special_po_3", "po", template_extension="pot3")
filetypes.add_filetype(po3)
filetypes.set_store_filetype(store, po3)
# the filetype and extension are changed
store = Store.objects.get(pk=store.pk)
assert store.filetype == po3
assert store.name.endswith(".pot3")
# does nothing
filetypes.set_store_filetype(store, po3)
assert store.filetype == po3
@pytest.mark.django_db
def test_format_set_native_store_filetype(po_directory, templates,
language0, po2, english):
project = ProjectDBFactory(source_language=english)
filetypes = project.filetype_tool
registry = formats.get()
templates_tp = TranslationProjectFactory(language=templates, project=project)
lang_tp = TranslationProjectFactory(language=language0, project=project)
template = Store.objects.create(
name="mystore.pot3.pot",
translation_project=templates_tp,
parent=templates_tp.directory)
store = Store.objects.create(
name="mystore.po3.po",
translation_project=lang_tp,
parent=lang_tp.directory)
# register po2 - not native template extension
filetypes.add_filetype(po2)
filetypes.set_store_filetype(store, po2)
assert store.name.endswith(".po3.po2")
assert store.filetype == po2
filetypes.set_store_filetype(template, po2)
assert template.name.endswith(".pot3.pot2")
assert template.filetype == po2
# register po3 - native template extension
po3 = registry.register(
"special_po_3", "po3", template_extension="pot3")
filetypes.add_filetype(po3)
# in this case extension is just removed
filetypes.set_store_filetype(store, po3)
assert not store.name.endswith(".po3.po3")
assert store.name.endswith(".po3")
assert store.filetype == po3
filetypes.set_store_filetype(template, po3)
assert not template.name.endswith(".pot3.pot3")
assert template.name.endswith(".pot3")
assert template.filetype == po3
@pytest.mark.django_db
def test_format_set_tp_from_store_filetype(po_directory, templates,
language0, po, po2):
project = ProjectDBFactory(source_language=templates)
filetypes = project.filetype_tool
registry = formats.get()
templates_tp = TranslationProjectFactory(language=templates, project=project)
lang_tp = TranslationProjectFactory(language=language0, project=project)
template = Store.objects.create(
name="mystore.pot",
translation_project=templates_tp,
parent=templates_tp.directory)
store = Store.objects.create(
name="mystore.po",
translation_project=lang_tp,
parent=lang_tp.directory)
po3 = registry.register(
"special_po_3", "po3", template_extension="pot3")
filetypes.add_filetype(po2)
filetypes.add_filetype(po3)
# this does nothing as the stores are currently po
filetypes.set_tp_filetype(lang_tp, po3, from_filetype=po2)
store = Store.objects.get(pk=store.pk)
assert store.filetype == po
assert store.name.endswith(".po")
filetypes.set_tp_filetype(templates_tp, po3, from_filetype=po2)
template = Store.objects.get(pk=template.pk)
assert template.filetype == po
assert template.name.endswith(".pot")
# it works if we switch to po2 first
filetypes.set_tp_filetype(lang_tp, po2, from_filetype=po)
filetypes.set_tp_filetype(templates_tp, po2, from_filetype=po)
filetypes.set_tp_filetype(lang_tp, po3, from_filetype=po2)
store = Store.objects.get(pk=store.pk)
assert store.filetype == po3
assert store.name.endswith(".po3")
filetypes.set_tp_filetype(templates_tp, po3, from_filetype=po2)
template = Store.objects.get(pk=template.pk)
assert template.filetype == po3
assert template.name.endswith(".pot3")
@pytest.mark.django_db
def test_format_set_templates_tp_filetype(po_directory, templates, po2):
project = ProjectDBFactory(source_language=templates)
filetypes = project.filetype_tool
registry = formats.get()
templates_tp = TranslationProjectFactory(language=templates, project=project)
template = Store.objects.create(
name="mystore.pot",
translation_project=templates_tp,
parent=templates_tp.directory)
filetypes.add_filetype(po2)
filetypes.set_tp_filetype(templates_tp, po2)
template = Store.objects.get(pk=template.pk)
assert template.filetype == po2
assert template.name.endswith(".pot2")
po3 = registry.register(
"special_po_3", "po3", template_extension="pot3")
filetypes.add_filetype(po3)
filetypes.set_tp_filetype(templates_tp, po3)
template = Store.objects.get(pk=template.pk)
assert template.filetype == po3
assert template.name.endswith(".pot3")
@pytest.mark.django_db
def test_format_set_tp_filetype(po_directory, english, language0, po2):
project = ProjectDBFactory(source_language=english)
filetypes = project.filetype_tool
registry = formats.get()
lang_tp = TranslationProjectFactory(language=language0, project=project)
store = Store.objects.create(
name="mystore.po",
translation_project=lang_tp,
parent=lang_tp.directory)
filetypes.add_filetype(po2)
filetypes.set_tp_filetype(lang_tp, po2)
store = Store.objects.get(pk=store.pk)
assert store.filetype == po2
assert store.name.endswith(".po2")
po3 = registry.register(
"special_po_3", "po3", template_extension="pot")
filetypes.add_filetype(po3)
filetypes.set_tp_filetype(lang_tp, po3)
store = Store.objects.get(pk=store.pk)
assert store.filetype == po3
assert store.name.endswith(".po3")
@pytest.mark.django_db
def test_format_set_template_tp_matching_filetype(po_directory, templates,
po, po2, english):
project = ProjectDBFactory(source_language=english)
filetypes = project.filetype_tool
tp = TranslationProjectFactory(project=project, language=templates)
filetypes.add_filetype(po2)
template5 = Store.objects.create_by_path(
"/templates/%s/subdir/store5.pot" % project.code)
assert template5.filetype == po
filetypes.set_tp_filetype(tp, po2, matching="store5")
# doesnt match - because its in a subdir
template5 = Store.objects.get(pk=template5.pk)
assert template5.filetype == po
filetypes.set_tp_filetype(tp, po2, matching="*store5")
template5 = Store.objects.get(pk=template5.pk)
assert template5.filetype == po2
filetypes.set_tp_filetype(tp, po, matching="*/*5")
template5 = Store.objects.get(pk=template5.pk)
assert template5.filetype == po
@pytest.mark.django_db
def test_format_set_tp_matching_filetype(tp0, po, po2):
project = tp0.project
project.filetype_tool.add_filetype(po2)
store5 = tp0.stores.get(name="store5.po")
assert store5.filetype == po
project.filetype_tool.set_tp_filetype(tp0, po2, matching="store5")
# doesnt match - because its in a subdir
store5 = Store.objects.get(pk=store5.pk)
assert store5.filetype == po
project.filetype_tool.set_tp_filetype(tp0, po2, matching="*store5")
store5 = Store.objects.get(pk=store5.pk)
assert store5.filetype == po2
project.filetype_tool.set_tp_filetype(tp0, po, matching="*/*5")
store5 = Store.objects.get(pk=store5.pk)
assert store5.filetype == po
@pytest.mark.django_db
def test_format_set_project_filetypes(templates_project0,
dummy_project_filetypes, po2):
project = templates_project0.project
template_tp = templates_project0
other_tps = project.translationproject_set.exclude(
pk=template_tp.pk)
filetype_tool = project.filetype_tool
result = filetype_tool.result
with pytest.raises(UnrecognizedFiletype):
filetype_tool.set_filetypes(po2)
filetype_tool.add_filetype(po2)
filetype_tool.set_filetypes(po2)
assert result[0] == (template_tp, po2, None, None)
for i, tp in enumerate(other_tps):
assert result[i + 1] == (tp, po2, None, None)
# test getting from_filetype
result.clear()
filetype_tool.set_filetypes(po2, from_filetype="foo")
assert result[0] == (template_tp, po2, "foo", None)
for i, tp in enumerate(other_tps):
assert result[i + 1] == (tp, po2, "foo", None)
# test getting match
result.clear()
filetype_tool.set_filetypes(po2, matching="bar")
assert result[0] == (template_tp, po2, None, "bar")
for i, tp in enumerate(other_tps):
assert result[i + 1] == (tp, po2, None, "bar")
# test getting both
result.clear()
filetype_tool.set_filetypes(po2, from_filetype="foo", matching="bar")
assert result[0] == (template_tp, po2, "foo", "bar")
for i, tp in enumerate(other_tps):
assert result[i + 1] == (tp, po2, "foo", "bar")
| 14,191
|
Python
|
.py
| 324
| 38.058642
| 81
| 0.706739
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,001
|
mozilla_lang.py
|
translate_pootle/tests/formats/mozilla_lang.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import pytest
from pytest_pootle.factories import StoreDBFactory
from pootle_format.models import Format
from pootle_store.constants import FUZZY, TRANSLATED
from pootle_store.models import Unit
@pytest.mark.django_db
def test_mozlang_update(tp0):
mozlang = Format.objects.get(name="lang")
tp0.project.filetypes.add(mozlang)
foo_lang = StoreDBFactory(
name="foo.lang",
filetype=mozlang,
parent=tp0.directory,
translation_project=tp0)
store0 = tp0.stores.get(name="store0.po")
# deserialize as source
foo_lang.update(store0.deserialize(store0.serialize()))
# get serialized lang store
serialized = foo_lang.serialize()
# mark a translated unit as fuzzy
translated = foo_lang.units.filter(state=TRANSLATED).first()
translated.state = FUZZY
translated.save()
# source is translated
old_ttk = foo_lang.deserialize(serialized)
foo_lang.update(old_ttk)
# unit is still fuzzy
translated.refresh_from_db()
assert translated.state == FUZZY
# source target changes state also gets updated
old_ttk.findid(translated.getid()).target = "something else {ok}"
foo_lang.update(old_ttk, store_revision=translated.revision)
translated.refresh_from_db()
assert translated.state == TRANSLATED
translated = foo_lang.units.filter(state=TRANSLATED).first()
translated.state = FUZZY
translated.save()
# set target == "" > untranslated
ttk = foo_lang.deserialize(serialized)
ttkunit = ttk.findid(translated.getid())
ttkunit.target = ""
foo_lang.update(ttk)
# unit stays FUZZY
translated = Unit.objects.get(pk=translated.pk)
assert translated.state == FUZZY
@pytest.mark.django_db
def test_mozlang_sync(tp0):
mozlang = Format.objects.get(name="lang")
tp0.project.filetypes.add(mozlang)
foo_lang = StoreDBFactory(
name="foo.lang",
filetype=mozlang,
parent=tp0.directory,
translation_project=tp0)
store0 = tp0.stores.get(name="store0.po")
# deserialize as source
foo_lang.update(store0.deserialize(store0.serialize()))
# mark the unit as fuzzy
unit = foo_lang.units.filter(state=TRANSLATED).first()
unit.markfuzzy()
unit.save()
ttk = foo_lang.deserialize(foo_lang.serialize())
ttk_unit = ttk.findid(unit.getid())
assert not ttk_unit.istranslated()
| 2,668
|
Python
|
.py
| 71
| 32.732394
| 77
| 0.720109
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,002
|
utils.py
|
translate_pootle/tests/pootle_translationproject/utils.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import pytest
from pytest_pootle.factories import (
LanguageDBFactory, ProjectDBFactory, TranslationProjectFactory)
from pytest_pootle.utils import create_store
from translate.filters.decorators import Category
from translate.misc.multistring import multistring
from pootle.core.plugin import getter
from pootle.core.delegate import paths, tp_tool
from pootle.core.url_helpers import split_pootle_path
from pootle_app.models import Directory
from pootle_language.models import Language
from pootle_project.models import Project
from pootle_store.models import Store
from pootle_translationproject.utils import TPPaths, TPTool
@pytest.mark.django_db
def test_paths_tp_util(tp0):
tp_paths = paths.get(tp0.__class__)(tp0, "1")
assert isinstance(tp_paths, TPPaths)
assert tp_paths.context == tp0
assert (
sorted(tp_paths.store_qs.values_list("pk", flat=True))
== sorted(
tp0.stores.values_list(
"pk", flat=True)))
@pytest.mark.django_db
def test_tp_tool_move(language0, project0, templates, no_templates_tps):
tp = project0.translationproject_set.get(language=language0)
original_stores = list(tp.stores.all())
TPTool(project0).move(tp, templates)
assert tp.language == templates
assert (
tp.pootle_path
== tp.directory.pootle_path
== "/%s/%s/" % (templates.code, project0.code))
assert tp.directory.parent == templates.directory
# all of the stores and their directories are updated
for store in original_stores:
store = Store.objects.get(pk=store.pk)
assert store.pootle_path.startswith(tp.pootle_path)
assert store.parent.pootle_path.startswith(tp.pootle_path)
assert not Store.objects.filter(
pootle_path__startswith="/%s/%s/"
% (language0.code, project0.code))
assert not Directory.objects.filter(
pootle_path__startswith="/%s/%s/"
% (language0.code, project0.code))
# calling with already set language does nothing
assert TPTool(project0).move(tp, templates) is None
@pytest.mark.django_db
def test_tp_tool_bad(po_directory, tp0, templates, english, no_templates_tps):
other_project = ProjectDBFactory(source_language=english)
other_tp = TranslationProjectFactory(
project=other_project,
language=LanguageDBFactory())
tp_tool = TPTool(tp0.project)
with pytest.raises(ValueError):
tp_tool.check_tp(other_tp)
with pytest.raises(ValueError):
tp_tool.set_parents(tp0.directory, other_tp.directory)
with pytest.raises(ValueError):
tp_tool.set_parents(other_tp.directory, tp0.directory)
with pytest.raises(ValueError):
tp_tool.move(other_tp, templates)
with pytest.raises(ValueError):
tp_tool.clone(other_tp, templates)
with pytest.raises(ValueError):
# cant set tp to a language if a tp already exists
tp_tool.move(
tp0, Language.objects.get(code="language1"))
with pytest.raises(ValueError):
# cant clone tp to a language if a tp already exists
tp_tool.clone(
tp0, Language.objects.get(code="language1"))
def _test_tp_match(source_tp, target_tp, project=None, update=False):
source_stores = []
for store in source_tp.stores.live():
source_stores.append(store.pootle_path)
project_code = (
project and project.code or source_tp.project.code)
store_path = "".join(split_pootle_path(store.pootle_path)[2:])
update_path = (
"/%s/%s/%s"
% (target_tp.language.code,
project_code,
store_path))
updated = Store.objects.get(pootle_path=update_path)
assert store.state == updated.state
updated_units = updated.units
for i, unit in enumerate(store.units):
updated_unit = updated_units[i]
assert unit.source == updated_unit.source
assert unit.target == updated_unit.target
assert unit.state == updated_unit.state
assert unit.getcontext() == updated_unit.getcontext()
assert unit.getlocations() == updated_unit.getlocations()
assert unit.hasplural() == updated_unit.hasplural()
# # these tests dont work yet
# assert unit.created_by == updated_unit.created_by
# assert unit.submitted_by == updated_unit.submitted_by
# assert unit.reviewed_by == updated_unit.reviewed_by
for store in target_tp.stores.live():
store_path = "".join(split_pootle_path(store.pootle_path)[2:])
source_path = (
"/%s/%s/%s"
% (source_tp.language.code,
source_tp.project.code,
store_path))
assert source_path in source_stores
if not update:
assert source_tp.stores.count() == target_tp.stores.count()
@pytest.mark.django_db
def test_tp_tool_clone(po_directory, tp0, templates):
new_lang = LanguageDBFactory()
tp_tool = TPTool(tp0.project)
_test_tp_match(tp0, tp_tool.clone(tp0, new_lang))
@pytest.mark.django_db
def test_tp_tool_update(po_directory, tp0, templates):
new_lang = LanguageDBFactory()
tp0_tool = TPTool(tp0.project)
new_tp = tp0.project.translationproject_set.create(
language=new_lang)
# this will clone stores/directories as new_tp is empty
tp0_tool.update_from_tp(tp0, new_tp)
_test_tp_match(tp0, new_tp, update=True)
tp0_tool.update_from_tp(tp0, new_tp)
tp0.stores.first().delete()
tp0.stores.first().units.first().delete()
unit = tp0.stores.first().units.first()
unit.source = multistring(["NEW TARGET", "NEW TARGETS"])
unit.target = "NEW TARGET"
unit.context = "something-else"
unit.save()
newunit = unit.__class__()
newunit.source = multistring(["OTHER NEW TARGET", "OTHER NEW TARGETS"])
newunit.target = "OTHER NEW TARGET"
newunit.context = "something-else-again"
unit.store.addunit(newunit)
update_unit = unit.store.units.exclude(
source_f__in=[unit.source_f, newunit.source_f]).first()
update_unit.target = "UPDATED TARGET"
update_unit.save()
tp0_tool.update_from_tp(tp0, new_tp)
_test_tp_match(tp0, new_tp, update=True)
# doing another update does nothing
tp0_tool.update_from_tp(tp0, new_tp)
_test_tp_match(tp0, new_tp, update=True)
@pytest.mark.django_db
def test_tp_tool_getter(project0_directory, project0):
assert tp_tool.get(Project) is TPTool
assert isinstance(project0.tp_tool, TPTool)
@pytest.mark.django_db
def test_tp_tool_custom_getter(project0, no_tp_tool):
class CustomTPTool(TPTool):
pass
with no_tp_tool():
@getter(tp_tool, sender=Project, weak=False)
def custom_tp_tool_getter(**kwargs_):
return CustomTPTool
assert tp_tool.get(Project) is CustomTPTool
assert isinstance(project0.tp_tool, CustomTPTool)
@pytest.mark.django_db
def test_tp_tool_gets(project0, tp0):
assert project0.tp_tool[tp0.language.code] == tp0
assert project0.tp_tool.get(tp0.language.code) == tp0
assert project0.tp_tool.get("TP_DOES_NOT_EXIST") is None
assert project0.tp_tool.get("TP_DOES_NOT_EXIST", "FOO") == "FOO"
with pytest.raises(tp0.DoesNotExist):
project0.tp_tool["DOES_NOT_EXIST"]
@pytest.mark.django_db
def test_tp_tool_move_project(language0, project0, project1,
templates, no_templates_tps):
tp = project0.translationproject_set.get(language=language0)
original_stores = list(tp.stores.all())
TPTool(project0).move(tp, templates, project1)
assert tp.language == templates
assert (
tp.pootle_path
== tp.directory.pootle_path
== "/%s/%s/" % (templates.code, project1.code))
assert tp.directory.parent == templates.directory
# all of the stores and their directories are updated
for store in original_stores:
store.refresh_from_db()
assert store.pootle_path.startswith(tp.pootle_path)
assert store.parent.pootle_path.startswith(tp.pootle_path)
assert not Store.objects.filter(
pootle_path__startswith="/%s/%s"
% (language0.code, project0.code))
assert not Directory.objects.filter(
pootle_path__startswith="/%s/%s/"
% (language0.code, project0.code))
@pytest.mark.django_db
def test_tp_tool_clone_project(tp0, project1, member):
new_lang = LanguageDBFactory()
tp_tool = TPTool(tp0.project)
_test_tp_match(
tp0,
tp_tool.clone(tp0, new_lang, project1),
project1)
@pytest.mark.django_db
def test_tp_tool_clone_project_same_lang(tp0, english):
new_proj = ProjectDBFactory(source_language=english)
tp_tool = TPTool(tp0.project)
_test_tp_match(
tp0,
tp_tool.clone(tp0, tp0.language, new_proj),
new_proj)
@pytest.mark.django_db
def test_tp_tool_store_clone_with_checks(store_po, system):
store_po.update(create_store(pootle_path=store_po.pootle_path, units=[
("Hello", "", False)
]))
unit = store_po.units.first()
unit.target = "Hello\n\nHello"
unit.save()
check_qs = unit.qualitycheck_set.filter(
category=Category.CRITICAL,
false_positive=False)
assert check_qs.count() == 1
check_id = check_qs[0].id
unit.toggle_qualitycheck(check_id=check_id, false_positive=True,
user=system)
assert unit.qualitycheck_set.get(id=check_id).false_positive
tool = tp_tool.get(Project)(store_po.translation_project.project)
directory = store_po.translation_project.directory.child_dirs.first()
cloned_store = tool.clone_store(store_po, directory)
cloned_unit = cloned_store.units[0]
check_qs = cloned_unit.qualitycheck_set.filter(category=Category.CRITICAL)
assert check_qs.count() == 1
assert check_qs[0].false_positive
| 10,193
|
Python
|
.py
| 237
| 36.362869
| 78
| 0.683365
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,003
|
panels.py
|
translate_pootle/tests/pootle_translationproject/panels.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import pytest
from django.template import loader
from pootle.core.browser import get_table_headings
from pootle.core.delegate import panels
from pootle_app.models.permissions import get_matching_permissions
from pootle_app.panels import ChildrenPanel
from pootle_translationproject.views import TPBrowseView
from virtualfolder.panels import VFolderPanel
@pytest.mark.django_db
def test_panel_tp_table(tp0, rf, member):
request = rf.get('/language0/project0/')
request.user = member
request.permissions = get_matching_permissions(
request.user,
tp0.directory)
view = TPBrowseView(
kwargs=dict(
language_code=tp0.language.code,
project_code=tp0.project.code))
view.request = request
view.object = view.get_object()
lang_panels = panels.gather(TPBrowseView)
assert lang_panels.keys() == ["children", "vfolders"]
assert lang_panels["children"] == ChildrenPanel
panel = ChildrenPanel(view)
assert panel.panel_name == "children"
assert (
panel.cache_key
== ("panel.%s.%s"
% (panel.panel_name, view.cache_key)))
table = {
'id': view.view_name,
'fields': panel.table_fields,
'headings': get_table_headings(panel.table_fields),
'rows': view.object_children}
assert panel.table == table
assert panel.get_context_data() == dict(
table=table, can_translate=view.can_translate)
content = loader.render_to_string(
panel.template_name, context=panel.get_context_data())
assert (
panel.content
== panel.update_times(content))
@pytest.mark.pootle_vfolders
@pytest.mark.django_db
def test_panel_tp_vfolder_table(tp0, rf, member):
request = rf.get('/language0/project0/')
request.user = member
request.permissions = get_matching_permissions(
request.user,
tp0.directory)
view = TPBrowseView(
kwargs=dict(
language_code=tp0.language.code,
project_code=tp0.project.code))
view.request = request
view.object = view.get_object()
lang_panels = panels.gather(TPBrowseView)
assert lang_panels.keys() == ["children", "vfolders"]
assert lang_panels["vfolders"] == VFolderPanel
panel = VFolderPanel(view)
assert panel.panel_name == "vfolder"
assert (
panel.cache_key
== ("panel.%s.%s"
% (panel.panel_name, view.cache_key)))
table = view.vfolders_data_view.table_data["children"]
assert panel.table == table
assert panel.get_context_data() == dict(
table=table, can_translate=view.can_translate)
content = loader.render_to_string(
panel.template_name, context=panel.get_context_data())
assert (
panel.content
== panel.update_times(content))
@pytest.mark.django_db
def test_panel_tp_subdir_table(subdir0, rf, member):
request = rf.get(subdir0.pootle_path)
request.user = member
request.permissions = get_matching_permissions(
request.user,
subdir0)
view = TPBrowseView(
kwargs=dict(
language_code=subdir0.tp.language.code,
project_code=subdir0.tp.project.code,
dir_path=subdir0.tp_path[1:]))
view.request = request
view.object = view.get_object()
lang_panels = panels.gather(TPBrowseView)
assert lang_panels.keys() == ["children", "vfolders"]
assert lang_panels["children"] == ChildrenPanel
panel = ChildrenPanel(view)
assert panel.panel_name == "children"
assert (
panel.cache_key
== ("panel.%s.%s"
% (panel.panel_name, view.cache_key)))
table = {
'id': view.view_name,
'fields': panel.table_fields,
'headings': get_table_headings(panel.table_fields),
'rows': view.object_children}
assert panel.table == table
assert panel.get_context_data() == dict(
table=table, can_translate=view.can_translate)
content = loader.render_to_string(
panel.template_name, context=panel.get_context_data())
assert (
panel.content
== panel.update_times(content))
@pytest.mark.django_db
def test_panel_tp_no_vfolders_table(tp0, rf, member, no_vfolders):
request = rf.get('/language0/project0/')
request.user = member
request.permissions = get_matching_permissions(
request.user,
tp0.directory)
view = TPBrowseView(
kwargs=dict(
language_code=tp0.language.code,
project_code=tp0.project.code))
view.request = request
view.object = view.get_object()
lang_panels = panels.gather(TPBrowseView)
assert lang_panels.keys() == ["children", "vfolders"]
assert lang_panels["vfolders"] == VFolderPanel
panel = VFolderPanel(view)
assert panel.panel_name == "vfolder"
assert panel.table == ""
view.vfolders_data_view = None
assert panel.table == ""
| 5,179
|
Python
|
.py
| 139
| 31.086331
| 77
| 0.672301
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,004
|
contextmanagers.py
|
translate_pootle/tests/pootle_translationproject/contextmanagers.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import pytest
from pootle.core.delegate import review
from pootle_store.models import Suggestion
from pootle_translationproject.contextmanagers import update_tp_after
class CriticalCheckTest(object):
def __init__(self, unit):
self.unit = unit
def _test_check_data(self, original, updated):
# check data
assert (
updated["store_checks_data"]["xmltags"]
== original["store_checks_data"].get("xmltags", 0) + 1)
assert (
updated["tp_checks_data"]["xmltags"]
== original["tp_checks_data"].get("xmltags", 0) + 1)
def _test_scores(self, original, updated):
# scores
assert (
updated["store_score"]["score"]
> original["store_score"]["score"])
assert (
updated["store_score"]["translated"]
> original["store_score"]["translated"])
assert (
updated["tp_score"]["score"]
> original["tp_score"]["score"])
assert (
updated["tp_score"]["translated"]
> original["tp_score"]["translated"])
def _test_data(self, original, updated):
# store and tp data
assert (
updated["store_data"]["critical_checks"]
== original["store_data"]["critical_checks"] + 2)
assert (
updated["store_data"]["translated_words"]
> original["store_data"]["translated_words"])
assert (
updated["store_data"]["pending_suggestions"]
== original["store_data"]["pending_suggestions"])
assert (
updated["tp_data"]["critical_checks"]
== original["tp_data"]["critical_checks"] + 2)
assert (
updated["tp_data"]["translated_words"]
> original["tp_data"]["translated_words"])
assert (
updated["tp_data"]["pending_suggestions"]
== original["tp_data"]["pending_suggestions"])
def _test_revisions(self, original, updated):
# unit and directory revisions
assert updated["unit_revision"] > original["unit_revision"]
assert (
updated["store_data"]["max_unit_revision"]
== updated["tp_data"]["max_unit_revision"]
== updated["unit_revision"])
assert (
updated["unit_revision"]
> original["store_data"]["max_unit_revision"])
assert (
updated["unit_revision"]
> original["tp_data"]["max_unit_revision"])
assert (
updated["dir_revision"][0].value
!= original["dir_revision"][0].value)
assert (
updated["dir_revision"][0].pk
== original["dir_revision"][0].pk)
assert (
updated["tp_dir_revision"][0].value
!= original["tp_dir_revision"][0].value)
assert (
updated["tp_dir_revision"][0].pk
== original["tp_dir_revision"][0].pk)
class SuggestionAddTest(object):
def __init__(self, unit):
self.unit = unit
def _test_check_data(self, original, updated):
# check data
assert (
updated["store_checks_data"]
== original["store_checks_data"])
assert (
updated["tp_checks_data"]
== original["tp_checks_data"])
def _test_scores(self, original, updated):
# scores
assert (
updated["store_score"]["score"]
== original["store_score"]["score"])
assert (
updated["store_score"]["translated"]
== original["store_score"]["translated"])
assert (
updated["tp_score"]["score"]
== original["tp_score"]["score"])
assert (
updated["tp_score"]["translated"]
== original["tp_score"]["translated"])
def _test_data(self, original, updated):
# store and tp data
assert (
updated["store_data"]["critical_checks"]
== original["store_data"]["critical_checks"])
assert (
updated["store_data"]["translated_words"]
== original["store_data"]["translated_words"])
assert (
updated["store_data"]["pending_suggestions"]
== original["store_data"]["pending_suggestions"] + 1)
assert (
updated["tp_data"]["critical_checks"]
== original["tp_data"]["critical_checks"])
assert (
updated["tp_data"]["translated_words"]
== original["tp_data"]["translated_words"])
assert (
updated["tp_data"]["pending_suggestions"]
== original["tp_data"]["pending_suggestions"] + 1)
def _test_revisions(self, original, updated):
# unit and directory revisions
assert updated["unit_revision"] == original["unit_revision"]
assert (
updated["store_data"]["max_unit_revision"]
== original["store_data"]["max_unit_revision"])
assert (
updated["dir_revision"][0].value
!= original["dir_revision"][0].value)
assert (
updated["dir_revision"][0].pk
== original["dir_revision"][0].pk)
assert (
updated["tp_dir_revision"][0].value
!= original["tp_dir_revision"][0].value)
assert (
updated["tp_dir_revision"][0].pk
== original["tp_dir_revision"][0].pk)
class SuggestionAcceptTest(object):
def __init__(self, unit):
self.unit = unit
def _test_check_data(self, original, updated):
# check data
assert (
updated["store_checks_data"]
== original["store_checks_data"])
assert (
updated["tp_checks_data"]
== original["tp_checks_data"])
def _test_scores(self, original, updated):
# scores
assert (
updated["store_score"]["score"]
> original["store_score"]["score"])
assert (
updated["store_score"]["translated"]
> original["store_score"]["translated"])
assert (
updated["tp_score"]["score"]
> original["tp_score"]["score"])
assert (
updated["tp_score"]["translated"]
> original["tp_score"]["translated"])
def _test_data(self, original, updated):
# store and tp data
assert (
updated["store_data"]["critical_checks"]
== original["store_data"]["critical_checks"])
assert (
updated["store_data"]["translated_words"]
> original["store_data"]["translated_words"])
assert (
updated["store_data"]["pending_suggestions"]
== original["store_data"]["pending_suggestions"] - 1)
assert (
updated["tp_data"]["critical_checks"]
== original["tp_data"]["critical_checks"])
assert (
updated["tp_data"]["translated_words"]
> original["tp_data"]["translated_words"])
assert (
updated["tp_data"]["pending_suggestions"]
== original["tp_data"]["pending_suggestions"] - 1)
def _test_revisions(self, original, updated):
# unit and directory revisions
assert updated["unit_revision"] > original["unit_revision"]
assert (
updated["store_data"]["max_unit_revision"]
== updated["unit_revision"])
assert (
updated["store_data"]["max_unit_revision"]
> original["store_data"]["max_unit_revision"])
assert (
updated["dir_revision"][0].value
!= original["dir_revision"][0].value)
assert (
updated["dir_revision"][0].pk
== original["dir_revision"][0].pk)
assert (
updated["tp_dir_revision"][0].value
!= original["tp_dir_revision"][0].value)
assert (
updated["tp_dir_revision"][0].pk
== original["tp_dir_revision"][0].pk)
class SuggestionRejectTest(object):
def __init__(self, unit):
self.unit = unit
def _test_check_data(self, original, updated):
# check data
assert (
updated["store_checks_data"]
== original["store_checks_data"])
assert (
updated["tp_checks_data"]
== original["tp_checks_data"])
def _test_scores(self, original, updated):
# scores
assert (
updated["store_score"]["score"]
> original["store_score"]["score"])
assert (
updated["store_score"]["translated"]
== original["store_score"]["translated"])
assert (
updated["tp_score"]["score"]
> original["tp_score"]["score"])
assert (
updated["tp_score"]["translated"]
== original["tp_score"]["translated"])
def _test_data(self, original, updated):
# store and tp data
assert (
updated["store_data"]["critical_checks"]
== original["store_data"]["critical_checks"])
assert (
updated["store_data"]["translated_words"]
== original["store_data"]["translated_words"])
assert (
updated["store_data"]["pending_suggestions"]
== original["store_data"]["pending_suggestions"] - 1)
assert (
updated["tp_data"]["critical_checks"]
== original["tp_data"]["critical_checks"])
assert (
updated["tp_data"]["translated_words"]
== original["tp_data"]["translated_words"])
assert (
updated["tp_data"]["pending_suggestions"]
== original["tp_data"]["pending_suggestions"] - 1)
def _test_revisions(self, original, updated):
# unit and directory revisions
assert updated["unit_revision"] == original["unit_revision"]
assert (
updated["store_data"]["max_unit_revision"]
== original["store_data"]["max_unit_revision"])
assert (
updated["dir_revision"][0].value
!= original["dir_revision"][0].value)
assert (
updated["dir_revision"][0].pk
== original["dir_revision"][0].pk)
assert (
updated["tp_dir_revision"][0].value
!= original["tp_dir_revision"][0].value)
assert (
updated["tp_dir_revision"][0].pk
== original["tp_dir_revision"][0].pk)
@pytest.mark.django_db
def test_contextmanager_update_tp_after_checks(tp0, store0, member,
update_unit_test):
# unit save
unit = store0.units.exclude(
qualitycheck__name="xmltags").first()
with update_unit_test(CriticalCheckTest(unit)):
with update_tp_after(tp0):
unit.target = "<bad></target>."
unit.save(user=member)
# unit updated by update
unit = store0.units.exclude(pk=unit.pk).exclude(
qualitycheck__name="xmltags").first()
store0.data.refresh_from_db()
ttk = store0.deserialize(store0.serialize())
ttk_unit = ttk.findid(unit.unitid)
ttk_unit.target = "<bad></target>."
with update_unit_test(CriticalCheckTest(unit)):
with update_tp_after(tp0):
store0.update(
store=ttk,
store_revision=store0.data.max_unit_revision + 1,
user=member)
@pytest.mark.django_db
def test_contextmanager_update_tp_after_suggestion(tp0, store0, member,
update_unit_test):
unit = store0.units.first()
sugg_review = review.get(Suggestion)
with update_unit_test(SuggestionAddTest(unit)):
with update_tp_after(tp0):
sugg_text = str(unit.source_f).replace("U", "X")
sugg1, created_ = review.get(Suggestion)().add(
unit,
sugg_text,
user=member)
with update_unit_test(SuggestionAcceptTest(unit)):
with update_tp_after(tp0):
sugg_review(suggestions=[sugg1], reviewer=member).accept()
unit = store0.units.exclude(pk=unit.pk).first()
with update_unit_test(SuggestionAddTest(unit)):
with update_tp_after(tp0):
sugg_text = str(unit.source_f).replace("U", "X")
sugg1, created_ = review.get(Suggestion)().add(
unit,
sugg_text,
user=member)
with update_unit_test(SuggestionRejectTest(unit)):
with update_tp_after(tp0):
sugg_review(suggestions=[sugg1], reviewer=member).reject()
| 12,889
|
Python
|
.py
| 322
| 29.468944
| 77
| 0.555201
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,005
|
views.py
|
translate_pootle/tests/pootle_translationproject/views.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import json
import pytest
from django.core.urlresolvers import reverse
from pootle.core.browser import make_directory_item, make_store_item
from pootle.core.forms import PathsSearchForm
from pootle.core.signals import update_revisions
from pootle.core.url_helpers import split_pootle_path
from pootle.core.views.browse import StatsDisplay
from pootle_app.models import Directory
from pootle_store.models import Store
from pootle_translationproject.views import TPBrowseView
def _test_view_tp_children(view, obj):
request = view.request
if obj.tp_path == "/":
data_obj = obj.tp
else:
data_obj = obj
stats = StatsDisplay(
data_obj,
stats=data_obj.data_tool.get_stats(user=request.user)).stats
assert stats == view.stats
stores = view.tp.stores
if obj.tp_path != "/":
stores = stores.filter(
tp_path__startswith=obj.tp_path)
vf_stores = stores.filter(
vfolders__isnull=False).exclude(parent=obj)
dirs_with_vfolders = set(
split_pootle_path(path)[2].split("/")[0]
for path
in vf_stores.values_list("pootle_path", flat=True))
directories = [
make_directory_item(
child,
**(dict(sort="priority")
if child.name in dirs_with_vfolders
else {}))
for child in obj.get_children()
if isinstance(child, Directory)]
stores = [
make_store_item(child)
for child in obj.get_children()
if isinstance(child, Store)]
items = directories + stores
for item in items:
if item["code"] in stats["children"]:
item["stats"] = stats["children"][item["code"]]
elif item["title"] in stats["children"]:
item["stats"] = stats["children"][item["title"]]
assert view.object_children == items
@pytest.mark.django_db
def test_view_tp_children(tp0, rf, request_users):
request = rf.get('/language0/project0/')
request.user = request_users["user"]
view = TPBrowseView(
kwargs=dict(
language_code=tp0.language.code,
project_code=tp0.project.code))
view.request = request
view.object = view.get_object()
obj = view.object
assert obj == tp0.directory
_test_view_tp_children(view, obj)
@pytest.mark.django_db
def test_view_tp_subdir_children(subdir0, rf, request_users):
request = rf.get(subdir0.pootle_path)
request.user = request_users["user"]
view = TPBrowseView(
kwargs=dict(
language_code=subdir0.tp.language.code,
project_code=subdir0.tp.project.code,
dir_path=subdir0.tp_path[1:]))
view.request = request
view.object = view.get_object()
obj = view.object
assert obj == subdir0
_test_view_tp_children(view, obj)
@pytest.mark.django_db
def test_view_tp_paths_bad(tp0, client, request_users):
user = request_users["user"]
client.login(
username=user.username,
password=request_users["password"])
url = reverse(
"pootle-tp-paths",
kwargs=dict(
project_code=tp0.project.code,
language_code=tp0.language.code))
# no xhr header
response = client.post(url)
assert response.status_code == 400
# no query
response = client.post(
url, HTTP_X_REQUESTED_WITH='XMLHttpRequest')
assert response.status_code == 400
# query too short
response = client.post(
url,
data=dict(q="xy"),
HTTP_X_REQUESTED_WITH='XMLHttpRequest')
assert response.status_code == 400
@pytest.mark.django_db
def test_view_tp_paths(tp0, store0, client, request_users):
user = request_users["user"]
client.login(
username=user.username,
password=request_users["password"])
url = reverse(
"pootle-tp-paths",
kwargs=dict(
project_code=tp0.project.code,
language_code=tp0.language.code))
response = client.post(
url,
data=dict(q="tore"),
HTTP_X_REQUESTED_WITH='XMLHttpRequest')
assert response.status_code == 200
result = json.loads(response.content)
path_form = PathsSearchForm(context=tp0, data=dict(q="tore"))
assert path_form.is_valid()
assert result["items"] == path_form.search(show_all=user.is_superuser)
assert "store0.po" in result["items"]["results"]
stores = Store.objects.filter(name=store0.name)
for store in stores:
store.obsolete = True
store.save()
update_revisions.send(
store.__class__,
instance=store,
keys=["stats"])
response = client.post(
url,
data=dict(q="tore"),
HTTP_X_REQUESTED_WITH='XMLHttpRequest')
assert response.status_code == 200
result = json.loads(response.content)
assert "store0.po" not in result["items"]["results"]
| 5,143
|
Python
|
.py
| 144
| 29.152778
| 77
| 0.655498
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,006
|
revision_updater.py
|
translate_pootle/tests/pootle_revision/revision_updater.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import pytest
from pootle.core.delegate import revision, revision_updater
from pootle_app.models import Directory
from pootle_revision.utils import UnitRevisionUpdater
from pootle_store.models import Store, Unit
def _test_revision_updater(updater):
revisions = revision.get(Directory)
for parent in updater.parents:
assert not revisions(parent).get(key="foo")
assert not revisions(parent).get(key="bar")
updater.update(keys=["foo"])
keys = dict(foo={}, bar={})
for parent in updater.parents:
keys["foo"][parent.id] = revisions(parent).get(key="foo")
assert revisions(parent).get(key="foo")
assert not revisions(parent).get(key="bar")
updater.update(keys=["bar"])
for parent in updater.parents:
keys[parent.id] = revisions(parent).get(key="foo")
assert revisions(parent).get(key="foo") == keys["foo"][parent.id]
assert revisions(parent).get(key="bar")
@pytest.mark.django_db
def test_revision_unit_updater(store0):
assert revision_updater.get() is None
unit = store0.units.first()
updater_class = revision_updater.get(unit.__class__)
assert updater_class is UnitRevisionUpdater
updater = updater_class(object_list=store0.units)
all_pootle_paths = updater.object_list.values_list(
"store__parent__pootle_path", flat=True)
assert (
list(updater.all_pootle_paths)
== list(
set(all_pootle_paths)))
assert (
list(updater.parents)
== list(
Directory.objects.filter(
pootle_path__in=updater.get_parent_paths(
updater.all_pootle_paths))))
def test_revision_unit_updater_parent_paths():
updater_class = revision_updater.get(Unit)
updater = updater_class([])
paths = updater.get_parent_paths(
["/foo/bar/path/foo.po",
"/foo/bar2/path/foo.po",
"/foo2/bar/path/foo.po",
"/foo/bar/baz/some/other/baz.po"])
assert (
sorted(paths)
== [u"/foo/",
u"/foo/bar/",
u"/foo/bar/baz/",
u"/foo/bar/baz/some/",
u"/foo/bar/baz/some/other/",
u"/foo/bar/path/",
u"/foo/bar2/",
u"/foo/bar2/path/",
u"/foo2/",
u"/foo2/bar/",
u"/foo2/bar/path/",
u"/projects/",
u"/projects/bar/",
u"/projects/bar2/"])
@pytest.mark.django_db
def test_revision_unit_updater_update(store0):
updater_class = revision_updater.get(Unit)
updater = updater_class(object_list=store0.units)
_test_revision_updater(updater)
@pytest.mark.django_db
def test_revision_unit_updater_update_single(store0):
updater_class = revision_updater.get(Unit)
updater = updater_class(store0.units.select_related("store__parent").first())
_test_revision_updater(updater)
@pytest.mark.django_db
def test_revision_store_updater_update(tp0):
updater_class = revision_updater.get(Store)
updater = updater_class(object_list=tp0.stores)
_test_revision_updater(updater)
@pytest.mark.django_db
def test_revision_store_updater_update_single(store0):
updater_class = revision_updater.get(Store)
updater = updater_class(store0)
_test_revision_updater(updater)
@pytest.mark.django_db
def test_revision_directory_updater_single(subdir0):
updater_class = revision_updater.get(Directory)
updater = updater_class(subdir0)
_test_revision_updater(updater)
@pytest.mark.django_db
def test_revision_directory_updater_update():
updater_class = revision_updater.get(Directory)
updater = updater_class(
object_list=Directory.objects.filter(name="subdir0"))
_test_revision_updater(updater)
| 4,010
|
Python
|
.py
| 102
| 32.95098
| 81
| 0.672325
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,007
|
proxy.py
|
translate_pootle/tests/statistics/proxy.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import pytest
from pootle_statistics.models import Submission
from pootle_statistics.proxy import SubmissionProxy
def _test_submission_proxy(proxy, sub, fields):
assert proxy.field == sub.field
if sub.field:
assert proxy.field_name
if sub.suggestion:
assert proxy.suggestion == sub.suggestion.pk
assert proxy.suggestion_target == sub.suggestion.target
if sub.unit and "unit_id" in fields:
assert proxy.unit == sub.unit.pk
assert proxy.unit_source == sub.unit.source
assert proxy.unit_translate_url == sub.unit.get_translate_url()
assert proxy.unit_pootle_path == sub.unit.store.pootle_path
assert proxy.unit_state == sub.unit.state
assert proxy.type == sub.type
if sub.quality_check:
assert proxy.qc_name == sub.quality_check.name
else:
assert proxy.qc_name is None
with pytest.raises(AttributeError):
proxy.asdf
@pytest.mark.django_db
def test_submission_proxy_info(submissions):
values = Submission.objects.values(
*(("id", ) + SubmissionProxy.info_fields))
for v in values.iterator():
proxy = SubmissionProxy(v)
submission = submissions[v["id"]]
_test_submission_proxy(
proxy,
submission,
SubmissionProxy.info_fields)
assert (
sorted(proxy.get_submission_info().items())
== sorted(submission.get_submission_info().items()))
@pytest.mark.django_db
def test_submission_proxy_timeline(submissions):
values = Submission.objects.values(
*(("id", ) + SubmissionProxy.timeline_fields))
for v in values.iterator():
_test_submission_proxy(
SubmissionProxy(v),
submissions[v["id"]],
SubmissionProxy.timeline_fields)
@pytest.mark.django_db
def test_submission_proxy_qc_timeline(quality_check_submission):
subs = Submission.objects.filter(pk=quality_check_submission.pk)
_test_submission_proxy(
SubmissionProxy(
subs.values(*SubmissionProxy.timeline_fields).first()),
quality_check_submission,
SubmissionProxy.timeline_fields)
@pytest.mark.django_db
def test_submission_proxy_qc_info(quality_check_submission):
subs = Submission.objects.filter(pk=quality_check_submission.pk)
proxy = SubmissionProxy(subs.values(*SubmissionProxy.info_fields).first())
_test_submission_proxy(
proxy,
quality_check_submission,
SubmissionProxy.info_fields)
assert (
sorted(proxy.get_submission_info().items())
== sorted(quality_check_submission.get_submission_info().items()))
@pytest.mark.django_db
def test_submission_proxy_timeline_info(quality_check_submission):
"""If you use the timeline fields but call get_submission_info you will
get the sub info without the unit data
"""
subs = Submission.objects.filter(pk=quality_check_submission.pk)
sub = subs.values(*SubmissionProxy.timeline_fields).first()
proxy = SubmissionProxy(sub)
assert proxy.unit_info == {}
assert proxy.unit_translate_url is None
assert proxy.unit_pootle_path is None
assert proxy.unit_state is None
non_unit_fields = [
'username', 'display_datetime', 'displayname',
'mtime', 'type', 'email', 'profile_url']
proxy_info = proxy.get_submission_info()
sub_info = quality_check_submission.get_submission_info()
for k in non_unit_fields:
assert proxy_info[k] == sub_info[k]
| 3,772
|
Python
|
.py
| 91
| 35.153846
| 78
| 0.695391
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,008
|
stats_utils.py
|
translate_pootle/tests/statistics/stats_utils.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from datetime import timedelta
from collections import OrderedDict
import pytest
from pytest_pootle.factories import UserFactory
from django.contrib.auth import get_user_model
from django.db.models import Q
from pootle.core.delegate import contributors
from pootle_statistics.models import Submission
from pootle_statistics.utils import Contributors
User = get_user_model()
def _contributors_list(contribs):
subs = []
for user in contribs.user_qs:
q = Q(submitter=user)
if contribs.project_codes:
q = q & Q(
translation_project__project__code__in=contribs.project_codes)
if contribs.language_codes:
q = q & Q(
translation_project__language__code__in=contribs.language_codes)
# group the creation_time query
if contribs.since or contribs.until:
_q = Q()
if contribs.since:
_q = _q & Q(creation_time__gte=contribs.since)
if contribs.until:
_q = _q & Q(creation_time__lte=contribs.until)
q = q & _q
submissions = Submission.objects.filter(q)
if submissions.count():
subs.append(
(user.username,
dict(contributions=submissions.count(),
username=user.username,
full_name=user.full_name,
email=user.email)))
if contribs.sort_by != "contributions":
return OrderedDict(
sorted(
subs,
key=lambda i: i[0]))
return OrderedDict(
sorted(
subs,
key=lambda i: (-i[1]["contributions"], i[1]["username"])))
@pytest.mark.django_db
def test_contributors_delegate():
contribs_class = contributors.get()
assert contribs_class is Contributors
@pytest.mark.django_db
def test_contributors_instance(member, anon_submission_unit):
"""Contributors across the site."""
anon = User.objects.get(username="nobody")
contribs = Contributors()
someuser = UserFactory()
assert contribs.include_anon is False
assert contribs.language_codes is None
assert contribs.project_codes is None
# user_qs
assert list(contribs.user_qs) == list(User.objects.hide_meta())
assert someuser in contribs.user_qs
assert anon not in contribs.user_qs
assert sorted(contribs.items()) == sorted(contribs.contributors.items())
assert (
sorted(contribs)
== sorted(contribs.contributors)
== sorted(
set(contribs.user_qs.filter(contribs.user_filters)
.values_list("username", flat=True)))
== sorted(
set(contribs.user_qs.filter(submission__gt=0)
.values_list("username", flat=True))))
# contrib object
for username in contribs:
assert contribs[username] == contribs.contributors[username]
assert username in contribs
assert anon.username not in contribs
assert someuser.username not in contribs
assert member.username in contribs
assert contribs.contributors == _contributors_list(contribs)
@pytest.mark.django_db
def test_contributors_include_anon(member, anon_submission_unit):
"""Contributors across the site."""
anon = User.objects.get(username="nobody")
contribs = Contributors(include_anon=True)
someuser = UserFactory()
assert contribs.include_anon is True
# user_qs
assert (
list(contribs.user_qs)
== list(User.objects.exclude(username__in=["system", "default"])))
assert someuser in contribs.user_qs
assert anon in contribs.user_qs
assert (
sorted(contribs)
== sorted(contribs.contributors)
== sorted(
set(contribs.user_qs.filter(contribs.user_filters)
.values_list("username", flat=True)))
== sorted(
set(contribs.user_qs.filter(submission__gt=0)
.values_list("username", flat=True))))
# contrib object
for username in contribs:
assert contribs[username] == contribs.contributors[username]
assert username in contribs
assert anon.username in contribs
assert contribs.contributors == _contributors_list(contribs)
@pytest.mark.django_db
def test_contributors_filter_projects(member):
contribs = Contributors(project_codes=["project0"])
assert contribs.project_codes == ["project0"]
assert contribs.contributors == _contributors_list(contribs)
@pytest.mark.django_db
def test_contributors_filter_language(member):
contribs = Contributors(language_codes=["language0"])
assert contribs.language_codes == ["language0"]
assert contribs.contributors == _contributors_list(contribs)
@pytest.mark.django_db
def test_contributors_filter_projects_and_language(member):
contribs = Contributors(
project_codes=["project0"],
language_codes=["language0"])
assert contribs.language_codes == ["language0"]
assert contribs.project_codes == ["project0"]
assert contribs.contributors == _contributors_list(contribs)
@pytest.mark.django_db
def test_contributors_filter_projects_since(member):
sub_times = sorted(set(
Submission.objects.filter(
translation_project__project__code="project0").values_list(
"creation_time", flat=True)))
start_time = sub_times[0]
mid_time = sub_times[len(sub_times) / 2]
end_time = sub_times[-1]
# get all of of the submissions
contribs = Contributors(
project_codes=["project0"],
since=start_time, until=end_time)
assert contribs.since == start_time
assert contribs.until == end_time
assert contribs.contributors == _contributors_list(contribs)
# get the first half of the submissions
contribs = Contributors(
project_codes=["project0"],
since=start_time, until=mid_time)
assert contribs.contributors == _contributors_list(contribs)
# get the second half of the submissions
contribs = Contributors(
project_codes=["project0"],
since=start_time, until=mid_time)
assert contribs.contributors == _contributors_list(contribs)
# try and get submissions before there were any
contribs = Contributors(
project_codes=["project0"],
until=start_time - timedelta(seconds=1))
assert contribs.contributors == OrderedDict()
@pytest.mark.django_db
def test_contributors_sort_contributions(member, anon_submission_unit):
"""Contributors across the site."""
contribs = Contributors()
assert contribs.sort_by == "username"
contribs = Contributors(sort_by="contributions")
assert contribs.sort_by == "contributions"
assert contribs.contributors == _contributors_list(contribs)
| 7,109
|
Python
|
.py
| 172
| 33.837209
| 80
| 0.672027
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,009
|
proxy.py
|
translate_pootle/tests/core/proxy.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import pytest
from pootle.core.proxy import BaseProxy, AttributeProxy
def test_proxy_base_primitives():
p = BaseProxy(3)
assert issubclass(type(p), BaseProxy)
assert p + 1 == 4
p += 1
assert type(p) == int
assert p == 4
assert BaseProxy([1, 2, 3]) + [4, 5] == [1, 2, 3, 4, 5]
p = BaseProxy([1, 2, 3])
p.extend(BaseProxy([4, 5]))
assert p == [1, 2, 3, 4, 5]
def test_proxy_base_primitive_exceptions():
# Proxying user-types should work perfectly well. But proxying builtin
# objects, like ints, floats, lists, etc., has some limitation and
# inconsistencies, imposed by the interprete
p = BaseProxy(6)
with pytest.raises(TypeError):
p + p
with pytest.raises(TypeError):
assert BaseProxy([1, 2, 3]) + BaseProxy([4, 5])
p = BaseProxy([1, 2, 3])
with pytest.raises(TypeError):
p + BaseProxy([6, 7])
def test_proxy_base():
class Foo(object):
bar = "BAR"
@property
def baz(self):
return "BAZ"
def dofoo(self):
return "FOO"
foo = Foo()
wrapped = BaseProxy(foo)
assert wrapped.bar == "BAR"
assert wrapped.baz == "BAZ"
assert wrapped.dofoo() == "FOO"
assert str(wrapped) == str(foo)
assert repr(wrapped) == repr(foo)
wrapped.bar = "something else"
assert foo.bar == "something else"
wrapped.special_attr = "SPECIAL"
assert foo.special_attr == "SPECIAL"
delattr(wrapped, "special_attr")
assert not hasattr(foo, "special_attr")
assert wrapped
assert not BaseProxy(0)
def test_proxy_attribute():
class Foo(object):
bar = "BAR"
@property
def baz(self):
return "BAZ"
def dofoo(self):
return "FOO"
foo = Foo()
wrapped = AttributeProxy(foo)
assert wrapped.bar == "BAR"
assert wrapped.baz == "BAZ"
assert wrapped.dofoo() == "FOO"
wrapped.bar = "SOMETHING ELSE"
assert foo.bar == "SOMETHING ELSE"
wrapped.dofoo = "I USED TO BE A METHOD"
assert foo.dofoo == "I USED TO BE A METHOD"
with pytest.raises(AttributeError):
wrapped.baz = "NO SETTING PROPERTIES"
# extra attrs are only placed on the wrapper
wrapped.special_attr = "SPECIAL"
assert wrapped.special_attr == "SPECIAL"
assert not hasattr(foo, "special_attr")
delattr(wrapped, "special_attr")
assert not hasattr(wrapped, "special_attr")
delattr(wrapped, "bar")
assert not hasattr(foo, "special_attr")
| 2,800
|
Python
|
.py
| 82
| 28.414634
| 77
| 0.641102
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,010
|
user.py
|
translate_pootle/tests/core/user.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import pytest
from pootle.core.user import get_system_user, get_system_user_id
@pytest.mark.django_db
def test_user_get_system_user(system):
assert get_system_user() == system
assert get_system_user_id() == system.id
| 504
|
Python
|
.py
| 13
| 36.846154
| 77
| 0.755647
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,011
|
bulk.py
|
translate_pootle/tests/core/bulk.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import pytest
from pootle.core.bulk import BulkCRUD
from pootle_data.models import StoreChecksData
from pootle_store.models import Unit
def test_bulk_crud_instance():
class ExampleBulkCRUD(BulkCRUD):
model = Unit
unit_crud = ExampleBulkCRUD()
assert repr(unit_crud) == "<ExampleBulkCRUD:%s>" % str(Unit._meta)
assert unit_crud.qs == Unit.objects
@pytest.mark.django_db
def test_bulk_crud_bulk_update_method(store0):
unit0, unit1 = store0.units[:2]
class ExampleBulkCRUD(BulkCRUD):
model = Unit
unit_crud = ExampleBulkCRUD()
unit0.target = "FOO"
unit1.target = "BAR"
unit_crud.bulk_update([unit0, unit1])
unit0.refresh_from_db()
unit1.refresh_from_db()
assert unit0.target == "FOO"
assert unit1.target == "BAR"
unit0.context = "FOO CONTEXT"
unit0.target = "NOT FOO"
unit1.target = "NOT BAR"
unit_crud.bulk_update(
[unit0, unit1],
fields=["context"])
unit0.refresh_from_db()
unit1.refresh_from_db()
assert unit0.target == "FOO"
assert unit1.target == "BAR"
assert unit0.context == "FOO CONTEXT"
@pytest.mark.django_db
def test_bulk_crud_create_delete(store0):
checkdata0 = StoreChecksData(
store=store0, name="foo", category=2)
class ExampleBulkCRUD(BulkCRUD):
model = StoreChecksData
checkdata_crud = ExampleBulkCRUD()
checkdata_crud.create(instance=checkdata0)
assert checkdata0.pk
checkdata1 = StoreChecksData(
store=store0, name="bar", category=2)
checkdata2 = StoreChecksData(
store=store0, name="baz", category=2)
checkdata_crud.create(
objects=[checkdata1, checkdata2])
checkdata1 = StoreChecksData.objects.get(
store=store0, name="bar", category=2)
checkdata2 = StoreChecksData.objects.get(
store=store0, name="baz", category=2)
assert checkdata1
assert checkdata2
checkdata_crud.delete(instance=checkdata2)
with pytest.raises(StoreChecksData.DoesNotExist):
checkdata2.refresh_from_db()
checkdata_crud.delete(
objects=StoreChecksData.objects.filter(
id__in=[checkdata0.id, checkdata1.id]))
for checkdata in [checkdata0, checkdata1]:
with pytest.raises(StoreChecksData.DoesNotExist):
checkdata.refresh_from_db()
@pytest.mark.django_db
def test_bulk_crud_update_methods(store0):
unit0, unit1, unit2 = store0.units[:3]
class ExampleBulkCRUD(BulkCRUD):
model = Unit
unit_crud = ExampleBulkCRUD()
updates = {
unit0.id: dict(
target_f="FOO",
context="FOO CONTEXT"),
unit1.id: dict(target_f="BAR")}
objects = []
result = sorted(
unit_crud.update_objects(
[unit0],
updates,
objects))
assert result == ["context", "target_f"]
assert objects == [unit0]
assert unit0.target_f == "FOO"
assert unit0.context == "FOO CONTEXT"
result = list(
unit_crud.update_objects(
[unit1, unit2],
updates,
objects))
assert result == ["target_f"]
assert objects == [unit0, unit1, unit2]
assert unit1.target_f == "BAR"
objects = [3, 4, 5]
result = list(
unit_crud.update_objects(
iter([1, 2, 3]), None, objects))
assert objects == [3, 4, 5, 1, 2, 3]
assert result == []
updates = dict(store0.units.values_list("id", "unitid_hash"))
fetched = unit_crud.objects_to_fetch([unit0, unit1, unit2], updates)
assert (
sorted(fetched.values_list("id", flat=True))
== sorted(
store0.units.exclude(
id__in=[
unit0.id,
unit1.id,
unit2.id]).values_list("id", flat=True)))
updates = {
unit0.id: dict(
target_f="BAR",
context="BAR CONTEXT"),
unit1.id: dict(target_f="BAZ")}
objects, fields = unit_crud.update_object_list(
objects=[unit0, unit1, unit2],
updates=updates,
update_fields=["field0", "field1"])
assert (
sorted(fields)
== ["context", "field0", "field1", "target_f"])
assert objects == [unit0, unit1, unit2]
objects = [unit0, unit1]
fields = unit_crud.update_object_dict(objects, updates, set())
assert objects == [unit0, unit1]
assert fields is None
updates = {
unit0.id: dict(target_f="FOO"),
unit2.id: dict(developer_comment="Are we done yet?")}
result = unit_crud.update_object_dict(objects, updates, set())
assert objects == [unit0, unit1, unit2]
assert result is None
# unit0 not updated
assert unit0.target_f == "BAR"
assert objects[2].developer_comment == "Are we done yet?"
@pytest.mark.django_db
def test_bulk_crud_update(store0):
unit0, unit1, unit2 = store0.units[:3]
class ExampleBulkCRUD(BulkCRUD):
model = Unit
kwargs = None
def update_common_objects(self, ids, values):
self.ids = ids
self.values = values
return 23
def bulk_update(self, objects, fields):
self.objects = objects
self.fields = fields
return 77
unit_crud = ExampleBulkCRUD()
result = unit_crud.update(
**dict(
updates={unit1.id: dict(foo=1, bar=2)}))
assert result == 23
assert unit_crud.ids == [unit1.id]
assert unit_crud.values == dict(foo=1, bar=2)
unit_crud = ExampleBulkCRUD()
result = unit_crud.update(objects=[unit0, unit1, unit2])
assert result == 77 + len(unit_crud.objects)
assert unit_crud.objects == [unit0, unit1, unit2]
assert unit_crud.fields is None
unit0.target = "THE END"
unit_crud.update(instance=unit0)
unit0.refresh_from_db()
assert unit0.target == "THE END"
@pytest.mark.django_db
def test_bulk_crud_update_common(store0):
unit0, unit1, unit2 = store0.units[:3]
class ExampleBulkCRUD(BulkCRUD):
model = Unit
kwargs = None
unit_crud = ExampleBulkCRUD()
common_dict = dict(foo="FOO", bar="BAR")
updates = {
i: common_dict.copy()
for i in range(0, 20)}
result = unit_crud.all_updates_common(updates=updates)
assert result == common_dict
updates[19]["foo"] = "NOTFOO"
result = unit_crud.all_updates_common(updates=updates)
assert not result
updates[19]["foo"] = "FOO"
updates[20] = common_dict.copy()
result = unit_crud.all_updates_common(updates=updates)
assert result == common_dict
del updates[20]["bar"]
result = unit_crud.all_updates_common(updates=updates)
assert not result
updates[20]["bar"] = "BAR"
result = unit_crud.all_updates_common(updates=updates)
assert result == common_dict
del updates[20]["bar"]
updates[20]["baz"] = "BAR"
result = unit_crud.all_updates_common(updates=updates)
assert not result
result = unit_crud.update_common_objects(
[unit0.id, unit1.id],
values=dict(target_f="FOO TARGET", context="FOO CONTEXT"))
unit0.refresh_from_db()
unit1.refresh_from_db()
unit2.refresh_from_db()
for unit in [unit0, unit1]:
assert unit.target == "FOO TARGET"
assert unit.context == "FOO CONTEXT"
assert unit2.target != "FOO TARGET"
assert unit2.context != "FOO CONTEXT"
assert result == 2
new_values = dict(target_f="BAR TARGET", context="BAR CONTEXT")
result = unit_crud.update(
updates={
unit.id: new_values.copy()
for unit
in [unit0, unit1, unit2]})
unit0.refresh_from_db()
unit1.refresh_from_db()
unit2.refresh_from_db()
for unit in [unit0, unit1, unit2]:
assert unit.target == "BAR TARGET"
assert unit.context == "BAR CONTEXT"
assert result == 3
| 8,116
|
Python
|
.py
| 227
| 29.004405
| 77
| 0.638322
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,012
|
language.py
|
translate_pootle/tests/core/language.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from django.conf import settings
from django.utils import translation
from pootle.core.delegate import language_code
from pootle.core.language import LanguageCode
def test_language_code_util():
assert language_code.get() == LanguageCode
def _server_lang_matches_request(ignore_dialect=True):
"""checks whether server lang matches request lang.
if ignore dialect is set, dialects are ignored
"""
server_code = LanguageCode(settings.LANGUAGE_CODE)
request_code = LanguageCode(translation.get_language())
return server_code.matches(request_code, ignore_dialect=ignore_dialect)
def test_language_server_request_match(settings):
# default LANGUAGE_CODE = "en-us"
with translation.override(settings.LANGUAGE_CODE):
assert (
_server_lang_matches_request()
is True)
assert (
_server_lang_matches_request(ignore_dialect=False)
is True)
# check against en and dialects
en_dialects = ["en-GB", "en-gb", "en@gb", "en_GB", "en-FOO"]
with translation.override("en"):
assert (
_server_lang_matches_request()
is True)
assert (
_server_lang_matches_request(ignore_dialect=False)
is False)
for lang_code in en_dialects:
with translation.override(lang_code):
assert (
_server_lang_matches_request()
is True)
assert (
_server_lang_matches_request(ignore_dialect=False)
is False)
# check against es and dialects
es_dialects = ["es", "es-MX", "es-mx", "es@mx", "es_MX", "es-FOO"]
for lang_code in es_dialects:
with translation.override(lang_code):
assert (
_server_lang_matches_request()
is False)
assert (
_server_lang_matches_request(ignore_dialect=False)
is False)
| 2,215
|
Python
|
.py
| 56
| 31.517857
| 77
| 0.644951
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,013
|
formtable.py
|
translate_pootle/tests/core/formtable.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from django.template import Context, Template
from pootle.core.views.formtable import Formtable
from .forms import DummyFormtableForm
def test_formtable():
form = DummyFormtableForm()
formtable = Formtable(form)
assert formtable.actions_field == "actions"
assert formtable.actions == form[formtable.actions_field]
assert formtable.columns == ()
assert formtable.colspan == 0
assert formtable.filters == ""
assert formtable.filters_template == ""
assert formtable.form == form
assert formtable.form_action == ""
assert formtable.form_method == "POST"
assert formtable.form_css_class == "formtable"
assert formtable.form_attrs == {
"action": formtable.form_action,
"method": formtable.form_method,
"class": formtable.form_css_class}
assert formtable.kwargs == {}
assert formtable.page == ()
assert formtable.row_field == ""
assert formtable.table_css_class == 'pootle-table centered'
assert formtable.table_attrs == {'class': formtable.table_css_class}
assert formtable.rows == []
assert formtable.sort_columns == ()
def _render_template(string, context=None):
context = context or {}
context = Context(context)
return Template(string).render(context=context)
def test_formtable_inclusion_tag():
form = DummyFormtableForm()
formtable = Formtable(form)
rendered = _render_template(
"{% load core %}{% formtable formtable %}",
context=dict(formtable=formtable))
assert rendered.strip("\n").startswith('<form')
assert 'class="formtable"' in rendered
assert rendered.strip("\n").endswith('</form>')
| 1,936
|
Python
|
.py
| 47
| 36.617021
| 77
| 0.70911
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,014
|
display.py
|
translate_pootle/tests/core/display.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import pytest
from pootle.core.display import Display, ItemDisplay, SectionDisplay
# context can be any dict-like object whose values are non-string iterables
# in this case we wrap the data dict, but we could just provide that dict
# as the context
class DummyDisplayContext(object):
data = {
"section1": ["item1", "item2"],
"section2": None,
"section3": [],
"section4": ["some", "more", "iterable", "values"]}
def __iter__(self):
for section in self.data:
yield section
def __getitem__(self, k):
return self.data[k]
def test_display_instance():
context = DummyDisplayContext()
display = Display(context)
assert sorted(display.sections) == ["section1", "section4"]
assert display.context is context
assert display.section_class == SectionDisplay
assert display.no_results_msg == ""
for name in display.sections:
section = display.section(name)
assert isinstance(section, SectionDisplay)
assert section.context is display
assert section.name == name
result = ""
for section in display.sections:
result += str(display.section(section))
assert str(display) == "%s\n" % result
def test_display_no_results():
class DisplayNoResults(Display):
no_results_msg = "Nothing to see here, move along"
display = DisplayNoResults({})
assert str(display) == "%s\n" % DisplayNoResults.no_results_msg
def test_display_section_instance():
context = DummyDisplayContext()
display = Display(context)
section = SectionDisplay(display, "section4")
assert section.context is display
assert section.name == "section4"
assert section.info == dict(title=section.name)
assert section.data == context[section.name]
assert section.description == ""
assert section.title == (
"%s (%s)"
% (section.name, len(section.data)))
assert len(section.items) == len(section.data)
for i, item_display in enumerate(section.items):
assert isinstance(item_display, section.item_class)
assert item_display.item == section.data[i]
result = (
"%s\n%s\n\n"
% (section.title,
"-" * len(section.title)))
for item in section:
result += str(item)
assert str(section) == "%s\n" % result
def test_display_section_info():
context = DummyDisplayContext()
class DisplayWithInfo(Display):
context_info = dict(
section4=dict(
title="Section 4 title",
description="Section 4 description"))
display = DisplayWithInfo(context)
section = display.section("section4")
assert section.info == display.context_info["section4"]
assert section.description == section.info["description"]
assert section.title == (
"%s (%s)"
% (section.info["title"], len(section.data)))
result = (
"%s\n%s\n%s\n\n"
% (section.title,
"-" * len(section.title),
section.description))
for item in section:
result += str(item)
assert str(section) == "%s\n" % result
def test_display_section_no_info():
context = DummyDisplayContext()
class DisplayWithoutInfo(Display):
context_info = dict(
section2=dict(
title="Section 4 title",
description="Section 4 description"))
display = DisplayWithoutInfo(context)
section = display.section("section4")
assert section.info == dict(title="section4")
assert section.description == ""
assert section.title == (
"%s (%s)"
% (section.name, len(section.data)))
result = (
"%s\n%s\n\n"
% (section.title,
"-" * len(section.title)))
for item in section:
result += str(item)
assert str(section) == "%s\n" % result
def test_display_section_bad_items_none():
display = Display(DummyDisplayContext())
section = SectionDisplay(display, "section2")
# in the example section2 would normally be ignored by
# the Display class, but if a section were created from it
# it would raise a TypeError
with pytest.raises(TypeError):
assert section.items
def test_display_section_bad_items_str():
display = Display(dict(section1="FOO"))
section = SectionDisplay(display, "section1")
assert section.data == "FOO"
with pytest.raises(TypeError):
assert section.items
def test_display_item_instance():
display = Display(DummyDisplayContext())
section = SectionDisplay(display, "section1")
item_display = ItemDisplay(section, section.data[0])
assert item_display.section is section
assert item_display.item == section.data[0]
assert str(item_display) == "%s\n" % section.data[0]
| 5,074
|
Python
|
.py
| 131
| 32.366412
| 77
| 0.658591
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,015
|
batch.py
|
translate_pootle/tests/core/batch.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import pytest
from pootle.core.batch import Batch
from pootle_store.models import Suggestion, Unit
@pytest.mark.django_db
def test_batch_create_reduce(store0, member):
"""The source queryset reduces as batches are created"""
Suggestion.objects.filter(unit__store=store0).delete()
store0.units.first().delete()
suggestionless = store0.units.filter(suggestion__isnull=True)
batch = Batch(Suggestion.objects, batch_size=2)
assert batch.target == Suggestion.objects
assert batch.batch_size == 2
last_sugg_pk = Suggestion.objects.order_by(
"-pk").values_list("pk", flat=True).first()
def _create_method(unit, source, mtime):
return dict(
unit_id=unit,
creation_time=mtime,
target_f=source,
user_id=member.id)
batches = batch.batched_create(
suggestionless.values_list("id", "source_f", "mtime"),
_create_method)
new_suggs = Suggestion.objects.filter(pk__gt=last_sugg_pk)
assert new_suggs.count() == 0
for batched in batches:
assert len(batched)
assert len(batched) <= 2
assert all(isinstance(b, Suggestion) for b in batched)
assert all(b.target_f == b.unit.source_f for b in batched)
assert new_suggs.count() == store0.units.count()
new_suggs.delete()
created = batch.create(
suggestionless.values_list("id", "source_f", "mtime"),
_create_method)
new_suggs = Suggestion.objects.filter(pk__gt=last_sugg_pk)
assert created == new_suggs.count() == store0.units.count()
assert (
list(new_suggs.values_list("unit"))
== list(store0.units.values_list("id")))
@pytest.mark.django_db
def test_batch_create_no_reduce(store0, member):
batch = Batch(Suggestion.objects, batch_size=2)
assert batch.target == Suggestion.objects
assert batch.batch_size == 2
last_sugg_pk = Suggestion.objects.order_by(
"-pk").values_list("pk", flat=True).first()
def _create_method(unit, source, mtime):
return dict(
unit_id=unit,
creation_time=mtime,
target_f=source,
user_id=member.id)
batches = batch.batched_create(
store0.units.values_list("id", "source_f", "mtime"),
_create_method,
reduces=False)
new_suggs = Suggestion.objects.filter(pk__gt=last_sugg_pk)
assert new_suggs.count() == 0
for batched in batches:
assert len(batched)
assert len(batched) <= 2
assert all(isinstance(b, Suggestion) for b in batched)
assert all(b.target_f == b.unit.source_f for b in batched)
assert new_suggs.count() == store0.units.count()
new_suggs.delete()
created = batch.create(
store0.units.values_list("id", "source_f", "mtime"),
_create_method,
reduces=False)
new_suggs = Suggestion.objects.filter(pk__gt=last_sugg_pk)
assert created == new_suggs.count() == store0.units.count()
assert (
list(new_suggs.values_list("unit"))
== list(store0.units.values_list("id")))
@pytest.mark.django_db
def test_batch_update_reduce(store0, member):
"""The source queryset reduces as batches are created"""
batch = Batch(Unit, batch_size=2)
store0.units.exclude(
pk=store0.units.first().pk).update(target_f="FOO")
def _update_method(unit):
unit.target_f = "BAR"
return unit
count = batch.update(
store0.units.filter(target_f="FOO"),
_update_method)
assert count == store0.units.count() - 1
assert count == store0.units.filter(target_f="BAR").count()
store0.units.update(target_f="BAZ")
newcount = batch.update(
store0.units.filter(target_f="FOO"),
_update_method,
update_fields=["source_f"])
# units not updated, only source in update_fields
assert newcount == 0
assert (
store0.units.count()
== store0.units.filter(target_f="BAZ").count())
@pytest.mark.django_db
def test_batch_lists(store0, member):
batch = Batch(Suggestion.objects, batch_size=2)
assert batch.target == Suggestion.objects
assert batch.batch_size == 2
last_sugg_pk = Suggestion.objects.order_by(
"-pk").values_list("pk", flat=True).first()
def _create_method(unit, source, mtime):
return dict(
unit_id=unit,
creation_time=mtime,
target_f=source,
user_id=member.id)
batch.create(
list(store0.units.values_list("id", "source_f", "mtime")),
_create_method,
reduces=False)
new_suggs = Suggestion.objects.filter(pk__gt=last_sugg_pk)
assert new_suggs.count() == store0.units.count()
updated_suggs = []
for suggestion in new_suggs:
suggestion.target_f = "suggestion %s" % suggestion.id
updated_suggs.append(suggestion)
batch.update(
updated_suggs,
update_fields=["target_f"],
reduces=False)
for suggestion in Suggestion.objects.filter(pk__gt=last_sugg_pk):
assert suggestion.target_f == "suggestion %s" % suggestion.id
| 5,362
|
Python
|
.py
| 135
| 33.037037
| 77
| 0.653492
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,016
|
site.py
|
translate_pootle/tests/core/site.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import pytest
from django.contrib.sites.models import Site
from pootle.core.delegate import site
@pytest.mark.django_db
def test_site(settings):
# default using Sites framework
settings.POOTLE_CANONICAL_URL = ""
pootle_site = site.get()
assert (
pootle_site.build_absolute_uri("/foo")
== u'https://example.com/foo')
assert not pootle_site.use_insecure_http
settings.USE_INSECURE_HTTP = True
assert pootle_site.use_insecure_http
assert (
pootle_site.build_absolute_uri("/foo")
== u'http://example.com/foo')
contrib_site = Site.objects.get_current()
contrib_site.domain = "foo.com"
contrib_site.save()
assert (
pootle_site.build_absolute_uri("/foo")
== u'http://foo.com/foo')
assert pootle_site.use_http_port == 80
settings.USE_HTTP_PORT = 8008
assert pootle_site.use_http_port == 8008
assert (
pootle_site.build_absolute_uri("/foo")
== u'http://foo.com:8008/foo')
@pytest.mark.django_db
def test_site_canonical(settings):
# default using POOTLE_CANONICAL_URL
pootle_site = site.get()
settings.POOTLE_CANONICAL_URL = "http://foo.com"
assert not pootle_site.uses_sites
assert not pootle_site.contrib_site
assert pootle_site.use_insecure_http
assert pootle_site.use_http_port == 80
assert pootle_site.domain == "foo.com"
assert (
pootle_site.build_absolute_uri("/foo")
== u'http://foo.com/foo')
settings.POOTLE_CANONICAL_URL = "http://foo.com/bar"
pootle_site = site.get()
assert not pootle_site.uses_sites
assert not pootle_site.contrib_site
assert pootle_site.use_insecure_http
assert pootle_site.use_http_port == 80
assert pootle_site.domain == "foo.com"
assert (
pootle_site.build_absolute_uri("/foo")
== u'http://foo.com/bar/foo')
settings.POOTLE_CANONICAL_URL = "https://foo.com/bar"
pootle_site = site.get()
assert not pootle_site.uses_sites
assert not pootle_site.contrib_site
assert not pootle_site.use_insecure_http
assert pootle_site.use_http_port == 80
assert pootle_site.domain == "foo.com"
assert (
pootle_site.build_absolute_uri("/foo")
== u'https://foo.com/bar/foo')
settings.POOTLE_CANONICAL_URL = "https://foo.com:8008/bar"
pootle_site = site.get()
assert not pootle_site.uses_sites
assert not pootle_site.contrib_site
assert not pootle_site.use_insecure_http
assert pootle_site.use_http_port == 8008
assert pootle_site.domain == "foo.com"
assert (
pootle_site.build_absolute_uri("/foo")
== u'https://foo.com:8008/bar/foo')
| 2,947
|
Python
|
.py
| 79
| 32.075949
| 77
| 0.682295
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,017
|
paths.py
|
translate_pootle/tests/core/paths.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import pathlib
import posixpath
from hashlib import md5
import pytest
from django.utils.encoding import force_bytes
from pootle.core.paths import Paths
from pootle_store.models import Store
@pytest.mark.django_db
def test_paths_util(project0):
with pytest.raises(NotImplementedError):
Paths("", "").store_qs
class DummyPathsUtil(Paths):
@property
def store_qs(self):
return Store.objects.all()
paths_util = DummyPathsUtil(project0, "1")
assert paths_util.context == project0
assert paths_util.show_all is False
assert paths_util.q == "1"
assert (
paths_util.rev_cache_key
== project0.directory.revisions.get(key="stats").value)
assert (
paths_util.cache_key
== ("%s.%s.%s"
% (md5(force_bytes(paths_util.q)).hexdigest(),
paths_util.rev_cache_key,
paths_util.show_all)))
assert (
Store.objects.filter(
translation_project__project__disabled=False).exclude(
obsolete=True).exclude(is_template=True).filter(
tp_path__contains="1").count()
== paths_util.stores.count())
stores = set(
st[1:] for st in paths_util.stores.values_list("tp_path", flat=True))
dirs = set(
("%s/" % posixpath.dirname(path))
for path
in stores
if (path.count("/") > 1))
dirs = set()
for store in stores:
if posixpath.dirname(store) in dirs:
continue
dirs = (
dirs
| (set(
"%s/" % str(p)
for p
in pathlib.PosixPath(store).parents
if str(p) != ".")))
assert (
paths_util.paths
== sorted(
stores | dirs,
key=lambda path: (posixpath.dirname(path), posixpath.basename(path))))
paths_util = DummyPathsUtil(project0, "1", show_all=True)
assert (
Store.objects.exclude(is_template=True).filter(
tp_path__contains="1").count()
== paths_util.stores.count())
stores = set(
st[1:] for st in paths_util.stores.values_list("tp_path", flat=True))
for store in stores:
if posixpath.dirname(store) in dirs:
continue
dirs = (
dirs
| (set(
"%s/" % str(p)
for p
in pathlib.PosixPath(store).parents
if str(p) != ".")))
assert (
paths_util.paths
== sorted(
stores | dirs,
key=lambda path: (posixpath.dirname(path), posixpath.basename(path))))
assert (
paths_util.paths
== sorted(
stores | dirs,
key=lambda path: (posixpath.dirname(path), posixpath.basename(path))))
| 3,081
|
Python
|
.py
| 91
| 25.252747
| 82
| 0.580872
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,018
|
panels.py
|
translate_pootle/tests/core/panels.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import pytest
from pootle.core.views.panels import Panel
@pytest.mark.django_db
def test_panel_base():
panel = Panel(None)
assert panel.get_context_data() == {}
assert panel.content == ""
| 479
|
Python
|
.py
| 14
| 32.071429
| 77
| 0.739696
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,019
|
contextmanagers.py
|
translate_pootle/tests/core/contextmanagers.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import pytest
from django.dispatch import receiver
from pootle.core.contextmanagers import bulk_operations, keep_data
from pootle.core.signals import create, delete, update, update_data
from pootle_data.models import StoreChecksData
from pootle_store.models import QualityCheck, Store, Unit
def qs_match(qs1, qs2):
return (
list(qs1.order_by("id").values_list("id", flat=True))
== list(qs2.order_by("id").values_list("id", flat=True)))
@pytest.mark.django_db
def test_contextmanager_keep_data(store0, no_update_data):
result = []
with no_update_data():
@receiver(update_data, sender=Store)
def update_data_handler(**kwargs):
store = kwargs["instance"]
result.append(store)
update_data.send(Store, instance=store0)
assert result == [store0]
result.remove(store0)
# with keep_data decorator signal is suppressed
with keep_data():
update_data.send(Store, instance=store0)
assert result == []
# works again now
update_data.send(Store, instance=store0)
assert result == [store0]
def _create_qc_events(unit):
create_instances = [
QualityCheck(
name=("Foo%s" % i), category=2, unit=unit)
for i in range(0, 3)]
for instance in create_instances:
create.send(
QualityCheck,
instance=instance)
create_objects = [
QualityCheck(
name=("Bar%s" % i),
category=2,
unit=unit)
for i in range(0, 3)]
create_more_objects = [
QualityCheck(
name=("Baz%s" % i),
category=2,
unit=unit)
for i in range(0, 3)]
create.send(
QualityCheck,
objects=create_objects)
create.send(
QualityCheck,
objects=create_more_objects)
return create_instances + create_objects + create_more_objects
def _create_data_events(unit):
create_instances = [
StoreChecksData(
store=unit.store,
name="check-foo-%s" % i,
count=i * 23)
for i in range(0, 3)]
for instance in create_instances:
# add instances - these shouldnt appear in bulk operation
create.send(
StoreChecksData,
instance=instance)
create_objects = [
StoreChecksData(
store=unit.store,
name="check-bar-%s" % i,
count=i * 23)
for i in range(0, 3)]
create_more_objects = [
StoreChecksData(
store=unit.store,
name="check-baz-%s" % i,
count=i * 23)
for i in range(0, 3)]
# add 2 lots of objects
create.send(
StoreChecksData,
objects=create_objects)
create.send(
StoreChecksData,
objects=create_more_objects)
return create_instances + create_objects + create_more_objects
@pytest.mark.django_db
def test_contextmanager_bulk_operations(store0):
unit = store0.units.first()
class Update(object):
data_created = None
qc_created = None
data_called = 0
qc_called = 0
with keep_data(signals=[create]):
updated = Update()
@receiver(create, sender=QualityCheck)
def handle_qc_create(**kwargs):
assert "instance" not in kwargs
updated.qc_created = kwargs["objects"]
updated.qc_called += 1
@receiver(create, sender=StoreChecksData)
def handle_data_create(**kwargs):
updated.data_called += 1
if "objects" in kwargs:
updated.data_created = kwargs["objects"]
else:
assert "instance" in kwargs
with bulk_operations(QualityCheck):
qc_creates = _create_qc_events(unit)
data_creates = _create_data_events(unit)
assert updated.qc_created == qc_creates
assert updated.qc_called == 1
assert updated.data_created != data_creates
assert updated.data_called == 5
# nested update
updated = Update()
with bulk_operations(QualityCheck):
with bulk_operations(QualityCheck):
qc_creates = _create_qc_events(unit)
data_creates = _create_data_events(unit)
assert updated.qc_created == qc_creates
assert updated.qc_called == 1
assert updated.data_created != data_creates
assert updated.data_called == 5
# nested update - different models
updated = Update()
with bulk_operations(StoreChecksData):
with bulk_operations(QualityCheck):
qc_creates = _create_qc_events(unit)
data_creates = _create_data_events(unit)
assert updated.qc_created == qc_creates
assert updated.qc_called == 1
assert updated.data_created == data_creates
assert updated.data_called == 1
updated = Update()
with bulk_operations(models=(StoreChecksData, QualityCheck)):
qc_creates = _create_qc_events(unit)
data_creates = _create_data_events(unit)
assert updated.qc_created == qc_creates
assert updated.qc_called == 1
assert updated.data_created == data_creates
assert updated.data_called == 1
@pytest.mark.django_db
def test_contextmanager_bulk_ops_delete(tp0, store0):
unit = store0.units.first()
store1 = tp0.stores.filter(name="store1.po").first()
store2 = tp0.stores.filter(name="store2.po").first()
class Update(object):
store_deleted = None
unit_deleted = None
store_called = 0
unit_called = 0
with keep_data(signals=[delete]):
updated = Update()
@receiver(delete, sender=Unit)
def handle_unit_delete(**kwargs):
assert "instance" not in kwargs
updated.unit_deleted = kwargs["objects"]
updated.unit_called += 1
@receiver(delete, sender=Store)
def handle_store_delete(**kwargs):
updated.store_called += 1
if "objects" in kwargs:
updated.store_deleted = kwargs["objects"]
else:
assert "instance" in kwargs
with bulk_operations(Unit):
delete.send(Unit, instance=unit)
delete.send(Unit, objects=store1.unit_set.all())
delete.send(Unit, objects=store2.unit_set.all())
delete.send(Store, instance=store0)
delete.send(
Store,
objects=store1.translation_project.stores.filter(
id=store1.id))
delete.send(
Store,
objects=store2.translation_project.stores.filter(
id=store2.id))
assert updated.unit_called == 1
assert qs_match(
updated.unit_deleted,
(store0.unit_set.filter(id=unit.id)
| store1.unit_set.all()
| store2.unit_set.all()))
assert updated.store_called == 3
@pytest.mark.django_db
def test_contextmanager_bulk_ops_update(tp0, store0):
unit = store0.units.first()
store1 = tp0.stores.filter(name="store1.po").first()
store2 = tp0.stores.filter(name="store2.po").first()
class Update(object):
store_updated = None
unit_updated = None
store_called = 0
unit_called = 0
unit_updates = None
with keep_data(signals=[update]):
updated = Update()
@receiver(update, sender=Unit)
def handle_unit_update(**kwargs):
assert "instance" not in kwargs
updated.unit_updated = kwargs["objects"]
updated.unit_called += 1
updated.unit_update_fields = kwargs.get("update_fields")
updated.unit_updates = kwargs.get("updates")
@receiver(update, sender=Store)
def handle_store_update(**kwargs):
updated.store_called += 1
if "objects" in kwargs:
updated.store_updated = kwargs["objects"]
else:
assert "instance" in kwargs
with bulk_operations(Unit):
update.send(Unit, instance=unit)
update.send(Unit, objects=list(store1.unit_set.all()))
update.send(Unit, objects=list(store2.unit_set.all()))
update.send(Unit, update_fields=set(["foo", "bar"]))
update.send(Unit, update_fields=set(["bar", "baz"]))
update.send(Store, instance=store0)
update.send(
Store,
objects=list(store1.translation_project.stores.filter(
id=store1.id)))
update.send(
Store,
objects=list(store2.translation_project.stores.filter(
id=store2.id)))
assert updated.unit_called == 1
assert isinstance(updated.unit_updated, list)
assert qs_match(
Unit.objects.filter(
id__in=(
un.id for un in updated.unit_updated)),
(store0.unit_set.filter(id=unit.id)
| store1.unit_set.all()
| store2.unit_set.all()))
assert updated.store_called == 3
assert updated.unit_update_fields == set(["bar", "baz", "foo"])
updated = Update()
d1 = {23: dict(foo=True), 45: dict(bar=False)}
d2 = {67: dict(baz=89)}
with bulk_operations(Unit):
update.send(Unit, updates=d1)
update.send(Unit, updates=d2)
d1.update(d2)
assert updated.unit_updates == d1
| 9,879
|
Python
|
.py
| 257
| 28.525292
| 77
| 0.594947
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,020
|
primitives.py
|
translate_pootle/tests/core/primitives.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import pytest
from pootle.core.primitives import PrefixedDict
def test_prefix_dict_no_prefix():
mydict = dict(
foo="apples",
bar="oranges",
baz="bananas")
no_prefix = PrefixedDict(mydict, prefix="")
for k, v in mydict.items():
assert no_prefix[k] == v
no_prefix["foo"] = "pears"
no_prefix["other"] = "plums"
assert mydict["foo"] == "pears"
assert mydict["other"] == "plums"
assert no_prefix.get("foo") == "pears"
assert no_prefix.get("DOES NOT EXIST") is None
assert no_prefix.get("DOES NOT EXIST", "pears") == "pears"
def test_prefix_dict_with_prefix():
prefix = "some_prefix_"
mydict = dict(
foo="apples",
bar="oranges",
baz="bananas")
with_prefix = PrefixedDict(mydict, prefix=prefix)
with pytest.raises(KeyError):
with_prefix["foo"]
mydict = dict(
some_prefix_foo="apples",
some_prefix_bar="oranges",
some_prefix_baz="bananas")
with_prefix = PrefixedDict(mydict, prefix=prefix)
for k, v in mydict.items():
assert with_prefix[k[len(prefix):]] == v
with_prefix["foo"] = "pears"
with_prefix["other"] = "plums"
assert mydict["%sfoo" % prefix] == "pears"
assert mydict["%sother" % prefix] == "plums"
assert with_prefix.get("foo") == "pears"
assert with_prefix.get("DOES NOT EXIST") is None
assert with_prefix.get("DOES NOT EXIST", "pears") == "pears"
| 1,734
|
Python
|
.py
| 47
| 31.446809
| 77
| 0.642515
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,021
|
schema.py
|
translate_pootle/tests/core/schema.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import json
import pytest
from pootle.core.schema.base import SchemaTool, UnsupportedDBError
from pootle.core.schema.utils import get_current_db_type
from pootle.core.schema.dump import SchemaDump
TEST_MYSQL_SCHEMA_PARAM_NAMES = {
'defaults': set(['collation', 'character_set']),
'tables': {
'fields': set(['collation', 'type', 'key', 'extra']),
'indices': set(['non_unique', 'column_name', 'column_names']),
'constraints': set([
'referenced_table_name',
'table_name',
'referenced_column_name',
'column_name',
'column_names',
]),
}
}
@pytest.mark.django_db
def test_schema_tool_supported_database():
if get_current_db_type() != 'mysql':
with pytest.raises(UnsupportedDBError):
SchemaTool()
return
assert SchemaTool()
@pytest.mark.django_db
def test_schema_tool():
if get_current_db_type() != 'mysql':
pytest.skip("unsupported database")
schema_tool = SchemaTool()
defaults = schema_tool.get_defaults()
assert set(defaults.keys()) == TEST_MYSQL_SCHEMA_PARAM_NAMES['defaults']
for app_label in schema_tool.app_configs:
for table in schema_tool.get_app_tables(app_label):
row = schema_tool.get_table_fields(table).values()[0]
assert (
set([x.lower() for x in row.keys()]).issubset(
TEST_MYSQL_SCHEMA_PARAM_NAMES['tables']['fields'])
)
row = schema_tool.get_table_indices(table).values()[0]
assert (
set([x.lower() for x in row.keys()]).issubset(
TEST_MYSQL_SCHEMA_PARAM_NAMES['tables']['indices'])
)
row = schema_tool.get_table_constraints(table).values()[0]
assert (
set([x.lower() for x in row.keys()]).issubset(
TEST_MYSQL_SCHEMA_PARAM_NAMES['tables']['constraints'])
)
@pytest.mark.xfail(
reason="This test is a bit brittle and fails on ordering/versions")
@pytest.mark.django_db
def test_schema_dump(test_fs):
if get_current_db_type() != 'mysql':
pytest.skip("unsupported database")
schema_tool = SchemaTool()
expected_result = SchemaDump()
with test_fs.open(['data', 'schema.json']) as f:
expected_result.load(data=json.loads(f.read()))
assert expected_result.defaults == schema_tool.get_defaults()
for app_label in schema_tool.app_configs:
expected_app_result = expected_result.get_app(app_label)
for table_name in schema_tool.get_app_tables(app_label):
expected_table_result = expected_app_result.get_table(table_name)
assert (schema_tool.get_table_fields(table_name) ==
expected_table_result.fields)
assert (schema_tool.get_table_indices(table_name) ==
expected_table_result.indices)
assert (schema_tool.get_table_constraints(table_name) ==
expected_table_result.constraints)
| 3,331
|
Python
|
.py
| 78
| 34.346154
| 77
| 0.628898
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,022
|
url_helpers.py
|
translate_pootle/tests/core/url_helpers.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from pootle.core.url_helpers import (
get_editor_filter, split_pootle_path, urljoin)
def test_urljoin():
"""Tests URL parts are properly joined with a base."""
base = 'https://www.evernote.com/'
assert urljoin(base) == base
assert urljoin(base, '/foo/bar', 'baz/blah') == base + 'foo/bar/baz/blah'
assert urljoin(base, '/foo/', '/bar/', '/baz/') == base + 'foo/bar/baz/'
assert urljoin(base, '/foo//', '//bar/') == base + 'foo/bar/'
assert urljoin(base, '/foo//', '//bar/?q=a') == base + 'foo/bar/?q=a'
assert urljoin(base, 'foo//', '//bar/?q=a') == base + 'foo/bar/?q=a'
assert urljoin(base, 'foo//////') == base + 'foo/'
assert urljoin(base, 'foo', 'bar/baz', 'blah') == base + 'foo/bar/baz/blah'
assert urljoin(base, 'foo/', 'bar', 'baz/') == base + 'foo/bar/baz/'
assert urljoin('', '', '/////foo') == '/foo'
def test_split_pootle_path():
"""Tests pootle path are properly split."""
assert split_pootle_path('') == (None, None, '', '')
assert split_pootle_path('/projects/') == (None, None, '', '')
assert split_pootle_path('/projects/tutorial/') == \
(None, 'tutorial', '', '')
assert split_pootle_path('/pt/tutorial/tutorial.po') == \
('pt', 'tutorial', '', 'tutorial.po')
assert split_pootle_path('/pt/tutorial/foo/tutorial.po') == \
('pt', 'tutorial', 'foo/', 'tutorial.po')
def test_get_editor_filter():
"""Tests editor filters are correctly constructed."""
assert get_editor_filter(state='untranslated') == '#filter=untranslated'
assert get_editor_filter(state='untranslated', sort='newest') == \
'#filter=untranslated&sort=newest'
assert get_editor_filter(sort='newest') == '#sort=newest'
assert get_editor_filter(state='all', search='Foo',
sfields='locations') == '#filter=all'
assert get_editor_filter(search='Foo', sfields='locations') == \
'#search=Foo&sfields=locations'
assert get_editor_filter(search='Foo', sfields=['locations', 'notes']) == \
'#search=Foo&sfields=locations,notes'
assert get_editor_filter(search='Foo: bar.po\nID: 1',
sfields='locations') == \
'#search=Foo%3A+bar.po%0AID%3A+1&sfields=locations'
| 2,537
|
Python
|
.py
| 47
| 48.106383
| 79
| 0.616996
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,023
|
decorators.py
|
translate_pootle/tests/core/decorators.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import pytest
from django.http import Http404
from pootle.core.cache import get_cache
from pootle.core.decorators import get_path_obj, persistent_property
from pootle_language.models import Language
from pootle_project.models import Project
from pootle_translationproject.models import TranslationProject
@pytest.mark.django_db
def test_get_path_obj(rf, po_directory, default, tp0):
"""Ensure the correct path object is retrieved."""
language_code = tp0.language.code
project_code = tp0.project.code
language_code_fake = 'faf'
project_code_fake = 'fake-tutorial'
request = rf.get('/')
request.user = default
# Fake decorated function
func = get_path_obj(lambda x, y: (x, y))
# Single project
func(request, project_code=project_code)
assert isinstance(request.ctx_obj, Project)
# Missing project
with pytest.raises(Http404):
func(request, project_code=project_code_fake)
# Single language
func(request, language_code=language_code)
assert isinstance(request.ctx_obj, Language)
# Missing language
with pytest.raises(Http404):
func(request, language_code=language_code_fake)
# Translation Project
func(request, language_code=language_code, project_code=project_code)
assert isinstance(request.ctx_obj, TranslationProject)
# Missing Translation Project
with pytest.raises(Http404):
func(request, language_code=language_code_fake,
project_code=project_code)
@pytest.mark.django_db
def test_get_path_obj_disabled(rf, default, admin,
project0_nongnu,
tp0,
project_foo,
en_tutorial_obsolete,
tutorial_disabled):
"""Ensure the correct path object is retrieved when projects are
disabled (#3451) or translation projects are obsolete (#3682).
"""
language_code = tp0.language.code
language_code_obsolete = en_tutorial_obsolete.language.code
project_code_obsolete = en_tutorial_obsolete.project.code
project_code_disabled = tutorial_disabled.code
# Regular users first
request = rf.get('/')
request.user = default
func = get_path_obj(lambda x, y: (x, y))
# Single project
func(request, project_code=project_foo.code)
assert isinstance(request.ctx_obj, Project)
with pytest.raises(Http404):
func(request, project_code=project_code_disabled)
# Disabled project
with pytest.raises(Http404):
func(request, language_code=language_code,
project_code=project_code_disabled)
# Obsolete translation project
with pytest.raises(Http404):
func(request, language_code=language_code_obsolete,
project_code=project_code_obsolete)
# Now admin users, they should have access to disabled projects too
request = rf.get('/')
request.user = admin
func = get_path_obj(lambda x, y: (x, y))
# Single project
func(request, project_code=project_foo.code)
assert isinstance(request.ctx_obj, Project)
func(request, project_code=project_code_disabled)
assert isinstance(request.ctx_obj, Project)
# Disabled projects are still inaccessible
with pytest.raises(Http404):
func(request, language_code=language_code,
project_code=project_code_disabled)
# Obsolete translation projects are still inaccessible
with pytest.raises(Http404):
func(request, language_code=language_code_obsolete,
project_code=project_code_obsolete)
def test_deco_persistent_property_no_cache_key():
# no cache key set - uses instance caching
class Foo(object):
@persistent_property
def bar(self):
return "Baz"
foo = Foo()
assert foo.bar == "Baz"
assert foo.__dict__ == dict(bar="Baz")
# no cache key set and not always_cache - no caching
class Foo(object):
def _bar(self):
return "Baz"
bar = persistent_property(_bar, always_cache=False)
foo = Foo()
assert foo.bar == "Baz"
assert foo.__dict__ == {}
# no cache key set - uses instance caching with custom name
class Foo(object):
def _bar(self):
return "Baz"
bar = persistent_property(_bar, name="special_bar")
foo = Foo()
assert foo.bar == "Baz"
assert foo.__dict__ == dict(special_bar="Baz")
def test_deco_persistent_property():
# cache_key set - cached with it
class Foo(object):
cache_key = "foo-cache"
@persistent_property
def bar(self):
"""Get a bar man"""
return "Baz"
assert isinstance(Foo.bar, persistent_property)
assert Foo.bar.__doc__ == "Get a bar man"
foo = Foo()
assert foo.bar == "Baz"
assert get_cache("lru").get('pootle.core..foo-cache.bar') == "Baz"
# cached version this time
assert foo.bar == "Baz"
# cache_key set with custom key attr - cached with it
class Foo(object):
special_key = "special-foo-cache"
def _bar(self):
return "Baz"
bar = persistent_property(_bar, key_attr="special_key")
foo = Foo()
assert foo.bar == "Baz"
assert get_cache("lru").get('pootle.core..special-foo-cache._bar') == "Baz"
# cache_key set with custom key attr and name - cached with it
class Foo(object):
special_key = "special-foo-cache"
def _bar(self):
return "Baz"
bar = persistent_property(
_bar, name="bar", key_attr="special_key")
foo = Foo()
assert foo.bar == "Baz"
assert get_cache("lru").get('pootle.core..special-foo-cache.bar') == "Baz"
# cache_key set with custom namespace
class Foo(object):
ns = "pootle.foo"
cache_key = "foo-cache"
@persistent_property
def bar(self):
"""Get a bar man"""
return "Baz"
foo = Foo()
assert foo.bar == "Baz"
assert get_cache("lru").get('pootle.foo..foo-cache.bar') == "Baz"
# cached version this time
assert foo.bar == "Baz"
# cache_key set with custom namespace and sw_version
class Foo(object):
ns = "pootle.foo"
cache_key = "foo-cache"
sw_version = "0.2.3"
@persistent_property
def bar(self):
"""Get a bar man"""
return "Baz"
foo = Foo()
assert foo.bar == "Baz"
assert get_cache("lru").get('pootle.foo.0.2.3.foo-cache.bar') == "Baz"
# cached version this time
assert foo.bar == "Baz"
| 6,871
|
Python
|
.py
| 178
| 31.5
| 79
| 0.650008
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,024
|
forms.py
|
translate_pootle/tests/core/forms.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import pathlib
import posixpath
import pytest
from django import forms
from pootle.core.forms import FormtableForm, PathsSearchForm
from pootle_store.models import Store, Unit
from pootle_project.models import Project
class DummyFormtableForm(FormtableForm):
search_field = "units"
units = forms.ModelMultipleChoiceField(
Unit.objects.order_by("id"),
required=False)
class DummySearchFormtableForm(DummyFormtableForm):
filter_project = forms.ModelChoiceField(
Project.objects.all(),
required=False)
def search(self):
qs = self.fields[self.search_field].queryset
project = self._search_filters.get("filter_project")
if project:
return qs.filter(
store__translation_project__project=project)
return qs
@pytest.mark.django_db
def test_form_formtable():
form = DummyFormtableForm()
assert form.should_save() is False
assert form.action_field == "actions"
assert form.comment_field == "comment"
assert form.select_all_field == "select_all"
assert sorted(form.fields.keys()) == [
"actions", "comment",
"page_no", "results_per_page", "select_all", "units"]
assert list(form.search()) == list(Unit.objects.order_by("id"))
assert form.fields["results_per_page"].initial == 10
assert form.fields["page_no"].initial == 1
@pytest.mark.django_db
def test_form_formtable_search_filters():
form = DummySearchFormtableForm(
data=dict(results_per_page=10, page_no=1))
assert form.is_valid()
assert form.cleaned_data["page_no"] == 1
assert form.cleaned_data["results_per_page"] == 10
assert list(form.search()) == list(Unit.objects.order_by("id"))
# filter by project
project = Project.objects.first()
form = DummySearchFormtableForm(
data=dict(filter_project=project.pk))
assert form.is_valid()
assert form.cleaned_data["page_no"] == 1
assert form.cleaned_data["results_per_page"] == 10
# results are filtered and field queryset is also limited
assert (
list(form.search())
== list(form.fields["units"].queryset.all())
== list(
Unit.objects.filter(
store__translation_project__project=project).order_by("id")))
def _test_batch(form, units):
batch = form.batch()
assert batch.number == form._page_no
units_count = form.fields["units"].queryset.count()
assert (
batch.paginator.num_pages
== ((units_count / form._results_per_page)
+ (1
if units_count % form._results_per_page
else 0)))
assert (
[unit.id for unit in batch.object_list]
== list(
units.values_list("id", flat=True)[
form._results_per_page * (form._page_no - 1): (
form._results_per_page * form._page_no)]))
@pytest.mark.django_db
def test_form_formtable_bad():
with pytest.raises(ValueError):
# the base form does not specify a search field
FormtableForm()
form = DummySearchFormtableForm()
unit_id = form.fields["units"].queryset.first().pk
project = form.fields["filter_project"].queryset.first()
project_units = Unit.objects.filter(
store__translation_project__project=project).order_by("id")
# now submit the form with units set but no action
form = DummySearchFormtableForm(data=dict(units=[unit_id]))
assert not form.is_valid()
assert form.errors.keys() == ["actions"]
_test_batch(form, Unit.objects.order_by("id"))
assert form._page_no == 1
assert form._results_per_page == 10
assert form.fields["page_no"].initial == 1
assert form.fields["results_per_page"].initial == 10
# submit the form with filters, form is not valid but filters work
form = DummySearchFormtableForm(
data=dict(
units=[unit_id],
filter_project=project.pk))
assert not form.is_valid()
assert (
sorted(project_units.values_list("id", flat=True))
== sorted(form.search().values_list("id", flat=True)))
_test_batch(form, project_units)
@pytest.mark.django_db
def test_form_formtable_batch():
form = DummySearchFormtableForm()
project = form.fields["filter_project"].queryset.first()
project_units = Unit.objects.filter(
store__translation_project__project=project).order_by("id")
# submit the form with page_no == 2
form = DummySearchFormtableForm(
data=dict(
page_no=2,
filter_project=project.pk))
assert form.is_valid()
assert (
form.cleaned_data["page_no"]
== form.batch().paginator.num_pages)
_test_batch(form, project_units)
# submit the form with page_no == max
form = DummySearchFormtableForm(
data=dict(
page_no=form.batch().paginator.num_pages,
filter_project=project.pk))
assert form.is_valid()
assert (
form.cleaned_data["page_no"]
== form.batch().paginator.num_pages)
_test_batch(form, project_units)
# submit the form with page_no == 2, per_page == 2
form = DummySearchFormtableForm(
data=dict(
page_no=2,
results_per_page=20,
filter_project=project.pk))
assert form.is_valid()
assert (
form.cleaned_data["page_no"]
== form.batch().paginator.num_pages)
_test_batch(form, project_units)
# submit the form with page_no too high, form is valid
# but page no is set to highest possible
form = DummySearchFormtableForm(
data=dict(
page_no=form.batch().paginator.num_pages + 1,
filter_project=project.pk))
assert form.is_valid()
assert (
form.cleaned_data["page_no"]
== form.batch().paginator.num_pages)
_test_batch(form, project_units)
# submit the form with bad results_per_page, form is valid and
# results_per_page is set to a multiple of 10
form = DummySearchFormtableForm(
data=dict(
results_per_page=23,
filter_project=project.pk))
assert form.is_valid()
form.cleaned_data["results_per_page"] == 20
assert (
sorted(project_units.values_list("id", flat=True))
== sorted(form.search().values_list("id", flat=True)))
_test_batch(form, project_units)
# submit the form with results_per_page set too high, form is valid and
# results_per_page is set to default
form = DummySearchFormtableForm(
data=dict(
results_per_page=200,
filter_project=project.pk))
assert form.is_valid()
form.cleaned_data["results_per_page"] == 20
assert (
sorted(project_units.values_list("id", flat=True))
== sorted(form.search().values_list("id", flat=True)))
_test_batch(form, project_units)
# submit the form with results_per_page set too high, form is valid and
# results_per_page is set to default
form = DummySearchFormtableForm(
data=dict(
results_per_page=200,
filter_project=project.pk))
assert form.is_valid()
form.cleaned_data["results_per_page"] == 20
assert (
sorted(project_units.values_list("id", flat=True))
== sorted(form.search().values_list("id", flat=True)))
_test_batch(form, project_units)
# submit the form with bad page_no, form is valid and page_no is default
form = DummySearchFormtableForm(
data=dict(
page_no="NOT A PAGE NO",
filter_project=project.pk))
assert form.is_valid()
assert form.cleaned_data["page_no"] == 1
assert (
sorted(project_units.values_list("id", flat=True))
== sorted(form.search().values_list("id", flat=True)))
_test_batch(form, project_units)
@pytest.mark.django_db
def test_form_formtable_no_comment():
class DummyNoCommentFormtableForm(DummyFormtableForm):
comment_field = None
form = DummyNoCommentFormtableForm()
assert "comment" not in form.fields
@pytest.mark.django_db
def test_form_project_paths(project0, member, admin):
# needs a project
with pytest.raises(KeyError):
PathsSearchForm()
# needs a q
form = PathsSearchForm(context=project0)
assert not form.is_valid()
# q max = 255
form = PathsSearchForm(
context=project0,
data=dict(q=("BAD" * 85)))
assert form.is_valid()
form = PathsSearchForm(
context=project0,
data=dict(q="x%s" % ("BAD" * 85)))
assert not form.is_valid()
form = PathsSearchForm(
context=project0,
data=dict(q="DOES NOT EXIST"))
assert form.is_valid()
assert form.search() == dict(
more_results=False,
results=[])
class DummyProjectPathsSearchForm(PathsSearchForm):
step = 2
form = DummyProjectPathsSearchForm(
context=project0,
min_length=1,
data=dict(q="/"))
assert form.is_valid()
results = form.search()
assert len(results["results"]) == 2
assert results["more_results"] is True
project_stores = Store.objects.filter(
translation_project__project=project0)
stores = set(
st[1:]
for st
in project_stores.values_list(
"tp_path", flat=True).order_by())
dirs = set()
for store in stores:
if posixpath.dirname(store) in dirs:
continue
dirs = (
dirs
| (set(
"%s/" % str(p)
for p
in pathlib.PosixPath(store).parents
if str(p) != ".")))
paths = sorted(
stores | dirs,
key=lambda path: (posixpath.dirname(path), posixpath.basename(path)))
assert results["results"] == paths[0:2]
for i in range(0, int(round(len(paths) / 2.0))):
form = DummyProjectPathsSearchForm(
context=project0,
min_length=1,
data=dict(q="/", page=i + 1))
assert form.is_valid()
results = form.search()
assert results["results"] == paths[i * 2:(i + 1) * 2]
if (i + 1) * 2 >= len(paths):
results["more_results"] is False
else:
results["more_results"] is True
form = DummyProjectPathsSearchForm(
context=project0,
min_length=1,
data=dict(q="1"))
stores = set(
st[1:]
for st
in project_stores.filter(tp_path__contains="1").values_list(
"tp_path", flat=True).order_by())
dirs = set()
for store in stores:
if posixpath.dirname(store) in dirs:
continue
dirs = (
dirs
| (set(
"%s/" % str(p)
for p
in pathlib.PosixPath(store).parents
if str(p) != ".")))
paths = sorted(
stores | dirs,
key=lambda path: (posixpath.dirname(path), posixpath.basename(path)))
assert form.is_valid()
results = form.search()
assert len(results["results"]) == 2
assert results["more_results"] is True
for i in range(0, int(round(len(paths) / 2.0))):
form = DummyProjectPathsSearchForm(
context=project0,
min_length=1,
data=dict(q="1", page=i + 1))
assert form.is_valid()
results = form.search()
assert results["results"] == paths[i * 2:(i + 1) * 2]
if (i + 1) * 2 >= len(paths):
results["more_results"] is False
else:
results["more_results"] is True
| 11,822
|
Python
|
.py
| 318
| 29.641509
| 77
| 0.625
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,025
|
views.py
|
translate_pootle/tests/core/views.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import json
import pytest
from django import forms
from django.http import Http404
from pytest_pootle.factories import LanguageDBFactory, UserFactory
from pytest_pootle.utils import create_api_request
from accounts.models import User
from pootle.core.delegate import panels
from pootle.core.plugin import provider
from pootle.core.views import APIView
from pootle.core.views.browse import PootleBrowseView
from pootle.core.views.display import StatsDisplay
from pootle.core.views.panels import Panel
from pootle.core.views.widgets import TableSelectMultiple
from pootle_config.utils import ObjectConfig
def _test_stats_display(obj):
stats = StatsDisplay(obj)
assert stats.context == obj
stat_data = obj.data_tool.get_stats()
assert stats.stat_data == stat_data.copy()
stats.add_children_info(stat_data)
if stat_data.get("last_submission"):
stat_data["last_submission"]["msg"] = (
stats.get_action_message(
stat_data["last_submission"]))
StatsDisplay(obj).localize_stats(stat_data)
assert stat_data == stats.stats
class UserAPIView(APIView):
model = User
restrict_to_methods = ('get', 'delete',)
page_size = 10
fields = ('username', 'full_name',)
class WriteableUserAPIView(APIView):
model = User
fields = ('username', 'email',)
class UserSettingsForm(forms.ModelForm):
password = forms.CharField(required=False)
class Meta(object):
model = User
fields = ('username', 'password', 'full_name')
widgets = {
'password': forms.PasswordInput(),
}
def clean_password(self):
return self.cleaned_data['password'].upper()
class WriteableUserSettingsAPIView(APIView):
model = User
edit_form_class = UserSettingsForm
class UserM2MAPIView(APIView):
model = User
restrict_to_methods = ('get', 'delete',)
page_size = 10
fields = ('username', 'alt_src_langs',)
m2m = ('alt_src_langs', )
class UserConfigAPIView(APIView):
model = User
restrict_to_methods = ('get', 'delete',)
page_size = 10
fields = ('username', )
config = (
("foo0", "foo0.bar"),
("foo1", "foo1.bar"))
def test_apiview_invalid_method(rf):
"""Tests for invalid methods."""
view = UserAPIView.as_view()
# Forbidden method
request = create_api_request(rf, 'post')
response = view(request)
# "Method not allowed" if the method is not within the restricted list
assert response.status_code == 405
# Non-existent method
request = create_api_request(rf, 'patch')
response = view(request)
assert response.status_code == 405
@pytest.mark.django_db
def test_apiview_get_single(rf):
"""Tests retrieving a single object using the API."""
view = UserAPIView.as_view()
user = UserFactory.create(username='foo')
request = create_api_request(rf)
response = view(request, id=user.id)
# This should have been a valid request...
assert response.status_code == 200
# ...and JSON-encoded, so should properly parse it
response_data = json.loads(response.content)
assert isinstance(response_data, dict)
assert response_data['username'] == 'foo'
assert 'email' not in response_data
# Non-existent IDs should return 404
with pytest.raises(Http404):
view(request, id='777')
@pytest.mark.django_db
def test_apiview_get_multiple(rf, no_extra_users):
"""Tests retrieving multiple objects using the API."""
view = UserAPIView.as_view()
UserFactory.create(username='foo')
request = create_api_request(rf)
response = view(request)
response_data = json.loads(response.content)
# Response should contain a 1-item list
assert response.status_code == 200
assert isinstance(response_data, dict)
assert 'count' in response_data
assert 'models' in response_data
assert len(response_data['models']) == User.objects.count()
# Let's add more users
UserFactory.create_batch(5)
response = view(request)
response_data = json.loads(response.content)
assert response.status_code == 200
assert isinstance(response_data, dict)
assert 'count' in response_data
assert 'models' in response_data
assert len(response_data['models']) == User.objects.count()
# Let's add even more users to test pagination
UserFactory.create_batch(5)
response = view(request)
response_data = json.loads(response.content)
# First page is full
assert response.status_code == 200
assert isinstance(response_data, dict)
assert 'count' in response_data
assert 'models' in response_data
assert len(response_data['models']) == 10
request = create_api_request(rf, url='/?p=2')
response = view(request)
response_data = json.loads(response.content)
# Second page constains a single user
assert response.status_code == 200
assert isinstance(response_data, dict)
assert 'count' in response_data
assert 'models' in response_data
assert len(response_data['models']) == User.objects.count() - 10
@pytest.mark.django_db
def test_apiview_post(rf):
"""Tests creating a new object using the API."""
view = WriteableUserAPIView.as_view()
# Malformed request, only JSON-encoded data is understood
request = create_api_request(rf, 'post')
response = view(request)
response_data = json.loads(response.content)
assert response.status_code == 400
assert 'msg' in response_data
assert response_data['msg'] == 'Invalid JSON data'
# Not sending all required data fails validation
missing_data = {
'not_a_field': 'not a value',
}
request = create_api_request(rf, 'post', data=missing_data)
response = view(request)
response_data = json.loads(response.content)
assert response.status_code == 400
assert 'errors' in response_data
# Sending all required data should create a new user
data = {
'username': 'foo',
'email': 'foo@bar.tld',
}
request = create_api_request(rf, 'post', data=data)
response = view(request)
response_data = json.loads(response.content)
assert response.status_code == 200
assert response_data['username'] == 'foo'
user = User.objects.latest('id')
assert user.username == 'foo'
# Trying to add the same user again should fail validation
response = view(request)
response_data = json.loads(response.content)
assert response.status_code == 400
assert 'errors' in response_data
@pytest.mark.django_db
def test_apiview_put(rf):
"""Tests updating an object using the API."""
view = WriteableUserAPIView.as_view()
user = UserFactory.create(username='foo')
# Malformed request, only JSON-encoded data is understood
request = create_api_request(rf, 'put')
response = view(request, id=user.id)
response_data = json.loads(response.content)
assert response.status_code == 400
assert response_data['msg'] == 'Invalid JSON data'
# Update a field's data
new_username = 'foo_new'
update_data = {
'username': new_username,
}
request = create_api_request(rf, 'put', data=update_data)
# Requesting unknown resources is a 404
with pytest.raises(Http404):
view(request, id='11')
# All fields must be submitted
response = view(request, id=user.id)
response_data = json.loads(response.content)
assert response.status_code == 400
assert 'errors' in response_data
# Specify missing fields
update_data.update({
'email': user.email,
})
request = create_api_request(rf, 'put', data=update_data)
response = view(request, id=user.id)
response_data = json.loads(response.content)
# Now all is ok
assert response.status_code == 200
assert response_data['username'] == new_username
# Email shouldn't have changed
assert response_data['email'] == user.email
# View with a custom form
update_data.update({
'password': 'd34db33f',
})
view = WriteableUserSettingsAPIView.as_view()
request = create_api_request(rf, 'put', data=update_data)
response = view(request, id=user.id)
response_data = json.loads(response.content)
assert response.status_code == 200
assert 'password' not in response_data
@pytest.mark.django_db
def test_apiview_delete(rf):
"""Tests deleting an object using the API."""
view = UserAPIView.as_view()
user = UserFactory.create(username='foo')
# Delete is not supported for collections
request = create_api_request(rf, 'delete')
response = view(request)
assert response.status_code == 405
assert User.objects.filter(id=user.id).count() == 1
# But it is supported for single items (specified by id):
response = view(request, id=user.id)
assert response.status_code == 200
assert User.objects.filter(id=user.id).count() == 0
# Should raise 404 if we try to access a deleted resource again:
with pytest.raises(Http404):
view(request, id=user.id)
@pytest.mark.django_db
def test_apiview_search(rf):
"""Tests filtering through a search query."""
# Note that `UserAPIView` is configured to search in all defined fields,
# which are `username` and `full_name`
view = UserAPIView.as_view()
# Let's create some users to search for
UserFactory.create(username='foo', full_name='Foo Bar')
UserFactory.create(username='foobar', full_name='Foo Bar')
UserFactory.create(username='foobarbaz', full_name='Foo Bar')
# `q=bar` should match 3 users (full names match)
request = create_api_request(rf, url='/?q=bar')
response = view(request)
response_data = json.loads(response.content)
assert response.status_code == 200
assert len(response_data['models']) == 3
# `q=baz` should match 1 user
request = create_api_request(rf, url='/?q=baz')
response = view(request)
response_data = json.loads(response.content)
assert response.status_code == 200
assert len(response_data['models']) == 1
# Searches are case insensitive; `q=BaZ` should match 1 user
request = create_api_request(rf, url='/?q=BaZ')
response = view(request)
response_data = json.loads(response.content)
assert response.status_code == 200
assert len(response_data['models']) == 1
@pytest.mark.django_db
def test_view_gathered_context_data(rf, member, no_context_data):
from pootle.core.views.base import PootleDetailView
from pootle_project.models import Project
from pootle.core.delegate import context_data
class DummyView(PootleDetailView):
model = Project
def get_object(self):
return Project.objects.get(code="project0")
def get_context_data(self, *args, **kwargs):
return dict(foo="bar")
@property
def permission_context(self):
return self.get_object().directory
request = rf.get("foo")
request.user = member
view = DummyView.as_view()
response = view(request)
assert response.context_data == dict(foo="bar")
@provider(context_data, sender=DummyView)
def provide_context_data(sender, **kwargs):
return dict(
foo2="bar2",
sender=sender,
context=kwargs["context"],
view=kwargs["view"])
view = DummyView.as_view()
response = view(request)
assert response.context_data.pop("sender") == DummyView
assert response.context_data.pop("context") is response.context_data
assert isinstance(response.context_data.pop("view"), DummyView)
assert sorted(response.context_data.items()) == [
("foo", "bar"), ("foo2", "bar2")]
@pytest.mark.django_db
def test_apiview_get_single_m2m(rf):
"""Tests retrieving a single object with an m2m field using the API."""
view = UserM2MAPIView.as_view()
user = UserFactory.create(username='foo')
request = create_api_request(rf)
response = view(request, id=user.id)
response_data = json.loads(response.content)
assert response_data["alt_src_langs"] == []
user.alt_src_langs.add(LanguageDBFactory(code="alt1"))
user.alt_src_langs.add(LanguageDBFactory(code="alt2"))
request = create_api_request(rf)
response = view(request, id=user.id)
response_data = json.loads(response.content)
assert response_data["alt_src_langs"]
assert (
response_data["alt_src_langs"]
== list(str(l) for l in user.alt_src_langs.values_list("pk", flat=True)))
@pytest.mark.django_db
def test_apiview_get_multi_m2m(rf):
"""Tests several objects with m2m fields using the API."""
view = UserM2MAPIView.as_view()
user0 = UserFactory.create(username='foo0')
user1 = UserFactory.create(username='foo1')
request = create_api_request(rf)
response = view(request)
response_data = json.loads(response.content)
for model in [x for x in response_data["models"]
if x['username'] in ['foo0', 'foo1']]:
assert model['alt_src_langs'] == []
user0.alt_src_langs.add(LanguageDBFactory(code="alt1"))
user0.alt_src_langs.add(LanguageDBFactory(code="alt2"))
user1.alt_src_langs.add(LanguageDBFactory(code="alt3"))
user1.alt_src_langs.add(LanguageDBFactory(code="alt4"))
request = create_api_request(rf)
response = view(request)
response_data = json.loads(response.content)
for model in response_data["models"]:
user = User.objects.get(username=model["username"])
if user in [user0, user1]:
assert model["alt_src_langs"]
assert (
model["alt_src_langs"]
== list(
str(l) for l
in user.alt_src_langs.values_list("pk", flat=True)))
@pytest.mark.django_db
def test_apiview_get_single_config(rf):
"""Tests retrieving a single object with an m2m field using the API."""
view = UserConfigAPIView.as_view()
user0 = UserFactory.create(username='user0')
user1 = UserFactory.create(username='user1')
request = create_api_request(rf)
response = view(request, id=user0.id)
response_data = json.loads(response.content)
assert response_data["foo0"] is None
assert response_data["foo1"] is None
# string config
user_config = ObjectConfig(user1)
user_config["foo0.bar"] = "foo0.baz"
user_config["foo1.bar"] = "foo1.baz"
request = create_api_request(rf)
response = view(request, id=user1.id)
response_data = json.loads(response.content)
assert response_data["foo0"] == "foo0.baz"
assert response_data["foo1"] == "foo1.baz"
# list config
user_config["foo0.bar"] = ["foo0.baz"]
user_config["foo1.bar"] = ["foo1.baz"]
request = create_api_request(rf)
response = view(request, id=user1.id)
response_data = json.loads(response.content)
assert response_data["foo0"] == ["foo0.baz"]
assert response_data["foo1"] == ["foo1.baz"]
@pytest.mark.django_db
def test_apiview_get_multi_config(rf):
"""Tests retrieving a single object with an m2m field using the API."""
view = UserConfigAPIView.as_view()
user0 = UserFactory.create(username='user0')
user1 = UserFactory.create(username='user1')
request = create_api_request(rf)
response = view(request)
response_data = json.loads(response.content)
for model in response_data["models"]:
assert model["foo0"] is None
assert model["foo1"] is None
user_config = ObjectConfig(user0)
user_config["foo0.bar"] = "user0.foo0.baz"
user_config["foo1.bar"] = "user0.foo1.baz"
user_config = ObjectConfig(user1)
user_config["foo0.bar"] = "user1.foo0.baz"
user_config["foo1.bar"] = "user1.foo1.baz"
request = create_api_request(rf)
response = view(request)
response_data = json.loads(response.content)
for model in response_data["models"]:
if model["username"] in ["user0", "user1"]:
model["foo0"] == "%s.foo0.baz" % model["username"]
model["foo1"] == "%s.foo1.baz" % model["username"]
@pytest.mark.django_db
def test_widget_table_select_multiple_dict():
choices = (
("foo", dict(id="foo", title="Foo")),
("bar", dict(id="bar", title="Bar")),
("baz", dict(id="baz", title="Baz")))
widget = TableSelectMultiple(item_attrs=["id"], choices=choices)
rendered = widget.render("a-field", None)
for i, (name, choice) in enumerate(choices):
assert (
('<td class="row-select"><input type="checkbox" '
'name="a-field" value="%s" /></td>'
% name)
in rendered)
assert ('<td>%s</td>' % choice["title"]) not in rendered
widget = TableSelectMultiple(item_attrs=["id"], choices=choices)
rendered = widget.render("a-field", choices[0])
for i, (name, choice) in enumerate(choices):
checked = ""
if i == 0:
checked = ' checked'
assert (
('<td class="row-select"><input type="checkbox" '
'name="a-field" value="%s"%s /></td>'
% (name, checked))
in rendered)
assert ('<td>%s</td>' % choice["title"]) not in rendered
widget = TableSelectMultiple(item_attrs=["id", "title"], choices=choices)
rendered = widget.render("a-field", choices[0])
for i, (name, choice) in enumerate(choices):
checked = ""
if i == 0:
checked = ' checked'
assert (
('<td class="row-select"><input type="checkbox" '
'name="a-field" value="%s"%s /></td>'
% (name, checked))
in rendered)
assert ('<td class="field-title">%s</td>' % choice["title"]) in rendered
@pytest.mark.django_db
def test_widget_table_select_multiple_objects():
choices = (
("foo", dict(id="foo", title="Foo")),
("bar", dict(id="bar", title="Bar")),
("baz", dict(id="baz", title="Baz")))
class Dummy(object):
def __init__(self, **kwargs):
for k, v in kwargs.items():
setattr(self, k, v)
object_choices = tuple(
(name, Dummy(**choice)) for name, choice in choices)
widget = TableSelectMultiple(item_attrs=["id"], choices=object_choices)
rendered = widget.render("a-field", None)
for i, (name, choice) in enumerate(choices):
# this test is way too brittle
assert (
('<td class="row-select"><input type="checkbox" '
'name="a-field" value="%s" /></td>'
% name)
in rendered)
assert ('<td>%s</td>' % choice["title"]) not in rendered
widget = TableSelectMultiple(item_attrs=["id"], choices=object_choices)
rendered = widget.render("a-field", choices[0])
for i, (name, choice) in enumerate(choices):
checked = ""
if i == 0:
checked = ' checked'
# this test is way too brittle
assert (
('<td class="row-select"><input type="checkbox" '
'name="a-field" value="%s"%s /></td>'
% (name, checked))
in rendered)
assert ('<td>%s</td>' % choice["title"]) not in rendered
widget = TableSelectMultiple(item_attrs=["id", "title"], choices=object_choices)
rendered = widget.render("a-field", choices[0])
for i, (name, choice) in enumerate(choices):
checked = ""
if i == 0:
checked = ' checked'
# this test is way too brittle
assert (
('<td class="row-select"><input type="checkbox" '
'name="a-field" value="%s"%s /></td>'
% (name, checked))
in rendered)
assert ('<td class="field-title">%s</td>' % choice["title"]) in rendered
@pytest.mark.django_db
def test_widget_table_select_multiple_callable():
choices = (
("foo", dict(id="foo", title="Foo")),
("bar", dict(id="bar", title="Bar")),
("baz", dict(id="baz", title="Baz")))
def _get_id(attr):
return "xx%s" % attr["id"]
def _get_title(attr):
return "xx%s" % attr["title"]
widget = TableSelectMultiple(item_attrs=[_get_id], choices=choices)
rendered = widget.render("a-field", None)
for i, (name, choice) in enumerate(choices):
assert (
('<td class="row-select"><input type="checkbox" '
'name="a-field" value="%s" /></td>'
% name)
in rendered)
assert ('<td class="field-get-id">xx%s</td>' % choice["id"]) in rendered
assert (
('<td class="field-get-title">xx%s</td>' % choice["title"])
not in rendered)
widget = TableSelectMultiple(item_attrs=[_get_id], choices=choices)
rendered = widget.render("a-field", choices[0])
for i, (name, choice) in enumerate(choices):
checked = ""
if i == 0:
checked = ' checked'
assert (
('<td class="row-select"><input type="checkbox" '
'name="a-field" value="%s"%s /></td>'
% (name, checked))
in rendered)
assert ('<td class="field-get-id">xx%s</td>' % choice["id"]) in rendered
assert (
('<td class="field-get-title">xx%s</td>' % choice["title"])
not in rendered)
widget = TableSelectMultiple(item_attrs=[_get_id, _get_title], choices=choices)
rendered = widget.render("a-field", choices[0])
for i, (name, choice) in enumerate(choices):
checked = ""
if i == 0:
checked = ' checked'
assert (
('<td class="row-select"><input type="checkbox" '
'name="a-field" value="%s"%s /></td>'
% (name, checked))
in rendered)
assert ('<td class="field-get-id">xx%s</td>' % choice["id"]) in rendered
assert (
('<td class="field-get-title">xx%s</td>' % choice["title"])
in rendered)
@pytest.mark.django_db
def test_widget_table_select_multiple_object_methods():
choices = (
("foo", dict(id="foo", title="Foo")),
("bar", dict(id="bar", title="Bar")),
("baz", dict(id="baz", title="Baz")))
class Dummy(object):
def get_id(self):
return self.kwargs["id"]
def get_title(self):
return self.kwargs["title"]
def __init__(self, **kwargs):
self.kwargs = kwargs
for k in kwargs.keys():
setattr(self, k, getattr(self, "get_%s" % k))
object_choices = tuple(
(name, Dummy(**choice)) for name, choice in choices)
widget = TableSelectMultiple(item_attrs=["id"], choices=object_choices)
rendered = widget.render("a-field", None)
for i, (name, choice) in enumerate(choices):
assert (
('<td class="row-select"><input type="checkbox" '
'name="a-field" value="%s" /></td>'
% name)
in rendered)
assert ('<td>%s</td>' % choice["title"]) not in rendered
widget = TableSelectMultiple(item_attrs=["id"], choices=object_choices)
rendered = widget.render("a-field", choices[0])
for i, (name, choice) in enumerate(choices):
checked = ""
if i == 0:
checked = ' checked'
assert (
('<td class="row-select"><input type="checkbox" '
'name="a-field" value="%s"%s /></td>'
% (name, checked))
in rendered)
assert ('<td>%s</td>' % choice["title"]) not in rendered
widget = TableSelectMultiple(item_attrs=["id", "title"], choices=object_choices)
rendered = widget.render("a-field", choices[0])
for i, (name, choice) in enumerate(choices):
checked = ""
if i == 0:
checked = ' checked'
assert (
('<td class="row-select"><input type="checkbox" '
'name="a-field" value="%s"%s /></td>'
% (name, checked))
in rendered)
assert ('<td class="field-title">%s</td>' % choice["title"]) in rendered
@pytest.mark.django_db
def test_widget_table_select_id_attr():
choices = (
("foo", dict(id="foo", title="Foo")),
("bar", dict(id="bar", title="Bar")),
("baz", dict(id="baz", title="Baz")))
widget = TableSelectMultiple(item_attrs=["id"], choices=choices)
rendered = widget.render("a-field", None, attrs=dict(id="special-id"))
for i, (name, choice) in enumerate(choices):
assert (
('<td class="row-select"><input type="checkbox" '
'name="a-field" value="%s" id="special-id_%s" /></td>'
% (name, i))
in rendered)
@pytest.mark.django_db
def test_display_stats(tp0, subdir0, language0, store0):
_test_stats_display(tp0)
_test_stats_display(subdir0)
_test_stats_display(language0)
_test_stats_display(store0)
@pytest.mark.django_db
def test_display_stats_action_message(tp0):
action = dict(
profile_url="/profile/url",
unit_source="Some unit source",
unit_url="/unit/url",
displayname="Some user",
check_name="some-check",
checks_url="/checks/url",
check_display_name="Some check")
stats = StatsDisplay(tp0)
for i in [2, 3, 4, 6, 7, 8, 9]:
_action = action.copy()
_action["type"] = i
message = stats.get_action_message(_action)
assert (
("<a href='%s' class='user-name'>%s</a>"
% (action["profile_url"], action["displayname"]))
in message)
if i != 4:
assert (
("<a href='%s'>%s</a>"
% (action["unit_url"], action["unit_source"]))
in message)
if i in [6, 7]:
assert (
("<a href='%s'>%s</a>"
% (action["checks_url"], action["check_display_name"]))
in message)
for i in [1, 5]:
for _i in [0, 1, 2, 3, 4, 5]:
_action = action.copy()
_action["type"] = i
_action["translation_action_type"] = _i
message = stats.get_action_message(_action)
assert (
("<a href='%s' class='user-name'>%s</a>"
% (action["profile_url"], action["displayname"]))
in message)
assert (
("<a href='%s'>%s</a>"
% (action["unit_url"], action["unit_source"]))
in message)
@pytest.mark.django_db
def test_browse_view_panels():
class FooBrowseView(PootleBrowseView):
panel_names = ["foo_panel"]
class FooPanel(Panel):
@property
def content(self):
return "__FOO__"
@provider(panels, sender=FooBrowseView)
def foo_panel_provider(**kwargs_):
return dict(foo_panel=FooPanel)
view = FooBrowseView()
assert list(view.panels) == ["__FOO__"]
class BarBrowseView(PootleBrowseView):
panel_names = ["foo_panel", "bar_panel"]
class BarPanel(Panel):
@property
def content(self):
return "__BAR__"
@provider(panels, sender=PootleBrowseView)
def bar_panel_provider(**kwargs_):
return dict(bar_panel=BarPanel)
# foo_panel is only registered for FooBrowseView
# bar_panel is registered for PootleBrowseView
# only bar_panel is included
view = BarBrowseView()
assert list(view.panels) == ["__BAR__"]
| 27,634
|
Python
|
.py
| 680
| 33.551471
| 84
| 0.628415
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,026
|
filter.py
|
translate_pootle/tests/core/markup/filter.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import pytest
from pootle.core.markup.filters import apply_markup_filter
@pytest.mark.parametrize('markdown_text, expected_html, config', [
# Blank
('', '', {}),
(' \t', '', {}),
# Standard markdown
('Paragraph', '<p>Paragraph</p>', {}),
('## Header', '<h2>Header</h2>', {}),
('* List', '<ul><li>List</li></ul>', {}),
('<hr>', '<hr>', {}),
# Accept img tags since markdown is rubbish at images
('Show icon <img alt="image" src="pic.png">',
'<p>Show icon <img alt="image" src="pic.png"></p>', {}),
# Escape a <script> tag
('Bad hacker <script>alert("Bang!")</script>',
'<p>Bad hacker <script>alert("Bang!")</script></p>', {}),
# Extra tags
('Unknown <tag>Escaped</tag>',
'<p>Unknown <tag>Escaped</tag></p>', {}),
('Extra <tag>Included</tag>',
'<p>Extra <tag>Included</tag></p>',
{'clean': {
'extra_tags': ['tag'],
}}),
# Extra attributes
('Unknown <a attr="no">Escaped</a>',
'<p>Unknown <a>Escaped</a></p>', {}),
('Extra <a attr="yes">Included</a>',
'<p>Extra <a attr="yes">Included</a></p>',
{'clean': {
'extra_attrs': {'a': ['attr']},
}}),
# Extra styles
('Unknown <a style="color: remove;">Escaped</a>',
'<p>Unknown <a>Escaped</a></p>', {}),
('Extra <a style="color: accept;">Included</a>',
'<p>Extra <a style="color: accept;">Included</a></p>',
{'clean': {
'extra_attrs': {'*': ['style']},
'extra_styles': ['color'],
}}),
])
def test_apply_markup_filter(settings, markdown_text, expected_html, config):
settings.POOTLE_MARKUP_FILTER = ('markdown', config)
output_html = apply_markup_filter(markdown_text)
output_html = output_html[5:-6] # Remove surrounding <div>...</div>
output_html = output_html.replace('\n', '') # Remove pretty print newlines
assert output_html == expected_html
| 2,202
|
Python
|
.py
| 56
| 34.5
| 79
| 0.581232
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,027
|
core.py
|
translate_pootle/tests/core/templatetags/core.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from pootle.core.templatetags.core import map_to_lengths
def test_map_to_length_empty_list():
assert map_to_lengths([]) == []
def test_map_to_length_one_element():
assert map_to_lengths(['foo']) == [3]
def test_map_to_length_multiple_elements():
assert map_to_lengths(['foobar', 'foo', 'f']) == [6, 3, 1]
| 599
|
Python
|
.py
| 14
| 40.428571
| 77
| 0.709343
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,028
|
treeitem.py
|
translate_pootle/tests/core/mixins/treeitem.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import pytest
from pootle_app.models import Directory
from pootle_project.models import Project
from pootle_store.models import Store
from pootle_translationproject.models import TranslationProject
@pytest.mark.django_db
def test_get_children(project0, language0):
"""Ensure that retrieved child objects have a correct type."""
def _all_children_are_directories_or_stores(item):
for child in item.children:
if isinstance(child, Directory):
_all_children_are_directories_or_stores(child)
else:
assert isinstance(child, Store)
for tp in project0.children:
assert isinstance(tp, TranslationProject)
_all_children_are_directories_or_stores(tp)
for tp in language0.children:
assert isinstance(tp, TranslationProject)
_all_children_are_directories_or_stores(tp)
@pytest.mark.django_db
def test_get_parents(po_directory, project0, language0, tp0, store0, subdir0,
no_vfolders):
"""Ensure that retrieved parent objects have a correct type."""
subdir_store = subdir0.child_stores.first()
parents = subdir_store.get_parents()
assert len(parents) == 1
assert isinstance(parents[0], Directory)
parents = store0.get_parents()
assert len(parents) == 1
assert isinstance(parents[0], TranslationProject)
parents = tp0.get_parents()
assert len(parents) == 1
assert isinstance(parents[0], Project)
parents = tp0.directory.get_parents()
assert len(parents) == 1
assert isinstance(parents[0], Project)
parents = project0.directory.get_parents()
assert len(parents) == 0
parents = language0.directory.get_parents()
assert len(parents) == 0
| 2,013
|
Python
|
.py
| 48
| 36.375
| 77
| 0.716556
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,029
|
wordcount.py
|
translate_pootle/tests/core/utils/wordcount.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from translate.storage.statsdb import wordcount as ttk_wordcount
from pytest_pootle.fixtures.core.utils.wordcount import WORDCOUNT_TESTS
def test_param_wordcount(wordcount_names):
this_test = WORDCOUNT_TESTS[wordcount_names]
assert ttk_wordcount(this_test["string"]) == this_test["ttk"]
| 574
|
Python
|
.py
| 12
| 45.833333
| 77
| 0.777778
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,030
|
timezone.py
|
translate_pootle/tests/core/utils/timezone.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from datetime import datetime, timedelta
import pytest
import pytz
from django.utils import timezone
from pootle.core.utils.timezone import (
localdate, make_aware, make_naive, aware_datetime)
def test_localdate(settings):
today = localdate()
assert today == timezone.localtime(timezone.now()).date()
assert (
localdate(timezone.now() + timedelta(weeks=1))
== today + timedelta(weeks=1))
@pytest.mark.django_db
def test_make_aware(settings):
"""Tests datetimes can be made aware of timezones."""
settings.USE_TZ = True
datetime_object = datetime(2016, 1, 2, 21, 52, 25)
assert timezone.is_naive(datetime_object)
datetime_aware = make_aware(datetime_object)
assert timezone.is_aware(datetime_aware)
@pytest.mark.django_db
def test_make_aware_default_tz(settings):
"""Tests datetimes are made aware of the configured timezone."""
settings.USE_TZ = True
datetime_object = datetime(2016, 1, 2, 21, 52, 25)
assert timezone.is_naive(datetime_object)
datetime_aware = make_aware(datetime_object)
assert timezone.is_aware(datetime_aware)
# Not comparing `tzinfo` directly because that depends on the combination of
# actual date+times
assert datetime_aware.tzinfo.zone == timezone.get_default_timezone().zone
@pytest.mark.django_db
def test_make_aware_explicit_tz(settings):
"""Tests datetimes are made aware of the given timezone."""
settings.USE_TZ = True
given_timezone = pytz.timezone('Asia/Bangkok')
datetime_object = datetime(2016, 1, 2, 21, 52, 25)
assert timezone.is_naive(datetime_object)
datetime_aware = make_aware(datetime_object, tz=given_timezone)
assert timezone.is_aware(datetime_aware)
assert datetime_aware.tzinfo.zone == given_timezone.zone
@pytest.mark.django_db
def test_make_aware_use_tz_false(settings):
"""Tests datetimes are left intact if `USE_TZ` is not in effect."""
settings.USE_TZ = False
datetime_object = datetime(2016, 1, 2, 21, 52, 25)
assert timezone.is_naive(datetime_object)
datetime_aware = make_aware(datetime_object)
assert timezone.is_naive(datetime_aware)
@pytest.mark.django_db
def test_make_naive(settings):
"""Tests datetimes can be made naive of timezones."""
settings.USE_TZ = True
datetime_object = datetime(2016, 1, 2, 21, 52, 25, tzinfo=pytz.utc)
assert timezone.is_aware(datetime_object)
naive_datetime = make_naive(datetime_object)
assert timezone.is_naive(naive_datetime)
@pytest.mark.django_db
def test_make_naive_default_tz(settings):
"""Tests datetimes are made naive of the configured timezone."""
settings.USE_TZ = True
datetime_object = timezone.make_aware(
datetime(2016, 1, 2, 21, 52, 25),
timezone=pytz.timezone('Europe/Helsinki'))
assert timezone.is_aware(datetime_object)
naive_datetime = make_naive(datetime_object)
assert timezone.is_naive(naive_datetime)
assert(
naive_datetime
== make_naive(
datetime_object,
tz=pytz.timezone(settings.TIME_ZONE)))
@pytest.mark.django_db
def test_make_naive_explicit_tz(settings):
"""Tests datetimes are made naive of the given timezone."""
settings.USE_TZ = True
datetime_object = timezone.make_aware(datetime(2016, 1, 2, 21, 52, 25),
timezone=pytz.timezone('Europe/Helsinki'))
assert timezone.is_aware(datetime_object)
naive_datetime = make_naive(datetime_object, tz=pytz.timezone('Asia/Bangkok'))
assert timezone.is_naive(naive_datetime)
# Conversion from a Helsinki aware datetime to a naive datetime in Bangkok
# should increment 5 hours (UTC+2 vs. UTC+7)
assert naive_datetime.hour == (datetime_object.hour + 5) % 24
@pytest.mark.django_db
def test_make_naive_use_tz_false(settings):
"""Tests datetimes are left intact if `USE_TZ` is not in effect."""
settings.USE_TZ = False
datetime_object = datetime(2016, 1, 2, 21, 52, 25, tzinfo=pytz.utc)
assert timezone.is_aware(datetime_object)
naive_datetime = make_naive(datetime_object)
assert timezone.is_aware(naive_datetime)
def test_aware_datetime(settings):
"""Tests the creation of a timezone-aware datetime."""
datetime_object = aware_datetime(2016, 1, 2, 21, 52, 25)
assert timezone.is_aware(datetime_object)
assert datetime_object.tzinfo.zone == settings.TIME_ZONE
def test_aware_datetime_explicit_tz():
"""Tests the creation of a explicitly provided timezone-aware datetime."""
new_datetime = aware_datetime(2016, 1, 2, 21, 52, 25, tz=pytz.utc)
assert timezone.is_aware(new_datetime)
assert new_datetime.tzinfo.zone == pytz.utc.zone
| 4,987
|
Python
|
.py
| 109
| 40.844037
| 84
| 0.720777
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,031
|
multistring.py
|
translate_pootle/tests/core/utils/multistring.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import pytest
from translate.misc.multistring import multistring
from pootle.core.utils.multistring import (PLURAL_PLACEHOLDER, SEPARATOR,
parse_multistring, unparse_multistring)
@pytest.mark.parametrize('invalid_value', [None, [], (), 69, 69L])
def test_parse_multistring_invalid(invalid_value):
"""Tests parsing doesn't support non-string values"""
with pytest.raises(ValueError):
parse_multistring(invalid_value)
@pytest.mark.parametrize('db_string, expected_ms, is_plural', [
('foo bar', multistring('foo bar'), False),
('foo%s' % SEPARATOR, multistring(['foo', '']), True),
('foo%s%s' % (SEPARATOR, PLURAL_PLACEHOLDER), multistring('foo'), True),
('foo%sbar' % SEPARATOR, multistring(['foo', 'bar']), True),
('foo%sbar%sbaz' % (SEPARATOR, SEPARATOR),
multistring(['foo', 'bar', 'baz']), True),
])
def test_parse_multistring(db_string, expected_ms, is_plural):
parsed_ms = parse_multistring(db_string)
assert parsed_ms == expected_ms
assert parsed_ms.plural == is_plural
@pytest.mark.parametrize('invalid_value', [None, (), 69, 69L])
def test_unparse_multistring_invalid(invalid_value):
"""Tests unparsing does nothing for unsupported values."""
assert unparse_multistring(invalid_value) == invalid_value
@pytest.mark.parametrize('values_list, expected_ms, has_plural_placeholder', [
(['foo bar'], 'foo bar', False),
(multistring('foo bar'), 'foo bar', False),
(['foo', ''], 'foo%s' % SEPARATOR, False),
(multistring(['foo', '']), 'foo%s' % SEPARATOR, False),
(multistring(['foo']), 'foo%s%s' % (SEPARATOR, PLURAL_PLACEHOLDER), True),
(['foo', 'bar'], 'foo%sbar' % SEPARATOR, False),
(multistring(['foo', 'bar']), 'foo%sbar' % SEPARATOR, False),
(['foo', 'bar', 'baz'], 'foo%sbar%sbaz' % (SEPARATOR, SEPARATOR), False),
(multistring(['foo', 'bar', 'baz']),
'foo%sbar%sbaz' % (SEPARATOR, SEPARATOR), False),
])
def test_unparse_multistring(values_list, expected_ms, has_plural_placeholder):
if has_plural_placeholder:
values_list.plural = True
unparsed_ms = unparse_multistring(values_list)
assert unparsed_ms == expected_ms
| 2,479
|
Python
|
.py
| 49
| 46
| 82
| 0.674246
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,032
|
getters.py
|
translate_pootle/tests/core/plugin/getters.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from pootle.core.plugin import getter
from pootle.core.plugin.delegate import Getter
def test_getter():
get_test = Getter(providing_args=["foo"])
@getter(get_test)
def getter_for_get_test(*args, **kwargs):
return 2
assert get_test.get() == 2
def test_no_getter():
get_test = Getter(providing_args=["foo"])
assert get_test.get() is None
def test_getter_with_arg():
get_test = Getter(providing_args=["foo"])
@getter(get_test)
def getter_for_get_test(*args, **kwargs):
return kwargs["foo"]
assert get_test.get(foo=3) == 3
def test_getter_with_with_sender():
get_test = Getter(providing_args=["foo"])
@getter(get_test, sender=str)
def getter_for_get_test(sender, *args, **kwargs):
return kwargs["foo"]
assert get_test.get(str, foo="BOOM") == "BOOM"
def test_getter_with_with_sender_int():
get_test = Getter(providing_args=["foo"])
@getter(get_test, sender=int)
def getter_for_get_test(sender, *args, **kwargs):
return kwargs["foo"] * 7
assert get_test.get(int, foo=3) == 21
def test_getter_with_with_sender_multi():
get_test = Getter(providing_args=["foo"])
@getter(get_test)
def getter_for_get_test(sender, *args, **kwargs):
if sender is int:
return kwargs["foo"] * 7
return int(kwargs["foo"]) * 7
assert get_test.get(str, foo="3") == 21
assert get_test.get(int, foo=3) == 21
def test_getter_handle_multi():
get_test = Getter(providing_args=["foo"])
get_test_2 = Getter(providing_args=["foo"])
@getter([get_test, get_test_2])
def getter_for_get_test(sender, *args, **kwargs):
return kwargs["foo"]
assert get_test.get(str, foo="test 1") == "test 1"
assert get_test_2.get(str, foo="test 2") == "test 2"
def test_getter_multi_sender():
get_test = Getter(providing_args=["foo"])
@getter(get_test, sender=(str, int))
def getter_for_get_test(sender, *args, **kwargs):
return kwargs["foo"]
assert get_test.get(str, foo="test") == "test"
assert get_test.get(int, foo="test") == "test"
def test_getter_handle_order():
get_test = Getter(providing_args=["foo"])
@getter(get_test)
def getter_for_get_test(sender, *args, **kwargs):
pass
@getter(get_test)
def getter_for_get_test_2(sender, *args, **kwargs):
return 2
assert get_test.get(str, foo="bar") == 2
def test_getter_handle_order_2():
get_test = Getter(providing_args=["foo"])
@getter(get_test)
def getter_for_get_test(sender, *args, **kwargs):
return 1
@getter(get_test)
def getter_for_get_test_2(sender, *args, **kwargs):
return 2
assert get_test.get(str, foo="bar") == 1
def test_getter_handle_order_3():
get_test = Getter(providing_args=["foo"])
@getter(get_test)
def getter_for_get_test(sender, *args, **kwargs):
pass
@getter(get_test)
def getter_for_get_test_2(sender, *args, **kwargs):
return 2
@getter(get_test)
def getter_for_get_test_3(sender, *args, **kwargs):
return 3
assert get_test.get(str, foo="bar") == 2
| 3,443
|
Python
|
.py
| 90
| 32.744444
| 77
| 0.64522
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,033
|
results.py
|
translate_pootle/tests/core/plugin/results.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from collections import OrderedDict
import pytest
from pootle.core.plugin.delegate import Provider
from pootle.core.plugin.results import GatheredDict, GatheredList
def test_gathered_dict():
provider_test = Provider()
with pytest.raises(TypeError):
GatheredDict()
members = (
("foo3", "bar1"),
("foo2", "bar2"),
("foo1", "bar3"))
memberdict = OrderedDict(members)
gd = GatheredDict(provider_test)
[gd.add_result(None, dict((member, )))
for member in members]
assert gd.keys() == memberdict.keys()
assert gd.values() == memberdict.values()
assert gd.items() == memberdict.items()
assert [x for x in gd] == memberdict.keys()
assert all((k in gd) for k in memberdict.keys())
assert all((gd.get(k) == gd[k]) for k in memberdict.keys())
assert gd.get("DOES_NOT_EXIST") is None
assert gd.get("DOES_NOT_EXIST", "DEFAULT") == "DEFAULT"
def test_gathered_dict_update():
provider_test = Provider()
members = (
("foo3", "bar1"),
("foo2", "bar2"),
("foo1", "bar3"))
memberdict = OrderedDict(members)
gd = GatheredDict(provider_test)
[gd.add_result(None, dict((member, )))
for member in members]
# None results are ignored
gd.add_result(None, None)
newdict = dict()
newdict.update(gd)
assert all((k in newdict) for k in memberdict.keys())
assert all((newdict[k] == v) for k, v in memberdict.items())
assert len(newdict) == len(memberdict)
def test_gathered_list():
provider_test = Provider()
with pytest.raises(TypeError):
GatheredList()
provider_test = Provider()
gl = GatheredList(provider_test)
members = [
[2, 3, 4],
[3, 4, 5],
[4, 4, 7],
["foo", "bar"],
None]
memberlist = []
[memberlist.extend(member) for member in members if member]
[gl.add_result(None, member)
for member in members]
assert list(gl) == memberlist
assert [x for x in gl] == memberlist
assert all((k in gl) for k in memberlist)
newlist = []
newlist.extend(gl)
assert newlist == memberlist
| 2,420
|
Python
|
.py
| 70
| 29.357143
| 77
| 0.648672
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,034
|
providers.py
|
translate_pootle/tests/core/plugin/providers.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from pootle.core.plugin import provider
from pootle.core.plugin.delegate import Provider
from pootle.core.plugin.exceptions import StopProviding
from pootle.core.plugin.results import GatheredDict, GatheredList
def test_provider():
provider_test = Provider(providing_args=["foo"])
@provider(provider_test)
def provider_for_test(*args, **kwargs):
return dict(result=2)
results = provider_test.gather()
assert isinstance(results, GatheredDict)
assert results["result"] == 2
def test_no_providers():
provider_test = Provider(providing_args=["foo"])
results = provider_test.gather()
assert isinstance(results, GatheredDict)
assert results.keys() == []
def test_provider_with_arg():
provider_test = Provider(providing_args=["foo"])
@provider(provider_test)
def provider_for_test(*args, **kwargs):
return dict(result=kwargs["foo"])
results = provider_test.gather(None, foo=3)
assert isinstance(results, GatheredDict)
assert results["result"] == 3
def test_provider_with_sender():
provider_test = Provider(providing_args=["foo"])
@provider(provider_test, sender=str)
def provider_for_test(sender, *args, **kwargs):
return dict(result=kwargs["foo"])
results = provider_test.gather(str, foo="BOOM")
assert isinstance(results, GatheredDict)
assert results["result"] == "BOOM"
def test_provider_with_sender_int():
provider_test = Provider(providing_args=["foo"])
@provider(provider_test)
def provider_for_test(*args, **kwargs):
return dict(result=kwargs["foo"] * 7)
results = provider_test.gather(int, foo=3)
assert isinstance(results, GatheredDict)
assert results["result"] == 21
def test_provider_with_sender_multi():
provider_test = Provider(providing_args=["foo"])
@provider(provider_test)
def provider_for_test(sender, *args, **kwargs):
if sender is str:
return dict(result=int(kwargs["foo"]) * 7)
return dict(result=kwargs["foo"] * 7)
results = provider_test.gather(str, foo="3")
assert isinstance(results, GatheredDict)
assert results["result"] == 21
results = provider_test.gather(int, foo=3)
assert isinstance(results, GatheredDict)
assert results["result"] == 21
def test_provider_handle_multi_decorators():
provider_test = Provider(providing_args=["foo"])
provider_test_2 = Provider(providing_args=["foo"])
@provider([provider_test, provider_test_2], sender=str)
def provider_for_test(sender, *args, **kwargs):
return dict(result="BOOM: %s" % kwargs["foo"])
results = provider_test.gather(str, foo="1")
assert isinstance(results, GatheredDict)
assert results["result"] == "BOOM: 1"
results = provider_test_2.gather(str, foo="2")
assert isinstance(results, GatheredDict)
assert results["result"] == "BOOM: 2"
def test_provider_handle_multi_providers():
provider_test = Provider()
@provider(provider_test)
def provider_for_test(sender, *args, **kwargs):
return dict(result1=1)
@provider(provider_test)
def provider_for_test_2(sender, *args, **kwargs):
return dict(result2=2)
results = provider_test.gather()
assert isinstance(results, GatheredDict)
assert results["result1"] == 1
assert results["result2"] == 2
def test_provider_handle_null_provider():
provider_test = Provider()
@provider(provider_test)
def provider_for_test(sender, *args, **kwargs):
return dict(result1=1)
@provider(provider_test)
def provider_for_test_2(sender, *args, **kwargs):
return None
@provider(provider_test)
def provider_for_test_3(sender, *args, **kwargs):
return dict(result3=3)
results = provider_test.gather()
assert isinstance(results, GatheredDict)
assert results["result1"] == 1
assert "result2" not in results
assert results["result3"] == 3
def test_provider_handle_bad_providers():
provider_test = Provider()
@provider(provider_test)
def provider_for_test(sender, *args, **kwargs):
return dict(result1=1)
@provider(provider_test)
def provider_for_test_2(sender, *args, **kwargs):
return 3
@provider(provider_test)
def provider_for_test_3(sender, *args, **kwargs):
return []
@provider(provider_test)
def provider_for_test_4(sender, *args, **kwargs):
return dict(result4=4)
results = provider_test.gather()
assert isinstance(results, GatheredDict)
assert results["result1"] == 1
assert "result2" not in results
assert "result3" not in results
assert results["result4"] == 4
def test_provider_handle_stop_providing():
provider_test = Provider()
@provider(provider_test)
def provider_for_test(sender, *args, **kwargs):
return dict(result1=1)
@provider(provider_test)
def provider_for_test_2(sender, *args, **kwargs):
raise StopProviding(result=dict(result2=2))
@provider(provider_test)
def provider_for_test_3(sender, *args, **kwargs):
return dict(result3=3)
results = provider_test.gather()
assert isinstance(results, GatheredDict)
assert results["result1"] == 1
assert results["result2"] == 2
assert "result3" not in results
def test_provider_list_results():
provider_test = Provider(result_class=GatheredList)
@provider(provider_test)
def provider_for_test(sender, *args, **kwargs):
return [1, 2, 3]
@provider(provider_test)
def provider_for_test_2(sender, *args, **kwargs):
return [2, 3, 4]
results = provider_test.gather()
assert isinstance(results, GatheredList)
assert [r for r in results] == [1, 2, 3, 2, 3, 4]
def test_provider_subclass():
class ParentClass(object):
pass
class ChildClass(ParentClass):
pass
provider_test = Provider()
@provider(provider_test, sender=ParentClass)
def provider_for_test(sender, *args, **kwargs):
return dict(foo="bar")
assert provider_test.gather(ChildClass)["foo"] == "bar"
def test_provider_caching():
provider_test = Provider(use_caching=True)
@provider(provider_test)
def provider_for_test(sender, *args, **kwargs):
return dict(foo="bar")
assert provider_test.gather()["foo"] == "bar"
assert provider_test.gather()["foo"] == "bar"
def test_provider_caching_sender():
class Sender(object):
pass
provider_test = Provider(use_caching=True)
@provider(provider_test, sender=Sender)
def provider_for_test(sender, *args, **kwargs):
return dict(foo="bar")
assert provider_test.gather(Sender)["foo"] == "bar"
assert provider_test.gather(Sender)["foo"] == "bar"
def test_provider_caching_no_receiver():
class Sender(object):
pass
provider_test = Provider(use_caching=True)
assert provider_test.gather(Sender).keys() == []
assert provider_test.gather(Sender).keys() == []
class NotSender(object):
pass
@provider(provider_test, sender=Sender)
def provider_for_test(sender, *args, **kwargs):
return dict(foo="bar")
assert provider_test.gather(NotSender).keys() == []
assert provider_test.gather(NotSender).keys() == []
| 7,574
|
Python
|
.py
| 187
| 34.877005
| 77
| 0.686968
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,035
|
set_filetype.py
|
translate_pootle/tests/commands/set_filetype.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import pytest
from django.core.management import call_command
from django.core.management.base import CommandError
from pootle_project.models import Project
@pytest.mark.cmd
@pytest.mark.django_db
def test_cmd_set_project_filetype(dummy_project_filetypes,
templates_project0, po, po2):
template_tp = templates_project0
project = template_tp.project
other_tps = project.translationproject_set.exclude(pk=template_tp.pk)
result = project.filetype_tool.result
project.filetype_tool.add_filetype(po2)
call_command("set_filetype", "--project=project0", "special_po_2")
assert result[0] == (template_tp, po2, None, None)
for i, tp in enumerate(other_tps):
assert result[i + 1] == (tp, po2, None, None)
# test getting from_filetype
result.clear()
call_command(
"set_filetype",
"--project=project0",
"--from-filetype=po",
"special_po_2")
assert result[0] == (template_tp, po2, po, None)
for i, tp in enumerate(other_tps):
assert result[i + 1] == (tp, po2, po, None)
# test getting match
result.clear()
call_command(
"set_filetype",
"--project=project0",
"--matching=bar",
"special_po_2")
assert result[0] == (template_tp, po2, None, "bar")
for i, tp in enumerate(other_tps):
assert result[i + 1] == (tp, po2, None, "bar")
# test getting both
result.clear()
call_command(
"set_filetype",
"--project=project0",
"--from-filetype=po",
"--matching=bar",
"special_po_2")
assert result[0] == (template_tp, po2, po, "bar")
for i, tp in enumerate(other_tps):
assert result[i + 1] == (tp, po2, po, "bar")
@pytest.mark.cmd
@pytest.mark.django_db
def test_cmd_set_all_project_filetypes(dummy_project_filetypes, templates, po2):
for project in Project.objects.all():
project.filetype_tool.add_filetype(po2)
# grab the result object from a project
result = project.filetype_tool.result
call_command("set_filetype", "special_po_2")
i = 0
for project in Project.objects.all():
project_tps = project.translationproject_set.all()
for tp in project.translationproject_set.all():
if tp.is_template_project:
assert result[i] == (tp, po2, None, None)
i += 1
project_tps = project_tps.exclude(pk=tp.pk)
for tp in project_tps:
assert result[i] == (tp, po2, None, None)
i += 1
@pytest.mark.cmd
@pytest.mark.django_db
def test_cmd_set_project_filetypes_bad():
with pytest.raises(CommandError):
call_command(
"set_filetype",
"--project=project0",
"--from-filetype=FORMAT_DOES_NOT_EXIST",
"po")
with pytest.raises(CommandError):
call_command(
"set_filetype",
"--project=project0",
"FORMAT_DOES_NOT_EXIST")
| 3,272
|
Python
|
.py
| 88
| 30.193182
| 80
| 0.631512
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,036
|
sync_stores.py
|
translate_pootle/tests/commands/sync_stores.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from mock import MagicMock, patch
import pytest
from pootle_app.management.commands import PootleCommand
from pootle_app.management.commands.sync_stores import Command
@pytest.mark.cmd
@patch('pootle_app.management.commands.sync_stores.FSPlugin')
@patch('pootle_app.management.commands.sync_stores.logger')
def test_cmd_sync_stores(logger_mock, fs_plugin_mock):
"""Site wide sync_stores"""
assert issubclass(Command, PootleCommand)
tp = MagicMock(**{'project.pk': 23, 'pootle_path': 'FOO'})
fs_plugin_mock.return_value.state.return_value = [
'pootle_updated', 'fs_updated']
command = Command()
command.handle_all_stores(tp, skip_missing=True)
assert (
list(fs_plugin_mock.call_args)
== [(tp.project,), {}])
assert (
list(fs_plugin_mock.return_value.fetch.call_args())
== ['', (), {}])
assert (
list(fs_plugin_mock.return_value.state.call_args())
== ['', (), {}])
assert (
list(fs_plugin_mock.return_value.sync.call_args)
== [(), {'pootle_path': 'FOO*', 'update': 'fs'}])
assert not logger_mock.warn.called
assert not fs_plugin_mock.return_value.add.called
assert command.warn_on_conflict == []
@pytest.mark.cmd
@patch('pootle_app.management.commands.sync_stores.FSPlugin')
@patch('pootle_app.management.commands.sync_stores.logger')
def test_cmd_sync_stores_skip_missing(logger_mock, fs_plugin_mock):
"""Site wide sync_stores"""
assert issubclass(Command, PootleCommand)
tp = MagicMock(**{'project.pk': 23, 'pootle_path': 'FOO'})
fs_plugin_mock.return_value.state.return_value = [
'pootle_updated', 'fs_updated']
command = Command()
command.handle_all_stores(tp, skip_missing=False)
assert (
list(fs_plugin_mock.call_args)
== [(tp.project,), {}])
assert (
list(fs_plugin_mock.return_value.fetch.call_args())
== ['', (), {}])
assert (
list(fs_plugin_mock.return_value.state.call_args())
== ['', (), {}])
assert (
list(fs_plugin_mock.return_value.sync.call_args)
== [(), {'pootle_path': 'FOO*', 'update': 'fs'}])
assert not logger_mock.warn.called
assert (
list(fs_plugin_mock.return_value.add.call_args)
== [(), {'pootle_path': 'FOO*', 'update': 'fs'}])
assert command.warn_on_conflict == []
@pytest.mark.cmd
@patch('pootle_app.management.commands.sync_stores.FSPlugin')
@patch('pootle_app.management.commands.sync_stores.logger')
def test_cmd_sync_stores_warn_on_conflict(logger_mock, fs_plugin_mock):
"""Site wide sync_stores"""
assert issubclass(Command, PootleCommand)
tp = MagicMock(
**{'project.code': 7,
'project.pk': 23,
'pootle_path': 'FOO'})
fs_plugin_mock.return_value.state.return_value = [
'pootle_updated', 'conflict_untracked']
command = Command()
command.handle_all_stores(tp, skip_missing=True)
assert (
list(fs_plugin_mock.call_args)
== [(tp.project,), {}])
assert (
list(fs_plugin_mock.return_value.fetch.call_args())
== ['', (), {}])
assert (
list(fs_plugin_mock.return_value.state.call_args())
== ['', (), {}])
assert (
list(fs_plugin_mock.return_value.sync.call_args)
== [(), {'pootle_path': 'FOO*', 'update': 'fs'}])
assert (
list(logger_mock.warn.call_args)
== [("The project '%s' has conflicting changes in the database "
"and translation files. Use `pootle fs resolve` to tell "
"pootle how to merge", 7), {}])
assert not fs_plugin_mock.return_value.add.called
assert command.warn_on_conflict == [23]
@pytest.mark.cmd
@patch('pootle_app.management.commands.sync_stores.PootleCommand.handle')
@patch('pootle_app.management.commands.sync_stores.logger')
def test_cmd_sync_stores_warn(logger_mock, super_mock):
command = Command()
kwargs = dict(force=False, overwrite=False, foo='bar')
command.handle(**kwargs)
assert (
list(logger_mock.warn.call_args)
== [('The sync_stores command is deprecated, use pootle fs instead',),
{}])
assert (
list(super_mock.call_args)
== [(), kwargs])
logger_mock.reset_mock()
super_mock.reset_mock()
kwargs['force'] = True
command.handle(**kwargs)
assert (
[list(l) for l in logger_mock.warn.call_args_list]
== [[('The sync_stores command is deprecated, use pootle fs instead',),
{}],
[('The force option no longer has any affect on this command',),
{}]])
assert (
list(super_mock.call_args)
== [(), kwargs])
logger_mock.reset_mock()
super_mock.reset_mock()
kwargs['force'] = False
kwargs['overwrite'] = True
command.handle(**kwargs)
assert (
[list(l) for l in logger_mock.warn.call_args_list]
== [[('The sync_stores command is deprecated, use pootle fs instead',),
{}],
[('The overwrite option no longer has any affect on this command',),
{}]])
assert (
list(super_mock.call_args)
== [(), kwargs])
| 5,456
|
Python
|
.py
| 139
| 33.007194
| 80
| 0.629902
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,037
|
create_project.py
|
translate_pootle/tests/commands/create_project.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import pytest
from django.core.management import call_command, CommandError
from pootle.core.plugin import provider
from pootle_fs.delegate import fs_plugins
from pootle_fs.plugin import Plugin
from pootle_fs.presets import FS_PRESETS
from pootle_project.models import Project
@pytest.mark.cmd
@pytest.mark.django_db
def test_cmd_create_project_defaults(settings):
call_command(
"create_project",
"foo0",
"--preset-mapping=gnu")
foo0 = Project.objects.get(code="foo0")
assert foo0.fullname == "Foo0"
assert foo0.checkstyle == "standard"
assert foo0.filetypes.first().name == "po"
assert foo0.source_language.code == "en"
assert foo0.disabled is False
assert foo0.report_email == ""
assert (
foo0.config["pootle_fs.translation_mapping"]
== dict(default=FS_PRESETS["gnu"][0]))
assert foo0.config["pootle_fs.fs_type"] == "localfs"
assert (
foo0.config["pootle_fs.fs_url"]
== ("{POOTLE_TRANSLATION_DIRECTORY}%s"
% foo0.code))
@pytest.mark.cmd
@pytest.mark.django_db
def test_cmd_create_existing_project(settings):
call_command(
"create_project",
"foo0",
"--preset-mapping=gnu")
with pytest.raises(CommandError) as e:
call_command(
"create_project",
"foo0",
"--preset-mapping=gnu")
assert (
"'code': [u'Project with this Code already exists.'"
in str(e))
@pytest.mark.cmd
@pytest.mark.django_db
def test_cmd_create_project_title(capfd):
call_command(
"create_project",
"foo1",
"--name=Bar1",
"--preset-mapping=gnu")
foo1 = Project.objects.get(code="foo1")
assert foo1.fullname == "Bar1"
@pytest.mark.cmd
@pytest.mark.django_db
def test_cmd_create_project_checkstyle(capfd):
call_command(
"create_project",
"foo0",
"--checkstyle=minimal",
"--preset-mapping=gnu")
foo0 = Project.objects.get(code="foo0")
assert foo0.checkstyle == "minimal"
with pytest.raises(CommandError) as e:
call_command(
"create_project",
"foo1",
"--preset-mapping=gnu",
"--checkstyle=DOESNOTEXIST")
assert (
"Error: argument --checkstyle: invalid choice: u'DOESNOTEXIST'"
in str(e))
@pytest.mark.cmd
@pytest.mark.django_db
def test_cmd_create_project_filetypes(capfd):
call_command(
"create_project",
"foo0",
"--filetype=ts",
"--preset-mapping=gnu")
foo0 = Project.objects.get(code="foo0")
assert foo0.filetypes.first().name == "ts"
call_command(
"create_project",
"foo1",
"--filetype=ts",
"--filetype=po",
"--preset-mapping=gnu")
foo1 = Project.objects.get(code="foo1")
assert (
list(foo1.filetypes.values_list("name", flat=True))
== ["ts", "po"])
with pytest.raises(CommandError) as e:
call_command(
"create_project",
"foo2",
"--preset-mapping=gnu",
"--filetype=DOESNOTEXIST")
assert (
"Error: argument --filetype: invalid choice: u'DOESNOTEXIST'"
in str(e))
@pytest.mark.cmd
@pytest.mark.django_db
def test_cmd_create_project_report_email(capfd):
call_command(
"create_project",
"foo0",
"--report-email=foo@bar.com",
"--preset-mapping=gnu")
foo0 = Project.objects.get(code="foo0")
assert foo0.report_email == "foo@bar.com"
with pytest.raises(CommandError) as e:
call_command(
"create_project",
"foo0",
"--report-email=foo@bar",
"--preset-mapping=gnu")
assert (
"CommandError: [u'Enter a valid email address.']"
in str(e))
@pytest.mark.cmd
@pytest.mark.django_db
def test_cmd_create_project_source_language(language0):
call_command(
"create_project",
"foo0",
"--preset-mapping=gnu",
"--source-language=%s" % language0.code)
foo0 = Project.objects.get(code="foo0")
assert foo0.source_language == language0
with pytest.raises(CommandError) as e:
call_command(
"create_project",
"foo0",
"--preset-mapping=gnu",
"--source-language=DOESNOTEXIST")
assert (
"CommandError: Source language DOESNOTEXIST does not exist"
in str(e))
@pytest.mark.cmd
@pytest.mark.django_db
def test_cmd_create_project_disabled():
call_command(
"create_project",
"foo0",
"--preset-mapping=gnu",
"--disabled")
foo0 = Project.objects.get(code="foo0")
assert foo0.disabled is True
@pytest.mark.cmd
@pytest.mark.django_db
def test_cmd_create_project_preset_mapping():
call_command(
"create_project",
"foo0",
"--preset-mapping=nongnu")
foo0 = Project.objects.get(code="foo0")
assert (
foo0.config["pootle_fs.translation_mapping"]
== dict(default=FS_PRESETS["nongnu"][0]))
with pytest.raises(CommandError) as e:
# cant specify both mapping and preset-mapping
call_command(
"create_project",
"foo1",
"--preset-mapping=gnu",
"--mapping='/<language_code>/<dir_path>/<filename>.<ext>'")
assert (
"Error: argument --mapping: not allowed with argument --preset-mapping"
in str(e))
with pytest.raises(CommandError) as e:
# must specify one or other mapping or preset
call_command(
"create_project",
"foo1")
assert (
"Error: one of the arguments --preset-mapping --mapping is required"
in str(e))
@pytest.mark.cmd
@pytest.mark.django_db
def test_cmd_create_project_mapping():
call_command(
"create_project",
"foo0",
"--mapping=/<language_code>/<dir_path>/<filename>.<ext>")
foo0 = Project.objects.get(code="foo0")
assert (
foo0.config["pootle_fs.translation_mapping"]
== dict(default=u'/<language_code>/<dir_path>/<filename>.<ext>'))
with pytest.raises(CommandError) as e:
call_command(
"create_project",
"foo1",
"--mapping=NOTAMAPPING")
assert (
"Translation mapping 'NOTAMAPPING'"
in str(e))
@pytest.mark.cmd
@pytest.mark.django_db
def test_cmd_create_project_fs_type():
class DummyPlugin(Plugin):
pass
@provider(fs_plugins)
def dummy_fs_plugin(**kwargs):
return dict(dummyfs=DummyPlugin)
with pytest.raises(CommandError) as e:
call_command(
"create_project",
"foo0",
"--preset-mapping=gnu",
"--fs-type=dummyfs")
assert (
"Parameter --fs-url is mandatory when --fs-type is not `localfs`"
in str(e))
call_command(
"create_project",
"foo0",
"--preset-mapping=gnu",
"--fs-type=dummyfs",
"--fs-url=DUMMYURL")
foo0 = Project.objects.get(code="foo0")
assert (
foo0.config["pootle_fs.fs_type"]
== "dummyfs")
with pytest.raises(CommandError) as e:
call_command(
"create_project",
"foo1",
"--preset-mapping=gnu",
"--fs-type=DOESNOTEXIST")
assert (
"Error: argument --fs-type: invalid choice"
in str(e))
@pytest.mark.cmd
@pytest.mark.django_db
def test_cmd_create_project_fs_url():
call_command(
"create_project",
"foo0",
"--preset-mapping=gnu",
"--fs-url={POOTLE_TRANSLATION_DIRECTORY}special_foo0")
foo0 = Project.objects.get(code="foo0")
assert (
foo0.config["pootle_fs.fs_url"]
== "{POOTLE_TRANSLATION_DIRECTORY}special_foo0")
call_command(
"create_project",
"foo1",
"--preset-mapping=gnu",
"--fs-url=/abs/path/to/foo1")
foo1 = Project.objects.get(code="foo1")
assert (
foo1.config["pootle_fs.fs_url"]
== "/abs/path/to/foo1")
with pytest.raises(CommandError) as e:
call_command(
"create_project",
"foo2",
"--preset-mapping=gnu",
"--fs-url=NOTANABSOLUTEPATH")
assert (
"Enter an absolute path "
in str(e))
with pytest.raises(Project.DoesNotExist):
Project.objects.get(code="foo2")
| 8,669
|
Python
|
.py
| 273
| 24.553114
| 79
| 0.608139
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,038
|
config.py
|
translate_pootle/tests/commands/config.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import json
import pytest
from django.core.management import call_command
from django.core.management.base import CommandError
from pootle.core.delegate import config
from pootle_project.models import Project
def _repr_value(value):
if not isinstance(value, (str, unicode)):
value_class = type(value).__name__
return (
"%s(%s)"
% (value_class,
json.dumps(value)))
return value
def _test_config_get(out, key, model=None, instance=None, as_repr=False):
expected = ""
conf = config.get(model, instance=instance)
expected = conf.get_config(key)
expected_class = type(expected).__name__
expected = json.dumps(expected)
if not as_repr:
expected = "%s(%s)" % (expected_class, expected)
assert expected == out
def _test_config_list(out, model=None, instance=None, object_field=None):
conf_list = config.get(model, instance=instance).list_config()
if model:
item_name = str(model._meta)
if instance:
if object_field:
identifier = getattr(instance, object_field)
else:
identifier = instance.pk
item_name = "%s[%s]" % (item_name, identifier)
else:
item_name = "Pootle"
expected = []
items = []
name_col = 25
key_col = 25
for k, v in conf_list:
if model:
ct = str(model._meta)
if instance:
if object_field:
pk = getattr(
instance,
object_field)
else:
pk = instance.pk
name = "%s[%s]" % (ct, pk)
else:
name = ct
else:
name = "Pootle"
if len(name) > name_col:
name_col = len(name)
if len(k) > key_col:
key_col = len(k)
items.append((name, k, v))
format_string = "{: <%d} {: <%d} {: <30}" % (name_col, key_col)
for name, key, value in items:
expected.append(
format_string.format(
item_name, k, _repr_value(v)))
if not items:
assert out == "No configuration found\n"
else:
assert out == "%s\n" % ("\n".join(expected))
@pytest.mark.cmd
@pytest.mark.django_db
def test_cmd_config_list(capfd):
# no config set for anything
call_command("config")
out, err = capfd.readouterr()
_test_config_list(out)
# no config set for key foo
call_command("config", "-l", "foo")
out, err = capfd.readouterr()
_test_config_list(out)
config.get().set_config("foo", ["bar"])
call_command("config")
out, err = capfd.readouterr()
_test_config_list(out)
@pytest.mark.cmd
@pytest.mark.django_db
def test_cmd_config_list_model(capfd):
# no config set for anything
call_command("config", "pootle_project.project")
out, err = capfd.readouterr()
_test_config_list(out, model=Project)
# no config set for key foo
call_command("config", "pootle_project.project", "-l", "foo")
out, err = capfd.readouterr()
_test_config_list(out, model=Project)
config.get(Project).set_config("foo", ["bar"])
call_command("config", "pootle_project.project")
out, err = capfd.readouterr()
_test_config_list(out, model=Project)
@pytest.mark.cmd
@pytest.mark.django_db
def test_cmd_config_list_instance(no_config_env, capfd):
project = Project.objects.get(code="project0")
# no config set for anything
call_command("config", "pootle_project.project", str(project.pk))
out, err = capfd.readouterr()
_test_config_list(out, model=Project, instance=project)
# no config set for key foo
call_command(
"config",
"pootle_project.project",
str(project.pk),
"-l", "foo")
out, err = capfd.readouterr()
_test_config_list(out, model=Project, instance=project)
config.get(Project, instance=project).set_config("foo", ["bar"])
call_command("config", "pootle_project.project", str(project.pk))
out, err = capfd.readouterr()
_test_config_list(out, model=Project, instance=project)
@pytest.mark.cmd
@pytest.mark.django_db
def test_cmd_config_list_instance_object_field(no_config_env, capfd):
project = Project.objects.get(code="project0")
# no config set for anything
call_command(
"config",
"pootle_project.project",
project.code,
"-o", "code")
out, err = capfd.readouterr()
_test_config_list(
out,
model=Project,
instance=project,
object_field="code")
# no config set for key foo
call_command(
"config",
"pootle_project.project",
project.code,
"-o", "code",
"-l", "foo")
out, err = capfd.readouterr()
_test_config_list(
out,
model=Project,
instance=project,
object_field="code")
config.get(Project, instance=project).set_config("foo", ["bar"])
call_command(
"config",
"pootle_project.project",
project.code,
"-o", "code")
out, err = capfd.readouterr()
_test_config_list(
out,
model=Project,
instance=project,
object_field="code")
@pytest.mark.cmd
@pytest.mark.django_db
def test_cmd_config_get(capfd):
# -g requires a key
with pytest.raises(CommandError):
call_command("config", "-g")
# no config set for key foo
call_command("config", "-g", "foo")
out, err = capfd.readouterr()
_test_config_get(out, "foo")
config.get().set_config("foo", ["bar"])
call_command("config", "-g", "foo")
out, err = capfd.readouterr()
_test_config_get(out, "foo")
config.get().append_config("foo", ["bar"])
# multiple objects
with pytest.raises(CommandError):
call_command("config", "-g", "foo")
@pytest.mark.cmd
@pytest.mark.django_db
def test_cmd_config_get_model(capfd):
# -g requires a key
with pytest.raises(CommandError):
call_command(
"config",
"pootle_project.project",
"-g")
# no config set for key foo
call_command(
"config",
"pootle_project.project",
"-g", "foo")
out, err = capfd.readouterr()
_test_config_get(out, "foo", model=Project)
config.get(Project).set_config("foo", ["bar"])
call_command(
"config",
"pootle_project.project",
"-g", "foo")
out, err = capfd.readouterr()
_test_config_get(out, "foo", model=Project)
config.get(Project).append_config("foo", ["bar"])
# multiple objects
with pytest.raises(CommandError):
call_command(
"config",
"pootle_project.project",
"-g", "foo")
@pytest.mark.cmd
@pytest.mark.django_db
def test_cmd_config_get_instance(capfd):
project = Project.objects.get(code="project0")
# -g requires a key
with pytest.raises(CommandError):
call_command(
"config",
"pootle_project.project",
str(project.pk),
"-g")
# no config set for key foo
call_command(
"config",
"pootle_project.project",
str(project.pk),
"-g", "foo")
out, err = capfd.readouterr()
_test_config_get(
out, "foo", model=Project, instance=project)
config.get(Project, instance=project).set_config("foo", ["bar"])
call_command(
"config",
"pootle_project.project",
str(project.pk),
"-g", "foo")
out, err = capfd.readouterr()
_test_config_get(
out, "foo", model=Project, instance=project)
config.get(Project, instance=project).append_config("foo", ["bar"])
# multiple objects
with pytest.raises(CommandError):
call_command(
"config",
"pootle_project.project",
str(project.pk),
"-g", "foo")
@pytest.mark.cmd
@pytest.mark.django_db
def test_cmd_config_set(capfd):
# -s requires a key and value
with pytest.raises(CommandError):
call_command("config", "-s")
with pytest.raises(CommandError):
call_command("config", "-s", "foo")
call_command("config", "-s", "foo", "bar")
assert config.get().get_config("foo") == "bar"
# we can set it something else
call_command("config", "-s", "foo", "bar2")
assert config.get().get_config("foo") == "bar2"
config.get().append_config("foo", "bar3")
# key must be unique for -s or non-existent
with pytest.raises(CommandError):
call_command("config", "-s", "foo", "bar")
@pytest.mark.cmd
@pytest.mark.django_db
def test_cmd_config_set_model(capfd):
# -s requires a key and value
with pytest.raises(CommandError):
call_command(
"config",
"pootle_project.project",
"-s")
with pytest.raises(CommandError):
call_command(
"config",
"pootle_project.project",
"-s", "foo")
call_command(
"config",
"pootle_project.project",
"-s", "foo", "bar")
assert config.get(Project).get_config("foo") == "bar"
# we can set it something else
call_command(
"config",
"pootle_project.project",
"-s", "foo", "bar2")
assert config.get(Project).get_config("foo") == "bar2"
config.get(Project).append_config("foo", "bar3")
# key must be unique for -s or non-existent
with pytest.raises(CommandError):
call_command(
"config",
"pootle_project.project",
"-s", "foo", "bar")
@pytest.mark.cmd
@pytest.mark.django_db
def test_cmd_config_set_instance(capfd):
project = Project.objects.get(code="project0")
# -s requires a key and value
with pytest.raises(CommandError):
call_command(
"config",
"pootle_project.project",
str(project.pk),
"-s")
with pytest.raises(CommandError):
call_command(
"config",
"pootle_project.project",
str(project.pk),
"-s", "foo")
call_command(
"config",
"pootle_project.project",
str(project.pk),
"-s", "foo", "bar")
assert config.get(
Project,
instance=project).get_config("foo") == "bar"
# we can set it something else
call_command(
"config",
"pootle_project.project",
str(project.pk),
"-s", "foo", "bar2")
assert config.get(
Project,
instance=project).get_config("foo") == "bar2"
config.get(
Project,
instance=project).append_config("foo", "bar3")
# key must be unique for -s or non-existent
with pytest.raises(CommandError):
call_command(
"config",
"pootle_project.project",
str(project.pk),
"-s", "foo", "bar")
@pytest.mark.cmd
@pytest.mark.django_db
def test_cmd_config_append(capfd):
# -s requires a key and value
with pytest.raises(CommandError):
call_command("config", "-a")
with pytest.raises(CommandError):
call_command("config", "-a", "foo")
call_command("config", "-a", "foo", "bar")
assert config.get().get_config("foo") == "bar"
# we can add another with same k/v
call_command("config", "-a", "foo", "bar")
assert config.get().list_config("foo") == [
(u'foo', u'bar'), (u'foo', u'bar')]
# and another with different v
call_command("config", "-a", "foo", "bar2")
assert config.get().list_config("foo") == [
(u'foo', u'bar'),
(u'foo', u'bar'),
(u'foo', u'bar2')]
# and another with different k
call_command("config", "-a", "foo2", "bar3")
assert config.get().get_config("foo2") == "bar3"
@pytest.mark.cmd
@pytest.mark.django_db
def test_cmd_config_append_model(capfd):
# -s requires a key and value
with pytest.raises(CommandError):
call_command(
"config",
"pootle_project.project",
"-a")
with pytest.raises(CommandError):
call_command(
"config",
"pootle_project.project",
"-a", "foo")
call_command(
"config",
"pootle_project.project",
"-a", "foo", "bar")
assert config.get(Project).get_config("foo") == "bar"
# we can add another with same k/v
call_command(
"config",
"pootle_project.project",
"-a", "foo", "bar")
assert config.get(Project).list_config("foo") == [
(u'foo', u'bar'), (u'foo', u'bar')]
# and another with different v
call_command(
"config",
"pootle_project.project",
"-a", "foo", "bar2")
assert config.get(Project).list_config("foo") == [
(u'foo', u'bar'),
(u'foo', u'bar'),
(u'foo', u'bar2')]
# and another with different k
call_command(
"config",
"pootle_project.project",
"-a", "foo2", "bar3")
assert config.get(Project).get_config("foo2") == "bar3"
@pytest.mark.cmd
@pytest.mark.django_db
def test_cmd_config_append_instance(capfd):
project = Project.objects.get(code="project0")
# -s requires a key and value
with pytest.raises(CommandError):
call_command(
"config",
"pootle_project.project",
str(project.pk),
"-a")
with pytest.raises(CommandError):
call_command(
"config",
"pootle_project.project",
str(project.pk),
"-a", "foo")
call_command(
"config",
"pootle_project.project",
str(project.pk),
"-a", "foo", "bar")
assert config.get(
Project,
instance=project).get_config("foo") == "bar"
# we can add another with same k/v
call_command(
"config",
"pootle_project.project",
str(project.pk),
"-a", "foo", "bar")
assert config.get(Project, instance=project).list_config("foo") == [
(u'foo', u'bar'), (u'foo', u'bar')]
# and another with different v
call_command(
"config",
"pootle_project.project",
str(project.pk),
"-a", "foo", "bar2")
assert config.get(Project, instance=project).list_config("foo") == [
(u'foo', u'bar'),
(u'foo', u'bar'),
(u'foo', u'bar2')]
# and another with different k
call_command(
"config",
"pootle_project.project",
str(project.pk),
"-a", "foo2", "bar3")
assert config.get(Project, instance=project).get_config("foo2") == "bar3"
@pytest.mark.cmd
@pytest.mark.django_db
def test_cmd_config_clear(capfd):
# -c requires a key and it should exist
with pytest.raises(CommandError):
call_command("config", "-c")
# you can clear nothing
call_command("config", "-c", "foo")
# lets add a config and clear it
config.get().append_config("foo", "bar")
call_command("config", "-c", "foo")
assert config.get().get_config("foo") is None
# lets add 2 config and clear them
config.get().append_config("foo", "bar")
config.get().append_config("foo", "bar")
call_command("config", "-c", "foo")
assert config.get().get_config("foo") is None
# lets add 2 config with diff v and clear them
config.get().append_config("foo", "bar")
config.get().append_config("foo", "bar2")
call_command("config", "-c", "foo")
assert config.get().get_config("foo") is None
# lets add 2 config with diff k and clear one
config.get().set_config("foo", "bar")
config.get().set_config("foo2", "bar2")
call_command("config", "-c", "foo")
assert config.get().get_config("foo2") == "bar2"
@pytest.mark.cmd
@pytest.mark.django_db
def test_cmd_config_clear_model(capfd):
# -c requires a key
with pytest.raises(CommandError):
call_command(
"config",
"pootle_project.project",
"-c")
# you can clear nothing
call_command(
"config",
"pootle_project.project",
"-c", "foo")
# lets add a config and clear it
config.get(Project).append_config("foo", "bar")
call_command(
"config",
"pootle_project.project",
"-c", "foo")
assert config.get(Project).get_config("foo") is None
# lets add 2 config and clear them
config.get(Project).append_config("foo", "bar")
config.get(Project).append_config("foo", "bar")
call_command(
"config",
"pootle_project.project",
"-c", "foo")
assert config.get(Project).get_config("foo") is None
# lets add 2 config with diff v and clear them
config.get(Project).append_config("foo", "bar")
config.get(Project).append_config("foo", "bar2")
call_command(
"config",
"pootle_project.project",
"-c", "foo")
assert config.get(Project).get_config("foo") is None
# lets add 2 config with diff k and clear one
config.get(Project).set_config("foo", "bar")
config.get(Project).set_config("foo2", "bar2")
call_command(
"config",
"pootle_project.project",
"-c", "foo")
assert config.get(Project).get_config("foo2") == "bar2"
@pytest.mark.cmd
@pytest.mark.django_db
def test_cmd_config_clear_instance(capfd):
project = Project.objects.get(code="project0")
# -c requires a key
with pytest.raises(CommandError):
call_command(
"config",
"pootle_project.project",
str(project.pk),
"-c")
# you can clear nothing
call_command(
"config",
"pootle_project.project",
str(project.pk),
"-c", "foo")
# lets add a config and clear it
config.get(Project, instance=project).append_config("foo", "bar")
call_command(
"config",
"pootle_project.project",
str(project.pk),
"-c", "foo")
assert config.get(Project, instance=project).get_config("foo") is None
# lets add 2 config and clear them
config.get(Project, instance=project).append_config("foo", "bar")
config.get(Project, instance=project).append_config("foo", "bar")
call_command(
"config",
"pootle_project.project",
str(project.pk),
"-c", "foo")
assert config.get(Project, instance=project).get_config("foo") is None
# lets add 2 config with diff v and clear them
config.get(Project, instance=project).append_config("foo", "bar")
config.get(Project, instance=project).append_config("foo", "bar2")
call_command(
"config",
"pootle_project.project",
str(project.pk),
"-c", "foo")
assert config.get(Project, instance=project).get_config("foo") is None
# lets add 2 config with diff k and clear one
config.get(Project, instance=project).set_config("foo", "bar")
config.get(Project, instance=project).set_config("foo2", "bar2")
call_command(
"config",
"pootle_project.project",
str(project.pk),
"-c", "foo")
assert config.get(Project, instance=project).get_config("foo2") == "bar2"
@pytest.mark.cmd
@pytest.mark.django_db
def test_cmd_config_bad(capfd):
project = Project.objects.get(code="project0")
with pytest.raises(CommandError):
call_command(
"config",
"pootle_project")
with pytest.raises(CommandError):
call_command(
"config",
"pootle_project.DOESNT_EXIST")
with pytest.raises(CommandError):
call_command(
"config",
"",
str(project.pk))
with pytest.raises(CommandError):
call_command(
"config",
"pootle_project.project",
"DOES_NOT_EXIST",
"-o", "code")
with pytest.raises(CommandError):
# non-unique
call_command(
"config",
"pootle_project.project",
"standard",
"-o", "checkstyle")
with pytest.raises(CommandError):
call_command(
"config",
"pootle_project.project",
project.code,
"-o", "OBJECT_FIELD_NOT_EXIST")
with pytest.raises(CommandError):
call_command(
"config",
"-j",
"-s", "foo", "[BAD JSON]")
with pytest.raises(CommandError):
call_command(
"config",
"pootle_project.project",
"asdf")
@pytest.mark.django_db
def test_cmd_config_set_json(capfd, json_objects):
call_command(
"config",
"-j",
"-s", "foo", json.dumps(json_objects))
if isinstance(json_objects, tuple):
json_objects = list(json_objects)
assert config.get(key="foo") == json_objects
capfd.readouterr()
call_command(
"config",
"-j",
"-g", "foo")
out, err = capfd.readouterr()
assert json.loads(out) == json_objects
call_command(
"config",
"-g", "foo")
out, err = capfd.readouterr()
assert out == _repr_value(json_objects)
@pytest.mark.django_db
def test_cmd_config_append_json(capfd, json_objects):
call_command(
"config",
"pootle_project.project",
"-j",
"-a", "foo", json.dumps(json_objects))
if isinstance(json_objects, tuple):
json_objects = list(json_objects)
assert config.get(Project, key="foo") == json_objects
capfd.readouterr()
call_command(
"config",
"pootle_project.project",
"-j",
"-g", "foo")
out, err = capfd.readouterr()
assert json.loads(out) == json_objects
call_command(
"config",
"pootle_project.project",
"-g", "foo")
out, err = capfd.readouterr()
assert out == _repr_value(json_objects)
@pytest.mark.django_db
def test_cmd_config_bad_flags(capfd, bad_config_flags):
with pytest.raises(CommandError):
call_command(
"config",
*bad_config_flags)
@pytest.mark.django_db
def test_cmd_config_long_instance_name(project0, no_config_env, capfd):
project0.code = "foobar" * 10
project0.save()
config.get(Project, instance=project0).append_config("foo", "bar")
config.get(Project, instance=project0).append_config("foo", "bar")
call_command(
"config",
"pootle_project.project",
project0.code,
"-o", "code")
out, err = capfd.readouterr()
_test_config_list(out, model=Project, instance=project0, object_field="code")
@pytest.mark.django_db
def test_cmd_config_long_key_name(no_config_env, capfd):
project = Project.objects.get(code="project0")
config.get(Project, instance=project).append_config("foobar" * 10, "bar")
call_command(
"config",
"pootle_project.project",
str(project.pk))
out, err = capfd.readouterr()
_test_config_list(out, model=Project, instance=project)
| 23,233
|
Python
|
.py
| 702
| 25.780627
| 81
| 0.591954
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,039
|
add_vfolders.py
|
translate_pootle/tests/commands/add_vfolders.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import os
import pytest
from django.core.management import call_command
from django.core.management.base import CommandError
@pytest.mark.cmd
def test_add_vfolders_user_nofile():
"""Missing vfolder argument."""
with pytest.raises(CommandError) as e:
call_command('add_vfolders')
assert "too few arguments" in str(e)
@pytest.mark.cmd
def test_add_vfolders_user_non_existant_file():
"""No file on filesystem."""
with pytest.raises(CommandError) as e:
call_command('add_vfolders', 'nofile.json')
assert "No such file or directory" in str(e)
@pytest.mark.cmd
@pytest.mark.django_db
def test_add_vfolders_emptyfile(capfd, tmpdir):
"""Load an empty vfolder.json file"""
p = tmpdir.mkdir("sub").join("empty.json")
p.write("{}")
call_command('add_vfolders', os.path.join(p.dirname, p.basename))
out, err = capfd.readouterr()
assert "Importing virtual folders" in out
| 1,207
|
Python
|
.py
| 32
| 34.4375
| 77
| 0.72813
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,040
|
update_stores.py
|
translate_pootle/tests/commands/update_stores.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from mock import PropertyMock, patch
import pytest
from django.core.management import CommandError, call_command
from pootle_app.management.commands.update_stores import Command
# TODO: add test for _create_tps_for_projects/_parse_tps_to_create
DEFAULT_OPTIONS = {
'force': False,
'settings': None,
'pythonpath': None,
'verbosity': 3,
'traceback': False,
u'skip_checks': True,
'no_rq': False,
'atomic': 'tp',
'noinput': False,
'overwrite': False,
'no_color': False}
@pytest.mark.cmd
@patch('pootle_app.management.commands.PootleCommand.handle_all')
@patch(
'pootle_app.management.commands.update_stores.Project.objects',
new_callable=PropertyMock)
@patch(
'pootle_app.management.commands.update_stores.Command._create_tps_for_project')
@patch(
'pootle_app.management.commands.update_stores.Command.check_projects')
def test_update_stores_noargs(check_projects, create_mock, project_mock,
command_mock, capfd):
"""Site wide update_stores"""
project_mock.configure_mock(
**{"return_value.all.return_value.iterator.return_value": [1, 2, 3],
"return_value.filter.return_value.iterator.return_value": [4, 5, 6]})
command_mock.return_value = 23
call_command('update_stores', '-v3')
assert (
[list(l) for l in create_mock.call_args_list]
== [[(1,), {}], [(2,), {}], [(3,), {}]])
assert (
list(command_mock.call_args)
== [(), DEFAULT_OPTIONS])
create_mock.reset_mock()
command_mock.reset_mock()
call_command('update_stores', '-v3', '--project', '7', '--project', '23')
assert (
list(check_projects.call_args)
== [([u'7', u'23'],), {}])
assert (
[list(l) for l in create_mock.call_args_list]
== [[(4,), {}], [(5,), {}], [(6,), {}]])
assert (
list(command_mock.call_args)
== [(), DEFAULT_OPTIONS])
@pytest.mark.cmd
@patch('pootle_app.management.commands.update_stores.FSPlugin')
def test_update_stores_tp(plugin_mock):
"""Site wide update_stores"""
command = Command()
tp = PropertyMock()
tp.configure_mock(
**{'pootle_path': 'FOO',
'project': 23})
command.handle_translation_project(tp, **DEFAULT_OPTIONS)
assert (
list(plugin_mock.return_value.add.call_args)
== [(), {'pootle_path': 'FOO*', 'update': 'pootle'}])
assert (
list(plugin_mock.return_value.rm.call_args)
== [(), {'pootle_path': 'FOO*', 'update': 'pootle'}])
assert (
list(plugin_mock.return_value.resolve.call_args)
== [(), {'pootle_path': 'FOO*', 'merge': True}])
assert (
list(plugin_mock.return_value.sync.call_args)
== [(), {'pootle_path': 'FOO*', 'update': 'pootle'}])
assert list(plugin_mock.call_args) == [(23,), {}]
@pytest.mark.cmd
@pytest.mark.django_db
def test_update_stores_non_existent_lang_or_proj():
with pytest.raises(CommandError):
call_command("update_stores", "--project", "non_existent_project")
with pytest.raises(CommandError):
call_command("update_stores", "--language", "non_existent_language")
| 3,451
|
Python
|
.py
| 89
| 33.258427
| 83
| 0.638158
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,041
|
update_data.py
|
translate_pootle/tests/commands/update_data.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import pytest
from django.core.management import call_command
@pytest.mark.cmd
@pytest.mark.django_db
def test_update_data_noargs(store0):
"""Site wide update_data"""
total_words = store0.data.total_words
critical_checks = store0.data.critical_checks
store0.data.total_words = 0
store0.data.critical_checks = 0
store0.data.save()
call_command("update_data")
store0.data.refresh_from_db()
assert store0.data.total_words == total_words
assert store0.data.critical_checks == critical_checks
@pytest.mark.cmd
@pytest.mark.django_db
def test_update_data_project(store0):
"""Site wide update_data"""
total_words = store0.data.total_words
critical_checks = store0.data.critical_checks
store0.data.total_words = 0
store0.data.critical_checks = 0
store0.data.save()
call_command(
"update_data",
"--project",
store0.translation_project.project.code)
store0.data.refresh_from_db()
assert store0.data.total_words == total_words
assert store0.data.critical_checks == critical_checks
@pytest.mark.cmd
@pytest.mark.django_db
def test_update_data_language(store0):
"""Site wide update_data"""
total_words = store0.data.total_words
critical_checks = store0.data.critical_checks
store0.data.total_words = 0
store0.data.critical_checks = 0
store0.data.save()
call_command(
"update_data",
"--language",
store0.translation_project.language.code)
store0.data.refresh_from_db()
assert store0.data.total_words == total_words
assert store0.data.critical_checks == critical_checks
@pytest.mark.cmd
@pytest.mark.django_db
def test_update_data_store(store0):
"""Site wide update_data"""
total_words = store0.data.total_words
critical_checks = store0.data.critical_checks
store0.data.total_words = 0
store0.data.critical_checks = 0
store0.data.save()
call_command(
"update_data",
"--store",
store0.pootle_path)
store0.data.refresh_from_db()
assert store0.data.total_words == total_words
assert store0.data.critical_checks == critical_checks
| 2,429
|
Python
|
.py
| 70
| 30.242857
| 77
| 0.716901
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,042
|
export.py
|
translate_pootle/tests/commands/export.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import os
import pytest
from django.core.management import call_command
from django.core.management.base import CommandError
from pootle.core.delegate import revision
@pytest.mark.cmd
@pytest.mark.django_db
def test_export_noargs(capfd, export_dir, cd_export_dir):
"""Export whole site"""
call_command('export')
out, err = capfd.readouterr()
assert 'Created project0-language0.zip' in out
@pytest.mark.cmd
@pytest.mark.django_db
def test_export_project(capfd, export_dir, cd_export_dir):
"""Export a project"""
call_command('export', '--project=project0')
out, err = capfd.readouterr()
assert 'project0.zip' in out
@pytest.mark.cmd
@pytest.mark.django_db
def test_export_project_and_lang(capfd, export_dir, cd_export_dir):
"""Export a project TP"""
call_command('export', '--project=project0', '--language=language0')
out, err = capfd.readouterr()
assert 'project0-language0.zip' in out
@pytest.mark.cmd
@pytest.mark.django_db
def test_export_language(capfd, export_dir, cd_export_dir):
"""Export a language"""
call_command('export', '--language=language0')
out, err = capfd.readouterr()
assert 'language0.zip' in out
assert 'language1.zip' not in out
@pytest.mark.cmd
@pytest.mark.django_db
def test_export_path(capfd, export_dir, cd_export_dir):
"""Export a path
Testing variants of lang, TP, single PO file and whole site.
"""
call_command('export', '--path=/language0')
out, err = capfd.readouterr()
assert 'language0.zip' in out
assert 'language1.zip' not in out
call_command('export', '--path=/language0/project0')
out, err = capfd.readouterr()
assert 'language0-project0.zip' in out
call_command('export', '--path=/language0/project0/store0.po')
out, err = capfd.readouterr()
assert 'store0.po' in out
call_command('export', '--path=/')
out, err = capfd.readouterr()
assert 'export.zip' in out
@pytest.mark.cmd
@pytest.mark.django_db
def test_export_path_unknown():
"""Export an unknown path"""
with pytest.raises(CommandError) as e:
call_command('export', '--path=/af/unknown')
assert "Could not find store matching '/af/unknown'" in str(e)
@pytest.mark.cmd
@pytest.mark.django_db
def test_export_tmx_tp(capfd, tp0, media_test_dir):
"""Export a tp"""
lang_code = tp0.language.code
prj_code = tp0.project.code
call_command('export', '--tmx', '--project=%s' % prj_code,
'--language=%s' % lang_code)
out, err = capfd.readouterr()
rev = revision.get(tp0.__class__)(tp0.directory).get(key="stats")
filename = '%s.%s.%s.tmx.zip' % (
tp0.project.code,
tp0.language.code, rev[:10])
assert os.path.join(lang_code, filename) in out
call_command('export', '--tmx', '--project=%s' % prj_code,
'--language=%s' % lang_code)
out, err = capfd.readouterr()
assert 'Translation project (%s) has not been changed' % tp0 in out
@pytest.mark.cmd
@pytest.mark.django_db
def test_export_tmx_with_wrong_options(capfd):
with pytest.raises(CommandError) as e:
call_command('export', '--tmx', '--path=/language0/project0/store0.po')
assert "--path: not allowed with argument --tmx" in str(e)
@pytest.mark.cmd
@pytest.mark.django_db
def test_export_tmx_tp_rotate(capfd, tp0, project1, media_test_dir):
"""Export a tp"""
lang_code = tp0.language.code
prj_code = tp0.project.code
tp1 = project1.translationproject_set.get(language__code=lang_code)
export_dir = os.path.join(media_test_dir, 'offline_tm')
call_command('export', '--tmx', '--project=%s' % prj_code,
'--language=%s' % lang_code)
out, err = capfd.readouterr()
def get_filename(tp):
rev = revision.get(tp.__class__)(tp.directory).get(key="stats")
filename = '%s.%s.%s.tmx.zip' % (
tp.project.code,
tp.language.code, rev[:10])
return os.path.join(lang_code, filename)
filename_1 = get_filename(tp0)
assert '%s" has been saved' % filename_1 in out
assert os.path.exists(os.path.join(export_dir, filename_1))
unit = tp0.stores.first().units.first()
unit.target_f = unit.target_f + ' CHANGED'
unit.save()
call_command('export', '--tmx', '--project=%s' % prj_code,
'--language=%s' % lang_code)
out, err = capfd.readouterr()
filename_2 = get_filename(tp0)
assert '%s" has been saved' % filename_2 in out
assert os.path.exists(os.path.join(export_dir, filename_2))
assert os.path.exists(os.path.join(export_dir, filename_1))
unit = tp0.stores.first().units.first()
unit.target_f = unit.target_f + ' CHANGED'
unit.save()
call_command('export', '--tmx', '--rotate', '--project=%s' % prj_code,
'--language=%s' % lang_code)
out, err = capfd.readouterr()
filename_3 = get_filename(tp0)
assert '%s" has been saved' % filename_3 in out
assert '%s" has been removed' % filename_1 in out
assert '%s" has been removed' % filename_2 not in out
assert not os.path.exists(os.path.join(export_dir, filename_1))
assert os.path.exists(os.path.join(export_dir, filename_2))
assert os.path.exists(os.path.join(export_dir, filename_3))
call_command('export', '--tmx', '--rotate',
'--project=%s' % tp1.project.code,
'--language=%s' % tp1.language.code)
out, err = capfd.readouterr()
filename_for_tp1 = get_filename(tp1)
assert '%s" has been saved' % filename_for_tp1 in out
assert os.path.exists(os.path.join(export_dir, filename_for_tp1))
assert os.path.exists(os.path.join(export_dir, filename_2))
assert os.path.exists(os.path.join(export_dir, filename_3))
| 6,032
|
Python
|
.py
| 143
| 37.090909
| 79
| 0.667805
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,043
|
find_duplicate_emails.py
|
translate_pootle/tests/commands/find_duplicate_emails.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import pytest
from django.contrib.auth import get_user_model
from django.core.management import call_command
@pytest.mark.cmd
@pytest.mark.django_db
def test_find_duplicate_emails_nodups(capfd, no_extra_users):
"""No duplicates found.
Standard users shouldn't flag any error.
"""
call_command('find_duplicate_emails')
out, err = capfd.readouterr()
assert "There are no accounts with duplicate emails" in out
@pytest.mark.cmd
@pytest.mark.django_db
def test_find_duplicate_emails_noemails(capfd, member, member2):
"""User have no email set."""
# this only works if there are more than one user with no email
get_user_model().objects.create(username="memberX")
get_user_model().objects.create(username="memberY")
call_command('find_duplicate_emails')
out, err = capfd.readouterr()
assert "The following users have no email set" in out
assert "memberX " in out
assert "memberY " in out
@pytest.mark.cmd
@pytest.mark.django_db
def test_find_duplicate_emails_withdups(capfd, member_with_email,
member2_with_email):
"""Find duplicate emails for removal where we have dups.
Standard users shouldn't flag any error.
"""
member2_with_email.email = member_with_email.email
member2_with_email.save()
call_command('find_duplicate_emails')
out, err = capfd.readouterr()
assert "The following users have the email: member_with_email@this.test" in out
assert "member_with_email" in out
assert "member2_with_email" in out
| 1,831
|
Python
|
.py
| 45
| 36.355556
| 83
| 0.725225
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,044
|
pootle_runner.py
|
translate_pootle/tests/commands/pootle_runner.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import os
from subprocess import call
import pytest
pytestmark = pytest.mark.skipif(call(['which', 'pootle']) != 0,
reason='not installed via setup.py')
@pytest.mark.cmd
def test_pootle_noargs(capfd):
"""Pootle no args should give help"""
call(['pootle'])
out, err = capfd.readouterr()
# Expected:
# Type 'pootle help <subcommand>'
# but 'pootle' is 'pootle-script.py' on Windows
assert "Type 'pootle" in out
assert " help <subcommand>'" in out
@pytest.mark.cmd
def test_pootle_version(capfd):
"""Display Pootle version info"""
call(['pootle', '--version'])
out, err = capfd.readouterr()
assert 'Pootle' in err
assert 'Django' in err
assert 'Translate Toolkit' in err
@pytest.mark.cmd
def test_pootle_init(capfd):
"""pootle init --help"""
call(['pootle', 'init', '--help'])
out, err = capfd.readouterr()
assert "--db" in out
@pytest.mark.cmd
def test_pootle_init_db_sqlite(capsys, tmpdir):
"""pootle init --help"""
test_conf_file = tmpdir.join("pootle.conf")
assert not os.path.exists(str(test_conf_file))
call(['pootle', 'init', '--db=sqlite', '--config=%s' % test_conf_file])
assert os.path.exists(str(test_conf_file))
| 1,534
|
Python
|
.py
| 43
| 31.511628
| 77
| 0.669371
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,045
|
minus_minus_help.py
|
translate_pootle/tests/commands/minus_minus_help.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import pytest
from django.core.management import call_command, get_commands
CORE_APPS_WITH_COMMANDS = (
'accounts', 'pootle_app', 'import_export', 'virtualfolder',
)
@pytest.mark.cmd
@pytest.mark.django_db
@pytest.mark.parametrize("command,app", [
(command, app)
for command, app in get_commands().iteritems()
if app.startswith('pootle_') or app in CORE_APPS_WITH_COMMANDS
])
def test_initdb_help(capfd, command, app):
"""Catch any simple command issues"""
print("Command: %s, App: %s" % (command, app))
with pytest.raises(SystemExit):
call_command(command, '--help')
out, err = capfd.readouterr()
assert '--help' in out
| 945
|
Python
|
.py
| 26
| 33.461538
| 77
| 0.714442
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,046
|
list_projects.py
|
translate_pootle/tests/commands/list_projects.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import pytest
from django.core.management import call_command
@pytest.mark.cmd
@pytest.mark.django_db
def test_list_projects_tutorial(capfd):
"""List site wide projects"""
call_command('list_projects')
out, err = capfd.readouterr()
assert 'project0' in out
assert 'project1' in out
@pytest.mark.cmd
@pytest.mark.django_db
def test_list_projects_modified_since(capfd):
"""Projects modified since a revision"""
call_command('list_projects', '--modified-since=5')
out, err = capfd.readouterr()
assert 'project0' in out
assert 'project1' in out
| 862
|
Python
|
.py
| 25
| 31.64
| 77
| 0.738869
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,047
|
list_serializers.py
|
translate_pootle/tests/commands/list_serializers.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from collections import OrderedDict
import pytest
from django.core.management import call_command
from django.core.management.base import CommandError
from pootle.core.delegate import serializers, deserializers
from pootle.core.plugin import provider
from pootle_project.models import Project
class EGSerializer1(object):
pass
class EGSerializer2(object):
pass
class EGDeserializer1(object):
pass
class EGDeserializer2(object):
pass
def serializer_provider_factory(sender=None):
@provider(serializers, sender=sender)
def serializer_provider(**kwargs):
return OrderedDict(
(("serializer1", EGSerializer1),
("serializer2", EGSerializer2)))
return serializer_provider
def deserializer_provider_factory(sender=None):
@provider(deserializers, sender=sender)
def deserializer_provider(**kwargs):
return OrderedDict(
(("deserializer1", EGDeserializer1),
("deserializer2", EGDeserializer2)))
return deserializer_provider
def _test_serializer_list(out, err, model=None):
NO_SERIALS = "There are no serializers set up on your system"
serials = serializers.gather(model)
expected = []
if not serials.keys():
expected.append(NO_SERIALS)
if serials.keys():
heading = "Serializers"
expected.append("\n%s" % heading)
expected.append("-" * len(heading))
for name, klass in serials.items():
expected.append("{!s: <30} {!s: <50} ".format(name, klass))
assert out == "%s\n" % ("\n".join(expected))
def _test_deserializer_list(out, err, model=None):
NO_DESERIALS = "There are no deserializers set up on your system"
deserials = deserializers.gather(model)
expected = []
if not deserials.keys():
expected.append(NO_DESERIALS)
if deserials.keys():
heading = "Deserializers"
expected.append("\n%s" % heading)
expected.append("-" * len(heading))
for name, klass in deserials.items():
expected.append("{!s: <30} {!s: <50} ".format(name, klass))
assert out == "%s\n" % ("\n".join(expected))
@pytest.mark.cmd
@pytest.mark.django_db
def test_cmd_list_serializers(capsys):
# tests with no de/serializers set up
call_command("list_serializers")
out, err = capsys.readouterr()
_test_serializer_list(out, err)
# set up some serializers
serial_provider = serializer_provider_factory()
call_command("list_serializers")
out, err = capsys.readouterr()
_test_serializer_list(out, err)
serializers.disconnect(serial_provider)
# set up some deserializers
deserial_provider = deserializer_provider_factory()
call_command("list_serializers")
out, err = capsys.readouterr()
_test_serializer_list(out, err)
# empty again
deserializers.disconnect(deserial_provider)
call_command("list_serializers")
out, err = capsys.readouterr()
_test_serializer_list(out, err)
# with both set up
deserial_provider = deserializer_provider_factory()
serial_provider = serializer_provider_factory()
call_command("list_serializers")
out, err = capsys.readouterr()
_test_serializer_list(out, err)
serializers.disconnect(serial_provider)
deserializers.disconnect(deserial_provider)
@pytest.mark.cmd
@pytest.mark.django_db
def test_cmd_list_serializers_for_model(capsys):
# tests with no de/serializers set up
call_command("list_serializers", "-m", "pootle_project.project")
out, err = capsys.readouterr()
_test_serializer_list(out, err, Project)
# set up some serializers
serial_provider = serializer_provider_factory(Project)
call_command("list_serializers", "-m", "pootle_project.project")
out, err = capsys.readouterr()
_test_serializer_list(out, err, Project)
call_command("list_serializers")
out, err = capsys.readouterr()
_test_serializer_list(out, err)
serializers.disconnect(serial_provider)
# set up some deserializers
deserial_provider = deserializer_provider_factory(Project)
call_command("list_serializers", "-m", "pootle_project.project")
out, err = capsys.readouterr()
_test_serializer_list(out, err, Project)
call_command("list_serializers")
out, err = capsys.readouterr()
_test_serializer_list(out, err)
# empty again
deserializers.disconnect(deserial_provider)
call_command("list_serializers", "-m", "pootle_project.project")
out, err = capsys.readouterr()
_test_serializer_list(out, err, Project)
call_command("list_serializers")
out, err = capsys.readouterr()
_test_serializer_list(out, err)
# with both set up
deserial_provider = deserializer_provider_factory(Project)
serial_provider = serializer_provider_factory(Project)
call_command("list_serializers", "-m", "pootle_project.project")
out, err = capsys.readouterr()
_test_serializer_list(out, err, Project)
call_command("list_serializers")
out, err = capsys.readouterr()
_test_serializer_list(out, err)
serializers.disconnect(serial_provider)
deserializers.disconnect(deserial_provider)
@pytest.mark.cmd
@pytest.mark.django_db
def test_cmd_list_deserializers(capsys):
# tests with no de/deserializers set up
call_command("list_serializers", "-d")
out, err = capsys.readouterr()
_test_deserializer_list(out, err)
# set up some deserializers
deserial_provider = deserializer_provider_factory()
call_command("list_serializers", "-d")
out, err = capsys.readouterr()
_test_deserializer_list(out, err)
deserializers.disconnect(deserial_provider)
# set up some deserializers
deserial_provider = deserializer_provider_factory()
call_command("list_serializers", "-d")
out, err = capsys.readouterr()
_test_deserializer_list(out, err)
# empty again
deserializers.disconnect(deserial_provider)
call_command("list_serializers", "-d")
out, err = capsys.readouterr()
_test_deserializer_list(out, err)
# with both set up
deserial_provider = deserializer_provider_factory()
deserial_provider = deserializer_provider_factory()
call_command("list_serializers", "-d")
out, err = capsys.readouterr()
_test_deserializer_list(out, err)
deserializers.disconnect(deserial_provider)
deserializers.disconnect(deserial_provider)
@pytest.mark.cmd
@pytest.mark.django_db
def test_cmd_list_deserializers_for_model(capsys):
# tests with no de/deserializers set up
call_command("list_serializers", "-d", "-m", "pootle_project.project")
out, err = capsys.readouterr()
_test_deserializer_list(out, err, Project)
# set up some deserializers
deserial_provider = deserializer_provider_factory(Project)
call_command("list_serializers", "-d", "-m", "pootle_project.project")
out, err = capsys.readouterr()
_test_deserializer_list(out, err, Project)
call_command("list_serializers", "-d")
out, err = capsys.readouterr()
_test_deserializer_list(out, err)
deserializers.disconnect(deserial_provider)
# set up some deserializers
deserial_provider = deserializer_provider_factory(Project)
call_command("list_serializers", "-d", "-m", "pootle_project.project")
out, err = capsys.readouterr()
_test_deserializer_list(out, err, Project)
call_command("list_serializers", "-d")
out, err = capsys.readouterr()
_test_deserializer_list(out, err)
# empty again
deserializers.disconnect(deserial_provider)
call_command("list_serializers", "-d", "-m", "pootle_project.project")
out, err = capsys.readouterr()
_test_deserializer_list(out, err, Project)
call_command("list_serializers", "-d")
out, err = capsys.readouterr()
_test_deserializer_list(out, err)
# with both set up
deserial_provider = deserializer_provider_factory(Project)
deserial_provider = deserializer_provider_factory(Project)
call_command("list_serializers", "-d", "-m", "pootle_project.project")
out, err = capsys.readouterr()
_test_deserializer_list(out, err, Project)
call_command("list_serializers", "-d")
out, err = capsys.readouterr()
_test_deserializer_list(out, err)
deserializers.disconnect(deserial_provider)
deserializers.disconnect(deserial_provider)
@pytest.mark.cmd
@pytest.mark.django_db
def test_cmd_list_serializers_bad_models(capsys):
with pytest.raises(CommandError):
call_command("list_serializers", "-m", "foo")
with pytest.raises(CommandError):
call_command("list_serializers", "-m", "foo.bar")
| 8,902
|
Python
|
.py
| 217
| 35.921659
| 77
| 0.711866
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,048
|
update_tmserver.py
|
translate_pootle/tests/commands/update_tmserver.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import os
import sys
import pytest
from django.core.management import call_command
from django.core.management.base import CommandError
@pytest.mark.cmd
@pytest.mark.django_db
def test_update_tmserver_nosetting(capfd, po_directory, tp0, settings):
"""We need configured TM for anything to work"""
settings.POOTLE_TM_SERVER = None
with pytest.raises(CommandError) as e:
call_command('update_tmserver')
assert "POOTLE_TM_SERVER setting is missing." in str(e)
@pytest.mark.cmd
@pytest.mark.django_db
def __test_update_tmserver_noargs(capfd, tp0, settings):
"""Load TM from the database"""
from pootle_store.models import Unit
units_qs = (
Unit.objects
.exclude(target_f__isnull=True)
.exclude(target_f__exact=''))
settings.POOTLE_TM_SERVER = {
'local': {
'ENGINE': 'pootle.core.search.backends.ElasticSearchBackend',
'HOST': 'elasticsearch',
'PORT': 9200,
'INDEX_NAME': 'translations',
}
}
call_command('update_tmserver')
out, err = capfd.readouterr()
assert "Last indexed revision = -1" in out
assert ("%d translations to index" % units_qs.count()) in out
@pytest.mark.cmd
@pytest.mark.django_db
def test_update_tmserver_bad_tm(capfd, settings):
"""Non-existant TM in the server"""
settings.POOTLE_TM_SERVER = {
'local': {
'ENGINE': 'pootle.core.search.backends.ElasticSearchBackend',
'HOST': 'elasticsearch',
'PORT': 9200,
'INDEX_NAME': 'translations',
}
}
with pytest.raises(CommandError) as e:
call_command('update_tmserver', '--tm=i_dont_exist')
assert "Translation Memory 'i_dont_exist' is not defined" in str(e)
@pytest.mark.cmd
@pytest.mark.django_db
def test_update_tmserver_files_no_displayname(capfd, settings, tmpdir):
"""File based TM needs a display-name"""
settings.POOTLE_TM_SERVER = {
'external': {
'ENGINE': 'pootle.core.search.backends.ElasticSearchBackend',
'HOST': 'elasticsearch',
'PORT': 9200,
'INDEX_NAME': 'translations-external',
}
}
with pytest.raises(CommandError) as e:
call_command('update_tmserver', '--tm=external', 'fake_file.po')
assert "--display-name" in str(e)
@pytest.mark.cmd
@pytest.mark.django_db
@pytest.mark.skipif(sys.platform == 'win32',
reason="No Elasticsearch in Windows testing")
def test_update_tmserver_files(capfd, settings, tmpdir):
"""Load TM from files"""
settings.POOTLE_TM_SERVER = {
'external': {
'ENGINE': 'pootle.core.search.backends.ElasticSearchBackend',
'HOST': 'elasticsearch',
'PORT': 9200,
'INDEX_NAME': 'translations-external',
}
}
p = tmpdir.mkdir("tmserver_files").join("tutorial.po")
p.write("""msgid "rest"
msgstr "test"
""")
# First try without a --target-language (headers in above PO would sort
# this out)
with pytest.raises(CommandError) as e:
call_command('update_tmserver', '--tm=external', '--display-name=Test',
os.path.join(p.dirname, p.basename))
assert "Unable to determine target language" in str(e)
# Now set the --target-language
call_command('update_tmserver', '--tm=external', '--display-name=Test',
'--target-language=af', os.path.join(p.dirname, p.basename))
out, err = capfd.readouterr()
assert "1 translations to index" in out
| 3,844
|
Python
|
.py
| 100
| 31.91
| 79
| 0.649839
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,049
|
initdb.py
|
translate_pootle/tests/commands/initdb.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from mock import MagicMock, patch
import pytest
from django.core.management import call_command
from pootle_app.management.commands import SkipChecksMixin
from pootle_app.management.commands.initdb import Command
@pytest.mark.cmd
def test_cmd_initdb_skip_checks():
assert issubclass(Command, SkipChecksMixin)
@pytest.mark.cmd
@patch('pootle_app.management.commands.initdb.InitDB')
def test_cmd_initdb_noprojects(init_mock):
"""Initialise the database with initdb
"""
stdout = MagicMock()
call_command('initdb', '--no-projects', stdout=stdout)
assert (
[list(l) for l in stdout.write.call_args_list]
== [[('Populating the database.\n',), {}],
[('Successfully populated the database.\n',), {}],
[('To create an admin user, use the `pootle createsuperuser` '
'command.\n',),
{}]])
assert (
list(init_mock.call_args)
== [(), {}])
assert (
list(init_mock.return_value.init_db.call_args)
== [(False,), {}])
@pytest.mark.cmd
@patch('pootle_app.management.commands.initdb.InitDB')
def test_cmd_initdb_projects(init_mock):
"""Initialise the database with initdb
"""
stdout = MagicMock()
call_command('initdb', stdout=stdout)
assert (
[list(l) for l in stdout.write.call_args_list]
== [[('Populating the database.\n',), {}],
[('Successfully populated the database.\n',), {}],
[('To create an admin user, use the `pootle createsuperuser` '
'command.\n',),
{}]])
assert (
list(init_mock.call_args)
== [(), {}])
assert (
list(init_mock.return_value.init_db.call_args)
== [(True,), {}])
| 2,016
|
Python
|
.py
| 55
| 30.781818
| 77
| 0.639159
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,050
|
merge_user.py
|
translate_pootle/tests/commands/merge_user.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from mock import MagicMock, patch
import pytest
from django.core.management import call_command
from django.core.management.base import CommandError
@pytest.mark.cmd
def test_cmd_merge_user_nousers():
with pytest.raises(CommandError) as e:
call_command('merge_user')
assert "too few arguments" in str(e)
with pytest.raises(CommandError) as e:
call_command('merge_user', 'memberX')
assert "too few arguments" in str(e)
@pytest.mark.cmd
@patch('accounts.management.commands.merge_user.Command.get_user')
@patch('accounts.management.commands.merge_user.utils')
def test_cmd_merge_user(utils_mock, get_user_mock):
user_mock = MagicMock()
stdout = MagicMock()
def _get_user(**kwargs):
user_mock.return_value.username = kwargs['username']
return user_mock(**kwargs)
get_user_mock.side_effect = _get_user
call_command('merge_user', 'memberX', 'memberY', stdout=stdout)
assert (
[list(l) for l in get_user_mock.call_args_list]
== [[(), {'username': u'memberX'}],
[(), {'username': u'memberY'}]])
assert (
[list(l) for l in user_mock.call_args_list]
== [[(), {'username': u'memberX'}],
[(), {'username': u'memberY'}]])
assert (
list(utils_mock.UserMerger.call_args)
== [(user_mock.return_value, user_mock.return_value), {}])
assert (
list(user_mock.return_value.delete.call_args)
== [(), {}])
assert (
[list(l) for l in stdout.write.call_args_list]
== [[('Deleting user: memberY...\n',), {}],
[('User deleted: memberY\n',), {}]])
@pytest.mark.cmd
@patch('accounts.management.commands.merge_user.Command.get_user')
@patch('accounts.management.commands.merge_user.utils')
def test_cmd_merge_user_no_delete(utils_mock, get_user_mock):
user_mock = MagicMock()
stdout = MagicMock()
def _get_user(**kwargs):
user_mock.return_value.username = kwargs['username']
return user_mock(**kwargs)
get_user_mock.side_effect = _get_user
call_command(
'merge_user', 'memberX', 'memberY', '--no-delete', stdout=stdout)
assert (
[list(l) for l in get_user_mock.call_args_list]
== [[(), {'username': u'memberX'}],
[(), {'username': u'memberY'}]])
assert (
[list(l) for l in user_mock.call_args_list]
== [[(), {'username': u'memberX'}],
[(), {'username': u'memberY'}]])
assert (
list(utils_mock.UserMerger.call_args)
== [(user_mock.return_value, user_mock.return_value), {}])
assert not user_mock.return_value.delete.called
assert not stdout.write.called
| 2,953
|
Python
|
.py
| 73
| 34.60274
| 77
| 0.640265
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,051
|
list_languages.py
|
translate_pootle/tests/commands/list_languages.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import pytest
from django.core.management import call_command
@pytest.mark.cmd
@pytest.mark.django_db
def test_list_languages(capfd):
"""Full site list of active languages"""
call_command('list_languages')
out, err = capfd.readouterr()
assert 'language0' in out
assert 'language1' in out
@pytest.mark.cmd
@pytest.mark.django_db
def test_list_languages_project(capfd):
"""Languages on a specific project"""
call_command('list_languages', '--project=project0')
out, err = capfd.readouterr()
assert 'language0' in out
assert 'language1' in out
assert 'en' not in out
@pytest.mark.cmd
@pytest.mark.django_db
def test_list_languages_modified_since(capfd):
"""Languages modified since a revision"""
call_command('list_languages', '--modified-since=%d' % (3))
out, err = capfd.readouterr()
assert 'language0' in out
assert 'language1' in out
| 1,182
|
Python
|
.py
| 34
| 31.647059
| 77
| 0.728947
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,052
|
purge_user.py
|
translate_pootle/tests/commands/purge_user.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from mock import patch
import pytest
from django.core.management import call_command
from django.core.management.base import CommandError
@pytest.mark.cmd
def test_cmd_purge_user_nouser():
with pytest.raises(CommandError) as e:
call_command('purge_user')
assert "too few arguments" in str(e)
@pytest.mark.cmd
@patch('accounts.management.commands.purge_user.Command.get_user')
def test_cmd_purge_user(get_user_mock):
call_command('purge_user', 'evil_member')
assert (
list(get_user_mock.call_args)
== [(u'evil_member',), {}])
assert (
list(get_user_mock.return_value.delete.call_args)
== [(), {'purge': True}])
get_user_mock.reset_mock()
call_command('purge_user', 'evil_member', 'eviler_member')
assert (
[list(l) for l in get_user_mock.call_args_list]
== [[(u'evil_member',), {}], [(u'eviler_member',), {}]])
assert (
list(get_user_mock.return_value.delete.call_args)
== [(), {'purge': True}])
| 1,287
|
Python
|
.py
| 34
| 33.411765
| 77
| 0.674437
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,053
|
revision.py
|
translate_pootle/tests/commands/revision.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import pytest
from django.core.management import call_command
@pytest.mark.cmd
@pytest.mark.django_db
def test_revision(capfd):
"""Get current revision."""
call_command('revision')
out, err = capfd.readouterr()
assert out.rstrip().isnumeric()
@pytest.mark.cmd
@pytest.mark.django_db
def test_revision_restore(capfd):
"""Restore redis revision from DB."""
call_command('revision', '--restore')
out, err = capfd.readouterr()
assert out.rstrip().isnumeric()
| 768
|
Python
|
.py
| 23
| 30.73913
| 77
| 0.734777
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,054
|
flush_cache.py
|
translate_pootle/tests/commands/flush_cache.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import pytest
from django.core.management import call_command
from django.core.management.base import CommandError
@pytest.mark.cmd
@pytest.mark.django_db
def test_flush_cache(capfd):
call_command('flush_cache', '--rqdata')
out, err = capfd.readouterr()
assert "Flushing cache..." in out
assert "RQ data removed." in out
assert "Max unit revision restored." in out
@pytest.mark.cmd
@pytest.mark.django_db
def test_flush_cache_no_options():
with pytest.raises(CommandError) as e:
call_command('flush_cache')
assert "No options were provided." in str(e)
| 869
|
Python
|
.py
| 24
| 33.458333
| 77
| 0.746126
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,055
|
update_user_email.py
|
translate_pootle/tests/commands/update_user_email.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import pytest
from django.core.management import call_command
from django.core.management.base import CommandError
@pytest.mark.cmd
@pytest.mark.django_db
def test_update_user_email_nouser():
with pytest.raises(CommandError) as e:
call_command('update_user_email')
assert "too few arguments" in str(e)
@pytest.mark.cmd
@pytest.mark.django_db
def test_update_user_email_noemail_supplied(member):
with pytest.raises(CommandError) as e:
call_command('update_user_email', 'member')
assert "too few arguments" in str(e)
@pytest.mark.cmd
@pytest.mark.django_db
def test_update_user_email_unkonwnuser():
with pytest.raises(CommandError) as e:
call_command('update_user_email', 'not_a_user', 'email@address')
assert "User not_a_user does not exist" in str(e)
@pytest.mark.cmd
@pytest.mark.django_db
def test_update_user_email_new_email(capfd, member):
call_command('update_user_email', 'member', 'new_email@address.com')
out, err = capfd.readouterr()
assert "Email updated: member, new_email@address.com" in out
@pytest.mark.cmd
@pytest.mark.django_db
def test_update_user_email_bad_email(member):
with pytest.raises(CommandError) as e:
call_command('update_user_email', 'member', 'new_email@address')
assert "Enter a valid email address." in str(e)
| 1,605
|
Python
|
.py
| 40
| 36.925
| 77
| 0.743722
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,056
|
refresh_scores.py
|
translate_pootle/tests/commands/refresh_scores.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from mock import patch
import pytest
from django.core.management import call_command
from pootle_app.management.commands.refresh_scores import Command
from pootle_translationproject.models import TranslationProject
DEFAULT_OPTIONS = {
'reset': False,
'users': None,
'settings': None,
'pythonpath': None,
'verbosity': 1,
'traceback': False,
u'skip_checks': True,
'no_rq': False,
'atomic': 'tp',
'noinput': False,
'no_color': False}
@pytest.mark.cmd
@patch('pootle_app.management.commands.refresh_scores.get_user_model')
@patch('pootle_app.management.commands.refresh_scores.Command.get_users')
@patch('pootle_app.management.commands.refresh_scores.score_updater')
def test_cmd_refresh_scores_recalculate(updater_mock, users_mock, user_mock):
"""Recalculate scores."""
user_mock.return_value = 7
users_mock.return_value = 23
call_command('refresh_scores')
assert (
list(users_mock.call_args)
== [(), DEFAULT_OPTIONS])
assert (
list(updater_mock.get.call_args)
== [(7,), {}])
assert (
list(updater_mock.get.return_value.call_args)
== [(), {}])
assert (
list(updater_mock.get.return_value.return_value.refresh_scores.call_args)
== [(23,), {}])
@pytest.mark.cmd
@patch('pootle_app.management.commands.refresh_scores.get_user_model')
@patch('pootle_app.management.commands.refresh_scores.Command.get_users')
@patch('pootle_app.management.commands.refresh_scores.score_updater')
def test_cmd_refresh_scores_recalculate_user(updater_mock, users_mock, user_mock):
"""Recalculate scores for given users."""
user_mock.return_value = 7
users_mock.return_value = 23
call_command('refresh_scores', '--user=member')
options = DEFAULT_OPTIONS.copy()
options["users"] = ["member"]
assert (
list(users_mock.call_args)
== [(), options])
assert (
list(updater_mock.get.call_args)
== [(7,), {}])
assert (
list(updater_mock.get.return_value.call_args)
== [(), {}])
assert (
list(updater_mock.get.return_value.return_value.refresh_scores.call_args)
== [(23,), {}])
@pytest.mark.cmd
@patch('pootle_app.management.commands.refresh_scores.get_user_model')
@patch('pootle_app.management.commands.refresh_scores.Command.get_users')
@patch('pootle_app.management.commands.refresh_scores.score_updater')
def test_cmd_refresh_scores_reset_user(updater_mock, users_mock, user_mock):
"""Set scores to zero for given users."""
user_mock.return_value = 7
users_mock.return_value = 23
call_command('refresh_scores', '--reset', '--user=member')
options = DEFAULT_OPTIONS.copy()
options["users"] = ["member"]
options["reset"] = True
assert (
list(users_mock.call_args)
== [(), options])
assert (
list(updater_mock.get.call_args)
== [(7,), {}])
assert (
list(updater_mock.get.return_value.call_args)
== [(), {'users': 23}])
assert (
list(updater_mock.get.return_value.return_value.clear.call_args)
== [(), {}])
@pytest.mark.cmd
@patch('pootle_app.management.commands.refresh_scores.get_user_model')
@patch('pootle_app.management.commands.refresh_scores.Command.get_users')
@patch('pootle_app.management.commands.refresh_scores.score_updater')
def test_cmd_refresh_scores_reset(updater_mock, users_mock, user_mock):
"""Set scores to zero."""
user_mock.return_value = 7
users_mock.return_value = 23
call_command('refresh_scores', '--reset')
options = DEFAULT_OPTIONS.copy()
options["reset"] = True
assert (
list(users_mock.call_args)
== [(), options])
assert (
list(updater_mock.get.call_args)
== [(7,), {}])
assert (
list(updater_mock.get.return_value.call_args)
== [(), {'users': 23}])
assert (
list(updater_mock.get.return_value.return_value.clear.call_args)
== [(), {}])
@pytest.mark.cmd
@patch('pootle_app.management.commands.PootleCommand.handle_all')
@patch('pootle_app.management.commands.refresh_scores.Command.check_projects')
def test_cmd_refresh_scores_project(projects_mock, command_mock):
"""Reset and set again scores for a project."""
call_command('refresh_scores', '--reset', '--project=project0')
options = DEFAULT_OPTIONS.copy()
options["reset"] = True
assert (
list(projects_mock.call_args)
== [([u'project0'],), {}])
assert (
list(command_mock.call_args)
== [(), options])
projects_mock.reset_mock()
command_mock.reset_mock()
call_command('refresh_scores', '--project=project0')
assert (
list(projects_mock.call_args)
== [([u'project0'],), {}])
assert (
list(command_mock.call_args)
== [(), DEFAULT_OPTIONS])
@pytest.mark.cmd
@patch('pootle_app.management.commands.PootleCommand.handle_all')
@patch('pootle_app.management.commands.refresh_scores.Command.check_languages')
def test_cmd_refresh_scores_language(languages_mock, command_mock):
"""Reset and set again scores for a language."""
call_command('refresh_scores', '--reset', '--language=language0')
assert (
list(languages_mock.call_args)
== [([u'language0'],), {}])
options = DEFAULT_OPTIONS.copy()
options["reset"] = True
assert (
list(command_mock.call_args)
== [(), options])
languages_mock.reset_mock()
command_mock.reset_mock()
call_command('refresh_scores', '--language=language0')
assert (
list(languages_mock.call_args)
== [([u'language0'],), {}])
assert (
list(command_mock.call_args)
== [(), DEFAULT_OPTIONS])
@pytest.mark.cmd
@patch('pootle_app.management.commands.PootleCommand.handle_all')
@patch('pootle_app.management.commands.refresh_scores.Command.check_projects')
@patch('pootle_app.management.commands.refresh_scores.Command.check_languages')
def test_cmd_refresh_scores_reset_tp(languages_mock, projects_mock, command_mock):
"""Reset and set again scores for a TP."""
call_command(
'refresh_scores',
'--reset',
'--language=language0',
'--project=project0')
assert (
list(languages_mock.call_args)
== [([u'language0'],), {}])
assert (
list(projects_mock.call_args)
== [([u'project0'],), {}])
options = DEFAULT_OPTIONS.copy()
options["reset"] = True
assert (
list(command_mock.call_args)
== [(), options])
languages_mock.reset_mock()
projects_mock.reset_mock()
command_mock.reset_mock()
call_command(
'refresh_scores',
'--language=language0',
'--project=project0')
assert (
list(languages_mock.call_args)
== [([u'language0'],), {}])
assert (
list(projects_mock.call_args)
== [([u'project0'],), {}])
assert (
list(command_mock.call_args)
== [(), DEFAULT_OPTIONS])
@pytest.mark.cmd
@patch('pootle_app.management.commands.PootleCommand.handle_all')
@patch('pootle_app.management.commands.refresh_scores.Command.check_languages')
def test_cmd_refresh_scores_user_language(languages_mock, command_mock):
"""Reset and set again scores for particular user in language."""
call_command(
'refresh_scores',
'--user=member',
'--language=language0')
options = DEFAULT_OPTIONS.copy()
options["users"] = ["member"]
assert (
list(languages_mock.call_args)
== [([u'language0'],), {}])
assert (
list(command_mock.call_args)
== [(), options])
languages_mock.reset_mock()
command_mock.reset_mock()
call_command(
'refresh_scores',
'--reset',
'--user=member',
'--language=language0')
options["reset"] = True
assert (
list(languages_mock.call_args)
== [([u'language0'],), {}])
assert (
list(command_mock.call_args)
== [(), options])
@pytest.mark.cmd
@patch('pootle_app.management.commands.PootleCommand.handle_all')
@patch('pootle_app.management.commands.refresh_scores.Command.check_projects')
def test_cmd_refresh_scores_user_project(projects_mock, command_mock):
"""Reset and set again scores for particular user in project."""
call_command(
'refresh_scores',
'--user=member',
'--project=project0')
options = DEFAULT_OPTIONS.copy()
options["users"] = ["member"]
assert (
list(projects_mock.call_args)
== [([u'project0'],), {}])
assert (
list(command_mock.call_args)
== [(), options])
projects_mock.reset_mock()
command_mock.reset_mock()
call_command(
'refresh_scores',
'--reset',
'--user=member',
'--project=project0')
options["reset"] = True
assert (
list(projects_mock.call_args)
== [([u'project0'],), {}])
assert (
list(command_mock.call_args)
== [(), options])
@pytest.mark.cmd
@patch('pootle_app.management.commands.PootleCommand.handle_all')
@patch('pootle_app.management.commands.refresh_scores.Command.check_languages')
@patch('pootle_app.management.commands.refresh_scores.Command.check_projects')
def test_cmd_refresh_scores_user_tp(projects_mock, languages_mock, command_mock):
"""Reset and set again scores for particular user in project."""
call_command(
'refresh_scores',
'--user=member',
'--language=language0',
'--project=project0')
options = DEFAULT_OPTIONS.copy()
options["users"] = ["member"]
assert (
list(projects_mock.call_args)
== [([u'project0'],), {}])
assert (
list(languages_mock.call_args)
== [([u'language0'],), {}])
assert (
list(command_mock.call_args)
== [(), options])
languages_mock.reset_mock()
projects_mock.reset_mock()
command_mock.reset_mock()
call_command(
'refresh_scores',
'--reset',
'--user=member',
'--language=language0',
'--project=project0')
options["reset"] = True
assert (
list(projects_mock.call_args)
== [([u'project0'],), {}])
assert (
list(languages_mock.call_args)
== [([u'language0'],), {}])
assert (
list(command_mock.call_args)
== [(), options])
@pytest.mark.cmd
@patch('pootle_app.management.commands.refresh_scores.get_user_model')
def test_cmd_refresh_scores_get_users(user_mock):
user_mock.configure_mock(
**{'return_value.objects.filter.return_value.values_list.return_value':
(1, 2, 3)})
command = Command()
assert command.get_users(users=None) is None
assert not user_mock.called
assert command.get_users(users="FOO") == [1, 2, 3]
assert (
list(user_mock.call_args)
== [(), {}])
user_filter = user_mock.return_value.objects.filter
assert (
list(user_filter.call_args)
== [(), {'username__in': 'FOO'}])
assert (
list(user_filter.return_value.values_list.call_args)
== [('pk',), {'flat': True}])
@pytest.mark.cmd
@patch('pootle_app.management.commands.refresh_scores.Command.get_users')
@patch('pootle_app.management.commands.refresh_scores.score_updater')
def test_cmd_refresh_scores_handle_all_stores(updater_mock, users_mock):
users_mock.return_value = 7
command = Command()
command.handle_all_stores("FOO", reset=False)
assert (
list(users_mock.call_args)
== [(), {'reset': False}])
assert (
list(updater_mock.get.call_args)
== [(TranslationProject,), {}])
assert (
list(updater_mock.get.return_value.call_args)
== [('FOO',), {}])
assert (
list(updater_mock.get.return_value.call_args)
== [('FOO',), {}])
assert (
list(updater_mock.get.return_value.return_value.refresh_scores.call_args)
== [(7,), {}])
command.handle_all_stores("FOO", reset=True)
assert (
list(users_mock.call_args)
== [(), {'reset': True}])
assert (
list(updater_mock.get.call_args)
== [(TranslationProject,), {}])
assert (
list(updater_mock.get.return_value.call_args)
== [('FOO',), {}])
assert (
list(updater_mock.get.return_value.call_args)
== [('FOO',), {}])
assert (
list(updater_mock.get.return_value.return_value.clear.call_args)
== [(7,), {}])
| 12,798
|
Python
|
.py
| 360
| 29.55
| 82
| 0.632449
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,057
|
test_checks.py
|
translate_pootle/tests/commands/test_checks.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import pytest
from django.core.management import call_command
from django.core.management.base import CommandError
from pootle_store.constants import TRANSLATED
from pootle_store.models import Unit
@pytest.mark.cmd
def test_test_checks_noargs():
"""No args should fail wanting either --unit or --source."""
with pytest.raises(CommandError) as e:
call_command('test_checks')
assert ("Either --unit or a pair of --source and "
"--target must be provided." in str(e))
@pytest.mark.cmd
@pytest.mark.django_db
def test_test_checks_unit_unkown():
"""Check a --unit that we won't have"""
with pytest.raises(CommandError) as e:
call_command('test_checks', '--unit=100000')
assert 'Unit matching query does not exist' in str(e)
@pytest.mark.cmd
@pytest.mark.django_db
def test_test_checks_unit(capfd):
"""Check a --unit"""
units = Unit.objects.filter(
state=TRANSLATED,
target_f__endswith="%s.")
call_command('test_checks', '--unit=%s' % units.first().id)
out, err = capfd.readouterr()
assert 'No errors found' in out
@pytest.mark.cmd
def test_test_checks_srctgt_missing_args():
"""Check a --source --target with incomplete options."""
with pytest.raises(CommandError) as e:
call_command('test_checks', '--source="files"')
assert 'Use a pair of --source and --target' in str(e)
with pytest.raises(CommandError) as e:
call_command('test_checks', '--target="leers"')
assert 'Use a pair of --source and --target' in str(e)
@pytest.mark.cmd
def test_test_checks_srctgt_pass(capfd):
"""Passing --source --target check."""
call_command('test_checks', '--source="Files"', '--target="Leers"')
out, err = capfd.readouterr()
assert 'No errors found' in out
@pytest.mark.cmd
def test_test_checks_srctgt_fail(capfd):
"""Failing --source --target check."""
call_command('test_checks', '--source="%s files"', '--target="%s leers"')
out, err = capfd.readouterr()
assert 'No errors found' in out
call_command('test_checks', '--source="%s files"', '--target="%d leers"')
out, err = capfd.readouterr()
assert 'Failing checks' in out
| 2,465
|
Python
|
.py
| 60
| 37.016667
| 77
| 0.686898
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,058
|
calculate_checks.py
|
translate_pootle/tests/commands/calculate_checks.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import pytest
from django.core.management import call_command
@pytest.mark.cmd
@pytest.mark.django_db
def test_calculate_checks_noargs(capfd, project0, project1):
# delete tps or this takes a long time
call_command('calculate_checks')
out, err = capfd.readouterr()
assert 'Running calculate_checks (noargs)' in out
@pytest.mark.cmd
@pytest.mark.django_db
def test_calculate_checks_printf(capfd, project0, project1):
# delete tps or this takes a long time
call_command('calculate_checks', '--check=printf')
out, err = capfd.readouterr()
assert 'Running calculate_checks (noargs)' in out
@pytest.mark.cmd
@pytest.mark.django_db
def test_calculate_checks_language(capfd, project1):
call_command('calculate_checks', '--language=language0')
out, err = capfd.readouterr()
assert 'Running calculate_checks for /language0/project0/' in out
| 1,159
|
Python
|
.py
| 29
| 37.172414
| 77
| 0.754902
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,059
|
schema.py
|
translate_pootle/tests/commands/schema.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import json
import pytest
from django.core.management import CommandError, call_command
from pootle.core.schema.base import SchemaTool
from pootle.core.schema.utils import get_current_db_type
from pootle.core.schema.dump import SchemaDump
@pytest.mark.cmd
@pytest.mark.django_db
def test_schema_supported_databases(capfd):
if get_current_db_type() != 'mysql':
with pytest.raises(CommandError):
call_command('schema')
return
call_command('schema')
out, err = capfd.readouterr()
assert '' == err
@pytest.mark.cmd
@pytest.mark.django_db
def test_app_schema_supported_databases(capfd):
if get_current_db_type() != 'mysql':
with pytest.raises(CommandError):
call_command('schema', 'app', 'pootle_store')
return
call_command('schema', 'app', 'pootle_store')
out, err = capfd.readouterr()
assert '' == err
@pytest.mark.cmd
@pytest.mark.django_db
def test_table_schema_supported_databases(capfd):
if get_current_db_type() != 'mysql':
with pytest.raises(CommandError):
call_command('schema', 'table', 'pootle_store_store')
return
call_command('schema', 'table', 'pootle_store_store')
out, err = capfd.readouterr()
assert '' == err
@pytest.mark.cmd
@pytest.mark.django_db
def test_schema(capfd):
if get_current_db_type() != 'mysql':
pytest.skip("unsupported database")
call_command('schema')
out, err = capfd.readouterr()
schema_tool = SchemaTool()
result = SchemaDump()
result.load(json.loads(out))
assert result.defaults == schema_tool.get_defaults()
@pytest.mark.cmd
@pytest.mark.django_db
def test_schema_tables(capfd):
if get_current_db_type() != 'mysql':
pytest.skip("unsupported database")
call_command('schema', '--tables')
out, err = capfd.readouterr()
schema_tool = SchemaTool()
result = SchemaDump()
result.load(json.loads(out))
assert schema_tool.get_tables() == result.tables
def _test_table_result(schema_tool, table_result, table_name):
assert (table_result.fields ==
schema_tool.get_table_fields(table_name))
assert (table_result.indices ==
schema_tool.get_table_indices(table_name))
assert (table_result.constraints ==
schema_tool.get_table_constraints(table_name))
@pytest.mark.cmd
@pytest.mark.django_db
def test_schema_app(capfd):
if get_current_db_type() != 'mysql':
pytest.skip("unsupported database")
call_command('schema', 'app', 'pootle_store')
out, err = capfd.readouterr()
result = SchemaDump()
result.load(json.loads(out))
schema_tool = SchemaTool('pootle_store')
for table_name in schema_tool.get_tables():
table_result = result.apps['pootle_store'].tables[table_name]
_test_table_result(schema_tool, table_result, table_name)
@pytest.mark.cmd
@pytest.mark.django_db
def test_schema_app_tables(capfd):
if get_current_db_type() != 'mysql':
pytest.skip("unsupported database")
call_command('schema', 'app', 'pootle_store', '--tables')
out, err = capfd.readouterr()
schema_tool = SchemaTool('pootle_store')
result = SchemaDump()
result.load(json.loads(out))
assert schema_tool.get_tables() == result.tables
@pytest.mark.cmd
@pytest.mark.django_db
def test_schema_table(capfd):
if get_current_db_type() != 'mysql':
pytest.skip("unsupported database")
call_command('schema', 'table', 'pootle_store_store')
out, err = capfd.readouterr()
schema_tool = SchemaTool()
result = SchemaDump()
result.load(json.loads(out))
app_label = schema_tool.get_app_by_table('pootle_store_store')
table_result = result.apps[app_label].tables['pootle_store_store']
_test_table_result(schema_tool, table_result, 'pootle_store_store')
@pytest.mark.cmd
@pytest.mark.django_db
def test_schema_multi_table(capfd):
if get_current_db_type() != 'mysql':
pytest.skip("unsupported database")
call_command('schema', 'table', 'pootle_store_store', 'pootle_store_unit')
out, err = capfd.readouterr()
schema_tool = SchemaTool()
result = SchemaDump()
result.load(json.loads(out))
app_label = schema_tool.get_app_by_table('pootle_store_store')
table_result = result.apps[app_label].tables['pootle_store_store']
_test_table_result(schema_tool, table_result, 'pootle_store_store')
table_result = result.apps[app_label].tables['pootle_store_unit']
_test_table_result(schema_tool, table_result, 'pootle_store_unit')
@pytest.mark.cmd
@pytest.mark.django_db
def test_schema_wrong_table():
if get_current_db_type() != 'mysql':
pytest.skip("unsupported database")
with pytest.raises(CommandError):
call_command('schema', 'table', 'wrong_table_name')
@pytest.mark.cmd
@pytest.mark.django_db
def test_schema_wrong_app():
if get_current_db_type() != 'mysql':
pytest.skip("unsupported database")
with pytest.raises(CommandError):
call_command('schema', 'app', 'wrong_app_name')
| 5,340
|
Python
|
.py
| 138
| 33.913043
| 78
| 0.693842
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,060
|
contributors.py
|
translate_pootle/tests/commands/contributors.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from argparse import ArgumentTypeError
from collections import OrderedDict
from dateutil.parser import parse as parse_datetime
from email.utils import formataddr
import pytest
import pytz
from django.core.management import call_command
from django.core.management.base import CommandError
from pootle.core.utils.timezone import make_aware
from pootle_app.management.commands.contributors import get_aware_datetime
from pytest_pootle.fixtures.contributors import CONTRIBUTORS_WITH_EMAIL
def test_contributors_get_aware_datetime():
"""Get an aware datetime from a valid string."""
iso_datetime = make_aware(parse_datetime("2016-01-24T23:15:22+0000"),
tz=pytz.utc)
# Test ISO 8601 datetime.
assert iso_datetime == get_aware_datetime("2016-01-24T23:15:22+0000",
tz=pytz.utc)
# Test git-like datetime.
assert iso_datetime == get_aware_datetime("2016-01-24 23:15:22 +0000",
tz=pytz.utc)
# Test just an ISO 8601 date.
iso_datetime = make_aware(parse_datetime("2016-01-24T00:00:00+0000"),
tz=pytz.utc)
assert iso_datetime == get_aware_datetime("2016-01-24", tz=pytz.utc)
# Test None.
assert get_aware_datetime(None) is None
# Test empty string.
assert get_aware_datetime("") is None
# Test non-empty string.
with pytest.raises(ArgumentTypeError):
get_aware_datetime("THIS FAILS")
# Test blank string.
with pytest.raises(ArgumentTypeError):
get_aware_datetime(" ")
@pytest.mark.cmd
@pytest.mark.django_db
def test_cmd_contributors(capfd, dummy_contributors,
default_contributors_kwargs, contributors_kwargs):
"""Contributors across the site."""
result_kwargs = default_contributors_kwargs.copy()
result_kwargs.update(contributors_kwargs)
cmd_args = []
for k in ["project", "language"]:
if result_kwargs["%s_codes" % k]:
for arg in result_kwargs["%s_codes" % k]:
cmd_args.extend(["--%s" % k, arg])
for k in ["since", "until"]:
if result_kwargs[k]:
cmd_args.extend(
["--%s" % k,
result_kwargs[k]])
result_kwargs[k] = make_aware(parse_datetime(result_kwargs[k]))
if result_kwargs["sort_by"]:
cmd_args.extend(["--sort-by", result_kwargs["sort_by"]])
call_command('contributors', *cmd_args)
out, err = capfd.readouterr()
assert out.strip() == str(
"\n".join(
"%s (%s contributions)" % (k, v)
for k, v
in result_kwargs.items()))
@pytest.mark.cmd
def test_cmd_contributors_mutually_exclusive(capfd):
"""Test mutually exclusive arguments are not accepted."""
with pytest.raises(CommandError) as e:
call_command('contributors', '--include-anonymous', '--mailmerge')
assert ("argument --mailmerge: not allowed with argument "
"--include-anonymous") in str(e)
with pytest.raises(CommandError) as e:
call_command('contributors', '--mailmerge', '--include-anonymous')
assert ("argument --include-anonymous: not allowed with argument "
"--mailmerge") in str(e)
@pytest.mark.cmd
@pytest.mark.django_db
def test_cmd_contributors_mailmerge(capfd, dummy_email_contributors):
"""Contributors across the site with mailmerge."""
call_command('contributors', '--mailmerge')
out, err = capfd.readouterr()
temp = OrderedDict(sorted(CONTRIBUTORS_WITH_EMAIL.items(),
key=lambda x: str.lower(x[1]['username'])))
expected = [
formataddr((item["full_name"].strip() or item["username"],
item['email'].strip()))
for item in temp.values() if item['email'].strip()]
assert out.strip() == "\n".join(expected)
| 4,168
|
Python
|
.py
| 93
| 37.075269
| 77
| 0.649149
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,061
|
import.py
|
translate_pootle/tests/commands/import.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import os
import pytest
from django.core.management import call_command
from django.core.management.base import CommandError
from pytest_pootle.utils import get_translated_storefile
@pytest.mark.cmd
def test_import_user_nofile():
"""Missing 'file' positional argument."""
with pytest.raises(CommandError) as e:
call_command('import')
assert "too few arguments" in str(e)
@pytest.mark.cmd
def test_import_user_non_existant_file():
"""No file on filesystem."""
with pytest.raises(CommandError) as e:
call_command('import', 'nofile.po')
assert "No such file" in str(e)
@pytest.mark.cmd
@pytest.mark.django_db
def test_import_emptyfile(capfd, tmpdir):
"""Load an empty PO file"""
p = tmpdir.mkdir("sub").join("empty.po")
p.write("")
with pytest.raises(CommandError) as e:
call_command('import', os.path.join(p.dirname, p.basename))
assert "missing X-Pootle-Path header" in str(e)
@pytest.mark.cmd
@pytest.mark.django_db
def test_import_onefile(capfd, tmpdir):
"""Load an one unit PO file"""
from pootle_store.models import Store
p = tmpdir.mkdir("sub").join("store0.po")
store = Store.objects.get(pootle_path="/language0/project0/store0.po")
p.write(str(get_translated_storefile(store)))
call_command('import', os.path.join(p.dirname, p.basename))
out, err = capfd.readouterr()
assert "/language0/project0/store0.po" in err
@pytest.mark.cmd
@pytest.mark.django_db
def test_import_onefile_with_user(capfd, tmpdir, site_users):
"""Load an one unit PO file"""
from pootle_store.models import Store
user = site_users['user'].username
p = tmpdir.mkdir("sub").join("store0.po")
store = Store.objects.get(pootle_path="/language0/project0/store0.po")
p.write(str(get_translated_storefile(store)))
call_command('import', '--user=%s' % user,
os.path.join(p.dirname, p.basename))
out, err = capfd.readouterr()
assert user in out
assert "[update]" in err
assert "units in /language0/project0/store0.po" in err
@pytest.mark.cmd
@pytest.mark.django_db
def test_import_bad_user(tmpdir):
from pootle_store.models import Store
p = tmpdir.mkdir("sub").join("store0.po")
store = Store.objects.get(pootle_path="/language0/project0/store0.po")
p.write(str(get_translated_storefile(store)))
with pytest.raises(CommandError) as e:
call_command('import', '--user=not_a_user',
os.path.join(p.dirname, p.basename))
assert "Unrecognised user: not_a_user" in str(e)
@pytest.mark.cmd
@pytest.mark.django_db
def test_import_bad_pootlepath(tmpdir):
"""Bad X-Pootle-Path
/ missing before language0
"""
from pootle_store.models import Store
p = tmpdir.join("store0.po")
store = Store.objects.get(pootle_path="/language0/project0/store0.po")
p.write(str(
get_translated_storefile(store,
pootle_path="language0/project0/store0.po")))
with pytest.raises(CommandError) as e:
call_command('import', os.path.join(p.dirname, p.basename))
assert "Missing Project/Language?" in str(e)
| 3,436
|
Python
|
.py
| 85
| 35.635294
| 78
| 0.700721
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,062
|
verify_user.py
|
translate_pootle/tests/commands/verify_user.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import pytest
from django.contrib.auth import get_user_model
from django.core.management import call_command
from django.core.management.base import CommandError
@pytest.mark.cmd
@pytest.mark.django_db
def test_verify_user_nouser(capfd):
with pytest.raises(CommandError) as e:
call_command('verify_user')
assert "Either provide a 'user' to verify or use '--all'" in str(e)
@pytest.mark.cmd
@pytest.mark.django_db
def test_verify_user_user_and_all(capfd):
with pytest.raises(CommandError) as e:
call_command('verify_user', '--all', 'member_with_email')
assert "Either provide a 'user' to verify or use '--all'" in str(e)
@pytest.mark.cmd
@pytest.mark.django_db
def test_verify_user_unknownuser(capfd):
with pytest.raises(CommandError) as e:
call_command('verify_user', 'not_a_user')
assert "User not_a_user does not exist" in str(e)
@pytest.mark.cmd
@pytest.mark.django_db
def test_verify_user_noemail(capfd):
get_user_model().objects.create(username="memberX")
call_command('verify_user', 'memberX')
out, err = capfd.readouterr()
assert "You cannot verify an account with no email set" in err
@pytest.mark.cmd
@pytest.mark.django_db
def test_verify_user_hasemail(capfd, member_with_email):
call_command('verify_user', 'member_with_email')
out, err = capfd.readouterr()
assert "User 'member_with_email' has been verified" in out
@pytest.mark.cmd
@pytest.mark.django_db
def test_verify_user_all(capfd, member_with_email, member2_with_email):
call_command('verify_user', '--all')
out, err = capfd.readouterr()
assert "Verified user 'member_with_email'" in out
assert "Verified user 'member2_with_email'" in out
@pytest.mark.cmd
@pytest.mark.django_db
def test_verify_user_multiple(capfd, member_with_email, member2_with_email):
call_command('verify_user', 'member_with_email', 'member2_with_email')
out, err = capfd.readouterr()
assert "User 'member_with_email' has been verified" in out
assert "User 'member2_with_email' has been verified" in out
| 2,344
|
Python
|
.py
| 56
| 38.642857
| 77
| 0.738116
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,063
|
dump.py
|
translate_pootle/tests/commands/dump.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import pytest
from django.core.management import call_command
from django.core.management.base import CommandError
@pytest.mark.cmd
@pytest.mark.django_db
def test_dump_noargs():
"""Dump requires an output option."""
with pytest.raises(CommandError) as e:
call_command('dump')
assert "Set --data or --stats option" in str(e)
@pytest.mark.cmd
@pytest.mark.django_db
def test_dump_data(capfd):
"""--data output."""
call_command('dump', '--data')
out, err = capfd.readouterr()
assert "Directory" in out
assert "Project" in out
assert "TranslationProject" in out
assert "Store" in out
# FIXME unsure why this one does not appear
# assert "Language" in out
@pytest.mark.cmd
@pytest.mark.django_db
def test_dump_stats(capfd):
"""--stats output."""
call_command('dump', '--stats')
out, err = capfd.readouterr()
# Ensure it's a --stats
assert 'None,None' in out
assert out.startswith('/')
# Ensure its got all the files, the data differs due to differing load
# sequences
# First level
assert '/language0/project0/' in out
assert '/language1/project0/' in out
assert '/projects/project0/' in out
# Deeper levels in output
assert '/language0/project0/store0.po' in out
assert '/language0/project0/subdir0' in out
@pytest.mark.cmd
@pytest.mark.django_db
def test_dump_stop_level(capfd):
"""Set the depth for data."""
call_command('dump', '--stats', '--stop-level=1')
out, err = capfd.readouterr()
# Ensure it's a --stats
assert 'None,None' in out
assert out.startswith('/')
# First level
assert '/language0/project0/' in out
assert '/language1/project0/' in out
assert '/projects/project0/' in out
# Deeper levels not output
assert '/language0/project0/store0.po' not in out
assert '/language0/project0/subdir0' not in out
@pytest.mark.cmd
@pytest.mark.django_db
def test_dump_data_tp(capfd):
"""--data output with TP selection."""
call_command('dump', '--data', '--project=project0', '--language=language0')
out, err = capfd.readouterr()
assert "Directory" in out
assert "Store" in out
# FIXME check if these really should be missing
assert "Language" not in out
assert "Project" not in out
assert "TranslationProject" not in out
@pytest.mark.cmd
@pytest.mark.django_db
def test_dump_stats_tp(capfd):
"""--stats output with TP selection"""
call_command('dump', '--stats', '--project=project0', '--language=language0')
out, err = capfd.readouterr()
# Ensure it's a --stats
stats_match = out.split("\n")[0].strip().split(" ").pop()
assert "None,None" in stats_match
assert out.startswith('/')
# Ensure its got all the files (the data differs due to differing load
# sequences)
# First level
assert '/language0/project0/' in out
# Deaper levels not output
assert '/language0/project0/store0.po' in out
assert '/language0/project0/subdir0' in out
assert '/projects/project0/' not in out
assert '/language1/project0/' not in out
| 3,375
|
Python
|
.py
| 94
| 31.87234
| 81
| 0.693627
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,064
|
dates.py
|
translate_pootle/tests/i18n/dates.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import pytest
import time
from datetime import datetime
from babel.dates import format_timedelta
from pootle.i18n.dates import timesince
from pootle.i18n.formatter import get_locale_formats
def test_local_date_timesince(settings):
timestamp = time.time() - 1000000
timedelta = datetime.now() - datetime.fromtimestamp(timestamp)
language = str(get_locale_formats().locale)
assert timesince(timestamp) == format_timedelta(timedelta, locale=language)
assert (
timesince(timestamp, locale="ff")
== timesince(timestamp, locale=settings.LANGUAGE_CODE))
@pytest.mark.parametrize('language,fallback', [
# Normal
('af', 'af'),
('en-za', 'en-za'),
('en-us', 'en-us'),
# Code from ISO 639 reserved range (cannot be used to represent a language)
# so we know for sure it has to fall back.
('qbb', 'en-us'),
])
def test_local_date_timesince_wrong_locale(language, fallback):
timestamp = time.time() - 1000000
timedelta = datetime.now() - datetime.fromtimestamp(timestamp)
fallback_format = get_locale_formats(fallback)
fallback_timedelta = fallback_format.timedelta(timedelta, format='long')
assert timesince(timestamp, locale=language) == fallback_timedelta
| 1,512
|
Python
|
.py
| 36
| 38.472222
| 79
| 0.734513
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,065
|
formatter.py
|
translate_pootle/tests/i18n/formatter.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import pytest
from babel.support import Format
from django.utils.translation import override
from pootle.i18n.formatter import (_clean_zero, get_locale_formats, number,
percent)
@pytest.mark.parametrize('language', [
'af', 'en-za', 'en-us', # Normal
'son', # Missing in babel
])
def test_get_locale_formats(language):
with override(language):
assert isinstance(get_locale_formats(), Format)
def test__clean_zero():
assert _clean_zero(None) == 0
assert _clean_zero('') == 0
assert _clean_zero(0) == 0
assert _clean_zero(3.1415) == 3.1415
@pytest.mark.parametrize('language, expected', [
('en-gb', '1,000.5'), # Normal
('gl', '1.000,5'), # Galician (inverted wrt en-us)
('af-za', u'1\u00a0000,5'), # Major difference
('son', '1,000.5'), # Missing
])
def test_number(language, expected):
with override(language):
assert number('1000.5') == expected
@pytest.mark.parametrize('language, expected', [
('en-gb', '1,000%'), # Normal
('gl', '1.000%'), # Galician (inverted wrt en-us)
('af-za', u'1\u00a0000%'), # Major difference
('son', '1,000%'), # Missing
])
def test_percent(language, expected):
with override(language):
assert percent(10.005) == expected
@pytest.mark.parametrize('language, expected', [
('en-gb', '1,000.5%'), # Normal
('gl', '1.000,5%'), # Galician (inverted wrt en-us)
('af-za', u'1\u00a0000,5%'), # Major difference
('son', '1,000.5%'), # Missing
])
def test_percent_format(language, expected):
with override(language):
assert percent(10.005, '#,##0.0%') == expected
| 1,940
|
Python
|
.py
| 51
| 33.745098
| 77
| 0.642324
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,066
|
override.py
|
translate_pootle/tests/i18n/override.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import pytest
from django.conf import settings
from django.utils.translation import LANGUAGE_SESSION_KEY
from pootle.i18n.override import (get_lang_from_cookie,
get_lang_from_http_header,
get_language_from_request,
get_lang_from_session, supported_langs)
SUPPORTED_LANGUAGES = {
'es-ar': 'es-ar',
'fr': 'fr',
'gl': 'gl',
}
@pytest.mark.django_db
def test_get_lang_from_session(rf, client):
# Test no session.
request = rf.get("")
assert not hasattr(request, 'session') # Check no session before test.
assert get_lang_from_session(request, SUPPORTED_LANGUAGES) is None
# Test session with no language.
response = client.get("")
request = response.wsgi_request
assert LANGUAGE_SESSION_KEY not in request.session
assert get_lang_from_session(request, SUPPORTED_LANGUAGES) is None
# Test session with supported language.
response = client.get("")
request = response.wsgi_request
request.session[LANGUAGE_SESSION_KEY] = 'gl'
assert get_lang_from_session(request, SUPPORTED_LANGUAGES) == 'gl'
# Test session with supported language.
response = client.get("")
request = response.wsgi_request
request.session[LANGUAGE_SESSION_KEY] = 'es-AR'
assert get_lang_from_session(request, SUPPORTED_LANGUAGES) == 'es-ar'
# Test cookie with longer underscore language code for a supported
# language.
response = client.get("")
request = response.wsgi_request
request.session[LANGUAGE_SESSION_KEY] = 'gl_ES'
assert get_lang_from_session(request, SUPPORTED_LANGUAGES) == 'gl'
# Test cookie with longer hyphen language code for a supported language.
response = client.get("")
request = response.wsgi_request
request.session[LANGUAGE_SESSION_KEY] = 'fr-FR'
assert get_lang_from_session(request, SUPPORTED_LANGUAGES) == 'fr'
# Test header with shorter language code for a supported language.
response = client.get("")
request = response.wsgi_request
request.session[LANGUAGE_SESSION_KEY] = 'es'
assert get_lang_from_session(request, SUPPORTED_LANGUAGES) is None
# Test header with unsupported language.
response = client.get("")
request = response.wsgi_request
request.session[LANGUAGE_SESSION_KEY] = 'FAIL'
assert get_lang_from_session(request, SUPPORTED_LANGUAGES) is None
# Test header with unsupported longer underscore language.
response = client.get("")
request = response.wsgi_request
request.session[LANGUAGE_SESSION_KEY] = 'the_FAIL'
assert get_lang_from_session(request, SUPPORTED_LANGUAGES) is None
# Test header with unsupported longer hyphen language.
response = client.get("")
request = response.wsgi_request
request.session[LANGUAGE_SESSION_KEY] = 'the-FAIL'
assert get_lang_from_session(request, SUPPORTED_LANGUAGES) is None
def test_get_lang_from_cookie(rf):
request = rf.get("")
# Test no cookie.
assert settings.LANGUAGE_COOKIE_NAME not in request.COOKIES
assert get_lang_from_cookie(request, SUPPORTED_LANGUAGES) is None
# Test cookie with supported language.
request.COOKIES[settings.LANGUAGE_COOKIE_NAME] = 'gl'
assert get_lang_from_cookie(request, SUPPORTED_LANGUAGES) == 'gl'
# Test cookie with longer supported language.
request.COOKIES[settings.LANGUAGE_COOKIE_NAME] = 'es-AR'
assert get_lang_from_cookie(request, SUPPORTED_LANGUAGES) == 'es-ar'
# Test cookie with longer underscore language code for a supported
# language.
request.COOKIES[settings.LANGUAGE_COOKIE_NAME] = 'gl_ES'
assert get_lang_from_cookie(request, SUPPORTED_LANGUAGES) == 'gl'
# Test cookie with longer hyphen language code for a supported language.
request.COOKIES[settings.LANGUAGE_COOKIE_NAME] = 'fr-FR'
assert get_lang_from_cookie(request, SUPPORTED_LANGUAGES) == 'fr'
# Test cookie with shorter language code for a supported language.
request.COOKIES[settings.LANGUAGE_COOKIE_NAME] = 'es'
assert get_lang_from_cookie(request, SUPPORTED_LANGUAGES) is None
# Test cookie with unsupported language.
request.COOKIES[settings.LANGUAGE_COOKIE_NAME] = 'FAIL'
assert get_lang_from_cookie(request, SUPPORTED_LANGUAGES) is None
# Test cookie with unsupported longer underscore language.
request.COOKIES[settings.LANGUAGE_COOKIE_NAME] = 'the_FAIL'
assert get_lang_from_cookie(request, SUPPORTED_LANGUAGES) is None
# Test cookie with unsupported longer hyphen language.
request.COOKIES[settings.LANGUAGE_COOKIE_NAME] = 'the-FAIL'
assert get_lang_from_cookie(request, SUPPORTED_LANGUAGES) is None
def test_get_lang_from_http_header(rf):
# Test no header.
request = rf.get("")
assert 'HTTP_ACCEPT_LANGUAGE' not in request.META
assert get_lang_from_http_header(request, SUPPORTED_LANGUAGES) is None
# Test empty header.
request = rf.get("", HTTP_ACCEPT_LANGUAGE='')
assert get_lang_from_http_header(request, SUPPORTED_LANGUAGES) is None
# Test header with wildcard.
request = rf.get("", HTTP_ACCEPT_LANGUAGE='*')
assert get_lang_from_http_header(request, SUPPORTED_LANGUAGES) is None
# Test header with supported language.
request = rf.get("", HTTP_ACCEPT_LANGUAGE='gl')
assert get_lang_from_http_header(request, SUPPORTED_LANGUAGES) == 'gl'
# Test cookie with longer supported language.
request = rf.get("", HTTP_ACCEPT_LANGUAGE='es-AR')
assert get_lang_from_http_header(request, SUPPORTED_LANGUAGES) == 'es-ar'
# Test header with longer underscore language code for a supported
# language.
request = rf.get("", HTTP_ACCEPT_LANGUAGE='gl_ES')
assert get_lang_from_http_header(request, SUPPORTED_LANGUAGES) is None
# Test header with longer hyphen language code for a supported language.
request = rf.get("", HTTP_ACCEPT_LANGUAGE='fr-FR')
assert get_lang_from_http_header(request, SUPPORTED_LANGUAGES) == 'fr'
# Test header with shorter language code for a supported language.
request = rf.get("", HTTP_ACCEPT_LANGUAGE='es')
assert get_lang_from_http_header(request, SUPPORTED_LANGUAGES) is None
# Test header with unsupported language.
request = rf.get("", HTTP_ACCEPT_LANGUAGE='FAIL')
assert get_lang_from_http_header(request, SUPPORTED_LANGUAGES) is None
# Test header with unsupported longer underscore language.
request = rf.get("", HTTP_ACCEPT_LANGUAGE='the_FAIL')
assert get_lang_from_http_header(request, SUPPORTED_LANGUAGES) is None
# Test header with unsupported longer hyphen language.
request = rf.get("", HTTP_ACCEPT_LANGUAGE='the-FAIL')
assert get_lang_from_http_header(request, SUPPORTED_LANGUAGES) is None
def test_get_language_from_request(rf):
settings_lang = settings.LANGUAGE_CODE
supported = dict(supported_langs()) # Get Django supported languages.
request = rf.get("")
# Ensure the response doesn't come from any of the `lang_getter` functions.
assert not hasattr(request, 'session')
assert settings.LANGUAGE_COOKIE_NAME not in request.COOKIES
assert 'HTTP_ACCEPT_LANGUAGE' not in request.META
# Test default server language fallback.
settings.LANGUAGE_CODE = 'it'
assert settings.LANGUAGE_CODE in supported
assert get_language_from_request(request) == settings.LANGUAGE_CODE
# Test ultimate fallback.
settings.LANGUAGE_CODE = 'FAIL-BABY-FAIL'
assert settings.LANGUAGE_CODE not in supported
assert get_language_from_request(request) == 'en-us'
settings.LANGUAGE_CODE = settings_lang
| 7,924
|
Python
|
.py
| 154
| 46.045455
| 79
| 0.725437
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,067
|
utils.py
|
translate_pootle/tests/pootle_terminology/utils.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import re
import pytest
from pootle.core.delegate import (
stemmer, stopwords, terminology, terminology_matcher)
from pootle_terminology.utils import UnitTerminology
@pytest.mark.django_db
def test_unit_terminology_instance(terminology_units, terminology0):
units = terminology0.stores.first().units.filter(
source_f=terminology_units)
unit = None
for _unit in units:
if _unit.source_f == terminology_units:
unit = _unit
break
term = terminology.get(unit.__class__)(unit)
assert isinstance(term, UnitTerminology)
assert term.context == unit
assert term.stopwords == stopwords.get().words
assert term.stemmer == stemmer.get()
assert term.text == unit.source_f
assert (
term.split(term.text)
== re.split(u"[^\w'-]+", term.text))
assert (
term.tokens
== [t.lower()
for t
in term.split(term.text)
if (len(t) > 2
and t.lower() not in term.stopwords)])
assert (
term.stems
== set(term.stemmer(t) for t in term.tokens))
assert term.stem_set == unit.stems
assert term.stem_model == term.stem_set.model
assert term.stem_m2m == term.stem_set.through
unit.stems.all().delete()
assert term.existing_stems == set([])
term.stem()
assert sorted(term.existing_stems) == sorted(term.stems)
old_source = unit.source_f
old_stems = term.existing_stems
unit.source_f = "hatstand hatstand umbrella"
unit.save()
term.stem()
assert (
sorted(term.existing_stems)
== [u'hatstand', u'umbrella'])
unit.source_f = old_source
unit.save()
term.stem()
assert (
term.existing_stems
== old_stems)
@pytest.mark.django_db
def test_unit_terminology_bad(store0):
unit = store0.units.first()
with pytest.raises(ValueError):
terminology.get(unit.__class__)(unit)
@pytest.mark.django_db
def test_terminology_matcher(store0, terminology0):
for store in terminology0.stores.all():
for unit in store.units.all():
terminology.get(unit.__class__)(unit).stem()
unit = store0.units.first()
matcher = terminology_matcher.get(unit.__class__)(unit)
assert matcher.text == unit.source_f
assert (
matcher.split(matcher.text)
== re.split(u"[\W]+", matcher.text))
assert (
matcher.tokens
== [t.lower()
for t
in matcher.split(matcher.text)
if (len(t) > 2
and t not in matcher.stopwords)])
assert matcher.stems == set(matcher.stemmer(t) for t in matcher.tokens)
assert (
matcher.matches
== matcher.similar(
matcher.terminology_units.filter(
stems__root__in=matcher.stems).distinct()))
unit.source_f = "on the cycle home"
unit.save()
matches = []
matched = []
results = matcher.terminology_units.filter(
stems__root__in=matcher.stems).distinct()
for result in results:
target_pair = (
result.source_f.lower().strip(),
result.target_f.lower().strip())
if target_pair in matched:
continue
similarity = matcher.comparison.similarity(result.source_f)
if similarity > matcher.similarity_threshold:
matches.append((similarity, result))
matched.append(target_pair)
assert (
matcher.similar(results)
== sorted(matches, key=lambda x: -x[0])[:matcher.max_matches])
assert (
matcher.matches
== matcher.similar(results))
| 3,889
|
Python
|
.py
| 112
| 27.803571
| 77
| 0.635422
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,068
|
signals.py
|
translate_pootle/tests/pootle_fs/signals.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import pytest
from django.dispatch import receiver
from pootle_fs.signals import (
fs_pre_push, fs_post_push, fs_pre_pull, fs_post_pull)
@pytest.mark.django_db
def test_fs_pull_signal(project_fs):
project_fs.add(force=True)
state = project_fs.state()
class Success(object):
expected = len(state["fs_staged"]) + len(state["fs_ahead"])
pre_pull_called = False
post_pull_called = False
success = Success()
@receiver(fs_pre_pull)
def fs_pre_pull_handler(**kwargs):
assert kwargs["plugin"] is project_fs.plugin
assert "No changes made" in str(kwargs["response"])
assert "pulled_to_pootle" not in kwargs["response"]
# we see the original state
assert (
success.expected
== (len(kwargs["state"]["fs_staged"])
+ len(kwargs["state"]["fs_ahead"])))
success.pre_pull_called = True
@receiver(fs_post_pull)
def fs_post_pull_handler(**kwargs):
assert kwargs["plugin"] is project_fs.plugin
# we still see the original state
assert (
success.expected
== (len(kwargs["state"]["fs_staged"])
+ len(kwargs["state"]["fs_ahead"])))
# but the response has been updated
assert (
success.expected
== len(kwargs["response"]["pulled_to_pootle"]))
success.post_pull_called = True
success.response = kwargs["response"]
assert project_fs.sync_pull() == success.response
assert success.pre_pull_called is True
assert success.post_pull_called is True
@pytest.mark.django_db
def test_fs_push_signal(project_fs):
project_fs.add(force=True)
state = project_fs.state()
class Success(object):
expected = len(state["pootle_staged"]) + len(state["pootle_ahead"])
pre_push_called = False
post_push_called = False
success = Success()
@receiver(fs_pre_push)
def fs_pre_push_handler(**kwargs):
assert kwargs["plugin"] is project_fs.plugin
assert "No changes made" in str(kwargs["response"])
assert "pushed_to_pootle" not in kwargs["response"]
# we see the original state
assert (
success.expected
== (len(kwargs["state"]["pootle_staged"])
+ len(kwargs["state"]["pootle_ahead"])))
success.pre_push_called = True
@receiver(fs_post_push)
def fs_post_push_handler(**kwargs):
assert kwargs["plugin"] is project_fs.plugin
# we still see the original state
assert (
success.expected
== (len(kwargs["state"]["pootle_staged"])
+ len(kwargs["state"]["pootle_ahead"])))
# but the response has been updated
assert (
success.expected
== len(kwargs["response"]["pushed_to_fs"]))
success.post_push_called = True
success.response = kwargs["response"]
assert project_fs.sync_push() == success.response
assert success.pre_push_called is True
assert success.post_push_called is True
| 3,369
|
Python
|
.py
| 85
| 31.894118
| 77
| 0.629017
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,069
|
resources.py
|
translate_pootle/tests/pootle_fs/resources.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from fnmatch import fnmatch
import sys
import pytest
from django.utils.functional import cached_property
from pootle_fs.apps import PootleFSConfig
from pootle_fs.models import StoreFS
from pootle_fs.resources import (
FSProjectResources, FSProjectStateResources)
from pootle_project.models import Project
from pootle_store.models import Store
@pytest.mark.django_db
def test_project_resources_instance():
project = Project.objects.get(code="project0")
resources = FSProjectResources(project)
assert resources.project == project
assert str(resources) == "<FSProjectResources(Project 0)>"
@pytest.mark.django_db
def test_project_resources_stores(project0, language0):
stores = Store.objects.filter(
translation_project__project=project0)
assert list(FSProjectResources(project0).stores) == list(stores)
# mark some Stores obsolete - should still show
store_count = stores.count()
assert store_count
for store in stores:
store.makeobsolete()
assert list(FSProjectResources(project0).stores) == list(stores)
assert stores.count() == store_count
project0.config["pootle.fs.excluded_languages"] = [language0.code]
filtered_stores = stores.exclude(
translation_project__language=language0)
assert (
list(FSProjectResources(project0).stores)
!= list(stores))
assert (
list(FSProjectResources(project0).stores)
== list(filtered_stores))
@pytest.mark.django_db
def test_project_resources_trackable_stores(project0_fs_resources):
project = project0_fs_resources
stores = Store.objects.filter(
translation_project__project=project)
# only stores that are not obsolete and do not have an
# exiting StoreFS should be trackable
trackable = stores.filter(obsolete=False).order_by("pk")
trackable = trackable.filter(fs__isnull=True)
assert (
list(FSProjectResources(project).trackable_stores.order_by("pk"))
== list(trackable))
for store in FSProjectResources(project).trackable_stores:
try:
fs = store.fs.get()
except StoreFS.DoesNotExist:
fs = None
assert fs is None
assert store.obsolete is False
@pytest.mark.django_db
def test_project_resources_tracked(project0_fs_resources):
project = project0_fs_resources
assert (
list(FSProjectResources(project).tracked.order_by("pk"))
== list(StoreFS.objects.filter(project=project).order_by("pk")))
# this includes obsolete stores
assert FSProjectResources(project).tracked.filter(
store__obsolete=True).exists()
@pytest.mark.django_db
def test_project_resources_synced(project0_fs_resources):
project = project0_fs_resources
synced = StoreFS.objects.filter(project=project).order_by("pk")
obsoleted = synced.filter(store__obsolete=True).first()
obsoleted.last_sync_hash = "FOO"
obsoleted.last_sync_revision = 23
obsoleted.save()
active = synced.exclude(store__obsolete=True).first()
active.last_sync_hash = "FOO"
active.last_sync_revision = 23
active.save()
synced = synced.exclude(last_sync_revision__isnull=True)
synced = synced.exclude(last_sync_hash__isnull=True)
assert (
list(FSProjectResources(project).synced.order_by("pk"))
== list(synced))
assert FSProjectResources(project).synced.count() == 2
@pytest.mark.django_db
def test_project_resources_unsynced(project0_fs_resources):
project = project0_fs_resources
for store_fs in FSProjectResources(project).tracked:
store_fs.last_sync_hash = "FOO"
store_fs.last_sync_revision = 23
store_fs.save()
unsynced = StoreFS.objects.filter(project=project).order_by("pk")
obsoleted = unsynced.filter(store__obsolete=True).first()
obsoleted.last_sync_hash = None
obsoleted.last_sync_revision = None
obsoleted.save()
active = unsynced.exclude(store__obsolete=True).first()
active.last_sync_hash = None
active.last_sync_revision = None
active.save()
unsynced = unsynced.filter(last_sync_revision__isnull=True)
unsynced = unsynced.filter(last_sync_hash__isnull=True)
assert (
list(FSProjectResources(project).unsynced.order_by("pk"))
== list(unsynced))
assert FSProjectResources(project).unsynced.count() == 2
class DummyPlugin(object):
def __init__(self, project):
self.project = project
@cached_property
def resources(self):
return FSProjectResources(self.project)
def reload(self):
if "resources" in self.__dict__:
del self.__dict__["resources"]
@pytest.mark.django_db
def test_fs_state_resources(project0_fs_resources):
project = project0_fs_resources
plugin = DummyPlugin(project)
state_resources = FSProjectStateResources(plugin)
assert state_resources.resources is plugin.resources
# resources are cached on state and plugin
plugin.reload()
assert state_resources.resources is not plugin.resources
state_resources.reload()
assert state_resources.resources is plugin.resources
@pytest.mark.django_db
def test_fs_state_trackable(fs_path_qs, dummyfs_untracked):
(qfilter, pootle_path, fs_path) = fs_path_qs
plugin = dummyfs_untracked
qs = Store.objects.filter(
translation_project__project=plugin.project)
if qfilter is False:
qs = qs.none()
elif qfilter:
qs = qs.filter(qfilter)
trackable = FSProjectStateResources(
plugin,
pootle_path=pootle_path,
fs_path=fs_path).trackable_stores
assert (
sorted(trackable, key=lambda item: item[0].pk)
== [(store, plugin.get_fs_path(store.pootle_path))
for store in list(qs.order_by("pk"))])
@pytest.mark.django_db
def test_fs_state_trackable_store_paths(fs_path_qs, dummyfs_untracked):
(qfilter, pootle_path, fs_path) = fs_path_qs
plugin = dummyfs_untracked
qs = Store.objects.filter(
translation_project__project=plugin.project)
if qfilter is False:
qs = qs.none()
elif qfilter:
qs = qs.filter(qfilter)
resources = FSProjectStateResources(plugin)
assert (
sorted(
(store.pootle_path, fs_path)
for store, fs_path
in resources.trackable_stores)
== sorted(resources.trackable_store_paths.items()))
@pytest.mark.django_db
def test_fs_state_trackable_tracked(dummyfs, no_complex_po_):
plugin = dummyfs
resources = FSProjectStateResources(plugin)
store_fs = resources.tracked[0]
store = store_fs.store
store_fs.delete()
trackable = resources.trackable_stores
store = plugin.resources.stores.get(
pootle_path=store.pootle_path)
assert len(trackable) == 1
assert trackable[0][0] == store
assert (
trackable[0][1]
== plugin.get_fs_path(store.pootle_path))
@pytest.mark.django_db
@pytest.mark.xfail(sys.platform == 'win32',
reason="path mangling broken on windows")
def test_fs_state_synced(fs_path_qs, dummyfs):
(qfilter, pootle_path, fs_path) = fs_path_qs
plugin = dummyfs
qs = StoreFS.objects.filter(project=plugin.project)
if qfilter is False:
qs = qs.none()
elif qfilter:
qs = qs.filter(qfilter)
synced = FSProjectStateResources(
plugin,
pootle_path=pootle_path,
fs_path=fs_path).synced
assert (
list(synced.order_by("pk"))
== list(qs.order_by("pk")))
@pytest.mark.django_db
def test_fs_state_synced_staged(dummyfs):
plugin = dummyfs
resources = FSProjectStateResources(plugin)
store_fs = resources.tracked[0]
resources.tracked.exclude(pk=store_fs.pk).update(
last_sync_hash=None,
last_sync_revision=None)
assert resources.synced.count() == 1
# synced does not include any that are staged rm/merge
store_fs.staged_for_merge = True
store_fs.save()
assert resources.synced.count() == 0
store_fs.staged_for_merge = False
store_fs.staged_for_removal = True
store_fs.save()
assert resources.synced.count() == 0
store_fs.staged_for_removal = False
store_fs.save()
assert resources.synced.count() == 1
@pytest.mark.django_db
@pytest.mark.xfail(sys.platform == 'win32',
reason="path mangling broken on windows")
def test_fs_state_unsynced(fs_path_qs, dummyfs):
(qfilter, pootle_path, fs_path) = fs_path_qs
plugin = dummyfs
resources = FSProjectStateResources(plugin)
resources.tracked.update(
last_sync_hash=None,
last_sync_revision=None)
qs = StoreFS.objects.filter(project=plugin.project)
if qfilter is False:
qs = qs.none()
elif qfilter:
qs = qs.filter(qfilter)
unsynced = FSProjectStateResources(
plugin,
pootle_path=pootle_path,
fs_path=fs_path).unsynced
assert (
list(unsynced.order_by("pk"))
== list(qs.order_by("pk")))
@pytest.mark.django_db
def test_fs_state_unsynced_staged(dummyfs):
plugin = dummyfs
resources = FSProjectStateResources(plugin)
store_fs = resources.tracked[0]
store_fs.last_sync_hash = None
store_fs.last_sync_revision = None
store_fs.save()
assert resources.unsynced.count() == 1
# unsynced does not include any that are staged rm/merge
store_fs.staged_for_merge = True
store_fs.save()
assert resources.unsynced.count() == 0
store_fs.staged_for_merge = False
store_fs.staged_for_removal = True
store_fs.save()
assert resources.unsynced.count() == 0
store_fs.staged_for_removal = False
store_fs.save()
assert resources.unsynced.count() == 1
@pytest.mark.django_db
@pytest.mark.xfail(sys.platform == 'win32',
reason="path mangling broken on windows")
def test_fs_state_tracked(fs_path_qs, dummyfs):
(qfilter, pootle_path, fs_path) = fs_path_qs
plugin = dummyfs
qs = StoreFS.objects.filter(project=plugin.project)
if qfilter is False:
qs = qs.none()
elif qfilter:
qs = qs.filter(qfilter)
tracked = FSProjectStateResources(
plugin,
pootle_path=pootle_path,
fs_path=fs_path).tracked
assert (
list(tracked.order_by("pk"))
== list(qs.order_by("pk")))
@pytest.mark.django_db
def test_fs_state_tracked_paths(fs_path_qs, dummyfs):
(qfilter, pootle_path, fs_path) = fs_path_qs
plugin = dummyfs
resources = FSProjectStateResources(plugin)
resources.tracked.update(
last_sync_hash=None,
last_sync_revision=None)
qs = StoreFS.objects.filter(project=plugin.project)
if qfilter is False:
qs = qs.none()
elif qfilter:
qs = qs.filter(qfilter)
resources = FSProjectStateResources(plugin)
assert (
sorted(resources.tracked.values_list("path", "pootle_path"))
== sorted(resources.tracked_paths.items()))
@pytest.mark.django_db
@pytest.mark.xfail(sys.platform == 'win32',
reason="path mangling broken on windows")
def test_fs_state_pootle_changed(fs_path_qs, dummyfs):
(qfilter, pootle_path, fs_path) = fs_path_qs
plugin = dummyfs
resources = FSProjectStateResources(plugin)
assert list(
FSProjectStateResources(
plugin,
pootle_path=pootle_path,
fs_path=fs_path).pootle_changed) == []
for store_fs in plugin.resources.tracked:
store_fs.last_sync_revision = store_fs.last_sync_revision - 1
store_fs.save()
qs = StoreFS.objects.filter(project=plugin.project)
if qfilter is False:
qs = qs.none()
elif qfilter:
qs = qs.filter(qfilter)
resources = FSProjectStateResources(
plugin,
pootle_path=pootle_path,
fs_path=fs_path)
assert (
sorted(resources.pootle_changed.values_list("pk", flat=True))
== sorted(qs.values_list("pk", flat=True)))
@pytest.mark.django_db
def test_fs_state_found_file_matches(fs_path_qs, dummyfs):
(qfilter, pootle_path, fs_path) = fs_path_qs
plugin = dummyfs
resources = FSProjectStateResources(
plugin, pootle_path=pootle_path, fs_path=fs_path)
stores = resources.resources.stores
found_files = []
for pp in stores.values_list("pootle_path", flat=True):
fp = plugin.get_fs_path(pp)
if fs_path and not fnmatch(fp, fs_path):
continue
if pootle_path and not fnmatch(pp, pootle_path):
continue
found_files.append((pp, fp))
assert (
sorted(resources.found_file_matches)
== sorted(found_files))
assert (
resources.found_file_paths
== [x[1] for x in resources.found_file_matches])
@pytest.mark.django_db
def test_fs_resources_cache_key(project_fs):
plugin = project_fs
resources = plugin.state().resources
assert resources.ns == "pootle.fs.resources"
assert resources.sw_version == PootleFSConfig.version
assert (
resources.fs_revision
== resources.context.fs_revision)
assert (
resources.sync_revision
== resources.context.sync_revision)
assert (
resources.cache_key
== resources.context.cache_key)
| 13,523
|
Python
|
.py
| 361
| 31.465374
| 77
| 0.68822
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,070
|
finder.py
|
translate_pootle/tests/pootle_fs/finder.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import os
import sys
import pytest
from django.core.exceptions import ValidationError
from django.urls import resolve
from pootle_fs.apps import PootleFSConfig
from pootle_fs.finder import TranslationFileFinder
from pootle_store.models import Store
@pytest.mark.django_db
@pytest.mark.xfail(sys.platform == 'win32',
reason="path mangling broken on windows")
def test_finder_match_filepath():
finder = TranslationFileFinder("/path/to/<language_code>.<ext>")
assert finder.match("/foo/baz/lang.po") is None
assert finder.match("/path/to/lang.xliff") is None
assert finder.match("/path/to/lang.po")
@pytest.mark.django_db
@pytest.mark.xfail(sys.platform == 'win32',
reason="path mangling broken on windows")
def test_finder_match_reverse():
finder = TranslationFileFinder("/path/to/<language_code>.<ext>")
assert finder.reverse_match("foo") == "/path/to/foo.po"
finder = TranslationFileFinder("/path/to/<language_code>/<filename>.<ext>")
assert finder.reverse_match("foo") == "/path/to/foo/foo.po"
finder = TranslationFileFinder("/path/to/<language_code>/<filename>.<ext>")
assert finder.reverse_match("foo", filename="bar") == "/path/to/foo/bar.po"
@pytest.mark.django_db
@pytest.mark.xfail(sys.platform == 'win32',
reason="path mangling broken on windows")
def test_finder_match_reverse_directory():
finder = TranslationFileFinder("/path/to/<language_code>.<ext>")
assert finder.reverse_match("foo", dir_path="bar") is None
finder = TranslationFileFinder(
"/path/to/<dir_path>/<language_code>.<ext>")
assert finder.reverse_match("foo") == "/path/to/foo.po"
assert finder.reverse_match(
"foo", dir_path="bar") == "/path/to/bar/foo.po"
assert finder.reverse_match(
"foo", dir_path="some/other") == "/path/to/some/other/foo.po"
@pytest.mark.django_db
@pytest.mark.xfail(sys.platform == 'win32',
reason="path mangling broken on windows")
def test_finder_match_stores():
TRANSLATION_PATH = "/path/to/<dir_path>/<language_code>/<filename>.<ext>"
finder = TranslationFileFinder(TRANSLATION_PATH)
stores = Store.objects.all()
for store in stores:
kwargs = resolve(store.pootle_path).kwargs
kwargs["filename"] = os.path.splitext(kwargs["filename"])[0]
del kwargs["project_code"]
expected = TRANSLATION_PATH
for k, v in kwargs.items():
expected = expected.replace("<%s>" % k, v)
# clean up if no dir_path
expected = expected.replace("//", "/")
expected = expected.replace(
"<ext>", str(store.filetype.extension))
assert finder.reverse_match(**kwargs) == expected
matched = finder.match(expected)
for k, v in kwargs.items():
assert matched[1][k] == v.strip("/")
@pytest.mark.django_db
@pytest.mark.xfail(sys.platform == 'win32',
reason="path mangling broken on windows")
def test_finder_filters():
finder = TranslationFileFinder(
"/path/to/<dir_path>/<language_code>.<ext>",
path_filters=["/path/to/*"])
# doesnt filter anything
assert finder.match("/path/to/any.po")
assert finder.match("/path/to/some/other.po")
assert finder.match("/path/to/and/any/other.po")
finder = TranslationFileFinder(
"/path/to/<dir_path>/<language_code>.<ext>",
path_filters=["/path/to/some/*"])
# these dont match
assert not finder.match("/path/to/any.po")
assert not finder.match("/path/to/and/any/other.po")
# but this does
assert finder.match("/path/to/some/other.po")
# filter_paths are `and` matches
finder = TranslationFileFinder(
"/path/to/<dir_path>/<language_code>.<ext>",
path_filters=["/path/to/this/*", "/path/to/this/other/*"])
# so this doesnt match
assert not finder.match("/path/to/this/file.po")
# but these do
assert finder.match("/path/to/this/other/file.po")
assert finder.match("/path/to/this/other/file2.po")
assert finder.match("/path/to/this/other/in/subdir/file2.po")
@pytest.mark.django_db
@pytest.mark.xfail(sys.platform == 'win32',
reason="path mangling broken on windows")
def test_finder_match_reverse_ext():
finder = TranslationFileFinder("/path/to/<language_code>.<ext>")
# ext must be in list of exts
with pytest.raises(ValueError):
finder.reverse_match("foo", extension="abc")
finder = TranslationFileFinder(
"/foo/bar/<language_code>.<ext>", extensions=["abc", "xyz"])
assert finder.reverse_match("foo") == "/foo/bar/foo.abc"
assert finder.reverse_match("foo", extension="abc") == "/foo/bar/foo.abc"
assert finder.reverse_match("foo", extension="xyz") == "/foo/bar/foo.xyz"
# Parametrized: ROOT_PATHS
@pytest.mark.django_db
@pytest.mark.xfail(sys.platform == 'win32',
reason="path mangling broken on windows")
def test_finder_file_root(finder_root_paths):
dir_path = os.sep.join(['', 'some', 'path'])
path, expected = finder_root_paths
assert (
TranslationFileFinder(
os.path.join(dir_path, path)).file_root
== (
expected
and os.path.join(dir_path, expected)
or dir_path))
# Parametrized: BAD_FINDER_PATHS
@pytest.mark.django_db
def test_finder_bad_paths(bad_finder_paths):
dir_path = os.sep.join(['', 'some', 'path'])
with pytest.raises(ValidationError):
TranslationFileFinder(os.path.join(dir_path, bad_finder_paths))
# Parametrized: FINDER_REGEXES
@pytest.mark.django_db
@pytest.mark.xfail(sys.platform == 'win32',
reason="path mangling broken on windows")
def test_finder_regex(finder_regexes):
dir_path = os.sep.join(['', 'some', 'path'])
translation_mapping = os.path.join(dir_path, finder_regexes)
finder = TranslationFileFinder(translation_mapping)
path = translation_mapping
for k, v in TranslationFileFinder.path_mapping:
path = path.replace(k, v)
path = os.path.splitext(path)
path = "%s%s" % (path[0], finder._ext_re())
assert finder.regex.pattern == "%s$" % path
# Parametrized: MATCHES
@pytest.mark.django_db
@pytest.mark.xfail(sys.platform == 'win32',
reason="path mangling broken on windows")
def test_finder_match(finder_matches):
dir_path = os.sep.join(['', 'some', 'path'])
match_path, not_matching, matching = finder_matches
finder = TranslationFileFinder(os.path.join(dir_path, match_path))
for path in not_matching:
assert not finder.match(
os.path.join(dir_path, path))
for path, expected in matching:
match = finder.regex.match(os.path.join(dir_path, path))
assert match
named = match.groupdict()
for k in ["lang", "dir_path", "filename", "ext"]:
if k in expected:
assert named[k].strip("/") == expected[k]
else:
assert k not in named
reverse = finder.reverse_match(
named['language_code'],
named.get('filename', os.path.splitext(os.path.basename(path))[0]),
named['ext'],
dir_path=named.get('dir_path'))
assert os.path.join(dir_path, path) == reverse
# Parametrized: FILES
@pytest.mark.django_db
@pytest.mark.xfail(sys.platform == 'win32',
reason="path mangling broken on windows")
def test_finder_find(fs_finder):
finder, expected = fs_finder
assert sorted(expected) == sorted(f for f in finder.find())
@pytest.mark.django_db
@pytest.mark.xfail(sys.platform == 'win32',
reason="path mangling broken on windows")
def test_finder_exclude_langs():
finder = TranslationFileFinder(
"/path/to/<dir_path>/<language_code>.<ext>",
exclude_languages=["foo", "bar"])
assert not finder.match("/path/to/foo.po")
assert not finder.match("/path/to/bar.po")
match = finder.match("/path/to/baz.po")
assert match[0] == "/path/to/baz.po"
assert match[1]["language_code"] == "baz"
assert not finder.reverse_match(language_code="foo")
assert not finder.reverse_match(language_code="bar")
assert (
finder.reverse_match(language_code="baz")
== "/path/to/baz.po")
@pytest.mark.django_db
@pytest.mark.xfail(sys.platform == 'win32',
reason="path mangling broken on windows")
def test_finder_cache_key():
finder = TranslationFileFinder(
"/path/to/<dir_path>/<language_code>.<ext>",
exclude_languages=["foo", "bar"])
assert not finder.fs_hash
assert not finder.cache_key
assert finder.ns == "pootle.fs.finder"
assert finder.sw_version == PootleFSConfig.version
finder = TranslationFileFinder(
"/path/to/<dir_path>/<language_code>.<ext>",
exclude_languages=["foo", "bar"],
fs_hash="XYZ")
assert finder.fs_hash == "XYZ"
assert (
finder.cache_key
== ("%s.%s.%s"
% (finder.fs_hash,
"::".join(finder.exclude_languages),
hash(finder.regex.pattern))))
@pytest.mark.django_db
@pytest.mark.xfail(sys.platform == 'win32',
reason="path mangling broken on windows")
def test_finder_lang_codes():
finder = TranslationFileFinder(
"/path/to/<dir_path>/<language_code>.<ext>")
match = finder.match("/path/to/foo/bar@baz.po")
assert match[1]["language_code"] == "bar@baz"
| 9,789
|
Python
|
.py
| 225
| 37.008889
| 79
| 0.653782
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,071
|
plugin.py
|
translate_pootle/tests/pootle_fs/plugin.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import os
import sys
import pytest
from pootle.core.delegate import revision
from pootle.core.response import Response
from pootle.core.state import State
from pootle_app.models import Directory
from pootle_fs.apps import PootleFSConfig
from pootle_fs.exceptions import FSStateError
from pootle_fs.matcher import FSPathMatcher
from pootle_fs.models import StoreFS
from pootle_fs.plugin import Plugin
from pootle_fs.utils import FSPlugin
from pootle_project.models import Project
from pootle_store.constants import POOTLE_WINS, SOURCE_WINS
FS_CHANGE_KEYS = [
"_added", "_pulled",
"_synced", "_pushed",
"_resolved", "_removed", "_unstaged"]
def _test_dummy_response(action, responses, **kwargs):
stores = kwargs.pop("stores", None)
if stores:
assert len(responses) == len(stores)
stores_fs = kwargs.pop("stores_fs", None)
if stores_fs:
assert len(responses) == len(stores_fs)
for response in responses:
if action.startswith("add"):
if response.fs_state.state_type.endswith("_untracked"):
store_fs = StoreFS.objects.get(
pootle_path=response.pootle_path,
path=response.fs_path)
else:
store_fs = response.store_fs
store_fs.refresh_from_db()
if response.fs_state.state_type == "fs_removed":
assert store_fs.resolve_conflict == POOTLE_WINS
elif response.fs_state.state_type == "pootle_removed":
assert store_fs.resolve_conflict == SOURCE_WINS
assert not store_fs.staged_for_merge
continue
if action.startswith("rm"):
if response.fs_state.state_type.endswith("_untracked"):
store_fs = StoreFS.objects.get(
pootle_path=response.pootle_path,
path=response.fs_path)
else:
store_fs = response.store_fs
store_fs.refresh_from_db()
assert store_fs.staged_for_removal
continue
remove_states = ["fs_staged", "pootle_staged", "remove"]
if action.startswith("unstage"):
if response.fs_state.state_type in remove_states:
with pytest.raises(StoreFS.DoesNotExist):
response.store_fs.refresh_from_db()
continue
store_fs = response.store_fs
store_fs.refresh_from_db()
assert not store_fs.staged_for_merge
assert not store_fs.resolve_conflict
continue
if stores:
if response.store_fs:
assert response.store_fs.store in stores
else:
assert stores.filter(
pootle_path=response.pootle_path).exists()
if action.startswith("resolve"):
if response.fs_state.state_type.endswith("_untracked"):
store_fs = StoreFS.objects.get(
path=response.fs_state.fs_path,
pootle_path=response.fs_state.pootle_path)
else:
store_fs = response.store_fs
store_fs.refresh_from_db()
if "pootle" in action:
assert store_fs.resolve_conflict == POOTLE_WINS
if not action.endswith("overwrite"):
assert store_fs.staged_for_merge is True
continue
check_store_fs = (
stores_fs
and not response.fs_state.state_type == "fs_untracked")
if check_store_fs:
assert response.store_fs in stores_fs
@pytest.mark.django_db
@pytest.mark.xfail(
sys.platform == 'win32',
reason="path mangling broken on windows")
def test_fs_plugin_unstage_response(capsys, no_complex_po_, localfs_envs):
state_type, plugin = localfs_envs
action = "unstage"
original_state = plugin.state()
plugin_response = getattr(plugin, action)(state=original_state)
unstaging_states = [
"fs_staged", "pootle_staged", "remove",
"merge_fs_wins", "merge_pootle_wins"]
if state_type in unstaging_states:
assert plugin_response.made_changes is True
_test_dummy_response(
action, plugin_response["unstaged"], _unstaged=True)
else:
assert plugin_response.made_changes is False
assert not plugin_response["unstaged"]
@pytest.mark.django_db
def test_fs_plugin_unstage_staged_response(capsys,
no_complex_po_,
localfs_staged_envs):
state_type, plugin = localfs_staged_envs
action = "unstage"
original_state = plugin.state()
plugin_response = getattr(plugin, action)(
state=original_state)
assert plugin_response.made_changes is True
_test_dummy_response(
action, plugin_response["unstaged"], _unstaged=True)
@pytest.mark.django_db
def test_fs_plugin_paths(project_fs_empty, possible_actions):
__, cmd, __, cmd_args = possible_actions
project_fs_empty.fetch()
pootle_path, fs_path = "FOO", "BAR"
response = getattr(project_fs_empty, cmd)(
pootle_path=pootle_path, fs_path=fs_path, **cmd_args)
assert response.context.pootle_path == pootle_path
assert response.context.fs_path == fs_path
new_response = getattr(project_fs_empty, cmd)(
response=response, pootle_path=pootle_path, fs_path=fs_path, **cmd_args)
assert response.context.pootle_path == pootle_path
assert response.context.fs_path == fs_path
assert new_response is response
state = response.context
new_response = getattr(project_fs_empty, cmd)(
state=state, pootle_path=pootle_path, fs_path=fs_path, **cmd_args)
assert response.context.pootle_path == pootle_path
assert response.context.fs_path == fs_path
assert new_response.context is state
@pytest.mark.django_db
@pytest.mark.xfail(
sys.platform == 'win32',
reason="path mangling broken on windows")
def test_fs_plugin_response(localfs_envs, possible_actions, fs_response_map):
state_type, plugin = localfs_envs
action_name, action, command_args, plugin_kwargs = possible_actions
stores_fs = None
expected = fs_response_map[state_type].get(action_name)
if not expected and action_name.endswith("_force"):
expected = fs_response_map[state_type].get(action_name[:-6])
plugin_response = getattr(plugin, action)(**plugin_kwargs)
changes = []
if not expected:
assert plugin_response.made_changes is False
return
stores = plugin.resources.stores
if not stores:
stores_fs = plugin.resources.tracked
if expected[0] in ["merged_from_pootle", "merged_from_fs"]:
changes = ["_pulled", "_pushed", "_synced"]
elif expected[0] == "added_from_pootle":
changes = ["_added"]
elif expected[0] == "pushed_to_fs":
changes = ["_pushed", "_synced"]
elif expected[0] == "pulled_to_pootle":
changes = ["_pulled", "_synced"]
elif expected[0] == "staged_for_merge_fs":
changes = ["_merged", "_merge_fs"]
elif expected[0] == "staged_for_merge_pootle":
changes = ["_merged", "_merge_pootle"]
elif expected[0] == "staged_for_removal":
changes = ["_removed"]
if changes:
kwargs = {
change: True
for change in changes}
else:
kwargs = {}
kwargs.update(
dict(stores=stores,
stores_fs=stores_fs))
_test_dummy_response(
action_name,
plugin_response[expected[0]],
**kwargs)
@pytest.mark.django_db
def test_plugin_instance_bad_args(project_fs_empty):
fs_plugin = project_fs_empty.plugin
with pytest.raises(TypeError):
fs_plugin.__class__()
with pytest.raises(TypeError):
fs_plugin.__class__("FOO")
@pytest.mark.django_db
def test_plugin_fetch(project_fs_empty):
assert project_fs_empty.is_cloned is False
project_fs_empty.fetch()
assert project_fs_empty.is_cloned is True
project_fs_empty.clear_repo()
assert project_fs_empty.is_cloned is False
@pytest.mark.django_db
def test_plugin_instance(project_fs_empty):
project_fs = project_fs_empty
assert project_fs.project == project_fs.plugin.project
assert project_fs.project.local_fs_path.endswith(project_fs.project.code)
assert project_fs.is_cloned is False
assert project_fs.resources.stores.exists() is False
assert project_fs.resources.tracked.exists() is False
# any instance of the same plugin is equal
new_plugin = FSPlugin(project_fs.project)
assert project_fs == new_plugin
assert project_fs is not new_plugin
# but the plugin doesnt equate to a cabbage 8)
assert not project_fs == "a cabbage"
@pytest.mark.django_db
def test_plugin_pootle_user(project_fs_empty, member):
project = project_fs_empty.project
assert "pootle_fs.pootle_user" not in project.config
assert project_fs_empty.pootle_user is None
project.config["pootle_fs.pootle_user"] = member.username
assert project_fs_empty.pootle_user is None
project_fs_empty.reload()
assert project_fs_empty.pootle_user == member
@pytest.mark.django_db
def test_plugin_pootle_user_bad(project_fs_empty, member):
project = project_fs_empty.project
project.config["pootle_fs.pootle_user"] = "USER_DOES_NOT_EXIST"
project_fs_empty.reload()
assert project_fs_empty.pootle_user is None
@pytest.mark.django_db
def test_fs_plugin_sync_all():
class SyncPlugin(Plugin):
sync_order = []
def push(self, response):
self._push_response = response
self.sync_order.append("plugin_push")
return response
def sync_merge(self, state, response, fs_path=None,
pootle_path=None, update=None):
self._merged = (state, response, fs_path, pootle_path)
self.sync_order.append("merge")
def sync_pull(self, state, response, fs_path=None, pootle_path=None):
self._pulled = (state, response, fs_path, pootle_path)
self.sync_order.append("pull")
def sync_push(self, state, response, fs_path=None, pootle_path=None):
self._pushed = (state, response, fs_path, pootle_path)
self.sync_order.append("push")
def sync_rm(self, state, response, fs_path=None, pootle_path=None):
self._rmed = (state, response, fs_path, pootle_path)
self.sync_order.append("rm")
project = Project.objects.get(code="project0")
plugin = SyncPlugin(project)
state = State("dummy")
response = Response(state)
class DummyResources(object):
file_hashes = {}
pootle_revisions = {}
state.resources = DummyResources()
plugin.sync(state, response, fs_path="FOO", pootle_path="BAR")
for result in [plugin._merged, plugin._pushed, plugin._rmed, plugin._pulled]:
assert result[0] is state
assert result[1] is response
assert result[2] == "FOO"
assert result[3] == "BAR"
assert plugin._push_response is response
assert plugin.sync_order == ["rm", "merge", "pull", "push", "plugin_push"]
@pytest.mark.django_db
def test_fs_plugin_not_implemented():
project = Project.objects.get(code="project0")
plugin = Plugin(project)
with pytest.raises(NotImplementedError):
plugin.latest_hash
with pytest.raises(NotImplementedError):
plugin.fetch()
with pytest.raises(NotImplementedError):
plugin.push()
@pytest.mark.django_db
def test_fs_plugin_matcher(localfs):
matcher = localfs.matcher
assert isinstance(matcher, FSPathMatcher)
assert matcher is localfs.matcher
localfs.reload()
assert matcher is not localfs.matcher
@pytest.mark.django_db
@pytest.mark.xfail(
sys.platform == 'win32',
reason="path mangling broken on windows")
def test_fs_plugin_localfs_push(localfs_pootle_staged_real):
plugin = localfs_pootle_staged_real
response = plugin.sync()
for response_item in response["pushed_to_fs"]:
src_file = os.path.join(
plugin.fs_url,
response_item.store_fs.file.path.lstrip("/"))
target_file = response_item.store_fs.file.file_path
with open(src_file) as target:
with open(target_file) as src:
assert src.read() == target.read()
@pytest.mark.django_db
def test_fs_plugin_cache_key(project_fs):
plugin = project_fs
assert plugin.ns == "pootle.fs.plugin"
assert plugin.sw_version == PootleFSConfig.version
assert (
plugin.fs_revision
== plugin.latest_hash)
assert (
plugin.sync_revision
== revision.get(
Project)(plugin.project).get(key="pootle.fs.sync"))
assert (
plugin.pootle_revision
== revision.get(
Directory)(plugin.project.directory).get(key="stats"))
assert (
plugin.cache_key
== ("%s.%s.%s.%s"
% (plugin.project.code,
plugin.pootle_revision,
plugin.sync_revision,
plugin.fs_revision)))
@pytest.mark.django_db
def test_fs_plugin_fetch_bad(project0):
plugin = FSPlugin(project0)
plugin.clear_repo()
with pytest.raises(FSStateError):
plugin.add()
| 13,585
|
Python
|
.py
| 331
| 33.190332
| 81
| 0.650633
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,072
|
display.py
|
translate_pootle/tests/pootle_fs/display.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import sys
import pytest
from pootle_fs.display import (
FS_EXISTS_ACTIONS, STORE_EXISTS_ACTIONS,
FS_EXISTS_STATES, STORE_EXISTS_STATES,
ResponseDisplay, ResponseItemDisplay, ResponseTypeDisplay,
StateDisplay, StateItemDisplay, StateTypeDisplay)
from pootle_fs.response import FS_RESPONSE
from pootle_fs.state import FS_STATE
@pytest.mark.django_db
def test_fs_response_display_instance(localfs_pootle_untracked):
plugin = localfs_pootle_untracked
response = plugin.add()
display = ResponseDisplay(response)
assert display.context == response
assert display.sections == [
rtype for rtype in response if response[rtype]]
for section in display.sections:
type_display = display.section(section)
assert isinstance(type_display, ResponseTypeDisplay)
assert type_display.context == display
assert type_display.name == section
result = ""
for rtype in display.sections:
result += str(display.section(rtype))
assert result
assert str(display) == "%s\n" % result
def test_fs_response_display_no_change():
assert str(ResponseDisplay([])) == "No changes made\n"
@pytest.mark.django_db
def test_fs_response_display_type_instance(localfs_pootle_untracked):
plugin = localfs_pootle_untracked
response = plugin.add()
display = ResponseDisplay(response)
section = ResponseTypeDisplay(display, "added_from_pootle")
assert section.context == display
assert section.name == "added_from_pootle"
assert section.info == FS_RESPONSE["added_from_pootle"]
assert section.description == section.info["description"]
assert section.title == (
"%s (%s)"
% (section.info['title'],
len(response[section.name])))
assert (
len(section.data)
== len(section.items)
== len(response["added_from_pootle"]))
for i, item in enumerate(section.items):
assert section.data[i] == item.item
assert isinstance(item, ResponseItemDisplay)
result = (
"%s\n%s\n%s\n\n"
% (section.title, "-" * len(section.title), section.description))
for item in section.data:
result += str(section.item_class(section, item))
assert str(section) == "%s\n" % result
@pytest.mark.django_db
def test_fs_response_display_item_instance(localfs_pootle_untracked):
plugin = localfs_pootle_untracked
response = plugin.add()
response_item = response["added_from_pootle"][0]
item_display = ResponseItemDisplay(response, response_item)
assert item_display.action_type == "added_from_pootle"
assert item_display.state_item == response_item.fs_state
assert item_display.file_exists is False
assert item_display.store_exists is True
assert item_display.pootle_path == response_item.pootle_path
assert item_display.fs_path == "(%s)" % response_item.fs_path
assert item_display.state_type == item_display.state_item.state_type
result = (
" %s\n <--> %s\n"
% (item_display.pootle_path, item_display.fs_path))
assert str(item_display) == result
@pytest.mark.django_db
@pytest.mark.xfail(
sys.platform == 'win32',
reason="path mangling broken on windows")
def test_fs_response_display_item_fs_untracked(localfs_fs_untracked):
plugin = localfs_fs_untracked
response = plugin.add()
response_item = response["added_from_fs"][0]
item_display = ResponseItemDisplay(None, response_item)
assert item_display.action_type == "added_from_fs"
assert item_display.state_item == response_item.fs_state
assert item_display.file_exists is True
assert item_display.store_exists is False
assert item_display.pootle_path == "(%s)" % response_item.pootle_path
assert item_display.fs_path == response_item.fs_path
assert item_display.state_type == item_display.state_item.state_type
result = (
" %s\n <--> %s\n"
% (item_display.pootle_path, item_display.fs_path))
assert str(item_display) == result
def test_fs_response_display_item_existence(fs_responses, fs_states):
class DummyResponseItem(object):
@property
def action_type(self):
return fs_responses
class ResponseItemDisplayTestable(ResponseItemDisplay):
@property
def state_type(self):
return fs_states
file_exists = (
fs_responses in FS_EXISTS_ACTIONS
or (fs_states
in ["conflict", "conflict_untracked"])
or (fs_responses == "staged_for_removal"
and (fs_states
in ["fs_untracked", "pootle_removed"])))
store_exists = (
fs_responses in STORE_EXISTS_ACTIONS
or (fs_states
in ["conflict", "conflict_untracked"])
or (fs_responses == "staged_for_removal"
and (fs_states
in ["pootle_untracked", "fs_removed"])))
fs_added = (
fs_responses == "added_from_fs"
and fs_states not in ["conflict", "conflict_untracked"])
pootle_added = (
fs_responses == "added_from_pootle"
and fs_states not in ["conflict", "conflict_untracked"])
item_display = ResponseItemDisplayTestable({}, DummyResponseItem())
assert item_display.file_exists == file_exists
assert item_display.store_exists == store_exists
assert item_display.fs_added == fs_added
assert item_display.pootle_added == pootle_added
@pytest.mark.django_db
def test_fs_state_display_instance(localfs_pootle_untracked):
plugin = localfs_pootle_untracked
state = plugin.state()
display = StateDisplay(state)
assert display.context == state
assert display.sections == [
state_type for state_type
in display.context
if display.context[state_type]]
@pytest.mark.django_db
def test_fs_state_display_type_instance(localfs_pootle_untracked):
plugin = localfs_pootle_untracked
state = plugin.state()
display = StateDisplay(state)
section = StateTypeDisplay(display, "pootle_untracked")
assert section.context == display
assert section.name == "pootle_untracked"
assert section.info == FS_STATE[section.name]
assert section.title == (
"%s (%s)"
% (section.info['title'],
len(section.context.context[section.name])))
@pytest.mark.django_db
def test_fs_display_state_item_instance(localfs_pootle_untracked):
plugin = localfs_pootle_untracked
state_item = plugin.state()["pootle_untracked"][0]
item_display = StateItemDisplay(None, state_item)
assert item_display.item == state_item
assert item_display.state_type == "pootle_untracked"
assert item_display.file is None
assert item_display.file_exists is False
assert item_display.store_exists is True
assert item_display.tracked is False
@pytest.mark.django_db
def test_fs_display_state_item_instance_file(localfs_pootle_untracked):
plugin = localfs_pootle_untracked
state_item = plugin.state()["pootle_untracked"][0]
item_display = StateItemDisplay(None, state_item)
assert item_display.item.store_fs is None
assert item_display.tracked is False
assert item_display.file is None
plugin.add()
state_item = plugin.state()["pootle_staged"][0]
item_display = StateItemDisplay(None, state_item)
assert item_display.file == state_item.store_fs.file
@pytest.mark.django_db
@pytest.mark.xfail(
sys.platform == 'win32',
reason="path mangling broken on windows")
def test_fs_display_state_item_instance_fs_untracked(localfs_fs_untracked):
plugin = localfs_fs_untracked
state_item = plugin.state()["fs_untracked"][0]
item_display = StateItemDisplay(None, state_item)
assert item_display.item == state_item
assert item_display.state_type == "fs_untracked"
assert item_display.file is None
assert item_display.file_exists is True
assert item_display.store_exists is False
assert item_display.tracked is False
def test_fs_display_state_item_existence(fs_states):
class DummyStateItem(object):
pass
class DummyFile(object):
file_exists = False
store_exists = False
class StateItemDisplayTestable(StateItemDisplay):
@property
def state_type(self):
return fs_states
file = DummyFile()
item_display = StateItemDisplayTestable({}, DummyStateItem())
if fs_states == "remove":
assert item_display.file_exists is False
assert item_display.store_exists is False
item_display.file.file_exists = True
assert item_display.file_exists is True
assert item_display.store_exists is False
item_display.file.store_exists = True
assert item_display.store_exists is True
else:
assert item_display.file_exists == (fs_states in FS_EXISTS_STATES)
assert item_display.store_exists == (fs_states in STORE_EXISTS_STATES)
| 9,173
|
Python
|
.py
| 217
| 36.299539
| 78
| 0.697544
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,073
|
localfs.py
|
translate_pootle/tests/pootle_fs/localfs.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import os
import pytest
from pootle_fs.utils import FSPlugin
@pytest.mark.django_db
def test_fs_localfs_path(settings, project0):
project0.config["pootle_fs.fs_url"] = (
"{POOTLE_TRANSLATION_DIRECTORY}%s"
% project0.code)
plugin = FSPlugin(project0)
assert (
plugin.fs_url
== os.path.join(
settings.POOTLE_TRANSLATION_DIRECTORY,
project0.code))
| 693
|
Python
|
.py
| 21
| 28.52381
| 77
| 0.701649
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,074
|
receivers.py
|
translate_pootle/tests/pootle_fs/receivers.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import pytest
from pootle_format.models import Format
@pytest.mark.django_db
def test_fs_filetypes_changed_receiver(project_fs, project1, po2):
project1.filetype_tool.add_filetype(po2)
xliff = Format.objects.get(name="xliff")
project1.filetypes.add(xliff)
sync_start = project_fs.project.revisions.filter(
key="pootle.fs.sync").first()
project_fs.project.filetype_tool.add_filetype(po2)
assert (
sync_start
!= project_fs.project.revisions.filter(
key="pootle.fs.sync").first())
| 820
|
Python
|
.py
| 21
| 34.857143
| 77
| 0.727273
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,075
|
utils.py
|
translate_pootle/tests/pootle_fs/utils.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from fnmatch import translate
import pytest
from pytest_pootle.factories import ProjectDBFactory
from django.core.exceptions import ValidationError
from pootle.core.exceptions import MissingPluginError, NotConfiguredError
from pootle.core.plugin import provider
from pootle_fs.delegate import fs_plugins
from pootle_fs.models import StoreFS
from pootle_fs.utils import (
PathFilter, StoreFSPathFilter, StorePathFilter, FSPlugin, parse_fs_url)
from pootle_project.models import Project
from pootle_store.models import Store
class DummyFSPlugin(object):
def __eq__(self, other):
return (
isinstance(other, self.__class__)
and self.project == other.project)
def __str__(self):
return (
"<%s(%s)>"
% (self.__class__.__name__, self.project))
def __init__(self, project):
self.project = project
@property
def plugin_property(self):
return "Plugin property"
def plugin_method(self, foo):
return "Plugin method called with: %s" % foo
@pytest.mark.django_db
def test_store_fs_path_filter_instance():
path_filter = StoreFSPathFilter()
assert path_filter.pootle_path is None
assert path_filter.pootle_regex is None
assert path_filter.fs_path is None
assert path_filter.fs_regex is None
# regexes are cached
path_filter.pootle_path = "/foo"
path_filter.fs_path = "/bar"
assert path_filter.pootle_regex is None
assert path_filter.fs_regex is None
del path_filter.__dict__["pootle_regex"]
del path_filter.__dict__["fs_regex"]
assert (
path_filter.pootle_regex
== path_filter.path_regex(path_filter.pootle_path))
assert (
path_filter.fs_regex
== path_filter.path_regex(path_filter.fs_path))
@pytest.mark.django_db
def test_store_path_filter_instance():
path_filter = StorePathFilter()
assert path_filter.pootle_path is None
assert path_filter.pootle_regex is None
assert not hasattr(path_filter, "fs_path")
assert not hasattr(path_filter, "fs_regex")
# regexes are cached
path_filter.pootle_path = "/foo"
path_filter.fs_path = "/bar"
assert path_filter.pootle_regex is None
del path_filter.__dict__["pootle_regex"]
assert (
path_filter.pootle_regex
== path_filter.path_regex(path_filter.pootle_path))
@pytest.mark.django_db
@pytest.mark.parametrize(
"glob", [None, "/language0", "/language0/*", "*.po",
"/language[01]*", "/language[!1]/*", "/language?/*"])
def test_store_path_filtered(glob):
project = Project.objects.get(code="project0")
stores = Store.objects.filter(
translation_project__project=project)
path_filter = StorePathFilter(glob)
if not glob:
assert path_filter.filtered(stores) is stores
else:
assert (
list(path_filter.filtered(stores))
== list(stores.filter(pootle_path__regex=path_filter.pootle_regex)))
@pytest.mark.django_db
@pytest.mark.parametrize(
"glob", [None, "/language0", "/language0/*", "*.po",
"/language[01]*", "/language[!1]/*", "/language?/*"])
def test_store_fs_path_filtered(glob):
project = Project.objects.get(code="project0")
stores = Store.objects.filter(
translation_project__project=project)
for store in stores:
StoreFS.objects.create(
store=store,
path="/fs%s" % store.pootle_path)
stores_fs = StoreFS.objects.filter(project=project)
if not glob:
assert StoreFSPathFilter().filtered(stores_fs) is stores_fs
else:
path_filter = StoreFSPathFilter(pootle_path=glob)
assert (
list(path_filter.filtered(stores_fs))
== list(stores_fs.filter(pootle_path__regex=path_filter.pootle_regex)))
path_filter = StoreFSPathFilter(fs_path="/fs%s" % glob)
assert (
list(path_filter.filtered(stores_fs))
== list(stores_fs.filter(path__regex=path_filter.fs_regex)))
@pytest.mark.parametrize(
"glob", ["/foo", "/bar/*", "*.baz", "[abc]", "[!xyz]", "language?"])
def test_fs_path_filter_path_regex(glob):
assert (
PathFilter().path_regex(glob)
== translate(glob).replace("\Z(?ms)", "$"))
@pytest.mark.django_db
def test_project_fs_instance():
@provider(fs_plugins, sender=Project)
def provide_fs_plugin(**kwargs):
return dict(dummyfs=DummyFSPlugin)
project = Project.objects.get(code="project0")
project.config["pootle_fs.fs_type"] = "dummyfs"
project.config["pootle_fs.fs_url"] = "/foo/bar"
plugin = FSPlugin(project)
assert str(plugin) == "<DummyFSPlugin(Project 0)>"
assert plugin.project == project
assert plugin.plugin_property == "Plugin property"
assert plugin.plugin_method("bar") == "Plugin method called with: bar"
assert plugin == FSPlugin(project)
@pytest.mark.django_db
def test_project_fs_instance_bad(english):
# needs a Project
with pytest.raises(TypeError):
FSPlugin()
project = ProjectDBFactory(source_language=english)
# project is not configured
with pytest.raises(NotConfiguredError):
FSPlugin(project)
with pytest.raises(ValidationError):
project.config["pootle_fs.fs_type"] = "foo"
project.config["pootle_fs.fs_type"] = "localfs"
with pytest.raises(NotConfiguredError):
FSPlugin(project)
project.config["pootle_fs.fs_url"] = "/bar"
default_receivers = fs_plugins.receivers[:]
default_cache = fs_plugins.sender_receivers_cache.copy()
@provider(fs_plugins, sender=Project)
def provide_fs_plugin(**kwargs):
return dict(dummyfs=DummyFSPlugin)
project.config["pootle_fs.fs_type"] = "dummyfs"
fs_plugins.receivers = default_receivers
fs_plugins.sender_receivers_cache = default_cache
with pytest.raises(MissingPluginError):
FSPlugin(project)
@pytest.mark.parametrize(
"fs, fs_type, fs_url", [
("/test/fs/path/", "localfs", "/test/fs/path/"),
("localfs+/test/fs/path/", "localfs", "/test/fs/path/"),
])
def test_parse_fs_url(fs, fs_type, fs_url):
assert (fs_type, fs_url) == parse_fs_url(fs)
| 6,485
|
Python
|
.py
| 162
| 34.259259
| 83
| 0.678117
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,076
|
templatetags.py
|
translate_pootle/tests/pootle_fs/templatetags.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import pytest
from pootle.core.contextmanagers import keep_data
from pootle.core.delegate import upstream
from pootle.core.plugin import provider
from pootle.core.utils.templates import render_as_template
from pootle_project.models import Project
def _render_upstream(ctx):
return render_as_template(
"{% load fs_tags %}{% upstream_link project %}",
context=ctx)
def _render_upstream_short(ctx):
return render_as_template(
"{% load fs_tags %}{% upstream_link_short project location %}",
context=ctx)
def _test_fs_tags_upstram(project0):
# no upstreams and project not configured
assert not _render_upstream(dict(project=project0)).strip()
# still no upstreams
project0.config["pootle.fs.upstream"] = "foostream"
assert not _render_upstream(dict(project=project0)).strip()
foocontext = dict(
upstream_url="UPSTREAM URL",
revision_url="REVISION URL",
fs_path="FS PATH",
latest_hash="LATEST HASH")
class Foostream(object):
def __init__(self, project):
self.project = project
@property
def context_data(self):
return foocontext
@provider(upstream, sender=Project)
def foostream_provider(**kwargs_):
return dict(foostream=Foostream)
rendered = _render_upstream(dict(project=project0))
assert all([(v in rendered) for v in foocontext.values()])
@pytest.mark.django_db
def test_fs_tags_upstream(project0):
with keep_data(upstream):
_test_fs_tags_upstram(project0)
def _test_fs_tags_upstream_short(project0):
# no upstreams and project not configured
assert not _render_upstream_short(dict(project=project0)).strip()
# still no upstreams
project0.config["pootle.fs.upstream"] = "foostream"
assert not _render_upstream_short(dict(project=project0)).strip()
foocontext = dict(
upstream_url="UPSTREAM URL",
revision_url="REVISION URL",
latest_hash="LATEST HASH")
class Foostream(object):
def __init__(self, project, location=None):
self.project = project
@property
def context_data(self):
return foocontext
@provider(upstream, sender=Project)
def foostream_provider(**kwargs_):
return dict(foostream=Foostream)
rendered = _render_upstream_short(dict(project=project0))
assert all([(v in rendered) for v in foocontext.values()])
rendered = _render_upstream_short(
dict(project=project0, location="FOO"))
assert all([(v in rendered) for v in foocontext.values()])
@pytest.mark.django_db
def test_fs_tags_upstream_short(project0):
with keep_data(upstream):
_test_fs_tags_upstream_short(project0)
| 3,022
|
Python
|
.py
| 75
| 34.426667
| 77
| 0.698424
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,077
|
validators.py
|
translate_pootle/tests/pootle_fs/validators.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import pytest
from django.core.exceptions import ValidationError
from pootle_fs.delegate import fs_translation_mapping_validator, fs_url_validator
from pootle_fs.finder import TranslationMappingValidator
from pootle_fs.localfs import LocalFSPlugin, LocalFSUrlValidator
def test_validator_localfs():
validator = fs_url_validator.get(LocalFSPlugin)()
assert isinstance(validator, LocalFSUrlValidator)
with pytest.raises(ValidationError):
validator.validate("foo/bar")
validator.validate("/foo/bar")
def test_validator_translation_mapping():
validator = fs_translation_mapping_validator.get()("asdf")
assert isinstance(validator, TranslationMappingValidator)
| 970
|
Python
|
.py
| 21
| 43.333333
| 81
| 0.796178
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,078
|
fs_state.py
|
translate_pootle/tests/pootle_fs/fs_state.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import sys
from copy import copy
import pytest
from pytest_pootle.factories import ProjectDBFactory
from pytest_pootle.fixtures.pootle_fs.state import DummyPlugin
from pootle_fs.models import StoreFS
from pootle_fs.resources import FSProjectStateResources
from pootle_fs.state import FS_STATE, ProjectFSState
from pootle_store.constants import POOTLE_WINS, SOURCE_WINS
def _test_state(plugin, pootle_path, fs_path, state_type, paths=None,
exclude_templates=False):
state = ProjectFSState(plugin, pootle_path=pootle_path, fs_path=fs_path)
if paths is None:
paths = state.resources.storefs_filter.filtered(
state.resources.tracked)
if exclude_templates:
paths = paths.exclude(
store__translation_project__language__code="templates")
paths = list(paths.values_list("pootle_path", "path"))
state_paths = []
for item in getattr(state, "state_%s" % state_type):
if item.get("pootle_path"):
pootle_path = item["pootle_path"]
else:
pootle_path = item["store"].pootle_path
fs_path = item["fs_path"]
state_paths.append((pootle_path, fs_path))
result_state_paths = []
for item in sorted(reversed(state[state_type])):
assert isinstance(item, state.item_state_class)
assert item > None
assert item.project == plugin.project
assert item.store == item.kwargs.get("store")
result_state_paths.append((item.pootle_path, item.fs_path))
assert sorted(state_paths) == result_state_paths == sorted(paths)
@pytest.mark.django_db
def test_fs_state_instance(settings, english):
settings.POOTLE_FS_WORKING_PATH = "/tmp/foo/"
project = ProjectDBFactory(source_language=english)
plugin = DummyPlugin(project)
state = ProjectFSState(plugin)
assert state.project == project
assert state.states == FS_STATE.keys()
assert (
str(state)
== ("<ProjectFSState(<DummyPlugin(%s)>): Nothing to report>"
% project.fullname))
@pytest.mark.django_db
@pytest.mark.xfail(sys.platform == 'win32',
reason="path mangling broken on windows")
def test_fs_state_fs_untracked(fs_path_qs, dummyfs_plugin_del_stores):
(qfilter, pootle_path, fs_path) = fs_path_qs
plugin = dummyfs_plugin_del_stores
state = ProjectFSState(plugin, pootle_path=pootle_path, fs_path=fs_path)
paths = list(
state.resources.storefs_filter.filtered(
state.resources.tracked).values_list("pootle_path", "path"))
plugin.resources.tracked.delete()
_test_state(plugin, pootle_path, fs_path, "fs_untracked", paths)
@pytest.mark.django_db
@pytest.mark.xfail(sys.platform == 'win32',
reason="path mangling broken on windows")
def test_fs_state_pootle_untracked(fs_path_qs, dummyfs_plugin_no_files):
(qfilter, pootle_path, fs_path) = fs_path_qs
plugin = dummyfs_plugin_no_files
state = ProjectFSState(plugin, pootle_path=pootle_path, fs_path=fs_path)
paths = list(
state.resources.storefs_filter.filtered(
state.resources.tracked).values_list("pootle_path", "path"))
plugin.resources.tracked.delete()
_test_state(plugin, pootle_path, fs_path, "pootle_untracked", paths)
@pytest.mark.django_db
def test_fs_state_fs_removed(fs_path_qs, dummyfs_plugin_no_files):
(qfilter, pootle_path, fs_path) = fs_path_qs
plugin = dummyfs_plugin_no_files
_test_state(plugin, pootle_path, fs_path, "fs_removed")
@pytest.mark.django_db
def test_fs_state_pootle_ahead(fs_path_qs, dummyfs_plugin_fs_unchanged):
(qfilter, pootle_path, fs_path) = fs_path_qs
plugin = dummyfs_plugin_fs_unchanged
for sfs in plugin.resources.tracked:
sfs.last_sync_hash = sfs.file.latest_hash
sfs.last_sync_revision = (
sfs.store.data.max_unit_revision - 1
if sfs.store.data.max_unit_revision
else 0)
sfs.save()
_test_state(
plugin,
pootle_path,
fs_path,
"pootle_ahead",
exclude_templates=True)
@pytest.mark.django_db
@pytest.mark.xfail(sys.platform == 'win32',
reason="path mangling broken on windows")
def test_fs_state_fs_staged(fs_path_qs, dummyfs_plugin_del_stores):
(qfilter, pootle_path, fs_path) = fs_path_qs
plugin = dummyfs_plugin_del_stores
plugin.resources.tracked.update(
last_sync_hash=None,
last_sync_revision=None,
resolve_conflict=SOURCE_WINS)
_test_state(plugin, pootle_path, fs_path, "fs_staged")
@pytest.mark.django_db
@pytest.mark.xfail(sys.platform == 'win32',
reason="path mangling broken on windows")
def test_fs_state_fs_staged_store_removed(fs_path_qs,
dummyfs_plugin_del_stores):
(qfilter, pootle_path, fs_path) = fs_path_qs
plugin = dummyfs_plugin_del_stores
plugin.resources.tracked.update(resolve_conflict=SOURCE_WINS)
_test_state(plugin, pootle_path, fs_path, "fs_staged")
@pytest.mark.django_db
def test_fs_state_pootle_staged(fs_path_qs, dummyfs_plugin_no_files):
(qfilter, pootle_path, fs_path) = fs_path_qs
plugin = dummyfs_plugin_no_files
plugin.resources.tracked.update(last_sync_hash=None, last_sync_revision=None)
_test_state(plugin, pootle_path, fs_path, "pootle_staged")
@pytest.mark.django_db
def test_fs_state_pootle_staged_no_file(fs_path_qs, dummyfs_plugin_no_files):
(qfilter, pootle_path, fs_path) = fs_path_qs
plugin = dummyfs_plugin_no_files
plugin.resources.tracked.update(resolve_conflict=POOTLE_WINS)
_test_state(plugin, pootle_path, fs_path, "pootle_staged")
@pytest.mark.django_db
def test_fs_state_both_removed(fs_path_qs, dummyfs_plugin_no_files):
(qfilter, pootle_path, fs_path) = fs_path_qs
plugin = dummyfs_plugin_no_files
plugin.resources.stores.delete()
_test_state(plugin, pootle_path, fs_path, "both_removed")
@pytest.mark.django_db
@pytest.mark.xfail(sys.platform == 'win32',
reason="path mangling broken on windows")
def test_fs_state_pootle_removed(dummyfs_plugin_del_stores, fs_path_qs):
(qfilter, pootle_path, fs_path) = fs_path_qs
plugin = dummyfs_plugin_del_stores
_test_state(plugin, pootle_path, fs_path, "pootle_removed")
@pytest.mark.django_db
@pytest.mark.xfail(sys.platform == 'win32',
reason="path mangling broken on windows")
def test_fs_state_conflict_untracked(fs_path_qs, no_complex_po_, dummyfs):
(qfilter, pootle_path, fs_path) = fs_path_qs
plugin = dummyfs
state = ProjectFSState(plugin, pootle_path=pootle_path, fs_path=fs_path)
paths = list(
state.resources.storefs_filter.filtered(
state.resources.tracked).values_list("pootle_path", "path"))
plugin.resources.tracked.delete()
_test_state(plugin, pootle_path, fs_path, "conflict_untracked", paths)
@pytest.mark.django_db
def test_fs_state_merge_fs_synced(fs_path_qs, dummyfs):
(qfilter, pootle_path, fs_path) = fs_path_qs
plugin = dummyfs
plugin.resources.tracked.update(
resolve_conflict=SOURCE_WINS, staged_for_merge=True)
_test_state(plugin, pootle_path, fs_path, "merge_fs_wins")
@pytest.mark.django_db
def test_fs_state_merge_fs_unsynced(fs_path_qs, dummyfs):
(qfilter, pootle_path, fs_path) = fs_path_qs
plugin = dummyfs
plugin.resources.tracked.update(
resolve_conflict=SOURCE_WINS, staged_for_merge=True,
last_sync_hash=None, last_sync_revision=None)
_test_state(plugin, pootle_path, fs_path, "merge_fs_wins")
@pytest.mark.django_db
def test_fs_state_merge_pootle_synced(fs_path_qs, dummyfs):
(qfilter, pootle_path, fs_path) = fs_path_qs
plugin = dummyfs
plugin.resources.tracked.update(
resolve_conflict=POOTLE_WINS, staged_for_merge=True)
_test_state(plugin, pootle_path, fs_path, "merge_pootle_wins")
@pytest.mark.django_db
def test_fs_state_merge_pootle_unsynced(fs_path_qs, dummyfs):
(qfilter, pootle_path, fs_path) = fs_path_qs
plugin = dummyfs
plugin.resources.tracked.update(
resolve_conflict=POOTLE_WINS, staged_for_merge=True,
last_sync_hash=None, last_sync_revision=None)
_test_state(plugin, pootle_path, fs_path, "merge_pootle_wins")
@pytest.mark.django_db
def test_fs_state_remove(fs_path_qs, dummyfs):
(qfilter, pootle_path, fs_path) = fs_path_qs
plugin = dummyfs
plugin.resources.tracked.update(staged_for_removal=True)
_test_state(plugin, pootle_path, fs_path, "remove")
@pytest.mark.django_db
def test_fs_state_conflict(fs_path_qs, dummyfs_plugin_fs_changed):
(qfilter, pootle_path, fs_path) = fs_path_qs
plugin = dummyfs_plugin_fs_changed
for store_fs in plugin.resources.tracked:
store_fs.last_sync_revision = store_fs.last_sync_revision - 1
store_fs.save()
_test_state(plugin, pootle_path, fs_path, "conflict")
@pytest.mark.django_db
@pytest.mark.xfail(sys.platform == 'win32',
reason="path mangling broken on windows")
def test_fs_state_fs_ahead(fs_path_qs, dummyfs_plugin_fs_changed):
(qfilter, pootle_path, fs_path) = fs_path_qs
plugin = dummyfs_plugin_fs_changed
_test_state(plugin, pootle_path, fs_path, "fs_ahead")
@pytest.mark.django_db
@pytest.mark.xfail(sys.platform == 'win32',
reason="path mangling broken on windows")
def test_fs_state_pootle_removed_obsolete(fs_path_qs,
dummyfs_plugin_obs_stores):
(qfilter, pootle_path, fs_path) = fs_path_qs
plugin = dummyfs_plugin_obs_stores
_test_state(plugin, pootle_path, fs_path, "pootle_removed")
@pytest.mark.django_db
@pytest.mark.xfail(sys.platform == 'win32',
reason="path mangling broken on windows")
def test_fs_state_filtered(state_filters, dummyfs_plugin_no_files, tp0):
plugin = dummyfs_plugin_no_files
state = ProjectFSState(plugin)
current_state = {
k: copy(v)
for k, v
in state.__state__.items()}
filtered_state = state.filter(**state_filters)
pootle_paths = state_filters["pootle_paths"]
fs_paths = state_filters["fs_paths"]
states = state_filters["states"]
# original is unchanged
assert state.__state__ == current_state
for name, items in state.__state__.items():
if states and name not in states:
assert filtered_state[name] == []
continue
assert (
[(item.fs_path, item.pootle_path)
for item in items
if (not pootle_paths
or item.pootle_path in pootle_paths)
and (not fs_paths
or item.fs_path in fs_paths)]
== [(x.fs_path, x.pootle_path) for x in filtered_state[name]])
@pytest.mark.django_db
@pytest.mark.xfail(sys.platform == 'win32',
reason="path mangling broken on windows")
def test_fs_state_fs_unchanged(fs_path_qs, no_complex_po_, dummyfs):
plugin = dummyfs
(qfilter, pootle_path, fs_path) = fs_path_qs
class UnchangedStateResources(FSProjectStateResources):
@property
def file_hashes(self):
hashes = {}
for pootle_path, path in self.found_file_matches:
hashes[pootle_path] = self.tracked.get(
pootle_path=pootle_path).last_sync_hash
return hashes
class UnchangedFSState(ProjectFSState):
@property
def resources(self):
return UnchangedStateResources(
self.context,
pootle_path=self.pootle_path,
fs_path=self.fs_path)
state = UnchangedFSState(plugin, fs_path=fs_path, pootle_path=pootle_path)
expected = (
plugin.resources.tracked.filter(qfilter)
if qfilter
else plugin.resources.tracked)
if qfilter is False:
expected = plugin.resources.tracked.none()
stores_fs = [x["store_fs"] for x in state.state_unchanged]
assert (
stores_fs
== list(
expected.order_by("pootle_path").values_list("id", flat=True)))
StoreFS.objects.filter(pk__in=stores_fs).update(staged_for_removal=True)
state = UnchangedFSState(plugin, fs_path=fs_path, pootle_path=pootle_path)
assert len(list(state.state_unchanged)) == 0
| 12,632
|
Python
|
.py
| 281
| 38.177936
| 81
| 0.679733
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,079
|
exceptions.py
|
translate_pootle/tests/pootle_fs/exceptions.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from pootle_fs.exceptions import (
FSAddError, FSFetchError, FSStateError, FSSyncError)
def test_error_fs_add():
error = FSAddError("it went pear shaped")
assert repr(error) == "FSAddError('it went pear shaped',)"
assert str(error) == "it went pear shaped"
assert error.message == "it went pear shaped"
def test_error_fs_fetch():
error = FSFetchError("it went pear shaped")
assert repr(error) == "FSFetchError('it went pear shaped',)"
assert str(error) == "it went pear shaped"
assert error.message == "it went pear shaped"
def test_error_fs_state():
error = FSStateError("it went pear shaped")
assert repr(error) == "FSStateError('it went pear shaped',)"
assert str(error) == "it went pear shaped"
assert error.message == "it went pear shaped"
def test_error_fs_sync():
error = FSSyncError("it went pear shaped")
assert repr(error) == "FSSyncError('it went pear shaped',)"
assert str(error) == "it went pear shaped"
assert error.message == "it went pear shaped"
| 1,316
|
Python
|
.py
| 29
| 41.689655
| 77
| 0.706343
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,080
|
fs_response.py
|
translate_pootle/tests/pootle_fs/fs_response.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import os
import pytest
from pootle.core.state import ItemState, State
from pootle_fs.models import StoreFS
from pootle_fs.response import (
FS_RESPONSE, ProjectFSItemResponse, ProjectFSResponse)
from pootle_project.models import Project
from pootle_store.models import Store
class DummyContext(object):
def __str__(self):
return "<DummyContext object>"
class DummyFSItemState(ItemState):
@property
def pootle_path(self):
if "pootle_path" in self.kwargs:
return self.kwargs["pootle_path"]
elif self.store_fs:
return self.store_fs.pootle_path
elif self.store:
return self.store.pootle_path
@property
def fs_path(self):
if "fs_path" in self.kwargs:
return self.kwargs["fs_path"]
elif self.store_fs:
return self.store_fs.path
@property
def store(self):
if "store" in self.kwargs:
return self.kwargs["store"]
elif self.store_fs:
return self.store_fs.store
@property
def store_fs(self):
return self.kwargs.get("store_fs")
class DummyFSState(State):
"""The pootle_fs State can create ItemStates with
- a store_fs (that has a store)
- a store_fs (that has no store)
- a store and an fs_path
- a pootle_path and an fs_path
"""
item_state_class = DummyFSItemState
def state_fs_staged(self, **kwargs):
for store_fs in kwargs.get("fs_staged", []):
yield dict(store_fs=store_fs)
def state_fs_ahead(self, **kwargs):
for store_fs in kwargs.get("fs_ahead", []):
yield dict(store_fs=store_fs)
def state_fs_untracked(self, **kwargs):
for fs_path, pootle_path in kwargs.get("fs_untracked", []):
yield dict(fs_path=fs_path, pootle_path=pootle_path)
def state_pootle_untracked(self, **kwargs):
for fs_path, store in kwargs.get("pootle_untracked", []):
yield dict(fs_path=fs_path, store=store)
@pytest.mark.django_db
def test_fs_response_instance():
context = DummyContext()
resp = ProjectFSResponse(context)
assert resp.context == context
assert resp.response_types == FS_RESPONSE.keys()
assert resp.has_failed is False
assert resp.made_changes is False
assert list(resp.failed()) == []
assert list(resp.completed()) == []
assert str(resp) == (
"<ProjectFSResponse(<DummyContext object>): No changes made>")
assert list(resp) == []
with pytest.raises(KeyError):
resp["DOES_NOT_EXIST"]
def _test_item(item, item_state):
assert isinstance(item, ProjectFSItemResponse)
assert item.kwargs["fs_state"] == item_state
assert item.fs_state == item_state
assert item.failed is False
assert item.fs_path == item.fs_state.fs_path
assert item.pootle_path == item.fs_state.pootle_path
assert item.store_fs == item.fs_state.store_fs
assert item.store == item.fs_state.store
assert (
str(item)
== ("<ProjectFSItemResponse(<DummyContext object>): %s "
"%s::%s>" % (item.action_type, item.pootle_path, item.fs_path)))
def _test_fs_response(expected=2, **kwargs):
action_type = kwargs.pop("action_type")
state_type = kwargs.pop("state_type")
resp = ProjectFSResponse(DummyContext())
state = DummyFSState(DummyContext(), **kwargs)
for fs_state in state[state_type]:
resp.add(action_type, fs_state=fs_state)
assert resp.has_failed is False
assert resp.made_changes is True
assert resp.response_types == FS_RESPONSE.keys()
assert len(list(resp.completed())) == 2
assert list(resp.failed()) == []
assert action_type in resp
assert str(resp) == (
"<ProjectFSResponse(<DummyContext object>): %s: %s>"
% (action_type, expected))
for i, item in enumerate(resp[action_type]):
_test_item(item, state[state_type][i])
@pytest.mark.django_db
def test_fs_response_path_items(settings, tmpdir):
settings.POOTLE_FS_WORKING_PATH = os.path.join(str(tmpdir),
"fs_response_test")
project = Project.objects.get(code="project0")
fs_untracked = []
for i in range(0, 2):
fs_untracked.append(
("/some/fs/fs_untracked_%s.po" % i,
"/language0/%s/fs_untracked_%s.po" % (project.code, i)))
_test_fs_response(
fs_untracked=fs_untracked,
action_type="added_from_fs",
state_type="fs_untracked")
@pytest.mark.django_db
def test_fs_response_store_items(settings, tmpdir):
settings.POOTLE_FS_WORKING_PATH = os.path.join(str(tmpdir),
"fs_response_test")
project = Project.objects.get(code="project0")
pootle_untracked = []
for i in range(0, 2):
pootle_untracked.append(
("/some/fs/pootle_untracked_%s.po" % i,
Store.objects.create_by_path(
"/language0/%s/pootle_untracked_%s.po" % (project.code, i))))
_test_fs_response(
pootle_untracked=pootle_untracked,
action_type="added_from_pootle",
state_type="pootle_untracked")
@pytest.mark.django_db
def test_fs_response_store_fs_items(settings, tmpdir):
settings.POOTLE_FS_WORKING_PATH = os.path.join(str(tmpdir),
"fs_response_test")
project = Project.objects.get(code="project0")
fs_ahead = []
for i in range(0, 2):
pootle_path = "/language0/%s/fs_ahead_%s.po" % (project.code, i)
fs_path = "/some/fs/fs_ahead_%s.po" % i
fs_ahead.append(
StoreFS.objects.create(
store=Store.objects.create_by_path(pootle_path),
path=fs_path))
_test_fs_response(
fs_ahead=fs_ahead,
action_type="pulled_to_pootle",
state_type="fs_ahead")
@pytest.mark.django_db
def test_fs_response_store_fs_no_store_items(settings, tmpdir):
settings.POOTLE_FS_WORKING_PATH = os.path.join(str(tmpdir),
"fs_response_test")
project = Project.objects.get(code="project0")
fs_staged = []
for i in range(0, 2):
pootle_path = "/language0/%s/fs_staged_%s.po" % (project.code, i)
fs_path = "/some/fs/fs_staged_%s.po" % i
fs_staged.append(
StoreFS.objects.create(
pootle_path=pootle_path,
path=fs_path))
_test_fs_response(
fs_staged=fs_staged,
action_type="pulled_to_pootle",
state_type="fs_staged")
| 6,884
|
Python
|
.py
| 172
| 32.273256
| 78
| 0.630878
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,081
|
files.py
|
translate_pootle/tests/pootle_fs/files.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import os
from mock import PropertyMock, patch
import pytest
from translate.storage.factory import getclass
from django.contrib.auth import get_user_model
from pootle_fs.files import FSFile
from pootle_statistics.models import SubmissionTypes
from pootle_store.constants import POOTLE_WINS
class MockProject(object):
local_fs_path = "LOCAL_FS_PATH"
code = 'project0'
class MockStoreFS(object):
pootle_path = "/language0/project0/example.po"
path = "/some/fs/example.po"
project = MockProject()
store = None
last_sync_hash = None
last_sync_revision = None
def test_wrap_store_fs_bad(settings, tmpdir):
with pytest.raises(TypeError):
FSFile("NOT A STORE_FS")
@patch("pootle_fs.files.FSFile._validate_store_fs")
def test_wrap_store_fs(valid_mock, settings, tmpdir):
"""Add a store_fs for a store that doesnt exist yet"""
settings.POOTLE_FS_WORKING_PATH = os.path.join(str(tmpdir), "fs_file_test")
valid_mock.side_effect = lambda x: x
store_fs = MockStoreFS()
fs_file = FSFile(store_fs)
assert (
fs_file.file_path
== os.path.join(
store_fs.project.local_fs_path,
store_fs.path.strip("/")))
assert fs_file.file_exists is False
assert fs_file.latest_hash is None
assert fs_file.pootle_changed is False
assert fs_file.fs_changed is False
assert fs_file.store is None
assert fs_file.store_exists is False
assert fs_file.deserialize() is None
assert fs_file.serialize() is None
assert str(fs_file) == "<FSFile: %s::%s>" % (fs_file.pootle_path, fs_file.path)
assert hash(fs_file) == hash(
"%s::%s::%s::%s"
% (fs_file.path,
fs_file.pootle_path,
fs_file.store_fs.last_sync_hash,
fs_file.store_fs.last_sync_revision))
assert fs_file == FSFile(store_fs)
testdict = {}
testdict[fs_file] = "foo"
testdict[FSFile(store_fs)] = "bar"
assert len(testdict.keys()) == 1
assert testdict.values()[0] == "bar"
@patch("pootle_fs.files.FSFile._validate_store_fs")
def test_wrap_store_fs_with_store(valid_mock):
valid_mock.side_effect = lambda x: x
store_mock = PropertyMock()
store_mock.configure_mock(
**{"data.max_unit_revision": 23,
"serialize.return_value": 73})
store_fs = MockStoreFS()
store_fs.store = store_mock
fs_file = FSFile(store_fs)
assert (
fs_file.file_path
== os.path.join(
store_fs.project.local_fs_path,
store_fs.path.strip("/")))
assert fs_file.file_exists is False
assert fs_file.latest_hash is None
assert fs_file.fs_changed is False
assert fs_file.pootle_changed is True
assert fs_file.store is store_mock
assert fs_file.store_exists is True
assert fs_file.serialize() == 73
assert fs_file.deserialize() is None
@patch("pootle_fs.files.FSFile._validate_store_fs")
@patch("pootle_fs.files.FSFile.latest_hash")
@patch("pootle_fs.files.os.path.exists")
def test_wrap_store_fs_with_file(path_mock, hash_mock, valid_mock):
valid_mock.side_effect = lambda x: x
path_mock.return_value = True
hash_mock.return_value = 23
store_fs = MockStoreFS()
store_fs.last_sync_hash = 73
fs_file = FSFile(store_fs)
assert fs_file.pootle_changed is False
assert fs_file.fs_changed is True
assert fs_file.file_exists is True
@pytest.mark.django_db
def test_wrap_store_fs_push_no_store(store_fs_file):
fs_file = store_fs_file
assert fs_file.store_fs.last_sync_revision is None
assert fs_file.store_fs.last_sync_hash is None
# does nothing there is no store
hashed = fs_file.latest_hash
fs_file.push()
assert fs_file.latest_hash == hashed
assert fs_file.store_fs.last_sync_hash is None
@pytest.mark.django_db
def test_wrap_store_fs_push(store_fs_file_store):
fs_file = store_fs_file_store
fs_file.push()
assert fs_file.file_exists is True
assert fs_file.read()
# after push the store and fs should always match
assert fs_file.read() == fs_file.serialize()
# pushing again does nothing once the Store and file are synced
fs_file.on_sync(
fs_file.latest_hash, fs_file.store.data.max_unit_revision)
fs_file.push()
assert fs_file.read() == fs_file.serialize()
@pytest.mark.django_db
def test_wrap_store_fs_pull(store_fs_file):
fs_file = store_fs_file
fs_file.pull()
assert fs_file.store
assert fs_file.serialize()
unit_count = fs_file.store.units.count()
assert unit_count == len(fs_file.deserialize().units) - 1
# pulling again will do nothing once the Store and file are synced
fs_file.on_sync(
fs_file.latest_hash, fs_file.store.data.max_unit_revision)
fs_file.pull()
assert unit_count == len(fs_file.deserialize().units) - 1
@pytest.mark.django_db
def test_wrap_store_fs_read(store_fs_file):
fs_file = store_fs_file
with open(fs_file.file_path, "r") as src:
assert fs_file.read() == src.read()
fs_file.remove_file()
assert fs_file.read() is None
@pytest.mark.django_db
def test_wrap_store_fs_remove_file(store_fs_file):
fs_file = store_fs_file
fs_file.remove_file()
assert fs_file.file_exists is False
@pytest.mark.django_db
def test_wrap_store_fs_delete(store_fs_file_store):
fs_file = store_fs_file_store
fs_file.push()
assert fs_file.store
assert fs_file.file_exists is True
fs_file.delete()
assert fs_file.store.obsolete is True
assert fs_file.file_exists is False
assert fs_file.store_fs.pk is None
@pytest.mark.django_db
def test_wrap_store_fs_readd(store_fs_file_store):
fs_file = store_fs_file_store
fs_file.push()
fs_file.store.makeobsolete()
fs_file.pull()
assert not fs_file.store.obsolete
@pytest.mark.django_db
def test_wrap_store_fs_bad_stage(store_fs_file_store, caplog):
fs_file = store_fs_file_store
fs_file._sync_to_pootle()
rec = caplog.records.pop()
assert "disappeared" in rec.message
assert rec.levelname == "WARNING"
@pytest.mark.django_db
def test_wrap_store_fs_create_store(store_fs_file):
fs_file = store_fs_file
assert fs_file.store is None
assert fs_file.store_exists is False
fs_file.create_store()
assert fs_file.store.pootle_path == fs_file.pootle_path
assert fs_file.store_fs.store == fs_file.store
assert fs_file.store.fs.get() == fs_file.store_fs
@pytest.mark.django_db
def test_wrap_store_fs_on_sync(store_fs_file_store):
fs_file = store_fs_file_store
fs_file.pull()
fs_file.on_sync(
fs_file.latest_hash, fs_file.store.data.max_unit_revision)
fs_file.store_fs.resolve_conflict = None
fs_file.store_fs.staged_for_merge = False
fs_file.store_fs.last_sync_hash = fs_file.latest_hash
fs_file.store_fs.last_sync_revision = fs_file.store.get_max_unit_revision()
@pytest.mark.django_db
def test_wrap_store_fs_pull_merge_pootle_wins(store_fs_file):
fs_file = store_fs_file
fs_file.pull()
unit = fs_file.store.units[0]
unit.target = "FOO"
unit.save()
with open(fs_file.file_path, "r+") as target:
ttk = getclass(target)(target.read())
target.seek(0)
ttk.units[1].target = "BAR"
target.write(str(ttk))
target.truncate()
assert fs_file.fs_changed is True
assert fs_file.pootle_changed is True
# this ensures POOTLE_WINS
fs_file.store_fs.resolve_conflict = POOTLE_WINS
fs_file.pull(merge=True)
assert fs_file.store.units[0].target == "FOO"
assert fs_file.store.units[0].get_suggestions()[0].target == "BAR"
@pytest.mark.django_db
def test_wrap_store_fs_pull_merge_pootle_wins_again(store_fs_file):
fs_file = store_fs_file
fs_file.pull()
unit = fs_file.store.units[0]
unit.target = "FOO"
unit.save()
with open(fs_file.file_path, "r+") as target:
ttk = getclass(target)(target.read())
target.seek(0)
ttk.units[1].target = "BAR"
target.write(str(ttk))
target.truncate()
assert fs_file.fs_changed is True
assert fs_file.pootle_changed is True
fs_file.pull(merge=True, pootle_wins=True)
assert fs_file.store.units[0].target == "FOO"
assert fs_file.store.units[0].get_suggestions()[0].target == "BAR"
@pytest.mark.django_db
def test_wrap_store_fs_pull_merge_fs_wins(store_fs_file):
fs_file = store_fs_file
fs_file.pull()
unit = fs_file.store.units[0]
unit.target = "FOO"
unit.save()
with open(fs_file.file_path, "r+") as target:
ttk = getclass(target)(target.read())
target.seek(0)
ttk.units[1].target = "BAR"
target.write(str(ttk))
target.truncate()
assert fs_file.fs_changed is True
assert fs_file.pootle_changed is True
fs_file.pull(merge=True)
assert fs_file.store.units[0].target == "BAR"
assert fs_file.store.units[0].get_suggestions()[0].target == "FOO"
@pytest.mark.django_db
def test_wrap_store_fs_pull_merge_fs_wins_again(store_fs_file):
fs_file = store_fs_file
fs_file.pull()
unit = fs_file.store.units[0]
unit.target = "FOO"
unit.save()
with open(fs_file.file_path, "r+") as target:
ttk = getclass(target)(target.read())
target.seek(0)
ttk.units[1].target = "BAR"
target.write(str(ttk))
target.truncate()
assert fs_file.fs_changed is True
assert fs_file.pootle_changed is True
fs_file.pull(merge=True, pootle_wins=False)
assert fs_file.store.units[0].target == "BAR"
assert fs_file.store.units[0].get_suggestions()[0].target == "FOO"
@pytest.mark.django_db
def test_wrap_store_fs_pull_merge_default(store_fs_file):
fs_file = store_fs_file
fs_file.pull()
unit = fs_file.store.units[0]
unit.target = "FOO"
unit.save()
with open(fs_file.file_path, "r+") as target:
ttk = getclass(target)(target.read())
target.seek(0)
ttk.units[1].target = "BAR"
target.write(str(ttk))
target.truncate()
assert fs_file.fs_changed is True
assert fs_file.pootle_changed is True
fs_file.pull(merge=True)
assert fs_file.store.units[0].target == "BAR"
assert fs_file.store.units[0].get_suggestions()[0].target == "FOO"
@pytest.mark.django_db
def test_wrap_store_fs_pull_submission_type(store_fs_file_store):
fs_file = store_fs_file_store
fs_file.push()
with open(fs_file.file_path, "r+") as target:
ttk = getclass(target)(target.read())
target.seek(0)
ttk.units[1].target = "BAR"
target.write(str(ttk))
target.truncate()
fs_file.pull()
assert (
fs_file.store.units[0].submission_set.latest().type
== SubmissionTypes.SYSTEM)
@patch("pootle_fs.files.FSFile.latest_author", new_callable=PropertyMock)
@patch("pootle_fs.files.FSFile.plugin", new_callable=PropertyMock)
@patch("pootle_fs.files.User.objects", new_callable=PropertyMock)
def test_fs_file_latest_author(user_mock, plugin_mock, author_mock):
user_mock.configure_mock(
**{"return_value.get.return_value": 73})
author_mock.return_value = None, None
plugin_mock.configure_mock(
**{"return_value.pootle_user": 23})
User = get_user_model()
class DummyFile(FSFile):
def __init__(self):
pass
myfile = DummyFile()
assert myfile.latest_user == 23
author_mock.return_value = 7, None
assert myfile.latest_user == 23
author_mock.return_value = None, 7
assert myfile.latest_user == 23
author_mock.return_value = 7, 17
assert myfile.latest_user == 73
assert (
list(user_mock.return_value.get.call_args)
== [(), {'email': 17}])
user_mock.return_value.get.side_effect = User.DoesNotExist
assert myfile.latest_user == 23
assert (
[list(l) for l in user_mock.return_value.get.call_args_list]
== [[(), {'email': 17}],
[(), {'email': 17}],
[(), {'username': 7}]])
| 12,278
|
Python
|
.py
| 326
| 32.355828
| 83
| 0.676396
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,082
|
matcher.py
|
translate_pootle/tests/pootle_fs/matcher.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import os
import random
import sys
from collections import OrderedDict
import pytest
from django.urls import resolve
from pootle_fs.finder import TranslationFileFinder
from pootle_fs.matcher import FSPathMatcher
from pootle_language.models import Language
from pootle_project.models import Project
from pootle_project.lang_mapper import ProjectLanguageMapper
from pootle_store.models import Store
TEST_LANG_MAPPING = OrderedDict(
[["en_FOO", "en"],
["language0_FOO", "language0"],
["language1_FOO", "language1"]])
TEST_LANG_MAPPING_BAD = OrderedDict(
[["en_FOO", "en"],
["language0_FOO", "language0"],
["language1_FOO", "language1 XXX"]])
class DummyFinder(TranslationFileFinder):
@property
def dummy_paths(self):
paths = []
for pootle_path in self.pootle_paths:
match = resolve(pootle_path).kwargs
excluded_languages = self.project.config.get(
"pootle.fs.excluded_languages", [])
if match["language_code"] in excluded_languages:
continue
match["filename"], match["ext"] = os.path.splitext(
match["filename"])
match["ext"] = match["ext"][1:]
dir_path = (
"%s/" % match["dir_path"]
if match["dir_path"]
else "")
fs_path = (
"/path/to/%s/%s/%s%s.%s"
% (self.project.code,
match["language_code"],
dir_path,
match["filename"],
match["ext"]))
paths.append((fs_path, match))
return paths
def find(self):
return self.dummy_paths
class DummyContext(object):
def __init__(self, project):
self.project = project
@property
def latest_hash(self):
return hash(random.random())
@property
def finder_class(self):
project = self.project
pootle_paths = list(
Store.objects.filter(translation_project__project=self.project)
.values_list("pootle_path", flat=True))
class DummyFinderClosure(DummyFinder):
def __init__(self, *args, **kwargs):
self.project = project
self.pootle_paths = pootle_paths
super(DummyFinderClosure, self).__init__(*args, **kwargs)
return DummyFinderClosure
@pytest.mark.django_db
@pytest.mark.xfail(sys.platform == 'win32',
reason="path mangling broken on windows")
def test_matcher_instance(settings):
settings.POOTLE_FS_WORKING_PATH = os.sep.join(['', 'path', 'to'])
translation_mapping = "<language_code>/<dir_path>/<filename>.<ext>"
project = Project.objects.get(code="project0")
project.config[
"pootle_fs.translation_mappings"] = dict(default=translation_mapping)
context = DummyContext(project)
matcher = FSPathMatcher(context)
assert matcher.project == project
assert matcher.root_directory == project.local_fs_path
assert matcher.translation_mapping == os.path.join(
project.local_fs_path, translation_mapping.lstrip("/"))
@pytest.mark.django_db
@pytest.mark.xfail(sys.platform == 'win32',
reason="path mangling broken on windows")
def test_matcher_finder(settings):
settings.POOTLE_FS_WORKING_PATH = os.sep.join(['', 'path', 'to'])
project = Project.objects.get(code="project0")
project.config["pootle_fs.translation_mappings"] = dict(
default="/<language_code>/<dir_path>/<filename>.<ext>")
matcher = FSPathMatcher(DummyContext(project))
finder = matcher.get_finder()
assert isinstance(finder, DummyFinder)
assert finder.translation_mapping == matcher.translation_mapping
finder = matcher.get_finder(fs_path="bar")
assert finder.translation_mapping == matcher.translation_mapping
assert finder.path_filters == ["bar"]
@pytest.mark.django_db
def test_matcher_get_lang():
project = Project.objects.get(code="project0")
project.config["pootle_fs.translation_mappings"] = dict(
default="/path/to/<language_code>/<dir_path>/<filename>.<ext>")
project.config["pootle.core.lang_mapping"] = {
"upstream-language0": "language0"}
matcher = FSPathMatcher(DummyContext(project))
assert (
matcher.get_language("upstream-language0")
== Language.objects.get(code="language0"))
@pytest.mark.django_db
def test_matcher_make_pootle_path(settings):
settings.POOTLE_FS_WORKING_PATH = os.sep.join(['', 'path', 'to'])
project = Project.objects.get(code="project0")
project.config["pootle_fs.translation_mappings"] = dict(
default="/path/to/<language_code>/<dir_path>/<filename>.<ext>")
matcher = FSPathMatcher(DummyContext(project))
assert matcher.make_pootle_path() is None
# must provide language_code, filename and ext at a min
assert matcher.make_pootle_path(language_code="foo") is None
assert (
matcher.make_pootle_path(language_code="foo", filename="bar")
is None)
assert (
matcher.make_pootle_path(language_code="foo", ext="baz")
is None)
assert (
matcher.make_pootle_path(
language_code="foo", filename="bar", ext="baz")
== "/foo/%s/bar.baz" % project.code)
assert (
matcher.make_pootle_path(
language_code="foo", filename="bar", ext="baz", dir_path="sub/dir")
== u'/foo/%s/sub/dir/bar.baz' % project.code)
assert (
matcher.make_pootle_path(
language_code="foo", filename="bar", ext="baz", dir_path="sub/dir/")
== u'/foo/%s/sub/dir/bar.baz' % project.code)
assert (
matcher.make_pootle_path(
language_code="foo", filename="bar", ext="baz", dir_path="/sub/dir")
== u'/foo/%s/sub/dir/bar.baz' % project.code)
@pytest.mark.django_db
def test_matcher_match_pootle_path(settings):
settings.POOTLE_FS_WORKING_PATH = os.sep.join(['', 'path', 'to'])
project = Project.objects.get(code="project0")
project.config["pootle_fs.translation_mappings"] = dict(
default="/path/to/<language_code>/<dir_path>/<filename>.<ext>")
matcher = FSPathMatcher(DummyContext(project))
assert matcher.match_pootle_path(language_code="foo") is None
assert (
matcher.match_pootle_path(language_code="foo", filename="bar")
is None)
assert (
matcher.match_pootle_path(language_code="foo", ext="baz")
is None)
assert (
matcher.match_pootle_path(
language_code="foo", filename="bar", ext="baz")
== "/foo/%s/bar.baz" % project.code)
assert (
matcher.match_pootle_path(
language_code="foo", filename="bar", ext="baz", dir_path="sub/dir")
== u'/foo/%s/sub/dir/bar.baz' % project.code)
assert (
matcher.match_pootle_path(
language_code="foo", filename="bar", ext="baz", dir_path="sub/dir/")
== u'/foo/%s/sub/dir/bar.baz' % project.code)
assert (
matcher.match_pootle_path(
language_code="foo", filename="bar", ext="baz", dir_path="/sub/dir")
== u'/foo/%s/sub/dir/bar.baz' % project.code)
assert (
matcher.match_pootle_path(
pootle_path_match="/foo*",
language_code="foo", filename="bar", ext="baz", dir_path="/sub/dir")
== u'/foo/%s/sub/dir/bar.baz' % project.code)
assert (
matcher.match_pootle_path(
pootle_path_match="*sub/dir/*",
language_code="foo", filename="bar", ext="baz", dir_path="/sub/dir")
== u'/foo/%s/sub/dir/bar.baz' % project.code)
assert (
matcher.match_pootle_path(
pootle_path_match="*/bar.baz",
language_code="foo", filename="bar", ext="baz", dir_path="/sub/dir")
== u'/foo/%s/sub/dir/bar.baz' % project.code)
assert (
matcher.match_pootle_path(
pootle_path_match="/foo",
language_code="foo", filename="bar", ext="baz", dir_path="/sub/dir")
is None)
@pytest.mark.django_db
@pytest.mark.xfail(sys.platform == 'win32',
reason="path mangling broken on windows")
def test_matcher_relative_path(settings):
settings.POOTLE_FS_WORKING_PATH = os.sep.join(['', 'path', 'to'])
project = Project.objects.get(code="project0")
project.config["pootle_fs.translation_mappings"] = dict(
default="/path/to/<language_code>/<dir_path>/<filename>.<ext>")
matcher = FSPathMatcher(DummyContext(project))
assert matcher.relative_path("/foo/bar") is "/foo/bar"
assert (
matcher.relative_path(os.path.join(matcher.root_directory, "foo/bar"))
== "/foo/bar")
assert (
matcher.relative_path(
os.path.join(
"/foo/bar",
matcher.root_directory.lstrip("/"),
"foo/bar"))
== os.path.join(
"/foo/bar",
matcher.root_directory.lstrip("/"),
"foo/bar"))
assert (
matcher.relative_path(
os.path.join(
matcher.root_directory,
"foo/bar",
matcher.root_directory.lstrip("/"),
"foo/bar"))
== os.path.join(
"/foo/bar",
matcher.root_directory.lstrip("/"),
"foo/bar"))
@pytest.mark.django_db
@pytest.mark.xfail(sys.platform == 'win32',
reason="path mangling broken on windows")
def test_matcher_matches(settings):
settings.POOTLE_FS_WORKING_PATH = os.sep.join(['', 'path', 'to'])
project = Project.objects.get(code="project0")
project.config["pootle_fs.translation_mappings"] = dict(
default="/some/other/path/<language_code>/<dir_path>/<filename>.<ext>")
matcher = FSPathMatcher(DummyContext(project))
finder = matcher.get_finder()
matches = []
for file_path, matched in finder.dummy_paths:
language = matcher.get_language(matched["language_code"])
matched["language_code"] = language.code
matches.append(
(matcher.match_pootle_path(**matched),
matcher.relative_path(file_path)))
assert matches == list(matcher.matches(None, None))
@pytest.mark.django_db
@pytest.mark.xfail(sys.platform == 'win32',
reason="path mangling broken on windows")
def test_matcher_matches_missing_langs(settings, caplog, no_templates_tps):
settings.POOTLE_FS_WORKING_PATH = os.sep.join(['', 'path', 'to'])
project = Project.objects.get(code="project0")
project.config["pootle_fs.translation_mappings"] = dict(
default="/some/other/path/<language_code>/<dir_path>/<filename>.<ext>")
project.config["pootle.core.lang_mapping"] = {
"language0": "language0-DOES_NOT_EXIST",
"language1": "language1-DOES_NOT_EXIST"}
matcher = FSPathMatcher(DummyContext(project))
assert list(matcher.matches(None, None)) == []
assert (
"Could not import files for languages: language0, language1"
in caplog.text)
@pytest.mark.django_db
@pytest.mark.xfail(sys.platform == 'win32',
reason="path mangling broken on windows")
def test_matcher_reverse_match(settings):
settings.POOTLE_FS_WORKING_PATH = os.sep.join(['', 'path', 'to'])
project = Project.objects.get(code="project0")
project.config["pootle_fs.translation_mappings"] = dict(
default="/<language_code>/<dir_path>/<filename>.<ext>")
project.config["pootle.core.lang_mapping"] = {
"upstream-foo": "foo"}
matcher = FSPathMatcher(DummyContext(project))
assert (
matcher.reverse_match("/foo/%s/bar.po" % project.code)
== "/upstream-foo/bar.po")
assert (
matcher.reverse_match("/foo/%s/some/path/bar.po" % project.code)
== "/upstream-foo/some/path/bar.po")
with pytest.raises(ValueError):
matcher.reverse_match("/foo/%s/bar.not" % project.code)
@pytest.mark.django_db
def test_matcher_language_mapper(english, settings):
settings.POOTLE_FS_WORKING_PATH = os.sep.join(['', 'path', 'to'])
project = Project.objects.get(code="project0")
matcher = FSPathMatcher(DummyContext(project))
assert "pootle.core.lang_mapping" not in project.config
assert isinstance(matcher.lang_mapper, ProjectLanguageMapper)
assert matcher.lang_mapper.lang_mappings == {}
assert matcher.lang_mapper["en_FOO"] is None
assert matcher.lang_mapper.get_pootle_code("en") == "en"
assert matcher.lang_mapper.get_pootle_code("en_FOO") == "en_FOO"
assert matcher.lang_mapper.get_upstream_code("en") == "en"
project.config["pootle.core.lang_mapping"] = TEST_LANG_MAPPING
assert matcher.lang_mapper.lang_mappings == {}
matcher = FSPathMatcher(DummyContext(project))
assert matcher.lang_mapper.lang_mappings == TEST_LANG_MAPPING
assert "en_FOO" in matcher.lang_mapper
assert matcher.lang_mapper["en_FOO"] == english
@pytest.mark.django_db
def test_matcher_language_mapper_bad(settings):
settings.POOTLE_FS_WORKING_PATH = os.sep.join(['', 'path', 'to'])
project = Project.objects.get(code="project0")
language1 = Language.objects.get(code="language1")
project.config["pootle.core.lang_mapping"] = TEST_LANG_MAPPING_BAD
# bad configuration lines are ignored
matcher = FSPathMatcher(DummyContext(project))
assert "language1_FOO" not in matcher.lang_mapper
assert matcher.lang_mapper["language1_FOO"] is None
assert matcher.lang_mapper["language1"] == language1
@pytest.mark.django_db
@pytest.mark.xfail(sys.platform == 'win32',
reason="path mangling broken on windows")
def test_matcher_matches_excluded_langs(settings, caplog, project0, language0):
settings.POOTLE_FS_WORKING_PATH = os.sep.join(['', 'path', 'to'])
project0.config["pootle_fs.translation_mappings"] = dict(
default="/some/other/path/<language_code>/<dir_path>/<filename>.<ext>")
project0.config["pootle.fs.excluded_languages"] = [language0.code]
matcher = FSPathMatcher(DummyContext(project0))
assert matcher.excluded_languages == [language0.code]
assert matcher.get_finder().exclude_languages == [language0.code]
assert not any(
m[0].startswith("/%s/" % language0.code)
for m in matcher.matches(None, None))
@pytest.mark.django_db
@pytest.mark.xfail(sys.platform == 'win32',
reason="path mangling broken on windows")
def test_matcher_matches_excluded_mapped_langs(settings, caplog,
project0, language0):
settings.POOTLE_FS_WORKING_PATH = os.sep.join(['', 'path', 'to'])
project0.config["pootle_fs.translation_mappings"] = dict(
default="/some/other/path/<language_code>/<dir_path>/<filename>.<ext>")
project0.config["pootle.fs.excluded_languages"] = [language0.code]
project0.config["pootle.core.lang_mapping"] = OrderedDict(
[["%s_FOO" % language0.code, language0.code]])
matcher = FSPathMatcher(DummyContext(project0))
assert matcher.excluded_languages == ["%s_FOO" % language0.code]
assert matcher.get_finder().exclude_languages == ["%s_FOO" % language0.code]
assert not any(
m[0].startswith("/%s/" % language0.code)
for m in matcher.matches(None, None))
assert matcher.matches(None, None)
| 15,636
|
Python
|
.py
| 345
| 37.730435
| 80
| 0.64401
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,083
|
decorators.py
|
translate_pootle/tests/pootle_fs/decorators.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import pytest
from django.dispatch import receiver
from pootle.core.state import State
from pootle.core.response import Response
from pootle_fs.decorators import emits_state, responds_to_state
from pootle_fs.signals import (
fs_post_pull, fs_post_push, fs_pre_pull, fs_pre_push)
class PluginState(State):
pass
class PluginResponse(Response):
pass
class DummyPlugin(object):
def state(self, **kwargs):
return PluginState(self, **kwargs)
def response(self, state, **kwargs):
return PluginResponse(state, **kwargs)
class MyPlugin(DummyPlugin):
@responds_to_state
def respond_to_state(self, state, response, **kwargs):
return state, response, kwargs
@emits_state(pre=fs_pre_pull)
def emit_state_pre(self, state, response, **kwargs):
return state, response, kwargs
@emits_state(pre=fs_post_pull)
def emit_state_post(self, state, response, **kwargs):
return state, response, kwargs
@emits_state(pre=fs_pre_push, post=fs_post_push)
def emit_state_both(self, state, response, **kwargs):
return state, response, kwargs
@pytest.mark.django_db
def test_fs_deco_emits_pre():
plugin = MyPlugin()
plugin_state = plugin.state()
plugin_response = plugin.response(plugin_state)
class Emitted(object):
pass
emitted = Emitted()
@receiver(fs_pre_pull)
def received(state, response, **kwargs):
emitted.state = state
emitted.response = response
emitted.kwargs = kwargs
state, response, kwargs = plugin.emit_state_pre(
plugin_state, plugin_response, foo="bar")
assert state is emitted.state is plugin_state
assert response is emitted.response is plugin_response
assert kwargs == dict(foo="bar")
assert emitted.kwargs["plugin"] == plugin
assert emitted.kwargs["sender"] == plugin.__class__
@pytest.mark.django_db
def test_fs_deco_emits_post():
plugin = MyPlugin()
plugin_state = plugin.state()
plugin_response = plugin.response(plugin_state)
class Emitted(object):
pass
emitted = Emitted()
@receiver(fs_post_pull)
def received(state, response, **kwargs):
emitted.state = state
emitted.response = response
emitted.kwargs = kwargs
state, response, kwargs = plugin.emit_state_post(
plugin_state, plugin_response, foo="bar")
assert state is emitted.state is plugin_state
assert response is emitted.response is plugin_response
assert kwargs == dict(foo="bar")
assert emitted.kwargs["plugin"] == plugin
assert emitted.kwargs["sender"] == plugin.__class__
@pytest.mark.django_db
def test_fs_deco_emits_both():
plugin = MyPlugin()
plugin_state = plugin.state()
plugin_response = plugin.response(plugin_state)
class Emitted(object):
pass
emitted_pre = Emitted()
emitted_post = Emitted()
@receiver(fs_pre_push)
def received_pre(state, response, **kwargs):
emitted_pre.state = state
emitted_pre.response = response
emitted_pre.kwargs = kwargs
@receiver(fs_post_push)
def received_post(state, response, **kwargs):
emitted_post.state = state
emitted_post.response = response
emitted_post.kwargs = kwargs
state, response, kwargs = plugin.emit_state_both(
plugin_state, plugin_response, foo="bar")
assert (
state is emitted_pre.state
is emitted_post.state
is plugin_state)
assert (
response is emitted_pre.response
is emitted_post.response
is plugin_response)
assert kwargs == dict(foo="bar")
assert emitted_pre.kwargs["plugin"] == plugin
assert emitted_pre.kwargs["sender"] == plugin.__class__
assert emitted_post.kwargs["plugin"] == plugin
assert emitted_post.kwargs["sender"] == plugin.__class__
@pytest.mark.django_db
def test_fs_deco_responds_to_state():
plugin = MyPlugin()
state, response, kwargs = plugin.respond_to_state()
assert isinstance(state, PluginState)
assert isinstance(response, PluginResponse)
assert state.context == plugin
assert response.context == state
assert state.kwargs["pootle_path"] is None
assert state.kwargs["fs_path"] is None
assert len(kwargs) == 0
assert len(state.kwargs) == 2
@pytest.mark.django_db
def test_fs_deco_responds_to_state_pootle_path():
plugin = MyPlugin()
state, response, kwargs = plugin.respond_to_state(pootle_path="/foo")
assert state.kwargs["pootle_path"] == "/foo"
assert state.kwargs["fs_path"] is None
assert kwargs["pootle_path"] == "/foo"
assert len(kwargs) == 1
assert len(state.kwargs) == 2
@pytest.mark.django_db
def test_fs_deco_responds_to_state_fs_path():
plugin = MyPlugin()
state, response, kwargs = plugin.respond_to_state(fs_path="/foo")
assert state.kwargs["pootle_path"] is None
assert state.kwargs["fs_path"] == "/foo"
assert kwargs["fs_path"] == "/foo"
assert len(kwargs) == 1
assert len(state.kwargs) == 2
@pytest.mark.django_db
def test_fs_deco_responds_to_state_kwargs():
plugin = MyPlugin()
state, response, kwargs = plugin.respond_to_state(foo="/foo")
assert state.kwargs["pootle_path"] is None
assert state.kwargs["fs_path"] is None
assert kwargs["foo"] == "/foo"
assert len(kwargs) == 1
assert len(state.kwargs) == 2
@pytest.mark.django_db
def test_fs_deco_responds_to_state_w_state():
plugin = MyPlugin()
plugin_state = plugin.state()
state, response, kwargs = plugin.respond_to_state(
foo="/foo", state=plugin_state)
assert plugin_state is state
assert "state" not in kwargs
assert "state" not in state.kwargs
state, response, kwargs = plugin.respond_to_state(
plugin_state, foo="/foo")
assert plugin_state is state
assert "state" not in kwargs
assert "state" not in state.kwargs
@pytest.mark.django_db
def test_fs_deco_responds_to_state_w_response():
plugin = MyPlugin()
plugin_state = plugin.state()
plugin_response = plugin.response(plugin_state)
state, response, kwargs = plugin.respond_to_state(
foo="/foo", response=plugin_response)
assert plugin_response is response
assert "response" not in kwargs
assert "response" not in state.kwargs
state, response, kwargs = plugin.respond_to_state(
plugin_state, plugin_response, foo="/foo")
assert plugin_response is response
assert "response" not in kwargs
assert "response" not in state.kwargs
@pytest.mark.django_db
def test_fs_deco_responds_to_state_w_state_response():
plugin = MyPlugin()
plugin_state = plugin.state()
plugin_response = plugin.response(plugin_state)
state, response, kwargs = plugin.respond_to_state(
foo="/foo", state=plugin_state, response=plugin_response)
assert plugin_response is response
assert "response" not in kwargs
assert "response" not in state.kwargs
assert plugin_state is state
assert "state" not in kwargs
assert "state" not in state.kwargs
state, response, kwargs = plugin.respond_to_state(
plugin_state, foo="/foo", response=plugin_response)
assert plugin_response is response
assert "response" not in kwargs
assert "response" not in state.kwargs
assert plugin_state is state
assert "state" not in kwargs
assert "state" not in state.kwargs
state, response, kwargs = plugin.respond_to_state(
plugin_state, plugin_response, foo="/foo")
assert plugin_response is response
assert "response" not in kwargs
assert "response" not in state.kwargs
assert plugin_state is state
assert "state" not in kwargs
assert "state" not in state.kwargs
| 8,044
|
Python
|
.py
| 208
| 33.427885
| 77
| 0.697597
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,084
|
delegate.py
|
translate_pootle/tests/pootle_fs/delegate.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import pytest
from pootle.core.plugin import provider
from pootle_fs.delegate import fs_plugins
from pootle_fs.localfs import LocalFSPlugin
from pootle_fs.plugin import Plugin
@pytest.mark.django_db
def test_local_plugin_provider():
assert fs_plugins.gather()["localfs"] == LocalFSPlugin
@pytest.mark.django_db
def test_plugin_providers():
class CustomPlugin(Plugin):
pass
@provider(fs_plugins)
def custom_fs_plugin(**kwargs):
return dict(custom=CustomPlugin)
assert fs_plugins.gather()["custom"] == CustomPlugin
| 833
|
Python
|
.py
| 23
| 33.26087
| 77
| 0.761548
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,085
|
fs.py
|
translate_pootle/tests/pootle_fs/commands/fs.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import os
import shutil
import sys
import pytest
from pytest_pootle.factories import ProjectDBFactory
from django.core.management import call_command, CommandError
from pootle.core.delegate import config
from pootle.core.exceptions import NotConfiguredError, MissingPluginError
from pootle_fs.display import ResponseDisplay, StateDisplay
from pootle_fs.management.commands import FSAPISubCommand
from pootle_fs.management.commands.fs_commands.state import StateCommand
from pootle_fs.utils import FSPlugin
from pootle_project.models import Project
@pytest.mark.django_db
def test_fs_cmd(project_fs, capsys):
call_command("fs")
out, err = capsys.readouterr()
expected = []
for project in Project.objects.order_by("pk"):
try:
plugin = FSPlugin(project)
expected.append(
"%s\t%s"
% (project.code, plugin.fs_url))
except (MissingPluginError, NotConfiguredError):
pass
expected = (
"%s\n"
% '\n'.join(expected))
assert out == expected
@pytest.mark.django_db
def test_fs_cmd_info(project_fs, capsys):
call_command("fs", "info", project_fs.project.code)
out, err = capsys.readouterr()
lines = []
lines.append(
"Project: %s"
% project_fs.project.code)
lines.append("type: %s" % project_fs.fs_type)
lines.append("URL: %s" % project_fs.fs_url)
assert out == "%s\n" % ("\n".join(lines))
@pytest.mark.django_db
def test_fs_cmd_no_projects(capsys):
for project in Project.objects.all():
conf = config.get(Project, instance=project)
conf.clear_config("pootle_fs.fs_type")
conf.clear_config("pootle_fs.fs_url")
call_command("fs")
out, err = capsys.readouterr()
assert out == "No projects configured\n"
@pytest.mark.django_db
def test_fs_cmd_bad_project(project_fs, capsys, english):
with pytest.raises(CommandError):
call_command(
"fs", "state", "BAD_PROJECT_CODE")
with pytest.raises(CommandError):
call_command(
"fs", "BAD_SUBCOMMAND", "project0")
with pytest.raises(CommandError):
call_command(
"fs", "state",
ProjectDBFactory(source_language=english).code)
@pytest.mark.django_db
@pytest.mark.xfail(
sys.platform == 'win32',
reason="path mangling broken on windows")
def test_fs_cmd_unstage_response(capsys, localfs_envs):
state_type, plugin = localfs_envs
action = "unstage"
original_state = plugin.state()
call_command("fs", action, plugin.project.code)
out, err = capsys.readouterr()
plugin_response = getattr(plugin, action)(state=original_state)
display = ResponseDisplay(plugin_response)
assert out.strip() == str(display).strip()
@pytest.mark.django_db
def test_fs_cmd_unstage_staged_response(capsys, localfs_staged_envs):
state_type, plugin = localfs_staged_envs
action = "unstage"
original_state = plugin.state()
call_command("fs", action, plugin.project.code)
out, err = capsys.readouterr()
plugin_response = getattr(plugin, action)(
state=original_state)
responses = sorted(
original_state["pootle_ahead"],
key=lambda x: x.pootle_path)
for fs_state in responses:
plugin_response.add("unstaged", fs_state=fs_state)
display = ResponseDisplay(plugin_response)
assert out.strip() == str(display).strip()
@pytest.mark.django_db
def test_fs_cmd_api(capsys, dummy_cmd_response, fs_path_qs, possible_actions):
__, cmd, cmd_args, plugin_kwargs = possible_actions
__, pootle_path, fs_path = fs_path_qs
dummy_response, api_call = dummy_cmd_response
project = dummy_response.context.context.project
if fs_path:
cmd_args += ["-p", fs_path]
if pootle_path:
cmd_args += ["-P", pootle_path]
forceable = ["add", "rm"]
if cmd in forceable and not plugin_kwargs.get("force"):
plugin_kwargs["force"] = False
plugin_kwargs["pootle_path"] = pootle_path
plugin_kwargs["fs_path"] = fs_path
api_call(dummy_response, cmd, **plugin_kwargs)
call_command("fs", cmd, project.code, *cmd_args)
out, err = capsys.readouterr()
assert out == str(ResponseDisplay(dummy_response))
@pytest.mark.django_db
def test_fs_cmd_state(capsys, dummy_cmd_state, fs_path_qs):
__, pootle_path, fs_path = fs_path_qs
plugin, state_class = dummy_cmd_state
project = plugin.project
cmd = "state"
cmd_args = []
plugin_kwargs = {}
if fs_path:
cmd_args += ["-p", fs_path]
if pootle_path:
cmd_args += ["-P", pootle_path]
if pootle_path:
plugin_kwargs["pootle_path"] = pootle_path
if fs_path:
plugin_kwargs["fs_path"] = fs_path
dummy_state = state_class(
plugin, pootle_path=pootle_path, fs_path=fs_path)
call_command("fs", cmd, project.code, *cmd_args)
out, err = capsys.readouterr()
assert out == str(StateDisplay(dummy_state))
@pytest.mark.skipif(sys.platform == 'win32',
reason=("Windows, the native console doesn’t support ANSI "
"escape sequences"))
def test_fs_cmd_state_colors():
state_cmd = StateCommand()
for k, (pootle_style, fs_style) in state_cmd.colormap.items():
if pootle_style:
pootle_style = getattr(state_cmd.style, "FS_%s" % pootle_style)
if fs_style:
fs_style = getattr(state_cmd.style, "FS_%s" % fs_style)
assert state_cmd.get_style(k) == (pootle_style, fs_style)
@pytest.mark.skipif(sys.platform == 'win32',
reason=("Windows, the native console doesn’t support ANSI "
"escape sequences"))
def test_fs_cmd_response_colors():
sub_cmd = FSAPISubCommand()
for k, (pootle_style, fs_style) in sub_cmd.colormap.items():
if pootle_style:
pootle_style = getattr(sub_cmd.style, "FS_%s" % pootle_style)
if fs_style:
fs_style = getattr(sub_cmd.style, "FS_%s" % fs_style)
assert sub_cmd.get_style(k) == (pootle_style, fs_style)
@pytest.mark.django_db
def test_fs_cmd_fetch(capsys, project_fs):
shutil.rmtree(project_fs.project.local_fs_path)
call_command("fs", "fetch", project_fs.project.code)
assert os.path.exists(project_fs.project.local_fs_path)
@pytest.mark.django_db
def test_fs_cmd_add_bad(capsys, project0):
with pytest.raises(CommandError):
call_command("fs", "add", project0.code)
| 6,765
|
Python
|
.py
| 169
| 34.017751
| 79
| 0.667734
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,086
|
init_fs_project.py
|
translate_pootle/tests/pootle_fs/commands/init_fs_project.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import sys
import pytest
from django.core.management import call_command, CommandError
from pootle_fs.utils import FSPlugin
from pootle_project.models import Project
@pytest.mark.django_db
@pytest.mark.cmd
def test_init_fs_project_cmd_bad_lang(capsys):
fs_path = "/test/fs/path"
tr_path = "<language_code>/<filename>.<ext>"
with pytest.raises(CommandError):
call_command("init_fs_project", "foo", fs_path, tr_path, "-l BAD_LANG")
@pytest.mark.django_db
@pytest.mark.cmd
@pytest.mark.xfail(sys.platform == 'win32',
reason="broken on windows")
def test_init_fs_project_cmd_nosync(settings, test_fs, tmpdir, revision):
settings.POOTLE_FS_WORKING_PATH = str(tmpdir)
fs_path = test_fs.path("data/fs/example_fs/non_gnu_style_minimal/")
tr_path = "<language_code>/<filename>.<ext>"
call_command(
"init_fs_project",
"foo",
fs_path,
tr_path,
"--nosync",
"--checkstyle=standard",
"--filetypes=po",
"--source-language=en",
"--name=Foo"
)
project = Project.objects.get(code='foo')
assert project is not None
assert project.code == "foo"
assert project.fullname == "Foo"
assert "po" in project.filetypes.values_list("name", flat=True)
assert project.checkstyle == "standard"
assert project.source_language.code == "en"
assert project.config.get('pootle_fs.fs_type') == 'localfs'
assert project.config.get('pootle_fs.fs_url') == fs_path
assert project.config.get(
'pootle_fs.translation_mappings')['default'] == tr_path
assert project.translationproject_set.all().count() == 0
plugin = FSPlugin(project)
plugin.fetch()
state = plugin.state()
assert "fs_untracked: 1" in str(state)
@pytest.mark.django_db
@pytest.mark.cmd
@pytest.mark.xfail(sys.platform == 'win32',
reason="broken on windows")
def test_init_fs_project_cmd(capsys, settings, test_fs, tmpdir, revision):
settings.POOTLE_FS_WORKING_PATH = str(tmpdir)
fs_path = test_fs.path("data/fs/example_fs/non_gnu_style_minimal/")
tr_path = "<language_code>/<filename>.<ext>"
call_command("init_fs_project", "foo", fs_path, tr_path)
project = Project.objects.get(code='foo')
assert project is not None
assert project.config.get('pootle_fs.fs_type') == 'localfs'
assert project.config.get('pootle_fs.fs_url') == fs_path
assert project.config.get(
'pootle_fs.translation_mappings')['default'] == tr_path
assert project.translationproject_set.all().count() > 0
state = FSPlugin(project).state()
assert "Nothing to report" in str(state)
@pytest.mark.django_db
@pytest.mark.cmd
def test_init_fs_project_cmd_duplicated(capsys):
fs_path = "/test/fs/path"
tr_path = "<language_code>/<filename>.<ext>"
call_command("init_fs_project", "foo", fs_path, tr_path, "--nosync")
project = Project.objects.get(code='foo')
assert project is not None
with pytest.raises(CommandError):
call_command("init_fs_project", "foo", fs_path, tr_path)
@pytest.mark.django_db
@pytest.mark.cmd
def test_cmd_init_fs_project_bad_filetype(capsys):
fs_path = "/test/fs/path"
tr_path = "<language_code>/<filename>.<ext>"
with pytest.raises(CommandError):
call_command(
"init_fs_project",
"foo",
fs_path,
tr_path,
"--filetypes", "NO_SUCH_FILETYPE")
@pytest.mark.django_db
@pytest.mark.cmd
def test_cmd_init_fs_project_bad_filepath(capsys):
fs_path = "/test/fs/path"
tr_path = "<language_code>/<filename>.<ext>"
with pytest.raises(CommandError) as e:
call_command(
"init_fs_project",
"foo",
fs_path,
tr_path,
"--filetypes", "po")
assert not Project.objects.filter(code="foo").exists()
assert "Source directory does not exist" in str(e)
| 4,210
|
Python
|
.py
| 108
| 33.342593
| 79
| 0.665031
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,087
|
signals.py
|
translate_pootle/tests/pootle_config/signals.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import pytest
from django.dispatch import receiver
from pootle.core.signals import config_updated
from pootle_config.utils import ModelConfig, SiteConfig
@pytest.mark.django_db
def test_signal_object_config_set(project0):
signal_recv = config_updated.receivers
signal_cache = config_updated.sender_receivers_cache
class Result(object):
pass
result = Result()
@receiver(config_updated, sender=project0.__class__)
def project_config_updated(**kwargs):
result.sender = kwargs["sender"]
result.instance = kwargs["instance"]
result.key = kwargs["key"]
result.value = kwargs["value"]
result.old_value = kwargs["old_value"]
project0.config["foo.setting"] = 1
assert result.sender == project0.__class__
assert result.instance == project0
assert result.key == "foo.setting"
assert result.value == 1
assert result.old_value is None
project0.config["foo.setting"] = 2
assert result.instance == project0
assert result.key == "foo.setting"
assert result.value == 2
assert result.old_value == 1
config_updated.receivers = signal_recv
config_updated.sender_receivers_cache = signal_cache
@pytest.mark.django_db
def test_signal_model_config_set(project0):
signal_recv = config_updated.receivers
signal_cache = config_updated.sender_receivers_cache
class Result(object):
pass
result = Result()
@receiver(config_updated, sender=project0.__class__)
def project_model_config_updated(**kwargs):
result.sender = kwargs["sender"]
result.instance = kwargs["instance"]
result.key = kwargs["key"]
result.value = kwargs["value"]
result.old_value = kwargs["old_value"]
config = ModelConfig(project0.__class__)
config["foo.setting"] = 1
assert result.sender == project0.__class__
assert result.instance is None
assert result.key == "foo.setting"
assert result.value == 1
assert result.old_value is None
config["foo.setting"] = 2
assert result.sender == project0.__class__
assert result.instance is None
assert result.key == "foo.setting"
assert result.value == 2
assert result.old_value == 1
config_updated.receivers = signal_recv
config_updated.sender_receivers_cache = signal_cache
@pytest.mark.django_db
def test_signal_site_config_set(project0):
signal_recv = config_updated.receivers
signal_cache = config_updated.sender_receivers_cache
class Result(object):
pass
result = Result()
@receiver(config_updated, sender=type(None))
def site_config_updated(**kwargs):
result.sender = kwargs["sender"]
result.instance = kwargs["instance"]
result.key = kwargs["key"]
result.value = kwargs["value"]
result.old_value = kwargs["old_value"]
config = SiteConfig()
config["foo.setting"] = 1
assert isinstance(None, result.sender)
assert result.instance is None
assert result.key == "foo.setting"
assert result.value == 1
assert result.old_value is None
config["foo.setting"] = 2
assert isinstance(None, result.sender)
assert result.instance is None
assert result.key == "foo.setting"
assert result.value == 2
assert result.old_value == 1
config_updated.receivers = signal_recv
config_updated.sender_receivers_cache = signal_cache
| 3,679
|
Python
|
.py
| 96
| 33.03125
| 77
| 0.700197
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,088
|
units.py
|
translate_pootle/tests/search/units.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import pytest
from pootle.core.delegate import search_backend
from pootle.core.plugin import getter
from pootle_project.models import Project
from pootle_statistics.models import Submission, SubmissionTypes
from pootle_store.getters import get_search_backend
from pootle_store.constants import FUZZY, TRANSLATED, UNTRANSLATED
from pootle_store.models import Suggestion, Unit
from pootle_store.unit.filters import (
FilterNotFound, UnitChecksFilter, UnitContributionFilter, UnitSearchFilter,
UnitStateFilter, UnitTextSearch)
from pootle_store.unit.search import DBSearchBackend
def _expected_text_search_words(text, case):
if case:
return [text]
return [t.strip() for t in text.split(" ") if t.strip()]
def _expected_text_search_results(qs, words, search_fields, exact, case):
contains = (
"contains"
if case
else "icontains")
def _search_field(k):
subresult = qs.all()
for word in words:
subresult = subresult.filter(
**{("%s__%s" % (k, contains)): word})
return subresult
result = qs.none()
for k in search_fields:
result = result | _search_field(k)
return list(result.order_by("pk"))
def _expected_text_search_fields(sfields):
search_fields = set()
for field in sfields:
if field in UnitTextSearch.search_mappings:
search_fields.update(UnitTextSearch.search_mappings[field])
else:
search_fields.add(field)
return search_fields
def _test_units_checks_filter(qs, check_type, check_data):
result = UnitChecksFilter(qs, **{check_type: check_data}).filter("checks")
for item in result:
assert item in qs
assert result.count() == result.distinct().count()
if check_type == "checks":
for item in result:
assert any(
qc in item.qualitycheck_set.values_list("name", flat=True)
for qc
in check_data)
assert(
list(result)
== list(
qs.filter(
qualitycheck__false_positive=False,
qualitycheck__name__in=check_data).distinct()))
else:
for item in result:
item.qualitycheck_set.values_list("category", flat=True)
assert(
list(result)
== list(
qs.filter(
qualitycheck__false_positive=False,
qualitycheck__category=check_data).distinct()))
def _test_units_contribution_filter(qs, user, unit_filter):
result = UnitContributionFilter(qs, user=user).filter(unit_filter)
for item in result:
assert item in qs
assert result.count() == result.distinct().count()
user_subs_overwritten = [
"my_submissions_overwritten",
"user_submissions_overwritten"]
if unit_filter == "suggestions":
assert (
result.count()
== qs.filter(
suggestion__state__name="pending").distinct().count())
return
elif not user:
assert result.count() == 0
return
elif unit_filter in ["my_suggestions", "user_suggestions"]:
expected = qs.filter(
suggestion__state__name="pending",
suggestion__user=user).distinct()
elif unit_filter == "user_suggestions_accepted":
expected = qs.filter(
suggestion__state__name="accepted",
suggestion__user=user).distinct()
elif unit_filter == "user_suggestions_rejected":
expected = qs.filter(
suggestion__state__name="rejected",
suggestion__user=user).distinct()
elif unit_filter in ["my_submissions", "user_submissions"]:
expected = qs.filter(change__submitted_by=user)
elif unit_filter in user_subs_overwritten:
# lets calc this long hand
# first submissions that have been added with no suggestion
user_edit_subs = Submission.objects.filter(
type__in=SubmissionTypes.EDIT_TYPES).filter(
suggestion__isnull=True).filter(
submitter=user).values_list("unit_id", flat=True)
# next the suggestions that are accepted and the user is this user
user_suggestions = Suggestion.objects.filter(
state__name="accepted",
user=user).values_list("unit_id", flat=True)
expected = qs.filter(
id__in=(
set(user_edit_subs)
| set(user_suggestions))).exclude(change__submitted_by=user)
assert (
list(expected.order_by("pk"))
== list(result.order_by("pk")))
def _test_unit_text_search(qs, text, sfields, exact, case, empty=True):
unit_search = UnitTextSearch(qs)
result = unit_search.search(text, sfields, exact, case).order_by("pk")
words = unit_search.get_words(text, exact)
fields = unit_search.get_search_fields(sfields)
# ensure result meets our expectation
assert (
list(result)
== _expected_text_search_results(qs, words, fields, exact, case))
# ensure that there are no dupes in result qs
assert list(result) == list(result.distinct())
if not empty:
assert result.count()
for item in result:
# item is in original qs
assert item in qs
for word in words:
searchword_found = False
for field in fields:
if word.lower() in getattr(item, field).lower():
# one of the items attrs matches search
searchword_found = True
break
assert searchword_found
def _test_units_state_filter(qs, unit_filter):
result = UnitStateFilter(qs).filter(unit_filter)
for item in result:
assert item in qs
assert result.count() == result.distinct().count()
if unit_filter == "all":
assert list(result) == list(qs)
return
elif unit_filter == "translated":
states = [TRANSLATED]
elif unit_filter == "untranslated":
states = [UNTRANSLATED]
elif unit_filter == "fuzzy":
states = [FUZZY]
elif unit_filter == "incomplete":
states = [UNTRANSLATED, FUZZY]
assert all(
state in states
for state
in result.values_list("state", flat=True))
assert (
qs.filter(state__in=states).count()
== result.count())
@pytest.mark.django_db
def test_get_units_text_search(units_text_searches):
search = units_text_searches
sfields = search["sfields"]
fields = _expected_text_search_fields(sfields)
words = _expected_text_search_words(search['text'], search["case"])
# ensure the fields parser works correctly
assert (
UnitTextSearch(Unit.objects.all()).get_search_fields(sfields)
== fields)
# ensure the text tokeniser works correctly
assert (
UnitTextSearch(Unit.objects.all()).get_words(
search['text'], search["case"])
== words)
assert isinstance(words, list)
# run the all units test first and check its not empty if it shouldnt be
_test_unit_text_search(
Unit.objects.all(),
search["text"], search["sfields"], search["exact"], search["case"],
search["empty"])
for qs in [Unit.objects.none(), Unit.objects.live()]:
# run tests against different qs
_test_unit_text_search(
qs, search["text"], search["sfields"], search["exact"], search["case"])
@pytest.mark.django_db
def test_units_contribution_filter_none(units_contributor_searches):
unit_filter = units_contributor_searches
user = None
qs = Unit.objects.all()
if not hasattr(UnitContributionFilter, "filter_%s" % unit_filter):
with pytest.raises(FilterNotFound):
UnitContributionFilter(qs, user=user).filter(unit_filter)
return
test_qs = [
qs,
qs.none(),
qs.filter(
store__translation_project__project=Project.objects.first())]
for _qs in test_qs:
_test_units_contribution_filter(_qs, user, unit_filter)
@pytest.mark.django_db
def test_units_contribution_filter(units_contributor_searches, site_users):
unit_filter = units_contributor_searches
user = site_users["user"]
qs = Unit.objects.all()
if not hasattr(UnitContributionFilter, "filter_%s" % unit_filter):
with pytest.raises(FilterNotFound):
UnitContributionFilter(qs, user=user).filter(unit_filter)
return
test_qs = [
qs,
qs.none(),
qs.filter(
store__translation_project__project=Project.objects.first())]
for _qs in test_qs:
_test_units_contribution_filter(_qs, user, unit_filter)
@pytest.mark.django_db
def test_units_state_filter(units_state_searches):
unit_filter = units_state_searches
qs = Unit.objects.all()
if not hasattr(UnitStateFilter, "filter_%s" % unit_filter):
with pytest.raises(FilterNotFound):
UnitStateFilter(qs).filter(unit_filter)
return
test_qs = [
qs,
qs.none(),
qs.filter(
store__translation_project__project=Project.objects.first())]
for _qs in test_qs:
_test_units_state_filter(_qs, unit_filter)
@pytest.mark.django_db
def test_units_checks_filter(units_checks_searches):
check_type, check_data = units_checks_searches
qs = Unit.objects.all()
test_qs = [
qs,
qs.none(),
qs.filter(
store__translation_project__project=Project.objects.first())]
for _qs in test_qs:
_test_units_checks_filter(_qs, check_type, check_data)
@pytest.mark.django_db
def test_units_checks_filter_bad():
qs = Unit.objects.all()
with pytest.raises(FilterNotFound):
UnitChecksFilter(qs).filter("BAD")
# if you dont supply check/category you get empty qs
assert not UnitChecksFilter(qs).filter("checks").count()
@pytest.mark.django_db
def test_units_filters():
qs = Unit.objects.all()
assert UnitSearchFilter().filter(qs, "FOO").count() == 0
@pytest.mark.django_db
def test_unit_search_backend():
assert search_backend.get() is None
assert search_backend.get(Unit) is DBSearchBackend
@pytest.mark.django_db
def test_unit_search_backend_custom():
class CustomSearchBackend(DBSearchBackend):
pass
# add a custom getter, simulating adding before pootle_store
# in INSTALLED_APPS
# disconnect the default search_backend
search_backend.disconnect(get_search_backend, sender=Unit)
@getter(search_backend, sender=Unit)
def custom_get_search_backend(**kwargs):
return CustomSearchBackend
# reconnect the default search_backend
search_backend.connect(get_search_backend, sender=Unit)
assert search_backend.get(Unit) is CustomSearchBackend
| 11,104
|
Python
|
.py
| 280
| 31.957143
| 83
| 0.649331
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,089
|
data_updater_tp.py
|
translate_pootle/tests/pootle_data/data_updater_tp.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import pytest
from translate.filters.decorators import Category
from django.db.models import Max
from pootle.core.delegate import review
from pootle.core.signals import update_checks, update_data
from pootle_data.tp_data import TPDataTool, TPDataUpdater
from pootle_store.constants import FUZZY, OBSOLETE, TRANSLATED, UNTRANSLATED
from pootle_store.models import Suggestion
from pootle_statistics.models import Submission
from pootle_store.models import QualityCheck, Unit
from .data_updater_store import _calc_word_counts, _calculate_checks
@pytest.mark.django_db
def test_data_tp_util(tp0):
data_tool = TPDataTool(tp0)
assert data_tool.context == tp0
assert isinstance(tp0.data_tool, TPDataTool)
@pytest.mark.django_db
def test_data_tp_updater(tp0):
data_tool = TPDataTool(tp0)
updater = TPDataUpdater(data_tool)
assert updater.tool.context == tp0
assert isinstance(tp0.data_tool.updater, TPDataUpdater)
@pytest.mark.django_db
def test_data_tp_util_wordcount(tp0):
WORDCOUNT_KEYS = ["total_words", "fuzzy_words", "translated_words"]
units = Unit.objects.filter(
state__gt=OBSOLETE,
store__translation_project=tp0)
# stats should always be correct
original_stats = _calc_word_counts(units.all())
update_data = tp0.data_tool.updater.get_store_data()
for k in WORDCOUNT_KEYS:
assert update_data[k] == original_stats[k]
assert getattr(tp0.data, k) == original_stats[k]
# make a translated unit fuzzy
unit = units.filter(state=TRANSLATED).first()
unit.state = FUZZY
unit.save()
updated_stats = _calc_word_counts(units.all())
update_data = tp0.data_tool.updater.get_store_data()
tp0.data.refresh_from_db()
for k in WORDCOUNT_KEYS:
assert update_data[k] == updated_stats[k]
for k in WORDCOUNT_KEYS:
assert getattr(tp0.data, k) == updated_stats[k]
assert (
update_data["fuzzy_words"]
== tp0.data.fuzzy_words
== original_stats["fuzzy_words"] + unit.unit_source.source_wordcount)
assert (
update_data["translated_words"]
== tp0.data.translated_words
== original_stats["translated_words"] - unit.unit_source.source_wordcount)
# improve me
@pytest.mark.django_db
def test_data_tp_util_max_unit_revision(tp0):
units = Unit.objects.filter(
store__translation_project=tp0)
original_revision = units.aggregate(
revision=Max("revision"))["revision"]
update_data = tp0.data_tool.updater.get_store_data()
assert (
update_data["max_unit_revision"]
== tp0.data.max_unit_revision
== tp0.data_tool.updater.get_max_unit_revision()
== original_revision)
unit = units.first()
unit.target = "SOMETHING ELSE"
unit.save()
update_data = tp0.data_tool.updater.get_store_data()
tp0.data.refresh_from_db()
assert update_data["max_unit_revision"] == unit.revision
assert tp0.data.max_unit_revision == unit.revision
# if you pass the unit it always gives the unit.revision
other_unit = units.exclude(pk=unit.pk).first()
tp0.data_tool.update(max_unit_revision=other_unit.revision)
assert tp0.data.max_unit_revision == other_unit.revision
@pytest.mark.django_db
def test_data_tp_updater_last_created(tp0):
units = Unit.objects.filter(
state__gt=OBSOLETE,
store__translation_project=tp0).exclude(creation_time__isnull=True)
original_created_unit = (
units.order_by('-creation_time', '-revision', '-pk').first())
update_data = tp0.data_tool.updater.get_store_data()
assert(
update_data["last_created_unit"]
== tp0.data.last_created_unit_id
== tp0.data_tool.updater.get_last_created_unit()
== original_created_unit.id)
original_created_unit.creation_time = None
original_created_unit.save()
update_data = tp0.data_tool.updater.get_store_data()
tp0.data.refresh_from_db()
assert(
update_data["last_created_unit"]
== tp0.data.last_created_unit_id
== tp0.data_tool.updater.get_last_created_unit()
!= original_created_unit.id)
# you can directly set the last created_unit_id
tp0.data_tool.update(last_created_unit=original_created_unit.id)
update_data = tp0.data_tool.updater.get_store_data()
assert(
tp0.data.last_created_unit_id
== original_created_unit.id)
# but the updater still calculates correctly
assert(
update_data["last_created_unit"]
== tp0.data_tool.updater.get_last_created_unit()
!= original_created_unit.id)
@pytest.mark.django_db
def test_data_tp_util_last_submission(tp0):
submissions = Submission.objects.filter(
unit__store__translation_project=tp0)
original_submission = submissions.latest()
update_data = tp0.data_tool.updater.get_store_data()
assert(
update_data["last_submission"]
== tp0.data.last_submission_id
== tp0.data_tool.updater.get_last_submission()
== original_submission.id)
store = original_submission.unit.store
original_submission.delete()
store.data_tool.update()
update_data = tp0.data_tool.updater.get_store_data()
tp0.data.refresh_from_db()
assert(
update_data["last_submission"]
== tp0.data.last_submission_id
== tp0.data_tool.updater.get_last_submission()
!= original_submission.id)
# you can directly set the last submission_id
tp0.data_tool.update(last_submission=original_submission.id)
update_data = tp0.data_tool.updater.get_store_data()
assert(
tp0.data.last_submission_id
== original_submission.id)
# but the updater still calculates correctly
assert(
update_data["last_submission"]
== tp0.data_tool.updater.get_last_submission()
!= original_submission.id)
@pytest.mark.django_db
def test_data_tp_util_suggestion_count(tp0, member):
units = Unit.objects.filter(
state__gt=OBSOLETE,
store__translation_project=tp0)
suggestions = Suggestion.objects.filter(
unit__store__translation_project=tp0,
unit__state__gt=OBSOLETE,
state__name="pending")
original_suggestion_count = suggestions.count()
update_data = tp0.data_tool.updater.get_store_data()
tp0.data.refresh_from_db()
assert(
update_data["pending_suggestions"]
== tp0.data.pending_suggestions
== tp0.data_tool.updater.get_pending_suggestions()
== original_suggestion_count)
unit = units.filter(
state__gt=OBSOLETE,
suggestion__state__name="pending").first()
unit_suggestion_count = unit.suggestion_set.filter(
state__name="pending").count()
unit_suggestion_count = unit.suggestion_set.filter(
state__name="pending").count()
sugg, added = review.get(Suggestion)().add(
unit,
"Another suggestion for %s" % (unit.target or unit.source),
user=member)
# unit now has an extra suggestion
assert (
unit.suggestion_set.filter(state__name="pending").count()
== unit_suggestion_count + 1)
update_data = tp0.data_tool.updater.get_store_data()
tp0.data.refresh_from_db()
assert(
update_data["pending_suggestions"]
== tp0.data.pending_suggestions
== tp0.data_tool.updater.get_pending_suggestions()
== original_suggestion_count + 1)
tp0.data_tool.update(pending_suggestions=1000000)
update_data = tp0.data_tool.updater.get_store_data()
assert(
tp0.data.pending_suggestions
== 1000000)
assert(
update_data["pending_suggestions"]
== tp0.data_tool.updater.get_pending_suggestions()
== original_suggestion_count + 1)
@pytest.mark.django_db
def test_data_tp_qc_stats(tp0):
units = Unit.objects.filter(
state__gt=OBSOLETE,
store__translation_project=tp0)
qc_qs = QualityCheck.objects
qc_qs = (
qc_qs.filter(unit__store__translation_project=tp0)
.filter(unit__state__gt=UNTRANSLATED)
.filter(category=Category.CRITICAL)
.exclude(false_positive=True))
check_count = qc_qs.count()
store_data = tp0.data_tool.updater.get_store_data()
assert (
store_data["critical_checks"]
== tp0.data.critical_checks
== check_count)
unit = units.exclude(
qualitycheck__isnull=True,
qualitycheck__name__in=["xmltags", "endpunc"]).first()
unit.target = "<foo></bar>;"
unit.save()
unit_critical = unit.qualitycheck_set.filter(
category=Category.CRITICAL).count()
store_data = tp0.data_tool.updater.get_store_data()
tp0.data.refresh_from_db()
assert (
store_data["critical_checks"]
== tp0.data.critical_checks
== check_count + unit_critical)
# lets make another unit false positive
other_qc = unit.qualitycheck_set.exclude(
name="xmltags").filter(category=Category.CRITICAL).first()
other_qc.false_positive = True
other_qc.save()
# trigger refresh
update_checks.send(
unit.__class__,
instance=unit,
keep_false_positives=True)
update_data.send(
unit.store.__class__,
instance=unit.store,
keep_false_positives=True)
store_data = tp0.data_tool.updater.get_store_data()
tp0.data.refresh_from_db()
assert (
store_data["critical_checks"]
== tp0.data.critical_checks
== check_count + unit_critical - 1)
@pytest.mark.django_db
def test_data_tp_checks(tp0):
units = Unit.objects.filter(
state__gt=OBSOLETE,
store__translation_project=tp0)
qc_qs = QualityCheck.objects
qc_qs = (
qc_qs.filter(unit__store__translation_project=tp0)
.filter(unit__state__gt=UNTRANSLATED)
.exclude(false_positive=True))
checks = _calculate_checks(qc_qs.all())
check_data = tp0.check_data.all().values_list("category", "name", "count")
assert len(check_data) == len(checks)
for (category, name), count in checks.items():
assert (category, name, count) in check_data
unit = units.exclude(
qualitycheck__isnull=True,
qualitycheck__name__in=["xmltags", "endpunc"]).first()
unit.target = "<foo></bar>;"
unit.save()
checks = _calculate_checks(qc_qs.all())
check_data = tp0.check_data.all().values_list("category", "name", "count")
assert len(check_data) == len(checks)
for (category, name), count in checks.items():
assert (category, name, count) in check_data
| 10,842
|
Python
|
.py
| 272
| 33.617647
| 82
| 0.676814
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,090
|
data_updater_store.py
|
translate_pootle/tests/pootle_data/data_updater_store.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from datetime import timedelta
import pytest
from pytest_pootle.factories import StoreDBFactory
from translate.filters.decorators import Category
from django.db.models import Max
from pootle.core.delegate import crud, review
from pootle.core.signals import update_checks, update_data
from pootle_data.models import StoreChecksData
from pootle_data.store_data import (
StoreChecksDataCRUD, StoreDataTool, StoreDataUpdater)
from pootle_statistics.models import Submission
from pootle_store.constants import FUZZY, OBSOLETE, TRANSLATED, UNTRANSLATED
from pootle_store.models import Suggestion
from pootle_store.models import QualityCheck, Unit
def _calc_word_counts(units):
expected = dict(
total_words=0, translated_words=0, fuzzy_words=0)
for unit in units:
expected["total_words"] += unit.unit_source.source_wordcount
if unit.state == TRANSLATED:
expected["translated_words"] += unit.unit_source.source_wordcount
elif unit.state == FUZZY:
expected["fuzzy_words"] += unit.unit_source.source_wordcount
return expected
@pytest.mark.django_db
def test_data_store_checks_data_crud():
store_data_crud = crud.get(StoreChecksData)
assert isinstance(store_data_crud, StoreChecksDataCRUD)
assert store_data_crud.qs.count() == StoreChecksData.objects.count()
@pytest.mark.django_db
def test_data_store_updater(store0):
data_tool = StoreDataTool(store0)
updater = StoreDataUpdater(data_tool)
assert updater.tool.context == store0
assert isinstance(store0.data_tool.updater, StoreDataUpdater)
@pytest.mark.django_db
def test_data_store_util_wordcount(store0):
WORDCOUNT_KEYS = ["total_words", "fuzzy_words", "translated_words"]
# stats should always be correct
original_stats = _calc_word_counts(store0.units)
update_data = store0.data_tool.updater.get_store_data()
for k in WORDCOUNT_KEYS:
assert update_data[k] == original_stats[k]
assert getattr(store0.data, k) == original_stats[k]
# make a translated unit fuzzy
unit = store0.units.filter(state=TRANSLATED).first()
unit.state = FUZZY
unit.save()
updated_stats = _calc_word_counts(store0.units)
update_data = store0.data_tool.updater.get_store_data()
for k in WORDCOUNT_KEYS:
assert update_data[k] == updated_stats[k]
for k in WORDCOUNT_KEYS:
assert getattr(store0.data, k) == updated_stats[k]
assert (
update_data["fuzzy_words"]
== store0.data.fuzzy_words
== (original_stats["fuzzy_words"]
+ unit.unit_source.source_wordcount))
assert (
update_data["translated_words"]
== store0.data.translated_words
== (original_stats["translated_words"]
- unit.unit_source.source_wordcount))
@pytest.mark.django_db
def test_data_store_util_max_unit_revision(store0):
original_revision = store0.unit_set.aggregate(
revision=Max("revision"))["revision"]
update_data = store0.data_tool.updater.get_store_data()
assert (
update_data["max_unit_revision"]
== store0.data.max_unit_revision
== store0.data_tool.updater.get_max_unit_revision()
== original_revision)
unit = store0.units.first()
unit.target = "SOMETHING ELSE"
unit.save()
update_data = store0.data_tool.updater.get_store_data()
assert update_data["max_unit_revision"] == unit.revision
assert store0.data.max_unit_revision == unit.revision
# if you pass the unit it always gives the unit.revision
other_unit = store0.units.exclude(pk=unit.pk).first()
store0.data_tool.update(max_unit_revision=other_unit.revision)
assert store0.data.max_unit_revision == other_unit.revision
@pytest.mark.django_db
def test_data_store_util_max_unit_mtime(store0):
original_mtime = store0.unit_set.aggregate(
mtime=Max("mtime"))["mtime"]
update_data = store0.data_tool.updater.get_store_data()
assert (
update_data["max_unit_mtime"]
== store0.data.max_unit_mtime
== store0.data_tool.updater.get_max_unit_mtime()
== original_mtime)
unit = store0.units.first()
unit.target = "SOMETHING ELSE"
unit.save()
update_data = store0.data_tool.updater.get_store_data()
assert (
update_data["max_unit_mtime"].replace(microsecond=0)
== unit.mtime.replace(microsecond=0))
assert (
store0.data.max_unit_mtime.replace(microsecond=0)
== unit.mtime.replace(microsecond=0))
# if you pass the unit it always gives the unit.mtime
other_unit = store0.units.exclude(pk=unit.pk).first()
store0.data_tool.update(max_unit_mtime=other_unit.mtime)
assert (
store0.data.max_unit_mtime.replace(microsecond=0)
== other_unit.mtime.replace(microsecond=0))
@pytest.mark.django_db
def test_data_store_updater_last_created(store0):
units = store0.units.exclude(creation_time__isnull=True)
original_created_unit = (
units.order_by('-creation_time', '-revision', '-pk').first())
update_data = store0.data_tool.updater.get_store_data()
assert(
update_data["last_created_unit"]
== store0.data.last_created_unit_id
== store0.data_tool.updater.get_last_created_unit()
== original_created_unit.id)
original_created_unit.creation_time = None
original_created_unit.save()
update_data = store0.data_tool.updater.get_store_data()
assert(
update_data["last_created_unit"]
== store0.data.last_created_unit_id
== store0.data_tool.updater.get_last_created_unit()
!= original_created_unit.id)
# you can directly set the last created_unit_id
store0.data_tool.update(last_created_unit=original_created_unit.id)
update_data = store0.data_tool.updater.get_store_data()
assert(
store0.data.last_created_unit_id
== original_created_unit.id)
# but the updater still calculates correctly
assert(
update_data["last_created_unit"]
== store0.data_tool.updater.get_last_created_unit()
!= original_created_unit.id)
@pytest.mark.django_db
def test_data_store_util_last_submission(store0):
original_submission = Submission.objects.filter(
unit__store=store0).latest()
update_data = store0.data_tool.updater.get_store_data()
assert(
update_data["last_submission"]
== store0.data.last_submission_id
== store0.data_tool.updater.get_last_submission()
== original_submission.id)
original_submission.delete()
# you can directly set the last submission_id
store0.data_tool.update(last_submission=original_submission.id)
update_data = store0.data_tool.updater.get_store_data()
assert(
store0.data.last_submission_id
== original_submission.id)
# but the updater still calculates correctly
assert(
update_data["last_submission"]
== store0.data_tool.updater.get_last_submission()
!= original_submission.id)
@pytest.mark.django_db
def test_data_store_util_suggestion_count(store0, member):
suggestions = Suggestion.objects.filter(
unit__store=store0,
unit__state__gt=OBSOLETE,
state__name="pending")
original_suggestion_count = suggestions.count()
update_data = store0.data_tool.updater.get_store_data()
assert(
update_data["pending_suggestions"]
== store0.data.pending_suggestions
== store0.data_tool.updater.get_pending_suggestions()
== original_suggestion_count)
unit = store0.units.filter(
state__gt=OBSOLETE,
suggestion__state__name="pending").first()
unit_suggestion_count = unit.suggestion_set.filter(
state__name="pending").count()
sugg, added = review.get(Suggestion)().add(
unit,
"Another suggestion for %s" % (unit.target or unit.source),
user=member)
# unit now has an extra suggestion
assert (
unit.suggestion_set.filter(state__name="pending").count()
== unit_suggestion_count + 1)
store0.data.refresh_from_db()
update_data = store0.data_tool.updater.get_store_data()
assert(
update_data["pending_suggestions"]
== store0.data.pending_suggestions
== store0.data_tool.updater.get_pending_suggestions()
== original_suggestion_count + 1)
store0.data_tool.update(pending_suggestions=1000000)
update_data = store0.data_tool.updater.get_store_data()
assert(
store0.data.pending_suggestions
== 1000000)
assert(
update_data["pending_suggestions"]
== store0.data_tool.updater.get_pending_suggestions()
== original_suggestion_count + 1)
@pytest.mark.django_db
def test_data_store_critical_checks(store0):
qc_qs = QualityCheck.objects
qc_qs = (
qc_qs.filter(unit__store=store0)
.filter(unit__state__gt=UNTRANSLATED)
.filter(category=Category.CRITICAL)
.exclude(false_positive=True))
check_count = qc_qs.count()
assert (
store0.data.critical_checks
== check_count)
unit = store0.units.exclude(
qualitycheck__isnull=True,
qualitycheck__name__in=["xmltags", "endpunc"]).first()
unit.target = "<foo></bar>;"
unit.save()
unit_critical = unit.qualitycheck_set.filter(
category=Category.CRITICAL).count()
assert (
store0.data.critical_checks
== check_count + unit_critical)
# lets make another unit false positive
other_qc = unit.qualitycheck_set.exclude(
name="xmltags").filter(category=Category.CRITICAL).first()
other_qc.false_positive = True
other_qc.save()
# trigger refresh
update_checks.send(
unit.__class__,
instance=unit,
keep_false_positives=True)
update_data.send(
unit.store.__class__,
instance=unit.store,
keep_false_positives=True)
assert (
store0.data.critical_checks
== check_count + unit_critical - 1)
@pytest.mark.django_db
def test_data_store_updater_fields(store0, stats_data_dict, stats_data_types):
"""Ensure we can get/set only some fields"""
data_type = stats_data_types
result = store0.data_tool.updater.get_store_data(fields=[data_type])
original_values = {
k: getattr(store0.data, k)
for k in stats_data_dict}
if data_type in store0.data_tool.updater.fk_fields:
match = "%s_id" % data_type
else:
match = data_type
assert (
getattr(store0.data, match)
== result[data_type])
assert data_type in result.keys()
if data_type in store0.data_tool.updater.fk_fields:
new_value = None
elif isinstance(result[data_type], int):
new_value = result[data_type] + 5
else:
new_value = result[data_type] + timedelta(seconds=5)
kwargs = {
"fields": [data_type],
data_type: "FOO"}
result = store0.data_tool.updater.get_store_data(**kwargs)
assert result[data_type] == "FOO"
kwargs[data_type] = new_value
store0.data_tool.updater.update(**kwargs)
# refresh fks
store0.data.refresh_from_db()
for k, v in original_values.items():
if k == data_type:
assert getattr(store0.data, k) == new_value
else:
assert (
getattr(store0.data, k)
== original_values[k])
def _calculate_checks(qc_qs):
checks = {}
checks_values = qc_qs.exclude(false_positive=True).values_list(
"category", "name")
for category, name in checks_values:
checks[(category, name)] = checks.get((category, name), 0) + 1
return checks
@pytest.mark.django_db
def test_data_store_updater_checks(store0):
qc_qs = QualityCheck.objects
qc_qs = (
qc_qs.filter(unit__store=store0)
.filter(unit__state__gt=UNTRANSLATED)
.exclude(false_positive=True))
original_checks = _calculate_checks(qc_qs.all())
check_data = store0.check_data.all().values_list("category", "name", "count")
assert len(check_data) == len(original_checks)
for (category, name), count in original_checks.items():
assert (category, name, count) in check_data
unit = store0.units.exclude(
qualitycheck__isnull=True,
qualitycheck__name__in=["xmltags", "endpunc"]).first()
original_unit_target = unit.target
unit.target = "<foo></bar>;"
unit.save()
checks = _calculate_checks(qc_qs.all())
check_data = store0.check_data.all().values_list("category", "name", "count")
assert len(check_data) == len(checks)
for (category, name), count in checks.items():
assert (category, name, count) in check_data
unit = Unit.objects.get(id=unit.id)
unit.target = original_unit_target
unit.save()
check_data = store0.check_data.all().values_list("category", "name", "count")
assert len(check_data) == len(original_checks)
for (category, name), count in original_checks.items():
assert (category, name, count) in check_data
@pytest.mark.django_db
def test_data_store_updater_no_fields(store0):
assert (
store0.data_tool.updater.get_store_data(fields=[])
== dict(fields=[], max_unit_revision=0))
orig_words = store0.data.total_words
store0.data.total_words = orig_words + 3
store0.data.save()
store0.data_tool.update()
assert store0.data.total_words == orig_words
store0.data.total_words = orig_words + 3
store0.data.save()
store0.data_tool.update(fields=[])
assert store0.data.total_words == orig_words + 3
@pytest.mark.django_db
def test_data_store_updater_defaults(tp0):
store = StoreDBFactory(
name="store_with_no_units.po",
parent=tp0.directory,
translation_project=tp0)
fields = store.data_tool.updater.aggregate_fields
aggregate_data = store.data_tool.updater.get_aggregate_data(
fields=fields)
for k in fields:
if k in store.data_tool.updater.aggregate_defaults:
assert (
aggregate_data[k]
== store.data_tool.updater.aggregate_defaults[k])
| 14,410
|
Python
|
.py
| 353
| 34.422096
| 81
| 0.678347
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,091
|
data_tool.py
|
translate_pootle/tests/pootle_data/data_tool.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import pytest
from django.db.models import Sum
from pootle.core.delegate import data_tool, revision
from pootle_app.models import Directory
from pootle_data.apps import PootleDataConfig
from pootle_data.models import StoreChecksData, StoreData, TPChecksData
from pootle_data.store_data import StoreDataTool
from pootle_data.utils import DataTool
from pootle_language.models import Language
from pootle_project.models import Project, ProjectResource, ProjectSet
from pootle_store.constants import FUZZY, OBSOLETE, TRANSLATED
from pootle_store.models import Unit
from virtualfolder.delegate import vfolders_data_tool
@pytest.mark.django_db
def test_data_tool_store(store0):
assert data_tool.get() is None
assert data_tool.get(store0.__class__) is StoreDataTool
assert isinstance(store0.data_tool, StoreDataTool)
assert store0.data_tool.context is store0
@pytest.mark.django_db
def test_data_tool_obsolete_resurrect_store(store0):
assert store0.check_data.count()
orig_stats = store0.data_tool.get_stats()
store0.makeobsolete()
assert store0.data.total_words == 0
assert store0.data.critical_checks == 0
assert not store0.check_data.count()
assert store0.data_tool.get_stats() != orig_stats
assert store0.data.max_unit_revision
store0.resurrect()
assert store0.data.total_words
assert store0.check_data.count()
assert store0.data.critical_checks
@pytest.mark.django_db
def test_data_tool_base_tool():
foo = object()
base_tool = DataTool(foo)
assert base_tool.context is foo
assert base_tool.get_stats() == dict(children={})
assert base_tool.get_stats(include_children=False) == {}
assert base_tool.get_checks() == {}
assert base_tool.object_stats == {}
assert base_tool.children_stats == {}
assert base_tool.updater is None
@pytest.mark.django_db
def test_data_tool_store_get_stats(store0):
stats = store0.data_tool.get_stats()
assert stats["translated"] == store0.data.translated_words
assert stats["fuzzy"] == store0.data.fuzzy_words
assert stats["total"] == store0.data.total_words
assert stats["critical"] == store0.data.critical_checks
assert stats["suggestions"] == store0.data.pending_suggestions
assert stats["children"] == {}
last_submission_info = (
store0.data.last_submission.get_submission_info())
assert (
sorted(stats["last_submission"].items())
== sorted(last_submission_info.items()))
last_created_unit_info = (
store0.data.last_created_unit.get_last_created_unit_info())
assert (
sorted(stats["last_created_unit"].items())
== sorted(last_created_unit_info.items()))
@pytest.mark.django_db
def test_data_tool_store_get_checks(store0):
checks = store0.data_tool.get_checks()
assert (
sorted(checks.items())
== sorted(store0.check_data.values_list("name", "count")))
@pytest.mark.django_db
def test_data_tool_tp_get_stats(tp0):
stats = tp0.data_tool.get_stats(include_children=False)
assert "children" not in stats
assert stats["translated"] == tp0.data.translated_words
assert stats["fuzzy"] == tp0.data.fuzzy_words
assert stats["total"] == tp0.data.total_words
assert stats["critical"] == tp0.data.critical_checks
assert stats["suggestions"] == tp0.data.pending_suggestions
last_submission_info = (
tp0.data.last_submission.get_submission_info())
assert (
sorted(stats["last_submission"].items())
== sorted(last_submission_info.items()))
last_created_unit_info = (
tp0.data.last_created_unit.get_last_created_unit_info())
assert (
sorted(stats["last_created_unit"].items())
== sorted(last_created_unit_info.items()))
@pytest.mark.django_db
def test_data_tool_tp_get_stats_with_children(tp0):
stats = tp0.data_tool.get_stats()
assert stats["translated"] == tp0.data.translated_words
assert stats["fuzzy"] == tp0.data.fuzzy_words
assert stats["total"] == tp0.data.total_words
assert stats["critical"] == tp0.data.critical_checks
assert stats["suggestions"] == tp0.data.pending_suggestions
last_submission_info = (
tp0.data.last_submission.get_submission_info())
assert (
sorted(stats["last_submission"].items())
== sorted(last_submission_info.items()))
last_created_unit_info = (
tp0.data.last_created_unit.get_last_created_unit_info())
assert (
sorted(stats["last_created_unit"].items())
== sorted(last_created_unit_info.items()))
for directory in tp0.directory.child_dirs.all():
dir_stats = stats["children"][directory.name]
store_data = StoreData.objects.filter(
store__pootle_path__startswith=directory.pootle_path)
aggregate_mapping = dict(
total="total_words",
fuzzy="fuzzy_words",
translated="translated_words",
suggestions="pending_suggestions",
critical="critical_checks")
for k, v in aggregate_mapping.items():
assert (
dir_stats[k]
== store_data.aggregate(**{k: Sum(v)})[k])
@pytest.mark.django_db
def test_data_tool_tp_get_checks(tp0):
checks = tp0.data_tool.get_checks()
assert (
sorted(checks.items())
== sorted(tp0.check_data.values_list("name", "count")))
def _test_children_stats(stats, directory):
child_stores = directory.child_stores.live()
child_dirs = directory.child_dirs.live()
# same roots
children = (
list(child_stores.values_list("name", flat=True))
+ list(child_dirs.values_list("name", flat=True)))
assert (
sorted(stats["children"].keys())
== (sorted(children)))
for store in child_stores:
_test_unit_stats(
stats["children"][store.name],
store.units)
def _test_object_stats(stats, stores):
assert "children" not in stats
_test_unit_stats(
stats,
stores)
def _test_unit_stats(stats, units):
units = units.exclude(
store__translation_project__language__code="templates"
).exclude(store__obsolete=True)
wordcount = sum(
units.filter(state__gt=OBSOLETE).values_list(
"unit_source__source_wordcount",
flat=True))
assert stats["total"] == wordcount
fuzzy_wordcount = sum(
units.filter(state=FUZZY).values_list(
"unit_source__source_wordcount",
flat=True))
assert stats["fuzzy"] == fuzzy_wordcount
translated_wordcount = sum(
units.filter(state=TRANSLATED).values_list(
"unit_source__source_wordcount",
flat=True))
assert stats["translated"] == translated_wordcount
@pytest.mark.django_db
def test_data_tp_stats(tp0):
# get the child directories
# child_dirs = tp0.directory.child_dirs.live()
_test_object_stats(
tp0.data_tool.get_stats(include_children=False),
Unit.objects.live().filter(
store__in=tp0.stores.live()))
# get the child stores
_test_children_stats(
tp0.data_tool.get_stats(),
tp0.directory)
@pytest.mark.django_db
def test_data_project_stats(project0):
units = (
Unit.objects.live().filter(
store__translation_project__project=project0).exclude(
store__translation_project__language__code="templates"))
_test_object_stats(
project0.data_tool.get_stats(include_children=False),
units)
child_stats = project0.data_tool.get_stats()
non_templates_tps = project0.translationproject_set.exclude(
language__code="templates")
assert (
len(child_stats["children"])
== non_templates_tps.count())
for tp in non_templates_tps.iterator():
stat_code = "%s-%s" % (tp.language.code, project0.code)
assert stat_code in child_stats["children"]
child = child_stats["children"][stat_code]
tp_stats = tp.data_tool.get_stats(include_children=False)
for k in ["fuzzy", "total", "translated", "suggestions", "critical"]:
assert child[k] == tp_stats[k]
@pytest.mark.pootle_vfolders
@pytest.mark.django_db
def test_data_cache_keys(language0, project0, subdir0, vfolder0):
# language
assert language0.data_tool.ns == "pootle.data"
assert language0.data_tool.sw_version == PootleDataConfig.version
assert (
'%s.%s.%s'
% (language0.data_tool.cache_key_name,
language0.code,
revision.get(Language)(language0).get(key="stats"))
== language0.data_tool.cache_key)
# project
assert project0.data_tool.ns == "pootle.data"
assert project0.data_tool.sw_version == PootleDataConfig.version
assert (
'%s.%s.%s'
% (project0.data_tool.cache_key_name,
project0.code,
revision.get(Project)(project0.directory).get(key="stats"))
== project0.data_tool.cache_key)
# directory
assert subdir0.data_tool.ns == "pootle.data"
assert subdir0.data_tool.sw_version == PootleDataConfig.version
assert (
'%s.%s.%s'
% (subdir0.data_tool.cache_key_name,
subdir0.pootle_path,
revision.get(Directory)(subdir0).get(key="stats"))
== subdir0.data_tool.cache_key)
# projectresource
resource_path = "%s%s" % (project0.pootle_path, subdir0.path)
projectresource = ProjectResource(
Directory.objects.none(),
resource_path,
context=project0)
assert projectresource.data_tool.ns == "pootle.data"
assert projectresource.data_tool.sw_version == PootleDataConfig.version
assert (
'%s.%s.%s'
% (projectresource.data_tool.cache_key_name,
resource_path,
revision.get(ProjectResource)(projectresource).get(key="stats"))
== projectresource.data_tool.cache_key)
# projectset
projectset = ProjectSet(Project.objects.all())
assert projectset.data_tool.ns == "pootle.data"
assert projectset.data_tool.sw_version == PootleDataConfig.version
assert (
'%s.%s.%s'
% (projectset.data_tool.cache_key_name,
"ALL",
revision.get(ProjectSet)(projectset).get(key="stats"))
== projectset.data_tool.cache_key)
# vfolders
vfdata = vfolders_data_tool.get(Directory)(subdir0)
assert vfdata.ns == "virtualfolder"
assert vfdata.sw_version == PootleDataConfig.version
assert (
'%s.%s.%s'
% (vfdata.cache_key_name,
subdir0.pootle_path,
revision.get(subdir0.__class__)(subdir0).get(key="stats"))
== vfdata.cache_key)
@pytest.mark.django_db
def test_data_language_stats(language0, request_users):
user = request_users["user"]
units = Unit.objects.live()
units = units.filter(store__translation_project__language=language0)
if not user.is_superuser:
units = units.exclude(store__translation_project__project__disabled=True)
_test_object_stats(
language0.data_tool.get_stats(include_children=False, user=user),
units)
language0.data_tool.get_stats(user=user)
@pytest.mark.django_db
def test_data_directory_stats(subdir0):
filtered_units = Unit.objects.live().filter(
store__pootle_path__startswith=subdir0.pootle_path)
filtered_units = filtered_units.exclude(store__parent=subdir0)
_test_object_stats(
subdir0.data_tool.get_stats(include_children=False),
filtered_units)
# get the child stores
_test_children_stats(
subdir0.data_tool.get_stats(),
subdir0)
@pytest.mark.django_db
def test_data_project_directory_stats(project_dir_resources0):
pd0 = project_dir_resources0
units = Unit.objects.none()
for directory in pd0.children:
units |= Unit.objects.live().filter(
store__pootle_path__startswith=directory.pootle_path)
_test_object_stats(
pd0.data_tool.get_stats(include_children=False),
units)
pd0.data_tool.get_stats()
@pytest.mark.django_db
def test_data_project_store_stats(project_store_resources0):
units = Unit.objects.none()
for store in project_store_resources0.children:
units |= Unit.objects.live().filter(
store__pootle_path=(
"%s%s"
% (store.parent.pootle_path,
store.name)))
_test_object_stats(
project_store_resources0.data_tool.get_stats(include_children=False),
units)
project_store_resources0.data_tool.get_stats()
@pytest.mark.django_db
def test_data_project_set_stats(project_set):
units = Unit.objects.live().exclude(
store__translation_project__project__disabled=True
).exclude(store__obsolete=True)
units = units.exclude(store__is_template=True)
stats = project_set.data_tool.get_stats(include_children=False)
_test_object_stats(
stats,
units)
project_set.data_tool.get_stats()
def _calculate_check_data(check_data):
data = {}
for check in check_data.iterator():
data[check.name] = data.get(check.name, 0) + check.count
return data
@pytest.mark.django_db
def test_data_tool_project_get_checks(project0):
assert (
project0.data_tool.get_checks()
== _calculate_check_data(
TPChecksData.objects.filter(tp__project=project0)))
@pytest.mark.django_db
def test_data_tool_directory_get_checks(subdir0):
expected = StoreChecksData.objects.filter(
store__pootle_path__startswith=subdir0.pootle_path)
expected = expected.exclude(store__parent=subdir0)
assert (
subdir0.data_tool.get_checks()
== _calculate_check_data(expected))
@pytest.mark.django_db
def test_data_tool_language_get_checks(language0, request_users):
user = request_users["user"]
check_data = TPChecksData.objects.filter(tp__language=language0)
if not user.is_superuser:
check_data = check_data.exclude(
tp__project__disabled=True)
assert (
language0.data_tool.get_checks(user=user)
== _calculate_check_data(check_data))
@pytest.mark.django_db
def test_data_project_directory_get_checks(project_dir_resources0):
pd0 = project_dir_resources0
checks_data = StoreChecksData.objects.none()
for directory in pd0.children:
checks_data |= StoreChecksData.objects.filter(
store__state__gt=OBSOLETE,
store__pootle_path__startswith=directory.pootle_path)
assert (
sorted(pd0.data_tool.get_checks().items())
== sorted(_calculate_check_data(checks_data).items()))
| 14,882
|
Python
|
.py
| 367
| 34.029973
| 81
| 0.676743
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,092
|
checks.py
|
translate_pootle/tests/pootle_checks/checks.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import pytest
from pootle.core.delegate import check_updater
from pootle_checks.utils import TPQCUpdater, StoreQCUpdater
from pootle_store.constants import OBSOLETE
from pootle_store.models import QualityCheck
@pytest.mark.django_db
def test_tp_qualitycheck_updater(tp0):
qc_updater = check_updater.get(tp0.__class__)
assert qc_updater is TPQCUpdater
updater = qc_updater(translation_project=tp0)
updater.update()
checks = QualityCheck.objects.filter(unit__store__translation_project=tp0)
original_checks = checks.delete()[0]
assert original_checks
updater.update()
assert checks.count() == original_checks
# make unit obsolete
original_revision = tp0.directory.revisions.filter(
key="stats").values_list("value", flat=True).first()
check = checks[0]
unit = check.unit
unit.__class__.objects.filter(pk=unit.pk).update(state=OBSOLETE)
updater.update(update_data_after=True)
assert check.__class__.objects.filter(pk=check.pk).count() == 0
new_revision = tp0.directory.revisions.filter(
key="stats").values_list("value", flat=True).first()
assert original_revision != new_revision
# set to unknown check
check = checks[0]
check.name = "DOES_NOT_EXIST"
check.save()
updater.update()
assert check.__class__.objects.filter(pk=check.pk).count() == 0
# fix a check
check = checks.filter(name="printf")[0]
unit = check.unit
unit.__class__.objects.filter(pk=unit.pk).update(target_f=unit.source_f)
updater.update()
assert check.__class__.objects.filter(pk=check.pk).count() == 0
# obsolete units in 2 stores - but only update checks for one store
store_ids = checks.filter(name="printf").values_list(
"unit__store", flat=True).distinct()[:2]
check1 = checks.filter(name="printf").filter(
unit__store_id=store_ids[0]).first()
check2 = checks.filter(name="printf").filter(
unit__store_id=store_ids[1]).first()
unit1 = check1.unit
store1 = unit1.store
unit2 = check2.unit
store2 = unit2.store
store1.units.filter(id=unit1.id).update(state=OBSOLETE)
store2.units.filter(id=unit2.id).update(state=OBSOLETE)
qc_updater(
translation_project=tp0,
stores=[store1.id]).update()
assert check.__class__.objects.filter(pk=check1.pk).count() == 0
assert check.__class__.objects.filter(pk=check2.pk).count() == 1
@pytest.mark.django_db
def test_store_qualitycheck_updater(tp0, store0):
qc_updater = check_updater.get(store0.__class__)
assert qc_updater is StoreQCUpdater
QualityCheck.objects.filter(unit__store__translation_project=tp0).delete()
updater = qc_updater(store=store0)
updater.update()
checks = QualityCheck.objects.filter(unit__store=store0)
original_checks = checks.delete()[0]
assert original_checks
updater.update()
assert checks.count() == original_checks
# make unit obsolete
original_revision = store0.parent.revisions.filter(
key="stats").values_list("value", flat=True).first()
check = checks[0]
unit = check.unit
unit.__class__.objects.filter(pk=unit.pk).update(state=OBSOLETE)
updater.update(update_data_after=True)
assert check.__class__.objects.filter(pk=check.pk).count() == 0
new_revision = tp0.directory.revisions.filter(
key="stats").values_list("value", flat=True).first()
assert original_revision != new_revision
updater.update(update_data_after=True)
newest_revision = tp0.directory.revisions.filter(
key="stats").values_list("value", flat=True).first()
assert newest_revision == new_revision
| 3,922
|
Python
|
.py
| 91
| 38.285714
| 78
| 0.707374
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,093
|
syspath_override.py
|
translate_pootle/pootle/syspath_override.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
"""Adds pootle directories to the python import path"""
# FIXME: is this useful on an installed codebase or only when running from
# source?
import os
import sys
ROOT_DIR = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
POOTLE_DIR = os.path.abspath(os.path.dirname(__file__))
sys.path.insert(0, ROOT_DIR) # Top level directory
sys.path.insert(0, POOTLE_DIR) # Pootle directory
sys.path.insert(0, os.path.join(POOTLE_DIR, 'apps')) # Applications
| 742
|
Python
|
.py
| 17
| 42.294118
| 77
| 0.751043
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,094
|
checks.py
|
translate_pootle/pootle/checks.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import sys
from django.core import checks
from django.db import OperationalError, ProgrammingError
from pootle.constants import DJANGO_MINIMUM_REQUIRED_VERSION
from pootle.i18n.gettext import ugettext as _
# Minimum Translate Toolkit version required for Pootle to run.
TTK_MINIMUM_REQUIRED_VERSION = (2, 2, 5)
# Minimum lxml version required for Pootle to run.
LXML_MINIMUM_REQUIRED_VERSION = (3, 5, 0, 0)
# Minimum Redis server version required.
# Initially set to some minimums based on:
# 1. Ubuntu 16.04LTS (Xenial) version 3.0.6
# Ubuntu 14.04LTS (Trusty) version 2.8.4
# Ubuntu 12.04LTS (Precise) version 2.2.12
# Ubuntu 10.04LTS was too old for RQ
# See http://packages.ubuntu.com/search?keywords=redis-server
# 2. RQ requires Redis >= 2.7.0, and
# See https://github.com/nvie/rq/blob/master/README.md
# 3. django-redis 4.x.y supports Redis >=2.8.x
# See http://niwinz.github.io/django-redis/latest/
# 4. Aligning with current Redis stable as best we can
# At the time of writing, actual Redis stable is 3.0 series with 2.8
# cosidered old stable.
# 5. Wanting to insist on at least the latest stable that devs are using
# The 2.8.* versions of Redis
REDIS_MINIMUM_REQUIRED_VERSION = (2, 8, 4)
# List of pootle commands that need a running rqworker.
# FIXME Maybe tagging can improve this?
RQWORKER_WHITELIST = [
"revision", "retry_failed_jobs", "check", "runserver",
]
EXPECTED_POOTLE_SCORES = [
'suggestion_add',
'suggestion_accept',
'suggestion_reject',
'comment_updated',
'target_updated',
'state_translated',
'state_fuzzy',
'state_unfuzzy']
def _version_to_string(version, significance=None):
if significance is not None:
version = version[significance:]
return '.'.join(str(n) for n in version)
@checks.register('data')
def check_duplicate_emails(app_configs=None, **kwargs):
from accounts.utils import get_duplicate_emails
errors = []
try:
if len(get_duplicate_emails()):
errors.append(
checks.Warning(
_("There are user accounts with duplicate emails. This "
"will not be allowed in Pootle 2.8."),
hint=_("Try using 'pootle find_duplicate_emails', and "
"then update user emails with 'pootle "
"update_user_email username email'. You might also "
"want to consider using pootle merge_user or "
"purge_user commands"),
id="pootle.W017"
)
)
except (OperationalError, ProgrammingError):
# no accounts set up - most likely in a test
pass
return errors
@checks.register()
def check_library_versions(app_configs=None, **kwargs):
from django import VERSION as DJANGO_VERSION
from lxml.etree import LXML_VERSION
from translate.__version__ import ver as ttk_version
errors = []
if DJANGO_VERSION < DJANGO_MINIMUM_REQUIRED_VERSION:
errors.append(checks.Critical(
_("Your version of Django is too old."),
hint=_("Try pip install --upgrade 'Django==%s'",
_version_to_string(DJANGO_MINIMUM_REQUIRED_VERSION)),
id="pootle.C002",
))
if LXML_VERSION < LXML_MINIMUM_REQUIRED_VERSION:
errors.append(checks.Warning(
_("Your version of lxml is too old."),
hint=_("Try pip install --upgrade lxml"),
id="pootle.W003",
))
if ttk_version < TTK_MINIMUM_REQUIRED_VERSION:
errors.append(checks.Critical(
_("Your version of Translate Toolkit is too old."),
hint=_("Try pip install --upgrade translate-toolkit"),
id="pootle.C003",
))
return errors
@checks.register()
def check_redis(app_configs=None, **kwargs):
from django_rq.queues import get_queue
from django_rq.workers import Worker
errors = []
try:
queue = get_queue()
Worker.all(queue.connection)
except Exception as e:
conn_settings = queue.connection.connection_pool.connection_kwargs
errors.append(checks.Critical(
_("Could not connect to Redis (%s)", e),
hint=_("Make sure Redis is running on "
"%(host)s:%(port)s") % conn_settings,
id="pootle.C001",
))
else:
redis_version = tuple(int(x) for x
in (queue.connection
.info()["redis_version"].split(".")))
if redis_version < REDIS_MINIMUM_REQUIRED_VERSION:
errors.append(checks.Critical(
_("Your version of Redis is too old."),
hint=_("Update your system's Redis server package to at least "
"version %s", str(REDIS_MINIMUM_REQUIRED_VERSION)),
id="pootle.C007",
))
if len(queue.connection.smembers(Worker.redis_workers_keys)) == 0:
# If we're not running 'pootle rqworker' report for whitelisted
# commands
if len(sys.argv) > 1 and sys.argv[1] in RQWORKER_WHITELIST:
errors.append(checks.Warning(
# Translators: a worker processes background tasks
_("No worker running."),
# Translators: a worker processes background tasks
hint=_("Run new workers with 'pootle rqworker'"),
id="pootle.W001",
))
return errors
@checks.register()
def check_settings(app_configs=None, **kwargs):
from django.conf import settings
errors = []
if "RedisCache" not in settings.CACHES.get("default", {}).get("BACKEND"):
errors.append(checks.Critical(
_("Cache backend is not set to Redis."),
hint=_("Set default cache backend to "
"django_redis.cache.RedisCache\n"
"Current settings: %r") % (settings.CACHES.get("default")),
id="pootle.C005",
))
else:
from django_redis import get_redis_connection
if not get_redis_connection():
errors.append(checks.Critical(
_("Could not initiate a Redis cache connection"),
hint=_("Double-check your CACHES settings"),
id="pootle.C004",
))
redis_cache_aliases = ("default", "redis", "lru")
redis_locations = set()
for alias in redis_cache_aliases:
if alias in settings.CACHES:
redis_locations.add(settings.CACHES.get(alias, {}).get("LOCATION"))
if len(redis_locations) < len(redis_cache_aliases):
errors.append(checks.Critical(
_("Distinct django_redis.cache.RedisCache configurations "
"are required for `default`, `redis` and `lru`."),
hint=_("Double-check your CACHES settings"),
id="pootle.C017",
))
if settings.DEBUG:
errors.append(checks.Warning(
_("DEBUG mode is on. Do not do this in production!"),
hint=_("Set DEBUG = False in Pootle settings"),
id="pootle.W005"
))
elif "sqlite" in settings.DATABASES.get("default", {}).get("ENGINE"):
# We don't bother warning about sqlite in DEBUG mode.
errors.append(checks.Warning(
_("The sqlite database backend is unsupported"),
hint=_("Set your default database engine to postgresql "
"or mysql"),
id="pootle.W006",
))
if settings.SESSION_ENGINE.split(".")[-1] not in ("cache", "cached_db"):
errors.append(checks.Warning(
_("Not using cached_db as session engine"),
hint=_("Set SESSION_ENGINE to "
"django.contrib.sessions.backend.cached_db\n"
"Current settings: %r") % (settings.SESSION_ENGINE),
id="pootle.W007",
))
if not settings.POOTLE_CONTACT_EMAIL and settings.POOTLE_CONTACT_ENABLED:
errors.append(checks.Warning(
_("POOTLE_CONTACT_EMAIL is not set."),
hint=_("Set POOTLE_CONTACT_EMAIL to allow users to contact "
"administrators through the Pootle contact form."),
id="pootle.W008",
))
if settings.POOTLE_CONTACT_EMAIL in ("info@YOUR_DOMAIN.com") \
and settings.POOTLE_CONTACT_ENABLED:
errors.append(checks.Warning(
_("POOTLE_CONTACT_EMAIL is using the following default "
"setting %r." % settings.POOTLE_CONTACT_EMAIL),
hint=_("POOTLE_CONTACT_EMAIL is the address that will receive "
"messages sent by the contact form."),
id="pootle.W011",
))
if not settings.DEFAULT_FROM_EMAIL:
errors.append(checks.Warning(
_("DEFAULT_FROM_EMAIL is not set."),
hint=_("DEFAULT_FROM_EMAIL is used in all outgoing Pootle email.\n"
"Don't forget to review your mail server settings."),
id="pootle.W009",
))
if settings.DEFAULT_FROM_EMAIL in ("info@YOUR_DOMAIN.com",
"webmaster@localhost"):
errors.append(checks.Warning(
_("DEFAULT_FROM_EMAIL is using the following default "
"setting %r." % settings.DEFAULT_FROM_EMAIL),
hint=_("DEFAULT_FROM_EMAIL is used in all outgoing Pootle email.\n"
"Don't forget to review your mail server settings."),
id="pootle.W010",
))
if settings.POOTLE_TM_SERVER:
tm_indexes = []
for server in settings.POOTLE_TM_SERVER:
if 'INDEX_NAME' not in settings.POOTLE_TM_SERVER[server]:
errors.append(checks.Critical(
_("POOTLE_TM_SERVER['%s'] has no INDEX_NAME.", server),
hint=_("Set an INDEX_NAME for POOTLE_TM_SERVER['%s'].",
server),
id="pootle.C008",
))
elif settings.POOTLE_TM_SERVER[server]['INDEX_NAME'] in tm_indexes:
errors.append(checks.Critical(
_("Duplicate '%s' INDEX_NAME in POOTLE_TM_SERVER.",
settings.POOTLE_TM_SERVER[server]['INDEX_NAME']),
hint=_("Set different INDEX_NAME for all servers in "
"POOTLE_TM_SERVER."),
id="pootle.C009",
))
else:
tm_indexes.append(
settings.POOTLE_TM_SERVER[server]['INDEX_NAME'])
if 'ENGINE' not in settings.POOTLE_TM_SERVER[server]:
errors.append(checks.Critical(
_("POOTLE_TM_SERVER['%s'] has no ENGINE.", server),
hint=_("Set a ENGINE for POOTLE_TM_SERVER['%s'].",
server),
id="pootle.C010",
))
if 'HOST' not in settings.POOTLE_TM_SERVER[server]:
errors.append(checks.Critical(
_("POOTLE_TM_SERVER['%s'] has no HOST.", server),
hint=_("Set a HOST for POOTLE_TM_SERVER['%s'].",
server),
id="pootle.C011",
))
if 'PORT' not in settings.POOTLE_TM_SERVER[server]:
errors.append(checks.Critical(
_("POOTLE_TM_SERVER['%s'] has no PORT.", server),
hint=_("Set a PORT for POOTLE_TM_SERVER['%s'].",
server),
id="pootle.C012",
))
if ('WEIGHT' in settings.POOTLE_TM_SERVER[server] and
not (0.0 <= settings.POOTLE_TM_SERVER[server]['WEIGHT']
<= 1.0)):
errors.append(checks.Warning(
_("POOTLE_TM_SERVER['%s'] has a WEIGHT less than 0.0 or "
"greater than 1.0", server),
hint=_("Set a WEIGHT between 0.0 and 1.0 (both included) "
"for POOTLE_TM_SERVER['%s'].", server),
id="pootle.W019",
))
for coefficient_name in EXPECTED_POOTLE_SCORES:
if coefficient_name not in settings.POOTLE_SCORES:
errors.append(checks.Critical(
_("POOTLE_SCORES has no %s.", coefficient_name),
hint=_("Set %s in POOTLE_SCORES.",
coefficient_name),
id="pootle.C014",
))
else:
coef = settings.POOTLE_SCORES[coefficient_name]
if not isinstance(coef, (float, int)):
errors.append(checks.Critical(
_("Invalid value for %s in POOTLE_SCORES.",
coefficient_name),
hint=_(
"Set a valid value for %s "
"in POOTLE_SCORES.", coefficient_name),
id="pootle.C015"))
return errors
@checks.register()
def check_settings_markup(app_configs=None, **kwargs):
from django.conf import settings
errors = []
try:
markup_filter = settings.POOTLE_MARKUP_FILTER[0]
except AttributeError:
errors.append(checks.Warning(
_("POOTLE_MARKUP_FILTER is missing."),
hint=_("Set POOTLE_MARKUP_FILTER."),
id="pootle.W012",
))
except (IndexError, TypeError, ValueError):
errors.append(checks.Warning(
_("Invalid value in POOTLE_MARKUP_FILTER."),
hint=_("Set a valid value for POOTLE_MARKUP_FILTER."),
id="pootle.W013",
))
else:
if markup_filter is not None:
try:
if markup_filter == 'textile':
import textile # noqa
elif markup_filter == 'markdown':
import markdown # noqa
elif markup_filter == 'restructuredtext':
import docutils # noqa
elif markup_filter == 'html':
pass
else:
errors.append(checks.Warning(
_("Invalid markup in POOTLE_MARKUP_FILTER."),
hint=_("Set a valid markup for POOTLE_MARKUP_FILTER."),
id="pootle.W014",
))
except ImportError:
errors.append(checks.Warning(
_("POOTLE_MARKUP_FILTER is set to '%s' markup, but the "
"package that provides can't be found.", markup_filter),
hint=_("Install the package or change "
"POOTLE_MARKUP_FILTER."),
id="pootle.W015",
))
if markup_filter is None:
errors.append(checks.Warning(
_("POOTLE_MARKUP_FILTER set to 'None' is deprecated."),
hint=_("Set your markup to 'html' explicitly."),
id="pootle.W025",
))
if markup_filter in ('html', 'textile', 'restructuredtext'):
errors.append(checks.Warning(
_("POOTLE_MARKUP_FILTER is using '%s' markup, which is "
"deprecated and will be removed in future.",
markup_filter),
hint=_("Convert your staticpages to Markdown and set your "
"markup to 'markdown'."),
id="pootle.W026",
))
return errors
@checks.register('data')
def check_users(app_configs=None, **kwargs):
from django.contrib.auth import get_user_model
errors = []
User = get_user_model()
try:
admin_user = User.objects.get(username='admin')
except (User.DoesNotExist, OperationalError, ProgrammingError):
pass
else:
if admin_user.check_password('admin'):
errors.append(checks.Warning(
_("The default 'admin' user still has a password set to "
"'admin'."),
hint=_("Remove the 'admin' user or change its password."),
id="pootle.W016",
))
return errors
@checks.register()
def check_db_transaction_hooks(app_configs=None, **kwargs):
from django.conf import settings
errors = []
if settings.DATABASES['default']['ENGINE'].startswith("transaction_hooks"):
errors.append(checks.Critical(
_("Database connection uses transaction_hooks."),
hint=_("Set the DATABASES['default']['ENGINE'] to use a Django "
"backend from django.db.backends."),
id="pootle.C006",
))
return errors
@checks.register()
def check_email_server_is_alive(app_configs=None, **kwargs):
from django.conf import settings
errors = []
if settings.POOTLE_SIGNUP_ENABLED or settings.POOTLE_CONTACT_ENABLED:
from django.core.mail import get_connection
connection = get_connection()
try:
connection.open()
except Exception:
errors.append(checks.Warning(
_("Email server is not available."),
hint=_("Review your email settings and make sure your email "
"server is working."),
id="pootle.W004",
))
else:
connection.close()
return errors
@checks.register('data')
def check_revision(app_configs=None, **kwargs):
from redis.exceptions import ConnectionError
from pootle.core.models import Revision
from pootle_store.models import Unit
errors = []
try:
revision = Revision.get()
except (ConnectionError):
return errors
try:
max_revision = Unit.max_revision()
except (OperationalError, ProgrammingError):
return errors
if revision is None or revision < max_revision:
errors.append(checks.Critical(
_("Revision is missing or has an incorrect value."),
hint=_("Run `revision --restore` to reset the revision counter."),
id="pootle.C016",
))
return errors
@checks.register()
def check_canonical_url(app_configs=None, **kwargs):
from django.conf import settings
from django.contrib.sites.models import Site
errors = []
no_canonical_error = checks.Critical(
_("No canonical URL provided and default site set to example.com."),
hint=_(
"Set the `POOTLE_CANONICAL_URL` in settings or update the "
"default site if you are using django.contrib.sites."),
id="pootle.C018")
localhost_canonical_warning = checks.Warning(
_("Canonical URL is set to http://localhost."),
hint=_(
"Set the `POOTLE_CANONICAL_URL` to an appropriate value for your "
"site or leave it empty if you are using `django.contrib.sites`."),
id="pootle.W020")
try:
contrib_site = Site.objects.get_current()
except (ProgrammingError, OperationalError):
if "django.contrib.sites" in settings.INSTALLED_APPS:
return []
contrib_site = None
uses_sites = (
not settings.POOTLE_CANONICAL_URL
and contrib_site)
if uses_sites:
site = Site.objects.get_current()
if site.domain == "example.com":
errors.append(no_canonical_error)
elif not settings.POOTLE_CANONICAL_URL:
errors.append(no_canonical_error)
elif settings.POOTLE_CANONICAL_URL == "http://localhost":
errors.append(localhost_canonical_warning)
return errors
@checks.register()
def check_pootle_fs_working_dir(app_configs=None, **kwargs):
import os
from django.conf import settings
missing_setting_error = checks.Critical(
_("POOTLE_FS_WORKING_PATH setting is not set."),
id="pootle.C019",
)
missing_directory_error = checks.Critical(
_("Path ('%s') pointed to by POOTLE_FS_WORKING_PATH doesn't exist."
% settings.POOTLE_FS_WORKING_PATH),
hint=_("Create the directory pointed to by `POOTLE_FS_WORKING_PATH`, "
"or change the setting."),
id="pootle.C020",
)
not_writable_directory_error = checks.Critical(
_("Path ('%s') pointed to by POOTLE_FS_WORKING_PATH is not writable by "
"Pootle."
% settings.POOTLE_FS_WORKING_PATH),
hint=_("Add the write permission to the `POOTLE_FS_WORKING_PATH` "
"or change the setting."),
id="pootle.C021",
)
errors = []
if not settings.POOTLE_FS_WORKING_PATH:
errors.append(missing_setting_error)
elif not os.path.exists(settings.POOTLE_FS_WORKING_PATH):
errors.append(missing_directory_error)
elif not os.access(settings.POOTLE_FS_WORKING_PATH, os.W_OK):
errors.append(not_writable_directory_error)
return errors
@checks.register()
def check_mysql_timezones(app_configs=None, **kwargs):
from django.db import connection
missing_mysql_timezone_tables = checks.Critical(
_("MySQL requires time zone settings."),
hint=("Load the time zone tables "
"http://dev.mysql.com/doc/refman/5.7/en/mysql-tzinfo-to-sql.html"),
id="pootle.C022",
)
errors = []
with connection.cursor() as cursor:
if hasattr(cursor.db, "mysql_version"):
cursor.execute("SELECT CONVERT_TZ(NOW(), 'UTC', 'UTC');")
converted_now = cursor.fetchone()[0]
if converted_now is None:
errors.append(missing_mysql_timezone_tables)
return errors
@checks.register()
def check_unsupported_python(app_configs=None, **kwargs):
errors = []
if sys.version_info >= (3, 0):
errors.append(checks.Critical(
_("Pootle does not yet support Python 3."),
hint=_("Use a Python 2.7 virtualenv."),
id="pootle.C023",
))
if sys.version_info < (2, 7):
errors.append(checks.Critical(
_("Pootle no longer supports Python versions older than 2.7"),
hint=_("Use a Python 2.7 virtualenv."),
id="pootle.C024",
))
return errors
| 22,506
|
Python
|
.py
| 523
| 31.996176
| 81
| 0.579464
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,095
|
settings.py
|
translate_pootle/pootle/settings.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import glob
import os
WORKING_DIR = os.path.abspath(os.path.dirname(__file__))
def working_path(filename):
"""Return an absolute path for :param:`filename` by joining it to
``WORKING_DIR``.
"""
return os.path.join(WORKING_DIR, filename)
conf_files_path = os.path.join(WORKING_DIR, 'settings', '*.conf')
conf_files = sorted(glob.glob(conf_files_path))
for f in conf_files:
execfile(os.path.abspath(f))
| 704
|
Python
|
.py
| 19
| 34.578947
| 77
| 0.728213
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,096
|
strings.py
|
translate_pootle/pootle/strings.py
|
# These are additional strings that we need for a fully localised Pootle. They
# come from Django and other dependencies and are not included in our POT file
# otherwise. This file itself is not used for a running Pootle.
# Rationale:
# Pootle sometimes needs one or two strings from an upstream project. We don't
# want to waste our localisers time translating the whole upstream project when
# we need only a few strings. In addition having them here makes it easy for
# the translator to easily correct linguistic issues.
# Notes:
# 1. Don't change any of these strings unless they changed in Django or the
# applicable Django app.
# 2. The adding of extra comments to help translators is fine.
# 3. If we ever rely on large parts of text from an upstream app, rather
# consider having translators work on the upstream translations.
# Fake imports
from pootle.i18n.gettext import ugettext as _
#########
# Django
#########
#######
# Apps
#######
###############
# Static pages
###############
# Commonly used terms to refer to Terms of Services, Privacy Policies, etc.
# We're anticipating possible link text for these pages so that the UI will
# remain 100% translated.
# Translators: Label that refers to the site's privacy policy
_("Privacy Policy")
# Translators: Label that refers to the site's legal requirements
_("Legal")
# Translators: Label that refers to a legally mandated statement of the
# ownership and authorship of a document, which must be included in ...
# websites published in Germany and certain other German-speaking countries,
# such as Austria and Switzerland. See https://en.wikipedia.org/wiki/Impressum
_("Imprint")
# Translators: Label that refers to the site's license requirements
_("License")
# Translators: Label that refers to the site's license requirements
_("License Statement")
# Translators: Label that refers to the site's license requirements
_("Contributor License")
# Translators: Label that refers to the site's terms of use
_("Terms of Use")
# Translators: Label that refers to the site's terms of service
_("Terms of Service")
# Translators: Label that refers to the site's getting started guide
_("Getting Started")
| 2,181
|
Python
|
.py
| 49
| 43.326531
| 79
| 0.763071
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,097
|
urls.py
|
translate_pootle/pootle/urls.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from django.conf import settings
from django.conf.urls import include, url
from django.views.generic import TemplateView
from pootle.core.delegate import url_patterns
urlpatterns = []
# Allow url handlers to be overriden by plugins
for delegate_urls in url_patterns.gather().values():
urlpatterns += delegate_urls
urlpatterns += [
# Allauth
url(r'^accounts/', include('accounts.urls')),
url(r'^accounts/', include('allauth.urls')),
]
# XXX should be autodiscovered
if "import_export" in settings.INSTALLED_APPS:
urlpatterns += [
# Pootle offline translation support URLs.
url(r'', include('import_export.urls')),
]
urlpatterns += [
# External apps
url(r'^contact/', include('contact.urls')),
url(r'', include('pootle_profile.urls')),
# Pootle URLs
url(r'', include('staticpages.urls')),
url(r'^help/quality-checks/',
TemplateView.as_view(template_name="help/quality_checks.html"),
name='pootle-checks-descriptions'),
url(r'', include('pootle_app.urls')),
url(r'^projects/', include('pootle_project.urls')),
url(r'', include('pootle_terminology.urls')),
url(r'', include('pootle_statistics.urls')),
url(r'', include('pootle_store.urls')),
url(r'', include('pootle_language.urls')),
url(r'', include('pootle_translationproject.urls')),
]
# TODO: handler400
handler403 = 'pootle.core.views.permission_denied'
handler404 = 'pootle.core.views.page_not_found'
handler500 = 'pootle.core.views.server_error'
| 1,794
|
Python
|
.py
| 47
| 34.638298
| 77
| 0.708525
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,098
|
constants.py
|
translate_pootle/pootle/constants.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
VERSION = (2, 9, 0, 'rc', 1)
# Minimum Django version required for Pootle to run.
DJANGO_MINIMUM_REQUIRED_VERSION = (1, 10, 8)
| 404
|
Python
|
.py
| 10
| 39.2
| 77
| 0.737245
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
15,099
|
runner.py
|
translate_pootle/pootle/runner.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from __future__ import print_function
import logging
import os
import sys
from argparse import SUPPRESS, ArgumentParser
from django.conf import settings
from django.core import management
import syspath_override # noqa
from pootle.core.cache import PERSISTENT_STORES
from pootle.core.log import cmd_log
logger = logging.getLogger(__name__)
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
handler = logging.StreamHandler()
handler.setFormatter(formatter)
logger.addHandler(handler)
#: Length for the generated :setting:`SECRET_KEY`
KEY_LENGTH = 50
#: Default path for the settings file
SYSTEM_SETTINGS_PATH = os.path.join('/etc', 'pootle', 'pootle.conf')
HOME_SETTINGS_PATH = os.path.join('~', '.pootle', 'pootle.conf')
if "VIRTUAL_ENV" in os.environ:
VENV_SETTINGS_PATH = os.path.join(os.environ["VIRTUAL_ENV"], "pootle.conf")
else:
VENV_SETTINGS_PATH = ""
DEFAULT_SETTINGS_PATH = ":".join(
[SYSTEM_SETTINGS_PATH,
HOME_SETTINGS_PATH,
VENV_SETTINGS_PATH])
# Python 2+3 support for input()
if sys.version_info[0] < 3:
input = raw_input
def add_help_to_parser(parser):
parser.add_help = True
parser.add_argument("-h", "--help",
action="help", default=SUPPRESS,
help="Show this help message and exit")
def init_settings(settings_filepath, template_filename,
db="sqlite", db_name="dbs/pootle.db", db_user="",
db_password="", db_host="", db_port=""):
"""Initializes a sample settings file for new installations.
:param settings_filepath: The target file path where the initial settings
will be written to.
:param template_filename: Template file used to initialize settings from.
:param db: Database engine to use
(default=sqlite, choices=[mysql, postgresql]).
:param db_name: Database name (default: pootledb) or path to database file
if using sqlite (default: dbs/pootle.db)
:param db_user: Name of the database user. Not used with sqlite.
:param db_password: Password for the database user. Not used with sqlite.
:param db_host: Database host. Defaults to localhost. Not used with sqlite.
:param db_port: Database port. Defaults to backend default. Not used with
sqlite.
"""
from base64 import b64encode
dirname = os.path.dirname(settings_filepath)
if dirname and not os.path.exists(dirname):
os.makedirs(dirname)
if db == "sqlite":
db_name = "working_path('%s')" % (db_name or "dbs/pootle.db")
db_user = db_password = db_host = db_port = "''"
else:
db_name = "'%s'" % (db_name or "pootledb")
db_user = "'%s'" % (db_user or "pootle")
db_password = "'%s'" % db_password
db_host = "'%s'" % db_host
db_port = "'%s'" % db_port
db_module = {
'sqlite': 'sqlite3',
'mysql': 'mysql',
'postgresql': 'postgresql',
}[db]
context = {
"default_key": ("'%s'"
% b64encode(os.urandom(KEY_LENGTH)).decode("utf-8")),
"db_engine": "'django.db.backends.%s'" % db_module,
"db_name": db_name,
"db_user": db_user,
"db_password": db_password,
"db_host": db_host,
"db_port": db_port,
}
with open(settings_filepath, 'w') as settings:
with open(template_filename) as template:
settings.write(
(template.read().decode("utf8") % context).encode("utf8"))
def init_command(parser, args):
"""Parse and run the `pootle init` command
:param parser: `argparse.ArgumentParser` instance to use for parsing
:param args: Arguments to call init command with.
"""
src_dir = os.path.abspath(os.path.dirname(__file__))
add_help_to_parser(parser)
parser.add_argument("--yes", "-y",
dest='overwrite_template',
default=False,
action='store_true',
help=(u"Overwrite existing configuration file "
"without asking."))
parser.add_argument("--dev",
dest='settings_template',
default=os.path.join(src_dir,
'settings/90-local.conf.template'),
const=os.path.join(src_dir,
'settings/90-dev-local.conf.template'),
action='store_const',
help=(u"Use a development configuration."))
parser.add_argument("--db",
default="sqlite",
choices=['sqlite', 'mysql', 'postgresql'],
help=(u"Use the specified database backend (default: "
u"%(default)s)."))
parser.add_argument("--db-name", default="",
help=(u"Database name (default: 'pootledb') or path "
u"to database file if using sqlite (default: "
u"'%s/dbs/pootle.db')" % src_dir))
parser.add_argument("--db-user", default="",
help=(u"Name of the database user. Not used with "
u"sqlite."))
parser.add_argument("--db-host", default="",
help=(u"Database host. Defaults to localhost. Not "
u"used with sqlite."))
parser.add_argument("--db-port", default="",
help=(u"Database port. Defaults to backend default. "
u"Not used with sqlite."))
args, remainder_ = parser.parse_known_args(args)
config_path = args.config or VENV_SETTINGS_PATH or HOME_SETTINGS_PATH
if os.path.exists(config_path):
resp = None
if args.overwrite_template:
resp = "yes"
elif args.noinput:
resp = 'n'
else:
resp = input("File already exists at %r, overwrite? [Ny] "
% config_path).lower()
if resp not in ("y", "yes"):
logger.error("File already exists, not overwriting.")
exit(2)
try:
init_settings(
config_path,
args.settings_template,
db=args.db,
db_name=args.db_name,
db_user=args.db_user,
db_host=args.db_host,
db_port=args.db_port)
except (IOError, OSError) as e:
raise e.__class__('Unable to write default settings file to %r'
% config_path)
if args.db in ['mysql', 'postgresql']:
logger.warn(
"Configuration file created at %r. Your database password is "
"not currently set . You may want to update the database "
"settings now",
config_path)
else:
logger.info("Configuration file created at %r", config_path)
def set_sync_mode(noinput=False):
"""Sets ASYNC = False on all redis worker queues
"""
from .core.utils.redis_rq import rq_workers_are_running
if rq_workers_are_running():
redis_warning = ("\nYou currently have RQ workers running.\n\n"
"Running in synchronous mode may conflict with jobs "
"that are dispatched to your workers.\n\n"
"It is safer to stop any workers before using "
"synchronous commands.\n\n")
if noinput:
logger.warn(redis_warning)
else:
resp = input("%sDo you wish to proceed? [Ny] " % redis_warning)
if resp not in ("y", "yes"):
logger.error("RQ workers running, not proceeding.")
exit(2)
# Update settings to set queues to ASYNC = False.
for q in settings.RQ_QUEUES.itervalues():
q['ASYNC'] = False
def configure_app(project, config_paths, django_settings_module, runner_name):
"""Determines which settings file to use and sets environment variables
accordingly.
:param project: Project's name. Will be used to generate the settings
environment variable.
:param config_paths: The paths to the user's configuration file(s).
:param django_settings_module: The module that ``DJANGO_SETTINGS_MODULE``
will be set to.
:param runner_name: The name of the running script.
"""
settings_envvar = project.upper() + '_SETTINGS'
config_paths = (
config_paths
or os.environ.get(
settings_envvar,
DEFAULT_SETTINGS_PATH))
# Normalize path and expand ~ constructions
_config_paths = [
os.path.normpath(
os.path.abspath(os.path.expanduser(config_path),))
for config_path
in config_paths.split(":")]
missing_config = (
not any(
os.path.exists(config_path)
for config_path
in _config_paths))
if not config_paths:
logger.warn(
u"%r environment variable has not been set.\n",
settings_envvar)
elif missing_config:
logger.error(
u"Configuration file does not exist at %(config_path)r. "
u"Use '%(runner_name)s init' to initialize the configuration file.",
dict(config_path=VENV_SETTINGS_PATH or HOME_SETTINGS_PATH,
runner_name=runner_name))
sys.exit(1)
os.environ.setdefault(settings_envvar, ":".join(_config_paths))
os.environ.setdefault('DJANGO_SETTINGS_MODULE', django_settings_module)
def run_app(project, django_settings_module):
"""Wrapper around django-admin.py.
:param project: Project's name.
:param django_settings_module: The module that ``DJANGO_SETTINGS_MODULE``
will be set to.
"""
runner_name = os.path.basename(sys.argv[0])
# This parser should ignore the --help flag, unless there is no subcommand
parser = ArgumentParser(add_help=False)
parser.add_argument("--version", action="version",
version=get_version())
# Print version and exit if --version present
args, remainder = parser.parse_known_args(sys.argv[1:])
# Add pootle args
parser.add_argument(
"--config",
default="",
help=u"Use the specified configuration file.",
)
parser.add_argument(
"--noinput",
action="store_true",
default=False,
help=u"Never prompt for input",
)
parser.add_argument(
"--no-rq",
action="store_true",
default=False,
help=(u"Run all jobs in a single process, without "
"using rq workers"),
)
# Parse the init command by hand to prevent raising a SystemExit while
# parsing
args_provided = [c for c in sys.argv[1:] if not c.startswith("-")]
if args_provided and args_provided[0] == "init":
init_command(parser, sys.argv[1:])
sys.exit(0)
args, remainder = parser.parse_known_args(sys.argv[1:])
# Configure settings from args.config path
configure_app(
project=project,
config_paths=args.config,
django_settings_module=django_settings_module,
runner_name=runner_name)
# If no CACHES backend set tell user and exit. This prevents raising
# ImproperlyConfigured error on trying to run any pootle commands
# NB: it may be possible to remove this when #4006 is fixed
caches = settings.CACHES.keys()
for cache in PERSISTENT_STORES:
if cache not in caches:
sys.stdout.write("\nYou need to configure the CACHES setting, "
"or to use the defaults remove CACHES from %s\n\n"
"Once you have fixed the CACHES setting you should "
"run 'pootle check' again\n\n"
% args.config)
sys.exit(2)
# Set synchronous mode
if args.no_rq:
set_sync_mode(args.noinput)
# Print the help message for "pootle --help"
if len(remainder) == 1 and remainder[0] in ["-h", "--help"]:
add_help_to_parser(parser)
parser.parse_known_args(sys.argv[1:])
command = [runner_name] + remainder
# Respect the noinput flag
if args.noinput:
command += ["--noinput"]
cmd_log(runner_name, *sys.argv[1:])
management.execute_from_command_line(command)
sys.exit(0)
def get_version():
from pootle import __version__
from pootle.core.utils.version import get_git_hash
from translate import __version__ as tt_version
from django import get_version as django_version
githash = get_git_hash()
if githash:
githash = "[%s] " % githash
return ("Pootle %s %s(Django %s, Translate Toolkit %s)" %
(__version__, githash or '', django_version(), tt_version.sver))
def main():
run_app(project='pootle', django_settings_module='pootle.settings')
if __name__ == '__main__':
main()
| 13,266
|
Python
|
.py
| 311
| 33.07717
| 82
| 0.600217
|
translate/pootle
| 1,486
| 288
| 526
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|