Skip to content

Instantly share code, notes, and snippets.

@storborg
Created November 14, 2009 03:56
Show Gist options
  • Select an option

  • Save storborg/234373 to your computer and use it in GitHub Desktop.

Select an option

Save storborg/234373 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
"Run me to check if there's any new code that doesn't have test coverage."
import os
import os.path
import pickle
import re
import git
from coverage import coverage
def get_changed_lines(diff_string):
"""
Given a unified diff, return the line numbers (as ints) in the new version
which have been touched.
"""
ret = set()
lines = {}
for hunk in iter(diff_string.split('\n@@')):
m = re.match(r'\s+-(\d+),(\d+)\s+\+(\d+),(\d+)\s+@@', hunk)
if m:
_, _, start, num = m.groups()
current_line = int(start)
for line in hunk.split('\n')[1:]:
if line.startswith(' '):
# This is a normal context line.
current_line += 1
elif line.startswith('+'):
# We're adding this line.
current_line += 1
lines[current_line] = line[1:]
ret.add(current_line)
return ret, lines
def print_file_summary(path, uncovered, lines):
"""
Print a summary of the uncovered new lines in a given file.
path
Relative path to this file.
uncovered
A set of uncovered line numbers.
lines
A dict of line number (int) -> line text with code lines.
"""
if len(uncovered) > 0:
print "%s:" % path
uncovered = list(uncovered)
uncovered.sort()
prev = uncovered[0]
for n in uncovered:
if n > (prev + 1):
print " ------"
prev = n
print " %d: %s" % (n, lines[n + 1])
# Set up .coverage file data.
cov = coverage(auto_data=True)
cov.data.read()
# Set up git repo object.
cwd = os.getcwd()
repo = git.Repo(cwd)
diffs = git.Diff.list_from_string(repo, repo.git.diff('HEAD', '--'))
for diff in diffs:
path = diff.b_path
if path.endswith('.py'):
touched, lines = get_changed_lines(diff.diff)
_, _, unexecuted, _ = cov.analysis([path])
uncovered = set(unexecuted).intersection(touched)
print_file_summary(path, uncovered, lines)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment