././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1621769527.0 SQLAlchemy-i18n-1.1.0/0000755000076500000240000000000000000000000014653 5ustar00konstastaff00000000000000././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1621769373.0 SQLAlchemy-i18n-1.1.0/CHANGES.rst0000644000076500000240000001252400000000000016461 0ustar00konstastaff00000000000000Changelog --------- Here you can see the full list of changes between each SQLAlchemy-i18n release. 1.1.0 (2021-05-23) ^^^^^^^^^^^^^^^^^^ - Added SA 1.4 support - Drop py27, py33, py34, py35 support 1.0.3 (2017-01-30) ^^^^^^^^^^^^^^^^^^ - Set autoincrement as False for translation class inherited primary keys 1.0.2 (2016-03-06) ^^^^^^^^^^^^^^^^^^ - Added ``translations_relationship_args`` configuration option - Added ``foreign_key_args`` parameter to ``translations_base`` function 1.0.1 (2014-10-21) ^^^^^^^^^^^^^^^^^^ - Made current_locale expression a GenericFunction 1.0 (2014-10-21) ^^^^^^^^^^^^^^^^ - Made current_translation work with same schematics as class variable and object variable. - Added get_fallback_locale utility function - Added fallback_translation hybrid property 0.9.0 (2014-09-30) ^^^^^^^^^^^^^^^^^^ - Added support for classical SQLAlchemy mappings 0.8.4 (2014-04-21) ^^^^^^^^^^^^^^^^^^ - Added enhanced column aliases handling - Updated SQLAlchemy-Utils dependency to 0.25.3 0.8.3 (2014-02-15) ^^^^^^^^^^^^^^^^^^ - Fixed infinite recursion issue with UnknownLocaleError when given object repr() uses translated columns 0.8.2 (2014-02-07) ^^^^^^^^^^^^^^^^^^ - Add custom base class support for translation_base - Better exception message for UnknownLocaleError 0.8.1 (2014-02-07) ^^^^^^^^^^^^^^^^^^ - Fixed common base class handling (__translatable__ args copied to each child class now) 0.8.0 (2014-02-06) ^^^^^^^^^^^^^^^^^^ - Add _translations relationship for translatable classes - Rewritten relationship model for translatable classes - New more robust syntax for declaring translation models - Composite primary key support for translation parent classes 0.7.1 (2013-10-10) ^^^^^^^^^^^^^^^^^^ - Added default_locale utility function 0.7.0 (2013-10-10) ^^^^^^^^^^^^^^^^^^ - Translatable.translations now a hybrid property instead of regular property (allows flexible querying) - New utility function find_translations 0.6.13 (2013-10-07) ^^^^^^^^^^^^^^^^^^^ - Fixed hybrid property collision detection for single table inheritance 0.6.12 (2013-10-07) ^^^^^^^^^^^^^^^^^^^ - Added property collision detection for generated hybrid properties - Added hybrid property exclusion for hybrid property generator 0.6.11 (2013-10-07) ^^^^^^^^^^^^^^^^^^^ - Hybrid property builder now checks for manager options if class option 'default_locale' is not set. 0.6.10 (2013-09-16) ^^^^^^^^^^^^^^^^^^^ - Support for callables as default locales 0.6.9 (2013-09-13) ^^^^^^^^^^^^^^^^^^ - Fixed object to string conversion in current_translation methods 0.6.8 (2013-09-11) ^^^^^^^^^^^^^^^^^^ - Fixed fatal bug in set_not_nullables_to_empty_strings which would cause setting of already assigned translation columns to empty strings 0.6.7 (2013-09-11) ^^^^^^^^^^^^^^^^^^ - Listener set_not_nullables_to_empty_strings invoked even if locale object already exists 0.6.6 (2013-09-10) ^^^^^^^^^^^^^^^^^^ - Translation auto generation with nullable to empty string auto setting now works with join table inheritance 0.6.5 (2013-09-10) ^^^^^^^^^^^^^^^^^^ - Translation auto creation now sets not nullable translated columns without defaults as empty strings 0.6.4 (2013-09-10) ^^^^^^^^^^^^^^^^^^ - Translation hybrid properties now fallback to default locale for empty strings 0.6.3 (2013-08-15) ^^^^^^^^^^^^^^^^^^ - Added get_locale_fallback option 0.6.2 (2013-08-13) ^^^^^^^^^^^^^^^^^^ - Fixed translation auto-creation 0.6.1 (2013-08-13) ^^^^^^^^^^^^^^^^^^ - Added unified and easily overridable global configuration 0.6.0 (2013-08-09) ^^^^^^^^^^^^^^^^^^ - Completely rewritten translation relationships 0.5.1 (2013-06-26) ^^^^^^^^^^^^^^^^^^ - Translation auto creation listener added 0.5.0 (2013-06-25) ^^^^^^^^^^^^^^^^^^ - Added TranslationManager 0.4.1 (2013-06-11) ^^^^^^^^^^^^^^^^^^ - Base classes option no longer mandatory 0.4.0 (2013-06-10) ^^^^^^^^^^^^^^^^^^ - New, more extendable syntax for setting up translatable models (make_translatable utility function) 0.3.2 (2013-06-05) ^^^^^^^^^^^^^^^^^^ - Fixed current_translation proxy window building 0.3.1 (2013-06-04) ^^^^^^^^^^^^^^^^^^ - Updated SQLAlchemy-Utils requirements to 0.12.4 0.3.0 (2013-05-30) ^^^^^^^^^^^^^^^^^^ - Added force_locale - Rewrote current_translation schematics 0.2.4 (2013-05-29) ^^^^^^^^^^^^^^^^^^ - Updated SQLAlchemy-Utils requirements to 0.12.2 0.2.3 (2013-05-20) ^^^^^^^^^^^^^^^^^^ - Renamed __locale_getter__ to get_locale 0.2.2 (2013-05-20) ^^^^^^^^^^^^^^^^^^ - Made __locale_getter__ a class attribute for more robust overriding 0.2.1 (2013-05-19) ^^^^^^^^^^^^^^^^^^ - Added hybrid_property expressions for current_translation and translations 0.2.0 (2013-05-17) ^^^^^^^^^^^^^^^^^^ - ProxyDict moved to SQLAlchemy-Utils - SQLAlchemy-Utils added as dependency - Completely rewritten inheritance handling 0.1.5 (2013-05-16) ^^^^^^^^^^^^^^^^^^ - Column locale defined right after primary keys 0.1.4 (2013-05-16) ^^^^^^^^^^^^^^^^^^ - Fixed translatable options handling when using common base class 0.1.3 (2013-05-16) ^^^^^^^^^^^^^^^^^^ - Joined table inheritance support 0.1.2 (2013-05-15) ^^^^^^^^^^^^^^^^^^ - Added base_classes configuration option 0.1.1 (2013-05-15) ^^^^^^^^^^^^^^^^^^ - Generated translations class names now in format '[ParentClass]Translation' 0.1.0 (2013-05-13) ^^^^^^^^^^^^^^^^^^ - Initial release ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1390482397.0 SQLAlchemy-i18n-1.1.0/LICENSE0000644000076500000240000000263500000000000015666 0ustar00konstastaff00000000000000Copyright (c) 2012, Konsta Vesterinen All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * The names of the contributors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1390482397.0 SQLAlchemy-i18n-1.1.0/MANIFEST.in0000644000076500000240000000030100000000000016403 0ustar00konstastaff00000000000000include CHANGES.rst LICENSE README.rst recursive-include tests * recursive-exclude tests *.pyc recursive-include docs * recursive-exclude docs *.pyc prune docs/_build exclude docs/_themes/.git ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1621769527.0 SQLAlchemy-i18n-1.1.0/PKG-INFO0000644000076500000240000000176500000000000015761 0ustar00konstastaff00000000000000Metadata-Version: 2.1 Name: SQLAlchemy-i18n Version: 1.1.0 Summary: Internationalization extension for SQLAlchemy models. Home-page: https://github.com/kvesteri/sqlalchemy-i18n Author: Konsta Vesterinen Author-email: konsta@fastmonkeys.com License: BSD Description: SQLAlchemy-i18n --------------- Internationalization extension for SQLAlchemy models. Platform: any Classifier: Environment :: Web Environment Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: BSD License Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.6 Classifier: Programming Language :: Python :: 3.7 Classifier: Programming Language :: Python :: 3.8 Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content Classifier: Topic :: Software Development :: Libraries :: Python Modules Requires-Python: >=3.6 Provides-Extra: test ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1485797088.0 SQLAlchemy-i18n-1.1.0/README.rst0000644000076500000240000000464600000000000016354 0ustar00konstastaff00000000000000SQLAlchemy-i18n =============== |Build Status| |Version Status| |Downloads| Internationalization extension for SQLAlchemy models. Features -------- - Stores translations in separate tables. - Reflects translation table structures based on parent model table structure. - Supports forcing of given locale. - Good performance (uses proxy dicts and other advanced SQLAlchemy concepts for performance optimization) Basic Usage ----------- Consider you have already defined SQLAlchemy connections and declarative base as follows: .. code-block:: python from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base engine = create_engine( 'postgres://postgres@localhost/sqlalchemy_i18n' ) Base = declarative_base() You only need to define two things, first you have to make the desired mapper translatable using make_translatable() function. Internally this function attaches two sqlalchemy event listeners for given mapper. NOTICE: Calling make_translatable() for given mapper should happen only once per application. .. code-block:: python from sqlalchemy_i18n import make_translatable make_translatable(sa.orm.mapper) Secondly you need to define translatable models. In the following example we add translatable Article model with two translatable properties (name and content). .. code-block:: python import sqlalchemy as sa from sqlalchemy_i18n import Translatable, translation_base class Article(Base, Translatable): id = sa.Column(sa.Integer, autoincrement=True, primary_key=True) description = sa.Column(sa.UnicodeText) class ArticleTranslation(translation_base(Article)): __tablename__ = 'article_translation' name = sa.Column(sa.Unicode(255)) content = sa.Column(sa.UnicodeText) Resources --------- - `Documentation `_ - `Issue Tracker `_ - `Code `_ .. |Build Status| image:: https://travis-ci.org/kvesteri/sqlalchemy-i18n.png?branch=master :target: https://travis-ci.org/kvesteri/sqlalchemy-i18n .. |Version Status| image:: https://img.shields.io/pypi/v/SQLAlchemy-i18n.svg :target: https://pypi.python.org/pypi/SQLAlchemy-i18n/ .. |Downloads| image:: https://img.shields.io/pypi/dm/SQLAlchemy-i18n.svg :target: https://pypi.python.org/pypi/SQLAlchemy-i18n/ ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1621769527.0 SQLAlchemy-i18n-1.1.0/SQLAlchemy_i18n.egg-info/0000755000076500000240000000000000000000000021146 5ustar00konstastaff00000000000000././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1621769527.0 SQLAlchemy-i18n-1.1.0/SQLAlchemy_i18n.egg-info/PKG-INFO0000644000076500000240000000176500000000000022254 0ustar00konstastaff00000000000000Metadata-Version: 2.1 Name: SQLAlchemy-i18n Version: 1.1.0 Summary: Internationalization extension for SQLAlchemy models. Home-page: https://github.com/kvesteri/sqlalchemy-i18n Author: Konsta Vesterinen Author-email: konsta@fastmonkeys.com License: BSD Description: SQLAlchemy-i18n --------------- Internationalization extension for SQLAlchemy models. Platform: any Classifier: Environment :: Web Environment Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: BSD License Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.6 Classifier: Programming Language :: Python :: 3.7 Classifier: Programming Language :: Python :: 3.8 Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content Classifier: Topic :: Software Development :: Libraries :: Python Modules Requires-Python: >=3.6 Provides-Extra: test ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1621769527.0 SQLAlchemy-i18n-1.1.0/SQLAlchemy_i18n.egg-info/SOURCES.txt0000644000076500000240000000302500000000000023032 0ustar00konstastaff00000000000000CHANGES.rst LICENSE MANIFEST.in README.rst setup.py SQLAlchemy_i18n.egg-info/PKG-INFO SQLAlchemy_i18n.egg-info/SOURCES.txt SQLAlchemy_i18n.egg-info/dependency_links.txt SQLAlchemy_i18n.egg-info/not-zip-safe SQLAlchemy_i18n.egg-info/requires.txt SQLAlchemy_i18n.egg-info/top_level.txt docs/.DS_Store docs/Makefile docs/basic.rst docs/conf.py docs/config.rst docs/index.rst docs/installation.rst docs/license.rst docs/make.bat docs/queries.rst docs/quickstart.rst sqlalchemy_i18n/__init__.py sqlalchemy_i18n/builders.py sqlalchemy_i18n/comparators.py sqlalchemy_i18n/exc.py sqlalchemy_i18n/expressions.py sqlalchemy_i18n/manager.py sqlalchemy_i18n/translatable.py sqlalchemy_i18n/utils.py tests/__init__.py tests/test_common_base_class.py tests/test_comparator.py tests/test_composite_primary_key.py tests/test_configuration.py tests/test_current_translation_property.py tests/test_current_translation_property_with_locale.py tests/test_custom_base_class.py tests/test_expressions.py tests/test_fallback_locale_as_callable.py tests/test_fallback_locale_without_class_default.py tests/test_fallback_translation.py tests/test_find_translations.py tests/test_hybrid_property_as_dynamic_source_locale.py tests/test_hybrid_property_exclusion.py tests/test_join_expressions.py tests/test_joined_loading.py tests/test_joined_table_inheritance.py tests/test_property_collision.py tests/test_relationships.py tests/test_translatable.py tests/test_translation_auto_creation.py tests/test_translation_auto_creation_with_non_nullables.py tests/test_translation_mapping.py././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1621769527.0 SQLAlchemy-i18n-1.1.0/SQLAlchemy_i18n.egg-info/dependency_links.txt0000644000076500000240000000000100000000000025214 0ustar00konstastaff00000000000000 ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1390995515.0 SQLAlchemy-i18n-1.1.0/SQLAlchemy_i18n.egg-info/not-zip-safe0000644000076500000240000000000100000000000023374 0ustar00konstastaff00000000000000 ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1621769527.0 SQLAlchemy-i18n-1.1.0/SQLAlchemy_i18n.egg-info/requires.txt0000644000076500000240000000025600000000000023551 0ustar00konstastaff00000000000000SQLAlchemy>=1.3 SQLAlchemy-Utils>=0.37.3 six>=1.4.1 [test] pytest>=2.2.3 Pygments>=1.2 Jinja2>=2.3 docutils>=0.10 flexmock>=0.9.7 psycopg2>=2.4.6 flake8>=2.4.0 isort>=3.9.6 ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1621769527.0 SQLAlchemy-i18n-1.1.0/SQLAlchemy_i18n.egg-info/top_level.txt0000644000076500000240000000002000000000000023670 0ustar00konstastaff00000000000000sqlalchemy_i18n ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1621769527.0 SQLAlchemy-i18n-1.1.0/docs/0000755000076500000240000000000000000000000015603 5ustar00konstastaff00000000000000././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1413885871.0 SQLAlchemy-i18n-1.1.0/docs/.DS_Store0000644000076500000240000001400400000000000017265 0ustar00konstastaff00000000000000Bud1  ldIlocblob _buildIlocblobF(  _buildbwspblob▄bplist00╪  ]ShowStatusBar[ShowPathbar[ShowToolbar[ShowTabView_ContainerShowSidebar\WindowBounds\SidebarWidth[ShowSidebar  _{{255, 318}, {770, 460}}Е '3?Kbo|ИЙКЛМНикл_buildvSrnlong basic.rstIlocblob╠(      conf.pyIlocblobR(       config.rstIlocblob╪(       index.rstIlocblobFШ      installation.rstIlocblobR       license.rstIlocblob╠Ш      make.batIlocblobRШ      MakefileIlocblob╪Ш       queries.rstIlocblobF      quickstart.rstIlocblob╠        @А @А @А @ E DSDB `А @А @А @././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1390482397.0 SQLAlchemy-i18n-1.1.0/docs/Makefile0000644000076500000240000001521600000000000017250 0ustar00konstastaff00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # User-friendly check for sphinx-build ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) endif # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " xml to make Docutils-native XML files" @echo " pseudoxml to make pseudoxml-XML files for display purposes" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/SQLAlchemy-i18n.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/SQLAlchemy-i18n.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/SQLAlchemy-i18n" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/SQLAlchemy-i18n" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." latexpdfja: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through platex and dvipdfmx..." $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." xml: $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml @echo @echo "Build finished. The XML files are in $(BUILDDIR)/xml." pseudoxml: $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml @echo @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1413888564.0 SQLAlchemy-i18n-1.1.0/docs/basic.rst0000644000076500000240000000427000000000000017421 0ustar00konstastaff00000000000000 Basic usage =========== Current translation ------------------- Current translation is a hybrid property in parent object that returns the associated translation object for current locale.:: article = Article() article.current_translation.name = 'Some article' You can also directly set the current translation:: article.current_translation = ArticleTranslation(name='Some article') Articles and translations can be efficiently fetched using various SQLAlchemy loading strategies:: session.query(Article).options(joinedload(Article.current_translation)) Fallback translation -------------------- If there is no translation available for the current locale then fallback locale is being used. Fallback translation is a convenient hybrid property for accessing this translation object.:: article = Article() article.translations.en.name = 'Some article' article.fallback_translation.name # Some article Fallback translation is especially handy in situations where you don't necessarily have all the objects translated in various languages but need to fetch them efficiently. :: query = ( session.query(Article) .options(joinedload(Article.current_translation)) .options(joinedload(Article.fallback_translation)) ) Translatable columns as hybrids ------------------------------- For each translatable column SQLAlchemy-i18n creates a hybrid property in the parent class. These hybrid properties always point at the current translation. Example: :: article = Article() article.name = u'Some article' article.translations['en'].name # u'Some article' If the there is no translation available for current locale then these hybrids return the translation for fallback locale. Let's assume the current locale here is 'fi':: article = Article() article.translations.fi.name = '' article.translations.en.name = 'Some article' article.name # 'Some article' Accessing translations ---------------------- Dictionary based access:: article.translations['en'].name = u'Some article' Attribute access:: article.translations.en.name = u'Some article' article.translations.fi.name = u'Joku artikkeli' ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1390482397.0 SQLAlchemy-i18n-1.1.0/docs/conf.py0000644000076500000240000002025600000000000017107 0ustar00konstastaff00000000000000# -*- coding: utf-8 -*- # # SQLAlchemy-i18n documentation build configuration file, created by # sphinx-quickstart on Wed Sep 11 11:27:08 2013. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath('..')) from sqlalchemy_i18n import __version__ # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.intersphinx', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.ifconfig', 'sphinx.ext.viewcode'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'SQLAlchemy-i18n' copyright = u'2013, Konsta Vesterinen' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = __version__ # The full version, including alpha/beta/rc tags. release = version # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'SQLAlchemy-i18ndoc' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'SQLAlchemy-i18n.tex', u'SQLAlchemy-i18n Documentation', u'Konsta Vesterinen', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'sqlalchemy-i18n', u'SQLAlchemy-i18n Documentation', [u'Konsta Vesterinen'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'SQLAlchemy-i18n', u'SQLAlchemy-i18n Documentation', u'Konsta Vesterinen', 'SQLAlchemy-i18n', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = {'http://docs.python.org/': None} ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1457259452.0 SQLAlchemy-i18n-1.1.0/docs/config.rst0000644000076500000240000000653700000000000017615 0ustar00konstastaff00000000000000Configuration ============= Several configuration options exists for SQLAlchemy-i18n. Each of these options can be set at either manager level or model level. Setting options an manager level affects all models using given translation manager where as model level configuration only affects given model. Dynamic source locale --------------------- Sometimes you may want to have dynamic source (default) locale. This can be achieved by setting `dynamic_source_locale` as `True`. Consider the following model definition:: class Article(Base): __tablename__ = 'article' __translatable__ =┬а{ 'locales': [u'en', u'fi'], 'dynamic_source_locale': True } id = sa.Column(sa.Integer, primary_key=True, autoincrement=True) author = sa.Column(sa.Unicode(255)) def get_locale(self): return 'en' class ArticleTranslation(translation_base(Article)): __tablename__ = 'article_translation' name = sa.Column(sa.Unicode(255)) content = sa.Column(sa.UnicodeText) Now you can use the dynamic source locales as follows:: article = Article(locale='fi', name=u'Joku artikkeli') article.name == article.translations['fi'].name # True article2 = Article(locale='en', name=u'Some article) article2.name == article.translations['en'].name # True As with regular translations, the translations using dynamic source locales can even be fetched efficiently using good old SQLAlchemy loading constructs:: articles = ( session.query(Article) .options(sa.orm.joinedload(Article.current_translation)) ) # loads translations based on the locale in the parent class Other options ------------- * locales Defines the list of locales that given model or manager supports * auto_create_locales Whether or not to auto-create all locales whenever some of the locales is created. By default this option is True. It is highly recommended to leave this as True, since not creating all locales at once can lead to problems in multithreading environments. Consider for example the following situtation. User creates a translatable Article which has two translatable fields (name and content). At the first request this article is created along with one translation table entry with locale 'en'. After this two users edit the finnish translation of this article at the same time. The application tries to create finnish translation twice resulting in database integrity errors. * fallback_locale The locale which will be used as a fallback for translation hybrid properties that return None or empty string. * translations_relationship_args Dictionary of arguments passed as defaults for automatically created translations relationship.:: class Article(Base): __tablename__ = 'article' __translatable__ =┬а{ 'locales': [u'en', u'fi'], 'translations_relationship_args': { 'passive_deletes': False } } id = sa.Column(sa.Integer, primary_key=True, autoincrement=True) author = sa.Column(sa.Unicode(255)) def get_locale(self): return 'en' class ArticleTranslation(translation_base(Article)): __tablename__ = 'article_translation' name = sa.Column(sa.Unicode(255)) content = sa.Column(sa.UnicodeText) ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1391081315.0 SQLAlchemy-i18n-1.1.0/docs/index.rst0000644000076500000240000000031500000000000017443 0ustar00konstastaff00000000000000SQLAlchemy-i18n =============== SQLAlchemy-i18n is an internationalization extension for SQLAlchemy. .. toctree:: :maxdepth: 2 installation quickstart basic queries config license ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1455286384.0 SQLAlchemy-i18n-1.1.0/docs/installation.rst0000644000076500000240000000237700000000000021047 0ustar00konstastaff00000000000000Installation ============ This part of the documentation covers the installation of SQLAlchemy-i18n. Supported platforms ------------------- SQLAlchemy-i18n has been tested against the following Python platforms. - cPython 2.6 - cPython 2.7 - cPython 3.3 - cPython 3.4 - cPython 3.5 Installing an official release ------------------------------ You can install the most recent official SQLAlchemy-i18n version using pip_:: pip install sqlalchemy-i18n .. _pip: http://www.pip-installer.org/ Installing the development version ---------------------------------- To install the latest version of SQLAlchemy-i18n, you need first obtain a copy of the source. You can do that by cloning the git_ repository:: git clone git://github.com/kvesteri/sqlalchemy-i18n.git Then you can install the source distribution using the ``setup.py`` script:: cd sqlalchemy-i18n python setup.py install .. _git: http://git-scm.org/ Checking the installation ------------------------- To check that SQLAlchemy-i18n has been properly installed, type ``python`` from your shell. Then at the Python prompt, try to import SQLAlchemy-i18n, and check the installed version: .. parsed-literal:: >>> import sqlalchemy_i18n >>> sqlalchemy_i18n.__version__ |release| ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1390987060.0 SQLAlchemy-i18n-1.1.0/docs/license.rst0000644000076500000240000000005100000000000017753 0ustar00konstastaff00000000000000License ======= .. include:: ../LICENSE ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1390482397.0 SQLAlchemy-i18n-1.1.0/docs/make.bat0000644000076500000240000001507700000000000017222 0ustar00konstastaff00000000000000@ECHO OFF REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=sphinx-build ) set BUILDDIR=_build set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . set I18NSPHINXOPTS=%SPHINXOPTS% . if NOT "%PAPER%" == "" ( set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% ) if "%1" == "" goto help if "%1" == "help" ( :help echo.Please use `make ^` where ^ is one of echo. html to make standalone HTML files echo. dirhtml to make HTML files named index.html in directories echo. singlehtml to make a single large HTML file echo. pickle to make pickle files echo. json to make JSON files echo. htmlhelp to make HTML files and a HTML help project echo. qthelp to make HTML files and a qthelp project echo. devhelp to make HTML files and a Devhelp project echo. epub to make an epub echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter echo. text to make text files echo. man to make manual pages echo. texinfo to make Texinfo files echo. gettext to make PO message catalogs echo. changes to make an overview over all changed/added/deprecated items echo. xml to make Docutils-native XML files echo. pseudoxml to make pseudoxml-XML files for display purposes echo. linkcheck to check all external links for integrity echo. doctest to run all doctests embedded in the documentation if enabled goto end ) if "%1" == "clean" ( for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i del /q /s %BUILDDIR%\* goto end ) %SPHINXBUILD% 2> nul if errorlevel 9009 ( echo. echo.The 'sphinx-build' command was not found. Make sure you have Sphinx echo.installed, then set the SPHINXBUILD environment variable to point echo.to the full path of the 'sphinx-build' executable. Alternatively you echo.may add the Sphinx directory to PATH. echo. echo.If you don't have Sphinx installed, grab it from echo.http://sphinx-doc.org/ exit /b 1 ) if "%1" == "html" ( %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/html. goto end ) if "%1" == "dirhtml" ( %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. goto end ) if "%1" == "singlehtml" ( %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. goto end ) if "%1" == "pickle" ( %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the pickle files. goto end ) if "%1" == "json" ( %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the JSON files. goto end ) if "%1" == "htmlhelp" ( %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run HTML Help Workshop with the ^ .hhp project file in %BUILDDIR%/htmlhelp. goto end ) if "%1" == "qthelp" ( %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run "qcollectiongenerator" with the ^ .qhcp project file in %BUILDDIR%/qthelp, like this: echo.^> qcollectiongenerator %BUILDDIR%\qthelp\SQLAlchemy-i18n.qhcp echo.To view the help file: echo.^> assistant -collectionFile %BUILDDIR%\qthelp\SQLAlchemy-i18n.ghc goto end ) if "%1" == "devhelp" ( %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp if errorlevel 1 exit /b 1 echo. echo.Build finished. goto end ) if "%1" == "epub" ( %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub if errorlevel 1 exit /b 1 echo. echo.Build finished. The epub file is in %BUILDDIR%/epub. goto end ) if "%1" == "latex" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex if errorlevel 1 exit /b 1 echo. echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. goto end ) if "%1" == "latexpdf" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex cd %BUILDDIR%/latex make all-pdf cd %BUILDDIR%/.. echo. echo.Build finished; the PDF files are in %BUILDDIR%/latex. goto end ) if "%1" == "latexpdfja" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex cd %BUILDDIR%/latex make all-pdf-ja cd %BUILDDIR%/.. echo. echo.Build finished; the PDF files are in %BUILDDIR%/latex. goto end ) if "%1" == "text" ( %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text if errorlevel 1 exit /b 1 echo. echo.Build finished. The text files are in %BUILDDIR%/text. goto end ) if "%1" == "man" ( %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man if errorlevel 1 exit /b 1 echo. echo.Build finished. The manual pages are in %BUILDDIR%/man. goto end ) if "%1" == "texinfo" ( %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo if errorlevel 1 exit /b 1 echo. echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. goto end ) if "%1" == "gettext" ( %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale if errorlevel 1 exit /b 1 echo. echo.Build finished. The message catalogs are in %BUILDDIR%/locale. goto end ) if "%1" == "changes" ( %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes if errorlevel 1 exit /b 1 echo. echo.The overview file is in %BUILDDIR%/changes. goto end ) if "%1" == "linkcheck" ( %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck if errorlevel 1 exit /b 1 echo. echo.Link check complete; look for any errors in the above output ^ or in %BUILDDIR%/linkcheck/output.txt. goto end ) if "%1" == "doctest" ( %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest if errorlevel 1 exit /b 1 echo. echo.Testing of doctests in the sources finished, look at the ^ results in %BUILDDIR%/doctest/output.txt. goto end ) if "%1" == "xml" ( %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml if errorlevel 1 exit /b 1 echo. echo.Build finished. The XML files are in %BUILDDIR%/xml. goto end ) if "%1" == "pseudoxml" ( %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml if errorlevel 1 exit /b 1 echo. echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. goto end ) :end ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1391681139.0 SQLAlchemy-i18n-1.1.0/docs/queries.rst0000644000076500000240000000166100000000000020016 0ustar00konstastaff00000000000000 Queries ======= Joinedload current translation ------------------------------ :: import sqlalchemy as sa articles = ( session.query(Article) .options(sa.orm.joinedload(Article.current_translation)) ) print articles[0].name Joinedload arbitrary translations --------------------------------- :: import sqlalchemy as sa articles = ( session.query(Article) .options(sa.orm.joinedload(Article.translations['fi'])) .options(sa.orm.joinedload(Article.translations['en'])) ) You can also use attribute accessors:: articles = ( session.query(Article) .options(sa.orm.joinedload(Article.translations.fi)) .options(sa.orm.joinedload(Article.translations.en)) ) Joinedload all translations --------------------------- :: articles = ( session.query(Article) .options(sa.orm.joinedload(Article.translations)) ) ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1421185501.0 SQLAlchemy-i18n-1.1.0/docs/quickstart.rst0000644000076500000240000000244500000000000020534 0ustar00konstastaff00000000000000QuickStart ---------- In order to make your models use SQLAlchemy-i18n you need two things: 1. Assign get_locale function sqlalchemy_utils.i18n module. The following example shows how to do this using flask.ext.babel:: import sqlalchemy_utils from flask.ext.babel import get_locale sqlalchemy_utils.i18n.get_locale = get_locale 2. Call make_translatable() before your models are defined. 3. Define translation model and make it inherit mixin provided by translation_base function :: import sqlalchemy as sa from sqlalchemy_i18n import ( make_translatable, translation_base, Translatable, ) make_translatable(options={'locales': ['fi', 'en']}) class Article(Translatable, Base): __tablename__ = 'article' __translatable__ = {'locales': ['fi', 'en']} locale = 'en' # this defines the default locale id = sa.Column(sa.Integer, primary_key=True, autoincrement=True) author = sa.Column(sa.Unicode(255)) class ArticleTranslation(translation_base(Article)): __tablename__ = 'article_translation' name = sa.Column(sa.Unicode(255)) content = sa.Column(sa.UnicodeText) article = Article() article.name = u'Some article' session.add(article) session.commit() ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1621769527.0 SQLAlchemy-i18n-1.1.0/setup.cfg0000644000076500000240000000004600000000000016474 0ustar00konstastaff00000000000000[egg_info] tag_build = tag_date = 0 ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1621769366.0 SQLAlchemy-i18n-1.1.0/setup.py0000644000076500000240000000356300000000000016374 0ustar00konstastaff00000000000000""" SQLAlchemy-i18n --------------- Internationalization extension for SQLAlchemy models. """ import os import re import sys from setuptools import setup PY3 = sys.version_info[0] == 3 HERE = os.path.dirname(os.path.abspath(__file__)) def get_version(): filename = os.path.join(HERE, 'sqlalchemy_i18n', '__init__.py') with open(filename) as f: contents = f.read() pattern = r"^__version__ = '(.*?)'$" return re.search(pattern, contents, re.MULTILINE).group(1) extras_require = { 'test': [ 'pytest>=2.2.3', 'Pygments>=1.2', 'Jinja2>=2.3', 'docutils>=0.10', 'flexmock>=0.9.7', 'psycopg2>=2.4.6', 'flake8>=2.4.0', 'isort>=3.9.6' ] } setup( name='SQLAlchemy-i18n', version=get_version(), url='https://github.com/kvesteri/sqlalchemy-i18n', license='BSD', author='Konsta Vesterinen', author_email='konsta@fastmonkeys.com', description='Internationalization extension for SQLAlchemy models.', long_description=__doc__, packages=['sqlalchemy_i18n'], zip_safe=False, include_package_data=True, platforms='any', install_requires=[ 'SQLAlchemy>=1.3', 'SQLAlchemy-Utils>=0.37.3', 'six>=1.4.1' ], python_requires='>=3.6', extras_require=extras_require, classifiers=[ 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules' ] ) ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1621769527.0 SQLAlchemy-i18n-1.1.0/sqlalchemy_i18n/0000755000076500000240000000000000000000000017654 5ustar00konstastaff00000000000000././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1621767666.0 SQLAlchemy-i18n-1.1.0/sqlalchemy_i18n/__init__.py0000644000076500000240000000440100000000000021764 0ustar00konstastaff00000000000000import sqlalchemy as sa from .builders import ImproperlyConfigured from .manager import translation_base, translation_manager, TranslationManager from .translatable import Translatable, UnknownLocaleError __all__ = ( translation_base, ImproperlyConfigured, Translatable, TranslationManager, translation_manager, UnknownLocaleError ) __version__ = '1.1.0' def make_translatable( mapper=sa.orm.mapper, session=sa.orm.session.Session, manager=translation_manager, options={} ): """ Assigns translation listeners for given mapper and session. :param mapper: SQLAlchemy declarative class or mapper to apply translation listeners into. :param session: SQLAlchemy session class. :param manager: SQLAlchemy-i18n TranslationManager instance :param options: TranslationManager options """ manager.options.update(options) sa.event.listen( mapper, 'instrument_class', manager.instrument_translation_classes ) sa.event.listen( mapper, 'after_configured', manager.configure_translatable_classes ) sa.event.listen( session, 'before_flush', manager.auto_create_translations ) def find_translations(obj, property_name, locale): class_ = obj.__class__ session = sa.orm.object_session(obj) translation_class = class_.__translatable__['class'] property_ = getattr(translation_class, property_name) subquery = ( session.query(translation_class.id) .filter( sa.and_( property_ == getattr(obj, property_name), translation_class.locale == obj.locale ) ) ) conditions = [ translation_class.id.in_(subquery), translation_class.locale == locale, property_.isnot(None) ] total_count = ( session.query(sa.func.cast(sa.func.count('1'), sa.Numeric)) .filter(sa.and_(*conditions)) ) query = ( session.query( property_.label('translation'), (sa.func.cast(sa.func.count('1'), sa.Numeric) / total_count) .label('confidence') ) .filter(sa.and_(*conditions)) .group_by(property_) ) return query ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1457258939.0 SQLAlchemy-i18n-1.1.0/sqlalchemy_i18n/builders.py0000644000076500000240000001744600000000000022053 0ustar00konstastaff00000000000000from copy import copy import sqlalchemy as sa from sqlalchemy.ext.hybrid import hybrid_property from sqlalchemy.orm.collections import attribute_mapped_collection from sqlalchemy_utils.functions import get_primary_keys from .comparators import TranslationComparator from .exc import ImproperlyConfigured from .expressions import current_locale from .utils import get_fallback_locale, option class HybridPropertyBuilder(object): def __init__(self, manager, translation_model): self.manager = manager self.translation_model = translation_model self.model = self.translation_model.__parent_class__ def getter_factory(self, property_name): def attribute_getter(obj): value = getattr(obj.current_translation, property_name) if value: return value locale = get_fallback_locale(obj) return getattr( obj.translations[locale], property_name ) return attribute_getter def setter_factory(self, property_name): """ Return a hybrid property setter for given property name. :param property_name: Name of the property to generate a setter for """ return ( lambda obj, value: setattr(obj.current_translation, property_name, value) ) def generate_hybrid(self, property_name): """ Generate a SQLAlchemy hybrid property for given translation model property. :param property_name: Name of the translation model property to generate hybrid property for. """ setattr( self.model, property_name, hybrid_property( fget=self.getter_factory(property_name), fset=self.setter_factory(property_name), expr=lambda cls: getattr( cls.__translatable__['class'], property_name ) ) ) def detect_collisions(self, property_name): """ Detect possible naming collisions for given property name. :raises sqlalchemy_i18n.exc.ImproperlyConfigured: if the model already has a property with given name """ mapper = sa.inspect(self.model) if mapper.has_property(property_name): raise ImproperlyConfigured( "Attribute name collision detected. Could not create " "hybrid property for translated attribute '%s'. " "An attribute with the same already exists in parent " "class '%s'." % ( property_name, self.model.__name__ ) ) def __call__(self): mapper = sa.orm.class_mapper(self.translation_model) for column in mapper.local_table.c: exclude = self.manager.option( self.model, 'exclude_hybrid_properties' ) if column.key in exclude or column.primary_key: continue self.detect_collisions(column.key) self.generate_hybrid(column.key) class RelationshipBuilder(object): def __init__(self, manager, translation_cls): self.manager = manager self.translation_cls = translation_cls self.parent_cls = self.translation_cls.__parent_class__ @property def primary_key_conditions(self): conditions = [] for key in get_primary_keys(self.parent_cls).keys(): conditions.append( getattr(self.parent_cls, key) == getattr(self.translation_cls, key) ) return conditions def assign_single_translations(self): mapper = sa.orm.class_mapper(self.parent_cls) for locale in option(self.parent_cls, 'locales'): key = '_translation_%s' % locale if mapper.has_property(key): continue conditions = self.primary_key_conditions conditions.append(self.translation_cls.locale == locale) mapper.add_property(key, sa.orm.relationship( self.translation_cls, primaryjoin=sa.and_(*conditions), foreign_keys=list( get_primary_keys(self.parent_cls).values() ), uselist=False, viewonly=True )) def assign_fallback_translation(self): """ Assign the current translation relationship for translatable parent class. """ mapper = sa.orm.class_mapper(self.parent_cls) if not mapper.has_property('_fallback_translation'): conditions = self.primary_key_conditions conditions.append( self.translation_cls.locale == get_fallback_locale(self.parent_cls) ) mapper.add_property('_fallback_translation', sa.orm.relationship( self.translation_cls, primaryjoin=sa.and_(*conditions), foreign_keys=list( get_primary_keys(self.parent_cls).values() ), viewonly=True, uselist=False )) def assign_current_translation(self): """ Assign the current translation relationship for translatable parent class. """ mapper = sa.orm.class_mapper(self.parent_cls) if not mapper.has_property('_current_translation'): conditions = self.primary_key_conditions conditions.append( self.translation_cls.locale == current_locale() ) mapper.add_property('_current_translation', sa.orm.relationship( self.translation_cls, primaryjoin=sa.and_(*conditions), foreign_keys=list( get_primary_keys(self.parent_cls).values() ), viewonly=True, uselist=False )) def assign_translations(self): """ Assigns translations relationship for translatable model. The assigned attribute is a relationship to all translation locales. """ mapper = sa.orm.class_mapper(self.parent_cls) if not mapper.has_property('_translations'): mapper.add_property('_translations', sa.orm.relationship( self.translation_cls, **self.get_translations_relationship_args() )) def get_translations_relationship_args(self): foreign_keys = [ getattr(self.translation_cls, column_key) for column_key in get_primary_keys(self.parent_cls).keys() ] relationship_args = copy( self.manager.option( self.parent_cls, 'translations_relationship_args' ) ) defaults = dict( primaryjoin=sa.and_(*self.primary_key_conditions), foreign_keys=foreign_keys, collection_class=attribute_mapped_collection('locale'), comparator_factory=TranslationComparator, cascade='all, delete-orphan', passive_deletes=True, ) for key, value in defaults.items(): relationship_args.setdefault(key, value) return relationship_args def assign_translation_parent(self): mapper = sa.orm.class_mapper(self.translation_cls) if not mapper.has_property('translation_parent'): mapper.add_property('translation_parent', sa.orm.relationship( self.parent_cls, uselist=False, viewonly=True )) def __call__(self): self.assign_single_translations() self.assign_current_translation() self.assign_fallback_translation() self.assign_translations() self.assign_translation_parent() ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1427274646.0 SQLAlchemy-i18n-1.1.0/sqlalchemy_i18n/comparators.py0000644000076500000240000000077500000000000022571 0ustar00konstastaff00000000000000from sqlalchemy.orm.relationships import RelationshipProperty from .exc import UnknownLocaleError class TranslationComparator(RelationshipProperty.Comparator): def __getitem__(self, key): return getattr(self._parentmapper.class_, '_translation_%s' % key) def __getattr__(self, locale): class_ = self._parentmapper.class_ try: return getattr(class_, '_translation_%s' % locale) except AttributeError: raise UnknownLocaleError(locale, class_) ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1427274646.0 SQLAlchemy-i18n-1.1.0/sqlalchemy_i18n/exc.py0000644000076500000240000000061500000000000021007 0ustar00konstastaff00000000000000from .utils import option class ImproperlyConfigured(Exception): pass class UnknownLocaleError(Exception): def __init__(self, locale, obj): Exception.__init__( self, 'Unknown locale %s given for instance of class %r. ' 'Locale is not one of %r' % ( locale, obj.__class__, list(option(obj, 'locales')) ) ) ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1427274646.0 SQLAlchemy-i18n-1.1.0/sqlalchemy_i18n/expressions.py0000644000076500000240000000074100000000000022612 0ustar00konstastaff00000000000000import sqlalchemy as sa from sqlalchemy.ext.compiler import compiles from sqlalchemy.sql.functions import GenericFunction class current_locale(GenericFunction): type = sa.types.String() @compiles(current_locale) def compile_current_locale(element, compiler, **kw): # Lazy import get_locale so that it can be overridden from sqlalchemy_utils.i18n import get_locale return '%s' % compiler.process( sa.bindparam('current_locale', str(get_locale())) ) ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1621767309.0 SQLAlchemy-i18n-1.1.0/sqlalchemy_i18n/manager.py0000644000076500000240000001277300000000000021652 0ustar00konstastaff00000000000000from copy import copy import sqlalchemy as sa from sqlalchemy.ext.declarative import declared_attr, has_inherited_table from sqlalchemy_utils.functions import get_declarative_base, get_primary_keys from .builders import HybridPropertyBuilder, RelationshipBuilder from .utils import all_translated_columns, is_string class BaseTranslationMixin(object): pass def translation_base( parent_cls, base_class_factory=None, foreign_key_args=None ): if base_class_factory is None: base_class_factory = get_declarative_base if foreign_key_args is None: foreign_key_args = {} foreign_key_args.setdefault('ondelete', 'CASCADE') class TranslationMixin( base_class_factory(parent_cls), BaseTranslationMixin ): __abstract__ = True __parent_class__ = parent_cls @declared_attr def __table_args__(cls): if has_inherited_table(cls): return tuple() else: names = list(get_primary_keys(parent_cls).keys()) return ( sa.schema.ForeignKeyConstraint( names, [ '%s.%s' % (parent_cls.__tablename__, name) for name in names ], **foreign_key_args ), ) for column in parent_cls.__table__.c: if column.primary_key: column_copy = column._copy() column_copy.autoincrement = False setattr( TranslationMixin, column.key, column_copy ) TranslationMixin.locale = sa.Column( sa.String(10), primary_key=True ) return TranslationMixin class TranslationManager(object): def __init__(self): self.class_map = {} self.pending_classes = [] self.options = { 'locales': [], 'auto_create_locales': True, 'fallback_locale': 'en', 'exclude_hybrid_properties': [], 'translations_relationship_args': {} } def instrument_translation_classes(self, mapper, cls): """ SQLAlchemy class instrumentation listener that adds all translation classes to pending classes list. These classes are later on processed by configure_translatable_classes listener. :param mapper: SQLAlchemy mapper :param cls: SQLAlchemy declarative class """ if issubclass(cls, BaseTranslationMixin): self.pending_classes.append(cls) def configure_translatable_classes(self): """ This SQLAlchemy after_configured listener configures all translation classes, builds hybrid properties for translation parent classes and finally builds relationships between translation and parent classes. """ for cls in self.pending_classes: self.class_map[cls.__parent_class__] = cls parent_cls = cls.__parent_class__ # Args need to be copied to avoid scenarios where many child # classes inherit the __translatable__ dict from parent class and # then have the same reference to same dict. parent_cls.__translatable__ = copy(parent_cls.__translatable__) parent_cls.__translatable__['manager'] = self parent_cls.__translatable__['class'] = cls HybridPropertyBuilder(self, cls)() RelationshipBuilder(self, cls)() self.pending_classes = [] def option(self, model, name): """ Returns the option value for given model. If the option is not found from given model falls back to default values of this manager object. If the option is not found from this manager object either this method throws a KeyError. :param model: SQLAlchemy declarative object :param name: name of the translation option """ try: return model.__translatable__[name] except (AttributeError, KeyError): return self.options[name] def set_not_nullables_to_empty_strings(self, locale, obj): for column in all_translated_columns(obj.__class__): if ( not column.nullable and is_string(column.type) and column.default is None and column.server_default is None and getattr(obj.translations[locale], column.name) is None ): setattr(obj.translations[locale], column.name, u'') def create_missing_locales(self, obj): """ Creates empty locale objects for given SQLAlchemy declarative object. :param model: SQLAlchemy declarative model object """ session = sa.orm.session.object_session(obj) for locale in self.option(obj, 'locales'): if obj.translations[locale] is None: class_ = obj.__translatable__['class'] obj.translations[locale] = class_( translation_parent=obj, locale=locale ) self.set_not_nullables_to_empty_strings(locale, obj) session.add(obj) def auto_create_translations(self, session, flush_context, instances): if self.options['auto_create_locales']: for obj in session.new: if hasattr(obj, '__translatable__'): self.create_missing_locales(obj) translation_manager = TranslationManager() ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1427274646.0 SQLAlchemy-i18n-1.1.0/sqlalchemy_i18n/translatable.py0000644000076500000240000001061300000000000022703 0ustar00konstastaff00000000000000import sqlalchemy as sa from sqlalchemy.ext.hybrid import hybrid_property from sqlalchemy.orm.util import has_identity from .exc import UnknownLocaleError from .utils import get_current_locale, get_fallback_locale class Translatable(object): __translatable__ = { 'fallback_locale': 'en' } @hybrid_property def locale(self): raise NotImplementedError( 'Your translatable model needs to define locale property.' ) # Current translation getters and setters @hybrid_property def current_translation(self): return self.translations[get_current_locale(self)] @current_translation.setter def current_translation(self, obj): self.translations[get_current_locale(self)] = obj @current_translation.expression def current_translation(cls): return cls._current_translation # Fallback translation getters and setters @hybrid_property def fallback_translation(self): return self.translations[get_fallback_locale(self)] @fallback_translation.setter def fallback_translation(self, obj): self.translations[get_fallback_locale(self)] = obj @fallback_translation.expression def fallback_translation(cls): return cls._fallback_translation # Translations getters and setters @hybrid_property def translations(self): if not hasattr(self, '_translations_mapping'): self._translations_mapping = TranslationsMapping(self) return self._translations_mapping @translations.setter def translations(self, translations_mapping): self._translations = translations_mapping @translations.expression def translations(self): return self._translations @sa.event.listens_for(sa.orm.mapper, 'expire') def receive_expire(target, attrs): if isinstance(target, Translatable): try: del target._translations_mapping except AttributeError: pass class TranslationsMapping(object): def __init__(self, obj): self.obj = obj self.manager = self.obj.__translatable__['manager'] def __contains__(self, locale): return locale in self.manager.option(self.obj, 'locales') def fetch(self, locale): session = sa.orm.object_session(self.obj) # If the object has no identity and its not in session or if the object # has _translations relationship loaded get the locale object from the # relationship. if '_translations' not in sa.inspect(self.obj).unloaded or ( not session or not has_identity(self.obj) ): return self.obj._translations.get(locale) return session.query(self.obj.__translatable__['class']).get( sa.inspect(self.obj).identity + (locale, ) ) def __getitem__(self, locale): if locale in self: locale_obj = self.fetch(locale) if locale_obj is not None: return locale_obj class_ = self.obj.__translatable__['class'] locale_obj = class_( translation_parent=self.obj, locale=locale ) self.obj._translations[locale] = locale_obj return locale_obj raise UnknownLocaleError(locale, self.obj) def __getattr__(self, locale): return self.__getitem__(locale) # Added for py2.6 compatibility def __length_hint__(self): return len(self) def __len__(self): return len(self.manager.option(self.obj, 'locales')) @property def all(self): return list(self.values()) def values(self): for locale in self.manager.option(self.obj, 'locales'): yield self[locale] def __setitem__(self, locale, translation_obj): if locale in self: translation_obj.translation_parent = self.obj translation_obj.locale = locale self.obj._translations[locale] = translation_obj def __repr__(self): return 'TranslationsMapping(%r)' % self.obj def items(self): return [ (locale, self[locale]) for locale in self.manager.option(self.obj, 'locales') ] def iteritems(self): for locale in self.manager.option(self.obj, 'locales'): yield locale, self[locale] def __iter__(self): for locale in self.manager.option(self.obj, 'locales'): yield locale, self[locale] ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1427274646.0 SQLAlchemy-i18n-1.1.0/sqlalchemy_i18n/utils.py0000644000076500000240000000165000000000000021370 0ustar00konstastaff00000000000000from inspect import isclass import sqlalchemy as sa def get_current_locale(obj): from sqlalchemy_utils import i18n locale = i18n.get_locale() if locale: return str(locale) return obj.locale def get_fallback_locale(obj): manager = obj.__translatable__['manager'] locale = manager.option(obj, 'fallback_locale') if callable(locale): locale = locale(obj) return locale def option(obj_or_class, option): class_ = obj_or_class if isclass(obj_or_class) else obj_or_class.__class__ manager = class_.__translatable__['manager'] return manager.option(class_, option) def all_translated_columns(model): for column in sa.inspect(model.__translatable__['class']).columns: if not column.primary_key: yield column def is_string(type_): return ( isinstance(type_, sa.String) or (isclass(type_) and issubclass(type_, sa.String)) ) ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1621769527.0 SQLAlchemy-i18n-1.1.0/tests/0000755000076500000240000000000000000000000016015 5ustar00konstastaff00000000000000././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1621766905.0 SQLAlchemy-i18n-1.1.0/tests/__init__.py0000644000076500000240000001426600000000000020137 0ustar00konstastaff00000000000000# -*- coding: utf-8 -*- import warnings import sqlalchemy as sa import sqlalchemy_utils from sqlalchemy import create_engine from sqlalchemy.engine import Engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.ext.hybrid import hybrid_property from sqlalchemy.orm import sessionmaker from sqlalchemy.orm.session import close_all_sessions from sqlalchemy_i18n import ( make_translatable, Translatable, translation_base, translation_manager ) from sqlalchemy_i18n.manager import BaseTranslationMixin @sa.event.listens_for(Engine, 'before_cursor_execute') def count_sql_calls(conn, cursor, statement, parameters, context, executemany): conn.query_count += 1 make_translatable(options={'locales': ['en', 'fi']}) warnings.simplefilter('error', sa.exc.SAWarning) sqlalchemy_utils.i18n.get_locale = lambda: 'en' class DeclarativeTestCase(object): engine_uri = 'postgresql://postgres@localhost/sqlalchemy_i18n_test' locales = ['en', 'fi'] create_tables = True configure_mappers = True def create_session(self): Session = sessionmaker(bind=self.connection) self.session = Session() def setup_method(self, method): self.engine = create_engine(self.engine_uri) # self.engine.echo = True self.connection = self.engine.connect() self.connection.query_count = 0 self.Model = declarative_base() self.create_models() if self.configure_mappers: sa.orm.configure_mappers() if self.create_tables: self.Model.metadata.create_all(self.connection) self.create_session() def teardown_method(self, method): translation_manager.pending_classes = [] close_all_sessions() self.Model.metadata.drop_all(self.connection) self.connection.close() self.engine.dispose() def create_models(self): class Article(self.Model, Translatable): __tablename__ = 'article' __translatable__ = { 'locales': self.locales, } @hybrid_property def locale(self): return 'en' id = sa.Column(sa.Integer, autoincrement=True, primary_key=True) description = sa.Column(sa.UnicodeText) def __repr__(self): return 'Article(id=%r)' % self.id class ArticleTranslation(translation_base(Article)): __tablename__ = 'article_translation' name = sa.Column(sa.Unicode(255)) content = sa.Column(sa.UnicodeText) self.Article = Article self.ArticleTranslation = ArticleTranslation def create_article(self): article = self.Article(name=u'Something', content=u'Something') self.session.add(article) self.session.commit() return article class ClassicBase(object): def __init__(self, **kwargs): cls_ = type(self) for k in kwargs: if not hasattr(cls_, k): raise TypeError( "%r is an invalid keyword argument for %s" % (k, cls_.__name__)) setattr(self, k, kwargs[k]) def __repr__(self): "Return an ASCII representation of the entity." from sqlalchemy.orm.exc import DetachedInstanceError mapper = sa.orm.object_mapper(self) pkeyf = mapper.primary_key try: pkeyv = mapper.primary_key_from_instance(self) except DetachedInstanceError: keys = "detached-instance" else: keys = ', '.join(u'%s=%r' % (f.name, v) for f, v in zip(pkeyf, pkeyv)) return '%s(%s)' % (self.__class__.__name__, keys) class ClassicTestCase(DeclarativeTestCase): def setup_method(self, method): self.metadata = sa.MetaData() self.engine = sa.create_engine(self.engine_uri) # self.engine.echo = True self.connection = self.engine.connect() self.connection.query_count = 0 self.create_tables() self.create_models() self.create_mappers() if self.configure_mappers: sa.orm.configure_mappers() if self.create_tables: self.metadata.create_all(self.connection) self.create_session() def teardown_method(self, method): translation_manager.pending_classes = [] close_all_sessions() self.metadata.drop_all(self.connection) self.connection.close() self.engine.dispose() def create_tables(self): self.article = sa.Table( 'article', self.metadata, sa.Column( 'id', sa.Integer, autoincrement=True, primary_key=True, nullable=False ), sa.Column('description', sa.UnicodeText) ) self.article_translation = sa.Table( 'article_translation', self.metadata, sa.Column( 'id', sa.Integer, sa.ForeignKey( 'article', ondelete="CASCADE" ), primary_key=True, nullable=False ), sa.Column( 'locale', sa.types.CHAR(2), primary_key=True, nullable=False ), sa.Column('name', sa.Unicode(255)), sa.Column('content', sa.UnicodeText) ) def create_models(self): class Article(ClassicBase, Translatable): __translatable__ = { 'locales': self.locales, } __translated_columns__ = [ sa.Column('name', sa.Unicode(255)), sa.Column('content', sa.UnicodeText), ] @hybrid_property def locale(self): return 'en' class ArticleTranslation(ClassicBase, BaseTranslationMixin): __parent_class__ = Article self.Article = Article self.ArticleTranslation = ArticleTranslation def create_mappers(self): sa.orm.mapper(self.Article, self.article) sa.orm.mapper(self.ArticleTranslation, self.article_translation) ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1427274478.0 SQLAlchemy-i18n-1.1.0/tests/test_common_base_class.py0000644000076500000240000000654600000000000023110 0ustar00konstastaff00000000000000# -*- coding: utf-8 -*- import sqlalchemy as sa from sqlalchemy_i18n import Translatable, translation_base from sqlalchemy_i18n.manager import BaseTranslationMixin from tests import ClassicBase, ClassicTestCase, DeclarativeTestCase class Suite(object): def test_translatable_dict_copied_to_each_child_class(self): assert ( self.Article.__translatable__['class'] == self.ArticleTranslation ) assert ( self.TextItem.__translatable__['class'] == self.TextItemTranslation ) class TestDeclarative(Suite, DeclarativeTestCase): def create_models(self): class Base(self.Model, Translatable): __abstract__ = True __translatable__ = { 'locales': ['en', 'fi'], } locale = 'en' class TextItem(Base): __tablename__ = 'text_item' id = sa.Column(sa.Integer, primary_key=True) class TextItemTranslation(translation_base(TextItem)): __tablename__ = 'text_item_translation' name = sa.Column(sa.Unicode(255)) class Article(Base): __tablename__ = 'article' id = sa.Column( sa.Integer, primary_key=True ) class ArticleTranslation(translation_base(Article)): __tablename__ = 'article_translation' name = sa.Column(sa.Unicode(255)) self.TextItem = TextItem self.TextItemTranslation = TextItemTranslation self.Article = Article self.ArticleTranslation = ArticleTranslation class TestClassic(Suite, ClassicTestCase): def create_tables(self): ClassicTestCase.create_tables(self) self.textitems = sa.Table( 'textitems', self.metadata, sa.Column('id', sa.Integer, autoincrement=True, primary_key=True, nullable=False)) self.textitems_translation = sa.Table( 'textitems_translation', self.metadata, sa.Column('id', sa.Integer, sa.ForeignKey('textitems'), primary_key=True, nullable=False), sa.Column('locale', sa.types.CHAR(2), primary_key=True, nullable=False), sa.Column('name', sa.UnicodeText)) def create_models(self): class CommonBase(ClassicBase, Translatable): __translatable__ = { 'locales': self.locales } locale = 'en' class TextItem(CommonBase): __translated_columns__ = [ sa.Column('name', sa.UnicodeText), ] class TextItemTranslation(BaseTranslationMixin): __parent_class__ = TextItem class Article(CommonBase, Translatable): __translated_columns__ = [ sa.Column('content', sa.UnicodeText), ] class ArticleTranslation(BaseTranslationMixin): __parent_class__ = Article self.TextItem = TextItem self.TextItemTranslation = TextItemTranslation self.Article = Article self.ArticleTranslation = ArticleTranslation def create_mappers(self): sa.orm.mapper(self.TextItem, self.textitems) sa.orm.mapper(self.TextItemTranslation, self.textitems_translation) ClassicTestCase.create_mappers(self) ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1427274478.0 SQLAlchemy-i18n-1.1.0/tests/test_comparator.py0000644000076500000240000000111200000000000021570 0ustar00konstastaff00000000000000# -*- coding: utf-8 -*- from pytest import raises from sqlalchemy_i18n import UnknownLocaleError from tests import ClassicTestCase, DeclarativeTestCase class Suite(object): def test_attribute_accessor_for_unknown_locale(self): with raises(UnknownLocaleError): assert self.Article.translations.some_unknown_locale def test_attribute_accessors(self): assert self.Article.translations.en assert self.Article.translations.fi class TestDeclarative(Suite, DeclarativeTestCase): pass class TestClassic(Suite, ClassicTestCase): pass ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1485797088.0 SQLAlchemy-i18n-1.1.0/tests/test_composite_primary_key.py0000644000076500000240000000562200000000000024050 0ustar00konstastaff00000000000000# -*- coding: utf-8 -*- import sqlalchemy as sa from sqlalchemy_i18n import Translatable, translation_base from sqlalchemy_i18n.manager import BaseTranslationMixin from tests import ClassicBase, ClassicTestCase, DeclarativeTestCase class Suite(object): def test_relationships(self): article = self.Article(id1=1, id2=1) article.name = u'Some article' self.session.add(article) self.session.commit() assert article.name == u'Some article' class TestDeclarative(Suite, DeclarativeTestCase): def create_models(self): class Article(self.Model, Translatable): __tablename__ = 'article' __translatable__ = { 'locales': ['fi', 'en'], 'auto_create_locales': True, } id1 = sa.Column(sa.Integer, primary_key=True) id2 = sa.Column(sa.Integer, primary_key=True) locale = 'en' class ArticleTranslation(translation_base(Article)): __tablename__ = 'article_translation' name = sa.Column(sa.Unicode(255)) self.Article = Article self.ArticleTranslation = ArticleTranslation class TestClassic(Suite, ClassicTestCase): def create_tables(self): self.article = sa.Table( 'article', self.metadata, sa.Column( 'id1', sa.Integer, primary_key=True, nullable=False ), sa.Column( 'id2', sa.Integer, primary_key=True, nullable=False ) ) self.article_translation = sa.Table( 'article_translation', self.metadata, sa.Column( 'id1', sa.Integer, primary_key=True, nullable=False ), sa.Column( 'id2', sa.Integer, primary_key=True, nullable=False ), sa.Column( 'locale', sa.types.CHAR(2), primary_key=True, nullable=False ), sa.Column('name', sa.Unicode(255)), sa.Column('content', sa.UnicodeText), sa.ForeignKeyConstraint( ['id1', 'id2'], ['article.id1', 'article.id2'] ) ) def create_models(self): class Article(ClassicBase, Translatable): __translatable__ = { 'locales': self.locales } __translated_columns__ = [ sa.Column('content', sa.UnicodeText), ] locale = 'en' class ArticleTranslation(ClassicBase, BaseTranslationMixin): __parent_class__ = Article self.Article = Article self.ArticleTranslation = ArticleTranslation ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1457259217.0 SQLAlchemy-i18n-1.1.0/tests/test_configuration.py0000644000076500000240000000245500000000000022303 0ustar00konstastaff00000000000000# -*- coding: utf-8 -*- import sqlalchemy as sa from sqlalchemy_i18n import Translatable, translation_base from tests import DeclarativeTestCase class TestTranslationBaseCustomization(DeclarativeTestCase): def create_models(self): class Article(self.Model, Translatable): __tablename__ = 'article' __translatable__ = { 'locales': ['fi', 'en'], 'auto_create_locales': True, 'translations_relationship_args': { 'collection_class': list, } } id = sa.Column(sa.Integer, primary_key=True) locale = 'en' TranslationBase = translation_base( Article, foreign_key_args={'onupdate': 'SET NULL'} ) class ArticleTranslation(TranslationBase): __tablename__ = 'article_translation' name = sa.Column(sa.Unicode(255)) self.Article = Article self.ArticleTranslation = ArticleTranslation def test_customize_foreign_key_args(self): assert ( self.ArticleTranslation.__table__.foreign_keys.pop().onupdate == 'SET NULL' ) def test_customize_relationships_args(self): assert self.Article._translations.property.collection_class == list ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1427274478.0 SQLAlchemy-i18n-1.1.0/tests/test_current_translation_property.py0000644000076500000240000000155500000000000025500 0ustar00konstastaff00000000000000# -*- coding: utf-8 -*- from tests import ClassicTestCase, DeclarativeTestCase class Suite(object): def test_as_object_property(self): article = self.Article() article.name = u'Some article' article.content = u'Some content' self.session.add(article) self.session.commit() assert article.current_translation.name == u'Some article' def test_as_class_property(self): assert self.Article.current_translation def test_setter(self): article = self.Article() article.current_translation = self.Article.__translatable__['class']( name=u'Something' ) self.session.add(article) self.session.commit() assert article.name == u'Something' class TestDeclarative(Suite, DeclarativeTestCase): pass class TestClassic(Suite, ClassicTestCase): pass ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1427274478.0 SQLAlchemy-i18n-1.1.0/tests/test_current_translation_property_with_locale.py0000644000076500000240000000372100000000000030047 0ustar00konstastaff00000000000000# -*- coding: utf-8 -*- import sqlalchemy as sa from sqlalchemy.ext.hybrid import hybrid_property from sqlalchemy_i18n import Translatable, translation_base from sqlalchemy_i18n.manager import BaseTranslationMixin from tests import ClassicBase, ClassicTestCase, DeclarativeTestCase class Suite(object): def test_converts_locale_object_to_unicode(self): article = self.Article() article.name = u'Some article' assert article.name == u'Some article' class Locale(object): def __init__(self, value): self.value = value def __str__(self): return self.value def __unicode__(self): return self.value class TestDeclarative(Suite, DeclarativeTestCase): def create_models(self): class Article(self.Model, Translatable): __tablename__ = 'article' @hybrid_property def locale(self): return Locale('en') id = sa.Column(sa.Integer, autoincrement=True, primary_key=True) description = sa.Column(sa.UnicodeText) class ArticleTranslation(translation_base(Article)): __tablename__ = 'article_translation' name = sa.Column(sa.Unicode(255)) content = sa.Column(sa.UnicodeText) self.Article = Article class TestClassic(Suite, ClassicTestCase): def create_models(self): class Article(ClassicBase, Translatable): __translatable__ = { 'locales': self.locales, 'default_locale': 'en', } __translated_columns__ = [ sa.Column('name', sa.Unicode(255)), sa.Column('content', sa.UnicodeText), ] @hybrid_property def locale(self): return Locale('en') class ArticleTranslation(ClassicBase, BaseTranslationMixin): __parent_class__ = Article self.Article = Article self.ArticleTranslation = ArticleTranslation ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1427274478.0 SQLAlchemy-i18n-1.1.0/tests/test_custom_base_class.py0000644000076500000240000000204600000000000023121 0ustar00konstastaff00000000000000# -*- coding: utf-8 -*- import sqlalchemy as sa from sqlalchemy_i18n import Translatable, translation_base from tests import DeclarativeTestCase class Suite(object): def test_translatable_dict_copied_to_each_child_class(self): assert issubclass(self.ArticleTranslation, self.TranslationBase) class TestDeclarative(Suite, DeclarativeTestCase): def create_models(self): class Base(self.Model): __abstract__ = True __versioned__ = {} class Article(self.Model, Translatable): __tablename__ = 'article' id = sa.Column( sa.Integer, primary_key=True ) class ArticleTranslation( translation_base(Article, base_class_factory=lambda cls: Base) ): __tablename__ = 'article_translation' name = sa.Column(sa.Unicode(255)) self.TranslationBase = Base self.Article = Article self.ArticleTranslation = ArticleTranslation # This is the common case in Classic mapping, no test needed ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1427274478.0 SQLAlchemy-i18n-1.1.0/tests/test_expressions.py0000644000076500000240000000027100000000000022010 0ustar00konstastaff00000000000000from sqlalchemy_i18n.expressions import current_locale class TestCurrentLocaleExpression(object): def test_render(self): assert str(current_locale()) == ':current_locale' ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1427274478.0 SQLAlchemy-i18n-1.1.0/tests/test_fallback_locale_as_callable.py0000644000076500000240000000545200000000000025014 0ustar00konstastaff00000000000000# -*- coding: utf-8 -*- import sqlalchemy as sa from sqlalchemy_i18n import Translatable, translation_base from sqlalchemy_i18n.manager import BaseTranslationMixin from tests import ClassicBase, ClassicTestCase, DeclarativeTestCase class Suite(object): def test_hybrid_properties_support_callable_fallback_locales(self): article = self.Article(locale=u'en') article.name = u'Some article' assert article.name == u'Some article' def test_locale_fallback(self): article = self.Article(locale=u'en') article.name class TestDeclarative(Suite, DeclarativeTestCase): def create_models(self): class Article(self.Model, Translatable): __tablename__ = 'article' __translatable__ = { 'locales': self.locales, 'auto_create_locales': True, 'fallback_locale': lambda self: self.locale or 'en' } id = sa.Column(sa.Integer, autoincrement=True, primary_key=True) locale = sa.Column(sa.Unicode(255), default=u'en') class ArticleTranslation(translation_base(Article)): __tablename__ = 'article_translation' name = sa.Column(sa.Unicode(255)) self.Article = Article class TestClassic(Suite, ClassicTestCase): def create_tables(self): self.article = sa.Table( 'article', self.metadata, sa.Column( 'id', sa.Integer, autoincrement=True, primary_key=True, nullable=False ), sa.Column('locale', sa.types.CHAR(2), default='en')) self.article_translation = sa.Table( 'article_translation', self.metadata, sa.Column( 'id', sa.Integer, sa.ForeignKey('article'), primary_key=True, nullable=False ), sa.Column( 'locale', sa.types.CHAR(2), primary_key=True, nullable=False ), sa.Column('name', sa.Unicode(255)), sa.Column('content', sa.UnicodeText) ) def create_models(self): class Article(ClassicBase, Translatable): __translatable__ = { 'locales': self.locales, 'auto_create_locales': True, 'fallback_locale': lambda self: self.locale or 'en' } __translated_columns__ = [ sa.Column('name', sa.Unicode(255)), sa.Column('content', sa.UnicodeText), ] class ArticleTranslation(ClassicBase, BaseTranslationMixin): __parent_class__ = Article self.Article = Article self.ArticleTranslation = ArticleTranslation ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1427274478.0 SQLAlchemy-i18n-1.1.0/tests/test_fallback_locale_without_class_default.py0000644000076500000240000000322000000000000027155 0ustar00konstastaff00000000000000# -*- coding: utf-8 -*- import sqlalchemy as sa from sqlalchemy_i18n import Translatable, translation_base from sqlalchemy_i18n.manager import BaseTranslationMixin from tests import ClassicBase from tests.test_fallback_locale_as_callable import TestClassic as TCBase from tests.test_fallback_locale_as_callable import TestDeclarative as TDBase class TestDeclarative(TDBase): def create_models(self): class Article(self.Model, Translatable): __tablename__ = 'article' __translatable__ = { 'locales': self.locales, 'auto_create_locales': True, } id = sa.Column(sa.Integer, autoincrement=True, primary_key=True) locale = sa.Column(sa.Unicode(255), default=u'en') def get_locale(self): return 'en' class ArticleTranslation(translation_base(Article)): __tablename__ = 'article_translation' name = sa.Column(sa.Unicode(255)) self.Article = Article class TestClassic(TCBase): def create_models(self): class Article(ClassicBase, Translatable): __translatable__ = { 'locales': self.locales, 'auto_create_locales': True, } __translated_columns__ = [ sa.Column('name', sa.Unicode(255)), sa.Column('content', sa.UnicodeText), ] def get_locale(self): return 'en' class ArticleTranslation(ClassicBase, BaseTranslationMixin): __parent_class__ = Article self.Article = Article self.ArticleTranslation = ArticleTranslation ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1427274478.0 SQLAlchemy-i18n-1.1.0/tests/test_fallback_translation.py0000644000076500000240000000161000000000000023601 0ustar00konstastaff00000000000000# -*- coding: utf-8 -*- from tests import ClassicTestCase, DeclarativeTestCase class Suite(object): def test_as_object_property_with_force_locale(self): article = self.Article() article.name = u'Some article' article.content = u'Some content' self.session.add(article) self.session.commit() assert article.fallback_translation == article.translations['en'] def test_as_class_property(self): assert self.Article.fallback_translation def test_setter(self): article = self.Article() article.fallback_translation = self.Article.__translatable__['class']( name=u'Something' ) self.session.add(article) self.session.commit() assert article.name == u'Something' class TestDeclarative(Suite, DeclarativeTestCase): pass class TestClassic(Suite, ClassicTestCase): pass ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1427274478.0 SQLAlchemy-i18n-1.1.0/tests/test_find_translations.py0000644000076500000240000000376200000000000023157 0ustar00konstastaff00000000000000# -*- coding: utf-8 -*- from decimal import Decimal from sqlalchemy_i18n import find_translations from tests import ClassicTestCase, DeclarativeTestCase class Suite(object): locales = ['en', 'fi', 'sv'] def test_with_full_confidence(self): article = self.Article() article.translations['en'].name = u'Some article' article.translations['en'].content = u'Some content' article.translations['fi'].name = u'Joku artikkeli' article.translations['fi'].content = u'Jotain tekstii' self.session.add(article) self.session.commit() article = self.Article() article.translations['en'].name = u'Some article' self.session.add(article) self.session.commit() assert dict(find_translations(article, 'name', 'fi')) == { u'Joku artikkeli': Decimal('1.0') } def test_with_varying_confidence(self): article = self.Article() article.translations['en'].name = u'Some article' article.translations['en'].content = u'Some content' article.translations['fi'].name = u'Joku artikkeli' article.translations['fi'].content = u'Jotain tekstii' self.session.add(article) article = self.Article() article.translations['en'].name = u'Some article' article.translations['en'].content = u'Some content' article.translations['fi'].name = u'Joku toinen artikkeli' article.translations['fi'].content = u'Jotain muuta tekstii' self.session.add(article) self.session.commit() article = self.Article() article.translations['en'].name = u'Some article' self.session.add(article) self.session.commit() assert dict(find_translations(article, 'name', 'fi').all()) == { u'Joku artikkeli': Decimal('0.5'), u'Joku toinen artikkeli': Decimal('0.5') } class TestDeclarative(Suite, DeclarativeTestCase): pass class TestClassic(Suite, ClassicTestCase): pass ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1427274478.0 SQLAlchemy-i18n-1.1.0/tests/test_hybrid_property_as_dynamic_source_locale.py0000644000076500000240000000677300000000000027756 0ustar00konstastaff00000000000000# -*- coding: utf-8 -*- import sqlalchemy as sa from sqlalchemy.ext.hybrid import hybrid_property from sqlalchemy_i18n import Translatable, translation_base from sqlalchemy_i18n.manager import BaseTranslationMixin from tests import ClassicBase, ClassicTestCase, DeclarativeTestCase class Suite(object): def test_joinedload_for_current_translation(self): count = self.connection.query_count article = ( self.session.query(self.Article) .options(sa.orm.joinedload(self.Article.current_translation)) ).first() article.translations['en'] assert self.connection.query_count == count + 1 class TestDeclarative(Suite, DeclarativeTestCase): def setup_method(self, method): DeclarativeTestCase.setup_method(self, method) self.ArticleTranslation = self.Article.__translatable__['class'] article = self.Article( description=u'Some description', name=u'Some name' ) self.session.add(article) self.session.commit() def create_models(self): class Article(self.Model, Translatable): __tablename__ = 'article' __translatable__ = { 'locales': self.locales } @hybrid_property def locale(self): return self._locale or 'en' id = sa.Column(sa.Integer, autoincrement=True, primary_key=True) description = sa.Column(sa.UnicodeText) _locale = sa.Column(sa.Unicode(10), default=u'en') class ArticleTranslation(translation_base(Article)): __tablename__ = 'article_translation' name = sa.Column(sa.Unicode(255)) content = sa.Column(sa.UnicodeText) self.Article = Article class TestClassic(Suite, ClassicTestCase): def setup_method(self, method): ClassicTestCase.setup_method(self, method) article = self.Article(description=u'Some description', name=u'Some name') self.session.add(article) self.session.commit() def create_tables(self): self.article = sa.Table( 'article', self.metadata, sa.Column('id', sa.Integer, autoincrement=True, primary_key=True, nullable=False), sa.Column('description', sa.UnicodeText), sa.Column('_locale', sa.types.CHAR(2), default=u'en')) self.article_translation = sa.Table( 'article_translation', self.metadata, sa.Column('id', sa.Integer, sa.ForeignKey('article'), primary_key=True, nullable=False), sa.Column('locale', sa.types.CHAR(2), primary_key=True, nullable=False), sa.Column('name', sa.Unicode(255)), sa.Column('content', sa.UnicodeText)) def create_models(self): class Article(ClassicBase, Translatable): __translatable__ = { 'locales': self.locales } __translated_columns__ = [ sa.Column('name', sa.Unicode(255)), sa.Column('content', sa.UnicodeText), ] @hybrid_property def locale(self): return self._locale or 'en' class ArticleTranslation(ClassicBase, BaseTranslationMixin): __parent_class__ = Article self.Article = Article self.ArticleTranslation = ArticleTranslation ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1427274478.0 SQLAlchemy-i18n-1.1.0/tests/test_hybrid_property_exclusion.py0000644000076500000240000000536000000000000024750 0ustar00konstastaff00000000000000# -*- coding: utf-8 -*- import sqlalchemy as sa from sqlalchemy_i18n import Translatable, translation_base from sqlalchemy_i18n.manager import BaseTranslationMixin from tests import ClassicBase, ClassicTestCase, DeclarativeTestCase class Suite(object): create_tables = False configure_mappers = False def test_does_not_generate_hybrid_properties(self): self.Article() class TestDeclarative(Suite, DeclarativeTestCase): def create_models(self): class Article(self.Model, Translatable): __tablename__ = 'article' __translatable__ = { 'locales': ['fi', 'en'], 'auto_create_locales': True, 'exclude_hybrid_properties': ['word_count'] } id = sa.Column(sa.Integer, autoincrement=True, primary_key=True) word_count = sa.Column(sa.Integer) locale = sa.Column(sa.Unicode(255), default=u'en') class ArticleTranslation(translation_base(Article)): __tablename__ = 'article_translation' name = sa.Column(sa.Unicode(255)) word_count = sa.Column(sa.Integer) self.Article = Article self.ArticleTranslation = ArticleTranslation class TestClassic(Suite, ClassicTestCase): def create_tables(self): self.article = sa.Table( 'article', self.metadata, sa.Column('id', sa.Integer, autoincrement=True, primary_key=True, nullable=False), sa.Column('locale', sa.types.CHAR(2), default='en'), sa.Column('word_count', sa.Integer)) self.article_translation = sa.Table( 'article_translation', self.metadata, sa.Column('id', sa.Integer, sa.ForeignKey('article'), primary_key=True, nullable=False), sa.Column('locale', sa.types.CHAR(2), primary_key=True, nullable=False), sa.Column('name', sa.Unicode(255)), sa.Column('content', sa.UnicodeText), sa.Column('word_count', sa.Integer)) def create_models(self): class Article(ClassicBase, Translatable): __translatable__ = { 'locales': self.locales, 'auto_create_locales': True, 'exclude_hybrid_properties': ['word_count'], } __translated_columns__ = [ sa.Column('name', sa.Unicode(255)), sa.Column('content', sa.UnicodeText), ] class ArticleTranslation(ClassicBase, BaseTranslationMixin): __parent_class__ = Article self.Article = Article self.ArticleTranslation = ArticleTranslation ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1621768974.0 SQLAlchemy-i18n-1.1.0/tests/test_join_expressions.py0000644000076500000240000000504500000000000023033 0ustar00konstastaff00000000000000# -*- coding: utf-8 -*- import sqlalchemy as sa from tests import ClassicTestCase, DeclarativeTestCase class Suite(object): def test_current_translation_as_expression(self): query = ( self.session.query(self.Article) .join(self.Article.current_translation) ) assert ( 'JOIN article_translation ON article.id = article_translation.id' ' AND article_translation.locale = ' in str(query) ) def test_order_by_translation(self): self.session.add(self.Article(name=u'cbc')) self.session.add(self.Article(name=u'abc')) self.session.add(self.Article(name=u'bbc')) self.session.commit() current_translation = sa.orm.aliased( self.Article.current_translation.prop.mapper ) articles = ( self.session.query(self.Article) .join(current_translation, self.Article.current_translation) .options(sa.orm.contains_eager( self.Article.current_translation, alias=current_translation) ) .order_by(current_translation.name) ).all() names = [a.name for a in articles] assert names == ['abc', 'bbc', 'cbc'] def test_fallback_locale_as_expression(self): query = ( self.session.query(self.Article) .join(self.Article.fallback_translation) ) assert ( 'JOIN article_translation ON article.id = article_translation.id' ' AND article_translation.locale = ' in str(query) ) def test_querying(self): query = ( self.session.query(self.Article) ) assert str(query) == ( 'SELECT article.id AS article_id, article.description AS' ' article_description \nFROM article' ) query = ( self.session.query(self.Article.__translatable__['class']) ) assert 'article_translation.id AS article_translation_id' in str(query) assert ( 'article_translation.locale AS article_translation_locale' in str(query) ) assert ( 'article_translation.name AS article_translation_name' in str(query) ) assert ( 'article_translation.content AS article_translation_content' in str(query) ) assert 'FROM article_translation' in str(query) class TestDeclarative(Suite, DeclarativeTestCase): pass class TestClassic(Suite, ClassicTestCase): pass ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1427274478.0 SQLAlchemy-i18n-1.1.0/tests/test_joined_loading.py0000644000076500000240000000507700000000000022404 0ustar00konstastaff00000000000000# -*- coding: utf-8 -*- import sqlalchemy as sa from tests import ClassicTestCase, DeclarativeTestCase class Suite(object): def test_joinedload_for_current_translation(self): article = ( self.session.query(self.Article) .options(sa.orm.joinedload(self.Article.current_translation)) ).first() query_count = self.connection.query_count article.name assert query_count == self.connection.query_count def test_contains_eager_for_current_translation(self): article = ( self.session.query(self.Article) .join(self.Article.current_translation) .options(sa.orm.contains_eager(self.Article.current_translation)) ).first() query_count = self.connection.query_count article.name assert query_count == self.connection.query_count def test_joinedload_for_single_translation(self): article = ( self.session.query(self.Article) .options(sa.orm.joinedload(self.Article.translations['en'])) ).first() query_count = self.connection.query_count article.name assert query_count == self.connection.query_count def test_joinedload_for_attr_accessor(self): article = ( self.session.query(self.Article) .options(sa.orm.joinedload(self.Article.translations.en)) ).first() query_count = self.connection.query_count article.name assert query_count == self.connection.query_count def test_joinedload_for_all_translations(self): article = ( self.session.query(self.Article) .options(sa.orm.joinedload(self.Article.translations)) ).first() query_count = self.connection.query_count article.name article.translations['fi'].name assert query_count == self.connection.query_count class TestDeclarative(Suite, DeclarativeTestCase): def setup_method(self, method): DeclarativeTestCase.setup_method(self, method) article = self.Article( description=u'Some description', name=u'Some name' ) self.session.add(article) self.session.commit() self.session.expunge_all() class TestClassic(Suite, ClassicTestCase): def setup_method(self, method): ClassicTestCase.setup_method(self, method) article = self.Article( description=u'Some description', name=u'Some name' ) self.session.add(article) self.session.commit() self.session.expunge_all() ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1427274478.0 SQLAlchemy-i18n-1.1.0/tests/test_joined_table_inheritance.py0000644000076500000240000001470700000000000024427 0ustar00konstastaff00000000000000# -*- coding: utf-8 -*- import sqlalchemy as sa from sqlalchemy_i18n import Translatable, translation_base from sqlalchemy_i18n.manager import BaseTranslationMixin from tests import ClassicBase, ClassicTestCase, DeclarativeTestCase class Suite(object): def test_auto_creates_relations(self): # textitem = self.TextItem() # assert textitem.translations # assert textitem._translations article = self.Article() assert article.translations def test_auto_creates_current_translation(self): # textitem = self.TextItem() # assert textitem.current_translation article = self.Article() assert article.current_translation def test_translatable_attributes(self): textitem = self.TextItem() class_ = textitem.__translatable__['class'] assert class_.__name__ == 'TextItemTranslation' def test_inherits_child_properties(self): assert self.Article.caption def test_translated_columns(self): article = self.Article() columns = sa.inspect(article.__translatable__['class']).columns assert 'caption' in columns assert 'name' in columns assert 'content' in columns assert 'description' not in columns def test_property_delegators(self): article = self.Article() article.translations['en'] assert not article.name article.current_translation.name = u'something' assert article.name == u'something' article.name = u'some other thing' assert article.current_translation.name == u'some other thing' assert article.translations['en'].name == u'some other thing' article.caption = u'some caption' assert article.current_translation.caption == u'some caption' class TestDeclarative(Suite, DeclarativeTestCase): def create_models(self): class TextItem(self.Model, Translatable): __tablename__ = 'text_item' __translatable__ = { 'locales': ['en', 'fi'], } locale = 'en' id = sa.Column(sa.Integer, autoincrement=True, primary_key=True) description = sa.Column(sa.UnicodeText) discriminator = sa.Column( sa.Unicode(100) ) __mapper_args__ = { 'polymorphic_on': discriminator, } class TextItemTranslation(translation_base(TextItem)): __tablename__ = 'text_item_translation' name = sa.Column(sa.Unicode(255)) content = sa.Column(sa.UnicodeText) caption = sa.Column(sa.UnicodeText) class Article(TextItem): __tablename__ = 'article' id = sa.Column( sa.Integer, sa.ForeignKey(TextItem.id), primary_key=True ) __mapper_args__ = {'polymorphic_identity': u'article'} category = sa.Unicode(255) self.TextItem = TextItem self.Article = Article def test_table_name(self): article = self.Article() table = article.__translatable__['class'].__table__ assert table.name == 'text_item_translation' def test_inherits_parent_table(self): table = self.Article.__translatable__['class'].__table__ assert table == self.TextItem.__translatable__['class'].__table__ class TestClassic(Suite, ClassicTestCase): def create_tables(self): self.text_item = sa.Table( 'text_item', self.metadata, sa.Column('id', sa.Integer, autoincrement=True, primary_key=True, nullable=False), sa.Column('description', sa.UnicodeText), sa.Column('discriminator', sa.Unicode(255))) self.text_item_translation = sa.Table( 'text_item_translation', self.metadata, sa.Column('id', sa.Integer, sa.ForeignKey('text_item.id', ondelete="CASCADE"), primary_key=True, nullable=False), sa.Column('locale', sa.types.CHAR(2), primary_key=True, nullable=False), sa.Column('name', sa.Unicode(255), nullable=False), sa.Column('content', sa.UnicodeText, nullable=False), sa.Column('caption', sa.UnicodeText, nullable=False)) self.article = sa.Table( 'article', self.metadata, sa.Column('id', sa.Integer, sa.ForeignKey('text_item.id', ondelete="CASCADE"), autoincrement=True, primary_key=True, nullable=False), sa.Column('category', sa.Unicode(255))) def create_models(self): class TextItem(ClassicBase, Translatable): __translatable__ = { 'locales': self.locales, } __translated_columns__ = [ sa.Column('name', sa.Unicode(255)), sa.Column('content', sa.UnicodeText), sa.Column('content2', sa.UnicodeText), ] locale = 'en' class TextItemTranslation(ClassicBase, BaseTranslationMixin): __parent_class__ = TextItem class Article(TextItem): pass self.TextItem = TextItem self.TextItemTranslation = TextItemTranslation self.Article = Article def create_mappers(self): sa.orm.mapper(self.TextItem, self.text_item, polymorphic_on=self.text_item.c.discriminator) sa.orm.mapper(self.TextItemTranslation, self.text_item_translation) sa.orm.mapper(self.Article, self.article, inherits=self.TextItem, polymorphic_identity=u'article') def test_table_name(self): article_l10n_mapper = sa.orm.class_mapper( self.Article.__translatable__['class'] ) table = article_l10n_mapper.local_table assert table.name == 'text_item_translation' def test_inherits_parent_table(self): article_l10n_mapper = sa.orm.class_mapper( self.Article.__translatable__['class'] ) textitem_l10n_mapper = sa.orm.class_mapper( self.TextItem.__translatable__['class'] ) article_l10n_table = article_l10n_mapper.local_table textitem_l10n_table = textitem_l10n_mapper.local_table assert article_l10n_table == textitem_l10n_table ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1427274478.0 SQLAlchemy-i18n-1.1.0/tests/test_property_collision.py0000644000076500000240000000220700000000000023366 0ustar00konstastaff00000000000000# -*- coding: utf-8 -*- import sqlalchemy as sa from pytest import raises from sqlalchemy_i18n import ( ImproperlyConfigured, Translatable, translation_base ) from tests import DeclarativeTestCase class Suite(object): configure_mappers = False create_tables = False def test_raises_exception(self): with raises(ImproperlyConfigured): class ArticleTranslation(translation_base(self.Article)): __tablename__ = 'article_translation' name = sa.Column(sa.Unicode(255)) self.Article() class TestDeclarative(Suite, DeclarativeTestCase): def create_models(self): class Article(self.Model, Translatable): __tablename__ = 'article' __translatable__ = { 'locales': ['fi', 'en'], 'auto_create_locales': True, } id = sa.Column(sa.Integer, autoincrement=True, primary_key=True) name = sa.Column(sa.Unicode(255)) locale = sa.Column(sa.Unicode(255), default=u'en') def get_locale(self): return 'en' self.Article = Article ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1427274478.0 SQLAlchemy-i18n-1.1.0/tests/test_relationships.py0000644000076500000240000001033600000000000022315 0ustar00konstastaff00000000000000# -*- coding: utf-8 -*- import sqlalchemy as sa from sqlalchemy_i18n import Translatable, translation_base from sqlalchemy_i18n.manager import BaseTranslationMixin from tests import ClassicBase, ClassicTestCase, DeclarativeTestCase class Suite(object): def test_nullify_relation(self): self.CategoryTranslation = self.Category.__translatable__['class'] article = self.Article() article.content = u'Some content' article.categories.append(self.Category()) self.session.commit() article.categories = [] self.session.commit() assert not self.session.query(self.CategoryTranslation).count() class TestDeclarative(Suite, DeclarativeTestCase): def create_models(self): class Article(self.Model): __tablename__ = 'article' id = sa.Column(sa.Integer, autoincrement=True, primary_key=True) content = sa.Column(sa.UnicodeText) class Category(self.Model, Translatable): __tablename__ = 'category' id = sa.Column(sa.Integer, autoincrement=True, primary_key=True) article_id = sa.Column(sa.Integer, sa.ForeignKey(Article.id)) article = sa.orm.relationship( Article, backref=sa.orm.backref( 'categories', passive_deletes=True, cascade='all, delete-orphan' ) ) class CategoryTranslation(translation_base(Category)): __tablename__ = 'article_translation' name = sa.Column(sa.Unicode(255)) self.Article = Article self.Category = Category class TestClassic(Suite, ClassicTestCase): def create_tables(self): self.article = sa.Table( 'article', self.metadata, sa.Column('id', sa.Integer, autoincrement=True, primary_key=True, nullable=False), sa.Column('content', sa.UnicodeText)) self.category = sa.Table( 'category', self.metadata, sa.Column('id', sa.Integer, autoincrement=True, primary_key=True, nullable=False), sa.Column('article_id', sa.Integer, sa.ForeignKey('article.id'))) self.category_translation = sa.Table( 'category_translation', self.metadata, sa.Column('id', sa.Integer, sa.ForeignKey('category'), primary_key=True, nullable=False), sa.Column('locale', sa.types.CHAR(2), primary_key=True, nullable=False), sa.Column('name', sa.Unicode(255))) def create_models(self): class Article(ClassicBase): __translatable__ = { 'locales': self.locales, 'default_locale': 'en', } __translated_columns__ = [ sa.Column('name', sa.Unicode(255)), sa.Column('content', sa.UnicodeText), ] class Category(ClassicBase, Translatable): __translated_columns__ = [ sa.Column('name', sa.Unicode(255)), ] class CategoryTranslation(ClassicBase, BaseTranslationMixin): __parent_class__ = Category self.Article = Article self.Category = Category self.CategoryTranslation = CategoryTranslation def create_mappers(self): sa.orm.mapper(self.Article, self.article) sa.orm.mapper(self.Category, self.category, properties={ 'article': sa.orm.relationship( self.Article, backref=sa.orm.backref('categories', passive_deletes=True, cascade='all, delete-orphan')) }) sa.orm.mapper(self.CategoryTranslation, self.category_translation) def test_nullify_relation(self): article = self.Article() article.content = u'Some content' article.categories.append(self.Category()) self.session.commit() article.categories = [] self.session.commit() assert not self.session.query(self.CategoryTranslation).count() ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1485797578.0 SQLAlchemy-i18n-1.1.0/tests/test_translatable.py0000644000076500000240000000505600000000000022110 0ustar00konstastaff00000000000000# -*- coding: utf-8 -*- from tests import ClassicTestCase, DeclarativeTestCase class Suite(object): def test_auto_creates_relations(self): article = self.Article() assert article.translations def test_translatable_attributes(self): article = self.Article() assert article.__translatable__['class'] assert article.__translatable__['class'].__name__ == ( 'ArticleTranslation' ) def test_relationship_consistency(self): article = self.Article() article.name = u'Some article' assert article.current_translation == article.translations['en'] def test_property_delegators(self): article = self.Article() article.translations['en'] assert not article.name article.current_translation.name = u'something' assert article.name == u'something' article.name = u'some other thing' assert article.current_translation.name == u'some other thing' assert article.translations['en'].name == u'some other thing' def test_commit_session(self): article = self.Article() article.name = u'Some article' article.content = u'Some content' self.session.add(article) self.session.commit() article = self.session.query(self.Article).get(1) assert article.name == u'Some article' assert article.content == u'Some content' def test_delete(self): article = self.Article() article.description = u'Some description' self.session.add(article) self.session.commit() article.name = u'Some article' article.content = u'Some content' self.session.delete(article) self.session.commit() class TestDeclarative(Suite, DeclarativeTestCase): def test_translated_columns(self): article = self.Article() columns = article.__translatable__['class'].__table__.c assert 'name' in columns assert 'content' in columns assert 'description' not in columns def test_appends_locale_column_to_translation_table(self): table = self.Model.metadata.tables['article_translation'] assert 'locale' in table.c class TestClassic(Suite, ClassicTestCase): def test_translated_columns(self): columns = self.article_translation.c assert 'name' in columns assert 'content' in columns assert 'description' not in columns def test_appends_locale_column_to_translation_table(self): table = self.article_translation assert 'locale' in table.c ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1427274478.0 SQLAlchemy-i18n-1.1.0/tests/test_translation_auto_creation.py0000644000076500000240000000233600000000000024704 0ustar00konstastaff00000000000000# -*- coding: utf-8 -*- from sqlalchemy_i18n import translation_manager from tests import ClassicTestCase, DeclarativeTestCase class Suite(object): def test_auto_creates_translation_objects(self): article = self.Article(name=u'Some article') self.session.add(article) self.session.commit() assert 'en' in article.translations assert article.translations['en'] assert 'fi' in article.translations assert article.translations['fi'] class TestDeclarative(Suite, DeclarativeTestCase): def setup_method(self, method): DeclarativeTestCase.setup_method(self, method) translation_manager.options['auto_created_locales'] = [u'fi', u'en'] def teardown_method(self, method): DeclarativeTestCase.teardown_method(self, method) translation_manager.options['auto_created_locales'] = [] class TestClassic(Suite, ClassicTestCase): def setup_method(self, method): ClassicTestCase.setup_method(self, method) translation_manager.options['auto_created_locales'] = [u'fi', u'en'] def teardown_method(self, method): ClassicTestCase.teardown_method(self, method) translation_manager.options['auto_created_locales'] = [] ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1427274478.0 SQLAlchemy-i18n-1.1.0/tests/test_translation_auto_creation_with_non_nullables.py0000644000076500000240000001176000000000000030653 0ustar00konstastaff00000000000000# -*- coding: utf-8 -*- import sqlalchemy as sa from sqlalchemy.ext.hybrid import hybrid_property from sqlalchemy_i18n import Translatable, translation_base, translation_manager from sqlalchemy_i18n.manager import BaseTranslationMixin from tests import ClassicBase, ClassicTestCase, DeclarativeTestCase class Suite(object): def test_auto_sets_nullables_as_empty_strings(self): article = self.ExtendedArticle( name=u'Some article', content2=u'Some content' ) self.session.add(article) self.session.commit() assert article.translations['en'].name == u'Some article' assert article.translations['fi'].name == u'' class TestDeclarative(Suite, DeclarativeTestCase): def setup_method(self, method): DeclarativeTestCase.setup_method(self, method) translation_manager.options['auto_created_locales'] = [u'fi', u'en'] def teardown_method(self, method): DeclarativeTestCase.teardown_method(self, method) translation_manager.options['auto_created_locales'] = [] def create_models(self): class Article(self.Model, Translatable): __tablename__ = 'article' __translatable__ = { 'auto_created_locales': True, 'locales': ['en', 'fi'] } @hybrid_property def locale(self): return 'en' id = sa.Column(sa.Integer, autoincrement=True, primary_key=True) description = sa.Column(sa.UnicodeText) discriminator = sa.Column(sa.Unicode(255)) __mapper_args__ = { 'polymorphic_on': discriminator, } class ExtendedArticle(Article): __tablename__ = 'extended_article' __mapper_args__ = {'polymorphic_identity': u'extended'} id = sa.Column( sa.Integer, sa.ForeignKey(Article.id), primary_key=True ) class ArticleTranslation(translation_base(Article)): __tablename__ = 'article_translation' name = sa.Column(sa.Unicode(255), nullable=False) content = sa.Column(sa.UnicodeText) content2 = sa.Column(sa.UnicodeText) self.Article = Article self.ExtendedArticle = ExtendedArticle class TestClassic(Suite, ClassicTestCase): def setup_method(self, method): ClassicTestCase.setup_method(self, method) translation_manager.options['auto_created_locales'] = [u'fi', u'en'] def teardown_method(self, method): ClassicTestCase.teardown_method(self, method) translation_manager.options['auto_created_locales'] = [] def create_tables(self): self.article = sa.Table( 'article', self.metadata, sa.Column('id', sa.Integer, autoincrement=True, primary_key=True, nullable=False), sa.Column('description', sa.UnicodeText), sa.Column('discriminator', sa.Unicode(255))) self.extended_article = sa.Table( 'extended_article', self.metadata, sa.Column('id', sa.Integer, sa.ForeignKey('article.id'), primary_key=True)) self.article_translation = sa.Table( 'article_translation', self.metadata, sa.Column('id', sa.Integer, sa.ForeignKey('article.id', ondelete="CASCADE"), primary_key=True, nullable=False), sa.Column('locale', sa.types.CHAR(2), primary_key=True, nullable=False), sa.Column('name', sa.Unicode(255), nullable=False), sa.Column('content', sa.UnicodeText, nullable=False), sa.Column('content2', sa.UnicodeText, nullable=False)) def create_models(self): class Article(ClassicBase, Translatable): __translatable__ = { 'locales': self.locales, 'auto_created_locales': True, } __translated_columns__ = [ sa.Column('name', sa.Unicode(255)), sa.Column('content', sa.UnicodeText), sa.Column('content2', sa.UnicodeText), ] @hybrid_property def locale(self): return 'en' class ExtendedArticle(Article): pass class ArticleTranslation(ClassicBase, BaseTranslationMixin): __parent_class__ = Article self.Article = Article self.ExtendedArticle = ExtendedArticle self.ArticleTranslation = ArticleTranslation def create_mappers(self): sa.orm.mapper(self.Article, self.article, polymorphic_on=self.article.c.discriminator) sa.orm.mapper(self.ExtendedArticle, self.extended_article, inherits=self.Article, polymorphic_identity=u'extended') sa.orm.mapper(self.ArticleTranslation, self.article_translation) ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1427274478.0 SQLAlchemy-i18n-1.1.0/tests/test_translation_mapping.py0000644000076500000240000000442300000000000023502 0ustar00konstastaff00000000000000# -*- coding: utf-8 -*- from pytest import raises from sqlalchemy_i18n import UnknownLocaleError from tests import ClassicTestCase, DeclarativeTestCase class Suite(object): def test_proxy_contains(self): article = self.Article() article.translations['en'] assert 'en' in article.translations def test_translation_mapping_attribute_getter(self): article = self.Article() article.translations.en.name = 'Something' assert article.name == 'Something' def test_attribute_accessor_for_unknown_locale(self): with raises(UnknownLocaleError): self.Article.translations.some_unknown_locale def test_proxy_not_contains(self): article = self.Article() assert 'unknown_locale' not in article.translations def test_items(self): article = self.create_article() assert isinstance(article.translations.items(), list) def test_iteritems(self): article = self.create_article() assert ( article.translations.items() == list(article.translations.iteritems()) ) def test_set_item(self): article = self.create_article() self.session.expunge_all() article = self.session.query(self.Article).first() locale_obj = self.Article.__translatable__['class']( name=u'Some other thing' ) article.translations['en'] = locale_obj self.session.commit() self.session.expunge_all() article = self.session.query(self.Article).first() assert article.translations['en'].name == u'Some other thing' def test_repr(self): article = self.create_article() assert ( repr(article.translations) == 'TranslationsMapping(Article(id=%d))' % article.id ) def test_iter(self): article = self.create_article() assert len(list(article.translations)) == 2 def test_values(self): article = self.create_article() values = list(article.translations.values()) for value in values: assert isinstance(value, article.__translatable__['class']) assert len(values) == 2 class TestDeclarative(Suite, DeclarativeTestCase): pass class TestClassic(Suite, ClassicTestCase): pass