Vim: Auto-Edit Whatever Tests Cover Your Program

Ovid on 2008-04-29T21:19:02

This is rough and needs a lot of cleaning up, but first, install Johan Lindstrom's Devel::CoverX::Covered. Then go into some directory where you have a test directory and run this bash script (stolen straight from the docs):

#!/bin/bash 

#Clean up from previous test run
cover -delete
          
#Test run with coverage instrumentation
PERL5OPT=-MDevel::Cover prove -r t
         
#Collect covered and caller information
#  Run this _before_ running "cover"
#  Don't run with Devel::Covered enabled
covered runs

#Post process to generate covered database 
cover -report Html_basic

Then, somewhere in your .vimrc (or better yet, a plugin), you have something like this:

au! FileType perl          :call PerlMappings()
au! BufRead,BufNewFile *.t :call PerlTestMappings()

" if it's a .pm file and it's in the t/ directory, we hope
" it's a Test::Class test.  This is fragile :/

au! BufNewFile,BufRead *.pm
    \ if match(bufname('%'), '^t\>') > -1 |
    \     call PerlTestMappings()         |
    \ else                                |
    \     call PerlMappings()             |
    \ endif

function! PerlMappings()
    noremap  ,tc :call Coverage()
    noremap  K :!perldoc   perldoc -f 
endfunction

function! PerlTestMappings()
    noremap  ,t :!prove -vl %
endfunction

function! Coverage()
    let filename = bufname('%')

    if match(filename, '\.t$') > -1
        let command = 'covered by --test_file="'. filename .'"'
    else
        let command = 'covered covering --source_file="'. filename .'"'
    end

    let result  = split( system(command), "\n" )
    let list    = []
    let counter = 1
    for element in result
        let list = list + [ counter . ": " . element ]
        let counter = counter + 1
    endfor
    let file = inputlist(list)
    execute "edit " . result[ file - 1 ]
endfunction

Now, if you're in a Perl module or a test file, you can type ',tc' and get a list of the tests covering the module or modules the test covers. Select the number of the one you want to edit and you automatically edit it.

This needs a lot more work, including much better error checking, but I am happy with the start of this.