Lila25mila
Lila25milaJan. 29, 2019, 2:53 a.m.

How to use Coverage in Django

When you are developing a large project, it is possible to accidentally forget some parts of the code that need to be tested. Coverage.py is a python tool to help you with this.


Installation

Use pip or easy_install as you like

pip install coverage 
Starting and uninstalling

To run in a Django project, use the command:

overage run --source='.' manage.py test the-app-you-want-to-test

This command will fill in ".coverage" which is located in COVERAGE_FILE and then you can see the results or report. If you need to delete the received data, use the command:

coverage erase
For one file

If you only want to test Python code, then you need to do:

coverage run your_program.py arg1 arg2 arg3

There are several additional options that you can look at link .
You can learn about templates in the plugins section .

View result

If you want to display results on the command line:

coverage report

For clearer and more convenient reports:

coverage html

To know exactly what part of your code is covered by tests, use the following command:

coverage annotate -d directory-where-to-put-annotated-files

The program will generate the same source code file with additional syntax:

- A line with ">" means that it has been executed.

- A line starting with "!" means that it was not executed.

- A line starting with "-" means that the line has been excluded from the coverage statistics.

Good level of coverage

Good coverage is usually 90%. However, if the result is 100%, this may be a bad signal, since it may be a matter of coverage, and not the quality of the tests.

A few tips:

- Be careful with the quality of your tests.

- Don't slow down your developer speeds for the sake of coverage.

- Use coverage to find unverified code and decide if it deserves coverage.

Exclude code

Sometimes we need to exclude some code that doesn't need coverage. There are several options:

- Specifying files to exclude and skip in .coveragerc.

- Writing in one line of the comment block.

 # pragma: no cover

For example, if you want to exclude generated code from coverage because it must be supported by the generation tool:

def generated_code():   # pragma: no cover
   do_something()

More info at Coverage.py documentation.

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
AD

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:50points,
  • Rating points-4
m

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:80points,
  • Rating points4
m

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:20points,
  • Rating points-10
Last comments
ИМ
Игорь МаксимовNov. 22, 2024, 11:51 a.m.
Django - Tutorial 017. Customize the login page to Django Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
Evgenii Legotckoi
Evgenii LegotckoiOct. 31, 2024, 2:37 p.m.
Django - Lesson 064. How to write a Python Markdown extension Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
A
ALO1ZEOct. 19, 2024, 8:19 a.m.
Fb3 file reader on Qt Creator Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html
ИМ
Игорь МаксимовOct. 5, 2024, 7:51 a.m.
Django - Lesson 064. How to write a Python Markdown extension Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
d
dblas5July 5, 2024, 11:02 a.m.
QML - Lesson 016. SQLite database and the working with it in QML Qt Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
Now discuss on the forum
Evgenii Legotckoi
Evgenii LegotckoiJune 24, 2024, 3:11 p.m.
добавить qlineseries в функции Я тут. Работы оень много. Отправил его в бан.
t
tonypeachey1Nov. 15, 2024, 6:04 a.m.
google domain [url=https://google.com/]domain[/url] domain [http://www.example.com link title]
NSProject
NSProjectJune 4, 2022, 3:49 a.m.
Всё ещё разбираюсь с кешем. В следствии прочтения данной статьи. Я принял для себя решение сделать кеширование свойств менеджера модели LikeDislike. И так как установка evileg_core для меня не была возможна, ибо он писался…
9
9AnonimOct. 25, 2024, 9:10 a.m.
Машина тьюринга // Начальное состояние 0 0, ,<,1 // Переход в состояние 1 при пустом символе 0,0,>,0 // Остаемся в состоянии 0, двигаясь вправо при встрече 0 0,1,>…

Follow us in social networks