On Mon, Sep 04, 2006 at 05:15:24PM +0900, Suraj N. Kurapati wrote:
> 
> How can I use rcov from an already running Ruby program?
> 
> I'm running a Ruby interpreter that is embedded within a C program.
> This situation is the inverse of how rcov is presently used: rcov is
> used to run *.rb files instead of ruby.
> 
> So, I want to be able to write something like "require
> 'rcov/runner'" and have rcov do it do its thing on the currently
> running Ruby program. This is like running unit tests by simply
> doing "require 'test/unit'" (which has a Kernel#at_exit statement
> that runs all the tests before the program terminates).

I've never used rcov with an embedded Ruby interpreter, but something like
this should work:

rcov/runner.rb:


require 'rcov' require 'rbconfig' # try to load xx, but don't give up if it's not available begin require 'xx' rescue LoadError end begin require 'rcov/report' rescue NameError # hack to make textual reports work in the absence of xx-0.1.0 # Rcov::HTMLCoverage cannot be used without it though end rcov_analyzer = Rcov::CodeCoverageAnalyzer.new at_exit do rcov_analyzer.remove_hook rcov_analyzer.dump_coverage_info([Rcov::TextReport.new]) # use Rcov::HTMLCoverage above to generate HTML reports; the formatters admit # a number of options, listed in rcov's RDoc documentation. end rcov_analyzer.install_hook
If you save that as rcov/runner.rb in your $LOAD_PATH, you will be able to $ cat a.rb srand(0) c = 0 d = 1 10.times do |i| if rand % (i + 10) c += i d += 1 end end puts "blergh" if c > 4*d # stuff puts "yep" else puts "nope" # more stuff end puts "Done: #{c+d}" $ ruby -I ../head/lib -rrcov/runner a.rb blergh yep Done: 56 +----------------------------------------------------+-------+-------+--------+ | File | Lines | LOC | COV | +----------------------------------------------------+-------+-------+--------+ |a.rb | 20 | 16 | 81.2% | +----------------------------------------------------+-------+-------+--------+ |Total | 20 | 16 | 81.2% | +----------------------------------------------------+-------+-------+--------+ 81.2% 1 file(s) 20 Lines 16 LOC In your case, you can require 'rcov/runner' in the embedded interpreter, and the code loaded/parsed from that moment on will be monitored. If you cannot load rcov/runner before the code you want to analyze is parsed, it might still be possible to make it work by doing SCRIPT_LINES__ = {} unless defined? SCRIPT_LINES__ early on. Of course, only the code executed after rcov/runner is loaded would be analyzed in that case. rcov/runner.rb seems a good idea and I'd want to add it to the next release; do you have any suggestions regarding the interface or the default options? Dumping a textual report like the above one seems to make sense as it is akin to Test::Unit's output. Thanks, -- Mauricio Fernandez - http://eigenclass.org - singular Ruby