How to ignore PonyORM generator expressions in nose-tests coverage

126 Views Asked by At

I'm using nosetests --cover-erase --with-cover --cover-branches to run my test cases.

I'm using PonyORM to delete set of objects. Below is how my code looks like.

@db_session
def remove_all_stuff(self):
    delete(j for j in MyEntityClass if j.deleted == True)

When I calculate the coverage, even though I execute remove_all_jobs. PonyORM doesn't execute the generator expression inside delete(.

How do I ignore the generator expression and still check that the delete( is called?


What I found.

  1. # pragma: no cover -> cannot be used because I need to cover delete
  2. [report] exclude_lines in .coveragerc also doesn't work for this scenario.
2

There are 2 best solutions below

1
On BEST ANSWER

I've added some other suggestions to the coverage.py issue about this.


Some other possibilities of how to handle this more gracefully:

You can set the coverage.py pragma regex so that some lines are automatically pragma'd:

[report]
partial_branches = 
    pragma: no branch
    \.select\(lambda

Now any line that matches either of the two regexes will be considered partial-branch, so your line is recognized even without a comment.

You can separate the definition of the lambda or generator expression from the line that uses them:

to_select = lambda p: p.nom_d_exercice.lower().startswith(chaine.lower())    # pragma: no branch
return Praticien.select(to_select)

or:

to_delete = (j for j in MyEntityClass if j.deleted == True)  # pragma: no branch
delete(to_delete)

This isolates the non-run code to its own line, so you don't run the risk of turning off coverage measurement on a line that truly needs it.

0
On

You can use the # pragma: no branch directive in this case. This will ignore the generator expression.

@db_session
def remove_all_stuff(self):
    delete(j for j in MyEntityClass if j.deleted == True)  # pragma: no branch

if you are using lambda to select, format those to a new line and use # pragma: no cover

Why this happens?

This is because PonyORM doesn't execute the generator expressions and sometimes lambdas. It generates SQL by decompiling and analysing the abstract syntax tree of these python expressions.

More Info: How Pony (ORM) does its tricks?