Run Django Tests

  • Getting a Django Application to 100% Test Coverage. Code coverage is a simple tool for checking which lines of your application code are run by your test suite. 100% coverage is a laudable goal, as it means every line is run at least once. Coverage.py is the Python tool for measuring code coverage.
  • A test runner is a class defining a runtests method. Django ships with a DiscoverRunner class that defines the default Django testing behavior. This class defines the runtests entry point, plus a selection of other methods that are used by runtests to set up, execute and tear down the test suite.
Latest version

Released:

Online Python IDE is a web-based tool powered by ACE code editor. This tool can be used to learn, build, run, test your python script. You can open the script from your local and continue to build using this IDE.

Test django schema and data migrations, including ordering

Django Test Runner

Project description

Features

  • Allows to test django schema and data migrations
  • Allows to test both forward and rollback migrations
  • Allows to test the migrations order
  • Allows to test migration names
  • Fully typed with annotations and checked with mypy, PEP561 compatible
  • Easy to start: has lots of docs, tests, and tutorials

Read the announcing post.See real-world usage example.

Installation

We support several django versions:

  • 1.11
  • 2.2
  • 3.0
  • 3.1

Other versions might work too, but they are not officially supported.

Testing django migrations

Testing migrations is not a frequent thing in django land.But, sometimes it is totally required. When?

Django Test Database

Django

When we do complex schema or data changesand what to be sure that existing data won't be corrupted.We might also want to be sure that all migrations can be safely rolled back.And as a final touch we want to be sure that migrationsare in the correct order and have correct dependencies.

Testing forward migrations

To test all migrations we have a Migrator class.

It has three methods to work with:

  • .apply_initial_migration() which takes app and migration names to generatea state before the actual migration happens. It creates the before stateby applying all migrations up to and including the ones passed as an argument.

  • .apply_tested_migration() which takes app and migration names to perform theactual migration

  • .reset() to clean everything up after we are done with testing

So, here's an example:

That was an example of a forward migration.

Backward migration

The thing is that you can also test backward migrations.Nothing really changes except migration names that you pass and your logic:

Testing migrations ordering

Sometimes we also want to be sure that our migrations are in the correct order.And all our dependecies = [...] are correct.

To achieve that we have plan.py module.

That's how it can be used:

This way you can be sure that migrationsand apps that depend on each other will be executed in the correct order.

Test framework integrations 🐍

We support several test frameworks as first-class citizens.That's a testing tool after all!

Note that the Django post_migrate signal's receiver list is cleared atthe start of tests and restored afterwards. If you need to test yourown post_migrate signals then attach/remove them during a test.

pytest

We ship django-test-migrations with a pytest pluginthat provides two convinient fixtures:

  • migrator_factory that gives you an opportunityto create Migrator classes for any database
  • migrator instance for the 'default' database

That's how it can be used:

unittest

We also ship an integration with the built-in unittest framework.

Here's how it can be used:

Choosing only migrations tests

In CI systems it is important to get instant feedback. Running tests thatapply database migration can slow down tests execution, so it is often a goodidea to run standard, fast, regular unit tests without migrations in parallelwith slower migrations tests.

pytest

django_test_migrations adds migration_test marker to each test usingmigrator_factory or migrator fixture.To run only migrations test, use -m option:

unittest

django_test_migrations adds migration_testtagto every MigratorTestCase subclass.To run only migrations tests, use --tag option:

Django Checks

django_test_migrations comes with 2 groups of Django's checks for:

  • detecting migrations scripts automatically generated names
  • validating some subset of database settings

Testing migration names

django generates migration names for you when you run makemigrations.And these names are bad (read more about why it is bad)!Just look at this: 0004_auto_20191119_2125.py

What does this migration do? What changes does it have?

One can also pass --name attribute when creating migrations, but it is easy to forget.

We offer an automated solution: django checkthat produces an error for each badly named migration.

Add our check into your INSTALLED_APPS:

And then in your CI run:

This way you will be safe from wrong names in your migrations.

Do you have a migrations that cannot be renamed? Add them to the ignore list:

And we won't complain about them.

Or you can completely ignore entire app:

Database configuration

Add our check to INSTALLED_APPS:

Then just run check management command in your CI like listed in sectionabove.

Credits

This project is based on work of other awesome people:

License

MIT.

Release historyRelease notifications | RSS feed

1.1.0

1.0.0

0.3.0

0.2.0

Run

0.1.0

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Files for django-test-migrations, version 1.1.0
Filename, sizeFile typePython versionUpload dateHashes
Filename, size django_test_migrations-1.1.0-py3-none-any.whl (25.2 kB) File type Wheel Python version py3 Upload dateHashes
Filename, size django-test-migrations-1.1.0.tar.gz (21.5 kB) File type Source Python version None Upload dateHashes
Close

Hashes for django_test_migrations-1.1.0-py3-none-any.whl

Hashes for django_test_migrations-1.1.0-py3-none-any.whl
AlgorithmHash digest
SHA2567ea17dac1a0b0c8084681899c6563d85f4262832f2fbb0c6240b12e554333934
MD552e8d6d65a119e313a3f5489f5699b16
BLAKE2-256ee87170f1a51f6829cba1f5b5e864371d6ab5544b3bbff36203583ce7566ec33
Close

Hashes for django-test-migrations-1.1.0.tar.gz

Hashes for django-test-migrations-1.1.0.tar.gz
AlgorithmHash digest
SHA25627c0127552920bbdc339a84de360f1792abc8c353e2c8d2b86af92dc1ade6703
MD577b7acfbdceb59b9ac7090afcc71fc98
BLAKE2-256ca3e11942a8769c47035dd55e26c8404d212015dc0503057263059b1ae8ecc33

Use this dialog to create a run/debug configuration for Django tests.

Configuration tab

ItemDescription
Target

Specify the target to be executed. If the field is left empty, it means that all the tests in all the applications specified in INSTALLED_APPS will be executed.

  • If you want to run tests in a certain application, specify the application name.

  • To run a specific test case, specify its name after the application name, delimited with a dot.

  • To run a single test method within a test case, add the test method name after dot.

Same rules apply to the doctests contained in the test targets. The test label is used as the path to the test method or class to be executed. If there is function with a doctest, or a class with a class-level doctest, you can invoke that test by appending the name of the test method or class to the label.

Custom settings

If this checkbox is selected, Django test will run with the specified custom settings, rather than with the default ones.

Specify the fully qualified name of the file that contains Django settings. You can either type it manually, in the text field to the right, or click the browse button, and select one in the dialog that opens.

If this checkbox is not selected, Django test will run with the default settings, defined in the Settings field of the Django page. The text field is disabled.

Options

If this checkbox is selected, it is possible to specify parameters to be passed to the Django tests. Type the list of parameters in the text field to the right, prepending parameters with '--' and using spaces as delimiters. For example:

If this checkbox is not selected, the text field is disabled.

Environment
ProjectClick this list to select one of the projects, opened in the same PyCharm window, where this run/debug configuration should be used. If there is only one open project, this field is not displayed.
Environment variables

This field shows the list of environment variables. If the list contains several variables, they are delimited with semicolons.

To fill in the list, click the browse button, or press Shift+Enter and specify the desired set of environment variables in the Environment Variables dialog.

To create a new variable, click , and type the desired name and value.

You might want to populate the list with the variables stored as a series of records in a text file, for example:
Variable1 = Value1 Variable2 = Value2
Just copy the list of variables from the text file and click Paste () in the Environmental Variables dialog. The variables will be added to the table. Click Ok to complete the task. At any time, you can select all variables in the Environment Variables dialog, click Copy , and paste them into a text file.
Python Interpreter

Select one of the pre-configured Python interpreters from the list.

When PyCharm stops supporting any of the outdated Python versions, the corresponding Python interpreter is marked as unsupported.

Interpreter optionsIn this field, specify the command-line options to be passed to the interpreter. If necessary, click , and type the string in the editor.
Working directory

Specify a directory to be used by the running task.

  • When a default run/debug configuration is created by the keyboard shortcut Ctrl+Shift+F10, or by choosing Run from the context menu of a script, the working directory is the one that contains the executable script. This directory may differ from the project directory.

  • When this field is left blank, the bin directory of the PyCharm installation will be used.

Add content roots to PYTHONPATHSelect this checkbox to add all content roots of your project to the environment variable PYTHONPATH;
Add source roots to PYTHONPATHSelect this checkbox to add all source roots of your project to the environment variable PYTHONPATH;
Docker container settings

This field only appears when a Docker-based remote interpreter is selected for a project..

Click to open the dialog and specify the following settings:

Options
  • Publish all ports: Expose all container ports to the host. This corresponds to the option --publish-all.

  • Port bindings: Specify the list of port bindings. Similar to using the -p option with docker run.

  • Volume bindings: Use this field to specify the bindings between the special folders- volumes and the folders of the computer, where the Docker daemon runs. This corresponds to the -v option. See Managing data in containers for details.

  • Environment variables: Use this field to specify the list of environment variables and their values. This corresponds to the -e option. Refer to the page ENV (environment variables) for details.

  • Run options: Use this field to specify the Docker command-line options.

Click to expand the tables. Click , , or to make up the lists.

Docker Compose

This field only appears when a Docker Compose-based remote interpreter is selected.

Commands and options

You can use the following commands of the Docker Compose Command-Line Interface:

CommandsSupported Options
up — Builds, creates, starts, and attaches to containers for a service.--build, --abort-on-container-exit, --timeout TIMEOUT, --exit-code-from SERVICE, --scale SERVICE=NUM..., SERVICE...
run — Runs a one-time command against a service. See the reference docs.--name NAME, --entrypoint CMD, -l, --label KEY=VAL, -u, --user=', --rm, -p, --publish=[], --service-ports, --use-aliases, -v, --volume=[].
exec — Runs arbitrary commands in your services.--privileged, -u, --user USER, --index=index.
Command Preview

You can expand this field to preview the complete command string.

Example: if you enter the following combination in the Commands and options field:

up --build exec --user jetbrains

the preview output should looks as follows:

docker-compose -f C:PyCharm-2019.2Demosdjangodocker-masterdocker-compose.yml -f <override configuration file> up --build exec --user jetbrains

Logs tab

Use this tab to specify which log files generated while running or debugging should be displayed in the console, that is, on the dedicated tabs of the Run or Debug tool window.

ItemDescription
Is ActiveSelect checkboxes in this column to have the log entries displayed in the corresponding tabs in the Run tool window or Debug tool window.
Log File Entry

The read-only fields in this column list the log files to show. The list can contain:

  • Full paths to specific files.

  • Aliases to substitute for full paths or patterns. These aliases are also displayed in the headers of the tabs where the corresponding log files are shown.

    If a log entry pattern defines more than one file, the tab header shows the name of the file instead of the log entry alias.

Skip ContentSelect this checkbox to have the previous content of the selected log skipped.
Save console output to fileSelect this checkbox to save the console output to the specified location. Type the path manually, or click the browse button and point to the desired location in the dialog that opens.
Show console when a message is printed to standard output streamSelect this checkbox to activate the output console and bring it forward if an associated process writes to Standard.out.
Show console when a message is printed to standard error streamSelect this checkbox to activate the output console and bring it forward if an associated process writes to Standard.err.
Click this button to open the Edit Log Files Aliases dialog where you can select a new log entry and specify an alias for it.
Click this button to edit the properties of the selected log file entry in the Edit Log Files Aliases dialog.
Click this button to remove the selected log entry from the list.
Click this button to edit the select log file entry. The button is available only when an entry is selected.

Common settings

When you edit a run configuration (but not a run configuration template), you can specify the following options:

Item

Description

Name

Specify a name for the run/debug configuration to quickly identify it when editing or running the configuration, for example, from the Run popup Alt+Shift+F10.

Allow parallel run

Select to allow running multiple instances of this run configuration in parallel.

By default, it is disabled, and when you start this configuration while another instance is still running, PyCharm suggests to stop the running instance and start another one. This is helpful when a run/debug configuration consumes a lot of resources and there is no good reason to run multiple instances.

Store as project file

Save the file with the run configuration settings to share it with other team members. The default location is .idea/runConfigurations. However, if you do not want to share the .idea directory, you can save the configuration to any other directory within the project.

By default, it is disabled, and PyCharm stores run configuration settings in .idea/workspace.xml.

Toolbar

The tree view of run/debug configurations has a toolbar that helps you manage configurations available in your project as well as adjust default configurations templates.

ItemShortcutDescription
Alt+InsertCreate a run/debug configuration.
Alt+DeleteDelete the selected run/debug configuration. Note that you cannot delete default configurations.
Ctrl+DCreate a copy of the selected run/debug configuration. Note that you create copies of default configurations.
The button is displayed only when you select a temporary configuration. Click this button to save a temporary configuration as permanent.

Move into new folder / Create new folder. You can group run/debug configurations by placing them into folders.

To create a folder, select the configurations within a category, click , and specify the folder name. If only a category is in focus, an empty folder is created.

Then, to move a configuration into a folder, between the folders or out of a folder, use drag or and buttons.

To remove grouping, select a folder and click .

Click this button to sort configurations in the alphabetical order.

Before launch

In this area, you can specify tasks to be performed before starting the selected run/debug configuration. The tasks are performed in the order they appear in the list.

ItemShortcutDescription
Alt+Insert

Click this icon to add one of the following available tasks:

  • Run External tool: select to run an external application. In the dialog that opens, select one or multiple applications you want to run. If it is not defined in PyCharm yet, add its definition. For more information, see External tools and External Tools.

  • Run Another Configuration: select to execute another run/debug configuration. In the dialog that opens, select the configuration to be run.

  • Launch Web Browser: select this option to have a browser started. In the dialog that opens, select the type of the browser and provide the start URL. Also, specify if you want the browser be launched with JavaScript debugger.

  • Run File Watchers: select this option to have PyCharm apply all the currently active File Watchers.

  • Run Grunt task: select this option to run a Grunt task.

    In the Grunt task dialog that opens, specify the Gruntfile.js where the required task is defined, select the task to execute, and specify the arguments to pass to the Grunt tool.

    Specify the location of the Node.js interpreter, the parameters to pass to it, and the path to the grunt-cli package.

  • Run gulp task: select this option to run a Gulp task.

    In the Gulp task dialog that opens, specify the Gulpfile.js where the required task is defined, select the task to execute, and specify the arguments to pass to the Gulp tool.

    Specify the location of the Node.js interpreter, the parameters to pass to it, and the path to the gulp package.

  • Run npm script: select this option to execute an npm script.

    In the NPM Script dialog that opens, specify the npm run/debug configuration settings.
  • Start React Native Bundler: select this option to run the bundler automatically, as part of a running or debugging session. by default, this is done through react-native start. If your application uses Expo, you need to run the development server via the start npm task. To do that, click , then in the Configure React Native dialog, choose npm script and select start from the list.

  • Compile TypeScript: select to run the built-in TypeScript compiler and thus make sure that all the changes you made to your TypeScript code are reflected in the generated JavaScript files. In the TypeScript Compile Settings dialog that opens, select or clear the Check errors checkbox to configure the behaviour of the compiler in case any errors are detected:

    • If the Check errors checkbox is selected, the compiler will show all the errors and the run configuration will not start.

    • If the Check errors checkbox is cleared, the compiler will show all the detected errors but the run configuration still will be launched.

  • Generate CoffeeScript Source Maps: select this option to generate the source maps for your CoffeeScript sources. In the dialog that opens, specify where your CoffeeScript source files are located.

  • Run Remote External Tool: adds a remote SSH external tool.

Alt+DeleteClick this icon to remove the selected task from the list.
EnterClick this icon to edit the selected task. Make the necessary changes in the dialog that opens.
/ Alt+Up/ Alt+DownClick these icons to move the selected task one line up or down in the list. The tasks are performed in the order that they appear in the list.
Show this pageSelect this checkbox to show the run/debug configuration settings prior to actually starting the run/debug configuration.
Activate tool window

By default this checkbox is selected and the Run or the Debug tool window opens when you start the run/debug configuration.

Otherwise, if the checkbox is cleared, the tool window is hidden. However, when the configuration is running, you can open the corresponding tool window for it yourself by pressing Alt+4 or Alt+5.