How to exclude codes under `if __name__ == '__main__':` from SonarQube test coverage

Viewed 1280

I have some requirement that at least 80% of the line coverage need to be achieved. I have some file where a large portion of the code is under if __name__ == '__main__': which need not to be tested.

How can I instruct SonarQube to exclude that portion of code from test coverage. I have seen there are options to exclude files and module using sonar.exclusions and sonar.coverage.exclusions. It would be a great help for me to exclude some parts of a file. For example, I want to exclude everything in the if __name__ == '__main__': block below from sonarQube:

#Test Everything inside this method
def do_something():
  # Some code

# Do not test and include the following codes in the SonarQube coverage
if __name__ == '__main__':
  # A lot of codes for running different functions of this module
2 Answers

I have found solution to the problem. That's why I am adding for other to be helped. We have used pytest and coverage to compute the coverage report. SonarQube just read that coverage report. To exclude some line we have add the following inline comment after that line:

# pragma: no cover

For example the line print("Hello World") will be excluded from the test coverage report,

if __name__=="__main__":
    print("Hello World") # pragma: no cover

I would say to first explore the options offered by the code coverage tool you are using.

As for Sonar, most language analyzers exclude the line of code that has //NOSONAR at the end of it. This works for rule violations for sure. You may try out if it works for code coverage as well. Even if it works you will have to put it on every line of code under if __name__ == '__main__':.
For the documentation on this, you may refer to https://docs.sonarqube.org/latest/faq/#header-1

This is the best what I could think of ..:)

Related