is it possible to make a code coverage assertion in python?

  • Last Update :
  • Techknowledgy :

Usage is simple:

$ coverage run my_program.py arg1 arg2

Than see the results with coverage report

$ coverage report - m
Name Stmts Miss Cover Missing
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
my_program 20 4 80 % 33 - 35, 39
my_other_module 56 6 89 % 17 - 23
   -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
   TOTAL 76 10 87 %

Suggestion : 2

Last Updated : 16 Aug, 2021,GATE CS 2021 Syllabus

Output : 

Traceback(most recent call last):
   File "/home/bafc2f900d9791144fbf59f477cd4059.py", line 4, in
assert y != 0, "Invalid Operation"
# denominator can 't be 0
AssertionError: Invalid Operation

Suggestion : 3

You should test as much of your code as possible. Code in functions only runs when the function is called, and code in branches, such as if blocks, only runs when the condition is met. You want to make sure that each function is tested with data that covers each branch.,To test that the page renders successfully, a simple request is made and checked for a 200 OK status_code. If rendering failed, Flask would return a 500 Internal Server Error code.,The only behavior that can change is passing test config. If config is not passed, there should be some default configuration, otherwise the configuration should be overridden.,The test code is located in the tests directory. This directory is next to the flaskr package, not inside it. The tests/conftest.py file contains setup functions called fixtures that each test will use. Tests are in Python modules that start with test_, and each test function in those modules also starts with test_.

$ pip install pytest coverage
INSERT INTO user(username, password)
VALUES
   ('test', 'pbkdf2:sha256:50000$TCI4GzcX$0de171a4f4dac32e3364c7ddc7c14f3e2fa61f2d17574483f7ffbb431b4acb2f'),
   ('other', 'pbkdf2:sha256:50000$kJPKsz6N$d2d4784f1b030a9761f5ccaeeaca413f27f2ecb76d6168407af962ddce849f79');

INSERT INTO post(title, body, author_id, created)
VALUES
   ('test title', 'test' || x '0a' || 'body', 1, '2018-01-01 00:00:00');
import os
import tempfile

import pytest
from flaskr
import create_app
from flaskr.db
import get_db, init_db

with open(os.path.join(os.path.dirname(__file__), 'data.sql'), 'rb') as f:
   _data_sql = f.read().decode('utf8')

@pytest.fixture
def app():
   db_fd, db_path = tempfile.mkstemp()

app = create_app({
   'TESTING': True,
   'DATABASE': db_path,
})

with app.app_context():
   init_db()
get_db().executescript(_data_sql)

yield app

os.close(db_fd)
os.unlink(db_path)

@pytest.fixture
def client(app):
   return app.test_client()

@pytest.fixture
def runner(app):
   return app.test_cli_runner()
from flaskr
import create_app

def test_config():
   assert not create_app().testing
assert create_app({
   'TESTING': True
}).testing

def test_hello(client):
   response = client.get('/hello')
assert response.data == b 'Hello, World!'
import sqlite3

import pytest
from flaskr.db
import get_db

def test_get_close_db(app):
   with app.app_context():
   db = get_db()
assert db is get_db()

with pytest.raises(sqlite3.ProgrammingError) as e:
   db.execute('SELECT 1')

assert 'closed' in str(e.value)
def test_init_db_command(runner, monkeypatch):
   class Recorder(object):
   called = False

def fake_init_db():
   Recorder.called = True

monkeypatch.setattr('flaskr.db.init_db', fake_init_db)
result = runner.invoke(args = ['init-db'])
assert 'Initialized' in result.output
assert Recorder.called

Suggestion : 4

Once our mock has been used (real.method in this example) it has methods and attributes that allow you to make assertions about how it has been used.,After it has been used you can make assertions about the access using the normal mock methods and attributes:,From here it is a simple step to configure and then make assertions about chained calls. Of course another alternative is writing your code in a more testable way in the first place…,Both assert_called_with and assert_called_once_with make assertions about the most recent call. If your mock is going to be called several times, and you want to make assertions about all those calls you can use call_args_list:

>>> real = SomeClass()
>>> real.method = MagicMock(name='method')
>>> real.method(3, 4, 5, key='value')
<MagicMock name='method()' id='...'>
>>> class ProductionClass:
   ...def method(self):
   ...self.something(1, 2, 3)
   ...def something(self, a, b, c):
   ...pass
   ...
   >>>
   real = ProductionClass() >>>
   real.something = MagicMock() >>>
   real.method() >>>
   real.something.assert_called_once_with(1, 2, 3)
>>> class ProductionClass:
   ...def closer(self, something):
   ...something.close()
   ...
>>> real = ProductionClass() >>>
   mock = Mock() >>>
   real.closer(mock) >>>
   mock.close.assert_called_with()
>>> def some_function():
   ...instance = module.Foo()
   ...
   return instance.method()
      ...
      >>>
      with patch('module.Foo') as mock:
      ...instance = mock.return_value
      ...instance.method.return_value = 'the result'
      ...result = some_function()
      ...assert result == 'the result'
>>> mock = MagicMock(name='foo')
>>> mock
<MagicMock name='foo' id='...'>
   >>> mock.method
   <MagicMock name='foo.method' id='...'>