4

Is there any way to exclude private methods during testing coverage?

In my .coveragerc I tried:

[report]
exclude_lines = 
    __*

But it seems to exclude methods such as long_method_name

Is ther any way to do it without listing all methdos?

EDIT

I want methods such as __add__ which have simillar syntax to private to be included in the tests.

MaLiN2223
  • 1,290
  • 3
  • 19
  • 40

2 Answers2

8

From the docs:

class MyObject(object):
    def __init__(self):
        blah1()
        blah2()

    def __repr__(self): # pragma: no cover
        return "<MyObject>"

Excluding all private methods with one config option does not make sense IMO - it would lead to wrong assumptions if one looks on the coverage results.

rvf
  • 1,409
  • 2
  • 15
  • 21
dahrens
  • 3,879
  • 1
  • 20
  • 38
  • We are in need to test only public API and not private methods and we got like albot 100 or more of them so writing everywhere `#pragma` is not an option. Is there no hack to do that? – MaLiN2223 Feb 04 '17 at 23:46
  • You could re-design your API calls to inherit from something sensible in another file, put the private methods into those objects, and ignore the file you're now importing. – ti7 Feb 05 '17 at 00:00
4

Your regex was __*, which matches one or more underscores, so it would exclude any line that had any underscores in it. This is not what you want.

This should work to exclude any function definition of a function that begins with double underscores:

[report]
exclude_lines = 
    def __

This seems like a bad idea to me. You need to know if these functions are properly tested. They are called from your public API: how can you claim your public API functions are fully tested if you are not measuring the coverage of the functions they call?

To exclude private methods, but not special methods, you can try a more elaborate regex:

[report]
exclude_lines = 
    def __[^(]*[^_][(]

but this is getting kind of crazy...

Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662
  • It is very close to answet I am looking for, however def __ also excludes methods such as __add__ or __init__ (I will edit my question to include those) which I would like to test. Reasoning for excluding private methods is that I have many of those in GUI (pygame) module which I do not want unit test - I got GUI tests for it. I got multiple config files and in one of them I need to test only public methods :) – MaLiN2223 Feb 05 '17 at 19:15
  • ["I do not unit test private methods. A private method is an implementation detail that should be hidden to the users of the class. Testing private methods breaks encapsulation."](https://stackoverflow.com/a/105021/125507) – endolith Jun 20 '17 at 04:38