master 7160dd935859 cached
84 files
322.2 KB
77.9k tokens
805 symbols
1 requests
Download .txt
Showing preview only (345K chars total). Download the full file or copy to clipboard to get everything.
Repository: paulocheque/django-dynamic-fixture
Branch: master
Commit: 7160dd935859
Files: 84
Total size: 322.2 KB

Directory structure:
gitextract_1_zfvdao/

├── .coveragerc
├── .flake8
├── .github/
│   ├── FUNDING.yml
│   └── workflows/
│       └── release.yml
├── .gitignore
├── .pylintrc
├── .python-version
├── .readthedocs.yaml
├── LICENSE.txt
├── MANIFEST.in
├── Makefile
├── README.md
├── ddf/
│   └── __init__.py
├── django_dynamic_fixture/
│   ├── __init__.py
│   ├── ddf.py
│   ├── decorators.py
│   ├── django_helper.py
│   ├── fdf.py
│   ├── fields.py
│   ├── fixture_algorithms/
│   │   ├── __init__.py
│   │   ├── default_fixture.py
│   │   ├── random_fixture.py
│   │   ├── sequential_fixture.py
│   │   ├── tests/
│   │   │   ├── __init__.py
│   │   │   ├── abstract_test_generic_fixture.py
│   │   │   ├── test_default_fixture.py
│   │   │   ├── test_default_fixture_postgres.py
│   │   │   ├── test_random_fixture.py
│   │   │   ├── test_sequential_fixture.py
│   │   │   └── test_unique_random_fixture.py
│   │   └── unique_random_fixture.py
│   ├── global_settings.py
│   ├── models.py
│   ├── models_sample_app.py
│   ├── models_test.py
│   ├── models_third_party.py
│   ├── script_ddf_checkings.py
│   └── tests/
│       ├── __init__.py
│       ├── conftest.py
│       ├── test_ddf.py
│       ├── test_ddf_checkings.py
│       ├── test_ddf_copier.py
│       ├── test_ddf_custom_fields.py
│       ├── test_ddf_custom_models.py
│       ├── test_ddf_geo.py
│       ├── test_ddf_signals.py
│       ├── test_ddf_teaching_and_lessons.py
│       ├── test_decorators.py
│       ├── test_django_helper.py
│       ├── test_fdf.py
│       ├── test_global_settings.py
│       ├── test_mask.py
│       ├── test_module_ddf_shortcut.py
│       ├── test_sample_app.py
│       └── test_wrappers.py
├── docs/
│   ├── Makefile
│   └── source/
│       ├── _static/
│       │   └── coverage.html
│       ├── about.rst
│       ├── change_log.rst
│       ├── conf.py
│       ├── data.rst
│       ├── data_fixtures.rst
│       ├── ddf.rst
│       ├── fdf.rst
│       ├── index.rst
│       ├── more.rst
│       ├── overview.rst
│       ├── patterns.rst
│       └── settings.rst
├── manage.py
├── pytest.ini
├── queries/
│   ├── __init__.py
│   ├── count_queries_on_save.py
│   └── management/
│       ├── __init__.py
│       └── commands/
│           ├── __init__.py
│           └── count_queries_on_save.py
├── requirements-dev.txt
├── requirements.txt
├── settings_ddf.py
├── settings_mysql.py
├── settings_postgres.py
├── settings_sqlite.py
├── setup.py
└── tox.ini

================================================
FILE CONTENTS
================================================

================================================
FILE: .coveragerc
================================================
[run]
source = django_dynamic_fixture
omit = */migrations/*

[report]
exclude_lines =
    pragma: no cover
    def __repr__
    if self.debug:
    if settings.DEBUG
    raise AssertionError
    raise NotImplementedError
    if 0:
    if __name__ == .__main__.:
    def __iter__
    def __len__
    __metaclass__
    def __init__
    class MetaChoice


================================================
FILE: .flake8
================================================
[flake8]
max-line-length=200
exclude=.git,*migrations/*,tmp/*,scripts/*,docs/*,*/tests/*,proto,env/*
max-complexity=15


================================================
FILE: .github/FUNDING.yml
================================================
# These are supported funding model platforms

github: [paulocheque]
#patreon: # Replace with a single Patreon username
#open_collective: # Replace with a single Open Collective username
#ko_fi: # Replace with a single Ko-fi username
#tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
#community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
#liberapay: # Replace with a single Liberapay username
#issuehunt: # Replace with a single IssueHunt username
#lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
#polar: # Replace with a single Polar username
#buy_me_a_coffee: # Replace with a single Buy Me a Coffee username
#custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']


================================================
FILE: .github/workflows/release.yml
================================================
name: Building and Testing

on:
  push:
    branches:
      - master
  pull_request:
    branches:
      - master

jobs:
  build:
    runs-on: 'ubuntu-latest'
    strategy:
      matrix:
        python_version:
          - '3.8'
          - '3.9'
          - '3.10'
          - '3.11'
        django_version:
          - '4.0'
          - '4.1'
          - '4.2'

    services:
      postgres:
        # https://github.com/postgis/docker-postgis/blob/master/15-3.4/alpine/Dockerfile
        image: postgis/postgis:15-3.4-alpine
        env:
          POSTGRES_DB: ddf
          POSTGRES_USER: ddf_user
          POSTGRES_PASSWORD: ddf_pass
        ports:
          # Random free port
          - 5432/tcp
        # Set health checks to wait until postgres has started
        options: >-
          --health-cmd pg_isready
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5

    steps:
      - name: 'Install OS dependencies (Ubuntu)'
        if: runner.os == 'Linux'
        run: |
            # https://docs.djangoproject.com/en/4.2/ref/contrib/gis/install/geolibs/
            # GDAL_LIBRARY_PATH: /usr/lib/libgdal.so.*
            # GEOS_LIBRARY_PATH: /usr/lib/libgeos_c.so.*
            # ln -s /usr/lib/libgdal.so.32 /usr/lib/libgdal.so \
            # ln -s /usr/lib/libgeos_c.so.1 /usr/lib/libgeos_c.so
            # ln -s /usr/lib/libproj.so.25 /usr/lib/libproj.so \
            sudo apt-get update \
            && sudo apt-get install -y binutils libproj-dev gdal-bin

      - name: 'Set up Python ${{ matrix.python_version }}'
        uses: actions/setup-python@v4
        with:
          python-version: ${{ matrix.python_version }}

      - name: 'Checkout DDF code'
        uses: actions/checkout@v3

      - name: 'Install Python dependencies'
        run: |
          pip install -r requirements.txt
          pip install -r requirements-dev.txt
          pip install pytest-django
          pip install django~=${{ matrix.django_version }}
          pip install jsonfield==3.1.0
          pip install django-polymorphic==3.1.0

      - name: 'Testing with SQLite'
        run: pytest --create-db --reuse-db --no-migrations --ds=settings_sqlite --maxfail=2

      - name: 'Coverage with SQLite'
        run: pytest --create-db --reuse-db --no-migrations -v --cov=django_dynamic_fixture

      - name: 'Testing with Postgres'
        env:
          POSTGRES_HOST: localhost
          POSTGRES_PORT: ${{ job.services.postgres.ports[5432] }}
          POSTGRES_DB: ddf
          POSTGRES_USER: ddf_user
          POSTGRES_PASSWORD: ddf_pass
        run: |
          pip install psycopg2
          pytest --create-db --reuse-db --no-migrations --ds=settings_postgres --maxfail=2


================================================
FILE: .gitignore
================================================
.DS_Store
.idea/
dist/
build/
cover/
.settings
.project
.pydevproject
.settings/org.eclipse.core.resources.prefs
.settings/org.eclipse.core.runtime.prefs
.settings/org.eclipse.ltk.core.refactoring.prefs
.settings/org.eclipse.wst.validation.prefs
*.bat
*.sh
*.coverage
*.pyc
*.pyo
*.log
.noseids
*.sqlite
virtualenv*

django_dynamic_fixture.egg-info
env/
envpypy
env26
env27
env32
env33
env34
env2.6
env2.7
env3.2
env3.3
env3.4
.tox
test_:memory:
.eggs/

ddf_compatibility_report.*
htmlcov/*

================================================
FILE: .pylintrc
================================================
[MASTER]

# A comma-separated list of package or module names from where C extensions may
# be loaded. Extensions are loading into the active Python interpreter and may
# run arbitrary code.
extension-pkg-whitelist=

# Add files or directories to the blacklist. They should be base names, not
# paths.
ignore=CVS

# Add files or directories matching the regex patterns to the blacklist. The
# regex matches against base names, not paths.
ignore-patterns=

# Python code to execute, usually for sys.path manipulation such as
# pygtk.require().
#init-hook=

# Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the
# number of processors available to use.
jobs=1

# Control the amount of potential inferred values when inferring a single
# object. This can help the performance when dealing with large functions or
# complex, nested conditions.
limit-inference-results=100

# List of plugins (as comma separated values of python module names) to load,
# usually to register additional checkers.
load-plugins=

# Pickle collected data for later comparisons.
persistent=yes

# Specify a configuration file.
#rcfile=

# When enabled, pylint would attempt to guess common misconfiguration and emit
# user-friendly hints instead of false-positive error messages.
suggestion-mode=yes

# Allow loading of arbitrary C extensions. Extensions are imported into the
# active Python interpreter and may run arbitrary code.
unsafe-load-any-extension=no


[MESSAGES CONTROL]

# Only show warnings with the listed confidence levels. Leave empty to show
# all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED.
confidence=

# Disable the message, report, category or checker with the given id(s). You
# can either give multiple identifiers separated by comma (,) or put this
# option multiple times (only on the command line, not in the configuration
# file where it should appear only once). You can also use "--disable=all" to
# disable everything first and then reenable specific checks. For example, if
# you want to run only the similarities checker, you can use "--disable=all
# --enable=similarities". If you want to run only the classes checker, but have
# no Warning level messages displayed, use "--disable=all --enable=classes
# --disable=W".
disable=print-statement,
        parameter-unpacking,
        unpacking-in-except,
        old-raise-syntax,
        backtick,
        long-suffix,
        old-ne-operator,
        old-octal-literal,
        import-star-module-level,
        non-ascii-bytes-literal,
        raw-checker-failed,
        bad-inline-option,
        locally-disabled,
        file-ignored,
        suppressed-message,
        useless-suppression,
        deprecated-pragma,
        use-symbolic-message-instead,
        apply-builtin,
        basestring-builtin,
        buffer-builtin,
        cmp-builtin,
        coerce-builtin,
        execfile-builtin,
        file-builtin,
        long-builtin,
        raw_input-builtin,
        reduce-builtin,
        standarderror-builtin,
        unicode-builtin,
        xrange-builtin,
        coerce-method,
        delslice-method,
        getslice-method,
        setslice-method,
        no-absolute-import,
        old-division,
        dict-iter-method,
        dict-view-method,
        next-method-called,
        metaclass-assignment,
        indexing-exception,
        raising-string,
        reload-builtin,
        oct-method,
        hex-method,
        nonzero-method,
        cmp-method,
        input-builtin,
        round-builtin,
        intern-builtin,
        unichr-builtin,
        map-builtin-not-iterating,
        zip-builtin-not-iterating,
        range-builtin-not-iterating,
        filter-builtin-not-iterating,
        using-cmp-argument,
        eq-without-hash,
        div-method,
        idiv-method,
        rdiv-method,
        exception-message-attribute,
        invalid-str-codec,
        sys-max-int,
        bad-python3-import,
        deprecated-string-function,
        deprecated-str-translate-call,
        deprecated-itertools-function,
        deprecated-types-field,
        next-method-defined,
        dict-items-not-iterating,
        dict-keys-not-iterating,
        dict-values-not-iterating,
        deprecated-operator-function,
        deprecated-urllib-function,
        xreadlines-attribute,
        deprecated-sys-function,
        exception-escape,
        comprehension-escape

# Enable the message, report, category or checker with the given id(s). You can
# either give multiple identifier separated by comma (,) or put this option
# multiple time (only on the command line, not in the configuration file where
# it should appear only once). See also the "--disable" option for examples.
enable=c-extension-no-member


[REPORTS]

# Python expression which should return a score less than or equal to 10. You
# have access to the variables 'error', 'warning', 'refactor', and 'convention'
# which contain the number of messages in each category, as well as 'statement'
# which is the total number of statements analyzed. This score is used by the
# global evaluation report (RP0004).
evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)

# Template used to display messages. This is a python new-style format string
# used to format the message information. See doc for all details.
#msg-template=

# Set the output format. Available formats are text, parseable, colorized, json
# and msvs (visual studio). You can also give a reporter class, e.g.
# mypackage.mymodule.MyReporterClass.
output-format=text

# Tells whether to display a full report or only the messages.
reports=no

# Activate the evaluation score.
score=yes


[REFACTORING]

# Maximum number of nested blocks for function / method body
max-nested-blocks=5

# Complete name of functions that never returns. When checking for
# inconsistent-return-statements if a never returning function is called then
# it will be considered as an explicit return statement and no message will be
# printed.
never-returning-functions=sys.exit


[LOGGING]

# Format style used to check logging format string. `old` means using %
# formatting, `new` is for `{}` formatting,and `fstr` is for f-strings.
logging-format-style=old

# Logging modules to check that the string format arguments are in logging
# function parameter format.
logging-modules=logging


[SPELLING]

# Limits count of emitted suggestions for spelling mistakes.
max-spelling-suggestions=4

# Spelling dictionary name. Available dictionaries: none. To make it work,
# install the python-enchant package.
spelling-dict=

# List of comma separated words that should not be checked.
spelling-ignore-words=

# A path to a file that contains the private dictionary; one word per line.
spelling-private-dict-file=

# Tells whether to store unknown words to the private dictionary (see the
# --spelling-private-dict-file option) instead of raising a message.
spelling-store-unknown-words=no


[MISCELLANEOUS]

# List of note tags to take in consideration, separated by a comma.
notes=FIXME,
      XXX,
      TODO


[TYPECHECK]

# List of decorators that produce context managers, such as
# contextlib.contextmanager. Add to this list to register other decorators that
# produce valid context managers.
contextmanager-decorators=contextlib.contextmanager

# List of members which are set dynamically and missed by pylint inference
# system, and so shouldn't trigger E1101 when accessed. Python regular
# expressions are accepted.
generated-members=

# Tells whether missing members accessed in mixin class should be ignored. A
# mixin class is detected if its name ends with "mixin" (case insensitive).
ignore-mixin-members=yes

# Tells whether to warn about missing members when the owner of the attribute
# is inferred to be None.
ignore-none=yes

# This flag controls whether pylint should warn about no-member and similar
# checks whenever an opaque object is returned when inferring. The inference
# can return multiple potential results while evaluating a Python object, but
# some branches might not be evaluated, which results in partial inference. In
# that case, it might be useful to still emit no-member and other checks for
# the rest of the inferred objects.
ignore-on-opaque-inference=yes

# List of class names for which member attributes should not be checked (useful
# for classes with dynamically set attributes). This supports the use of
# qualified names.
ignored-classes=optparse.Values,thread._local,_thread._local

# List of module names for which member attributes should not be checked
# (useful for modules/projects where namespaces are manipulated during runtime
# and thus existing member attributes cannot be deduced by static analysis). It
# supports qualified module names, as well as Unix pattern matching.
ignored-modules=

# Show a hint with possible names when a member name was not found. The aspect
# of finding the hint is based on edit distance.
missing-member-hint=yes

# The minimum edit distance a name should have in order to be considered a
# similar match for a missing member name.
missing-member-hint-distance=1

# The total number of similar names that should be taken in consideration when
# showing a hint for a missing member.
missing-member-max-choices=1

# List of decorators that change the signature of a decorated function.
signature-mutators=


[VARIABLES]

# List of additional names supposed to be defined in builtins. Remember that
# you should avoid defining new builtins when possible.
additional-builtins=

# Tells whether unused global variables should be treated as a violation.
allow-global-unused-variables=yes

# List of strings which can identify a callback function by name. A callback
# name must start or end with one of those strings.
callbacks=cb_,
          _cb

# A regular expression matching the name of dummy variables (i.e. expected to
# not be used).
dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_

# Argument names that match this expression will be ignored. Default to name
# with leading underscore.
ignored-argument-names=_.*|^ignored_|^unused_

# Tells whether we should check for unused import in __init__ files.
init-import=no

# List of qualified module names which can have objects that can redefine
# builtins.
redefining-builtins-modules=past.builtins,future.builtins,builtins,io


[FORMAT]

# Expected format of line ending, e.g. empty (any line ending), LF or CRLF.
expected-line-ending-format=

# Regexp for a line that is allowed to be longer than the limit.
ignore-long-lines=^\s*(# )?<?https?://\S+>?$

# Number of spaces of indent required inside a hanging or continued line.
indent-after-paren=4

# String used as indentation unit. This is usually "    " (4 spaces) or "\t" (1
# tab).
indent-string='    '

# Maximum number of characters on a single line.
max-line-length=200

# Maximum number of lines in a module.
max-module-lines=1000

# List of optional constructs for which whitespace checking is disabled. `dict-
# separator` is used to allow tabulation in dicts, etc.: {1  : 1,\n222: 2}.
# `trailing-comma` allows a space between comma and closing bracket: (a, ).
# `empty-line` allows space-only lines.
no-space-check=trailing-comma,
               dict-separator

# Allow the body of a class to be on the same line as the declaration if body
# contains single statement.
single-line-class-stmt=no

# Allow the body of an if to be on the same line as the test if there is no
# else.
single-line-if-stmt=no


[SIMILARITIES]

# Ignore comments when computing similarities.
ignore-comments=yes

# Ignore docstrings when computing similarities.
ignore-docstrings=yes

# Ignore imports when computing similarities.
ignore-imports=no

# Minimum lines number of a similarity.
min-similarity-lines=4


[BASIC]

# Naming style matching correct argument names.
argument-naming-style=snake_case

# Regular expression matching correct argument names. Overrides argument-
# naming-style.
#argument-rgx=

# Naming style matching correct attribute names.
attr-naming-style=snake_case

# Regular expression matching correct attribute names. Overrides attr-naming-
# style.
#attr-rgx=

# Bad variable names which should always be refused, separated by a comma.
bad-names=foo,
          bar,
          baz,
          toto,
          tutu,
          tata

# Naming style matching correct class attribute names.
class-attribute-naming-style=any

# Regular expression matching correct class attribute names. Overrides class-
# attribute-naming-style.
#class-attribute-rgx=

# Naming style matching correct class names.
class-naming-style=PascalCase

# Regular expression matching correct class names. Overrides class-naming-
# style.
#class-rgx=

# Naming style matching correct constant names.
const-naming-style=UPPER_CASE

# Regular expression matching correct constant names. Overrides const-naming-
# style.
#const-rgx=

# Minimum line length for functions/classes that require docstrings, shorter
# ones are exempt.
docstring-min-length=-1

# Naming style matching correct function names.
function-naming-style=snake_case

# Regular expression matching correct function names. Overrides function-
# naming-style.
#function-rgx=

# Good variable names which should always be accepted, separated by a comma.
good-names=i,
           j,
           k,
           ex,
           Run,
           _

# Include a hint for the correct naming format with invalid-name.
include-naming-hint=no

# Naming style matching correct inline iteration names.
inlinevar-naming-style=any

# Regular expression matching correct inline iteration names. Overrides
# inlinevar-naming-style.
#inlinevar-rgx=

# Naming style matching correct method names.
method-naming-style=snake_case

# Regular expression matching correct method names. Overrides method-naming-
# style.
#method-rgx=

# Naming style matching correct module names.
module-naming-style=snake_case

# Regular expression matching correct module names. Overrides module-naming-
# style.
#module-rgx=

# Colon-delimited sets of names that determine each other's naming style when
# the name regexes allow several styles.
name-group=

# Regular expression which should only match function or class names that do
# not require a docstring.
no-docstring-rgx=^_

# List of decorators that produce properties, such as abc.abstractproperty. Add
# to this list to register other decorators that produce valid properties.
# These decorators are taken in consideration only for invalid-name.
property-classes=abc.abstractproperty

# Naming style matching correct variable names.
variable-naming-style=snake_case

# Regular expression matching correct variable names. Overrides variable-
# naming-style.
#variable-rgx=


[STRING]

# This flag controls whether the implicit-str-concat-in-sequence should
# generate a warning on implicit string concatenation in sequences defined over
# several lines.
check-str-concat-over-line-jumps=no


[IMPORTS]

# List of modules that can be imported at any level, not just the top level
# one.
allow-any-import-level=

# Allow wildcard imports from modules that define __all__.
allow-wildcard-with-all=no

# Analyse import fallback blocks. This can be used to support both Python 2 and
# 3 compatible code, which means that the block might have code that exists
# only in one or another interpreter, leading to false positives when analysed.
analyse-fallback-blocks=no

# Deprecated modules which should not be used, separated by a comma.
deprecated-modules=optparse,tkinter.tix

# Create a graph of external dependencies in the given file (report RP0402 must
# not be disabled).
ext-import-graph=

# Create a graph of every (i.e. internal and external) dependencies in the
# given file (report RP0402 must not be disabled).
import-graph=

# Create a graph of internal dependencies in the given file (report RP0402 must
# not be disabled).
int-import-graph=

# Force import order to recognize a module as part of the standard
# compatibility libraries.
known-standard-library=

# Force import order to recognize a module as part of a third party library.
known-third-party=enchant

# Couples of modules and preferred modules, separated by a comma.
preferred-modules=


[CLASSES]

# List of method names used to declare (i.e. assign) instance attributes.
defining-attr-methods=__init__,
                      __new__,
                      setUp,
                      __post_init__

# List of member names, which should be excluded from the protected access
# warning.
exclude-protected=_asdict,
                  _fields,
                  _replace,
                  _source,
                  _make

# List of valid names for the first argument in a class method.
valid-classmethod-first-arg=cls

# List of valid names for the first argument in a metaclass class method.
valid-metaclass-classmethod-first-arg=cls


[DESIGN]

# Maximum number of arguments for function / method.
max-args=5

# Maximum number of attributes for a class (see R0902).
max-attributes=7

# Maximum number of boolean expressions in an if statement (see R0916).
max-bool-expr=5

# Maximum number of branch for function / method body.
max-branches=12

# Maximum number of locals for function / method body.
max-locals=15

# Maximum number of parents for a class (see R0901).
max-parents=7

# Maximum number of public methods for a class (see R0904).
max-public-methods=20

# Maximum number of return / yield for function / method body.
max-returns=6

# Maximum number of statements in function / method body.
max-statements=50

# Minimum number of public methods for a class (see R0903).
min-public-methods=2


[EXCEPTIONS]

# Exceptions that will emit a warning when being caught. Defaults to
# "BaseException, Exception".
overgeneral-exceptions=BaseException,
                       Exception


================================================
FILE: .python-version
================================================
3.7.17
3.8.17
3.9.17
3.10.12
3.11.4


================================================
FILE: .readthedocs.yaml
================================================
# https://docs.readthedocs.io/en/stable/config-file/v2.html
version: 2

build:
  os: ubuntu-22.04
  tools:
    python: "3.11"

sphinx:
  configuration: docs/source/conf.py


================================================
FILE: LICENSE.txt
================================================
MIT license: http://opensource.org/licenses/MIT

Copyright (c) <2013> <Paulo Cheque>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


Apache 2.0

Copyright [2013] [Paulo Cheque]

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

================================================
FILE: MANIFEST.in
================================================


================================================
FILE: Makefile
================================================
VERSION=4.0.1

# Python env tasks

clean:
	clear
	@find . -type f -name "*.py[co]" -delete
	@find . -type d -name "__pycache__" -delete
	rm -rf *.egg
	rm -rf *.egg-info/
	rm -rf *.log
	rm -rf ~*
	rm -rf data/
	rm -rf dist/
	rm -rf build/
	rm -rf .eggs/
	rm -rf .tox/
	#rm -rf env/

os_deps:
	brew install gdal

prepare:
	clear ; python3.11 -m venv env

deps:
	clear
	env/bin/python -m pip install --upgrade pip
	env/bin/python -m pip install --upgrade setuptools wheel
	env/bin/pip install -r requirements.txt
	env/bin/pip install -r requirements-dev.txt
	env/bin/pip list

shell:
	#clear ; env/bin/python -i -c "from ddf import *"
	clear ; env/bin/python manage.py shell
	# from ddf import *

# Python code tasks

compile:
	env/bin/python -OO -m compileall .

test:
	# Run specific test:
	# TESTS=django_dynamic_fixture.tests.FILE::CLASS::METHOD make test
	clear ; time env/bin/pytest --create-db --reuse-db --no-migrations ${TESTS}

testfailed:
	clear ; env/bin/pytest --create-db --reuse-db --no-migrations ${TESTS} --last-failed

config_postgres:
	psql -U postgres -c "create extension postgis"
	# set up postgresql
	psql -U postgres -c "create role cacheops login superuser"
	# postgis django backend requires these to exist
	psql -U postgres -c "create database cacheops"
	psql -U postgres -c "create database cacheops_slave"
	# create db and user
	psql -c "CREATE DATABASE ddf;" -U postgres
	psql -c "CREATE USER ddf_user WITH PASSWORD 'ddf_pass';" -U postgres
	psql -c "ALTER USER ddf_user CREATEDB;" -U postgres
	psql -c "ALTER USER ddf_user WITH SUPERUSER;" -U postgres

test_postgres:
	# TESTS=django_dynamic_fixture.tests.FILE::CLASS::METHOD make test_postgres
	clear ; env/bin/pytest --reuse-db --no-migrations --ds=settings_postgres ${TESTS}

test_mysql:
	# TESTS=django_dynamic_fixture.tests.FILE::CLASS::METHOD make test_mysql
	clear ; env/bin/pytest --reuse-db --no-migrations --ds=settings_mysql ${TESTS}

cov:
	clear ; env/bin/pytest --create-db --reuse-db --no-migrations -v --cov=django_dynamic_fixture --cov-report html
	cp htmlcov/index.html docs/source/_static/coverage.html
	open htmlcov/index.html

code_style:
	# Code Style
	clear ; env/bin/pylint ddf django_dynamic_fixture queries

code_checking:
	# Code error checking
	clear ; env/bin/python -m pyflakes ddf django_dynamic_fixture queries

code_feedbacks:
	# PEP8, code style and circular complexity
	clear ; env/bin/flake8 ddf django_dynamic_fixture queries

code_ruff:
	clear ; env/bin/ruff check .
	#clear ; env/bin/ruff check . --fix

check: code_style code_checking code_feedbacks code_ruff

install_precommit_hooks: code_ruff
	clear ; env/bin/ruff check .
	env/bin/pre-commit install

doc: cov
	clear ; cd docs ; make clean html ; open build/html/index.html

tox:
	#brew update ; brew install pyenv
	#pyenv install 3.8 3.9 3.10 3.11
	#pyenv versions
	#pyenv local 3.7 3.8 3.9 3.10 3.11
	clear ; time env/bin/tox --parallel all

build: clean os_deps prepare deps test cov

# Python package tasks

lib: clean test cov doc
	# 	clear ; env/bin/python setup.py build
	# 	clear ; env/bin/python setup.py sdist
	clear ; env/bin/python -m build
	clear ; env/bin/twine check dist/*

publish: lib
	# Fixing Python 3 Certificates
	# /Applications/Python\ 3.7/Install\ Certificates.command
	# Manual upload to PypI
	# http://pypi.python.org/pypi/THE-PROJECT
	# Go to 'edit' link
	# Update version and save
	# Go to 'files' link and upload the file
	clear ; env/bin/twine upload dist/* --username=UPDATE_ME --password=UPDATE_ME

# Git tasks

push: tox doc
	clear ; git push origin `git symbolic-ref --short HEAD`

tag:
	git tag ${VERSION}
	git push origin ${VERSION}

reset_tag:
	git tag -d ${VERSION}
	git push origin :refs/tags/${VERSION}


# GitHub Action

act:
	#brew install act
	time act --container-architecture linux/amd64 --matrix python_version:3.11 --matrix django_version:4.2

actall:
	time act --container-architecture linux/amd64


================================================
FILE: README.md
================================================
Django Dynamic Fixture
======================

[![Docs Status](https://readthedocs.org/projects/django-dynamic-fixture/badge/?version=latest)](http://django-dynamic-fixture.readthedocs.org/en/latest/index.html)
[![PyPI version](https://badge.fury.io/py/django-dynamic-fixture.svg)](https://badge.fury.io/py/django-dynamic-fixture)
![PyPI - Python Version](https://img.shields.io/pypi/pyversions/django-dynamic-fixture)
![PyPI - Downloads](https://img.shields.io/pypi/dm/django-dynamic-fixture)

**Latest version: 4.0.1 (Sep 2023)**

Django Dynamic Fixture (DDF) is a complete and simple library to create dynamic model instances for testing purposes.

It lets you focus on your tests, instead of focusing on generating some dummy data which is boring and polutes the test source code.

* [Basic Examples](#basic-examples)
* [Cheat Sheet](#cheat-sheet)
* [Sponsors](#sponsors)
* <a href="http://django-dynamic-fixture.readthedocs.org/en/latest/index.html" target="_blank">Full Documentation</a>


Basic Examples
--------------

> Customize only the important details of the test:

```python
    from ddf import G
    from my_library import Author, Book

    def test_search_book_by_author():
        author1 = G(Author)
        author2 = G(Author)
        book1 = G(Book, authors=[author1])
        book2 = G(Book, authors=[author2])
        books = Book.objects.search_by_author(author1.name)
        assert book1 in books
        assert book2 not in books
```

> Using some goodies to keep the test code smaller:

```python
    from ddf import G

    def test_search_book_by_author():
        author1, author2 = G('my_library.Author', n=2)
        book1 = G('my_library.Book', authors=[author1])
        book2 = G('my_library.Book', authors=[author2])
        books = Book.objects.search_by_author(author1.name)
        assert book1 in books
        assert book2 not in books
```

> Configuring data from relationship fields:

```python
    from ddf import G

    def test_search_book_by_author():
        book1 = G(Book, main_author__name='Eistein')
        book2 = G(Book)
        books = Book.objects.search_by_author(book1.main_author.name)
        assert book1 in books
        assert book2 not in books
        assert book1.main_author.name == 'Eistein'
```

Cheat Sheet
--------------

```python
# Import the main DDF features
from ddf import N, G, F, M, C, P, teach # meaning: New, Get, ForeignKey, Mask, Copier, Print, teach
```

```python
# `N` creates an instance of model without saving it to DB
instance = N(Book)
```

```python
# `G` creates an instance of model and save it into the DB
instance = G(Book)
```

```python
# `F` customize relationship objects
instance = G(Book, author=F(name='Eistein'))
# Same as `F`
instance = G(Book, author__name='Eistein')
```

```python
# `M` receives a data mask and create a random string using it
# Known symbols: `_`, `#` or `-`
# To escape known symbols: `!`
instance = N(Book, address=M('Street ___, ### !- --'))
assert instance.address == 'Street TPA, 632 - BR'
```

```python
# `C` copies data from one field to another
instance = N(Book, address_formatted=C('address'), address=M('Street ___, ### \- --'))
assert instance.address_formatted == 'Street TPA, 632 - BR'
```

```python
# `teach` teaches DDF in how to build an instance
teach(Book, address=M('Street ___, ### !- --'))
instance = G(Book)
assert instance.address == 'Street TPA, 632 - BR'
```

```python
# `P` print instance values for debugging
P(instance)
```

```python
import ddf
ddf.__version__
```

```python
from ddf import ddf_check_models
succeeded, errors = ddf_check_models()
succeeded, errors = ddf_check_models(print_csv=True)
succeeded, errors = ddf_check_models(csv_filename='ddf_compatibility_report.csv')
```

Sponsors
--------------
- https://github.com/thnxdev


================================================
FILE: ddf/__init__.py
================================================
# Short alias to use: # `from ddf import *` instead of `from django_dynamic_fixture import *`
from django_dynamic_fixture import N, G, F, C, M, P, PRE_SAVE, POST_SAVE, __version__
from django_dynamic_fixture import new, get, fixture, teach, look_up_alias
from django_dynamic_fixture.decorators import skip_for_database, only_for_database
from django_dynamic_fixture.fdf import FileSystemDjangoTestCase
from django_dynamic_fixture.script_ddf_checkings import ddf_check_models


================================================
FILE: django_dynamic_fixture/__init__.py
================================================

"""
This is the facade of all features of DDF.
Module that contains wrappers and shortcuts (aliases).
"""
import warnings

from django.apps import apps

from django_dynamic_fixture.ddf import DynamicFixture, Copier, Mask, DDFLibrary, \
    set_pre_save_receiver, set_post_save_receiver
from django_dynamic_fixture.django_helper import print_field_values, django_greater_than
from django_dynamic_fixture.fixture_algorithms.sequential_fixture import SequentialDataFixture, \
    StaticSequentialDataFixture
from django_dynamic_fixture.global_settings import DDF_DEFAULT_DATA_FIXTURE, DDF_FILL_NULLABLE_FIELDS, DDF_FK_MIN_DEPTH, \
                                                    DDF_IGNORE_FIELDS, DDF_VALIDATE_MODELS, \
                                                    DDF_DEBUG_MODE, DDF_FIELD_FIXTURES
from django_dynamic_fixture.script_ddf_checkings import ddf_check_models


__version__ = '4.0.1'


if not django_greater_than(4, 0):
    warnings.warn("DDF 4.* officially supports only Django 4 or higher.", DeprecationWarning)


LOOKUP_SEP = '__'

def look_up_alias(ddf_as_f=True, **kwargs):
    """
    Example of parameters:
    a__b__c=1 => {a: {b: {c: 1}}}
    """
    field_dict = {}
    params_to_be_skipped = []
    for alias, value in kwargs.items():
        parts = alias.split(LOOKUP_SEP)
        if len(parts) == 1:
            params_to_be_skipped.append(alias)
        level_dict = field_dict
        for part in parts[:-1]:
            level_dict = level_dict.setdefault(part, {})
        level_dict[parts[-1]] = value
    if ddf_as_f:
        for root, value in field_dict.items():
            if root in params_to_be_skipped:
                field_dict[root] = value
            else:
                field_dict[root] = dict_to_f(value)
    return field_dict


def dict_to_f(value):
    """
    Example:
    1 => 1
    {b: 1} => F(b=1)
    {b: {c: 1}} => F(b=F(c=1))
    """
    if not isinstance(value, dict):
        return value
    else:
        kwargs = {}
        for k, v in value.items():
            if not isinstance(v, dict):
                kwargs[k] = v
            else:
                kwargs[k] = dict_to_f(v)
        return F(**kwargs)


def fixture(**kwargs):
    """
    DynamicFixture factory: It instantiate a DynamicFixture using global configurations.
    Same as F(...)
    """
    kwargs = look_up_alias(**kwargs)
    f = DynamicFixture(data_fixture=kwargs.pop('data_fixture', DDF_DEFAULT_DATA_FIXTURE),
                       fill_nullable_fields=kwargs.pop('fill_nullable_fields', DDF_FILL_NULLABLE_FIELDS),
                       ignore_fields=kwargs.pop('ignore_fields', []),
                       fk_min_depth=kwargs.pop('fk_min_depth', DDF_FK_MIN_DEPTH),
                       validate_models=kwargs.pop('validate_models', DDF_VALIDATE_MODELS),
                       print_errors=kwargs.pop('print_errors', True),
                       debug_mode=kwargs.pop('debug_mode', DDF_DEBUG_MODE),
                       **kwargs)
    return f


# Wrappers

def _new(model, n=1, ddf_lesson=None, persist_dependencies=False, **kwargs):
    """
    Return one or many valid instances of Django Models with fields filled with auto generated or customized data.
    All instances will NOT be persisted in the database, except its dependencies, in case @persist_dependencies is True.

    @model: The class of the Django model. It can be a string `<app_label>.<model_name>`
    @n: number of instances to be created with the given configuration. Default is 1.
    @ddf_lesson: use a custom ddf_lesson to build the model object.
    @persist_dependencies: If True, save internal dependencies, otherwise just instantiate them. Default is False.

    @data_fixture: override DDF_DEFAULT_DATA_FIXTURE configuration. Default is SequentialDataFixture().
    @fill_nullable_fields: override DDF_FILL_NULLABLE_FIELDS global configuration. Default is True.
    @ignore_fields: List of fields that will be ignored by DDF. It will be concatenated with the global list DDF_IGNORE_FIELDS. Default is [].
    @fk_min_depth: override DDF_FK_MIN_DEPTH global configuration. Default 0.
    @validate_models: override DDF_VALIDATE_MODELS global configuration. Default is False.
    @print_errors: print on console all instance values if DDF can not generate a valid object with the given configuration.

    Wrapper for the method DynamicFixture.new
    """
    if isinstance(model, str):
        model = apps.get_model(model)
    kwargs = look_up_alias(**kwargs)
    d = fixture(**kwargs)
    if n == 1:
        return d.new(model, ddf_lesson=ddf_lesson, persist_dependencies=persist_dependencies, **kwargs)
    instances = []
    for _ in range(n):
        instances.append(d.new(model, ddf_lesson=ddf_lesson, persist_dependencies=persist_dependencies, **kwargs))
    return instances


def _get(model, n=1, ddf_lesson=None, **kwargs):
    """
    Return one or many valid instances of Django Models with fields filled with auto generated or customized data.
    All instances will be persisted in the database.

    @model: The class of the Django model. It can be a string `<app_label>.<model_name>`
    @n: number of instances to be created with the given configuration. Default is 1.
    @ddf_lesson: use a custom ddf_lesson to build the model object.

    @data_fixture: override DDF_DEFAULT_DATA_FIXTURE configuration. Default is SequentialDataFixture().
    @fill_nullable_fields: override DDF_FILL_NULLABLE_FIELDS global configuration. Default is True.
    @ignore_fields: List of fields that will be ignored by DDF. It will be concatenated with the global list DDF_IGNORE_FIELDS. Default is [].
    @fk_min_depth: override DDF_FK_MIN_DEPTH global configuration. Default 0.
    @validate_models: override DDF_VALIDATE_MODELS global configuration. Default is False.
    @print_errors: print on console all instance values if DDF can not generate a valid object with the given configuration.

    Wrapper for the method DynamicFixture.get
    """
    if isinstance(model, str):
        model = apps.get_model(model)
    kwargs = look_up_alias(**kwargs)
    d = fixture(**kwargs)
    if n == 1:
        return d.get(model, ddf_lesson=ddf_lesson, **kwargs)
    instances = []
    for _ in range(n):
        instances.append(d.get(model, ddf_lesson=ddf_lesson, **kwargs))
    return instances


def _teach(model, ddf_lesson=None, **kwargs):
    '''
    @model: The class of the Django model. It can be a string `<app_label>.<model_name>`
    @ddf_lesson: Name of custom ddf_lesson to be created.

    @raise an CantOverrideddf_lesson error if the same model/ddf_lesson were called twice.

    Sometimes DDF can't create an model instance because the particularities of the model.
    The workaround for this is to teach DDF how to create it.
    Basically, we use the same object creation approach that will be saved as a template
    for the next DDF calls.

    Use this method to teach DDF how to create an instance.

    New metaphor for the shelve/library feature.
    `Shelve` becomes `Teach`
    `Library` becomes `Lessons`
    '''
    if isinstance(model, str):
        model = apps.get_model(model)
    kwargs = look_up_alias(**kwargs)
    d = fixture(**kwargs)
    return d.teach(model, ddf_lesson=ddf_lesson, **kwargs)


# Shortcuts
N = new = _new
G = get = _get
T = teach = _teach
F = fixture
C = Copier
M = Mask
P = print_field_values
DDFLibrary = DDFLibrary
PRE_SAVE = set_pre_save_receiver
POST_SAVE = set_post_save_receiver

import typing

INSTANCE_TYPE = typing.TypeVar('INSTANCE')

def new(model: typing.Type[INSTANCE_TYPE], n: int = 1, ddf_lesson = None, persist_dependencies: bool = True, **kwargs) -> INSTANCE_TYPE:
    return _new(model, n=n, ddf_lesson=ddf_lesson, persist_dependencies=persist_dependencies, **kwargs)

def get(model: typing.Type[INSTANCE_TYPE], n: int=1, ddf_lesson=None, **kwargs) -> INSTANCE_TYPE | typing.List[INSTANCE_TYPE]:
    return _get(model, n=n, ddf_lesson=ddf_lesson, **kwargs)

def teach(model: typing.Type[INSTANCE_TYPE], ddf_lesson=None, **kwargs):
    return _teach(model, ddf_lesson=ddf_lesson, **kwargs)

N = new
G = get
T = teach


================================================
FILE: django_dynamic_fixture/ddf.py
================================================

import inspect
import logging
import re
import sys

from django.core.files import File
from django.db.models import Field

try:
    from importlib import import_module
except ImportError:
    from django.utils.importlib import import_module

from django_dynamic_fixture.django_helper import get_related_model, \
    field_has_choices, field_has_default_value, get_fields_from_model, \
    print_field_values, get_many_to_many_fields_from_model, \
    get_unique_model_name, get_unique_field_name, is_model_abstract, \
    field_is_a_parent_link, get_field_by_name_or_raise, get_app_name_of_model, \
    is_model_class, is_relationship_field, is_file_field, is_key_field, \
    model_has_the_field, enable_auto_now, disable_auto_now, enable_auto_now_add, disable_auto_now_add


LOGGER = logging.getLogger('DDFLog')
_PRE_SAVE = {} # receivers to be executed before saving a instance;
_POST_SAVE = {} # receivers to be executed after saving a instance;


class UnsupportedFieldError(Exception):
    "DynamicFixture does not support this field."


class InvalidCopierExpressionError(Exception):
    "The specified expression used in a Copier is invalid."


class InvalidConfigurationError(Exception):
    "The specified configuration for the field can not be applied or it is bugged."


class InvalidManyToManyConfigurationError(Exception):
    "M2M attribute configuration must be a number or a list of DynamicFixture or model instances."


class BadDataError(Exception):
    "The data passed to a field has some problem (not unique or invalid) or a required attribute is in ignore list."


class InvalidModelError(Exception):
    "Invalid Model: The class is not a model or it is abstract."


class InvalidReceiverError(Exception):
    "Receiver is not a function that receive only the instance as parameter."


class PendingField(Exception):
    "Internal exception to control pending fields when using Copier."


def _validate_model(model_class):
    if not is_model_class(model_class):
        raise InvalidReceiverError(model_class, 'Invalid model')


def _validate_function(model_class, callback_function):
    if not inspect.isfunction(callback_function) or not callback_function:
        raise InvalidReceiverError(model_class, 'Invalid function')
    if callback_function:
        args = len(inspect.getfullargspec(callback_function).args)
    if args != 1:
        raise InvalidReceiverError(model_class, 'Invalid number of function arguments')


def set_pre_save_receiver(model_class, callback_function):
    '''
    :model_class: a model_class can have only one receiver. Do not complicate yourself.
    :callback_function must be a function that receive the instance as unique parameter.
    '''
    _validate_model(model_class)
    _validate_function(model_class, callback_function)
    _PRE_SAVE[model_class] = callback_function


def set_post_save_receiver(model_class, callback_function):
    '''
    :model_class: a model_class can have only one receiver. Do not complicate yourself.
    :callback_function must be a function that receive the instance as unique parameter.
    '''
    _validate_model(model_class)
    _validate_function(model_class, callback_function)
    _POST_SAVE[model_class] = callback_function


class DataFixture:
    '''
    Responsibility: return a valid data for a Django Field, according to its type, model class, constraints etc.

    You must create a separated method to generate data for an specific field. For a field called 'MyField',
    the method must be:

    def myfield_config(self, field, key): return 'some value'

    :field: Field object.
    :key: string that represents a unique name for a Field, considering app, model and field names.
    '''
    def __init__(self):
        self.plugins = {}

    def _field_fixture_template(self, field_class):
        return f'{field_class.__name__.lower()}_config'

    def _field_fixture_factory(self, field_class):
        try:
            fixture = self._field_fixture_template(field_class)
            getattr(self, fixture)
            return fixture
        except AttributeError:
            if len(field_class.__bases__) > 0:
                # Pick the first parent class that inherits Field (or use the first parent class)
                field_subclasses = (cls for cls in field_class.__bases__ if issubclass(cls, Field))
                parent_class = next(field_subclasses, field_class.__bases__[0])
                return self._field_fixture_factory(parent_class)
            else:
                return None

    def generate_data(self, field):
        '''Get a unique and valid data for the field.'''
        field_fullname = field.__module__ + "." + field.__class__.__name__
        fixture = self.plugins.get(field_fullname, {})
        if type(fixture) == dict:
            fixture = fixture.get('ddf_fixture', None)
        if fixture and callable(fixture):
            return fixture()
        config = self._field_fixture_factory(field.__class__)
        is_supported_field = config != None
        if is_supported_field:
            key = get_unique_field_name(field)
            data = eval(f'self.{config}(field, "{key}")')
        else:
            if field.null:
                data = None # a workaround for versatility
            else:
                raise(UnsupportedFieldError(get_unique_field_name(field) + ' (%s)' % (field_fullname)))
        return data


class Copier:
    '''
    Wrapper of an expression in the format 'field' or 'field.field' or 'field.field.field' etc
    This expression will be interpreted to copy the value of the specified field to the current field.
    Example of usage: G(MyModel, x=C('y.z')) => the value 'z' of field 'y' will be copied to field 'x'.
    '''
    def __init__(self, expression):
        self.expression = expression

    def __str__(self):
        return "C('%s')" % self.expression

    def immediate_field_name(self, instance):
        model_class = instance.__class__
        field_name = self.expression.split('.')[0]
        get_field_by_name_or_raise(model_class, field_name)
        return field_name

    def eval_expression(self, instance):
        try:
            current_instance = instance
            fields = self.expression.split('.')
            for field in fields:
                current_instance = getattr(current_instance, field)
            return current_instance
        except Exception as e:
            raise InvalidCopierExpressionError(self.expression, e)


class Mask:
    '''
    Wrapper for an expression mask that will be used to generate a random string with a custom format.

    The expression mask supports 4 special characters:
    - `#` for random numbers;
    - `-` for random uppercase chars;
    - `_` for random lowercase chars;
    - `!` to escape special chars;

    Other characters will not be interpreted and it will be considered part of the final string.

    Example of usage: D('###.___!----') => '510.kap-NGK'
    '''
    def __init__(self, expression):
        self.expression = expression

    def __str__(self):
        return "D('%s')" % self.expression

    def evaluate(self):
        import random
        import string
        chars = []
        escaped = False
        for char in self.expression:
            if escaped:
                c = char
                escaped = False
            elif char == '#':
                c = random.choice(string.digits)
            elif char == '-':
                c = random.choice(string.ascii_uppercase)
            elif char == '_':
               c = random.choice(string.ascii_lowercase)
            elif char == '!':
                escaped = True
                continue
            else:
                c = char
            chars.append(c)
        return ''.join(chars)


class DDFLibrary:
    instance = None
    DEFAULT_KEY = 'ddf_default'

    def __init__(self):
        self.configs = {} # {Model: {name: config}}"

    def __str__(self):
        return '\n'.join([f'{key} = {value}' for key, value in self.configs.items()])

    @classmethod
    def get_instance(cls):
        if not cls.instance:
            cls.instance = DDFLibrary()
        return cls.instance

    def add_configuration(self, model_class, kwargs, name=None):
        import os
        import warnings
        if name in [None, True]:
            name = self.DEFAULT_KEY
        model_class = self._get_concrete_model(model_class)
        if model_class in self.configs and name in self.configs[model_class]:
            if not os.getenv('DDF_SHELL_MODE'):
                msg = "Override a lesson is an anti-pattern and will turn your test suite very hard to understand."
                msg = f'A lesson {name} has already been saved for the model {model_class}. {msg}'
                warnings.warn(msg, RuntimeWarning)
        model_class_config = self.configs.setdefault(model_class, {})
        model_class_config[name] = kwargs

    def get_configuration(self, model_class, name=None):
        if name is None:
            name = self.DEFAULT_KEY
        model_class = self._get_concrete_model(model_class)
        # copy is important because this dict will be updated every time in the algorithm.
        config = self.configs.get(model_class, {})
        if name != self.DEFAULT_KEY and name not in config.keys():
            raise InvalidConfigurationError('There is no lesson for model {} with the name "{}"'.format(get_unique_model_name(model_class), name))
        return config.get(name, {}).copy() # default configuration never raises an error

    def _get_concrete_model(self, model_class):
        if hasattr(model_class, '_meta') and model_class._meta.proxy:
            return model_class._meta.concrete_model or model_class
        else:
            return model_class

    def clear(self):
        '''Remove all lessons of the library. Util for the DDF tests.'''
        self.configs = {}

    def clear_configuration(self, model_class):
        '''Remove from the library an specific configuration of a model.'''
        if model_class in self.configs.keys():
            del self.configs[model_class]


class DynamicFixture:
    '''
    Responsibility: create a valid model instance according to the given configuration.
    '''

    _DDF_CONFIGS = ['fill_nullable_fields', 'ignore_fields', 'data_fixture', 'fk_min_depth',
                    'validate_models', 'print_errors']

    def __init__(self, data_fixture, fill_nullable_fields=False, ignore_fields=[], fk_min_depth=0,
                 validate_models=False, print_errors=True, debug_mode=False, **kwargs):
        '''
        :data_fixture: algorithm to fill field data.
        :fill_nullable_fields: flag to decide if nullable fields must be filled with data.
        :ignore_fields: list of field names that must not be filled with data.
        :fk_min_depth: how deep DDF should go to create non-required FKs fields from the main model.
        :validate_models: flag to decide if the model_instance.full_clean() must be called before saving the object.
        :print_errors: flag to determine if the model data must be printed to console on errors. For some scripts is interesting to disable it.
        '''
        from django_dynamic_fixture.global_settings import DDF_IGNORE_FIELDS
        from django_dynamic_fixture.fixture_algorithms import FixtureFactory
        # custom config of fixtures
        self.data_fixture = FixtureFactory.get(data_fixture)

        self.fill_nullable_fields = fill_nullable_fields
        self.ignore_fields = ignore_fields
        # extend ignore_fields with globally declared ignore_fields
        self.ignore_fields.extend(DDF_IGNORE_FIELDS)
        self.fk_min_depth = fk_min_depth
        # other ddfs configs
        self.validate_models = validate_models
        self.print_errors = print_errors
        # internal logic
        self.pending_fields = []
        self.fields_processed = []
        self.debug_mode = debug_mode
        self.kwargs = kwargs
        self.fields_to_disable_auto_now = []
        self.fields_to_disable_auto_now_add = []

    def __str__(self):
        return 'F(%s)' % (', '.join(f'{key}={value}' for key, value in self.kwargs.items()))

    def __eq__(self, that):
        return isinstance(that, self.__class__) and self.kwargs == that.kwargs

    def _get_data_from_custom_dynamic_fixture(self, field, fixture, persist_dependencies):
        '''return data of a Dynamic Fixture: field=F(...)'''
        next_model = get_related_model(field)
        if persist_dependencies:
            data = fixture.get(next_model)
        else:
            data = fixture.new(next_model, persist_dependencies=persist_dependencies)
        return data

    def _get_data_from_custom_copier(self, instance, field, fixture):
        '''return data of a Copier: field=C(...)'''
        field_name = fixture.immediate_field_name(instance)
        if field_name in self.fields_processed:
            data = fixture.eval_expression(instance)
        else:
            self.pending_fields.append(field.name)
            raise PendingField('%s' % field.name)
        return data

    def _get_data_from_data_fixture(self, field, fixture):
        '''return data of a Data Fixture: field=DataFixture()'''
        next_model = get_related_model(field)
        return fixture.generate_data(next_model)

    def _get_data_from_a_custom_function(self, field, fixture):
        '''Returns data of a custom function: field=lambda field: field.name'''
        data = fixture(field)
        return data

    def _get_data_from_static_data(self, field, fixture):
        '''return date from a static value: field=3'''
        if hasattr(field, 'auto_now_add') and field.auto_now_add:
            self.fields_to_disable_auto_now_add.append(field)
        if hasattr(field, 'auto_now') and field.auto_now:
            self.fields_to_disable_auto_now.append(field)
        return fixture

    def _process_field_with_customized_fixture(self, instance, field, fixture, persist_dependencies):
        '''Set a custom value to a field.'''
        if isinstance(fixture, DynamicFixture): # DynamicFixture (F)
            data = self._get_data_from_custom_dynamic_fixture(field, fixture, persist_dependencies)
        elif isinstance(fixture, Copier): # Copier (C)
            data = self._get_data_from_custom_copier(instance, field, fixture)
        elif isinstance(fixture, Mask): # Mask (M)
            data = fixture.evaluate()
        elif isinstance(fixture, DataFixture): # DataFixture
            data = self._get_data_from_data_fixture(field, fixture)
        elif callable(fixture): # callable with the field as parameters
            data = self._get_data_from_a_custom_function(field, fixture)
        else: # attribute value
            data = self._get_data_from_static_data(field, fixture)
        return data

    def _process_foreign_key(self, model_class, field, persist_dependencies):
        '''
        Returns auto-generated value for a field ForeignKey or OneToOneField.
        '''
        if field_is_a_parent_link(field):
            return None
        next_model = get_related_model(field)

        # 1. Propagate ignored_fields only for self references
        if model_class == next_model: # self reference
            ignore_fields = self.ignore_fields
        else:
            ignore_fields = []
        # 2. It needs a new DynamicFixture to control the cycles and ignored fields.
        fixture = DynamicFixture(data_fixture=self.data_fixture,
                                 fill_nullable_fields=self.fill_nullable_fields,
                                 ignore_fields=ignore_fields,
                                 fk_min_depth=self.fk_min_depth - 1, # Depth decreased
                                 validate_models=self.validate_models,
                                 print_errors=self.print_errors)
        # 3. Persist it
        if persist_dependencies:
            data = fixture.get(next_model)
        else:
            data = fixture.new(next_model, persist_dependencies=persist_dependencies)
        return data

    def _process_field_with_default_fixture(self, field, model_class, persist_dependencies):
        '''
        The field has no custom value (F, C, static, Lessons...), so the default behavior of the tool is applied.
        - DDF behavior priority for common fields:
        1. Use `null` if possible (considering the `fill_nullable_fields` settings)
        2. Use the `default` value
        3. Use the first option of `choices`
        - DDF behavior priority for relationship fields:
        1. Use the `default` value
        2. Use `null` if possible, or consider the `fk_min_depth` value
        3. Create a new FK model
        '''
        if is_relationship_field(field):
            if field_has_default_value(field):
                # datetime default can receive a function: datetime.now
                data = field.default() if callable(field.default) else field.default
            else:
                if (not field.null) or self.fk_min_depth > 0:
                    data = self._process_foreign_key(model_class, field, persist_dependencies)
                else:
                    data = None
        else:
            if field_has_default_value(field):
                # datetime default can receive a function: datetime.now
                data = field.default() if callable(field.default) else field.default
            elif field.null and not self.fill_nullable_fields:
                data = None
            elif field_has_choices(field):
                data = field.flatchoices[0][0] # key of the first choice
            else:
                data = self.data_fixture.generate_data(field)
        return data

    def set_data_for_a_field(self, model_class, __instance, __field, persist_dependencies=True, **kwargs):
        if __field.name in kwargs:
            config = kwargs[__field.name]
            try:
                data = self._process_field_with_customized_fixture(__instance, __field, config, persist_dependencies)
            except PendingField:
                return # ignore this field for a while.
            except Exception as e:
                raise InvalidConfigurationError(get_unique_field_name(__field), e)
        else:
            data = self._process_field_with_default_fixture(__field, model_class, persist_dependencies)

        if is_file_field(__field) and data:
            django_file = data
            if isinstance(django_file, File):
                setattr(__instance, __field.name, data.name) # set the attribute
                if hasattr(django_file.file, 'mode') and django_file.file.mode != 'rb':
                    django_file.file.close() # this file may be open in another mode, for example, in a+b
                    opened_file = open(django_file.file.name, 'rb') # to save the file it must be open in rb mode
                    django_file.file = opened_file # we update the reference to the rb mode opened file

                # https://github.com/paulocheque/django-dynamic-fixture/issues/10
                # getattr(__instance, __field.name).save(django_file.name, django_file) # save the file into the file storage system
                # django_file.close()
                getattr(__instance, __field.name).save(django_file.name, django_file, save=False)

            else: # string (saving just a name in the file, without saving the file to the storage file system
                setattr(__instance, __field.name, data) # Model.field = data
        else:
            if self.debug_mode:
                LOGGER.debug(f'{get_unique_model_name(model_class)}.{__field.name} = {data}')
            try:
                setattr(__instance, __field.name, data) # Model.field = data
            except (ValueError, AttributeError) as e:
                if is_relationship_field(__field):
                    # Handle AttributeError for compatibility with django-polymorphic
                    # https://github.com/paulocheque/django-dynamic-fixture/issues/88
                    field_value = data.id if data and isinstance(e, AttributeError) else data
                    setattr(__instance, "%s_id" % __field.name, field_value) # Model.field = data
                else:
                    raise e
        self.fields_processed.append(__field.name)

    def _validate_kwargs(self, model_class, kwargs):
        '''validate all kwargs match Model.fields.'''
        for field_name in kwargs.keys():
            if field_name in self._DDF_CONFIGS:
                continue
            if not model_has_the_field(model_class, field_name):
                raise InvalidConfigurationError('Field "%s" does not exist.' % field_name)

    def _configure_params(self, model_class, ddf_lesson, **kwargs):
        '''
        1) validate kwargs
        2) load default fixture from DDF library. Store default fixture in DDF library.
        3) Load fixtures defined in F attributes.
        '''
        self._validate_kwargs(model_class, kwargs)

        library = DDFLibrary.get_instance()
        configuration = {}
        # 1. Load the default/global lesson for the model.
        configuration_default = library.get_configuration(model_class, name=DDFLibrary.DEFAULT_KEY)
        configuration.update(configuration_default) # always use default configuration
        # 2. Load a custom lesson for the model.
        if ddf_lesson:
            configuration_custom = library.get_configuration(model_class, name=ddf_lesson)
            configuration.update(configuration_custom) # override default configuration
        # 3. Load the custom `kwargs` attributes.
        configuration.update(kwargs) # override the configuration with current configuration
        configuration.update(self.kwargs) # Used by F: kwargs are passed by constructor, not by get.

        return configuration

    def new(self, model_class, ddf_lesson=None, persist_dependencies=True, **kwargs):
        '''
        Create an instance filled with data without persist it.
        1) validate all kwargs match Model.fields.
        2) validate model is a model.Model class.
        3) Iterate model fields: for each field, fill it with data.

        :ddf_lesson: the lesson that will be used to create the model instance, if exists.
        :persist_dependencies: tell if internal dependencies will be saved in the database or not.
        '''
        if self.debug_mode:
            LOGGER.debug('>>> [%s] Generating instance.' % get_unique_model_name(model_class))
        configuration = self._configure_params(model_class, ddf_lesson, **kwargs)
        try:
            instance = model_class()
        except TypeError:
            raise InvalidModelError(get_unique_model_name(model_class))
        if not is_model_class(instance):
            raise InvalidModelError(get_unique_model_name(model_class))

        try:
            # https://github.com/paulocheque/django-dynamic-fixture/pull/112
            from polymorphic import PolymorphicModel
            is_polymorphic = isinstance(instance, PolymorphicModel)
        except ImportError:
            # Django-polymorphic is not installed so the model can't be polymorphic.
            is_polymorphic = False
        for field in get_fields_from_model(model_class):
            if is_key_field(field) and field.name not in configuration: continue
            if field.name not in self.kwargs and self._is_ignored_field(field.name): continue
            if is_polymorphic and (field.name == 'polymorphic_ctype' or field.primary_key): continue
            self.set_data_for_a_field(model_class, instance, field, persist_dependencies=persist_dependencies, **configuration)
        number_of_pending_fields = len(self.pending_fields)
        # For Copier fixtures: dealing with pending fields that need to receive values of another fields.
        i = 0
        while self.pending_fields != []:
            field_name = self.pending_fields.pop(0)
            field = get_field_by_name_or_raise(model_class, field_name)
            self.set_data_for_a_field(model_class, instance, field, persist_dependencies=persist_dependencies, **configuration)
            i += 1
            if i > 2 * number_of_pending_fields: # dealing with infinite loop too.
                raise InvalidConfigurationError(get_unique_field_name(field), 'Cyclic dependency of Copiers.')
        if self.debug_mode:
            LOGGER.debug('<<< [%s] Instance created.' % get_unique_model_name(model_class))
        return instance

    def _is_ignored_field(self, field_name):
        '''
        Return `True` if the given field name should be ignored according to
        this class's `self.ignored_fields`. Both literal field names and
        names with wildcard '*' and '?' characters are supported.
        '''
        # Do fast check for literal field name first
        if field_name in self.ignore_fields:
            return True
        # If any ignored field names contain wildcards, check them against the
        # given field name
        for ignore_spec in self.ignore_fields:
            if '*' in ignore_spec or '?' in ignore_spec:
                # Replace wildcard characters with regexp equivalents
                re_spec = ignore_spec.replace('?', '.').replace('*', '.*')
                # Update regexp to match entire field name, not just a portion
                re_spec = r'^%s$' % re_spec
                if re.match(re_spec, field_name):
                    return True
        return False

    def _process_many_to_many_field(self, field, manytomany_field, fixture, instance):
        '''
        Set ManyToManyField fields with or without 'trough' option.

        :field: model field.
        :manytomany_field: ManyRelatedManager of the field.
        :fixture: value passed by user.
        '''
        next_model = get_related_model(field)
        if isinstance(fixture, int):
            amount = fixture
            for _ in range(amount):
                next_instance = self.get(next_model)
                self._create_manytomany_relationship(manytomany_field, instance, next_instance)
        elif isinstance(fixture, (list, tuple)):
            items = fixture
            for item in items:
                if isinstance(item, DynamicFixture):
                    next_instance = item.get(next_model, **item.kwargs) # need to pass F.kwargs recursively.
                else:
                    next_instance = item

                self._create_manytomany_relationship(manytomany_field, instance, next_instance)
        else:
            raise InvalidManyToManyConfigurationError('Field: %s' % field.name, str(fixture))

    def _create_manytomany_relationship(self, manytomany_field, instance, next_instance):
        try:
            manytomany_field.add(next_instance)
        except AttributeError:
            next_instance.save()

            # Create an instance of the "through" model using the current data fixture
            through_model = manytomany_field.through
            through_instance = DynamicFixture(data_fixture=self.data_fixture) \
                    .get(through_model, **{
                        manytomany_field.source_field_name: instance,
                        manytomany_field.target_field_name: next_instance
                    })

    def _save_the_instance(self, instance):
        for field in self.fields_to_disable_auto_now:
            disable_auto_now(field)
        for field in self.fields_to_disable_auto_now_add:
            disable_auto_now_add(field)
        instance.save()
        for field in self.fields_to_disable_auto_now:
            enable_auto_now(field)
        for field in self.fields_to_disable_auto_now_add:
            enable_auto_now_add(field)

    def get(self, model_class, ddf_lesson=None, **kwargs):
        '''
        Create an instance with data and persist it.

        :ddf_lesson: a custom lesson that will be used to create the model object.
        '''
        instance = self.new(model_class, ddf_lesson=ddf_lesson, **kwargs)
        if is_model_abstract(model_class):
            raise InvalidModelError(get_unique_model_name(model_class))
        try:
            if self.validate_models:
                instance.full_clean()
            if model_class in _PRE_SAVE:
                try:
                    _PRE_SAVE[model_class](instance)
                except Exception as e:
                    raise InvalidReceiverError(e)
            self._save_the_instance(instance)
            if model_class in _POST_SAVE:
                try:
                    _POST_SAVE[model_class](instance)
                except Exception as e:
                    raise InvalidReceiverError(e)
        except Exception as e:
            if self.print_errors:
                print_field_values(instance)
            raise BadDataError(get_unique_model_name(model_class), e)
        self.fields_processed = [] # TODO: need more tests for M2M and Copier
        self.pending_fields = []
        for field in get_many_to_many_fields_from_model(model_class):
            if field.name in kwargs.keys(): # TODO: library
                manytomany_field = getattr(instance, field.name)
                fixture = kwargs[field.name]
                try:
                    self._process_many_to_many_field(field, manytomany_field, fixture, instance)
                except InvalidManyToManyConfigurationError as e:
                    raise e
                except Exception as e:
                    raise InvalidManyToManyConfigurationError(get_unique_field_name(field), e)
        return instance

    def teach(self, model_class, ddf_lesson=None, **kwargs):
        library = DDFLibrary.get_instance()
        for field_name in kwargs.keys():
            if field_name in self._DDF_CONFIGS:
                continue
            field = get_field_by_name_or_raise(model_class, field_name)
            if field.unique and not _is_dynamic_value(kwargs[field_name]):
                raise InvalidConfigurationError('It is not possible to store static values for fields with unique=True (%s). Try using a lambda function instead.' % get_unique_field_name(field))
        library.add_configuration(model_class, kwargs, name=ddf_lesson)


def _is_dynamic_value(fixture):
    return isinstance(fixture, (DynamicFixture, Copier, DataFixture, Mask)) or callable(fixture)


================================================
FILE: django_dynamic_fixture/decorators.py
================================================

from django.conf import settings


DATABASE_ENGINE = settings.DATABASES['default']['ENGINE']

SQLITE3 = 'sqlite3'
POSTGRES = 'postgresql'
MYSQL = 'mysql'
ORACLE = 'oracle'
SQLSERVER = 'pyodbc'


def skip_for_database(database):
    def main_decorator(testcase_function):
        def wrapper(*args, **kwargs):
            if database not in DATABASE_ENGINE:
                testcase_function(*args, **kwargs)
        return wrapper
    return main_decorator


def only_for_database(database):
    def main_decorator(testcase_function):
        def wrapper(*args, **kwargs):
            if database in DATABASE_ENGINE:
                testcase_function(*args, **kwargs)
        return wrapper
    return main_decorator


================================================
FILE: django_dynamic_fixture/django_helper.py
================================================
"""
Module to wrap dirty stuff of django core.
"""
import django
from django.apps import apps
from django.db import models  # noqa
from django.db.models import *
from django.db.models.fields import NOT_PROVIDED, AutoField
from django.db.models.base import ModelBase
from django.db.models.query import QuerySet
try:
    from django.db.models.fields import FieldDoesNotExist
except ImportError:
    from django.core.exceptions import FieldDoesNotExist


def django_greater_than(major, minor=0):
    return django.VERSION[:2] > (major, minor)


# Apps
def get_apps(application_labels=[], exclude_application_labels=[]):
    """
    - if not @application_labels and not @exclude_application_labels, it returns all applications.
    - if @application_labels is not None, it returns just these applications,
    except applications with label in exclude_application_labels.
    @Returns an array of application labels.
    """
    if application_labels:
        applications = []
        for app_label in application_labels:
            app_config = apps.get_app_config(app_label)
            applications.append(app_config.label)
    else:
        applications = [
            app_config.label
            for app_config in apps.get_app_configs()
        ]
    if exclude_application_labels:
        for app_label in exclude_application_labels:
            if app_label:
                if app_label in applications:
                    applications.remove(app_label)
                else:
                    raise ValueError(
                        f"Excluded application with label '{app_label}' "
                        "is not installed.")
    return applications


def get_app_name(app_module):
    """
    app is the object (python module) returned by get_apps method
    """
    return app_module.__name__.split('.')[0]


def get_models_of_an_app(app_label):
    """
    app_module is the object returned by get_apps method (python module)
    """
    app_config = apps.get_app_config(app_label)
    return list(app_config.get_models())


# Models
def get_app_name_of_model(model_class):
    return model_class.__module__.split('.')[0]


def get_model_name(model_class):
    "Example: ModelName"
    return model_class.__name__


def get_unique_model_name(model_class):
    "Example: app.packages.ModelName"
    return model_class.__module__ + '.' + model_class.__name__


def get_fields_from_model(model_class):
    "Returns all fields, including inherited fields but ignoring M2M fields."
    return model_class._meta.fields


def get_local_fields(model):
    "Returns all local fields!?"
    return model._meta.local_fields


def get_many_to_many_fields_from_model(model_class):
    "Return only M2M fields, including inherited ones?"
    return model_class._meta.many_to_many
    #_meta.local_many_to_many


def get_all_fields_of_model(model_class):
    fields1 = get_fields_from_model(model_class)
    fields2 = get_many_to_many_fields_from_model(model_class)
    fields1.extend(fields2)
    return fields1


def get_field_names_of_model(model_class):
    "Get field names, including inherited fields, except M2M fields."
    fields = get_fields_from_model(model_class)
    return [field.name for field in fields]


def get_field_by_name_or_raise(model_class, field_name):
    "Get field by name, including inherited fields and M2M fields."
    return model_class._meta.get_field(field_name)


def is_model_class(instance_or_model_class):
    "True if model_class is a Django Model."
    return isinstance(instance_or_model_class, Model) or instance_or_model_class.__class__ == ModelBase


def is_model_abstract(model):
    "True if abstract is True in Meta class"
    return model._meta.abstract


def is_model_managed(model):
    "True if managed is True in Meta class"
    return model._meta.managed


def model_has_the_field(model_class, field_name):
    ""
    try:
        get_field_by_name_or_raise(model_class, field_name)
        return True
    except FieldDoesNotExist:
        return False


# Fields
def get_unique_field_name(field):
    if hasattr(field, 'model'):
        return get_unique_model_name(field.model) + '.' + field.name
    return field.name or ''


def get_related_model(field):
    return field.remote_field.model if hasattr(field, 'remote_field') else field.rel.to


def field_is_a_parent_link(field):
    # FIXME
    #return hasattr(field, 'rel') and hasattr(field.rel, 'parent_link') and field.rel.parent_link
    return hasattr(field, 'parent_link') and field.parent_link


def field_has_choices(field):
    """field.choices may be a tee, which we can't count without converting
    it to a list, or it may be a large database queryset, in which case we
    don't want to convert it to a list. We only care if the list is empty
    or not, so just try to access the first element and return True if that
    doesn't throw an exception."""
    if not field.choices:
        return False
    for i in field.choices:
        return True
    return False


def field_has_default_value(field):
    return field.default != NOT_PROVIDED


def field_is_unique(field):
    return field.unique


def is_key_field(field):
    return isinstance(field, AutoField)


def is_relationship_field(field):
    return isinstance(field, (ForeignKey, OneToOneField))


def is_file_field(field):
    return isinstance(field, FileField)


def print_field_values_of_a_model(model_instance):
    "Print values from all fields of a model instance."
    if model_instance == None:
        print('\n:: Model Unknown: None')
    else:
        print('\n:: Model %s (%s)' % (get_unique_model_name(model_instance.__class__), model_instance.pk))
        for field in get_fields_from_model(model_instance.__class__):
            try:
                value = getattr(model_instance, field.name)
            except Exception as e:
                value = repr(e)
            print('%s: %s' % (field.name, value))
        if model_instance.pk is not None:
            for field in get_many_to_many_fields_from_model(model_instance.__class__):
                print('%s: %s' % (field.name, getattr(model_instance, field.name).all()))


def print_field_values(model_instance_or_list_of_model_instances_or_queryset):
    "Print values from all fields of a model instance or a list of model instances."
    if isinstance(model_instance_or_list_of_model_instances_or_queryset, (list, tuple, QuerySet)):
        for model_instance in model_instance_or_list_of_model_instances_or_queryset:
            print_field_values_of_a_model(model_instance)
    else:
        model_instance = model_instance_or_list_of_model_instances_or_queryset
        print_field_values_of_a_model(model_instance)


def enable_auto_now(field):
    if hasattr(field, 'auto_now'):
        field.auto_now = True

def disable_auto_now(field):
    if hasattr(field, 'auto_now'):
        field.auto_now = False

def enable_auto_now_add(field):
    if hasattr(field, 'auto_now_add'):
        field.auto_now_add = True

def disable_auto_now_add(field):
    if hasattr(field, 'auto_now_add'):
        field.auto_now_add = False



def is_boolean(field):
    return isinstance(field, (BooleanField, NullBooleanField))

def is_string(field):
    return isinstance(field, (CharField, EmailField, IPAddressField, SlugField, URLField))

def is_number(field):
    return isinstance(field, (IntegerField, SmallIntegerField, PositiveIntegerField,
        PositiveSmallIntegerField, BigIntegerField, CommaSeparatedIntegerField, DecimalField, FloatField))

def is_datetime(field):
    return isinstance(field, (DateTimeField, DateField, TimeField))

def is_file(field):
    return isinstance(field, (FileField, FilePathField))

def is_binary(field):
    return isinstance(field, (BinaryField))


================================================
FILE: django_dynamic_fixture/fdf.py
================================================

import os
import tempfile

from shutil import rmtree, copy2
from django.core.files import File

from django.test import TestCase
from django.conf import settings
from django.core.files.storage import FileSystemStorage


TEMP_PATH = tempfile.gettempdir() or os.environ.get('TEMP')
TEMP_PATH_DDF = os.path.join(TEMP_PATH, 'DDF_TEMP')


class CustomFileSystemStorage(FileSystemStorage):
    def __init__(self, *args, **kwargs):
        super().\
        __init__(location=TEMP_PATH_DDF, *args, **kwargs)


class FileSystemDjangoTestCase(TestCase):
    TEAR_DOWN_ENABLED = True

    def setUp(self):
        self.fdf_setup()

    def tearDown(self):
        self.fdf_teardown()

    def _pre_setup(self):
        super()._pre_setup()
        self.fdf_setup()

    def _post_teardown(self):
        "Try to remove all files and directories created by the test."
        super()._post_teardown()
        self.fdf_teardown()

    def fdf_setup(self):
        self.directories = []
        self.files = {}
        setattr(settings, 'DEFAULT_FILE_STORAGE', 'django_dynamic_fixture.fdf.CustomFileSystemStorage')

    def fdf_teardown(self):
        if self.TEAR_DOWN_ENABLED:
            while self.files:
                self.remove_temp_file(next(iter(self.files.keys())))
            while self.directories:
                self.remove_temp_directory(self.directories[0])
            if os.path.exists(TEMP_PATH_DDF):
                rmtree(TEMP_PATH_DDF)

    def create_temp_directory(self, prefix='file_system_test_case_dir_'):
        "Create a temporary directory and returns the directory pathname."
        directory = tempfile.mkdtemp(prefix=prefix)
        self.directories.append(directory)
        return directory

    def remove_temp_directory(self, directory_pathname):
        "Remove a directory."
        rmtree(directory_pathname)
        if directory_pathname in self.directories:
            try:
                self.directories.remove(directory_pathname)
            except WindowsError:
                pass

    def create_temp_file(self, directory=None, prefix='file_system_test_case_file_', suffix='.tmp'):
        """
        Create a temporary file with a option prefix and suffix in a temporary or custom directory.
        Returns the filepath
        """
        tmp_file = tempfile.mkstemp(prefix=prefix, dir=directory, suffix=suffix)
        file_obj = os.fdopen(tmp_file[0])
        self.files[tmp_file[1]] = file_obj
        return tmp_file[1]

    def create_temp_file_with_name(self, directory, name):
        "Create a temporary file with a specified name."
        filepath = os.path.join(directory, name)
        file_obj = open(filepath, 'wb')
        file_obj.close()
        self.files[filepath] = file_obj
        return filepath

    def rename_temp_file(self, filepath, name):
        "Rename an existent file. 'name' is not a file path, so it must not include the directory path name."
        directory = self.get_directory_of_the_file(filepath)
        new_filepath = os.path.join(directory, name)
        os.rename(filepath, new_filepath)
        if filepath in self.files.keys():
            self.files.pop(filepath)
        self.files[new_filepath] = open(new_filepath, 'a+b')
        self.files[new_filepath].close()
        return new_filepath

    def remove_temp_file(self, filepath):
        "Remove a file."
        if filepath in self.files.keys():
            fileobj = self.files.pop(filepath)
            fileobj.close()
        if os.path.exists(filepath):
            try:
                os.unlink(filepath)
            except WindowsError:
                pass

    def copy_file_to_dir(self, filepath, directory):
        "Copy a file to a specified directory."
        copy2(filepath, directory)
        return self.get_filepath(directory, self.get_filename(filepath))

    def add_text_to_file(self, filepath, content):
        "Add text to an existent file."
        file = open(filepath, 'a')
        file.write(content)
        file.close()

    def get_directory_of_the_file(self, filepath):
        "Get the directory path name of a file."
        return os.path.dirname(filepath)

    def get_filename(self, filepath):
        "Get the filename of a file."
        return os.path.basename(filepath)

    def get_filepath(self, directory, filename):
        "Get the file path of a file with a defined name in a directory."
        return os.path.join(directory, filename)

    def get_content_of_file(self, filepath):
        "Returns the content of a file."
        file = open(filepath, 'r')
        content = file.read()
        file.close()
        return content

    def create_django_file_with_temp_file(self, name, content=None, dir=None, prefix='file_system_test_case_file_', suffix='.tmp'):
        "Create and returns a django.core.files.File"
        file = open(self.create_temp_file(directory=dir, prefix=prefix, suffix=suffix), 'w')
        file.close()
        django_file = File(file, name=name)
        self.files[django_file.file.name] = open(django_file.file.name, 'a+b')
        if content:
            self.files[django_file.file.name].write(content)
        self.files[django_file.file.name].close()
        return django_file

    def create_django_file_using_file(self, filepath):
        "Create and returns a django.core.files.File"
        new_filepath = self.copy_file_to_dir(filepath, self.create_temp_directory())
        the_file = open(new_filepath, 'rb')
        django_file = File(the_file, name=os.path.basename(new_filepath))
        self.files[django_file.file.name] = the_file
        #self.files[django_file.file.name].close()
        return django_file

    def assertFileExists(self, filepath):
        assert os.path.exists(filepath), '%s does not exist' % filepath

    def assertFileDoesNotExists(self, filepath):
        assert os.path.exists(filepath) is False, '%s exist' % filepath

    def assertDirectoryExists(self, directory):
        "@directory must be the directory path"
        assert os.path.exists(directory), '%s does not exist' % directory

    def assertDirectoryDoesNotExists(self, directory):
        "@directory must be the directory path"
        assert os.path.exists(directory) is False, '%s exist' % directory

    def assertDirectoryContainsFile(self, directory, filename):
        filepath = os.path.join(directory, filename)
        self.assertFileExists(filepath)

    def assertDirectoryDoesNotContainsFile(self, directory, filename):
        filepath = os.path.join(directory, filename)
        self.assertFileDoesNotExists(filepath)

    def assertFilesHaveEqualLastModificationTimestamps(self, filepath1, filepath2):
        assert os.path.getmtime(filepath1) - os.path.getmtime(filepath2) == 0

    def assertFilesHaveNotEqualLastModificationTimestamps(self, filepath1, filepath2):
        assert os.path.getmtime(filepath1) - os.path.getmtime(filepath2) != 0

    def assertNumberOfFiles(self, directory, number_of_files):
        filenames = [filename for filename in os.listdir(directory) if os.path.isfile(os.path.join(directory, filename))]
        assert len(filenames) == number_of_files, '[%s] %s' % (len(filenames), filenames)


================================================
FILE: django_dynamic_fixture/fields.py
================================================
import json

from django.conf import settings
from django.contrib.postgres.fields import (
    JSONField as DjangoJSONField,
    ArrayField as DjangoArrayField,
)
from django.db.models import Field


class JSONField(DjangoJSONField):
    pass


class ArrayField(DjangoArrayField):
    pass


if 'sqlite' in settings.DATABASES['default']['ENGINE']:
    class JSONField(Field):
        def db_type(self, connection):
            return 'text'

        def from_db_value(self, value, expression, connection):
            if value is not None:
                return self.to_python(value)
            return value

        def to_python(self, value):
            if value is not None:
                try:
                    return json.loads(value)
                except (TypeError, ValueError):
                    return value
            return value

        def get_prep_value(self, value):
            if value is not None:
                return str(json.dumps(value))
            return value

        def value_to_string(self, obj):
            return self.value_from_object(obj)


    class ArrayField(JSONField):
        def __init__(self, base_field, size=None, **kwargs):
            """Care for DjanroArrayField's kwargs."""
            self.base_field = base_field
            self.size = size
            return super().__init__(**kwargs)

        def deconstruct(self):
            """Need to create migrations properly."""
            name, path, args, kwargs = super().deconstruct()
            kwargs.update({
                'base_field': self.base_field.clone(),
                'size': self.size,
            })
            return name, path, args, kwargs


================================================
FILE: django_dynamic_fixture/fixture_algorithms/__init__.py
================================================
from django_dynamic_fixture.fixture_algorithms.sequential_fixture import SequentialDataFixture, StaticSequentialDataFixture
from django_dynamic_fixture.fixture_algorithms.random_fixture import RandomDataFixture


class FixtureFactory:
    @staticmethod
    def get(data_fixture):
        if data_fixture == 'static_sequential':
            return SequentialDataFixture()
        elif data_fixture == 'sequential':
            return SequentialDataFixture()
        elif data_fixture == 'random':
            return RandomDataFixture()
        return data_fixture

================================================
FILE: django_dynamic_fixture/fixture_algorithms/default_fixture.py
================================================
# -*- coding: utf-8 -*-
from datetime import datetime, date, timedelta
from decimal import Decimal
import random
import string
import uuid

from django.core.exceptions import ImproperlyConfigured


try:
    from django.utils.timezone import now
except ImportError:
    now = datetime.now

try:
    from django.contrib.gis.geos import *
except ImproperlyConfigured:
    pass  # environment without geo libs
except Exception:
    pass # Avoid errors like GDALException


from django_dynamic_fixture.ddf import DataFixture


class BaseDataFixture(DataFixture):
    # Django >= 1.6
    def binaryfield_config(self, field, key):
        return b'\x00\x46\xFE'

    # Django >= 1.8
    def uuidfield_config(self, field, key):
        return uuid.uuid4()

    # Django >= 1.4
    def genericipaddressfield_config(self, field, key):
        return self.ipaddressfield_config(field, key)

    # POSTGRES
    def  jsonfield_config(self, field, key):
        return {}


# GIS/GeoDjango
class GeoDjangoFixtureMixin:
    def create_point(self, x=None, y=None):
        # latitude: [-90,90], longitude: [-180,180]
        latitude = x or random.randint(-90, 90)
        longitude = y or random.randint(-180, 180)
        return Point(longitude, latitude)

    def create_points(self, n=3, closed=True):
        points = [self.create_point() for i in range(n)]
        if closed: # LinearRing
            points.append(points[0])
        return points

    def geometryfield_config(self, field, key):
        return GEOSGeometry('POINT(%s %s)' % self.create_point().coords)

    def pointfield_config(self, field, key):
        return self.create_point()

    def linestringfield_config(self, field, key, n=3):
        return LineString(self.create_points(n))

    def polygonfield_config(self, field, key, n=3):
        return Polygon(self.create_points(n))

    def multipointfield_config(self, field, key, n=3):
        return MultiPoint(self.create_points(n))

    def multilinestringfield_config(self, field, key, n=3):
        lines = [self.linestringfield_config(field, key, n) for i in range(n)]
        return MultiLineString(lines)

    def multipolygonfield_config(self, field, key, n=3):
        polygons = [self.polygonfield_config(field, key, n) for i in range(n)]
        return MultiPolygon(polygons)

    def geometrycollectionfield_config(self, field, key, n=3):
        polygons = [self.polygonfield_config(field, key, n) for i in range(n)]
        return GeometryCollection(polygons)


# Postgres fields
# https://docs.djangoproject.com/en/1.8/ref/contrib/postgres/fields/
class PostgresFixtureMixin:
    def arrayfield_config(self, field, key, n=1):
        data = [self.generate_data(field.base_field) for i in range(n)]
        return data


================================================
FILE: django_dynamic_fixture/fixture_algorithms/random_fixture.py
================================================
from datetime import datetime, date, timedelta
from decimal import Decimal
import random
import string

from django.core.exceptions import ImproperlyConfigured

try:
    from django.utils.timezone import now
except ImportError:
    now = datetime.now

try:
    from django.contrib.gis.geos import *
except ImproperlyConfigured:
    pass  # environment without geo libs
except Exception:
    pass # Avoid errors like GDALException

from django_dynamic_fixture.fixture_algorithms.default_fixture import BaseDataFixture, GeoDjangoFixtureMixin, PostgresFixtureMixin


class RandomDataFixture(BaseDataFixture, GeoDjangoFixtureMixin, PostgresFixtureMixin):
    def random_string(self, n):
        return ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(n))

    # NUMBERS
    def integerfield_config(self, field, key, start=1, end=10 ** 6):
        return random.randint(start, end)

    def smallintegerfield_config(self, field, key):
        # Values from -32768 to 32767 are safe in all databases supported by Django.
        return self.integerfield_config(field, key, -2 ** 15, 2 ** 15 - 1)

    def positiveintegerfield_config(self, field, key):
        return self.integerfield_config(field, key)

    def positivesmallintegerfield_config(self, field, key):
        # Values up to 32767 are safe in all databases supported by Django.
        return self.integerfield_config(field, key, end=2 ** 15 - 1)

    def bigintegerfield_config(self, field, key):
        return self.integerfield_config(field, key)

    def floatfield_config(self, field, key):
        return float(self.integerfield_config(field, key))

    def decimalfield_config(self, field, key):
        data = self.integerfield_config(field, key)
        number_of_digits = field.max_digits - field.decimal_places
        max_value = 10 ** number_of_digits
        data = data % max_value
        return Decimal(str(data))

    # STRINGS
    def charfield_config(self, field, key):
        if field.max_length:
            length = field.max_length
        else:
            length = 10
        return self.random_string(length)

    def textfield_config(self, field, key):
        return self.charfield_config(field, key)

    def slugfield_config(self, field, key):
        return self.charfield_config(field, key)

    def commaseparatedintegerfield_config(self, field, key):
        return str(random.randint(1, field.max_length)) #FIXME:

    # BOOLEAN
    def booleanfield_config(self, field, key):
        return random.randint(0, 1) == 0

    def nullbooleanfield_config(self, field, key):
        values = {0: None, 1: False, 2: True}
        return values[random.randint(0, 2)]

    # DATE/TIME RELATED
    def datefield_config(self, field, key):
        return date.today() - timedelta(days=random.randint(1, 36500))

    def timefield_config(self, field, key):
        return (now() - timedelta(seconds=random.randint(1, 36500))).time()

    def datetimefield_config(self, field, key):
        return now() - timedelta(seconds=random.randint(1, 36500))

    # FORMATTED STRINGS
    def emailfield_config(self, field, key):
        return f'a{self.random_string(10)}@dynamicfixture.com'

    def urlfield_config(self, field, key):
        return f'http://dynamicfixture{self.random_string(10)}.com'

    # Deprecated in Django >= 1.7
    def ipaddressfield_config(self, field, key):
        a = random.randint(1, 255)
        b = random.randint(1, 255)
        c = random.randint(1, 255)
        d = random.randint(1, 255)
        return f'{a}.{b}.{c}.{d}'

    def xmlfield_config(self, field, key):
        return f'<a>{self.random_string(5)}</a>'

    # FILES
    def filepathfield_config(self, field, key):
        return self.random_string(10)

    def filefield_config(self, field, key):
        return self.random_string(10)

    def imagefield_config(self, field, key):
        return self.random_string(10)


================================================
FILE: django_dynamic_fixture/fixture_algorithms/sequential_fixture.py
================================================
from datetime import datetime, date, timedelta
from decimal import Decimal
import threading

from django.core.exceptions import ImproperlyConfigured

try:
    from django.utils.timezone import now
except ImportError:
    now = datetime.now

try:
    from django.contrib.gis.geos import *
except ImproperlyConfigured:
    pass  # environment without geo libs
except Exception:
    pass # Avoid errors like GDALException

from django_dynamic_fixture.fixture_algorithms.default_fixture import BaseDataFixture, GeoDjangoFixtureMixin, PostgresFixtureMixin
from django_dynamic_fixture.django_helper import field_is_unique


class AutoDataFiller:
    """
    Responsibility: generate a unique and sequential value for each key.
    """

    def __init__(self):
        self.__data_controller_map = {} # key => counter
        self.__locks = {} # key => lock

    # synchronized by key
    def next(self, key):
        if key not in self.__data_controller_map:
            self.__data_controller_map[key] = 0
            self.__locks[key] = threading.RLock()
        self.__locks[key].acquire()
        self.__data_controller_map[key] += 1
        value = self.__data_controller_map[key]
        self.__locks[key].release()
        return value

    def current(self, key):
        if key not in self.__data_controller_map:
            self.next(key)
        return self.__data_controller_map[key]


class SequentialDataFixture(BaseDataFixture, GeoDjangoFixtureMixin, PostgresFixtureMixin):

    def __init__(self):
        super().__init__()
        self.filler = AutoDataFiller()

    def get_value(self, field, key):
        return self.filler.next(key)

    # NUMBERS
    def integerfield_config(self, field, key):
        return self.get_value(field, key)

    def smallintegerfield_config(self, field, key):
        return self.integerfield_config(field, key)

    def positiveintegerfield_config(self, field, key):
        return self.integerfield_config(field, key)

    def positivesmallintegerfield_config(self, field, key):
        return self.integerfield_config(field, key)

    def bigintegerfield_config(self, field, key):
        return self.integerfield_config(field, key)

    def floatfield_config(self, field, key):
        return float(self.get_value(field, key))

    def decimalfield_config(self, field, key):
        data = self.get_value(field, key)
        number_of_digits = field.max_digits - field.decimal_places
        max_value = 10 ** number_of_digits
        data = data % max_value
        return Decimal(str(data))

    # STRINGS
    def charfield_config(self, field, key):
        data = self.get_value(field, key)
        if field.max_length:
            max_value = (10 ** field.max_length) - 1
            data = str(data % max_value)
            data = data[:field.max_length]
        else:
            data = str(data)
        return data

    def textfield_config(self, field, key):
        return self.charfield_config(field, key)

    def slugfield_config(self, field, key):
        return self.charfield_config(field, key)

    def commaseparatedintegerfield_config(self, field, key):
        return self.charfield_config(field, key)

    # BOOLEAN
    def booleanfield_config(self, field, key):
        return False

    def nullbooleanfield_config(self, field, key):
        return None

    # DATE/TIME RELATED
    def datefield_config(self, field, key):
        data = self.get_value(field, key)
        return date.today() - timedelta(days=data)

    def timefield_config(self, field, key):
        data = self.get_value(field, key)
        return (now() - timedelta(seconds=data)).time()

    def datetimefield_config(self, field, key):
        data = self.get_value(field, key)
        return now() - timedelta(seconds=data)

    # FORMATTED STRINGS
    def emailfield_config(self, field, key):
        return f'a{self.get_value(field, key)}@dynamicfixture.com'

    def urlfield_config(self, field, key):
        return f'http://dynamicfixture{self.get_value(field, key)}.com'

    # Deprecated in Django >= 1.7
    def ipaddressfield_config(self, field, key):
        # TODO: better workaround (this suppose ip field is not unique)
        data = self.get_value(field, key)
        a = '1'
        b = '1'
        c = '1'
        d = data % 256
        return f'{a}.{b}.{c}.{d}'

    def xmlfield_config(self, field, key):
        return f'<a>{self.get_value(field, key)}</a>'

    # FILES
    def filepathfield_config(self, field, key):
        return str(self.get_value(field, key))

    def filefield_config(self, field, key):
        return str(self.get_value(field, key))

    def imagefield_config(self, field, key):
        return str(self.get_value(field, key))


class GlobalSequentialDataFixture(SequentialDataFixture):
    def get_value(self, field, key):
        return self.filler.next('ddf-global-key')


class StaticSequentialDataFixture(SequentialDataFixture):
    def get_value(self, field, key):
        if field_is_unique(field):
            return self.filler.next(key)
        else:
            return self.filler.current(key)


================================================
FILE: django_dynamic_fixture/fixture_algorithms/tests/__init__.py
================================================



================================================
FILE: django_dynamic_fixture/fixture_algorithms/tests/abstract_test_generic_fixture.py
================================================

from django.db import models

from datetime import datetime, date, time
from decimal import Decimal


class DataFixtureTestCase:
    def setUp(self):
        self.fixture = None

    def test_numbers(self):
        assert isinstance(self.fixture.generate_data(models.IntegerField()), int)
        assert isinstance(self.fixture.generate_data(models.SmallIntegerField()), int)
        assert isinstance(self.fixture.generate_data(models.PositiveIntegerField()), int)
        assert isinstance(self.fixture.generate_data(models.PositiveSmallIntegerField()), int)
        assert isinstance(self.fixture.generate_data(models.BigIntegerField()), int)
        assert isinstance(self.fixture.generate_data(models.FloatField()), float)
        assert isinstance(self.fixture.generate_data(models.DecimalField(max_digits=1, decimal_places=1)), Decimal)

    def test_it_must_deal_with_decimal_max_digits(self):
        # value 10 must be a problem, need to restart the counter: 10.0 has 3 digits
        for _ in range(11):
            assert isinstance(self.fixture.generate_data(models.DecimalField(max_digits=1, decimal_places=1)), Decimal)
            assert isinstance(self.fixture.generate_data(models.DecimalField(max_digits=2, decimal_places=1)), Decimal)

    def test_strings(self):
        assert isinstance(self.fixture.generate_data(models.CharField(max_length=1)), str)
        assert isinstance(self.fixture.generate_data(models.TextField()), str)
        assert isinstance(self.fixture.generate_data(models.SlugField(max_length=1)), str)
        assert isinstance(self.fixture.generate_data(models.CommaSeparatedIntegerField(max_length=1)), str)

    def test_new_truncate_strings_to_max_length(self):
        for _ in range(12): # truncate start after the 10 object
            assert isinstance(self.fixture.generate_data(models.CharField(max_length=1)), str)

    def test_boolean(self):
        assert isinstance(self.fixture.generate_data(models.BooleanField()), bool)
        value = self.fixture.generate_data(models.NullBooleanField())
        assert isinstance(value, bool) or value is None

    def test_date_time_related(self):
        assert isinstance(self.fixture.generate_data(models.DateField()), date)
        assert isinstance(self.fixture.generate_data(models.TimeField()), time)
        assert isinstance(self.fixture.generate_data(models.DateTimeField()), datetime)

    def test_formatted_strings(self):
        assert isinstance(self.fixture.generate_data(models.EmailField(max_length=100)), str)
        assert isinstance(self.fixture.generate_data(models.URLField(max_length=100)), str)
        assert isinstance(self.fixture.generate_data(models.IPAddressField(max_length=100)), str)
        assert isinstance(self.fixture.generate_data(models.GenericIPAddressField(max_length=100)), str)

    def test_files(self):
        assert isinstance(self.fixture.generate_data(models.FilePathField(max_length=100)), str)
        assert isinstance(self.fixture.generate_data(models.FileField()), str)
        try:
            import pil
            # just test it if the PIL package is installed
            assert isinstance(self.fixture.generate_data(models.ImageField(max_length=100)), str)
        except ImportError:
            pass



================================================
FILE: django_dynamic_fixture/fixture_algorithms/tests/test_default_fixture.py
================================================
import uuid

from django.db import models
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured


try:
    from django.contrib.gis.geos import *
    from django.contrib.gis.db import models as geomodels
except ImproperlyConfigured:
    pass  # environment without geo libs


from django.test import TestCase

from django_dynamic_fixture.fixture_algorithms.default_fixture import BaseDataFixture


class BaseDataFixtureTestCase(TestCase):
    def setUp(self):
        self.fixture = BaseDataFixture()

    def test_uuid(self):
        assert isinstance(self.fixture.generate_data(models.UUIDField()), uuid.UUID)


if (hasattr(settings, 'DDF_TEST_GEODJANGO') and settings.DDF_TEST_GEODJANGO):
    from django_dynamic_fixture.fixture_algorithms.default_fixture import GeoDjangoFixtureMixin

    # Mixing for tests
    class GeoDjangoFixtureMixin(BaseDataFixture, GeoDjangoFixtureMixin):
        pass

    class GeoDjangoDataFixtureTestCase(TestCase):
        def setUp(self):
            self.fixture = GeoDjangoFixtureMixin()

        def test_geometryfield_config(self):
            assert isinstance(self.fixture.generate_data(geomodels.GeometryField()), GEOSGeometry)

        def test_pointfield_config(self):
            assert isinstance(self.fixture.generate_data(geomodels.PointField()), Point)

        def test_linestringfield_config(self):
            assert isinstance(self.fixture.generate_data(geomodels.LineStringField()), LineString)

        def test_polygonfield_config(self):
            assert isinstance(self.fixture.generate_data(geomodels.PolygonField()), Polygon)

        def test_multipointfield_config(self):
            assert isinstance(self.fixture.generate_data(geomodels.MultiPointField()), MultiPoint)

        def test_multilinesstringfield_config(self):
            assert isinstance(self.fixture.generate_data(geomodels.MultiLineStringField()), MultiLineString)

        def test_multipolygonfield_config(self):
            assert isinstance(self.fixture.generate_data(geomodels.MultiPolygonField()), MultiPolygon)

        def test_geometrycollectionfield_config(self):
            assert isinstance(self.fixture.generate_data(geomodels.GeometryCollectionField()), GeometryCollection)


================================================
FILE: django_dynamic_fixture/fixture_algorithms/tests/test_default_fixture_postgres.py
================================================
from datetime import datetime

from django.db import models
from django.test import TestCase

from django_dynamic_fixture.fixture_algorithms.default_fixture import PostgresFixtureMixin
from django_dynamic_fixture.fixture_algorithms.sequential_fixture import SequentialDataFixture, StaticSequentialDataFixture
from django_dynamic_fixture.fixture_algorithms.random_fixture import RandomDataFixture
from django_dynamic_fixture.fixture_algorithms.unique_random_fixture import UniqueRandomDataFixture

try:
    import psycopg2
    from django.contrib.postgres.fields import ArrayField

    class PostgresDataFixtureTestMixin:
        def test_arrayfield_integer_config(self):
            data = self.fixture.generate_data(ArrayField(models.IntegerField()))
            assert isinstance(data, list)
            assert isinstance(data[0], int)

        def test_arrayfield_char_config(self):
            data = self.fixture.generate_data(ArrayField(models.CharField()))
            assert isinstance(data, list)
            assert isinstance(data[0], str)

        def test_arrayfield_datetime_config(self):
            data = self.fixture.generate_data(ArrayField(models.DateTimeField()))
            assert isinstance(data, list)
            assert isinstance(data[0], datetime)

        def test_arrayfield_email_config(self):
            data = self.fixture.generate_data(ArrayField(models.EmailField(max_length=100)))
            assert isinstance(data, list)
            assert isinstance(data[0], str)


    class PostgresSequentialDataFixtureTestCase(TestCase, PostgresDataFixtureTestMixin):
        def setUp(self):
            class CustomFixture(SequentialDataFixture, PostgresFixtureMixin):
                pass
            self.fixture = CustomFixture()

    class PostgresStaticSequentialDataFixtureTestCase(TestCase, PostgresDataFixtureTestMixin):
        def setUp(self):
            class CustomFixture(StaticSequentialDataFixture, PostgresFixtureMixin):
                pass
            self.fixture = CustomFixture()

    class PostgresRandomDataFixtureTestCase(TestCase, PostgresDataFixtureTestMixin):
        def setUp(self):
            class CustomFixture(RandomDataFixture, PostgresFixtureMixin):
                pass
            self.fixture = CustomFixture()

    class PostgresUniqueRandomDataFixtureTestCase(TestCase, PostgresDataFixtureTestMixin):
        def setUp(self):
            class CustomFixture(UniqueRandomDataFixture, PostgresFixtureMixin):
                pass
            self.fixture = CustomFixture()

except (ImportError, ModuleNotFoundError):
    print('Skipping Postgres tests because psycopg2 has not been installed.')


================================================
FILE: django_dynamic_fixture/fixture_algorithms/tests/test_random_fixture.py
================================================

from django.test import TestCase

from django_dynamic_fixture.fixture_algorithms.tests.abstract_test_generic_fixture import DataFixtureTestCase
from django_dynamic_fixture.fixture_algorithms.random_fixture import RandomDataFixture


class RandomDataFixtureTestCase(TestCase, DataFixtureTestCase):
    def setUp(self):
        self.fixture = RandomDataFixture()


================================================
FILE: django_dynamic_fixture/fixture_algorithms/tests/test_sequential_fixture.py
================================================
from django.db import models

from django.test import TestCase

from django_dynamic_fixture.fixture_algorithms.tests.abstract_test_generic_fixture import DataFixtureTestCase
from django_dynamic_fixture.fixture_algorithms.sequential_fixture import SequentialDataFixture, StaticSequentialDataFixture


class SequentialDataFixtureTestCase(TestCase, DataFixtureTestCase):
    def setUp(self):
        self.fixture = SequentialDataFixture()

    def test_it_must_fill_integer_fields_sequencially_by_attribute(self):
        assert self.fixture.generate_data(models.IntegerField()) == 1
        field = models.IntegerField()
        field.name = 'x'
        assert self.fixture.generate_data(field) == 1
        assert self.fixture.generate_data(field) == 2

    def test_it_must_fill_string_with_sequences_of_numbers_by_attribute(self):
        assert self.fixture.generate_data(models.CharField(max_length=1)) == '1'
        field = models.CharField(max_length=1)
        field.name = 'x'
        assert self.fixture.generate_data(field) == '1'
        assert self.fixture.generate_data(field) == '2'


class StaticSequentialDataFixtureTestCase(TestCase, DataFixtureTestCase):
    def setUp(self):
        self.fixture = StaticSequentialDataFixture()

    def test_it_must_fill_fields_sequencially_by_attribute_if_field_is_unique(self):
        field = models.IntegerField(unique=True)
        field.name = 'x'
        assert self.fixture.generate_data(field) == 1
        assert self.fixture.generate_data(field) == 2

    def test_it_must_fill_fields_with_static_value_by_attribute_if_field_is_not_unique(self):
        field = models.IntegerField(unique=False)
        field.name = 'x'
        assert self.fixture.generate_data(field) == 1
        assert self.fixture.generate_data(field) == 1



================================================
FILE: django_dynamic_fixture/fixture_algorithms/tests/test_unique_random_fixture.py
================================================
from warnings import catch_warnings

from django.db import models
from django.test import TestCase

from django_dynamic_fixture.fixture_algorithms.tests.abstract_test_generic_fixture import DataFixtureTestCase
from django_dynamic_fixture.fixture_algorithms.unique_random_fixture import \
    UniqueRandomDataFixture


class RandomDataFixtureTestCase(TestCase, DataFixtureTestCase):
    def setUp(self):
        self.fixture = UniqueRandomDataFixture()

    def test_generated_strings_are_unique(self):
        results = set()
        for _ in range(self.fixture.OBJECT_COUNT):
            results.add(
                self.fixture.generate_data(models.CharField(max_length=10))
            )
        assert len(results) == self.fixture.OBJECT_COUNT

    def test_generated_signed_integers_are_unique(self):
        results = set()
        prev = 0
        for _ in range(self.fixture.OBJECT_COUNT):
            integer = self.fixture.generate_data(models.IntegerField())
            results.add(integer)
            assert abs(integer) > abs(prev)
            prev = integer
        assert len(results) == self.fixture.OBJECT_COUNT

    def test_generated_unsigned_integers_are_unique(self):
        results = set()
        prev = 0
        for _ in range(self.fixture.OBJECT_COUNT):
            integer = self.fixture.generate_data(models.PositiveIntegerField())
            results.add(integer)
            assert integer > prev
            prev = integer
        assert len(results) == self.fixture.OBJECT_COUNT

    def test_warning(self):
        with catch_warnings(record=True) as w:
            for _ in range(self.fixture.OBJECT_COUNT + 1):
                self.fixture.generate_data(models.CharField(max_length=10))
            warning = w[-1]
            assert issubclass(warning.category, RuntimeWarning)
            expected_message = (
                self.fixture.WARNING_MESSAGE_TMPL % self.fixture.OBJECT_COUNT
            )
            assert expected_message in str(warning.message)


================================================
FILE: django_dynamic_fixture/fixture_algorithms/unique_random_fixture.py
================================================
from datetime import datetime, date, timedelta
from decimal import Decimal
from itertools import chain
import random
import socket
import string
import struct
from warnings import warn

from django.core.exceptions import ImproperlyConfigured

try:
    from django.utils.timezone import now
except ImportError:
    now = datetime.now

try:
    from django.contrib.gis.geos import *
except ImproperlyConfigured:
    pass  # environment without geo libs
except Exception:
    pass # Avoid errors like GDALException

from django_dynamic_fixture.fixture_algorithms.sequential_fixture import AutoDataFiller
from django_dynamic_fixture.fixture_algorithms.default_fixture import BaseDataFixture, GeoDjangoFixtureMixin, PostgresFixtureMixin


class UniqueRandomDataFixture(BaseDataFixture, GeoDjangoFixtureMixin, PostgresFixtureMixin):
    DEFAULT_LENGTH = 10
    OBJECT_COUNT = 512
    WARNING_MESSAGE_TMPL = (
        'Maximum number of objects (%d) is exceeded in '
        'unique_random_fixture. Uniqueness is not guaranteed.'
    )

    def __init__(self):
        super().__init__()
        self.filler = AutoDataFiller()

    def get_counter(self, field, key):
        result = self.filler.next(key)
        if result > self.OBJECT_COUNT:
            warn(self.WARNING_MESSAGE_TMPL % self.OBJECT_COUNT, RuntimeWarning)
        return result

    def random_string(self, field, key, n=None):
        counter = str(self.get_counter(field, key))
        length = n or self.DEFAULT_LENGTH
        result = counter
        result += ''.join(
            random.choice(string.ascii_letters)
            for _ in range(length - len(counter))
        )
        return result

    def random_integer(self, field, key, signed=True):
        counter = self.get_counter(field, key) - 1
        counter %= self.OBJECT_COUNT
        if not signed:
            MAX_INT = 2 ** 16
            multiplier = MAX_INT // self.OBJECT_COUNT
            return random.randrange(
                multiplier * counter + 1, multiplier * (counter + 1)
            )

        MAX_SIGNED_INT = 2 ** 15
        multiplier = MAX_SIGNED_INT // self.OBJECT_COUNT
        positive_range = range(
            multiplier * counter + 1, multiplier * (counter + 1)
        )
        negative_range = range(
            (-multiplier) * (counter + 1), (-multiplier) * counter
        )
        return random.choice(list(chain(positive_range, negative_range)))

    # NUMBERS
    def integerfield_config(self, field, key):
        return self.random_integer(field, key)

    def smallintegerfield_config(self, field, key):
        return self.random_integer(field, key)

    def bigintegerfield_config(self, field, key):
        return self.random_integer(field, key)

    def positiveintegerfield_config(self, field, key):
        return self.random_integer(field, key, signed=False)

    def positivesmallintegerfield_config(self, field, key):
        return self.random_integer(field, key, signed=False)

    def floatfield_config(self, field, key):
        return float(self.random_integer(field, key)) + random.random()

    def decimalfield_config(self, field, key):
        number_of_digits = field.max_digits - field.decimal_places
        max_value = 10 ** number_of_digits
        value = self.random_integer(field, key) % max_value
        value = float(value) + random.random()
        return Decimal(str(value))

    # STRINGS
    def charfield_config(self, field, key):
        return self.random_string(field, key, field.max_length)

    def textfield_config(self, field, key):
        return self.charfield_config(field, key)

    def slugfield_config(self, field, key):
        return self.charfield_config(field, key)

    def commaseparatedintegerfield_config(self, field, key):
        return self.charfield_config(field, key)

    # BOOLEAN
    def booleanfield_config(self, field, key):
        counter = self.get_counter(field, key)
        if counter == 1:
            return True
        elif counter == 2:
            return False
        return random.choice((True, False))

    def nullbooleanfield_config(self, field, key):
        counter = self.get_counter(field, key)
        if counter == 1:
            return None
        elif counter == 2:
            return True
        elif counter == 3:
            return False
        return random.choice((None, True, False))

    # DATE/TIME RELATED
    def datefield_config(self, field, key):
        integer = self.random_integer(field, key, signed=False)
        return date.today() - timedelta(days=integer)

    def timefield_config(self, field, key):
        integer = self.random_integer(field, key, signed=False)
        return (now() - timedelta(seconds=integer)).time()

    def datetimefield_config(self, field, key):
        integer = self.random_integer(field, key, signed=False)
        return now() - timedelta(seconds=integer)

    # FORMATTED STRINGS
    def emailfield_config(self, field, key):
        return f'a{self.random_string(field, key)}@dynamicfixture.com'

    def urlfield_config(self, field, key):
        return f'http://dynamicfixture{self.random_string(field, key)}.com'

    # Deprecated in Django >= 1.7
    def ipaddressfield_config(self, field, key):
        MAX_IP = 2 ** 32 - 1

        integer = self.random_integer(field, key, signed=False)
        integer %= MAX_IP
        return str(socket.inet_ntoa(struct.pack('!L', integer)))

    def xmlfield_config(self, field, key):
        return f'<a>{self.random_string(field, key)}</a>'

    # FILES
    def filepathfield_config(self, field, key):
        return self.random_string(field, key)

    def filefield_config(self, field, key):
        return self.random_string(field, key)

    def imagefield_config(self, field, key):
        return self.random_string(field, key)


================================================
FILE: django_dynamic_fixture/global_settings.py
================================================

"""
Module that contains wrappers and shortcuts.
This is the facade of all features of DDF.
"""
import os
import sys
import warnings

from django.conf import settings
from django.urls import get_mod_func
try:
    from importlib import import_module
except ImportError:
    from django.utils.importlib import import_module

from django_dynamic_fixture.fixture_algorithms.sequential_fixture import SequentialDataFixture, StaticSequentialDataFixture, GlobalSequentialDataFixture
from django_dynamic_fixture.fixture_algorithms.random_fixture import RandomDataFixture


class DDFImproperlyConfigured(Exception):
    "DDF is improperly configured. Some global settings has bad value in django settings."


def get_ddf_config(name, default, cast=None, options=None, msg=''):
    try:
        value = os.getenv(name) # Priority for Env variables
        if not value:
            value = getattr(settings, name) if hasattr(settings, name) else default
        value = cast(value) if cast else value
        if options and value not in options:
            # to educate users to use the property correctly.
            raise DDFImproperlyConfigured()
        return value
    except Exception as e:
        raise DDFImproperlyConfigured(f'{name}="{value}": {msg} ({e})')


def get_boolean_config(config_name, default=False):
    return get_ddf_config(config_name, default, options=[True, False], msg='it must be True or False')


def get_data_fixture(default='sequential'):
    # It must be 'sequential', 'static_sequential', 'global_sequential', 'random' or 'path.to.CustomDataFixtureClass'
    try:
        INTERNAL_DATA_FIXTURES = {'sequential': SequentialDataFixture(),
                                  'static_sequential': StaticSequentialDataFixture(),
                                  'global_sequential': GlobalSequentialDataFixture(),
                                  'random': RandomDataFixture()}
        if hasattr(settings, 'DDF_DEFAULT_DATA_FIXTURE'):
            if settings.DDF_DEFAULT_DATA_FIXTURE in INTERNAL_DATA_FIXTURES.keys():
                return INTERNAL_DATA_FIXTURES[settings.DDF_DEFAULT_DATA_FIXTURE]
            else:
                # path.to.CustomDataFixtureClass
                mod_name, obj_name = get_mod_func(settings.DDF_DEFAULT_DATA_FIXTURE)
                module = import_module(mod_name)
                custom_data_fixture = getattr(module, obj_name)
                return custom_data_fixture()
        else:
            return INTERNAL_DATA_FIXTURES[default]
    except:
        raise DDFImproperlyConfigured(
            f"DDF_DEFAULT_DATA_FIXTURE ({settings.DDF_DEFAULT_DATA_FIXTURE}) must be "
            "'sequential', 'static_sequential', 'global_sequential', 'random' or 'path.to.CustomDataFixtureClass'."
        )


DDF_DEFAULT_DATA_FIXTURE = get_data_fixture(default='sequential')
DDF_IGNORE_FIELDS = get_ddf_config('DDF_IGNORE_FIELDS', default=[], cast=list, msg='it must be a list of strings')
DDF_FK_MIN_DEPTH = get_ddf_config('DDF_FK_MIN_DEPTH', default=0, cast=int, msg='it must be a integer number')
if hasattr(settings, 'DDF_NUMBER_OF_LAPS'):
    warnings.warn(
        "The old DDF_NUMBER_OF_LAPS settings was replaced by the new DDF_FK_MIN_DEPTH.",
        DeprecationWarning
    )
DDF_FIELD_FIXTURES = get_ddf_config('DDF_FIELD_FIXTURES', default={}, cast=dict, msg='it must be a dict')
DDF_DEFAULT_DATA_FIXTURE.plugins = DDF_FIELD_FIXTURES
DDF_FILL_NULLABLE_FIELDS = get_boolean_config('DDF_FILL_NULLABLE_FIELDS', default=False)
DDF_VALIDATE_MODELS = get_boolean_config('DDF_VALIDATE_MODELS', default=False)
DDF_DEBUG_MODE = get_boolean_config('DDF_DEBUG_MODE', default=False)


================================================
FILE: django_dynamic_fixture/models.py
================================================
from django.conf import settings

import_models = getattr(settings, 'IMPORT_DDF_MODELS', False)

if import_models:
    from django_dynamic_fixture.models_test import *


================================================
FILE: django_dynamic_fixture/models_sample_app.py
================================================
from django.db import models


class Publisher(models.Model):
    name = models.CharField(max_length=100, unique=True)

class Author(models.Model):
    name = models.CharField(max_length=100)
    description = models.TextField(null=True)

class Category(models.Model):
    name = models.CharField(max_length=100, unique=True)
    parent = models.ForeignKey('self', on_delete=models.DO_NOTHING, null=True, blank=True)

class Book(models.Model):
    isb = models.CharField(max_length=100, unique=True)
    name = models.CharField(max_length=100)
    main_author = models.ForeignKey(Author, related_name='books', on_delete=models.DO_NOTHING)
    authors = models.ManyToManyField('Author', related_name='m2m')
    categories = models.ManyToManyField('Category', related_name='m2m')
    from .fields import JSONField
    metadata = JSONField(null=True)

class BookPublisher(models.Model):
    book_edition = models.ForeignKey('BookEdition', on_delete=models.DO_NOTHING)
    publisher = models.ForeignKey('Publisher', on_delete=models.DO_NOTHING)
    comments = models.TextField(max_length=100)

class BookEdition(models.Model):
    book = models.ForeignKey(Book, related_name='editions', on_delete=models.DO_NOTHING)
    publishers = models.ManyToManyField('Publisher', related_name='edition_publishers', through=BookPublisher)
    year = models.IntegerField()


================================================
FILE: django_dynamic_fixture/models_test.py
================================================
#!/usr/bin/env python

# https://docs.djangoproject.com/en/3.0/ref/models/fields
import django
from django.conf import settings
from django.db import models
from django.core.exceptions import ValidationError
from django.core.validators import RegexValidator

from django_dynamic_fixture.models_sample_app import *
from django_dynamic_fixture.models_third_party import *


class EmptyModel(models.Model):
    class Meta:
        app_label = 'django_dynamic_fixture'


class ModelWithNumbers(models.Model):
    #id is a models.AutoField()
    integer = models.IntegerField(unique=True)
    smallinteger = models.SmallIntegerField(unique=True)
    positiveinteger = models.PositiveIntegerField(unique=True)
    positivesmallinteger = models.PositiveSmallIntegerField(unique=True)
    biginteger = models.BigIntegerField(unique=True)
    float = models.FloatField(unique=True)
    decimal = models.DecimalField(max_digits=2, decimal_places=1, unique=False)

    class Meta:
        verbose_name = 'Numbers'
        app_label = 'django_dynamic_fixture'


class ModelWithStrings(models.Model):
    char = models.CharField(max_length=1, unique=True)
    string = models.CharField(max_length=50, unique=True)
    text = models.TextField(unique=True)
    slug = models.SlugField(unique=True)
    commaseparated = models.CommaSeparatedIntegerField(max_length=100, unique=True)

    class Meta:
        verbose_name = 'Strings'
        app_label = 'django_dynamic_fixture'


class ModelWithBooleans(models.Model):
    # https://docs.djangoproject.com/en/1.6/ref/models/fields/#booleanfield
    # Django 1.6 changed the default value of BooleanField from False to None
    boolean = models.BooleanField(default=False)
    nullboolean = models.NullBooleanField()

    class Meta:
        verbose_name = 'Booleans'
        app_label = 'django_dynamic_fixture'


class ModelWithDateTimes(models.Model):
    date = models.DateField(unique=True)
    datetime = models.DateTimeField(unique=True)
    time = models.TimeField(unique=True)

    class Meta:
        verbose_name = 'DateTimes'
        app_label = 'django_dynamic_fixture'


class ModelWithBinary(models.Model):
    binary = models.BinaryField()
    class Meta:
        app_label = 'django_dynamic_fixture'


class ModelWithFieldsWithCustomValidation(models.Model):
    email = models.EmailField(unique=True)
    url = models.URLField(unique=True)
    ip = models.IPAddressField(unique=False)
    ipv6 = models.GenericIPAddressField(unique=False)

    class Meta:
        verbose_name = 'Custom validation'
        app_label = 'django_dynamic_fixture'

class ModelWithFileFields(models.Model):
    filepath = models.FilePathField(unique=True, blank=True)
    file = models.FileField(upload_to='.')

    try:
        import pil
        # just test it if the PIL package is installed
        image = models.ImageField(upload_to='.')
    except ImportError:
        pass

    class Meta:
        verbose_name = 'File fields'
        app_label = 'django_dynamic_fixture'


class ModelWithDefaultValues(models.Model):
    integer_with_default = models.IntegerField(default=3)
    string_with_choices = models.CharField(max_length=5, choices=(('a', 'A'), ('b', 'B')))
    string_with_choices_and_default = models.CharField(max_length=5, default='b', choices=(('a', 'A'), ('b', 'B')))
    string_with_optgroup_choices = models.CharField(max_length=5, choices=(('group1', (('a', 'A'), ('b', 'B'))), ('group2', (('c', 'C'), ('d', 'D')))))
    foreign_key_with_default = models.ForeignKey(EmptyModel, null=True, default=None, on_delete=models.DO_NOTHING)

    class Meta:
        verbose_name = 'Default values'
        app_label = 'django_dynamic_fixture'


class ModelForNullable(models.Model):
    nullable = models.IntegerField(null=True)
    not_nullable = models.IntegerField(null=False)

    class Meta:
        verbose_name = 'Nullable'
        app_label = 'django_dynamic_fixture'


class ModelForIgnoreList2(models.Model):
    nullable = models.IntegerField(null=True)
    non_nullable = models.IntegerField()

    class Meta:
        verbose_name = 'Ignore list 2'
        app_label = 'django_dynamic_fixture'


class ModelForIgnoreList(models.Model):
    required = models.IntegerField(null=False)
    required_with_default = models.IntegerField(null=False, default=1)
    not_required = models.IntegerField(null=True)
    not_required_with_default = models.IntegerField(default=1)
    self_reference = models.ForeignKey('ModelForIgnoreList', on_delete=models.DO_NOTHING, null=True)
    different_reference = models.ForeignKey(ModelForIgnoreList2, on_delete=models.DO_NOTHING)

    class Meta:
        verbose_name = 'Ignore list'
        app_label = 'django_dynamic_fixture'


class ModelRelated(models.Model):
    selfforeignkey = models.ForeignKey('self', on_delete=models.DO_NOTHING, null=True, blank=True)
    integer = models.IntegerField(null=True)
    integer_b = models.IntegerField(null=True)

    class Meta:
        verbose_name = 'Related'
        app_label = 'django_dynamic_fixture'


class ModelRelatedThrough(models.Model):
    related = models.ForeignKey('ModelRelated', on_delete=models.DO_NOTHING)
    relationship = models.ForeignKey('ModelWithRelationships', on_delete=models.DO_NOTHING)

    class Meta:
        app_label = 'django_dynamic_fixture'

def default_fk_value():
    try:
        return ModelRelated.objects.get(id=1)
    except ModelRelated.DoesNotExist:
        ModelRelated.objects.create()
        return ModelRelated.objects.all()[0]


def default_fk_id():
    return default_fk_value().pk


class ModelWithRelationships(models.Model):
    # relationship
    selfforeignkey = models.ForeignKey('self', on_delete=models.DO_NOTHING, null=True, blank=True)
    foreignkey = models.ForeignKey('ModelRelated', related_name='fk', on_delete=models.DO_NOTHING)
    onetoone = models.OneToOneField('ModelRelated', related_name='o2o', on_delete=models.DO_NOTHING)
    manytomany = models.ManyToManyField('ModelRelated', related_name='m2m')
    manytomany_through = models.ManyToManyField('ModelRelated', related_name='m2m_through', through=ModelRelatedThrough)

    foreignkey_with_default = models.ForeignKey('ModelRelated', related_name='fk2', default=default_fk_value, on_delete=models.DO_NOTHING)
    foreignkey_with_id_default = models.ForeignKey('ModelRelated', related_name='fk3', default=default_fk_id, on_delete=models.DO_NOTHING)

    integer = models.IntegerField(null=True)
    integer_b = models.IntegerField(null=True)
    # generic field
    # TODO

    class Meta:
        verbose_name = 'Relationships'
        app_label = 'django_dynamic_fixture'


class ModelWithCyclicDependency(models.Model):
    model_b = models.ForeignKey('ModelWithCyclicDependency2', on_delete=models.DO_NOTHING, null=True)

    class Meta:
        verbose_name = 'Cyclic dependency'
        app_label = 'django_dynamic_fixture'


class ModelWithCyclicDependency2(models.Model):
    model_a = models.ForeignKey(ModelWithCyclicDependency, on_delete=models.DO_NOTHING, null=True)

    class Meta:
        verbose_name = 'Cyclic dependency 2'
        app_label = 'django_dynamic_fixture'


class ModelAbstract(models.Model):
    integer = models.IntegerField(unique=True)
    class Meta:
        abstract = True
        verbose_name = 'Abstract'
        app_label = 'django_dynamic_fixture'


class ModelParent(ModelAbstract):
    class Meta:
        verbose_name = 'Parent'
        app_label = 'django_dynamic_fixture'


class ModelChild(ModelParent):
    class Meta:
        verbose_name = 'Child'
        app_label = 'django_dynamic_fixture'


class ModelChildWithCustomParentLink(ModelParent):
    my_custom_ref = models.OneToOneField(ModelParent, parent_link=True, related_name='my_custom_ref_x', on_delete=models.DO_NOTHING)

    class Meta:
        verbose_name = 'Custom child'
        app_label = 'django_dynamic_fixture'


class ModelWithRefToParent(models.Model):
    parent = models.ForeignKey(ModelParent, on_delete=models.DO_NOTHING)

    class Meta:
        verbose_name = 'Child with parent'
        app_label = 'django_dynamic_fixture'


class CustomDjangoField(models.IntegerField):
    pass


class CustomDjangoField2(models.IntegerField):
    pass


class CustomDjangoFieldMixin:
    pass


class CustomDjangoFieldMultipleInheritance(CustomDjangoFieldMixin, models.IntegerField):
    pass


class NewField(models.Field):
    # Avoid OperationalError("table has no column named ...") errors
    def db_type(self, connection):
        return 'char(25)'


class ModelWithCustomFields(models.Model):
    x = CustomDjangoField(null=False)
    y = NewField(null=True)

    class Meta:
        verbose_name = 'Custom fields'
        app_label = 'django_dynamic_fixture'


class ModelWithCustomFieldsMultipleInheritance(models.Model):
    x = CustomDjangoFieldMultipleInheritance(null=False)
    y = NewField(null=True)

    class Meta:
        verbose_name = 'Custom fields with multiple inheritance'
        app_label = 'django_dynamic_fixture'


class ModelWithUnsupportedField(models.Model):
    z = NewField(null=False)

    class Meta:
        verbose_name = 'Unsupported field'
        app_label = 'django_dynamic_fixture'


class ModelWithValidators(models.Model):
    field_validator = models.CharField(max_length=3, validators=[RegexValidator(regex=r'ok')])
    clean_validator = models.CharField(max_length=3)

    class Meta:
        verbose_name = 'Validators'
        app_label = 'django_dynamic_fixture'

    def clean(self):
        if self.clean_validator != 'ok':
            raise ValidationError('ops')


class ModelWithAutoDateTimes(models.Model):
    auto_now_add = models.DateField(auto_now_add=True)
    auto_now = models.DateField(auto_now=True)
    manytomany = models.ManyToManyField('ModelWithAutoDateTimes', related_name='m2m')

    class Meta:
        verbose_name = 'Auto DateTime'
        app_label = 'django_dynamic_fixture'


class ModelForCopy2(models.Model):
    int_e = models.IntegerField()

    class Meta:
        verbose_name = 'Copy 2'
        app_label = 'django_dynamic_fixture'


class ModelForCopy(models.Model):
    int_a = models.IntegerField()
    int_b = models.IntegerField(null=None)
    int_c = models.IntegerField()
    int_d = models.IntegerField()
    e = models.ForeignKey(ModelForCopy2, on_delete=models.DO_NOTHING)

    class Meta:
        verbose_name = 'Copy'
        app_label = 'django_dynamic_fixture'


class ModelForLibrary2(models.Model):
    integer = models.IntegerField(null=True)
    integer_unique = models.IntegerField(unique=True)

    class Meta:
        verbose_name = 'Library 2'
        app_label = 'django_dynamic_fixture'


class ModelForLibrary(models.Model):
    integer = models.IntegerField(null=True)
    integer_unique = models.IntegerField(unique=True)
    selfforeignkey = models.ForeignKey('self', on_delete=models.DO_NOTHING, null=True, blank=True)
    foreignkey = models.ForeignKey('ModelForLibrary2', related_name='fk', on_delete=models.DO_NOTHING)

    class Meta:
        verbose_name = 'Library'
        app_label = 'django_dynamic_fixture'


class ProxyModelForLibrary(ModelForLibrary):
    class Meta:
        proxy = True
        verbose_name = 'Proxy Library'
        app_label = 'django_dynamic_fixture'


class ModelWithUniqueCharField(models.Model):
    text_unique = models.CharField(max_length=20, unique=True)

    class Meta:
        verbose_name = 'Unique char field'
        app_label = 'django_dynamic_fixture'


class ModelWithClean(models.Model):
    integer = models.IntegerField()

    class Meta:
        verbose_name = 'Clean'
        app_label = 'django_dynamic_fixture'

    def clean(self):
        if self.integer != 9999: # just for testing
            raise ValidationError('integer is not 9999')


class ModelForSignals(models.Model):
    class Meta:
        verbose_name = 'Signals'
        app_label = 'django_dynamic_fixture'


class ModelForSignals2(models.Model):
    class Meta:
        verbose_name = 'Signals 2'
        app_label = 'django_dynamic_fixture'


class ModelForFieldPlugins(models.Model):
    # aaa = CustomDjangoField(null=False) # defined in settings.py
    # bbb = models.IntegerField(null=False)
    custom_field_custom_fixture = CustomDjangoField(null=False) # defined in settings.py
    custom_field_custom_fixture2 = CustomDjangoField2(null=False) # defined in settings.py
    class Meta:
        app_label = 'django_dynamic_fixture'

class ModelWithCommonNames(models.Model):
    instance = models.IntegerField(null=False)
    field = models.IntegerField(null=False)
    class Meta:
        app_label = 'django_dynamic_fixture'


class ModelWithNamedPrimaryKey(models.Model):
    named_pk = models.AutoField(primary_key=True)

if (hasattr(settings, 'DDF_TEST_GEODJANGO') and settings.DDF_TEST_GEODJANGO):
    from django.contrib.gis.db import models as geomodels
    class ModelForGeoDjango(geomodels.Model):
        geometry = geomodels.GeometryField()
        point = geomodels.PointField()
        line_string = geomodels.LineStringField()
        polygon = geomodels.PolygonField()
        multi_point = geomodels.MultiPointField()
        multi_line_string = geomodels.MultiLineStringField()
        multi_polygon = geomodels.MultiPolygonField()
        geometry_collection = geomodels.GeometryCollectionField()
        class Meta:
            app_label = 'django_dynamic_fixture'


class ModelForUUID(models.Model):
    uuid = models.UUIDField()
    class Meta:
        app_label = 'django_dynamic_fixture'



================================================
FILE: django_dynamic_fixture/models_third_party.py
================================================
from django.db import models


try:
    from django.contrib.postgres.fields import JSONField
    class ModelForPostgresFields(models.Model):
        nullable_json_field = JSONField(null=True)
        json_field = JSONField(null=False)
        class Meta:
            app_label = 'django_dynamic_fixture'
except ImportError:
    pass

try:
    from jsonfield import JSONField
    from jsonfield import JSONCharField
    class ModelForPlugins1(models.Model):
        json_field1 = JSONCharField(max_length=10)
        json_field2 = JSONField()
        class Meta:
            app_label = 'django_dynamic_fixture'
except ImportError:
    print('Library `jsonfield` not installed. Skipping.')


try:
    from json_field import JSONField as JSONField2
    class ModelForPlugins2(models.Model):
        json_field1 = JSONField2()
        class Meta:
            app_label = 'django_dynamic_fixture'
except ImportError:
    print('Library `django-json-field` not installed. Skipping.')


try:
    from polymorphic.models import PolymorphicModel
    class ModelPolymorphic(PolymorphicModel):
        class Meta:
            verbose_name = 'Polymorphic Model'


    class ModelPolymorphic2(ModelPolymorphic):
        class Meta:
            verbose_name = 'Polymorphic Model 2'


    class ModelPolymorphic3(ModelPolymorphic):
        class CannotSave(Exception):
            pass

        def save(self):
            raise self.CannotSave
except ImportError:
    print('Library `django_polymorphic` not installed. Skipping.')


================================================
FILE: django_dynamic_fixture/script_ddf_checkings.py
================================================
import csv

from django.db import transaction

from django_dynamic_fixture.django_helper import get_apps, get_models_of_an_app


def color(color, string):
    return '\033[1;{}m{}\033[0m'.format(color, string)

def white(string):
    return color('37', string)

def red(string):
    return color('91', string)

def green(string):
    return color('92', string)

def yellow(string):
    return color('93', string)


def ddf_check_models(application_labels=[], exclude_application_labels=[], print_csv=False, csv_filename=None):
    from django_dynamic_fixture import get

    succeeded = {}
    errors = {}
    for app_label in get_apps(application_labels, exclude_application_labels):
        models = get_models_of_an_app(app_label)
        for model_class in models:
            ref = '{}.{}'.format(app_label, model_class.__name__)
            try:
                with transaction.atomic():
                    get(model_class)
                succeeded[ref] = None
            except Exception as e:
                errors[ref] = '[{}] {}'.format(type(e), str(e))

    console_report(succeeded, errors)
    if print_csv or csv_filename:
        content = csv_report(succeeded, errors)
        if print_csv:
            print(yellow('\nCSV Report.\n'))
            print(content)
        if csv_filename:
            print(yellow('\nCSV Report file created: {}.\n'.format(csv_filename)))
            save_csv(content, filename=csv_filename)
    return succeeded, errors


def console_report(succeeded, errors):
    print(green('\nModels that DDF can create using the default settings.\n'))
    for i, (ref, _) in enumerate(succeeded.items(), start=1):
        i = str(i).zfill(3)
        print(white('{}. {}: '.format(i, ref)) + green('succeeded'))

    print(red('\nModels that requires some customisation.\n'))
    for i, (ref, error) in enumerate(errors.items(), start=1):
        i = str(i).zfill(3)
        print(white('{}. {}: '.format(i, ref)) + red(error))


def csv_report(succeeded, errors):
    SEP = '\t'
    LN = '\n'
    lines = []
    lines.append(SEP.join(['#', 'Model', 'Succeeded']))
    for i, (ref, _) in enumerate(succeeded.items(), start=1):
        lines.append(SEP.join([str(i), ref, 'succeeded']))

    lines.append(SEP.join(['#', 'Model', 'Error']))
    for i, (ref, error) in enumerate(errors.items(), start=1):
        lines.append(SEP.join([str(i), ref, error]))
    return LN.join(lines)


def save_csv(content, filename):
    with open(filename, 'w') as f:
        f.write(content)


================================================
FILE: django_dynamic_fixture/tests/__init__.py
================================================



================================================
FILE: django_dynamic_fixture/tests/conftest.py
================================================
# PyTest file for global set up.

# Django initialisation
import django
django.setup()

# Give DB access to PyTests
import pytest
pytest.mark.django_db

# MonkeyPatch Django-Test teardown
from django.test import utils
original_teardown_test_environment = utils.teardown_test_environment
def fixed_teardown_test_environment():
    try:
        original_teardown_test_environment()
    except TypeError:
        # Ignore some Django or PyTest-Django bug
        pass
utils.teardown_test_environment = fixed_teardown_test_environment

print(':: PyTest conftest.py loaded.')


================================================
FILE: django_dynamic_fixture/tests/test_ddf.py
================================================
from datetime import datetime, date
from decimal import Decimal
import uuid

from django.test import TestCase
import pytest

from django_dynamic_fixture.models_test import *
from django_dynamic_fixture.ddf import *
from django_dynamic_fixture.fixture_algorithms.sequential_fixture import SequentialDataFixture


data_fixture = SequentialDataFixture()


class DDFTestCase(TestCase):
    def setUp(self):
        self.ddf = DynamicFixture(data_fixture)


class NewCreateAModelInstanceTest(DDFTestCase):
    def test_new_create_a_non_saved_instance_of_the_model(self):
        instance = self.ddf.new(EmptyModel)
        assert isinstance(instance, EmptyModel)
        assert instance.id is None


class GetDealWithPrimaryKeyTest(DDFTestCase):
    def test_get_use_database_id_by_default(self):
        instance = self.ddf.get(EmptyModel)
        assert instance.id is not None
        assert instance.pk is not None

    def test_get_use_given_id(self):
        instance = self.ddf.new(EmptyModel, id=99998)
        assert instance.id == 99998
        assert instance.pk == 99998

    def test_get_use_given_named_id(self):
        instance = self.ddf.get(ModelWithNamedPrimaryKey, named_pk=99998)
        assert instance.named_pk == 99998
        assert instance.pk == 99998


class NewFullFillAttributesWithAutoDataTest(DDFTestCase):
    def test_new_fill_number_fields_with_numbers(self):
        instance = self.ddf.new(ModelWithNumbers)
        assert isinstance(instance.integer, int)
        assert isinstance(instance.smallinteger, int)
        assert isinstance(instance.positiveinteger, int)
        assert isinstance(instance.positivesmallinteger, int)
        assert isinstance(instance.biginteger, int)
        assert isinstance(instance.float, float)

    def test_new_fill_string_fields_with_text_type_strings(self):
        instance = self.ddf.new(ModelWithStrings)
        assert isinstance(instance.string, str)
        assert isinstance(instance.text, str)
        assert isinstance(instance.slug, str)
        assert isinstance(instance.commaseparated, str)

    def test_new_fill_boolean_fields_with_False_and_None(self):
        instance = self.ddf.new(ModelWithBooleans)
        assert instance.boolean is False
        assert instance.nullboolean is None

    def test_new_fill_time_related_fields_with_current_values(self):
        instance = self.ddf.new(ModelWithDateTimes)
        assert date.today() >= instance.date
        assert datetime.now().time() >= instance.time
        assert datetime.now() >= instance.datetime

    def test_new_fill_formatted_strings_fields_with_basic_values(self):
        instance = self.ddf.new(ModelWithFieldsWithCustomValidation)
        assert isinstance(instance.email, str)
        assert isinstance(instance.url, str)
        assert isinstance(instance.ip, str)
        assert isinstance(instance.ipv6, str)

    def test_new_fill_file_fields_with_basic_strings(self):
        instance = self.ddf.new(ModelWithFileFields)
        assert isinstance(instance.filepath, str)
        assert isinstance(instance.file.path, str)
        try:
            import pil
            # just test it if the PIL package is installed
            assert isinstance(instance.image, str)
        except ImportError:
            pass

    def test_new_fill_binary_fields_with_basic_data(self):
        value = b'\x00\x46\xFE'
        instance = self.ddf.new(ModelWithBinary, binary=value)
        assert bytes(instance.binary) == bytes(value)

        instance = self.ddf.get(ModelWithBinary)
        assert isinstance(instance.binary, bytes), type(instance.binary)


class NewFullFillAttributesWithDefaultDataTest(DDFTestCase):
    def test_fill_field_with_default_data(self):
        instance = self.ddf.new(ModelWithDefaultValues)
        assert instance.integer_with_default == 3

    def test_fill_field_with_possible_choices(self):
        instance = self.ddf.new(ModelWithDefaultValues)
        assert instance.string_with_choices == 'a'

    def test_fill_field_with_default_value_even_if_field_is_foreign_key(self):
        instance = self.ddf.new(ModelWithDefaultValues)
        assert instance.foreign_key_with_default is None

    def test_fill_field_with_default_data_and_choices_must_consider_default_data_instead_choices(self):
        instance = self.ddf.new(ModelWithDefaultValues)
        assert instance.string_with_choices_and_default == 'b'

    def test_fill_field_with_possible_optgroup_choices(self):
        instance = self.ddf.new(ModelWithDefaultValues)
        assert instance.string_with_optgroup_choices == 'a'


class NewFullFillAttributesWithCustomDataTest(DDFTestCase):
    def test_fields_are_filled_with_custom_attributes(self):
        assert self.ddf.new(ModelWithNumbers, integer=9).integer == 9
        assert self.ddf.new(ModelWithStrings, string='7').string == '7'
        assert self.ddf.new(ModelWithBooleans, boolean=True).boolean

    def test_decimal_can_be_filled_by_an_string(self):
        self.ddf.get(ModelWithNumbers, decimal='9.5')
        assert ModelWithNumbers.objects.latest('id').decimal == Decimal('9.5')

    def test_fields_can_be_filled_by_functions(self):
        instance = self.ddf.new(ModelWithStrings, string=lambda field: field.name)
        assert instance.string == 'string'

    def test_invalid_configuration_raise_an_error(self):
        with pytest.raises(InvalidConfigurationError):
            self.ddf.new(ModelWithNumbers, integer=lambda x: ''.invalidmethod())

    def test_bad_data_raise_an_error(self):
        self.ddf.get(ModelWithNumbers, integer=50000)
        with pytest.raises(BadDataError):
            self.ddf.get(ModelWithNumbers, integer=50000)


class NewIgnoringNullableFieldsTest(DDFTestCase):
    def test_new_do_not_fill_nullable_fields_if_we_do_not_want_to(self):
        self.ddf = DynamicFixture(data_fixture, fill_nullable_fields=False)
        instance = self.ddf.new(ModelForNullable)
        assert instance.not_nullable is not None
        assert instance.nullable is None


class NewIgnoreFieldsInIgnoreListTest(DDFTestCase):
    def test_new_do_not_fill_ignored_fields(self):
        self.ddf = DynamicFixture(data_fixture, ignore_fields=['not_required', 'not_required_with_default'])
        instance = self.ddf.new(ModelForIgnoreList)
        assert instance.not_required is None
        assert instance.not_required_with_default is not None
        # not ignored fields
        assert instance.required is not None
        assert instance.required_with_default is not None

    def test_get_raise_an_error_if_a_required_field_is_in_ignore_list(self):
        self.ddf = DynamicFixture(data_fixture, ignore_fields=['required', 'required_with_default'])
        with pytest.raises(BadDataError):
            self.ddf.get(ModelForIgnoreList)

    def test_ignore_fields_are_propagated_to_self_references(self):
        self.ddf = DynamicFixture(data_fixture, ignore_fields=['not_required'], fk_min_depth=1, not_required=10)
        instance = self.ddf.new(ModelForIgnoreList)
        assert instance.not_required == 10
        assert instance.self_reference is not None
        assert instance.self_reference.not_required is None

    def test_ignore_fields_are_not_propagated_to_different_references(self):
        self.ddf = DynamicFixture(data_fixture, ignore_fields=['non_nullable'], different_reference=DynamicFixture(data_fixture))
        instance = self.ddf.new(ModelForIgnoreList)
        assert instance.different_reference is not None
        assert instance.different_reference.non_nullable is not None

    def test_ignore_fields_are_not_ignored_if_explicitely_given(self):
        self.ddf = DynamicFixture(data_fixture, not_required=3, ignore_fields=['not_required', 'nullable'])
        instance = self.ddf.new(ModelForIgnoreList)
        assert instance.not_required == 3


class NewAlsoCreatesRelatedObjectsTest(DDFTestCase):
    def test_new_fill_foreignkey_fields(self):
        instance = self.ddf.new(ModelWithRelationships)
        assert isinstance(instance.foreignkey, ModelRelated)

    def test_new_fill_onetoone_fields(self):
        instance = self.ddf.new(ModelWithRelationships)
        assert isinstance(instance.onetoone, ModelRelated)

    def test_new_deal_with_default_values(self):
        instance = self.ddf.new(ModelWithRelationships)
        assert isinstance(instance.foreignkey_with_default, ModelRelated), str(type(instance.foreignkey_with_default))

    def test_new_deal_with_id_default_values(self):
        instance = self.ddf.new(ModelWithRelationships)
        assert isinstance(instance.foreignkey_with_id_default, ModelRelated), str(type(instance.foreignkey_with_default))

#        TODO
#    def test_new_fill_genericrelations_fields(self):
#        instance = self.ddf.new(ModelWithRelationships)
#        assert isinstance(instance.foreignkey, ModelRelated)


class NewCanCreatesCustomizedRelatedObjectsTest(DDFTestCase):
    def test_customizing_nullable_fields_for_related_objects(self):
        instance = self.ddf.new(ModelWithRelationships, selfforeignkey=DynamicFixture(data_fixture, fill_nullable_fields=True))
        assert instance.integer is None
        assert isinstance(instance.selfforeignkey.integer, int)


class NewDealWithSelfReferencesTest(DDFTestCase):
    def test_new_create_by_default_no_self_fks(self):
        instance = self.ddf.new(ModelWithRelationships, fill_nullable_fields=False)
        assert instance.selfforeignkey is None # no cycle
        instance = self.ddf.new(ModelWithRelationships, fill_nullable_fields=True)
        assert instance.selfforeignkey is None # no cycle

    def test_new_create_only_1_lap_in_cycle(self):
        self.ddf = DynamicFixture(data_fixture, fk_min_depth=1)
        instance = self.ddf.new(ModelWithRelationships)
        assert instance.selfforeignkey is not None # 1 cycle
        assert instance.selfforeignkey.selfforeignkey is None # 2 cycles

    def test_new_create_with_min_depth_2(self):
        self.ddf = DynamicFixture(data_fixture, fk_min_depth=2)
        instance = self.ddf.new(ModelWithRelationships)
        assert instance.selfforeignkey is not None # 1 cycle
        assert instance.selfforeignkey.selfforeignkey is not None # 2 cycles
        assert instance.selfforeignkey.selfforeignkey.selfforeignkey is None # 3 cycles

    def test_number_of_fk_cycles_does_not_break_default_non_null_fk(self):
        self.ddf = DynamicFixture(data_fixture, fk_min_depth=0)
        instance = self.ddf.new(ModelWithRefToParent)
        assert instance.parent is not None


class GetFullFilledModelInstanceAndPersistTest(DDFTestCase):
    def test_get_create_and_save_a_full_filled_instance_of_the_model(self):
        instance = self.ddf.get(ModelWithRelationships)
        assert isinstance(instance, ModelWithRelationships)
        assert instance.id is not None
        # checking unique problems
        another_instance = self.ddf.get(ModelWithRelationships)
        assert isinstance(another_instance, ModelWithRelationships)
        assert another_instance.id is not None

    def test_get_create_and_save_related_fields(self):
        instance = self.ddf.get(ModelWithRelationships)
        assert instance.selfforeignkey is None
        assert instance.foreignkey is not None
        assert instance.onetoone is not None
        self.ddf = DynamicFixture(data_fixture, fk_min_depth=1)
        instance = self.ddf.get(ModelWithRelationships)
        assert instance.selfforeignkey is not None


class ManyToManyRelationshipTest(DDFTestCase):
    def test_new_ignore_many_to_many_configuratios(self):
        instance = self.ddf.new(ModelWithRelationships, manytomany=3)
        instance.save()
        assert instance.manytomany.all().count() == 0

    def test_get_ignore_many_to_many_configuratios(self):
        instance = self.ddf.get(ModelWithRelationships, manytomany=3)
        assert instance.manytomany.all().count() == 3

    def test_many_to_many_configuratios_accept_list_of_dynamic_filters(self):
        instance = self.ddf.get(ModelWithRelationships, manytomany=[DynamicFixture(data_fixture, integer=1000), DynamicFixture(data_fixture, integer=1001)])
        assert instance.manytomany.all().count() == 2
        assert instance.manytomany.all()[0].integer == 1000
        assert instance.manytomany.all()[1].integer == 1001

    def test_many_to_many_configuratios_accept_list_of_instances(self):
        b1 = self.ddf.get(ModelRelated, integer=1000)
        b2 = self.ddf.get(ModelRelated, integer=1001)
        instance = self.ddf.get(ModelWithRelationships, manytomany=[b1, b2])
        assert instance.manytomany.all().count() == 2
        objs = instance.manytomany.all().order_by('integer')
        assert objs[0].integer == 1000
        assert objs[1].integer == 1001

    def test_invalid_many_to_many_configuration(self):
        with pytest.raises(InvalidManyToManyConfigurationError):
            self.ddf.get(ModelWithRelationships, manytomany='a')

    def test_many_to_many_through(self):
        b1 = self.ddf.get(ModelRelated, integer=1000)
        b2 = self.ddf.get(ModelRelated, integer=1001)
        instance = self.ddf.get(ModelWithRelationships, manytomany_through=[b1, b2])
        objs = instance.manytomany_through.all().order_by('integer')
        assert objs.count() == 2
        assert objs[0].integer == 1000
        assert objs[1].integer == 1001


class NewDealWithCyclicDependenciesTest(DDFTestCase):
    def test_new_create_by_default_no_cycles(self):
        a = self.ddf.new(ModelWithCyclicDependency)
        assert a.model_b is None

    def test_new_create_only_1_lap_in_fk_cycle(self):
        self.ddf = DynamicFixture(data_fixture, fk_min_depth=1)
        a = self.ddf.get(ModelWithCyclicDependency)
        assert a.model_b.model_a is None

    def test_new_create_with_min_depth_2(self):
        self.ddf = DynamicFixture(data_fixture, fk_min_depth=2)
        a = self.ddf.get(ModelWithCyclicDependency)
        assert a.model_b.model_a.model_b is None


class NewDealWithInheritanceTest(DDFTestCase):
    def test_get_must_raise_an_error_if_model_is_abstract(self):
        with pytest.raises(InvalidModelError):
            self.ddf.get(ModelAbstract)

    def test_get_must_fill_parent_fields_too(self):
        instance = self.ddf.get(ModelParent)
        assert isinstance(instance.integer, int)
        assert ModelParent.objects.count() == 1

    def test_get_must_fill_grandparent_fields_too(self):
        instance = self.ddf.get(ModelChild)
        assert isinstance(instance.integer, int)
        assert ModelParent.objects.count() == 1
        assert ModelChild.objects.count() == 1

    def test_get_must_ignore_parent_link_attributes_but_the_parent_object_must_be_created(self):
        instance = self.ddf.get(ModelChildWithCustomParentLink)
        assert isinstance(instance.integer, int)
        assert ModelParent.objects.count() == 1
        assert ModelChildWithCustomParentLink.objects.count() == 1
        assert instance.my_custom_ref.id is not None
        assert instance.my_custom_ref.my_custom_ref_x.id is not None

    # TODO: need to check these tests. Here we are trying to simulate a bug with parent_link attribute
    def test_get_0(self):
        instance = self.ddf.get(ModelWithRefToParent)
        assert ModelWithRefToParent.objects.count() == 1
        assert ModelParent.objects.count() == 1
        assert isinstance(instance.parent, ModelParent)

    def test_get_1(self):
        instance = self.ddf.get(ModelWithRefToParent, parent=self.ddf.get(ModelChild))
        assert ModelWithRefToParent.objects.count() == 1
        assert ModelParent.objects.count() == 1
        assert ModelChild.objects.count() == 1
        assert isinstance(instance.parent, ModelChild)

    def test_get_2(self):
        instance = self.ddf.get(ModelWithRefToParent, parent=self.ddf.get(ModelChildWithCustomParentLink))
        assert ModelWithRefToParent.objects.count() == 1
        assert ModelParent.objects.count() == 1
        assert ModelChildWithCustomParentLink.objects.count() == 1
        assert isinstance(instance.parent, ModelChildWithCustomParentLink)


class ComplexFieldsTest(DDFTestCase):
    def test_x(self):
        instance = self.ddf.new(ModelForUUID)
        assert isinstance(instance.uuid, uuid.UUID)


class ModelValidatorsTest(DDFTestCase):
    def test_it_must_create_if_validation_is_disabled(self):
        instance = self.ddf.get(ModelWithValidators, field_validator='nok', clean_validator='nok')
        self.ddf.validate_models = False
        assert instance.field_validator == 'nok'
        assert instance.clean_validator == 'nok'

    def test_it_must_create_if_there_is_no_validation_errors(self):
        instance = self.ddf.get(ModelWithValidators, field_validator='ok', clean_validator='ok')
        self.ddf.validate_models = True
        assert instance.field_validator == 'ok'
        assert instance.clean_validator == 'ok'

    def test_it_must_raise_a_bad_data_error_if_data_is_not_valid(self):
        self.ddf.validate_models = True
        self.ddf.get(ModelWithValidators, field_validator='nok', clean_validator='ok')
        with pytest.raises(BadDataError):
            self.ddf.get(ModelWithValidators, field_validator='ok', clean_validator='nok')


class ConfigurationValidatorTest(DDFTestCase):
    def test_it_must_raise_a_bad_data_error_if_data_is_not_valid(self):
        with pytest.raises(InvalidConfigurationError):
            self.ddf.get(EmptyModel, unexistent_field='x')


class DisableAutoGeneratedDateTimesTest(DDFTestCase):
    def test_auto_generated_datetimes_must_be_respected_if_nothing_is_specified(self):
        instance = self.ddf.get(ModelWithAutoDateTimes)
        assert datetime.today().date() == instance.auto_now_add
        assert datetime.today().date() == instance.auto_now

    def test_it_must_ignore_auto_generated_datetime_if_a_custom_value_is_provided(self):
        instance = self.ddf.get(ModelWithAutoDateTimes, auto_now_add=date(2000, 12, 31))
        assert instance.auto_now_add == date(2000, 12, 31)

        instance = self.ddf.get(ModelWithAutoDateTimes, auto_now=date(2000, 12, 31))
        assert instance.auto_now == date(2000, 12, 31)

    def test_checking_if_implementation_works_for_m2m_fields_too(self):
        instance = self.ddf.get(ModelWithAutoDateTimes, manytomany=[DynamicFixture(data_fixture, auto_now_add=date(2000, 12, 31))])
        assert instance.manytomany.all()[0].auto_now_add == date(2000, 12, 31)

        instance = self.ddf.get(ModelWithAutoDateTimes, manytomany=[DynamicFixture(data_fixture, auto_now=date(2000, 12, 31))])
        assert instance.manytomany.all()[0].auto_now == date(2000, 12, 31)


class ModelWithCustomValidationTest(DDFTestCase):
    def test_ddf_can_not_create_instance_of_models_with_custom_validations(self):
        self.ddf.validate_models = True
        with pytest.raises(BadDataError):
            self.ddf.get(ModelWithClean)
        self.ddf.get(ModelWithClean, integer=9999) # this does not raise an exception


class ExceptionsLayoutMessagesTest(DDFTestCase):
    def test_UnsupportedFieldError(self):
        try:
            self.ddf.new(ModelWithUnsupportedField)
            self.fail()
        except UnsupportedFieldError as e:
            assert """django_dynamic_fixture.models_test.ModelWithUnsupportedField.z""" in str(e)

    def test_BadDataError(self):
        self.ddf = DynamicFixture(data_fixture, ignore_fields=['required', 'required_with_default'])
        try:
            self.ddf.get(ModelForIgnoreList)
            self.fail()
        except BadDataError as e:
            assert 'IntegrityError' in str(e), str(e)
            assert 'NULL' in str(e).upper(), str(e)

    def test_InvalidConfigurationError(self):
        try:
            self.ddf.new(ModelWithNumbers, integer=lambda x: ''.invalidmethod())
            self.fail()
        except InvalidConfigurationError as e:
            assert 'django_dynamic_fixture.models_test.ModelWithNumbers.integer' in str(e)
            assert 'AttributeError' in str(e)
            assert 'invalidmethod' in str(e)

    def test_InvalidManyToManyConfigurationError(self):
        try:
            self.ddf.get(ModelWithRelationships, manytomany='a')
            self.fail()
        except InvalidManyToManyConfigurationError as e:
            assert """('Field: manytomany', 'a')""" == str(e)

    def test_InvalidModelError(self):
        try:
            self.ddf.get(ModelAbstract)
            self.fail()
        except InvalidModelError as e:
            assert """django_dynamic_fixture.models_test.ModelAbstract""" == str(e)

    def test_InvalidModelError_for_common_object(self):
        class MyClass: pass
        try:
            self.ddf.new(MyClass)
            self.fail()
        except InvalidModelError as e:
            assert """django_dynamic_fixture.tests.test_ddf.MyClass""" == str(e)


class SanityTest(DDFTestCase):
    def test_create_lots_of_models_to_verify_data_unicity_errors(self):
        for i in range(1000):
            self.ddf.get(ModelWithNumbers)


class AvoidNameCollisionTest(DDFTestCase):
    def test_avoid_common_name_instance(self):
        self.ddf = DynamicFixture(data_fixture, fill_nullable_fields=False)
        instance = self.ddf.new(ModelWithCommonNames)
        assert instance.instance is not None

        instance = self.ddf.new(ModelWithCommonNames, instance=3)
        assert instance.instance == 3

        instance = self.ddf.get(ModelWithCommonNames)
        assert instance.instance is not None

        instance = self.ddf.get(ModelWithCommonNames, instance=4)
        assert instance.instance == 4

    def test_avoid_common_name_field(self):
        self.ddf = DynamicFixture(data_fixture, fill_nullable_fields=False)
        instance = self.ddf.new(ModelWithCommonNames)
        assert instance.field is not None

        instance = self.ddf.new(ModelWithCommonNames, field=5)
        assert instance.field == 5

        instance = self.ddf.get(ModelWithCommonNames)
        assert instance.field is not None

        instance = self.ddf.get(ModelWithCommonNames, field=6)
        assert instance.field == 6


================================================
FILE: django_dynamic_fixture/tests/test_ddf_checkings.py
================================================

from django.test import TestCase

from django_dynamic_fixture.ddf import DDFLibrary
from django_dynamic_fixture import ddf_check_models, teach


class DDFTestCase(TestCase):
    def setUp(self):
        DDFLibrary.get_instance().clear()


class TestCheckCompatibility(DDFTestCase):
    def test_default(self):
        succeeded, errors = ddf_check_models()

        compatible_models = [
            'django_dynamic_fixture.EmptyModel',
            'django_dynamic_fixture.ModelWithNumbers',
        ]
        for model in compatible_models:
            assert model in succeeded.keys(), model

        incompatible_models = [
            'django_dynamic_fixture.ModelWithUnsupportedField',
        ]
        for model in incompatible_models:
            assert model in errors.keys(), model
        # TODO: Consider the RelatedObjectDoesNotExist errors
        # https://stackoverflow.com/questions/26270042/how-do-you-catch-this-exception

    def test_teaching_ddf(self):
        teach('django_dynamic_fixture.ModelWithUnsupportedField', z='z')
        succeeded, errors = ddf_check_models()

        compatible_models = [
            'django_dynamic_fixture.ModelWithUnsupportedField',
        ]
        for model in compatible_models:
            assert model in succeeded.keys(), model
            assert model not in errors.keys(), model


================================================
FILE: django_dynamic_fixture/tests/test_ddf_copier.py
================================================
from django.test import TestCase
import pytest

from django_dynamic_fixture.models_test import *
from django_dynamic_fixture.ddf import *
from django_dynamic_fixture.fixture_algorithms.sequential_fixture import SequentialDataFixture


data_fixture = SequentialDataFixture()


class DDFTestCase(TestCase):
    def setUp(self):
        self.ddf = DynamicFixture(data_fixture)


class CopyTest(DDFTestCase):
    def test_it_should_copy_from_model_fields(self):
        instance = self.ddf.get(ModelForCopy, int_a=Copier('int_b'), int_b=3)
        assert instance.int_a == 3

    def test_simple_scenario(self):
        instance = self.ddf.get(ModelForCopy, int_b=Copier('int_a'))
        assert instance.int_b == instance.int_a

    def test_order_of_attributes_must_be_superfluous(self):
        instance = self.ddf.get(ModelForCopy, int_a=Copier('int_b'))
        assert instance.int_a == instance.int_b

    def test_it_should_deal_with_multiple_copiers(self):
        instance = self.ddf.get(ModelForCopy, int_a=Copier('int_b'), int_c=Copier('int_d'))
        assert instance.int_a == instance.int_b
        assert instance.int_c == instance.int_d

    def test_multiple_copiers_can_depend_of_one_field(self):
        instance = self.ddf.get(ModelForCopy, int_a=Copier('int_c'), int_b=Copier('int_c'))
        assert instance.int_a == instance.int_c
        assert instance.int_b == instance.int_c

    def test_it_should_deal_with_dependent_copiers(self):
        instance = self.ddf.get(ModelForCopy, int_a=Copier('int_b'), int_b=Copier('int_c'))
        assert instance.int_a == instance.int_b
        assert instance.int_b == instance.int_c

    def test_it_should_deal_with_relationships(self):
        instance = self.ddf.get(ModelForCopy, int_a=Copier('e.int_e'))
        assert instance.int_a == instance.e.int_e

        instance = self.ddf.get(ModelForCopy, int_a=Copier('e.int_e'), e=DynamicFixture(data_fixture, int_e=5))
        assert instance.int_a == 5

    def test_it_should_raise_a_bad_data_error_if_value_is_invalid(self):
        with pytest.raises(BadDataError):
            self.ddf.get(ModelForCopy, int_a=Copier('int_b'), int_b=None)

    def test_it_should_raise_a_invalid_configuration_error_if_expression_is_bugged(self):
        with pytest.raises(InvalidConfigurationError):
            self.ddf.get(ModelForCopy, int_a=Copier('invalid_field'))
        with pytest.raises(InvalidConfigurationError):
            self.ddf.get(ModelForCopy, int_a=Copier('int_b.invalid_field'))

    def test_it_should_raise_a_invalid_configuration_error_if_copier_has_cyclic_dependency(self):
        with pytest.raises(InvalidConfigurationError):
            self.ddf.get(ModelForCopy, int_a=Copier('int_b'), int_b=Copier('int_a'))

    def test_it_must_copy_generated_data_mask_too(self):
        import re
        instance = self.ddf.get(ModelWithStrings, string=Mask('- _ #'), text=Copier('string'))
        assert re.match(r'[A-Z]{1} [a-z]{1} [0-9]{1}', instance.string)
        assert re.match(r'[A-Z]{1} [a-z]{1} [0-9]{1}', instance.text)


================================================
FILE: django_dynamic_fixture/tests/test_ddf_custom_fields.py
================================================
from django.conf import settings

from django.test import TestCase
import pytest

from django_dynamic_fixture.models_test import *
from django_dynamic_fixture.ddf import *
from django_dynamic_fixture.decorators import only_for_database, POSTGRES
from django_dynamic_fixture.fixture_algorithms.sequential_fixture import SequentialDataFixture

data_fixture = SequentialDataFixture()


class DDFTestCase(TestCase):
    def setUp(self):
        self.ddf = DynamicFixture(data_fixture)


class CustomFieldsTest(DDFTestCase):
    def test_new_field_that_extends_django_field_must_be_supported(self):
        instance = self.ddf.new(ModelWithCustomFields)
        assert instance.x == 1

    def test_new_field_that_extends_django_field_must_be_supported_with_custom_value(self):
        instance = self.ddf.new(ModelWithCustomFields, x=6)
        assert instance.x == 6

    def test_unsupported_field_is_filled_with_null_if_it_is_possible(self):
        instance = self.ddf.new(ModelWithCustomFields)
        assert instance.y is None

    def test_unsupported_field_raise_an_error_if_it_does_not_accept_null_value(self):
        DDFLibrary.get_instance().clear()
        with pytest.raises(UnsupportedFieldError):
            self.ddf.new(ModelWithUnsupportedField)

    def test_new_field_that_double_inherits_django_field_must_be_supported(self):
        instance = self.ddf.new(ModelWithCustomFieldsMultipleInheritance)
        assert instance.x == 1

    def test_new_field_that_double_inherits_django_field_must_be_supported_with_custom_value(self):
        instance = self.ddf.new(ModelWithCustomFieldsMultipleInheritance, x=5)
        assert instance.x == 5


class NewFullFillAttributesUsingPluginsTest(DDFTestCase):
    def test_custom_field_not_registered_must_raise_an_unsupported_field_exception(self):
        DDFLibrary.get_instance().clear()
        with pytest.raises(UnsupportedFieldError):
            self.ddf.get(ModelWithUnsupportedField)

    def test_new_fill_field_with_data_generated_by_plugins_with_dict(self):
        data_fixture.plugins = settings.DDF_FIELD_FIXTURES
        try:
            instance = self.ddf.get(ModelForFieldPlugins)
            # assert instance.aaa == 123456789
            # assert instance.bbb == 123456789
            assert instance.custom_field_custom_fixture == 123456789
        finally:
            data_fixture.plugins = {}

    def test_new_fill_field_with_data_generated_by_plugins_with_direct_fuction(self):
        data_fixture.plugins = settings.DDF_FIELD_FIXTURES
        try:
            instance = self.ddf.get(ModelForFieldPlugins)
            assert instance.custom_field_custom_fixture2 == 987654321
        finally:
            data_fixture.plugins = {}

    # Real Custom Field
    def test_json_field_not_registered_must_raise_an_unsupported_field_exception(self):
        # jsonfield requires Django 1.4+
        try:
            from jsonfield import JSONCharField, JSONField
            instance = self.ddf.new(ModelForPlugins1)
            assert False, 'JSON fields must not be supported by default'
        except ImportError:
            pass
        except UnsupportedFieldError as e:
            pass

    def test_new_fill_json_field_with_data_generated_by_plugins(self):
        # jsonfield requires Django 1.4+
        try:
            import json
            from jsonfield import JSONCharField, JSONField
            data_fixture.plugins = settings.DDF_FIELD_FIXTURES
            try:
                instance = self.ddf.new(ModelForPlugins1)
                assert isinstance(instance.json_field1, str), type(instance.json_field1)
                assert isinstance(instance.json_field2, str), type(instance.json_field2)
                assert isinstance(json.loads(instance.json_field1), dict)
                assert isinstance(json.loads(instance.json_field2), list)
                assert instance.json_field1 == '{"some random value": "c"}'
                assert instance.json_field2 == '[1, 2, 3]'
            finally:
                data_fixture.plugins = {}
        except ImportError:
            pass


class PostgresCustomFieldsTest(DDFTestCase):
    @only_for_database(POSTGRES)
    def test_json_field(self):
        instance = self.ddf.get(ModelForPostgresFields)
        assert instance.nullable_json_field == {}
        assert instance.json_field == {}

    @only_for_database(POSTGRES)
    def test_json_field_as_null(self):
        instance = self.ddf.get(ModelForPostgresFields, nullable_json_field=None)
        assert instance.nullable_json_field is None

    @only_for_database(POSTGRES)
    def test_json_field_as_dicts(self):
        instance = self.ddf.get(ModelForPostgresFields, json_field={'a': 1})
        assert instance.json_field == {'a': 1}

    @only_for_database(POSTGRES)
    def test_json_field_as_lists(self):
        instance = self.ddf.get(ModelForPostgresFields, json_field=['str1', 2, {'c': 3}])
        assert instance.json_field == ['str1', 2, {'c': 3}]

    @only_for_database(POSTGRES)
    def test_json_field_as_strings(self):
        instance = self.ddf.get(ModelForPostgresFields, json_field='str')
        assert instance.json_field == 'str'


================================================
FILE: django_dynamic_fixture/tests/test_ddf_custom_models.py
================================================
from django.test import TestCase
import pytest

from django_dynamic_fixture.models_test import *
from django_dynamic_fixture.ddf import *
from django_dynamic_fixture import G

try:
    from polymorphic.models import PolymorphicModel

    class PolymorphicModelTest(TestCase):
        def test_create_polymorphic_model_and_retrieve(self):
            p = G(ModelPolymorphic)
            assert list(ModelPolymorphic.objects.all()) == [p]

        def test_create_polymorphic_model_2_and_retrieve(self):
            p = G(ModelPolymorphic2)
            assert list(ModelPolymorphic2.objects.all()) == [p]

        def test_cannot_save(self):
            with self.assertRaises(BadDataError):
                G(ModelPolymorphic3)
except ImportError:
    pass


================================================
FILE: django_dynamic_fixture/tests/test_ddf_geo.py
================================================
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured

try:
    from django.contrib.gis.geos import *
except ImproperlyConfigured:
    pass  # environment without geo libs

try:
    from django.contrib.gis.db import models as geomodel
except ImproperlyConfigured:
    pass  # environment without geo libs

from django.test import TestCase
import pytest

from django_dynamic_fixture.models_test import *
from django_dynamic_fixture.ddf import *
from django_dynamic_fixture.fixture_algorithms.sequential_fixture import SequentialDataFixture


data_fixture = SequentialDataFixture()


class DDFTestCase(TestCase):
    def setUp(self):
        self.ddf = DynamicFixture(data_fixture)


if (hasattr(settings, 'DDF_TEST_GEODJANGO') and settings.DDF_TEST_GEODJANGO):
    class GeoDjangoFieldsTest(DDFTestCase):
        def test_geodjango_fields(self):
            instance = self.ddf.new(ModelForGeoDjango)
            assert isinstance(instance.geometry, GEOSGeometry), str(type(instance.geometry))
            assert isinstance(instance.point, Point)
            assert isinstance(instance.line_string, LineString)
            assert isinstance(instance.polygon, Polygon)
            assert isinstance(instance.multi_point, MultiPoint)
            assert isinstance(instance.multi_line_string, MultiLineString)
            assert isinstance(instance.multi_polygon, MultiPolygon)
            assert isinstance(instance.geometry_collection, GeometryCollection)


================================================
FILE: django_dynamic_fixture/tests/test_ddf_signals.py
================================================
from django.test import TestCase
import pytest

from django_dynamic_fixture.models_test import *
from django_dynamic_fixture.ddf import *
from django_dynamic_fixture.ddf import _PRE_SAVE, _POST_SAVE
from django_dynamic_fixture.fixture_algorithms.sequential_fixture import SequentialDataFixture


data_fixture = SequentialDataFixture()


class DDFTestCase(TestCase):
    def setUp(self):
        self.ddf = DynamicFixture(data_fixture)
        _PRE_SAVE.clear()
        _POST_SAVE.clear()



class PreSaveTest(DDFTestCase):
    def test_set_pre_save_receiver(self):
        def callback_function(instance):
            pass
        set_pre_save_receiver(ModelForSignals, callback_function)
        callback_function = lambda x: x
        set_pre_save_receiver(ModelForSignals, callback_function)

    def test_pre_save_receiver_must_raise_an_error_if_first_parameter_is_not_a_model_class(self):
        callback_function = lambda x: x
        with pytest.raises(InvalidReceiverError):
            set_pre_save_receiver(str, callback_function)

    def test_pre_save_receiver_must_raise_an_error_if_it_is_not_a_function(self):
        with pytest.raises(InvalidReceiverError):
            set_pre_save_receiver(ModelForSignals, '')

    def test_pre_save_receiver_must_raise_an_error_if_it_is_not_an_only_one_argument_function(self):
        callback_function = lambda x, y: x
        with pytest.raises(InvalidReceiverError):
            set_pre_save_receiver(ModelForSignals, callback_function)

    def test_pre_save_receiver_must_be_executed_before_saving(self):
        def callback_function(instance):
            if instance.id is not None:
                raise Exception('ops, instance already saved')
            self.ddf.get(ModelForSignals2)
        set_pre_save_receiver(ModelForSignals, callback_function)
        self.ddf.get(ModelForSignals)
        assert ModelForSignals2.objects.count() == 1

    def test_bugged_pre_save_receiver_must_raise_an_error(self):
        def callback_function(instance):
            raise Exception('ops')
        set_pre_save_receiver(ModelForSignals, callback_function)
        with pytest.raises(BadDataError):
            self.ddf.get(ModelForSignals)


class PostSaveTest(DDFTestCase):
    def test_set_post_save_receiver(self):
        def callback_function(instance):
            pass
        set_post_save_receiver(ModelForSignals, callback_function)
        callback_function = lambda x: x
        set_post_save_receiver(ModelForSignals, callback_function)

    def test_post_save_receiver_must_raise_an_error_if_first_parameter_is_not_a_model_class(self):
        callback_function = lambda x: x
        with pytest.raises(InvalidReceiverError):
            set_post_save_receiver(str, callback_function)

    def test_post_save_receiver_must_raise_an_error_if_it_is_not_a_function(self):
        with pytest.raises(InvalidReceiverError):
            set_post_save_receiver(ModelForSignals, '')

    def test_post_save_receiver_must_raise_an_error_if_it_is_not_an_only_one_argument_function(self):
        callback_function = lambda x, y: x
        with pytest.raises(InvalidReceiverError):
            set_post_save_receiver(ModelForSignals, callback_function)

    def test_pre_save_receiver_must_be_executed_before_saving(self):
        def callback_function(instance):
            if instance.id is None:
                raise Exception('ops, instance not saved')
            self.ddf.get(ModelForSignals2)
        set_post_save_receiver(ModelForSignals, callback_function)
        self.ddf.get(ModelForSignals)
        assert ModelForSignals2.objects.count() == 1

    def test_bugged_post_save_receiver_must_raise_an_error(self):
        def callback_function(instance):
            raise Exception('ops')
        set_post_save_receiver(ModelForSignals, callback_function)
        with pytest.raises(BadDataError):
            self.ddf.get(ModelForSignals)


================================================
FILE: django_dynamic_fixture/tests/test_ddf_teaching_and_lessons.py
================================================
import re

from django.test import TestCase
import pytest

from django_dynamic_fixture.models_test import *
from django_dynamic_fixture.ddf import *
from django_dynamic_fixture.fixture_algorithms.sequential_fixture import SequentialDataFixture


data_fixture = SequentialDataFixture()


class DDFTestCase(TestCase):
    def setUp(self):
        self.ddf = DynamicFixture(data_fixture)
        DDFLibrary.get_instance().clear()


class TeachAndLessonsTest(DDFTestCase):
    def test_teach_a_default_lesson_for_a_model(self):
        self.ddf.teach(ModelForLibrary, integer=1000)
        instance = self.ddf.get(ModelForLibrary)
        assert instance.integer == 1000

    def test_default_lesson_may_be_overrided_although_it_is_an_anti_pattern(self):
        self.ddf.teach(ModelForLibrary, integer=1000)
        instance = self.ddf.get(ModelForLibrary)
        assert instance.integer == 1000
        self.ddf.teach(ModelForLibrary, integer=1001)
        instance = self.ddf.get(ModelForLibrary)
        assert instance.integer == 1001

    def test_it_must_NOT_raise_an_error_if_user_try_to_use_a_not_saved_default_configuration(self):
        self.ddf.get(ModelForLibrary)

    def test_it_must_raise_an_error_if_try_to_set_a_static_value_to_a_field_with_unicity(self):
        with pytest.raises(InvalidConfigurationError):
            self.ddf.teach(ModelForLibrary, integer_unique=1000)

    def test_it_allows_to_use_masks_as_lessons_for_unique_integer_fields(self):
        self.ddf.teach(ModelForLibrary, integer_unique=Mask('1###'))
        instance = self.ddf.get(ModelForLibrary)
        assert 1000 <= int(instance.integer_unique) <= 1999

    def test_it_allows_to_use_masks_as_lessons_for_unique_char_fields(self):
        self.ddf.teach(ModelWithUniqueCharField, text_unique=Mask('---- ### __'))
        instance = self.ddf.get(ModelWithUniqueCharField)
        assert re.match(r'[A-Z]{4} [0-9]{3} [a-z]{2}', instance.text_unique)

    def test_it_must_accept_dynamic_values_for_fields_with_unicity(self):
        self.ddf.teach(ModelForLibrary, integer_unique=lambda field: 1000)

    def test_it_must_NOT_propagate_lessons_for_internal_dependencies(self):
        self.ddf.teach(ModelForLibrary, foreignkey=DynamicFixture(data_fixture, integer=1000))
        instance = self.ddf.get(ModelForLibrary)
        assert instance.integer != 1000
        assert instance.foreignkey.integer == 1000

    def test_it_must_use_lessons_for_internal_dependencies(self):
        # ModelForLibrary.foreignkey is a `ModelForLibrary2`
        self.ddf.teach(ModelForLibrary, integer=1000)
        self.ddf.teach(ModelForLibrary2, integer=1001)
        instance = self.ddf.get(ModelForLibrary, foreignkey=DynamicFixture(data_fixture))
        assert instance.integer == 1000
        assert instance.foreignkey.integer == 1001

    def test_it_uses_lessons_for_base_model_when_creating_a_proxy_model(self):
        self.ddf.teach(ModelForLibrary, integer=123)
        instance = self.ddf.get(ProxyModelForLibrary)
        assert instance.__class__ is ProxyModelForLibrary
        assert instance.integer == 123

    def test_it_uses_lessons_for_proxy_models_when_creating_the_base_model(self):
        self.ddf.teach(ProxyModelForLibrary, integer=456)
        instance = self.ddf.get(ModelForLibrary)
        assert instance.__class__ is ModelForLibrary
        assert instance.integer == 456

    def test_it_uses_lessons_for_proxy_models_when_creating_the_proxy_model(self):
        self.ddf.teach(ProxyModelForLibrary, integer=789)
        instance = self.ddf.get(ProxyModelForLibrary)
        assert instance.__class__ is ProxyModelForLibrary
        assert instance.integer == 789

    # Not implemented yet
    # def test_teaching_must_store_ddf_configs_too(self):
    #     self.ddf.teach(ModelForLibrary, fill_nullable_fields=False)
    #     instance = self.ddf.get(ModelForLibrary)
    #     assert instance.integer is None

    #     DDFLibrary.get_instance().clear()
    #     self.ddf.teach(ModelForLibrary, fill_nullable_fields=True)
    #     instance = self.ddf.get(ModelForLibrary)
    #     assert instance.integer is not None

    # Not implemented yet
    # def test_teaching_ddf_configs_must_NOT_be_propagated_to_another_models(self):
    #     self.ddf.teach(ModelForLibrary, fill_nullable_fields=False)
    #     instance = self.ddf.get(ModelForLibrary)
    #     assert instance.integer is None
    #     assert instance.foreignkey.integer is None

    #     DDFLibrary.get_instance().clear()
    #     self.ddf.teach(ModelForLibrary, fill_nullable_fields=True)
    #     instance = self.ddf.get(ModelForLibrary)
    #     assert instance.integer is not None
    #     assert instance.foreignkey.integer is None # not populated


class TeachingAndCustomLessonsTest(DDFTestCase):
    def test_a_model_can_have_custom_lessons(self):
        self.ddf.teach(ModelForLibrary, integer=1000, ddf_lesson=None)
        self.ddf.teach(ModelForLibrary, integer=1001, ddf_lesson='a name')
        instance = self.ddf.get(ModelForLibrary)
        assert instance.integer == 1000
        instance = self.ddf.get(ModelForLibrary, ddf_lesson='a name')
        assert instance.integer == 1001

    def test_custom_lessons_must_not_be_used_if_not_explicity_specified(self):
        self.ddf.teach(ModelForLibrary, integer=1000, ddf_lesson='a name')
        instance = self.ddf.get(ModelForLibrary)
        assert instance.integer != 1000

    def test_a_model_can_have_many_custom_lessons(self):
        self.ddf.teach(ModelForLibrary, integer=1000, ddf_lesson='a name')
        self.ddf.teach(ModelForLibrary, integer=1001, ddf_lesson='a name 2')

        instance = self.ddf.get(ModelForLibrary, ddf_lesson='a name')
        assert instance.integer == 1000

        instance = self.ddf.get(ModelForLibrary, ddf_lesson='a name 2')
        assert instance.integer == 1001

    def test_it_must_raise_an_error_if_user_try_to_use_a_not_saved_configuration(self):
        with pytest.raises(InvalidConfigurationError):
            self.ddf.get(ModelForLibrary, ddf_lesson='a not teached lesson')

    def test_default_lesson_and_custom_lesson_must_work_together(self):
        # regression test
        self.ddf.teach(ModelForLibrary, integer=1000, ddf_lesson='a name')
        self.ddf.teach(ModelForLibrary, integer=1001, ddf_lesson=True)
        self.ddf.teach(ModelForLibrary, integer=1002, ddf_lesson='a name2')
        instance = self.ddf.get(ModelForLibrary, ddf_lesson='a name')
        assert instance.integer == 1000
        instance = self.ddf.get(ModelForLibrary)
        assert instance.integer == 1001
        instance = self.ddf.get(ModelForLibrary, ddf_lesson='a name2')
        assert instance.integer == 1002

    def test_default_lesson_and_custom_lesson_must_work_together_for_different_models(self):
        # regression test
        self.ddf.teach(ModelForLibrary, integer=1000, ddf_lesson='a name')
        self.ddf.teach(ModelForLibrary, integer=1001, ddf_lesson=True)
        self.ddf.teach(ModelForLibrary, integer=1002, ddf_lesson='a name2')
        self.ddf.teach(ModelForLibrary2, integer=2000, ddf_lesson='a name')
        self.ddf.teach(ModelForLibrary2, integer=2001, ddf_lesson=True)
        self.ddf.teach(ModelForLibrary2, integer=2002, ddf_lesson='a name2')

        instance = self.ddf.get(ModelForLibrary, ddf_lesson='a name')
        assert instance.integer == 1000
        instance = self.ddf.get(ModelForLibrary)
        assert instance.integer == 1001
        instance = self.ddf.get(ModelForLibrary, ddf_lesson='a name2')
        assert instance.integer == 1002

        instance = self.ddf.get(ModelForLibrary2, ddf_lesson='a name')
        assert instance.integer == 2000
        instance = self.ddf.get(ModelForLibrary2)
        assert instance.integer == 2001
        instance = self.ddf.get(ModelForLibrary2, ddf_lesson='a name2')
        assert instance.integer == 2002


class DDFLibraryTest(TestCase):
    def setUp(self):
        self.lib = DDFLibrary()

    def test_add_and_get_configuration_without_string_name(self):
        self.lib.add_configuration(ModelForLibrary, {'a': 1})
        assert self.lib.get_configuration(ModelForLibrary) == {'a': 1}
        assert self.lib.get_configuration(ModelForLibrary, name=DDFLibrary.DEFAULT_KEY) == {'a': 1}
        assert self.lib.get_configuration(ModelForLibrary, name=None) == {'a': 1}

        self.lib.clear()
        self.lib.add_configuration(ModelForLibrary, {'a': 2}, name=None)
        assert self.lib.get_configuration(ModelForLibrary) == {'a': 2}
        assert self.lib.get_configuration(ModelForLibrary, name=DDFLibrary.DEFAULT_KEY) == {'a': 2}
        assert self.lib.get_configuration(ModelForLibrary, name=None) == {'a': 2}

        self.lib.clear()
        self.lib.add_configuration(ModelForLibrary, {'a': 3}, name=True)
        assert self.lib.get_configuration(ModelForLibrary) == {'a': 3}
        assert self.lib.get_configuration(ModelForLibrary, name=DDFLibrary.DEFAULT_KEY) == {'a': 3}
        assert self.lib.get_configuration(ModelForLibrary, name=None) == {'a': 3}

    def test_add_and_get_configuration_with_name(self):
        self.lib.add_configuration(ModelForLibrary, {'a': 1}, name='x')
        assert self.lib.get_configuration(ModelForLibrary, name='x') == {'a': 1}

    def test_clear_config(self):
        self.lib.clear_configuration(ModelForLibrary) # run ok if empty
        self.lib.add_configuration(ModelForLibrary, {'a': 1})
        self.lib.add_configuration(ModelForLibrary, {'a': 2}, name='x')
        self.lib.add_configuration(ModelForLibrary2, {'a': 3})
        self.lib.clear_configuration(ModelForLibrary)
        assert self.lib.get_configuration(ModelForLibrary) == {}
        with pytest.raises(Exception):
            self.lib.get_configuration(ModelForLibrary, name='x')
        assert self.lib.get_configuration(ModelForLibrary2) == {'a': 3}

    def test_clear(self):
        self.lib.add_configuration(ModelForLibrary, {'a': 1})
        self.lib.add_configuration(ModelForLibrary, {'a': 2}, name='x')
        self.lib.add_configuration(ModelForLibrary2, {'a': 3})
        self.lib.add_configuration(ModelForLibrary2, {'a': 4}, name='x')
        self.lib.clear()
        assert self.lib.get_configuration(ModelForLibrary) == {}
        with pytest.raises(Exception):
            self.lib.get_configuration(ModelForLibrary, name='x')
        assert self.lib.get_configuration(ModelForLibrary2) == {}
        with pytest.raises(Exception):
            self.lib.get_configuration(ModelForLibrary2, name='x')


================================================
FILE: django_dynamic_fixture/tests/test_decorators.py
================================================
from unittest import TestCase

from django.conf import settings

from django_dynamic_fixture import decorators


class SkipForDatabaseTest(TestCase):
    def setUp(self):
        self.it_was_executed = False

    def tearDown(self):
        # It is important to do not break others tests: global and shared variable
        decorators.DATABASE_ENGINE = settings.DATABASES['default']['ENGINE']

    @decorators.only_for_database(decorators.POSTGRES)
    def method_postgres(self):
        self.it_was_executed = True

    def test_annotated_method_only_for_postgres(self):
        decorators.DATABASE_ENGINE = decorators.SQLITE3
        self.method_postgres()
        assert self.it_was_executed is False

        decorators.DATABASE_ENGINE = decorators.POSTGRES
        self.method_postgres()
        assert self.it_was_executed


class OnlyForDatabaseTest(TestCase):
    def setUp(self):
        self.it_was_executed = False

    def tearDown(self):
        # It is important to do not break others tests: global and shared variable
        decorators.DATABASE_ENGINE = settings.DATABASES['default']['ENGINE']

    @decorators.skip_for_database(decorators.SQLITE3)
    def method_sqlite3(self):
        self.it_was_executed = True

    def test_annotated_method_skip_for_sqlite3(self):
        decorators.DATABASE_ENGINE = decorators.SQLITE3
        self.method_sqlite3()
        assert self.it_was_executed is False

        decorators.DATABASE_ENGINE = decorators.POSTGRES
        self.method_sqlite3()
        assert self.it_was_executed


================================================
FILE: django_dynamic_fixture/tests/test_django_helper.py
================================================

from django.test import TestCase
from django.db import models
import pytest

from django_dynamic_fixture import N, G
from django_dynamic_fixture.models_test import *
from django_dynamic_fixture.django_helper import *


class DjangoHelperAppsTest(TestCase):
    def test_get_apps_must_return_all_installed_apps(self):
        assert len(get_apps()) >= 1

    def test_get_apps_may_be_filtered_by_app_names(self):
        apps = get_apps(application_labels=['django_dynamic_fixture'])
        assert len(apps) == 1

    def test_get_apps_may_ignore_some_apps(self):
        apps = len(get_apps(exclude_application_labels=['django_dynamic_fixture']))
        assert len(get_app
Download .txt
gitextract_1_zfvdao/

├── .coveragerc
├── .flake8
├── .github/
│   ├── FUNDING.yml
│   └── workflows/
│       └── release.yml
├── .gitignore
├── .pylintrc
├── .python-version
├── .readthedocs.yaml
├── LICENSE.txt
├── MANIFEST.in
├── Makefile
├── README.md
├── ddf/
│   └── __init__.py
├── django_dynamic_fixture/
│   ├── __init__.py
│   ├── ddf.py
│   ├── decorators.py
│   ├── django_helper.py
│   ├── fdf.py
│   ├── fields.py
│   ├── fixture_algorithms/
│   │   ├── __init__.py
│   │   ├── default_fixture.py
│   │   ├── random_fixture.py
│   │   ├── sequential_fixture.py
│   │   ├── tests/
│   │   │   ├── __init__.py
│   │   │   ├── abstract_test_generic_fixture.py
│   │   │   ├── test_default_fixture.py
│   │   │   ├── test_default_fixture_postgres.py
│   │   │   ├── test_random_fixture.py
│   │   │   ├── test_sequential_fixture.py
│   │   │   └── test_unique_random_fixture.py
│   │   └── unique_random_fixture.py
│   ├── global_settings.py
│   ├── models.py
│   ├── models_sample_app.py
│   ├── models_test.py
│   ├── models_third_party.py
│   ├── script_ddf_checkings.py
│   └── tests/
│       ├── __init__.py
│       ├── conftest.py
│       ├── test_ddf.py
│       ├── test_ddf_checkings.py
│       ├── test_ddf_copier.py
│       ├── test_ddf_custom_fields.py
│       ├── test_ddf_custom_models.py
│       ├── test_ddf_geo.py
│       ├── test_ddf_signals.py
│       ├── test_ddf_teaching_and_lessons.py
│       ├── test_decorators.py
│       ├── test_django_helper.py
│       ├── test_fdf.py
│       ├── test_global_settings.py
│       ├── test_mask.py
│       ├── test_module_ddf_shortcut.py
│       ├── test_sample_app.py
│       └── test_wrappers.py
├── docs/
│   ├── Makefile
│   └── source/
│       ├── _static/
│       │   └── coverage.html
│       ├── about.rst
│       ├── change_log.rst
│       ├── conf.py
│       ├── data.rst
│       ├── data_fixtures.rst
│       ├── ddf.rst
│       ├── fdf.rst
│       ├── index.rst
│       ├── more.rst
│       ├── overview.rst
│       ├── patterns.rst
│       └── settings.rst
├── manage.py
├── pytest.ini
├── queries/
│   ├── __init__.py
│   ├── count_queries_on_save.py
│   └── management/
│       ├── __init__.py
│       └── commands/
│           ├── __init__.py
│           └── count_queries_on_save.py
├── requirements-dev.txt
├── requirements.txt
├── settings_ddf.py
├── settings_mysql.py
├── settings_postgres.py
├── settings_sqlite.py
├── setup.py
└── tox.ini
Download .txt
SYMBOL INDEX (805 symbols across 40 files)

FILE: django_dynamic_fixture/__init__.py
  function look_up_alias (line 30) | def look_up_alias(ddf_as_f=True, **kwargs):
  function dict_to_f (line 54) | def dict_to_f(value):
  function fixture (line 73) | def fixture(**kwargs):
  function _new (line 92) | def _new(model, n=1, ddf_lesson=None, persist_dependencies=False, **kwar...
  function _get (line 123) | def _get(model, n=1, ddf_lesson=None, **kwargs):
  function _teach (line 153) | def _teach(model, ddf_lesson=None, **kwargs):
  function new (line 194) | def new(model: typing.Type[INSTANCE_TYPE], n: int = 1, ddf_lesson = None...
  function get (line 197) | def get(model: typing.Type[INSTANCE_TYPE], n: int=1, ddf_lesson=None, **...
  function teach (line 200) | def teach(model: typing.Type[INSTANCE_TYPE], ddf_lesson=None, **kwargs):

FILE: django_dynamic_fixture/ddf.py
  class UnsupportedFieldError (line 29) | class UnsupportedFieldError(Exception):
  class InvalidCopierExpressionError (line 33) | class InvalidCopierExpressionError(Exception):
  class InvalidConfigurationError (line 37) | class InvalidConfigurationError(Exception):
  class InvalidManyToManyConfigurationError (line 41) | class InvalidManyToManyConfigurationError(Exception):
  class BadDataError (line 45) | class BadDataError(Exception):
  class InvalidModelError (line 49) | class InvalidModelError(Exception):
  class InvalidReceiverError (line 53) | class InvalidReceiverError(Exception):
  class PendingField (line 57) | class PendingField(Exception):
  function _validate_model (line 61) | def _validate_model(model_class):
  function _validate_function (line 66) | def _validate_function(model_class, callback_function):
  function set_pre_save_receiver (line 75) | def set_pre_save_receiver(model_class, callback_function):
  function set_post_save_receiver (line 85) | def set_post_save_receiver(model_class, callback_function):
  class DataFixture (line 95) | class DataFixture:
    method __init__ (line 107) | def __init__(self):
    method _field_fixture_template (line 110) | def _field_fixture_template(self, field_class):
    method _field_fixture_factory (line 113) | def _field_fixture_factory(self, field_class):
    method generate_data (line 127) | def generate_data(self, field):
  class Copier (line 148) | class Copier:
    method __init__ (line 154) | def __init__(self, expression):
    method __str__ (line 157) | def __str__(self):
    method immediate_field_name (line 160) | def immediate_field_name(self, instance):
    method eval_expression (line 166) | def eval_expression(self, instance):
  class Mask (line 177) | class Mask:
    method __init__ (line 191) | def __init__(self, expression):
    method __str__ (line 194) | def __str__(self):
    method evaluate (line 197) | def evaluate(self):
  class DDFLibrary (line 221) | class DDFLibrary:
    method __init__ (line 225) | def __init__(self):
    method __str__ (line 228) | def __str__(self):
    method get_instance (line 232) | def get_instance(cls):
    method add_configuration (line 237) | def add_configuration(self, model_class, kwargs, name=None):
    method get_configuration (line 251) | def get_configuration(self, model_class, name=None):
    method _get_concrete_model (line 261) | def _get_concrete_model(self, model_class):
    method clear (line 267) | def clear(self):
    method clear_configuration (line 271) | def clear_configuration(self, model_class):
  class DynamicFixture (line 277) | class DynamicFixture:
    method __init__ (line 285) | def __init__(self, data_fixture, fill_nullable_fields=False, ignore_fi...
    method __str__ (line 316) | def __str__(self):
    method __eq__ (line 319) | def __eq__(self, that):
    method _get_data_from_custom_dynamic_fixture (line 322) | def _get_data_from_custom_dynamic_fixture(self, field, fixture, persis...
    method _get_data_from_custom_copier (line 331) | def _get_data_from_custom_copier(self, instance, field, fixture):
    method _get_data_from_data_fixture (line 341) | def _get_data_from_data_fixture(self, field, fixture):
    method _get_data_from_a_custom_function (line 346) | def _get_data_from_a_custom_function(self, field, fixture):
    method _get_data_from_static_data (line 351) | def _get_data_from_static_data(self, field, fixture):
    method _process_field_with_customized_fixture (line 359) | def _process_field_with_customized_fixture(self, instance, field, fixt...
    method _process_foreign_key (line 375) | def _process_foreign_key(self, model_class, field, persist_dependencies):
    method _process_field_with_default_fixture (line 402) | def _process_field_with_default_fixture(self, field, model_class, pers...
    method set_data_for_a_field (line 435) | def set_data_for_a_field(self, model_class, __instance, __field, persi...
    method _validate_kwargs (line 478) | def _validate_kwargs(self, model_class, kwargs):
    method _configure_params (line 486) | def _configure_params(self, model_class, ddf_lesson, **kwargs):
    method new (line 509) | def new(self, model_class, ddf_lesson=None, persist_dependencies=True,...
    method _is_ignored_field (line 555) | def _is_ignored_field(self, field_name):
    method _process_many_to_many_field (line 576) | def _process_many_to_many_field(self, field, manytomany_field, fixture...
    method _create_manytomany_relationship (line 602) | def _create_manytomany_relationship(self, manytomany_field, instance, ...
    method _save_the_instance (line 616) | def _save_the_instance(self, instance):
    method get (line 627) | def get(self, model_class, ddf_lesson=None, **kwargs):
    method teach (line 668) | def teach(self, model_class, ddf_lesson=None, **kwargs):
  function _is_dynamic_value (line 679) | def _is_dynamic_value(fixture):

FILE: django_dynamic_fixture/decorators.py
  function skip_for_database (line 14) | def skip_for_database(database):
  function only_for_database (line 23) | def only_for_database(database):

FILE: django_dynamic_fixture/django_helper.py
  function django_greater_than (line 17) | def django_greater_than(major, minor=0):
  function get_apps (line 22) | def get_apps(application_labels=[], exclude_application_labels=[]):
  function get_app_name (line 51) | def get_app_name(app_module):
  function get_models_of_an_app (line 58) | def get_models_of_an_app(app_label):
  function get_app_name_of_model (line 67) | def get_app_name_of_model(model_class):
  function get_model_name (line 71) | def get_model_name(model_class):
  function get_unique_model_name (line 76) | def get_unique_model_name(model_class):
  function get_fields_from_model (line 81) | def get_fields_from_model(model_class):
  function get_local_fields (line 86) | def get_local_fields(model):
  function get_many_to_many_fields_from_model (line 91) | def get_many_to_many_fields_from_model(model_class):
  function get_all_fields_of_model (line 97) | def get_all_fields_of_model(model_class):
  function get_field_names_of_model (line 104) | def get_field_names_of_model(model_class):
  function get_field_by_name_or_raise (line 110) | def get_field_by_name_or_raise(model_class, field_name):
  function is_model_class (line 115) | def is_model_class(instance_or_model_class):
  function is_model_abstract (line 120) | def is_model_abstract(model):
  function is_model_managed (line 125) | def is_model_managed(model):
  function model_has_the_field (line 130) | def model_has_the_field(model_class, field_name):
  function get_unique_field_name (line 140) | def get_unique_field_name(field):
  function get_related_model (line 146) | def get_related_model(field):
  function field_is_a_parent_link (line 150) | def field_is_a_parent_link(field):
  function field_has_choices (line 156) | def field_has_choices(field):
  function field_has_default_value (line 169) | def field_has_default_value(field):
  function field_is_unique (line 173) | def field_is_unique(field):
  function is_key_field (line 177) | def is_key_field(field):
  function is_relationship_field (line 181) | def is_relationship_field(field):
  function is_file_field (line 185) | def is_file_field(field):
  function print_field_values_of_a_model (line 189) | def print_field_values_of_a_model(model_instance):
  function print_field_values (line 206) | def print_field_values(model_instance_or_list_of_model_instances_or_quer...
  function enable_auto_now (line 216) | def enable_auto_now(field):
  function disable_auto_now (line 220) | def disable_auto_now(field):
  function enable_auto_now_add (line 224) | def enable_auto_now_add(field):
  function disable_auto_now_add (line 228) | def disable_auto_now_add(field):
  function is_boolean (line 234) | def is_boolean(field):
  function is_string (line 237) | def is_string(field):
  function is_number (line 240) | def is_number(field):
  function is_datetime (line 244) | def is_datetime(field):
  function is_file (line 247) | def is_file(field):
  function is_binary (line 250) | def is_binary(field):

FILE: django_dynamic_fixture/fdf.py
  class CustomFileSystemStorage (line 17) | class CustomFileSystemStorage(FileSystemStorage):
    method __init__ (line 18) | def __init__(self, *args, **kwargs):
  class FileSystemDjangoTestCase (line 23) | class FileSystemDjangoTestCase(TestCase):
    method setUp (line 26) | def setUp(self):
    method tearDown (line 29) | def tearDown(self):
    method _pre_setup (line 32) | def _pre_setup(self):
    method _post_teardown (line 36) | def _post_teardown(self):
    method fdf_setup (line 41) | def fdf_setup(self):
    method fdf_teardown (line 46) | def fdf_teardown(self):
    method create_temp_directory (line 55) | def create_temp_directory(self, prefix='file_system_test_case_dir_'):
    method remove_temp_directory (line 61) | def remove_temp_directory(self, directory_pathname):
    method create_temp_file (line 70) | def create_temp_file(self, directory=None, prefix='file_system_test_ca...
    method create_temp_file_with_name (line 80) | def create_temp_file_with_name(self, directory, name):
    method rename_temp_file (line 88) | def rename_temp_file(self, filepath, name):
    method remove_temp_file (line 99) | def remove_temp_file(self, filepath):
    method copy_file_to_dir (line 110) | def copy_file_to_dir(self, filepath, directory):
    method add_text_to_file (line 115) | def add_text_to_file(self, filepath, content):
    method get_directory_of_the_file (line 121) | def get_directory_of_the_file(self, filepath):
    method get_filename (line 125) | def get_filename(self, filepath):
    method get_filepath (line 129) | def get_filepath(self, directory, filename):
    method get_content_of_file (line 133) | def get_content_of_file(self, filepath):
    method create_django_file_with_temp_file (line 140) | def create_django_file_with_temp_file(self, name, content=None, dir=No...
    method create_django_file_using_file (line 151) | def create_django_file_using_file(self, filepath):
    method assertFileExists (line 160) | def assertFileExists(self, filepath):
    method assertFileDoesNotExists (line 163) | def assertFileDoesNotExists(self, filepath):
    method assertDirectoryExists (line 166) | def assertDirectoryExists(self, directory):
    method assertDirectoryDoesNotExists (line 170) | def assertDirectoryDoesNotExists(self, directory):
    method assertDirectoryContainsFile (line 174) | def assertDirectoryContainsFile(self, directory, filename):
    method assertDirectoryDoesNotContainsFile (line 178) | def assertDirectoryDoesNotContainsFile(self, directory, filename):
    method assertFilesHaveEqualLastModificationTimestamps (line 182) | def assertFilesHaveEqualLastModificationTimestamps(self, filepath1, fi...
    method assertFilesHaveNotEqualLastModificationTimestamps (line 185) | def assertFilesHaveNotEqualLastModificationTimestamps(self, filepath1,...
    method assertNumberOfFiles (line 188) | def assertNumberOfFiles(self, directory, number_of_files):

FILE: django_dynamic_fixture/fields.py
  class JSONField (line 11) | class JSONField(DjangoJSONField):
    method db_type (line 21) | def db_type(self, connection):
    method from_db_value (line 24) | def from_db_value(self, value, expression, connection):
    method to_python (line 29) | def to_python(self, value):
    method get_prep_value (line 37) | def get_prep_value(self, value):
    method value_to_string (line 42) | def value_to_string(self, obj):
  class ArrayField (line 15) | class ArrayField(DjangoArrayField):
    method __init__ (line 47) | def __init__(self, base_field, size=None, **kwargs):
    method deconstruct (line 53) | def deconstruct(self):
  class JSONField (line 20) | class JSONField(Field):
    method db_type (line 21) | def db_type(self, connection):
    method from_db_value (line 24) | def from_db_value(self, value, expression, connection):
    method to_python (line 29) | def to_python(self, value):
    method get_prep_value (line 37) | def get_prep_value(self, value):
    method value_to_string (line 42) | def value_to_string(self, obj):
  class ArrayField (line 46) | class ArrayField(JSONField):
    method __init__ (line 47) | def __init__(self, base_field, size=None, **kwargs):
    method deconstruct (line 53) | def deconstruct(self):

FILE: django_dynamic_fixture/fixture_algorithms/__init__.py
  class FixtureFactory (line 5) | class FixtureFactory:
    method get (line 7) | def get(data_fixture):

FILE: django_dynamic_fixture/fixture_algorithms/default_fixture.py
  class BaseDataFixture (line 27) | class BaseDataFixture(DataFixture):
    method binaryfield_config (line 29) | def binaryfield_config(self, field, key):
    method uuidfield_config (line 33) | def uuidfield_config(self, field, key):
    method genericipaddressfield_config (line 37) | def genericipaddressfield_config(self, field, key):
    method jsonfield_config (line 41) | def  jsonfield_config(self, field, key):
  class GeoDjangoFixtureMixin (line 46) | class GeoDjangoFixtureMixin:
    method create_point (line 47) | def create_point(self, x=None, y=None):
    method create_points (line 53) | def create_points(self, n=3, closed=True):
    method geometryfield_config (line 59) | def geometryfield_config(self, field, key):
    method pointfield_config (line 62) | def pointfield_config(self, field, key):
    method linestringfield_config (line 65) | def linestringfield_config(self, field, key, n=3):
    method polygonfield_config (line 68) | def polygonfield_config(self, field, key, n=3):
    method multipointfield_config (line 71) | def multipointfield_config(self, field, key, n=3):
    method multilinestringfield_config (line 74) | def multilinestringfield_config(self, field, key, n=3):
    method multipolygonfield_config (line 78) | def multipolygonfield_config(self, field, key, n=3):
    method geometrycollectionfield_config (line 82) | def geometrycollectionfield_config(self, field, key, n=3):
  class PostgresFixtureMixin (line 89) | class PostgresFixtureMixin:
    method arrayfield_config (line 90) | def arrayfield_config(self, field, key, n=1):

FILE: django_dynamic_fixture/fixture_algorithms/random_fixture.py
  class RandomDataFixture (line 23) | class RandomDataFixture(BaseDataFixture, GeoDjangoFixtureMixin, Postgres...
    method random_string (line 24) | def random_string(self, n):
    method integerfield_config (line 28) | def integerfield_config(self, field, key, start=1, end=10 ** 6):
    method smallintegerfield_config (line 31) | def smallintegerfield_config(self, field, key):
    method positiveintegerfield_config (line 35) | def positiveintegerfield_config(self, field, key):
    method positivesmallintegerfield_config (line 38) | def positivesmallintegerfield_config(self, field, key):
    method bigintegerfield_config (line 42) | def bigintegerfield_config(self, field, key):
    method floatfield_config (line 45) | def floatfield_config(self, field, key):
    method decimalfield_config (line 48) | def decimalfield_config(self, field, key):
    method charfield_config (line 56) | def charfield_config(self, field, key):
    method textfield_config (line 63) | def textfield_config(self, field, key):
    method slugfield_config (line 66) | def slugfield_config(self, field, key):
    method commaseparatedintegerfield_config (line 69) | def commaseparatedintegerfield_config(self, field, key):
    method booleanfield_config (line 73) | def booleanfield_config(self, field, key):
    method nullbooleanfield_config (line 76) | def nullbooleanfield_config(self, field, key):
    method datefield_config (line 81) | def datefield_config(self, field, key):
    method timefield_config (line 84) | def timefield_config(self, field, key):
    method datetimefield_config (line 87) | def datetimefield_config(self, field, key):
    method emailfield_config (line 91) | def emailfield_config(self, field, key):
    method urlfield_config (line 94) | def urlfield_config(self, field, key):
    method ipaddressfield_config (line 98) | def ipaddressfield_config(self, field, key):
    method xmlfield_config (line 105) | def xmlfield_config(self, field, key):
    method filepathfield_config (line 109) | def filepathfield_config(self, field, key):
    method filefield_config (line 112) | def filefield_config(self, field, key):
    method imagefield_config (line 115) | def imagefield_config(self, field, key):

FILE: django_dynamic_fixture/fixture_algorithms/sequential_fixture.py
  class AutoDataFiller (line 23) | class AutoDataFiller:
    method __init__ (line 28) | def __init__(self):
    method next (line 33) | def next(self, key):
    method current (line 43) | def current(self, key):
  class SequentialDataFixture (line 49) | class SequentialDataFixture(BaseDataFixture, GeoDjangoFixtureMixin, Post...
    method __init__ (line 51) | def __init__(self):
    method get_value (line 55) | def get_value(self, field, key):
    method integerfield_config (line 59) | def integerfield_config(self, field, key):
    method smallintegerfield_config (line 62) | def smallintegerfield_config(self, field, key):
    method positiveintegerfield_config (line 65) | def positiveintegerfield_config(self, field, key):
    method positivesmallintegerfield_config (line 68) | def positivesmallintegerfield_config(self, field, key):
    method bigintegerfield_config (line 71) | def bigintegerfield_config(self, field, key):
    method floatfield_config (line 74) | def floatfield_config(self, field, key):
    method decimalfield_config (line 77) | def decimalfield_config(self, field, key):
    method charfield_config (line 85) | def charfield_config(self, field, key):
    method textfield_config (line 95) | def textfield_config(self, field, key):
    method slugfield_config (line 98) | def slugfield_config(self, field, key):
    method commaseparatedintegerfield_config (line 101) | def commaseparatedintegerfield_config(self, field, key):
    method booleanfield_config (line 105) | def booleanfield_config(self, field, key):
    method nullbooleanfield_config (line 108) | def nullbooleanfield_config(self, field, key):
    method datefield_config (line 112) | def datefield_config(self, field, key):
    method timefield_config (line 116) | def timefield_config(self, field, key):
    method datetimefield_config (line 120) | def datetimefield_config(self, field, key):
    method emailfield_config (line 125) | def emailfield_config(self, field, key):
    method urlfield_config (line 128) | def urlfield_config(self, field, key):
    method ipaddressfield_config (line 132) | def ipaddressfield_config(self, field, key):
    method xmlfield_config (line 141) | def xmlfield_config(self, field, key):
    method filepathfield_config (line 145) | def filepathfield_config(self, field, key):
    method filefield_config (line 148) | def filefield_config(self, field, key):
    method imagefield_config (line 151) | def imagefield_config(self, field, key):
  class GlobalSequentialDataFixture (line 155) | class GlobalSequentialDataFixture(SequentialDataFixture):
    method get_value (line 156) | def get_value(self, field, key):
  class StaticSequentialDataFixture (line 160) | class StaticSequentialDataFixture(SequentialDataFixture):
    method get_value (line 161) | def get_value(self, field, key):

FILE: django_dynamic_fixture/fixture_algorithms/tests/abstract_test_generic_fixture.py
  class DataFixtureTestCase (line 8) | class DataFixtureTestCase:
    method setUp (line 9) | def setUp(self):
    method test_numbers (line 12) | def test_numbers(self):
    method test_it_must_deal_with_decimal_max_digits (line 21) | def test_it_must_deal_with_decimal_max_digits(self):
    method test_strings (line 27) | def test_strings(self):
    method test_new_truncate_strings_to_max_length (line 33) | def test_new_truncate_strings_to_max_length(self):
    method test_boolean (line 37) | def test_boolean(self):
    method test_date_time_related (line 42) | def test_date_time_related(self):
    method test_formatted_strings (line 47) | def test_formatted_strings(self):
    method test_files (line 53) | def test_files(self):

FILE: django_dynamic_fixture/fixture_algorithms/tests/test_default_fixture.py
  class BaseDataFixtureTestCase (line 20) | class BaseDataFixtureTestCase(TestCase):
    method setUp (line 21) | def setUp(self):
    method test_uuid (line 24) | def test_uuid(self):
  class GeoDjangoFixtureMixin (line 32) | class GeoDjangoFixtureMixin(BaseDataFixture, GeoDjangoFixtureMixin):
  class GeoDjangoDataFixtureTestCase (line 35) | class GeoDjangoDataFixtureTestCase(TestCase):
    method setUp (line 36) | def setUp(self):
    method test_geometryfield_config (line 39) | def test_geometryfield_config(self):
    method test_pointfield_config (line 42) | def test_pointfield_config(self):
    method test_linestringfield_config (line 45) | def test_linestringfield_config(self):
    method test_polygonfield_config (line 48) | def test_polygonfield_config(self):
    method test_multipointfield_config (line 51) | def test_multipointfield_config(self):
    method test_multilinesstringfield_config (line 54) | def test_multilinesstringfield_config(self):
    method test_multipolygonfield_config (line 57) | def test_multipolygonfield_config(self):
    method test_geometrycollectionfield_config (line 60) | def test_geometrycollectionfield_config(self):

FILE: django_dynamic_fixture/fixture_algorithms/tests/test_default_fixture_postgres.py
  class PostgresDataFixtureTestMixin (line 15) | class PostgresDataFixtureTestMixin:
    method test_arrayfield_integer_config (line 16) | def test_arrayfield_integer_config(self):
    method test_arrayfield_char_config (line 21) | def test_arrayfield_char_config(self):
    method test_arrayfield_datetime_config (line 26) | def test_arrayfield_datetime_config(self):
    method test_arrayfield_email_config (line 31) | def test_arrayfield_email_config(self):
  class PostgresSequentialDataFixtureTestCase (line 37) | class PostgresSequentialDataFixtureTestCase(TestCase, PostgresDataFixtur...
    method setUp (line 38) | def setUp(self):
  class PostgresStaticSequentialDataFixtureTestCase (line 43) | class PostgresStaticSequentialDataFixtureTestCase(TestCase, PostgresData...
    method setUp (line 44) | def setUp(self):
  class PostgresRandomDataFixtureTestCase (line 49) | class PostgresRandomDataFixtureTestCase(TestCase, PostgresDataFixtureTes...
    method setUp (line 50) | def setUp(self):
  class PostgresUniqueRandomDataFixtureTestCase (line 55) | class PostgresUniqueRandomDataFixtureTestCase(TestCase, PostgresDataFixt...
    method setUp (line 56) | def setUp(self):

FILE: django_dynamic_fixture/fixture_algorithms/tests/test_random_fixture.py
  class RandomDataFixtureTestCase (line 8) | class RandomDataFixtureTestCase(TestCase, DataFixtureTestCase):
    method setUp (line 9) | def setUp(self):

FILE: django_dynamic_fixture/fixture_algorithms/tests/test_sequential_fixture.py
  class SequentialDataFixtureTestCase (line 9) | class SequentialDataFixtureTestCase(TestCase, DataFixtureTestCase):
    method setUp (line 10) | def setUp(self):
    method test_it_must_fill_integer_fields_sequencially_by_attribute (line 13) | def test_it_must_fill_integer_fields_sequencially_by_attribute(self):
    method test_it_must_fill_string_with_sequences_of_numbers_by_attribute (line 20) | def test_it_must_fill_string_with_sequences_of_numbers_by_attribute(se...
  class StaticSequentialDataFixtureTestCase (line 28) | class StaticSequentialDataFixtureTestCase(TestCase, DataFixtureTestCase):
    method setUp (line 29) | def setUp(self):
    method test_it_must_fill_fields_sequencially_by_attribute_if_field_is_unique (line 32) | def test_it_must_fill_fields_sequencially_by_attribute_if_field_is_uni...
    method test_it_must_fill_fields_with_static_value_by_attribute_if_field_is_not_unique (line 38) | def test_it_must_fill_fields_with_static_value_by_attribute_if_field_i...

FILE: django_dynamic_fixture/fixture_algorithms/tests/test_unique_random_fixture.py
  class RandomDataFixtureTestCase (line 11) | class RandomDataFixtureTestCase(TestCase, DataFixtureTestCase):
    method setUp (line 12) | def setUp(self):
    method test_generated_strings_are_unique (line 15) | def test_generated_strings_are_unique(self):
    method test_generated_signed_integers_are_unique (line 23) | def test_generated_signed_integers_are_unique(self):
    method test_generated_unsigned_integers_are_unique (line 33) | def test_generated_unsigned_integers_are_unique(self):
    method test_warning (line 43) | def test_warning(self):

FILE: django_dynamic_fixture/fixture_algorithms/unique_random_fixture.py
  class UniqueRandomDataFixture (line 28) | class UniqueRandomDataFixture(BaseDataFixture, GeoDjangoFixtureMixin, Po...
    method __init__ (line 36) | def __init__(self):
    method get_counter (line 40) | def get_counter(self, field, key):
    method random_string (line 46) | def random_string(self, field, key, n=None):
    method random_integer (line 56) | def random_integer(self, field, key, signed=True):
    method integerfield_config (line 77) | def integerfield_config(self, field, key):
    method smallintegerfield_config (line 80) | def smallintegerfield_config(self, field, key):
    method bigintegerfield_config (line 83) | def bigintegerfield_config(self, field, key):
    method positiveintegerfield_config (line 86) | def positiveintegerfield_config(self, field, key):
    method positivesmallintegerfield_config (line 89) | def positivesmallintegerfield_config(self, field, key):
    method floatfield_config (line 92) | def floatfield_config(self, field, key):
    method decimalfield_config (line 95) | def decimalfield_config(self, field, key):
    method charfield_config (line 103) | def charfield_config(self, field, key):
    method textfield_config (line 106) | def textfield_config(self, field, key):
    method slugfield_config (line 109) | def slugfield_config(self, field, key):
    method commaseparatedintegerfield_config (line 112) | def commaseparatedintegerfield_config(self, field, key):
    method booleanfield_config (line 116) | def booleanfield_config(self, field, key):
    method nullbooleanfield_config (line 124) | def nullbooleanfield_config(self, field, key):
    method datefield_config (line 135) | def datefield_config(self, field, key):
    method timefield_config (line 139) | def timefield_config(self, field, key):
    method datetimefield_config (line 143) | def datetimefield_config(self, field, key):
    method emailfield_config (line 148) | def emailfield_config(self, field, key):
    method urlfield_config (line 151) | def urlfield_config(self, field, key):
    method ipaddressfield_config (line 155) | def ipaddressfield_config(self, field, key):
    method xmlfield_config (line 162) | def xmlfield_config(self, field, key):
    method filepathfield_config (line 166) | def filepathfield_config(self, field, key):
    method filefield_config (line 169) | def filefield_config(self, field, key):
    method imagefield_config (line 172) | def imagefield_config(self, field, key):

FILE: django_dynamic_fixture/global_settings.py
  class DDFImproperlyConfigured (line 21) | class DDFImproperlyConfigured(Exception):
  function get_ddf_config (line 25) | def get_ddf_config(name, default, cast=None, options=None, msg=''):
  function get_boolean_config (line 39) | def get_boolean_config(config_name, default=False):
  function get_data_fixture (line 43) | def get_data_fixture(default='sequential'):

FILE: django_dynamic_fixture/models_sample_app.py
  class Publisher (line 4) | class Publisher(models.Model):
  class Author (line 7) | class Author(models.Model):
  class Category (line 11) | class Category(models.Model):
  class Book (line 15) | class Book(models.Model):
  class BookPublisher (line 24) | class BookPublisher(models.Model):
  class BookEdition (line 29) | class BookEdition(models.Model):

FILE: django_dynamic_fixture/models_test.py
  class EmptyModel (line 14) | class EmptyModel(models.Model):
    class Meta (line 15) | class Meta:
  class ModelWithNumbers (line 19) | class ModelWithNumbers(models.Model):
    class Meta (line 29) | class Meta:
  class ModelWithStrings (line 34) | class ModelWithStrings(models.Model):
    class Meta (line 41) | class Meta:
  class ModelWithBooleans (line 46) | class ModelWithBooleans(models.Model):
    class Meta (line 52) | class Meta:
  class ModelWithDateTimes (line 57) | class ModelWithDateTimes(models.Model):
    class Meta (line 62) | class Meta:
  class ModelWithBinary (line 67) | class ModelWithBinary(models.Model):
    class Meta (line 69) | class Meta:
  class ModelWithFieldsWithCustomValidation (line 73) | class ModelWithFieldsWithCustomValidation(models.Model):
    class Meta (line 79) | class Meta:
  class ModelWithFileFields (line 83) | class ModelWithFileFields(models.Model):
    class Meta (line 94) | class Meta:
  class ModelWithDefaultValues (line 99) | class ModelWithDefaultValues(models.Model):
    class Meta (line 106) | class Meta:
  class ModelForNullable (line 111) | class ModelForNullable(models.Model):
    class Meta (line 115) | class Meta:
  class ModelForIgnoreList2 (line 120) | class ModelForIgnoreList2(models.Model):
    class Meta (line 124) | class Meta:
  class ModelForIgnoreList (line 129) | class ModelForIgnoreList(models.Model):
    class Meta (line 137) | class Meta:
  class ModelRelated (line 142) | class ModelRelated(models.Model):
    class Meta (line 147) | class Meta:
  class ModelRelatedThrough (line 152) | class ModelRelatedThrough(models.Model):
    class Meta (line 156) | class Meta:
  function default_fk_value (line 159) | def default_fk_value():
  function default_fk_id (line 167) | def default_fk_id():
  class ModelWithRelationships (line 171) | class ModelWithRelationships(models.Model):
    class Meta (line 187) | class Meta:
  class ModelWithCyclicDependency (line 192) | class ModelWithCyclicDependency(models.Model):
    class Meta (line 195) | class Meta:
  class ModelWithCyclicDependency2 (line 200) | class ModelWithCyclicDependency2(models.Model):
    class Meta (line 203) | class Meta:
  class ModelAbstract (line 208) | class ModelAbstract(models.Model):
    class Meta (line 210) | class Meta:
  class ModelParent (line 216) | class ModelParent(ModelAbstract):
    class Meta (line 217) | class Meta:
  class ModelChild (line 222) | class ModelChild(ModelParent):
    class Meta (line 223) | class Meta:
  class ModelChildWithCustomParentLink (line 228) | class ModelChildWithCustomParentLink(ModelParent):
    class Meta (line 231) | class Meta:
  class ModelWithRefToParent (line 236) | class ModelWithRefToParent(models.Model):
    class Meta (line 239) | class Meta:
  class CustomDjangoField (line 244) | class CustomDjangoField(models.IntegerField):
  class CustomDjangoField2 (line 248) | class CustomDjangoField2(models.IntegerField):
  class CustomDjangoFieldMixin (line 252) | class CustomDjangoFieldMixin:
  class CustomDjangoFieldMultipleInheritance (line 256) | class CustomDjangoFieldMultipleInheritance(CustomDjangoFieldMixin, model...
  class NewField (line 260) | class NewField(models.Field):
    method db_type (line 262) | def db_type(self, connection):
  class ModelWithCustomFields (line 266) | class ModelWithCustomFields(models.Model):
    class Meta (line 270) | class Meta:
  class ModelWithCustomFieldsMultipleInheritance (line 275) | class ModelWithCustomFieldsMultipleInheritance(models.Model):
    class Meta (line 279) | class Meta:
  class ModelWithUnsupportedField (line 284) | class ModelWithUnsupportedField(models.Model):
    class Meta (line 287) | class Meta:
  class ModelWithValidators (line 292) | class ModelWithValidators(models.Model):
    class Meta (line 296) | class Meta:
    method clean (line 300) | def clean(self):
  class ModelWithAutoDateTimes (line 305) | class ModelWithAutoDateTimes(models.Model):
    class Meta (line 310) | class Meta:
  class ModelForCopy2 (line 315) | class ModelForCopy2(models.Model):
    class Meta (line 318) | class Meta:
  class ModelForCopy (line 323) | class ModelForCopy(models.Model):
    class Meta (line 330) | class Meta:
  class ModelForLibrary2 (line 335) | class ModelForLibrary2(models.Model):
    class Meta (line 339) | class Meta:
  class ModelForLibrary (line 344) | class ModelForLibrary(models.Model):
    class Meta (line 350) | class Meta:
  class ProxyModelForLibrary (line 355) | class ProxyModelForLibrary(ModelForLibrary):
    class Meta (line 356) | class Meta:
  class ModelWithUniqueCharField (line 362) | class ModelWithUniqueCharField(models.Model):
    class Meta (line 365) | class Meta:
  class ModelWithClean (line 370) | class ModelWithClean(models.Model):
    class Meta (line 373) | class Meta:
    method clean (line 377) | def clean(self):
  class ModelForSignals (line 382) | class ModelForSignals(models.Model):
    class Meta (line 383) | class Meta:
  class ModelForSignals2 (line 388) | class ModelForSignals2(models.Model):
    class Meta (line 389) | class Meta:
  class ModelForFieldPlugins (line 394) | class ModelForFieldPlugins(models.Model):
    class Meta (line 399) | class Meta:
  class ModelWithCommonNames (line 402) | class ModelWithCommonNames(models.Model):
    class Meta (line 405) | class Meta:
  class ModelWithNamedPrimaryKey (line 409) | class ModelWithNamedPrimaryKey(models.Model):
  class ModelForGeoDjango (line 414) | class ModelForGeoDjango(geomodels.Model):
    class Meta (line 423) | class Meta:
  class ModelForUUID (line 427) | class ModelForUUID(models.Model):
    class Meta (line 429) | class Meta:

FILE: django_dynamic_fixture/models_third_party.py
  class ModelForPostgresFields (line 6) | class ModelForPostgresFields(models.Model):
    class Meta (line 9) | class Meta:
  class ModelForPlugins1 (line 17) | class ModelForPlugins1(models.Model):
    class Meta (line 20) | class Meta:
  class ModelForPlugins2 (line 28) | class ModelForPlugins2(models.Model):
    class Meta (line 30) | class Meta:
  class ModelPolymorphic (line 38) | class ModelPolymorphic(PolymorphicModel):
    class Meta (line 39) | class Meta:
  class ModelPolymorphic2 (line 43) | class ModelPolymorphic2(ModelPolymorphic):
    class Meta (line 44) | class Meta:
  class ModelPolymorphic3 (line 48) | class ModelPolymorphic3(ModelPolymorphic):
    class CannotSave (line 49) | class CannotSave(Exception):
    method save (line 52) | def save(self):

FILE: django_dynamic_fixture/script_ddf_checkings.py
  function color (line 8) | def color(color, string):
  function white (line 11) | def white(string):
  function red (line 14) | def red(string):
  function green (line 17) | def green(string):
  function yellow (line 20) | def yellow(string):
  function ddf_check_models (line 24) | def ddf_check_models(application_labels=[], exclude_application_labels=[...
  function console_report (line 52) | def console_report(succeeded, errors):
  function csv_report (line 64) | def csv_report(succeeded, errors):
  function save_csv (line 78) | def save_csv(content, filename):

FILE: django_dynamic_fixture/tests/conftest.py
  function fixed_teardown_test_environment (line 14) | def fixed_teardown_test_environment():

FILE: django_dynamic_fixture/tests/test_ddf.py
  class DDFTestCase (line 16) | class DDFTestCase(TestCase):
    method setUp (line 17) | def setUp(self):
  class NewCreateAModelInstanceTest (line 21) | class NewCreateAModelInstanceTest(DDFTestCase):
    method test_new_create_a_non_saved_instance_of_the_model (line 22) | def test_new_create_a_non_saved_instance_of_the_model(self):
  class GetDealWithPrimaryKeyTest (line 28) | class GetDealWithPrimaryKeyTest(DDFTestCase):
    method test_get_use_database_id_by_default (line 29) | def test_get_use_database_id_by_default(self):
    method test_get_use_given_id (line 34) | def test_get_use_given_id(self):
    method test_get_use_given_named_id (line 39) | def test_get_use_given_named_id(self):
  class NewFullFillAttributesWithAutoDataTest (line 45) | class NewFullFillAttributesWithAutoDataTest(DDFTestCase):
    method test_new_fill_number_fields_with_numbers (line 46) | def test_new_fill_number_fields_with_numbers(self):
    method test_new_fill_string_fields_with_text_type_strings (line 55) | def test_new_fill_string_fields_with_text_type_strings(self):
    method test_new_fill_boolean_fields_with_False_and_None (line 62) | def test_new_fill_boolean_fields_with_False_and_None(self):
    method test_new_fill_time_related_fields_with_current_values (line 67) | def test_new_fill_time_related_fields_with_current_values(self):
    method test_new_fill_formatted_strings_fields_with_basic_values (line 73) | def test_new_fill_formatted_strings_fields_with_basic_values(self):
    method test_new_fill_file_fields_with_basic_strings (line 80) | def test_new_fill_file_fields_with_basic_strings(self):
    method test_new_fill_binary_fields_with_basic_data (line 91) | def test_new_fill_binary_fields_with_basic_data(self):
  class NewFullFillAttributesWithDefaultDataTest (line 100) | class NewFullFillAttributesWithDefaultDataTest(DDFTestCase):
    method test_fill_field_with_default_data (line 101) | def test_fill_field_with_default_data(self):
    method test_fill_field_with_possible_choices (line 105) | def test_fill_field_with_possible_choices(self):
    method test_fill_field_with_default_value_even_if_field_is_foreign_key (line 109) | def test_fill_field_with_default_value_even_if_field_is_foreign_key(se...
    method test_fill_field_with_default_data_and_choices_must_consider_default_data_instead_choices (line 113) | def test_fill_field_with_default_data_and_choices_must_consider_defaul...
    method test_fill_field_with_possible_optgroup_choices (line 117) | def test_fill_field_with_possible_optgroup_choices(self):
  class NewFullFillAttributesWithCustomDataTest (line 122) | class NewFullFillAttributesWithCustomDataTest(DDFTestCase):
    method test_fields_are_filled_with_custom_attributes (line 123) | def test_fields_are_filled_with_custom_attributes(self):
    method test_decimal_can_be_filled_by_an_string (line 128) | def test_decimal_can_be_filled_by_an_string(self):
    method test_fields_can_be_filled_by_functions (line 132) | def test_fields_can_be_filled_by_functions(self):
    method test_invalid_configuration_raise_an_error (line 136) | def test_invalid_configuration_raise_an_error(self):
    method test_bad_data_raise_an_error (line 140) | def test_bad_data_raise_an_error(self):
  class NewIgnoringNullableFieldsTest (line 146) | class NewIgnoringNullableFieldsTest(DDFTestCase):
    method test_new_do_not_fill_nullable_fields_if_we_do_not_want_to (line 147) | def test_new_do_not_fill_nullable_fields_if_we_do_not_want_to(self):
  class NewIgnoreFieldsInIgnoreListTest (line 154) | class NewIgnoreFieldsInIgnoreListTest(DDFTestCase):
    method test_new_do_not_fill_ignored_fields (line 155) | def test_new_do_not_fill_ignored_fields(self):
    method test_get_raise_an_error_if_a_required_field_is_in_ignore_list (line 164) | def test_get_raise_an_error_if_a_required_field_is_in_ignore_list(self):
    method test_ignore_fields_are_propagated_to_self_references (line 169) | def test_ignore_fields_are_propagated_to_self_references(self):
    method test_ignore_fields_are_not_propagated_to_different_references (line 176) | def test_ignore_fields_are_not_propagated_to_different_references(self):
    method test_ignore_fields_are_not_ignored_if_explicitely_given (line 182) | def test_ignore_fields_are_not_ignored_if_explicitely_given(self):
  class NewAlsoCreatesRelatedObjectsTest (line 188) | class NewAlsoCreatesRelatedObjectsTest(DDFTestCase):
    method test_new_fill_foreignkey_fields (line 189) | def test_new_fill_foreignkey_fields(self):
    method test_new_fill_onetoone_fields (line 193) | def test_new_fill_onetoone_fields(self):
    method test_new_deal_with_default_values (line 197) | def test_new_deal_with_default_values(self):
    method test_new_deal_with_id_default_values (line 201) | def test_new_deal_with_id_default_values(self):
  class NewCanCreatesCustomizedRelatedObjectsTest (line 211) | class NewCanCreatesCustomizedRelatedObjectsTest(DDFTestCase):
    method test_customizing_nullable_fields_for_related_objects (line 212) | def test_customizing_nullable_fields_for_related_objects(self):
  class NewDealWithSelfReferencesTest (line 218) | class NewDealWithSelfReferencesTest(DDFTestCase):
    method test_new_create_by_default_no_self_fks (line 219) | def test_new_create_by_default_no_self_fks(self):
    method test_new_create_only_1_lap_in_cycle (line 225) | def test_new_create_only_1_lap_in_cycle(self):
    method test_new_create_with_min_depth_2 (line 231) | def test_new_create_with_min_depth_2(self):
    method test_number_of_fk_cycles_does_not_break_default_non_null_fk (line 238) | def test_number_of_fk_cycles_does_not_break_default_non_null_fk(self):
  class GetFullFilledModelInstanceAndPersistTest (line 244) | class GetFullFilledModelInstanceAndPersistTest(DDFTestCase):
    method test_get_create_and_save_a_full_filled_instance_of_the_model (line 245) | def test_get_create_and_save_a_full_filled_instance_of_the_model(self):
    method test_get_create_and_save_related_fields (line 254) | def test_get_create_and_save_related_fields(self):
  class ManyToManyRelationshipTest (line 264) | class ManyToManyRelationshipTest(DDFTestCase):
    method test_new_ignore_many_to_many_configuratios (line 265) | def test_new_ignore_many_to_many_configuratios(self):
    method test_get_ignore_many_to_many_configuratios (line 270) | def test_get_ignore_many_to_many_configuratios(self):
    method test_many_to_many_configuratios_accept_list_of_dynamic_filters (line 274) | def test_many_to_many_configuratios_accept_list_of_dynamic_filters(self):
    method test_many_to_many_configuratios_accept_list_of_instances (line 280) | def test_many_to_many_configuratios_accept_list_of_instances(self):
    method test_invalid_many_to_many_configuration (line 289) | def test_invalid_many_to_many_configuration(self):
    method test_many_to_many_through (line 293) | def test_many_to_many_through(self):
  class NewDealWithCyclicDependenciesTest (line 303) | class NewDealWithCyclicDependenciesTest(DDFTestCase):
    method test_new_create_by_default_no_cycles (line 304) | def test_new_create_by_default_no_cycles(self):
    method test_new_create_only_1_lap_in_fk_cycle (line 308) | def test_new_create_only_1_lap_in_fk_cycle(self):
    method test_new_create_with_min_depth_2 (line 313) | def test_new_create_with_min_depth_2(self):
  class NewDealWithInheritanceTest (line 319) | class NewDealWithInheritanceTest(DDFTestCase):
    method test_get_must_raise_an_error_if_model_is_abstract (line 320) | def test_get_must_raise_an_error_if_model_is_abstract(self):
    method test_get_must_fill_parent_fields_too (line 324) | def test_get_must_fill_parent_fields_too(self):
    method test_get_must_fill_grandparent_fields_too (line 329) | def test_get_must_fill_grandparent_fields_too(self):
    method test_get_must_ignore_parent_link_attributes_but_the_parent_object_must_be_created (line 335) | def test_get_must_ignore_parent_link_attributes_but_the_parent_object_...
    method test_get_0 (line 344) | def test_get_0(self):
    method test_get_1 (line 350) | def test_get_1(self):
    method test_get_2 (line 357) | def test_get_2(self):
  class ComplexFieldsTest (line 365) | class ComplexFieldsTest(DDFTestCase):
    method test_x (line 366) | def test_x(self):
  class ModelValidatorsTest (line 371) | class ModelValidatorsTest(DDFTestCase):
    method test_it_must_create_if_validation_is_disabled (line 372) | def test_it_must_create_if_validation_is_disabled(self):
    method test_it_must_create_if_there_is_no_validation_errors (line 378) | def test_it_must_create_if_there_is_no_validation_errors(self):
    method test_it_must_raise_a_bad_data_error_if_data_is_not_valid (line 384) | def test_it_must_raise_a_bad_data_error_if_data_is_not_valid(self):
  class ConfigurationValidatorTest (line 391) | class ConfigurationValidatorTest(DDFTestCase):
    method test_it_must_raise_a_bad_data_error_if_data_is_not_valid (line 392) | def test_it_must_raise_a_bad_data_error_if_data_is_not_valid(self):
  class DisableAutoGeneratedDateTimesTest (line 397) | class DisableAutoGeneratedDateTimesTest(DDFTestCase):
    method test_auto_generated_datetimes_must_be_respected_if_nothing_is_specified (line 398) | def test_auto_generated_datetimes_must_be_respected_if_nothing_is_spec...
    method test_it_must_ignore_auto_generated_datetime_if_a_custom_value_is_provided (line 403) | def test_it_must_ignore_auto_generated_datetime_if_a_custom_value_is_p...
    method test_checking_if_implementation_works_for_m2m_fields_too (line 410) | def test_checking_if_implementation_works_for_m2m_fields_too(self):
  class ModelWithCustomValidationTest (line 418) | class ModelWithCustomValidationTest(DDFTestCase):
    method test_ddf_can_not_create_instance_of_models_with_custom_validations (line 419) | def test_ddf_can_not_create_instance_of_models_with_custom_validations...
  class ExceptionsLayoutMessagesTest (line 426) | class ExceptionsLayoutMessagesTest(DDFTestCase):
    method test_UnsupportedFieldError (line 427) | def test_UnsupportedFieldError(self):
    method test_BadDataError (line 434) | def test_BadDataError(self):
    method test_InvalidConfigurationError (line 443) | def test_InvalidConfigurationError(self):
    method test_InvalidManyToManyConfigurationError (line 452) | def test_InvalidManyToManyConfigurationError(self):
    method test_InvalidModelError (line 459) | def test_InvalidModelError(self):
    method test_InvalidModelError_for_common_object (line 466) | def test_InvalidModelError_for_common_object(self):
  class SanityTest (line 475) | class SanityTest(DDFTestCase):
    method test_create_lots_of_models_to_verify_data_unicity_errors (line 476) | def test_create_lots_of_models_to_verify_data_unicity_errors(self):
  class AvoidNameCollisionTest (line 481) | class AvoidNameCollisionTest(DDFTestCase):
    method test_avoid_common_name_instance (line 482) | def test_avoid_common_name_instance(self):
    method test_avoid_common_name_field (line 496) | def test_avoid_common_name_field(self):

FILE: django_dynamic_fixture/tests/test_ddf_checkings.py
  class DDFTestCase (line 8) | class DDFTestCase(TestCase):
    method setUp (line 9) | def setUp(self):
  class TestCheckCompatibility (line 13) | class TestCheckCompatibility(DDFTestCase):
    method test_default (line 14) | def test_default(self):
    method test_teaching_ddf (line 32) | def test_teaching_ddf(self):

FILE: django_dynamic_fixture/tests/test_ddf_copier.py
  class DDFTestCase (line 12) | class DDFTestCase(TestCase):
    method setUp (line 13) | def setUp(self):
  class CopyTest (line 17) | class CopyTest(DDFTestCase):
    method test_it_should_copy_from_model_fields (line 18) | def test_it_should_copy_from_model_fields(self):
    method test_simple_scenario (line 22) | def test_simple_scenario(self):
    method test_order_of_attributes_must_be_superfluous (line 26) | def test_order_of_attributes_must_be_superfluous(self):
    method test_it_should_deal_with_multiple_copiers (line 30) | def test_it_should_deal_with_multiple_copiers(self):
    method test_multiple_copiers_can_depend_of_one_field (line 35) | def test_multiple_copiers_can_depend_of_one_field(self):
    method test_it_should_deal_with_dependent_copiers (line 40) | def test_it_should_deal_with_dependent_copiers(self):
    method test_it_should_deal_with_relationships (line 45) | def test_it_should_deal_with_relationships(self):
    method test_it_should_raise_a_bad_data_error_if_value_is_invalid (line 52) | def test_it_should_raise_a_bad_data_error_if_value_is_invalid(self):
    method test_it_should_raise_a_invalid_configuration_error_if_expression_is_bugged (line 56) | def test_it_should_raise_a_invalid_configuration_error_if_expression_i...
    method test_it_should_raise_a_invalid_configuration_error_if_copier_has_cyclic_dependency (line 62) | def test_it_should_raise_a_invalid_configuration_error_if_copier_has_c...
    method test_it_must_copy_generated_data_mask_too (line 66) | def test_it_must_copy_generated_data_mask_too(self):

FILE: django_dynamic_fixture/tests/test_ddf_custom_fields.py
  class DDFTestCase (line 14) | class DDFTestCase(TestCase):
    method setUp (line 15) | def setUp(self):
  class CustomFieldsTest (line 19) | class CustomFieldsTest(DDFTestCase):
    method test_new_field_that_extends_django_field_must_be_supported (line 20) | def test_new_field_that_extends_django_field_must_be_supported(self):
    method test_new_field_that_extends_django_field_must_be_supported_with_custom_value (line 24) | def test_new_field_that_extends_django_field_must_be_supported_with_cu...
    method test_unsupported_field_is_filled_with_null_if_it_is_possible (line 28) | def test_unsupported_field_is_filled_with_null_if_it_is_possible(self):
    method test_unsupported_field_raise_an_error_if_it_does_not_accept_null_value (line 32) | def test_unsupported_field_raise_an_error_if_it_does_not_accept_null_v...
    method test_new_field_that_double_inherits_django_field_must_be_supported (line 37) | def test_new_field_that_double_inherits_django_field_must_be_supported...
    method test_new_field_that_double_inherits_django_field_must_be_supported_with_custom_value (line 41) | def test_new_field_that_double_inherits_django_field_must_be_supported...
  class NewFullFillAttributesUsingPluginsTest (line 46) | class NewFullFillAttributesUsingPluginsTest(DDFTestCase):
    method test_custom_field_not_registered_must_raise_an_unsupported_field_exception (line 47) | def test_custom_field_not_registered_must_raise_an_unsupported_field_e...
    method test_new_fill_field_with_data_generated_by_plugins_with_dict (line 52) | def test_new_fill_field_with_data_generated_by_plugins_with_dict(self):
    method test_new_fill_field_with_data_generated_by_plugins_with_direct_fuction (line 62) | def test_new_fill_field_with_data_generated_by_plugins_with_direct_fuc...
    method test_json_field_not_registered_must_raise_an_unsupported_field_exception (line 71) | def test_json_field_not_registered_must_raise_an_unsupported_field_exc...
    method test_new_fill_json_field_with_data_generated_by_plugins (line 82) | def test_new_fill_json_field_with_data_generated_by_plugins(self):
  class PostgresCustomFieldsTest (line 102) | class PostgresCustomFieldsTest(DDFTestCase):
    method test_json_field (line 104) | def test_json_field(self):
    method test_json_field_as_null (line 110) | def test_json_field_as_null(self):
    method test_json_field_as_dicts (line 115) | def test_json_field_as_dicts(self):
    method test_json_field_as_lists (line 120) | def test_json_field_as_lists(self):
    method test_json_field_as_strings (line 125) | def test_json_field_as_strings(self):

FILE: django_dynamic_fixture/tests/test_ddf_custom_models.py
  class PolymorphicModelTest (line 11) | class PolymorphicModelTest(TestCase):
    method test_create_polymorphic_model_and_retrieve (line 12) | def test_create_polymorphic_model_and_retrieve(self):
    method test_create_polymorphic_model_2_and_retrieve (line 16) | def test_create_polymorphic_model_2_and_retrieve(self):
    method test_cannot_save (line 20) | def test_cannot_save(self):

FILE: django_dynamic_fixture/tests/test_ddf_geo.py
  class DDFTestCase (line 25) | class DDFTestCase(TestCase):
    method setUp (line 26) | def setUp(self):
  class GeoDjangoFieldsTest (line 31) | class GeoDjangoFieldsTest(DDFTestCase):
    method test_geodjango_fields (line 32) | def test_geodjango_fields(self):

FILE: django_dynamic_fixture/tests/test_ddf_signals.py
  class DDFTestCase (line 13) | class DDFTestCase(TestCase):
    method setUp (line 14) | def setUp(self):
  class PreSaveTest (line 21) | class PreSaveTest(DDFTestCase):
    method test_set_pre_save_receiver (line 22) | def test_set_pre_save_receiver(self):
    method test_pre_save_receiver_must_raise_an_error_if_first_parameter_is_not_a_model_class (line 29) | def test_pre_save_receiver_must_raise_an_error_if_first_parameter_is_n...
    method test_pre_save_receiver_must_raise_an_error_if_it_is_not_a_function (line 34) | def test_pre_save_receiver_must_raise_an_error_if_it_is_not_a_function...
    method test_pre_save_receiver_must_raise_an_error_if_it_is_not_an_only_one_argument_function (line 38) | def test_pre_save_receiver_must_raise_an_error_if_it_is_not_an_only_on...
    method test_pre_save_receiver_must_be_executed_before_saving (line 43) | def test_pre_save_receiver_must_be_executed_before_saving(self):
    method test_bugged_pre_save_receiver_must_raise_an_error (line 52) | def test_bugged_pre_save_receiver_must_raise_an_error(self):
  class PostSaveTest (line 60) | class PostSaveTest(DDFTestCase):
    method test_set_post_save_receiver (line 61) | def test_set_post_save_receiver(self):
    method test_post_save_receiver_must_raise_an_error_if_first_parameter_is_not_a_model_class (line 68) | def test_post_save_receiver_must_raise_an_error_if_first_parameter_is_...
    method test_post_save_receiver_must_raise_an_error_if_it_is_not_a_function (line 73) | def test_post_save_receiver_must_raise_an_error_if_it_is_not_a_functio...
    method test_post_save_receiver_must_raise_an_error_if_it_is_not_an_only_one_argument_function (line 77) | def test_post_save_receiver_must_raise_an_error_if_it_is_not_an_only_o...
    method test_pre_save_receiver_must_be_executed_before_saving (line 82) | def test_pre_save_receiver_must_be_executed_before_saving(self):
    method test_bugged_post_save_receiver_must_raise_an_error (line 91) | def test_bugged_post_save_receiver_must_raise_an_error(self):

FILE: django_dynamic_fixture/tests/test_ddf_teaching_and_lessons.py
  class DDFTestCase (line 14) | class DDFTestCase(TestCase):
    method setUp (line 15) | def setUp(self):
  class TeachAndLessonsTest (line 20) | class TeachAndLessonsTest(DDFTestCase):
    method test_teach_a_default_lesson_for_a_model (line 21) | def test_teach_a_default_lesson_for_a_model(self):
    method test_default_lesson_may_be_overrided_although_it_is_an_anti_pattern (line 26) | def test_default_lesson_may_be_overrided_although_it_is_an_anti_patter...
    method test_it_must_NOT_raise_an_error_if_user_try_to_use_a_not_saved_default_configuration (line 34) | def test_it_must_NOT_raise_an_error_if_user_try_to_use_a_not_saved_def...
    method test_it_must_raise_an_error_if_try_to_set_a_static_value_to_a_field_with_unicity (line 37) | def test_it_must_raise_an_error_if_try_to_set_a_static_value_to_a_fiel...
    method test_it_allows_to_use_masks_as_lessons_for_unique_integer_fields (line 41) | def test_it_allows_to_use_masks_as_lessons_for_unique_integer_fields(s...
    method test_it_allows_to_use_masks_as_lessons_for_unique_char_fields (line 46) | def test_it_allows_to_use_masks_as_lessons_for_unique_char_fields(self):
    method test_it_must_accept_dynamic_values_for_fields_with_unicity (line 51) | def test_it_must_accept_dynamic_values_for_fields_with_unicity(self):
    method test_it_must_NOT_propagate_lessons_for_internal_dependencies (line 54) | def test_it_must_NOT_propagate_lessons_for_internal_dependencies(self):
    method test_it_must_use_lessons_for_internal_dependencies (line 60) | def test_it_must_use_lessons_for_internal_dependencies(self):
    method test_it_uses_lessons_for_base_model_when_creating_a_proxy_model (line 68) | def test_it_uses_lessons_for_base_model_when_creating_a_proxy_model(se...
    method test_it_uses_lessons_for_proxy_models_when_creating_the_base_model (line 74) | def test_it_uses_lessons_for_proxy_models_when_creating_the_base_model...
    method test_it_uses_lessons_for_proxy_models_when_creating_the_proxy_model (line 80) | def test_it_uses_lessons_for_proxy_models_when_creating_the_proxy_mode...
  class TeachingAndCustomLessonsTest (line 111) | class TeachingAndCustomLessonsTest(DDFTestCase):
    method test_a_model_can_have_custom_lessons (line 112) | def test_a_model_can_have_custom_lessons(self):
    method test_custom_lessons_must_not_be_used_if_not_explicity_specified (line 120) | def test_custom_lessons_must_not_be_used_if_not_explicity_specified(se...
    method test_a_model_can_have_many_custom_lessons (line 125) | def test_a_model_can_have_many_custom_lessons(self):
    method test_it_must_raise_an_error_if_user_try_to_use_a_not_saved_configuration (line 135) | def test_it_must_raise_an_error_if_user_try_to_use_a_not_saved_configu...
    method test_default_lesson_and_custom_lesson_must_work_together (line 139) | def test_default_lesson_and_custom_lesson_must_work_together(self):
    method test_default_lesson_and_custom_lesson_must_work_together_for_different_models (line 151) | def test_default_lesson_and_custom_lesson_must_work_together_for_diffe...
  class DDFLibraryTest (line 175) | class DDFLibraryTest(TestCase):
    method setUp (line 176) | def setUp(self):
    method test_add_and_get_configuration_without_string_name (line 179) | def test_add_and_get_configuration_without_string_name(self):
    method test_add_and_get_configuration_with_name (line 197) | def test_add_and_get_configuration_with_name(self):
    method test_clear_config (line 201) | def test_clear_config(self):
    method test_clear (line 212) | def test_clear(self):

FILE: django_dynamic_fixture/tests/test_decorators.py
  class SkipForDatabaseTest (line 8) | class SkipForDatabaseTest(TestCase):
    method setUp (line 9) | def setUp(self):
    method tearDown (line 12) | def tearDown(self):
    method method_postgres (line 17) | def method_postgres(self):
    method test_annotated_method_only_for_postgres (line 20) | def test_annotated_method_only_for_postgres(self):
  class OnlyForDatabaseTest (line 30) | class OnlyForDatabaseTest(TestCase):
    method setUp (line 31) | def setUp(self):
    method tearDown (line 34) | def tearDown(self):
    method method_sqlite3 (line 39) | def method_sqlite3(self):
    method test_annotated_method_skip_for_sqlite3 (line 42) | def test_annotated_method_skip_for_sqlite3(self):

FILE: django_dynamic_fixture/tests/test_django_helper.py
  class DjangoHelperAppsTest (line 11) | class DjangoHelperAppsTest(TestCase):
    method test_get_apps_must_return_all_installed_apps (line 12) | def test_get_apps_must_return_all_installed_apps(self):
    method test_get_apps_may_be_filtered_by_app_names (line 15) | def test_get_apps_may_be_filtered_by_app_names(self):
    method test_get_apps_may_ignore_some_apps (line 19) | def test_get_apps_may_ignore_some_apps(self):
    method test_app_name_must_be_valid (line 23) | def test_app_name_must_be_valid(self):
    method test_get_app_name_must (line 29) | def test_get_app_name_must(self):
    method test_get_models_of_an_app_must (line 33) | def test_get_models_of_an_app_must(self):
  class DjangoHelperModelsTest (line 40) | class DjangoHelperModelsTest(TestCase):
    method test_get_model_name (line 41) | def test_get_model_name(self):
    method test_get_unique_model_name (line 45) | def test_get_unique_model_name(self):
    method test_get_fields_from_model (line 49) | def test_get_fields_from_model(self):
    method test_get_local_fields (line 56) | def test_get_local_fields(self):
    method test_get_field_names_of_model (line 63) | def test_get_field_names_of_model(self):
    method test_get_many_to_many_fields_from_model (line 70) | def test_get_many_to_many_fields_from_model(self):
    method test_is_model_class (line 78) | def test_is_model_class(self):
    method test_is_model_abstract (line 84) | def test_is_model_abstract(self):
    method test_is_model_managed (line 95) | def test_is_model_managed(self):
    method test_model_has_the_field (line 106) | def test_model_has_the_field(self):
  class DjangoHelperFieldsTest (line 117) | class DjangoHelperFieldsTest(TestCase):
    method test_get_unique_field_name (line 118) | def test_get_unique_field_name(self):
    method test_get_related_model (line 124) | def test_get_related_model(self):
    method test_field_is_a_parent_link (line 132) | def test_field_is_a_parent_link(self):
    method test_field_has_choices (line 142) | def test_field_has_choices(self):
    method test_field_has_default_value (line 149) | def test_field_has_default_value(self):
    method test_field_is_unique (line 156) | def test_field_is_unique(self):
    method test_is_key_field (line 163) | def test_is_key_field(self):
    method test_is_relationship_field (line 169) | def test_is_relationship_field(self):
    method test_is_file_field (line 177) | def test_is_file_field(self):
  class PrintFieldValuesTest (line 184) | class PrintFieldValuesTest(TestCase):
    method test_model_not_saved_do_not_raise_an_exception (line 185) | def test_model_not_saved_do_not_raise_an_exception(self):
    method test_model_saved_do_not_raise_an_exception (line 189) | def test_model_saved_do_not_raise_an_exception(self):
    method test_print_accept_list_of_models_too (line 193) | def test_print_accept_list_of_models_too(self):
    method test_print_accept_a_queryset_too (line 198) | def test_print_accept_a_queryset_too(self):

FILE: django_dynamic_fixture/tests/test_fdf.py
  class FileSystemDjangoTestCaseDealWithDirectoriesTest (line 5) | class FileSystemDjangoTestCaseDealWithDirectoriesTest(FileSystemDjangoTe...
    method test_create_temp_directory_must_create_an_empty_directory (line 7) | def test_create_temp_directory_must_create_an_empty_directory(self):
    method test_remove_temp_directory (line 12) | def test_remove_temp_directory(self):
    method test_remove_temp_directory_must_remove_directories_created_out_of_the_testcase_too (line 17) | def test_remove_temp_directory_must_remove_directories_created_out_of_...
    method test_remove_temp_directory_must_remove_their_files_too (line 22) | def test_remove_temp_directory_must_remove_their_files_too(self):
  class FileSystemDjangoTestCaseDealWithTemporaryFilesTest (line 29) | class FileSystemDjangoTestCaseDealWithTemporaryFilesTest(FileSystemDjang...
    method test_create_temp_file_must_create_a_temporary_file_in_an_arbitrary_directory (line 31) | def test_create_temp_file_must_create_a_temporary_file_in_an_arbitrary...
    method test_create_temp_file_must_create_an_empty_temporary_file (line 39) | def test_create_temp_file_must_create_an_empty_temporary_file(self):
    method test_create_temp_file_must_is_ready_to_add_content_to_it (line 43) | def test_create_temp_file_must_is_ready_to_add_content_to_it(self):
  class FileSystemDjangoTestCaseDealWithSpecificTemporaryFilesTest (line 49) | class FileSystemDjangoTestCaseDealWithSpecificTemporaryFilesTest(FileSys...
    method test_create_temp_file_with_name_must_create_a_file_in_an_specific_directory_with_an_specific_name (line 51) | def test_create_temp_file_with_name_must_create_a_file_in_an_specific_...
    method test_create_temp_file_with_name_must_create_an_empty_file (line 61) | def test_create_temp_file_with_name_must_create_an_empty_file(self):
    method test_create_temp_file_with_name_is_ready_to_add_content_to_it (line 66) | def test_create_temp_file_with_name_is_ready_to_add_content_to_it(self):
  class FileSystemDjangoTestCaseCanRenameFilesTest (line 73) | class FileSystemDjangoTestCaseCanRenameFilesTest(FileSystemDjangoTestCase):
    method test_rename_file_must_preserve_the_directory (line 75) | def test_rename_file_must_preserve_the_directory(self):
    method test_rename_file_must_preserve_the_file_content (line 88) | def test_rename_file_must_preserve_the_file_content(self):
  class FileSystemDjangoTestCaseCanRemoveFilesTest (line 98) | class FileSystemDjangoTestCaseCanRemoveFilesTest(FileSystemDjangoTestCase):
    method test_remove_file (line 100) | def test_remove_file(self):
    method test_remove_file_must_remove_files_with_custom_name_too (line 105) | def test_remove_file_must_remove_files_with_custom_name_too(self):
    method test_remove_file_must_remove_files_with_data_too (line 111) | def test_remove_file_must_remove_files_with_data_too(self):
  class FileSystemDjangoTestCaseCanCopyFilesTest (line 118) | class FileSystemDjangoTestCaseCanCopyFilesTest(FileSystemDjangoTestCase):
    method test_copy_file_to_dir_must_not_remove_original_file (line 120) | def test_copy_file_to_dir_must_not_remove_original_file(self):
    method test_copy_file_to_dir_must_preserve_file_content (line 129) | def test_copy_file_to_dir_must_preserve_file_content(self):
  class FileSystemDjangoTestCaseDealWithDjangoFileFieldTest (line 138) | class FileSystemDjangoTestCaseDealWithDjangoFileFieldTest(FileSystemDjan...
    method test_django_file_must_create_a_django_file_object (line 140) | def test_django_file_must_create_a_django_file_object(self):
    method test_django_file_must_create_a_temporary_file_ready_to_add_content (line 145) | def test_django_file_must_create_a_temporary_file_ready_to_add_content...
  class FileSystemDjangoTestCaseTearDownTest (line 154) | class FileSystemDjangoTestCaseTearDownTest(FileSystemDjangoTestCase):
    method test_teardown_must_delete_all_created_files_in_tests (line 156) | def test_teardown_must_delete_all_created_files_in_tests(self):
    method test_teardown_must_delete_files_with_content_too (line 166) | def test_teardown_must_delete_files_with_content_too(self):
    method test_teardown_must_delete_all_created_directories_in_tests (line 174) | def test_teardown_must_delete_all_created_directories_in_tests(self):
  class FileSystemDjangoTestCaseTearDownFrameworkConfigurationTest (line 182) | class FileSystemDjangoTestCaseTearDownFrameworkConfigurationTest(FileSys...
    method tearDown (line 184) | def tearDown(self):
    method test_creating_directory_and_files_for_the_testcase (line 191) | def test_creating_directory_and_files_for_the_testcase(self):

FILE: django_dynamic_fixture/tests/test_global_settings.py
  class AbstractGlobalSettingsTestCase (line 15) | class AbstractGlobalSettingsTestCase(TestCase):
    method tearDown (line 16) | def tearDown(self):
  class CustomDataFixture (line 25) | class CustomDataFixture: pass
  class DDF_DEFAULT_DATA_FIXTURE_TestCase (line 27) | class DDF_DEFAULT_DATA_FIXTURE_TestCase(AbstractGlobalSettingsTestCase):
    method test_not_configured_must_load_default_value (line 28) | def test_not_configured_must_load_default_value(self):
    method test_may_be_an_internal_data_fixture_nick_name (line 32) | def test_may_be_an_internal_data_fixture_nick_name(self):
    method test_may_be_a_path_to_a_custom_data_fixture (line 45) | def test_may_be_a_path_to_a_custom_data_fixture(self):
    method test_if_path_can_not_be_found_it_will_raise_an_exception (line 50) | def test_if_path_can_not_be_found_it_will_raise_an_exception(self):
  class DDF_FILL_NULLABLE_FIELDS_TestCase (line 56) | class DDF_FILL_NULLABLE_FIELDS_TestCase(AbstractGlobalSettingsTestCase):
    method test_not_configured_must_load_default_value (line 57) | def test_not_configured_must_load_default_value(self):
    method test_must_be_a_boolean (line 61) | def test_must_be_a_boolean(self):
    method test_must_raise_an_exception_if_it_is_not_a_boolean (line 66) | def test_must_raise_an_exception_if_it_is_not_a_boolean(self):
  class DDF_IGNORE_FIELDS_TestCase (line 72) | class DDF_IGNORE_FIELDS_TestCase(AbstractGlobalSettingsTestCase):
    method test_not_configured_must_load_default_value (line 73) | def test_not_configured_must_load_default_value(self):
    method test_must_be_a_list_of_strings (line 77) | def test_must_be_a_list_of_strings(self):
    method test_must_raise_an_exception_if_it_is_not_an_list_of_strings (line 82) | def test_must_raise_an_exception_if_it_is_not_an_list_of_strings(self):
  class DDF_FK_MIN_DEPTH_TestCase (line 88) | class DDF_FK_MIN_DEPTH_TestCase(AbstractGlobalSettingsTestCase):
    method test_not_configured_must_load_default_value (line 89) | def test_not_configured_must_load_default_value(self):
    method test_must_be_an_integer (line 93) | def test_must_be_an_integer(self):
    method test_must_raise_an_exception_if_it_is_not_an_integer (line 98) | def test_must_raise_an_exception_if_it_is_not_an_integer(self):
  class DDF_VALIDATE_MODELS_TestCase (line 104) | class DDF_VALIDATE_MODELS_TestCase(AbstractGlobalSettingsTestCase):
    method test_not_configured_must_load_default_value (line 105) | def test_not_configured_must_load_default_value(self):
    method test_must_be_a_boolean (line 109) | def test_must_be_a_boolean(self):
    method test_must_raise_an_exception_if_it_is_not_a_boolean (line 114) | def test_must_raise_an_exception_if_it_is_not_a_boolean(self):

FILE: django_dynamic_fixture/tests/test_mask.py
  class DDFTestCase (line 11) | class DDFTestCase(TestCase):
    method setUp (line 12) | def setUp(self):
  class MaskTests (line 16) | class MaskTests(DDFTestCase):
    method test_it_must_generate_random_numbers (line 17) | def test_it_must_generate_random_numbers(self):
    method test_it_must_generate_lower_ascii_chars (line 21) | def test_it_must_generate_lower_ascii_chars(self):
    method test_it_must_generate_upper_ascii_chars (line 25) | def test_it_must_generate_upper_ascii_chars(self):
    method test_it_must_accept_pure_chars (line 29) | def test_it_must_accept_pure_chars(self):
    method test_it_must_be_able_to_escape_symbols (line 33) | def test_it_must_be_able_to_escape_symbols(self):
    method test_phone_mask (line 37) | def test_phone_mask(self):
    method test_address_mask (line 41) | def test_address_mask(self):

FILE: django_dynamic_fixture/tests/test_sample_app.py
  class SampleAppTestCase (line 8) | class SampleAppTestCase(TestCase):
    method test_publisher (line 9) | def test_publisher(self):
    method test_author (line 13) | def test_author(self):
    method test_category (line 20) | def test_category(self):
    method test_book (line 31) | def test_book(self):
    method test_book_edition (line 43) | def test_book_edition(self):
    method test_book_publisher (line 51) | def test_book_publisher(self):

FILE: django_dynamic_fixture/tests/test_wrappers.py
  class NShortcutTest (line 8) | class NShortcutTest(TestCase):
    method test_shortcut_N (line 9) | def test_shortcut_N(self):
  class GShortcutTest (line 14) | class GShortcutTest(TestCase):
    method test_shortcut_G (line 15) | def test_shortcut_G(self):
  class PShortcutTest (line 20) | class PShortcutTest(TestCase):
    method test_accept_model_instance (line 21) | def test_accept_model_instance(self):
    method test_accepts_list (line 25) | def test_accepts_list(self):
    method test_accepts_tuple (line 28) | def test_accepts_tuple(self):
    method test_accepts_queryset (line 31) | def test_accepts_queryset(self):
  class FShortcutTest (line 35) | class FShortcutTest(TestCase):
    method test_fk (line 36) | def test_fk(self):
    method test_self_fk (line 41) | def test_self_fk(self):
    method test_o2o (line 46) | def test_o2o(self):
    method test_m2m_with_one_element (line 51) | def test_m2m_with_one_element(self):
    method test_m2m_with_many_elements (line 56) | def test_m2m_with_many_elements(self):
    method test_full_example (line 62) | def test_full_example(self):
    method test_two_properties_same_object (line 76) | def test_two_properties_same_object(self):
    method test_using_look_up_alias (line 82) | def test_using_look_up_alias(self):
    method test_using_look_up_alias_two_properties_same_object (line 96) | def test_using_look_up_alias_two_properties_same_object(self):
    method test_using_look_up_alias_two_properties_same_object (line 104) | def test_using_look_up_alias_two_properties_same_object(self):
  class CShortcutTest (line 113) | class CShortcutTest(TestCase):
    method test_copying_from_the_same_model (line 114) | def test_copying_from_the_same_model(self):
    method test_copying_from_a_fk (line 118) | def test_copying_from_a_fk(self):
    method test_copying_from_a_one2one (line 122) | def test_copying_from_a_one2one(self):
    method test_copying_from_a_self_fk (line 126) | def test_copying_from_a_self_fk(self):
    method test_copying_inside_fk (line 130) | def test_copying_inside_fk(self):
    method test_copying_inside_many_to_many (line 134) | def test_copying_inside_many_to_many(self):
  class MShortcutTest (line 140) | class MShortcutTest(TestCase):
    method test_full_data_mask_sample (line 141) | def test_full_data_mask_sample(self):
  class TeachingAndLessonsTest (line 147) | class TeachingAndLessonsTest(TestCase):
    method test_global_lesson (line 148) | def test_global_lesson(self):
  class CreatingMultipleObjectsTest (line 160) | class CreatingMultipleObjectsTest(TestCase):
    method test_new (line 161) | def test_new(self):
    method test_get (line 168) | def test_get(self):
  class LookUpSeparatorTest (line 176) | class LookUpSeparatorTest(TestCase):
    method test_look_up_alias_with_all_params_combination (line 177) | def test_look_up_alias_with_all_params_combination(self):
    method test_look_up_alias_as_f_with_all_params_combination (line 187) | def test_look_up_alias_as_f_with_all_params_combination(self):
    method test_look_up_alias_with_just_one_parameter (line 197) | def test_look_up_alias_with_just_one_parameter(self):
    method test_look_up_alias_with_many_parameters (line 206) | def test_look_up_alias_with_many_parameters(self):
    method test_dont_format_default_dict_values (line 212) | def test_dont_format_default_dict_values(self):
  class PreAndPostSaveTest (line 218) | class PreAndPostSaveTest(TestCase):
    method tearDown (line 219) | def tearDown(self):
    method test_pre_save (line 224) | def test_pre_save(self):
    method test_post_save (line 227) | def test_post_save(self):
  class UsingModelNameInsteadTest (line 231) | class UsingModelNameInsteadTest(TestCase):
    method test_compatibility_for_new (line 232) | def test_compatibility_for_new(self):
    method test_compatibility_for_get (line 236) | def test_compatibility_for_get(self):
    method test_compatibility_for_teach (line 240) | def test_compatibility_for_teach(self):
  class OverrideDataFixture (line 246) | class OverrideDataFixture(TestCase):
    method test_random (line 247) | def test_random(self):
    method test_sequential (line 253) | def test_sequential(self):
    method test_static_sequential (line 259) | def test_static_sequential(self):
    method test_custom_one (line 265) | def test_custom_one(self):
  class Version (line 273) | class Version(TestCase):
    method test_version (line 274) | def test_version(self):

FILE: queries/count_queries_on_save.py
  class Report (line 10) | class Report:
    method __init__ (line 11) | def __init__(self):
    method add_record (line 15) | def add_record(self, app, model, queries_insert, queries_update):
    method add_error (line 18) | def add_error(self, msg):
    method export_csv (line 21) | def export_csv(self, order_by_quantity_queries=False):
  class CountQueriesOnSave (line 32) | class CountQueriesOnSave:
    method __init__ (line 33) | def __init__(self):
    method count_queries_for_model (line 36) | def count_queries_for_model(self, app, model):
    method execute (line 61) | def execute(self, app_labels=[], exclude_app_labels=[]):

FILE: queries/management/commands/count_queries_on_save.py
  class Command (line 8) | class Command(AppCommand):
    method handle (line 33) | def handle(self, *args, **options):
Condensed preview — 84 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (345K chars).
[
  {
    "path": ".coveragerc",
    "chars": 350,
    "preview": "[run]\nsource = django_dynamic_fixture\nomit = */migrations/*\n\n[report]\nexclude_lines =\n    pragma: no cover\n    def __rep"
  },
  {
    "path": ".flake8",
    "chars": 119,
    "preview": "[flake8]\nmax-line-length=200\nexclude=.git,*migrations/*,tmp/*,scripts/*,docs/*,*/tests/*,proto,env/*\nmax-complexity=15\n"
  },
  {
    "path": ".github/FUNDING.yml",
    "chars": 812,
    "preview": "# These are supported funding model platforms\n\ngithub: [paulocheque]\n#patreon: # Replace with a single Patreon username\n"
  },
  {
    "path": ".github/workflows/release.yml",
    "chars": 2731,
    "preview": "name: Building and Testing\n\non:\n  push:\n    branches:\n      - master\n  pull_request:\n    branches:\n      - master\n\njobs:"
  },
  {
    "path": ".gitignore",
    "chars": 490,
    "preview": ".DS_Store\n.idea/\ndist/\nbuild/\ncover/\n.settings\n.project\n.pydevproject\n.settings/org.eclipse.core.resources.prefs\n.settin"
  },
  {
    "path": ".pylintrc",
    "chars": 17867,
    "preview": "[MASTER]\n\n# A comma-separated list of package or module names from where C extensions may\n# be loaded. Extensions are lo"
  },
  {
    "path": ".python-version",
    "chars": 36,
    "preview": "3.7.17\n3.8.17\n3.9.17\n3.10.12\n3.11.4\n"
  },
  {
    "path": ".readthedocs.yaml",
    "chars": 172,
    "preview": "# https://docs.readthedocs.io/en/stable/config-file/v2.html\nversion: 2\n\nbuild:\n  os: ubuntu-22.04\n  tools:\n    python: \""
  },
  {
    "path": "LICENSE.txt",
    "chars": 1706,
    "preview": "MIT license: http://opensource.org/licenses/MIT\n\nCopyright (c) <2013> <Paulo Cheque>\n\nPermission is hereby granted, free"
  },
  {
    "path": "MANIFEST.in",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "Makefile",
    "chars": 3918,
    "preview": "VERSION=4.0.1\n\n# Python env tasks\n\nclean:\n\tclear\n\t@find . -type f -name \"*.py[co]\" -delete\n\t@find . -type d -name \"__pyc"
  },
  {
    "path": "README.md",
    "chars": 3801,
    "preview": "Django Dynamic Fixture\n======================\n\n[![Docs Status](https://readthedocs.org/projects/django-dynamic-fixture/b"
  },
  {
    "path": "ddf/__init__.py",
    "chars": 475,
    "preview": "# Short alias to use: # `from ddf import *` instead of `from django_dynamic_fixture import *`\nfrom django_dynamic_fixtur"
  },
  {
    "path": "django_dynamic_fixture/__init__.py",
    "chars": 8123,
    "preview": "\n\"\"\"\nThis is the facade of all features of DDF.\nModule that contains wrappers and shortcuts (aliases).\n\"\"\"\nimport warnin"
  },
  {
    "path": "django_dynamic_fixture/ddf.py",
    "chars": 30339,
    "preview": "\nimport inspect\nimport logging\nimport re\nimport sys\n\nfrom django.core.files import File\nfrom django.db.models import Fie"
  },
  {
    "path": "django_dynamic_fixture/decorators.py",
    "chars": 718,
    "preview": "\nfrom django.conf import settings\n\n\nDATABASE_ENGINE = settings.DATABASES['default']['ENGINE']\n\nSQLITE3 = 'sqlite3'\nPOSTG"
  },
  {
    "path": "django_dynamic_fixture/django_helper.py",
    "chars": 7751,
    "preview": "\"\"\"\nModule to wrap dirty stuff of django core.\n\"\"\"\nimport django\nfrom django.apps import apps\nfrom django.db import mode"
  },
  {
    "path": "django_dynamic_fixture/fdf.py",
    "chars": 7184,
    "preview": "\nimport os\nimport tempfile\n\nfrom shutil import rmtree, copy2\nfrom django.core.files import File\n\nfrom django.test import"
  },
  {
    "path": "django_dynamic_fixture/fields.py",
    "chars": 1678,
    "preview": "import json\n\nfrom django.conf import settings\nfrom django.contrib.postgres.fields import (\n    JSONField as DjangoJSONFi"
  },
  {
    "path": "django_dynamic_fixture/fixture_algorithms/__init__.py",
    "chars": 562,
    "preview": "from django_dynamic_fixture.fixture_algorithms.sequential_fixture import SequentialDataFixture, StaticSequentialDataFixt"
  },
  {
    "path": "django_dynamic_fixture/fixture_algorithms/default_fixture.py",
    "chars": 2749,
    "preview": "# -*- coding: utf-8 -*-\nfrom datetime import datetime, date, timedelta\nfrom decimal import Decimal\nimport random\nimport "
  },
  {
    "path": "django_dynamic_fixture/fixture_algorithms/random_fixture.py",
    "chars": 3920,
    "preview": "from datetime import datetime, date, timedelta\nfrom decimal import Decimal\nimport random\nimport string\n\nfrom django.core"
  },
  {
    "path": "django_dynamic_fixture/fixture_algorithms/sequential_fixture.py",
    "chars": 5095,
    "preview": "from datetime import datetime, date, timedelta\nfrom decimal import Decimal\nimport threading\n\nfrom django.core.exceptions"
  },
  {
    "path": "django_dynamic_fixture/fixture_algorithms/tests/__init__.py",
    "chars": 1,
    "preview": "\n"
  },
  {
    "path": "django_dynamic_fixture/fixture_algorithms/tests/abstract_test_generic_fixture.py",
    "chars": 3265,
    "preview": "\nfrom django.db import models\n\nfrom datetime import datetime, date, time\nfrom decimal import Decimal\n\n\nclass DataFixture"
  },
  {
    "path": "django_dynamic_fixture/fixture_algorithms/tests/test_default_fixture.py",
    "chars": 2255,
    "preview": "import uuid\n\nfrom django.db import models\nfrom django.conf import settings\nfrom django.core.exceptions import Improperly"
  },
  {
    "path": "django_dynamic_fixture/fixture_algorithms/tests/test_default_fixture_postgres.py",
    "chars": 2662,
    "preview": "from datetime import datetime\n\nfrom django.db import models\nfrom django.test import TestCase\n\nfrom django_dynamic_fixtur"
  },
  {
    "path": "django_dynamic_fixture/fixture_algorithms/tests/test_random_fixture.py",
    "chars": 362,
    "preview": "\nfrom django.test import TestCase\n\nfrom django_dynamic_fixture.fixture_algorithms.tests.abstract_test_generic_fixture im"
  },
  {
    "path": "django_dynamic_fixture/fixture_algorithms/tests/test_sequential_fixture.py",
    "chars": 1794,
    "preview": "from django.db import models\n\nfrom django.test import TestCase\n\nfrom django_dynamic_fixture.fixture_algorithms.tests.abs"
  },
  {
    "path": "django_dynamic_fixture/fixture_algorithms/tests/test_unique_random_fixture.py",
    "chars": 2003,
    "preview": "from warnings import catch_warnings\n\nfrom django.db import models\nfrom django.test import TestCase\n\nfrom django_dynamic_"
  },
  {
    "path": "django_dynamic_fixture/fixture_algorithms/unique_random_fixture.py",
    "chars": 5799,
    "preview": "from datetime import datetime, date, timedelta\nfrom decimal import Decimal\nfrom itertools import chain\nimport random\nimp"
  },
  {
    "path": "django_dynamic_fixture/global_settings.py",
    "chars": 3639,
    "preview": "\n\"\"\"\nModule that contains wrappers and shortcuts.\nThis is the facade of all features of DDF.\n\"\"\"\nimport os\nimport sys\nim"
  },
  {
    "path": "django_dynamic_fixture/models.py",
    "chars": 168,
    "preview": "from django.conf import settings\n\nimport_models = getattr(settings, 'IMPORT_DDF_MODELS', False)\n\nif import_models:\n    f"
  },
  {
    "path": "django_dynamic_fixture/models_sample_app.py",
    "chars": 1356,
    "preview": "from django.db import models\n\n\nclass Publisher(models.Model):\n    name = models.CharField(max_length=100, unique=True)\n\n"
  },
  {
    "path": "django_dynamic_fixture/models_test.py",
    "chars": 13540,
    "preview": "#!/usr/bin/env python\n\n# https://docs.djangoproject.com/en/3.0/ref/models/fields\nimport django\nfrom django.conf import s"
  },
  {
    "path": "django_dynamic_fixture/models_third_party.py",
    "chars": 1518,
    "preview": "from django.db import models\n\n\ntry:\n    from django.contrib.postgres.fields import JSONField\n    class ModelForPostgresF"
  },
  {
    "path": "django_dynamic_fixture/script_ddf_checkings.py",
    "chars": 2517,
    "preview": "import csv\n\nfrom django.db import transaction\n\nfrom django_dynamic_fixture.django_helper import get_apps, get_models_of_"
  },
  {
    "path": "django_dynamic_fixture/tests/__init__.py",
    "chars": 1,
    "preview": "\n"
  },
  {
    "path": "django_dynamic_fixture/tests/conftest.py",
    "chars": 571,
    "preview": "# PyTest file for global set up.\n\n# Django initialisation\nimport django\ndjango.setup()\n\n# Give DB access to PyTests\nimpo"
  },
  {
    "path": "django_dynamic_fixture/tests/test_ddf.py",
    "chars": 22181,
    "preview": "from datetime import datetime, date\nfrom decimal import Decimal\nimport uuid\n\nfrom django.test import TestCase\nimport pyt"
  },
  {
    "path": "django_dynamic_fixture/tests/test_ddf_checkings.py",
    "chars": 1346,
    "preview": "\nfrom django.test import TestCase\n\nfrom django_dynamic_fixture.ddf import DDFLibrary\nfrom django_dynamic_fixture import "
  },
  {
    "path": "django_dynamic_fixture/tests/test_ddf_copier.py",
    "chars": 3059,
    "preview": "from django.test import TestCase\nimport pytest\n\nfrom django_dynamic_fixture.models_test import *\nfrom django_dynamic_fix"
  },
  {
    "path": "django_dynamic_fixture/tests/test_ddf_custom_fields.py",
    "chars": 5178,
    "preview": "from django.conf import settings\n\nfrom django.test import TestCase\nimport pytest\n\nfrom django_dynamic_fixture.models_tes"
  },
  {
    "path": "django_dynamic_fixture/tests/test_ddf_custom_models.py",
    "chars": 756,
    "preview": "from django.test import TestCase\nimport pytest\n\nfrom django_dynamic_fixture.models_test import *\nfrom django_dynamic_fix"
  },
  {
    "path": "django_dynamic_fixture/tests/test_ddf_geo.py",
    "chars": 1489,
    "preview": "from django.conf import settings\nfrom django.core.exceptions import ImproperlyConfigured\n\ntry:\n    from django.contrib.g"
  },
  {
    "path": "django_dynamic_fixture/tests/test_ddf_signals.py",
    "chars": 3918,
    "preview": "from django.test import TestCase\nimport pytest\n\nfrom django_dynamic_fixture.models_test import *\nfrom django_dynamic_fix"
  },
  {
    "path": "django_dynamic_fixture/tests/test_ddf_teaching_and_lessons.py",
    "chars": 10568,
    "preview": "import re\n\nfrom django.test import TestCase\nimport pytest\n\nfrom django_dynamic_fixture.models_test import *\nfrom django_"
  },
  {
    "path": "django_dynamic_fixture/tests/test_decorators.py",
    "chars": 1542,
    "preview": "from unittest import TestCase\n\nfrom django.conf import settings\n\nfrom django_dynamic_fixture import decorators\n\n\nclass S"
  },
  {
    "path": "django_dynamic_fixture/tests/test_django_helper.py",
    "chars": 10875,
    "preview": "\nfrom django.test import TestCase\nfrom django.db import models\nimport pytest\n\nfrom django_dynamic_fixture import N, G\nfr"
  },
  {
    "path": "django_dynamic_fixture/tests/test_fdf.py",
    "chars": 7657,
    "preview": "from django_dynamic_fixture.fdf import *\nfrom django.core.files import File\n\n\nclass FileSystemDjangoTestCaseDealWithDire"
  },
  {
    "path": "django_dynamic_fixture/tests/test_global_settings.py",
    "chars": 4928,
    "preview": "import importlib\n\nfrom django import conf\n\nfrom django.test import TestCase\nimport pytest\n\nfrom django_dynamic_fixture i"
  },
  {
    "path": "django_dynamic_fixture/tests/test_mask.py",
    "chars": 1682,
    "preview": "import re\n\nfrom django.test import TestCase\nimport pytest\n\nfrom django_dynamic_fixture.models_test import *\nfrom django_"
  },
  {
    "path": "django_dynamic_fixture/tests/test_module_ddf_shortcut.py",
    "chars": 308,
    "preview": "\ntry:\n    from ddf import N, G, F, C, P, PRE_SAVE, POST_SAVE\n    from ddf import new, get, fixture, teach, look_up_alias"
  },
  {
    "path": "django_dynamic_fixture/tests/test_sample_app.py",
    "chars": 1958,
    "preview": "import pytest\n\nfrom django.test import TestCase\n\nfrom ddf import *\n\n\nclass SampleAppTestCase(TestCase):\n    def test_pub"
  },
  {
    "path": "django_dynamic_fixture/tests/test_wrappers.py",
    "chars": 12072,
    "preview": "\nfrom django.test import TransactionTestCase as TestCase\n\nfrom django_dynamic_fixture.models_test import EmptyModel, Mod"
  },
  {
    "path": "docs/Makefile",
    "chars": 6770,
    "preview": "# Makefile for Sphinx documentation\n#\n\n# You can set these variables from the command line.\nSPHINXOPTS    =\nSPHINXBUILD "
  },
  {
    "path": "docs/source/_static/coverage.html",
    "chars": 18079,
    "preview": "<!DOCTYPE html>\n<html>\n<head>\n    <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n    <title>Coverag"
  },
  {
    "path": "docs/source/about.rst",
    "chars": 3092,
    "preview": ".. about:\n\nAbout\n*******************************************************************************\n\n.. contents::\n   :loca"
  },
  {
    "path": "docs/source/change_log.rst",
    "chars": 14852,
    "preview": ".. about:\n\nChange Log\n*******************************************************************************\n\n.. contents::\n   "
  },
  {
    "path": "docs/source/conf.py",
    "chars": 8203,
    "preview": "#\n# DDF documentation build configuration file, created by\n# sphinx-quickstart on Mon Sep  1 18:20:45 2014.\n#\n# This fil"
  },
  {
    "path": "docs/source/data.rst",
    "chars": 5740,
    "preview": ".. _data:\n\nField Data Generation\n*******************************************************************************\n\n.. con"
  },
  {
    "path": "docs/source/data_fixtures.rst",
    "chars": 5246,
    "preview": ".. _data_fixtures:\n\nData Fixtures\n*******************************************************************************\n\n.. co"
  },
  {
    "path": "docs/source/ddf.rst",
    "chars": 9146,
    "preview": ".. _ddf:\n\nCore DDF features\n*******************************************************************************\n\n.. contents"
  },
  {
    "path": "docs/source/fdf.rst",
    "chars": 1133,
    "preview": ".. _fdf:\n\nFileSystemDjangoTestCase (New in 1.3.0)\n**********************************************************************"
  },
  {
    "path": "docs/source/index.rst",
    "chars": 929,
    "preview": ".. DDF documentation master file, created by\n   sphinx-quickstart on Mon Sep  1 18:20:45 2014.\n   You can adapt this fil"
  },
  {
    "path": "docs/source/more.rst",
    "chars": 4465,
    "preview": ".. _more:\n\nDDF Extras\n*******************************************************************************\n\n.. contents::\n   "
  },
  {
    "path": "docs/source/overview.rst",
    "chars": 6862,
    "preview": ".. _overview:\n\n\nGetting Started\n*******************************************************************************\n\n.. cont"
  },
  {
    "path": "docs/source/patterns.rst",
    "chars": 1673,
    "preview": ".. _patterns:\n\nPatterns\n*******************************************************************************\n\n.. contents::\n "
  },
  {
    "path": "docs/source/settings.rst",
    "chars": 2391,
    "preview": ".. _settings:\n\nDDF Settings\n===============================================================================\n\n.. contents"
  },
  {
    "path": "manage.py",
    "chars": 654,
    "preview": "#!/usr/bin/env python\ntry:\n    import settings_sqlite # Assumed to be in the same directory.\nexcept ImportError:\n    imp"
  },
  {
    "path": "pytest.ini",
    "chars": 133,
    "preview": "[pytest]\nDJANGO_SETTINGS_MODULE = settings_sqlite\naddopts = --pyargs --create-db --reuse-db --no-migrations\npython_files"
  },
  {
    "path": "queries/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "queries/count_queries_on_save.py",
    "chars": 2440,
    "preview": "\nfrom django_dynamic_fixture import new\n\nfrom django.conf import settings\nfrom django.db import connection\nfrom django i"
  },
  {
    "path": "queries/management/__init__.py",
    "chars": 1,
    "preview": "\n"
  },
  {
    "path": "queries/management/commands/__init__.py",
    "chars": 1,
    "preview": "\n"
  },
  {
    "path": "queries/management/commands/count_queries_on_save.py",
    "chars": 1287,
    "preview": "\nfrom optparse import make_option\n\nfrom django.core.management.base import AppCommand\nfrom queries.count_queries_on_save"
  },
  {
    "path": "requirements-dev.txt",
    "chars": 342,
    "preview": "# Build/Package/Publish\nbuild\ntwine\n\n# Tests and Coverage\npytest\npytest-django\npytest-xdist # Run tests in parallel\npyte"
  },
  {
    "path": "requirements.txt",
    "chars": 197,
    "preview": "# Database Drivers\n#mysql-python\n#psycopg2 # not pypy compatible\n#psycopg2cffi # pypy2+ compatible\n\n# DjangoGEO\ngeopy\n\n#"
  },
  {
    "path": "settings_ddf.py",
    "chars": 1373,
    "preview": "from distutils.version import StrictVersion\nimport django\nDJANGO_VERSION = django.get_version()[0:3]\n\nDEBUG = True\n\nIMPO"
  },
  {
    "path": "settings_mysql.py",
    "chars": 410,
    "preview": "from settings_ddf import *\n\nDDF_TEST_GEODJANGO = True\n\n# MySQL\nDATABASES = {\n    'default': {\n        'ENGINE': 'django."
  },
  {
    "path": "settings_postgres.py",
    "chars": 764,
    "preview": "import os\nfrom settings_ddf import *\n\nDDF_TEST_GEODJANGO = True\n\n# Postgres and PostGis\n# > psql -d ddf -c \"CREATE EXTEN"
  },
  {
    "path": "settings_sqlite.py",
    "chars": 382,
    "preview": "from settings_ddf import *\n\nDDF_TEST_GEODJANGO = False\n\n# SQlite and SpatialLite\n# brew install spatialite-tools\n# brew "
  },
  {
    "path": "setup.py",
    "chars": 1303,
    "preview": "from pathlib import Path\nfrom setuptools import setup, find_packages\n\nVERSION = '4.0.1'\n\ntests_require = []\n\ninstall_req"
  },
  {
    "path": "tox.ini",
    "chars": 545,
    "preview": "[tox]\nenvlist =\n    py38-django40\n    py38-django41\n    py38-django42\n    py39-django40\n    py39-django41\n    py39-djang"
  }
]

About this extraction

This page contains the full source code of the paulocheque/django-dynamic-fixture GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 84 files (322.2 KB), approximately 77.9k tokens, and a symbol index with 805 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!