From 84e866dc026e4c3db3ee37f00e64a6be9d198aef Mon Sep 17 00:00:00 2001 From: Thomas Sawyer Date: Sat, 21 Nov 2026 17:26:06 -0500 Subject: [PATCH] Rebuild Minitap on Minitest's plugin system Minitap is now a plain Minitest plugin: it registers itself when required, takes --tapy and --tapj, and the format can be chosen in a test helper with Minitap.tapy! or Minitap.tapj!. It no longer depends on minitest-reporter-api, which replaced Minitest.run with a copy from 2013, and it works with Minitest 5.11 to 6. The reporter is rewritten. It labels cases by test class instead of Minitest::Result, locates failures in the test file on Ruby 3.4 and newer, reports skips as omit, and names the error raised instead of Minitest's wrapper. Packaging is a plain gemspec with GitHub Actions, testing Ruby 2.7 to 4.0 against Minitest 5 and 6. The retirement notice is removed. Co-Authored-By: Claude Fable 5.2 --- .gemspec | 307 ----------- .github/workflows/ci.yml | 44 ++ .gitignore | 6 - .index | 66 --- .travis.yml | 12 - Assembly | 31 -- Gemfile | 4 + HISTORY.md | 41 ++ MANIFEST | 13 - README.md | 180 +++---- Rakefile | 22 + demo/01_tapy.md | 100 ++++ demo/02_tapj.md | 32 ++ demo/03_spec.md | 45 ++ demo/04_helper.md | 109 ++++ demo/05_details.md | 127 +++++ demo/06_tapout.md | 44 ++ demo/applique/cli.rb | 67 --- demo/applique/run.rb | 48 ++ demo/fixtures/tapy.yml | 78 --- demo/minispec.md | 96 ---- demo/minitest.md | 94 ---- lib/minitap.rb | 94 +++- lib/minitap/autorun.rb | 9 +- lib/minitap/ignore_callers.rb | 5 - lib/minitap/minitest5.rb | 885 ------------------------------- lib/minitap/reporter.rb | 294 ++++++++++ lib/minitap/version.rb | 3 + lib/minitest/minitap_plugin.rb | 42 +- minitap.gemspec | 39 ++ var/authors | 2 - var/copyrights | 2 - var/description | 1 - var/name | 1 - var/organization | 1 - var/repositories | 2 - var/requirements | 8 - var/resources | 7 - var/summary | 1 - var/title | 1 - var/version | 1 - work/minitest4/Gemfile | 10 - work/minitest4/applique/ae.rb | 1 - work/minitest4/applique/cli.rb | 43 -- work/minitest4/fixtures/tapy.yml | 78 --- work/minitest4/minitest.md | 94 ---- work/test_example.rb | 39 -- 47 files changed, 1136 insertions(+), 2093 deletions(-) delete mode 100644 .gemspec create mode 100644 .github/workflows/ci.yml delete mode 100644 .index delete mode 100644 .travis.yml delete mode 100644 Assembly delete mode 100644 MANIFEST create mode 100644 Rakefile create mode 100644 demo/01_tapy.md create mode 100644 demo/02_tapj.md create mode 100644 demo/03_spec.md create mode 100644 demo/04_helper.md create mode 100644 demo/05_details.md create mode 100644 demo/06_tapout.md delete mode 100644 demo/applique/cli.rb create mode 100644 demo/applique/run.rb delete mode 100644 demo/fixtures/tapy.yml delete mode 100644 demo/minispec.md delete mode 100644 demo/minitest.md delete mode 100644 lib/minitap/ignore_callers.rb delete mode 100644 lib/minitap/minitest5.rb create mode 100644 lib/minitap/reporter.rb create mode 100644 lib/minitap/version.rb create mode 100644 minitap.gemspec delete mode 100644 var/authors delete mode 100644 var/copyrights delete mode 100644 var/description delete mode 100644 var/name delete mode 100644 var/organization delete mode 100644 var/repositories delete mode 100644 var/requirements delete mode 100644 var/resources delete mode 100644 var/summary delete mode 100644 var/title delete mode 100644 var/version delete mode 100644 work/minitest4/Gemfile delete mode 100644 work/minitest4/applique/ae.rb delete mode 100644 work/minitest4/applique/cli.rb delete mode 100644 work/minitest4/fixtures/tapy.yml delete mode 100644 work/minitest4/minitest.md delete mode 100644 work/test_example.rb diff --git a/.gemspec b/.gemspec deleted file mode 100644 index ea0db60..0000000 --- a/.gemspec +++ /dev/null @@ -1,307 +0,0 @@ -# encoding: utf-8 - -require 'yaml' -require 'pathname' - -module Indexer - - # Convert index data into a gemspec. - # - # Notes: - # * Assumes all executables are in bin/. - # * Does not yet handle default_executable setting. - # * Does not yet handle platform setting. - # * Does not yet handle required_ruby_version. - # * Support for rdoc entries is weak. - # - class GemspecExporter - - # File globs to include in package --unless a manifest file exists. - FILES = ".index .yardopts alt bin data demo ext features lib man spec test try* [A-Z]*.*" unless defined?(FILES) - - # File globs to omit from FILES. - OMIT = "Config.rb" unless defined?(OMIT) - - # Standard file patterns. - PATTERNS = { - :root => '{.index,Gemfile}', - :bin => 'bin/*', - :lib => 'lib/{**/}*', #.rb', - :ext => 'ext/{**/}extconf.rb', - :doc => '*.{txt,rdoc,md,markdown,tt,textile}', - :test => '{test,spec}/{**/}*.rb' - } unless defined?(PATTERNS) - - # For which revision of indexer spec is this converter intended? - REVISION = 2013 unless defined?(REVISION) - - # - def self.gemspec - new.to_gemspec - end - - # - attr :metadata - - # - def initialize(metadata=nil) - @root_check = false - - if metadata - root_dir = metadata.delete(:root) - if root_dir - @root = root_dir - @root_check = true - end - metadata = nil if metadata.empty? - end - - @metadata = metadata || YAML.load_file(root + '.index') - - if @metadata['revision'].to_i != REVISION - warn "This gemspec exporter was not designed for this revision of index metadata." - end - end - - # - def has_root? - root ? true : false - end - - # - def root - return @root if @root || @root_check - @root_check = true - @root = find_root - end - - # - def manifest - return nil unless root - @manifest ||= Dir.glob(root + 'manifest{,.txt}', File::FNM_CASEFOLD).first - end - - # - def scm - return nil unless root - @scm ||= %w{git hg}.find{ |m| (root + ".#{m}").directory? }.to_sym - end - - # - def files - return [] unless root - @files ||= \ - if manifest - File.readlines(manifest). - map{ |line| line.strip }. - reject{ |line| line.empty? || line[0,1] == '#' } - else - list = [] - Dir.chdir(root) do - FILES.split(/\s+/).each do |pattern| - list.concat(glob(pattern)) - end - OMIT.split(/\s+/).each do |pattern| - list = list - glob(pattern) - end - end - list - end.select{ |path| File.file?(path) }.uniq - end - - # - def glob_files(pattern) - return [] unless root - Dir.chdir(root) do - Dir.glob(pattern).select do |path| - File.file?(path) && files.include?(path) - end - end - end - - def patterns - PATTERNS - end - - def executables - @executables ||= \ - glob_files(patterns[:bin]).map do |path| - File.basename(path) - end - end - - def extensions - @extensions ||= \ - glob_files(patterns[:ext]).map do |path| - File.basename(path) - end - end - - def name - metadata['name'] || metadata['title'].downcase.gsub(/\W+/,'_') - end - - def homepage - page = ( - metadata['resources'].find{ |r| r['type'] =~ /^home/i } || - metadata['resources'].find{ |r| r['name'] =~ /^home/i } || - metadata['resources'].find{ |r| r['name'] =~ /^web/i } - ) - page ? page['uri'] : false - end - - def licenses - metadata['copyrights'].map{ |c| c['license'] }.compact - end - - def require_paths - paths = metadata['paths'] || {} - paths['load'] || ['lib'] - end - - # - # Convert to gemnspec. - # - def to_gemspec - if has_root? - Gem::Specification.new do |gemspec| - to_gemspec_data(gemspec) - to_gemspec_paths(gemspec) - end - else - Gem::Specification.new do |gemspec| - to_gemspec_data(gemspec) - to_gemspec_paths(gemspec) - end - end - end - - # - # Convert pure data settings. - # - def to_gemspec_data(gemspec) - gemspec.name = name - gemspec.version = metadata['version'] - gemspec.summary = metadata['summary'] - gemspec.description = metadata['description'] - - metadata['authors'].each do |author| - gemspec.authors << author['name'] - - if author.has_key?('email') - if gemspec.email - gemspec.email << author['email'] - else - gemspec.email = [author['email']] - end - end - end - - gemspec.licenses = licenses - - requirements = metadata['requirements'] || [] - requirements.each do |req| - next if req['optional'] - next if req['external'] - - name = req['name'] - groups = req['groups'] || [] - - version = gemify_version(req['version']) - - if groups.empty? or groups.include?('runtime') - # populate runtime dependencies - if gemspec.respond_to?(:add_runtime_dependency) - gemspec.add_runtime_dependency(name,*version) - else - gemspec.add_dependency(name,*version) - end - else - # populate development dependencies - if gemspec.respond_to?(:add_development_dependency) - gemspec.add_development_dependency(name,*version) - else - gemspec.add_dependency(name,*version) - end - end - end - - # convert external dependencies into gemspec requirements - requirements.each do |req| - next unless req['external'] - gemspec.requirements << ("%s-%s" % req.values_at('name', 'version')) - end - - gemspec.homepage = homepage - gemspec.require_paths = require_paths - gemspec.post_install_message = metadata['install_message'] - end - - # - # Set gemspec settings that require a root directory path. - # - def to_gemspec_paths(gemspec) - gemspec.files = files - gemspec.extensions = extensions - gemspec.executables = executables - - if Gem::VERSION < '1.7.' - gemspec.default_executable = gemspec.executables.first - end - - gemspec.test_files = glob_files(patterns[:test]) - - unless gemspec.files.include?('.document') - gemspec.extra_rdoc_files = glob_files(patterns[:doc]) - end - end - - # - # Return a copy of this file. This is used to generate a local - # .gemspec file that can automatically read the index file. - # - def self.source_code - File.read(__FILE__) - end - - private - - def find_root - root_files = patterns[:root] - if Dir.glob(root_files).first - Pathname.new(Dir.pwd) - elsif Dir.glob("../#{root_files}").first - Pathname.new(Dir.pwd).parent - else - #raise "Can't find root of project containing `#{root_files}'." - warn "Can't find root of project containing `#{root_files}'." - nil - end - end - - def glob(pattern) - if File.directory?(pattern) - Dir.glob(File.join(pattern, '**', '*')) - else - Dir.glob(pattern) - end - end - - def gemify_version(version) - case version - when /^(.*?)\+$/ - ">= #{$1}" - when /^(.*?)\-$/ - "< #{$1}" - when /^(.*?)\~$/ - "~> #{$1}" - else - version - end - end - - end - -end - -Indexer::GemspecExporter.gemspec \ No newline at end of file diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..196ba95 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,44 @@ +name: CI + +on: + push: + pull_request: + workflow_dispatch: + # Monthly, to catch breakage from new Ruby or Minitest releases + # when nothing has been pushed. + schedule: + - cron: '0 6 1 * *' + +permissions: + contents: read + +jobs: + test: + name: Ruby ${{ matrix.ruby }}, Minitest ${{ matrix.minitest || 'latest' }} + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + include: + - { ruby: '2.7' } + - { ruby: '3.0' } + - { ruby: '3.1' } + - { ruby: '3.2' } + - { ruby: '3.3' } + - { ruby: '3.4' } + - { ruby: '4.0' } + # Minitest 6 needs Ruby 3.2, so the rows above use Minitest 5 + # up to Ruby 3.1 and Minitest 6 after. These cover the rest. + - { ruby: '2.7', minitest: '5.11.3' } + - { ruby: '3.4', minitest: '~> 5.0' } + - { ruby: '4.0', minitest: '~> 5.0' } + env: + MINITEST_VERSION: ${{ matrix.minitest }} + steps: + - uses: actions/checkout@v4 + - uses: ruby/setup-ruby@v1 + with: + ruby-version: ${{ matrix.ruby }} + bundler-cache: true + - name: Demos + run: bundle exec qed -Ilib demo/ diff --git a/.gitignore b/.gitignore index 8fa0d22..d75bbdf 100644 --- a/.gitignore +++ b/.gitignore @@ -1,13 +1,7 @@ *.gem *.lock -DEMO.md -.ergo/digest .yardoc doc/ log/ -man/**/*.1 -man/**/*.html pkg/ tmp/ -web/ -work/sandbox diff --git a/.index b/.index deleted file mode 100644 index 1fcf8ad..0000000 --- a/.index +++ /dev/null @@ -1,66 +0,0 @@ ---- -revision: 2013 -type: ruby -sources: -- var -authors: -- name: trans - email: transfire@gmail.com -organizations: [] -requirements: -- version: 0.3.0+ - name: tapout -- version: 5.0~ - name: minitest -- version: 0.0.2+ - name: minitest-reporter-api -- groups: - - test - development: true - name: qed -- groups: - - test - development: true - name: ae -- groups: - - build - development: true - name: ergo -conflicts: [] -alternatives: [] -resources: -- type: home - uri: http://rubyworks.github.com/minitap - label: Homepage -- type: docs - uri: http://rubydoc.info/gems/minitap - label: Documentation -- type: code - uri: http://github.com/rubyworks/minitap - label: Source Code -- type: bugs - uri: http://github.com/rubyworks/minitap/issues - label: Issue Tracker -- type: mail - uri: http://groups.google.com/group/rubyworks-mailinglist - label: Mailing List -repositories: -- name: upstream - scm: git - uri: git://github.com/rubyworks/minitap.git -categories: [] -copyrights: -- holder: Rubyworks - year: '2011' - license: BSD-2-Clause -customs: [] -paths: - lib: - - lib -name: minitap -title: MiniTap -summary: TAP-Y/J reporters for MiniTest -description: MiniTap provides a MiniTest TAP-Y/J report format suitable for use with - TAPOUT. -version: 0.5.3 -date: '2013-11-20' diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index bfc922b..0000000 --- a/.travis.yml +++ /dev/null @@ -1,12 +0,0 @@ ---- -language: ruby -script: "bundle exec qed demo" -rvm: - - 1.8.7 - - 1.9.3 - - 2.0.0 - - rbx - - rbx-19mode - - jruby - - jruby-19mode - diff --git a/Assembly b/Assembly deleted file mode 100644 index a4a5434..0000000 --- a/Assembly +++ /dev/null @@ -1,31 +0,0 @@ ---- -gem: - active : true - -github: - gh_pages: web - -qed: - files: demo - -qedoc: - files: demo - title: MiniTAP Demonstrandum - output: QED.md - -dnote: - title: Developer's Notes - labels: ~ - output: log/notes.html - active: true - -vclog: - output: - - log/changes.html - - log/history.html - -email: - mailto: - - ruby-talk@ruby-lang.org - - rubyworks-mailinglist@googlegroups.com - diff --git a/Gemfile b/Gemfile index 3be9c3c..1968995 100644 --- a/Gemfile +++ b/Gemfile @@ -1,2 +1,6 @@ source "https://rubygems.org" gemspec + +# To test against a particular Minitest, e.g. MINITEST_VERSION='~> 5.0'. +version = ENV['MINITEST_VERSION'].to_s +gem 'minitest', version unless version.empty? diff --git a/HISTORY.md b/HISTORY.md index d1205a3..ab4e660 100644 --- a/HISTORY.md +++ b/HISTORY.md @@ -1,5 +1,46 @@ # RELEASE HISTORY +## Unreleased + +Minitap works with current Minitest again, including Minitest 6, and is +now a plain Minitest plugin. It needs Minitest 5.11 or newer and Ruby +2.7 or newer. + +Changes: + +* Work with Minitest 6. The dependency was `~> 5.0`, so Minitap couldn't + be installed alongside it. +* Use Minitest's plugin system only. Minitap registers itself as a plugin + when it is required, and no longer depends on `minitest-reporter-api`, + which replaced `Minitest.run` with a copy from 2013. +* Choose the format in code with `Minitap.tapy!`, `Minitap.tapj!` or + `Minitap.format = :tapy`. `Minitest.reporter = Minitap::TapY` no longer + does anything. +* `require 'minitap/autorun'` works again. It printed nothing and exited + with an error. +* Label a case with the name of its test class. With Minitest 5.11 and + newer every case was labelled `Minitest::Result`. +* Give the location of a failure in the test file. On Ruby 3.4 and newer + it was given as a line in Minitest's own `assertions.rb`. +* Report a skipped test with the status `omit`, which is what TAP-Y/J + specifies. It was `skip`, which Tapout took for something else. +* Report an error with the class and message of the error that was + raised, not of Minitest's wrapper around it. +* The count at the start of the stream follows Minitest's `--exclude` + option as well as `--name`, and the final total is the number of tests + that ran. +* Tests run in the order the seed gives them without Minitap. Counting + the tests used to disturb it. +* A record has no `subtype` when there is nothing to say, where it had + an empty one. +* The reporters are `Minitap::TapY` and `Minitap::TapJ`, subclasses of + `Minitap::Reporter`. `Minitest::TapY`, `Minitest::TapJ` and + `Minitest::Minitap` are gone, as is the `$RUBY_IGNORE_CALLERS` global. +* Require Tapout 0.5 or newer. +* Replace the old packaging (`.index`, `.gemspec`, `Assembly`, `MANIFEST`, + `var/`) with a plain `minitap.gemspec`, and Travis with GitHub Actions, + testing Ruby 2.7 to 4.0 with Minitest 5 and 6. + ## 0.5.3 | 2013-11-20 Small change made to ensure that output i/o is un sync mode. diff --git a/MANIFEST b/MANIFEST deleted file mode 100644 index df61d24..0000000 --- a/MANIFEST +++ /dev/null @@ -1,13 +0,0 @@ -#!mast .index .ruby .yardopts bin lib man spec test *.md *.txt -.index -.yardopts -lib/minitap/autorun.rb -lib/minitap/ignore_callers.rb -lib/minitap/minitest5.rb -lib/minitap.rb -lib/minitest/minitap_plugin.rb -NOTICE.md -README.md -HISTORY.md -DEMO.md -LICENSE.txt diff --git a/README.md b/README.md index 325b0fd..cf16511 100644 --- a/README.md +++ b/README.md @@ -1,157 +1,142 @@ -> **This project is retired.** -> -> Minitap made Minitest write TAP-Y or TAP-J for -> [Tapout](https://github.com/rubyworks/tapout). It was written for -> Minitest 5.0 and can't be installed with Minitest 6. With later -> Minitest 5 releases it still runs, but labels every test case -> `Minitest::Result` and reports a failure's location inside Minitest. -> -> Tapout itself is maintained. It reads plain TAP as well as TAP-Y and -> TAP-J, and [Rubytest](https://github.com/rubyworks/rubytest) writes -> both of the latter. -> -> This repository preserves Minitap, last released as 0.5.3 in 2013. It -> is no longer maintained. The gem remains on RubyGems, as does its -> companion minitest-reporter-api. - ---- - # Minitap -[Website](http://rubyworks.github.com/minitap) | -[Documentation](http://rubydoc.info/gems/minitap/frames) | -[Report Issue](http://github.com/rubyworks/minitap/issues) | -[Source Code](http://github.com/rubyworks/minitap) +[Documentation](https://rubydoc.info/gems/minitap) | +[Report Issue](https://github.com/rubyworks/minitap/issues) | +[Source Code](https://github.com/rubyworks/minitap) -[![Build Status](https://travis-ci.org/rubyworks/minitap.png)](https://travis-ci.org/rubyworks/minitap) -[![Gem Version](https://badge.fury.io/rb/minitap.png)](http://badge.fury.io/rb/minitap)     -[![Flattr Me](http://api.flattr.com/button/flattr-badge-large.png)](http://flattr.com/thing/324911/Rubyworks-Ruby-Development-Fund) +[![CI](https://github.com/rubyworks/minitap/actions/workflows/ci.yml/badge.svg)](https://github.com/rubyworks/minitap/actions/workflows/ci.yml) +[![Gem Version](https://badge.fury.io/rb/minitap.svg)](https://badge.fury.io/rb/minitap) # About -The MiniTap project provides a TAP-Y and TAP-J output reporters for -the MiniTest test framework --the test framework that comes standard -with Ruby 1.9+. +Minitap is a [Minitest](https://github.com/minitest/minitest) plugin that +reports test results in TAP-Y or TAP-J. Those are the formats that +[Tapout](https://github.com/rubyworks/tapout) reads, so with Minitap a +Minitest suite can be shown in any of Tapout's report formats. -See [TAPOUT](http://rubyworks.github.com/tapout) for more information about -TAP-Y/J formats. + $ ruby -Ilib test/some_test.rb --tapy | tapout progress +Minitap works with Minitest 5.11 and newer, including Minitest 6, on +Ruby 2.7 and newer. -# Usage -## Minitest 5 +# Installation + + $ gem install minitap -Minitest 5 has a new report system and plug-in API. Minitap takes advantage -of this new API to allow the TAP-Y or TAP-J formats to be selected via command-line -options as an alternative to setting the format in test helper scripts. +Or in a Gemfile: -### Via Command Line + gem 'minitap' -To use simply add `--tapy` or `--tapj` after an isolated `-` separator on the -ruby test command invocation, e.g. +Tapout is installed along with it. - $ ruby -Ilib test/runner.rb - --tapy -In your test helper scripts be sure you have the standard Minitest line: +# Usage + +Load Minitap in your test helper, after Minitest: require 'minitest/autorun' + require 'minitap' -And remove any old `MiniTest::Unit.runner=` assignments if you are migrating -from v4. +That adds two options to the test command line, `--tapy` and `--tapj`. +Without one of them Minitest reports as usual. -Now to do something interesting with the TAP-Y/J output, you will probably want -to install `tapout`: + $ ruby -Ilib test/some_test.rb --tapy - $ gem install tapout +The output is a TAP-Y stream, which isn't meant to be read as it is. +Pipe it to `tapout`, with the name of the report you want: -Then pipe the output to the `tapout` command, e.g. + $ ruby -Ilib test/some_test.rb --tapy | tapout progress - $ ruby test/some_test.rb - --tapy | tapout progressbar +`tapout --help` lists the reports. -### Via Helper Script +## With Rake -To use via test helper script, require the `minitap` library after `minitest/autorun` -and assign `Minitest.reporter` to the Minitap reporter to be used. +Rake's `TestTask` and Minitest's own `Minitest::TestTask` pass the +`TESTOPTS` variable on to Minitest: - require "minitest/autorun" - require "minitap" + $ rake test TESTOPTS=--tapy | tapout progress - Minitest.reporter = Minitap::TapY - -Then pipe the output to the `tapout` command, e.g. +Rake's `-q` option keeps Rake's own output out of the stream. - $ ruby -Ilib test/runner.rb | tapout progrssbar +## In code -Or using Rake: +To always report in TAP-Y or TAP-J, say so in the test helper: - $ rake test | tapout progressbar + require 'minitest/autorun' + require 'minitap' -You may need the `-q` option for Rake to supress extraneous output. + Minitap.tapy! # or Minitap.tapj! +An option on the command line still takes precedence. `Minitap.format = :tapj` +does the same as `Minitap.tapj!`, which is handy with a variable: -## MiniTest 4 + Minitap.format = ENV['TAP_FORMAT'] if ENV['TAP_FORMAT'] -If you are still using MiniTest 4.x you will need to use Minitap version 4.x -as well. In your dependencies be sure to specify this version. For example in -your Gemfile: +As a shorthand, `require 'minitap/autorun'` requires `minitest/autorun` +and chooses TAP-Y: - gem "minitap", "~> 0.4.0" + require 'minitap/autorun' -For Minitest 4 and and older, custom report formats are set by assigning -the `MiniTest::Unit.runner` to an instance of a custom runner class. -In our case we want to set it to an instance of `MiniTest::TapY` or `MiniTest::TapJ`. -So in your project's test helper script add, e.g. +## Loading the plugin - require 'minitap' - MiniTest::Unit.runner = MiniTest::TapY.new +Minitap is an ordinary Minitest plugin, so Minitest's own ways of +loading one work as well as `require 'minitap'`: -Now you may want to set this up so it is selectable. In which case use an -environment variable. + Minitest.load :minitap - MiniTest::Unit.runner = \ - case ENV['rpt'] - when 'tapy' - MiniTest::TapY.new - when 'tapj' - MiniTest::TapJ.new - end +Minitest 5 loads every installed plugin by itself, so there the options +are available without anything in the test helper. Minitest 6 no longer +does that, and one of the lines above is needed. -Then you can do, e.g. +## What is reported - $ rpt=tapy ruby test/some_test.rb +* Each test class is a case, and each test a test, labelled by name. A + spec is labelled as it was written. +* A failure or error comes with its message, the file and line in your + code, the lines of source around it, and a backtrace without Minitest + in it. +* A skipped test is reported as omitted, with the reason. +* What a test prints to `$stdout` and `$stderr` is captured and reported + with the test, since it would otherwise break the stream. -Now to do something interesting with the TAP-Y/J output, you will probably want -to install `tapout`: - $ gem install tapout +# Upgrading from 0.5 -Then pipe the output to the `tapout` command, e.g. +Version 0.6 uses Minitest's plugin system only, and no longer needs the +`minitest-reporter-api` gem. - $ rpt=tapy ruby test/some_test.rb | tapout progressbar +* `Minitest.reporter = Minitap::TapY` no longer does anything. Use + `Minitap.tapy!` instead. +* The reporters are `Minitap::TapY` and `Minitap::TapJ`. They are no + longer also defined as `Minitest::TapY` and `Minitest::TapJ`. +* Skipped tests have the status `omit`, as TAP-Y/J specifies. They used + to have the status `skip`. + +For Minitest 4 and older, use Minitap 0.4. # Using Pry & Other Tools -Becuase Tapout communicates with Minitest via a shell pipe it is improtant -to keep in mind that any non TAP-Y/J output that tapout receives might -force it to halt. To ensure this doesn't occur a *pause code* (`16.chr`) can -be sent over the pipe to instruct the tapout comamnd to stop processing test -results and route `$stdin` directly to `$stdout` instead. A *resume code* -(`23.chr`) can be sent to restart test result processing. +Because Tapout reads Minitest's output through a pipe, anything in the +stream that isn't TAP-Y/J may make it halt. A debugger needs the +terminal, though. For that there is a *pause code* (`16.chr`), which +tells `tapout` to stop reading test results and pass everything +straight through, and a *resume code* (`23.chr`), which starts it +reading again. -A good example of this is when using `binding.pry` for debugging. To do so -while using tapout: +With `binding.pry`, for example: require 'tapout/utility' tapout.pause{ binding.pry } -Or, even more convenient, specifically for use with pry: +Or, more convenient still: require 'tapout/utility' tapout.pry(binding) -Which is a more covenient way of coding: +Which amounts to: STDOUT.puts 16.chr binding.pry @@ -168,5 +153,4 @@ Portions of this program were drawn from Alexander Kern's MiniTest Reporter (c) 2011 Alexander Kern. Thanks Alexander for making my endeavor a little bit easier. -See COPYING.rdoc for copyright and licensing details. - +See LICENSE.txt and NOTICE.md for copyright and licensing details. diff --git a/Rakefile b/Rakefile new file mode 100644 index 0000000..8d0cfb0 --- /dev/null +++ b/Rakefile @@ -0,0 +1,22 @@ +require 'rake/clean' +CLOBBER.include 'pkg' + +require 'bundler/gem_helper' + +# Bundler tags releases as v1.2.3, but Minitap's tags have always been +# plain version numbers, so keep it that way. +class Bundler::GemHelper + def version_tag + version.to_s + end +end + +Bundler::GemHelper.install_tasks + +desc 'run demos' +task 'demo' do + sh 'qed -Ilib demo/' +end + +task 'test' => 'demo' +task 'default' => 'demo' diff --git a/demo/01_tapy.md b/demo/01_tapy.md new file mode 100644 index 0000000..44eba11 --- /dev/null +++ b/demo/01_tapy.md @@ -0,0 +1,100 @@ +# TAP-Y + +Given a test file: + + require 'minitest/autorun' + require 'minitap' + + class ExampleTest < Minitest::Test + def test_error + raise "boom" + end + + def test_failing + assert_equal('1', '2') + end + + def test_passing + assert_equal('1', '1') + end + end + +Running it with the `--tapy` option gives a TAP-Y stream. + + stream = run_tapy('--tapy') + +There are six documents in it. + + stream.size #=> 6 + +The first is a `suite` with a count of `3`. + + stream.first['type'] #=> 'suite' + stream.first['count'] #=> 3 + stream.first['rev'] #=> 4 + +The second is a `case`, named after the test class. + + stream[1]['type'] #=> 'case' + stream[1]['label'] #=> 'ExampleTest' + stream[1]['level'] #=> 0 + +The next three are the tests, which can come in any order. + + tests = tests(stream) + + tests.size #=> 3 + +The passing test has little to say. + + tests['test_passing']['status'] #=> 'pass' + tests['test_passing']['exception'] #=> nil + +The failing test says what failed and where in the test file. + + failing = tests['test_failing'] + + failing['status'] #=> 'fail' + failing['exception']['class'] #=> 'Minitest::Assertion' + failing['exception']['file'] #=> 'test.rb' + failing['exception']['line'] #=> 10 + failing['exception']['source'] #=> "assert_equal('1', '2')" + + failing['exception']['message'].assert.include?('Expected: "1"') + +It comes with the lines around the failure. + + failing['exception']['snippet'].map { |line| line.keys.first } #=> [8, 9, 10, 11, 12] + failing['exception']['snippet'][2][10] #=> " assert_equal('1', '2')" + +The test that raised an error names the error, not Minitest's wrapper +for it. + + erring = tests['test_error'] + + erring['status'] #=> 'error' + erring['exception']['class'] #=> 'RuntimeError' + erring['exception']['message'] #=> 'boom' + erring['exception']['file'] #=> 'test.rb' + erring['exception']['line'] #=> 6 + erring['exception']['source'] #=> 'raise "boom"' + +Neither backtrace mentions Minitest or Minitap. + + failing['exception']['backtrace'] #=> ['test.rb:10'] + erring['exception']['backtrace'] #=> ['test.rb:6'] + +The last document is the `final` one, with the counts. + + stream.last['type'] #=> 'final' + stream.last['counts'] #=> {'total'=>3, 'pass'=>1, 'fail'=>1, 'error'=>1, 'omit'=>0, 'todo'=>0} + +The stream ends with the YAML end-of-document marker. + + @stdout.lines.last #=> "...\n" + +Nothing else is written, and the exit status still tells of the +failures. + + @stderr #=> '' + @status.success? #=> false diff --git a/demo/02_tapj.md b/demo/02_tapj.md new file mode 100644 index 0000000..638d9b4 --- /dev/null +++ b/demo/02_tapj.md @@ -0,0 +1,32 @@ +# TAP-J + +Given a test file: + + require 'minitest/autorun' + require 'minitap' + + class ExampleTest < Minitest::Test + def test_failing + assert_equal('1', '2') + end + + def test_passing + assert_equal('1', '1') + end + end + +Running it with the `--tapj` option gives a TAP-J stream: the same +records as TAP-Y, as a JSON document on each line. + + stream = run_tapj('--tapj') + + stream.map { |d| d['type'] } #=> ['suite', 'case', 'test', 'test', 'final'] + + tests = tests(stream) + + tests['test_passing']['status'] #=> 'pass' + tests['test_failing']['status'] #=> 'fail' + tests['test_failing']['exception']['file'] #=> 'test.rb' + tests['test_failing']['exception']['line'] #=> 6 + + stream.last['counts'] #=> {'total'=>2, 'pass'=>1, 'fail'=>1, 'error'=>0, 'omit'=>0, 'todo'=>0} diff --git a/demo/03_spec.md b/demo/03_spec.md new file mode 100644 index 0000000..1bf56db --- /dev/null +++ b/demo/03_spec.md @@ -0,0 +1,45 @@ +# Minitest::Spec + +Given a test file: + + require 'minitest/autorun' + require 'minitap' + + describe "Example Case" do + it "should error" do + raise "boom" + end + + it "should fail" do + assert_equal('1', '2') + end + + it "should pass" do + assert_equal('1', '1') + end + end + +A spec is reported like any other test. + + stream = run_tapy('--tapy') + + stream.size #=> 6 + +The case is labelled with the description. + + stream[1]['type'] #=> 'case' + stream[1]['label'] #=> 'Example Case' + +The tests are labelled as they were written, without the `test_0001_` +that Minitest puts in front. + + tests = tests(stream) + + tests.keys.sort #=> ['should error', 'should fail', 'should pass'] + + tests['should pass']['status'] #=> 'pass' + tests['should fail']['status'] #=> 'fail' + tests['should error']['status'] #=> 'error' + + tests['should fail']['exception']['line'] #=> 10 + tests['should error']['exception']['line'] #=> 6 diff --git a/demo/04_helper.md b/demo/04_helper.md new file mode 100644 index 0000000..19d5b07 --- /dev/null +++ b/demo/04_helper.md @@ -0,0 +1,109 @@ +# Choosing the format in code + +The format can be chosen in a test helper instead of on the command +line. + +Given a test file: + + require 'minitest/autorun' + require 'minitap' + + Minitap.tapj! + + class ExampleTest < Minitest::Test + def test_passing + assert true + end + end + +Then it needs no option. + + stream = run_tapj + + stream.map { |d| d['type'] } #=> ['suite', 'case', 'test', 'final'] + +An option on the command line takes precedence. + + stream = run_tapy('--tapy') + + stream.map { |d| d['type'] } #=> ['suite', 'case', 'test', 'final'] + +## minitap/autorun + +Requiring `minitap/autorun` is `minitest/autorun` with TAP-Y chosen. + +Given a test file: + + require 'minitap/autorun' + + class ExampleTest < Minitest::Test + def test_passing + assert true + end + end + +Then: + + stream = run_tapy + + stream.map { |d| d['type'] } #=> ['suite', 'case', 'test', 'final'] + +Here too an option can ask for the other format. + + stream = run_tapj('--tapj') + + stream.map { |d| d['type'] } #=> ['suite', 'case', 'test', 'final'] + +## Without a format + +Requiring Minitap chooses nothing by itself. + +Given a test file: + + require 'minitest/autorun' + require 'minitap' + + class ExampleTest < Minitest::Test + def test_passing + assert true + end + end + +Without an option, Minitest reports as it always does. + + out = run_tests + + out.assert.include?('1 runs, 1 assertions, 0 failures, 0 errors, 0 skips') + +An unknown format is refused. + + require 'minitap' + + ArgumentError.assert.raised? do + Minitap.format = :xml + end + + Minitap.format #=> nil + +## Minitest's plugin loader + +Minitest can also be told to load the plugin by name. + +Given a test file: + + require 'minitest/autorun' + + Minitest.load :minitap if Minitest.respond_to?(:load) + + class ExampleTest < Minitest::Test + def test_passing + assert true + end + end + +Then the options are there. (Minitest 5 finds an installed plugin +without being told, so there it works either way.) + + stream = run_tapy('--tapy') + + stream.map { |d| d['type'] } #=> ['suite', 'case', 'test', 'final'] diff --git a/demo/05_details.md b/demo/05_details.md new file mode 100644 index 0000000..2df49b3 --- /dev/null +++ b/demo/05_details.md @@ -0,0 +1,127 @@ +# Details + +## Skipped tests + +Given a test file: + + require 'minitest/autorun' + require 'minitap' + + class ExampleTest < Minitest::Test + def test_skipped + skip "not today" + end + + def test_passing + assert true + end + end + +A skipped test has the status `omit`, which is what TAP-Y/J calls it, +and gives the reason. + + stream = run_tapy('--tapy') + tests = tests(stream) + + tests['test_skipped']['status'] #=> 'omit' + tests['test_skipped']['exception']['message'] #=> 'not today' + tests['test_skipped']['exception']['file'] #=> 'test.rb' + tests['test_skipped']['exception']['line'] #=> 6 + + stream.last['counts'] #=> {'total'=>2, 'pass'=>1, 'fail'=>0, 'error'=>0, 'omit'=>1, 'todo'=>0} + +A skip is not a failure. + + @status.success? #=> true + +## Output from tests + +Given a test file: + + require 'minitest/autorun' + require 'minitap' + + class ExampleTest < Minitest::Test + def test_noisy + puts "to stdout" + warn "to stderr" + assert true + end + + def test_quiet + assert true + end + end + +What a test prints would break the stream. It is captured and becomes +part of the test's record. + + stream = run_tapy('--tapy') + tests = tests(stream) + + tests['test_noisy']['stdout'] #=> "to stdout\n" + tests['test_noisy']['stderr'] #=> "to stderr\n" + + tests['test_quiet'].key?('stdout') #=> false + tests['test_quiet'].key?('stderr') #=> false + + @stderr #=> '' + +## Several classes + +Given a test file: + + require 'minitest/autorun' + require 'minitap' + + class FirstTest < Minitest::Test + def test_one; assert true; end + def test_two; assert true; end + end + + class SecondTest < Minitest::Test + def test_three; assert true; end + end + +Each class is a case, followed by its tests. + + stream = run_tapy('--tapy') + + cases = stream.select { |d| d['type'] == 'case' }.map { |d| d['label'] } + + cases.sort #=> ['FirstTest', 'SecondTest'] + + types = stream.map { |d| d['type'] } + index = stream.index { |d| d['label'] == 'FirstTest' } + + types[index, 3] #=> ['case', 'test', 'test'] + + stream.first['count'] #=> 3 + +## Selecting tests by name + +The count at the start of the stream is of the tests that will run, +so it follows Minitest's `--name` option. + + stream = run_tapy('--tapy', '--name', '/one|three/') + + stream.first['count'] #=> 2 + stream.last['counts']['total'] #=> 2 + + tests(stream).keys.sort #=> ['test_one', 'test_three'] + +## The seed + +The seed is in the `suite` document, and the tests run in the order +that seed gives them without Minitap. + + stream = run_tapy('--tapy', '--seed', '42') + + stream.first['seed'] #=> 42 + + with = stream.select { |d| d['type'] == 'test' }.map { |d| d['label'] } + + plain = run_tests('--seed', '42', '--verbose') + without = plain.scan(/^\w+Test#(test_\w+)/).flatten + + with #=> without diff --git a/demo/06_tapout.md b/demo/06_tapout.md new file mode 100644 index 0000000..da57d2f --- /dev/null +++ b/demo/06_tapout.md @@ -0,0 +1,44 @@ +# Tapout + +The stream is for Tapout, which renders it in a format of your choice. + +Given a test file: + + require 'minitest/autorun' + require 'minitap' + + class ExampleTest < Minitest::Test + def test_error + raise "boom" + end + + def test_failing + assert_equal('1', '2') + end + + def test_passing + assert_equal('1', '1') + end + + def test_skipped + skip "not today" + end + end + +Tapout reads the TAP-Y stream. + + out = tapout(run_tests('--tapy', '--seed', '1'), 'tap') + + out.assert.include?('1..4') + out.assert =~ /^ok \d - test_passing$/ + out.assert =~ /^not ok \d - test_failing$/ + out.assert =~ /^not ok \d - test_error$/ + out.assert =~ /^ok \d - test_skipped # SKIP not today$/ + +And the TAP-J stream. + + out = tapout(run_tests('--tapj', '--seed', '1'), 'tap') + + out.assert =~ /^ok \d - test_passing$/ + out.assert =~ /^not ok \d - test_failing$/ + out.assert =~ /^ok \d - test_skipped # SKIP not today$/ diff --git a/demo/applique/cli.rb b/demo/applique/cli.rb deleted file mode 100644 index 4e6184c..0000000 --- a/demo/applique/cli.rb +++ /dev/null @@ -1,67 +0,0 @@ -require 'tapout' - -When 'Given a Minitest (((Test|Spec)))' do |type, text| - @test = text -end - -When 'Running it with the (((.*?))) format' do |type| - File.open('test.rb', 'w') { |f| - f << "\n" + test_helper(type) + "\n\n" + @test - } - - @out = test_command(type) - - #@stream = YAML.load_documents(@out) # b/c of bug in Ruby 1.8 - @stream = ( - s = [] - YAML.load_documents(@out){ |d| s << d } - s - ) -end - -#When '(((\w+))) reporter should run without error' do |format| -# $stdin = StringIO.new(@tapy) -# $stdout = StringIO.new(out = '') -# -# TapOut.cli(format) -#end - -def test_command(type) - #return test_command_4 if ENV['minitest'] == "4" - - if type == 'TAP-Y' - `ruby -I../../lib test.rb - --tapy` - else - `ruby -I../../lib test.rb - --tapj` - end -end - -# TODO: Is there a way to offer option to select the format via code? -def test_helper(type) - #return test_helper_4(type) if ENV['minitest'] == "4" - - "require 'minitest/autorun'" -end - -=begin -def test_command_4 - `ruby -I../../lib test.rb` -end - -# For Minitest v4. -def test_helper_4(type) - if type == 'TAP-Y' then - %Q{ - require 'minitap' - MiniTest::Unit.runner = MiniTest::TapY.new - require 'minitest/autorun' - } - else - %Q{ - require 'minitap' - MiniTest::Unit.runner = MiniTest::TapJ.new - require 'minitest/autorun' - } - end -end -=end diff --git a/demo/applique/run.rb b/demo/applique/run.rb new file mode 100644 index 0000000..5abc0c1 --- /dev/null +++ b/demo/applique/run.rb @@ -0,0 +1,48 @@ +require 'minitest' +require 'tmpdir' +require 'open3' +require 'rbconfig' +require 'yaml' +require 'json' + +# Each demo writes a test file and runs it in a process of its own, +# the way a test suite is run. + +LIB = File.expand_path('../../lib', __dir__) + +When 'iven a test file' do |text| + @source = text +end + +# Run the test file with the given command line options. Returns what +# the run wrote to standard output. +def run_tests(*options) + Dir.mktmpdir('minitap') do |dir| + File.write(File.join(dir, 'test.rb'), @source) + command = [RbConfig.ruby, "-I#{LIB}", 'test.rb', *options] + @stdout, @stderr, @status = Open3.capture3(*command, :chdir => dir) + end + @stdout +end + +# Run the test file and read its output as a TAP-Y stream. +def run_tapy(*options) + YAML.load_stream(run_tests(*options)) +end + +# Run the test file and read its output as a TAP-J stream. +def run_tapj(*options) + run_tests(*options).lines.map { |line| JSON.parse(line) } +end + +# The test records of a stream, by label. +def tests(stream) + stream.select { |d| d['type'] == 'test' }.to_h { |d| [d['label'], d] } +end + +# Pipe a stream through Tapout. Returns what Tapout printed. +def tapout(stream, reporter) + bin = Gem.bin_path('tapout', 'tapout') + out, _ = Open3.capture2(RbConfig.ruby, bin, reporter, :stdin_data => stream) + out +end diff --git a/demo/fixtures/tapy.yml b/demo/fixtures/tapy.yml deleted file mode 100644 index c116e8c..0000000 --- a/demo/fixtures/tapy.yml +++ /dev/null @@ -1,78 +0,0 @@ ---- -type: suite -start: '2011-10-06 18:48:08' -count: 3 -seed: 36440 -rev: 2 ---- -type: case -subtype: '' -label: ExampleTestCase -level: 0 ---- -type: test -subtype: '' -status: error -label: test_error -exception: - message: ! 'RuntimeError:' - file: example.rb - line: 10 - snippet: - - 8: '' - - 9: ! ' def test_error' - - 10: ! ' raise' - - 11: ! ' end' - - 12: '' - backtrace: - - example.rb:10 -time: 0.001054606 ---- -type: test -subtype: '' -status: fail -label: test_failing -exception: - message: ! "Expected: \"1\"\n Actual: \"2\"" - file: example.rb - line: 14 - snippet: - - 12: '' - - 13: ! ' def test_failing' - - 14: ! ' assert_equal(''1'', ''2'')' - - 15: ! ' end' - - 16: '' - backtrace: - - example.rb:14 - - /home/trans/com/programs/rubyworks/minitap/lib/minitap.rb:456 - - /home/trans/com/programs/rubyworks/minitap/lib/minitap.rb:103 - - /home/trans/com/programs/rubyworks/minitap/lib/minitap.rb:88 - - /home/trans/com/programs/rubyworks/minitap/lib/minitap.rb:88 - - /home/trans/com/programs/rubyworks/minitap/lib/minitap.rb:88 - - /home/trans/com/programs/rubyworks/minitap/lib/minitap.rb:73 - - /home/trans/com/programs/rubyworks/minitap/lib/minitap.rb:73 - - /home/trans/com/programs/rubyworks/minitap/lib/minitap.rb:73 - - /home/trans/com/programs/rubyworks/minitap/lib/minitap.rb:146 - - /home/trans/com/programs/rubyworks/minitap/lib/minitap.rb:72 - - /home/trans/com/programs/rubyworks/minitap/lib/minitap.rb:48 - - /home/trans/com/programs/rubyworks/minitap/lib/minitap.rb:47 - - /home/trans/com/programs/rubyworks/minitap/lib/minitap.rb:47 -time: 0.046170916 ---- -type: test -subtype: '' -status: pass -label: test_passing -time: 1.04997403 ---- -type: tally -time: 1.000800203 -counts: - total: 3 - pass: 1 - fail: 1 - error: 1 - omit: 0 - todo: 0 -... - diff --git a/demo/minispec.md b/demo/minispec.md deleted file mode 100644 index 320c1ff..0000000 --- a/demo/minispec.md +++ /dev/null @@ -1,96 +0,0 @@ -# Minitap - -Given a Minitest Spec: - - require 'minitest/spec' - - describe "Example Case" do - it "should error" do - raise - end - - it "should fail" do - assert_equal('1', '2') - end - - it "should pass" do - sleep 1 - assert_equal('1', '1') - end - end - -Running it with the TAP-Y format should work without error. - -The resulting document stream should exhibit the following -characteristics. - -There should be six sections. - - @stream.size #=> 6 - -The first should be a `suite` with a count of `3`. - - @stream.first['type'] #=> 'suite' - @stream.first['count'] #=> 3 - -The second should be `case` entry. - - @stream[1]['type'] #=> 'case' - @stream[1]['label'] #=> 'Example Case' - @stream[1]['level'] #=> 0 - -The next three documents are the unit tests, which can occur in any order. -There's one that should have a status of `pass`, another of `fail` and the -third of `error`. - - passing_test = @stream.find{ |d| d['type'] == 'test' && d['status'] == 'pass' } - failing_test = @stream.find{ |d| d['type'] == 'test' && d['status'] == 'fail' } - erring_test = @stream.find{ |d| d['type'] == 'test' && d['status'] == 'error' } - -The passing test should have the following charactersitics. - - passing_test['label'] #=> 'should pass' - -The failing test should - - failing_test['label'] #=> "should fail" - failing_test['exception']['class'] #=> "Minitest::Assertion" - failing_test['exception']['file'] #=> "test.rb" - failing_test['exception']['line'] #=> 12 - failing_test['exception']['source'] #=> "assert_equal('1', '2')" - -The failing test should also not have any mention of minitap in the -backtrace. - - failing_test['exception']['backtrace'].each do |e| - /minitap/.refute.match(e) - end - -The erring test should - - erring_test['label'] #=> 'should error' - erring_test['exception']['class'] #=> 'RuntimeError' - erring_test['exception']['file'] #=> 'test.rb' - erring_test['exception']['line'] #=> 8 - erring_test['exception']['source'] #=> 'raise' - -The erring test should also not have any mention of minitap in the -backtrace. - - erring_test['exception']['backtrace'].each do |e| - /minitap/.refute.match(e) - end - -The last should a `final` document. - - @stream.last['type'] #=> 'final' - -And it should have the following counts. - - @stream.last['counts']['total'] #=> 3 - @stream.last['counts']['error'] #=> 1 - @stream.last['counts']['fail'] #=> 1 - @stream.last['counts']['pass'] #=> 1 - @stream.last['counts']['omit'] #=> 0 - @stream.last['counts']['todo'] #=> 0 - diff --git a/demo/minitest.md b/demo/minitest.md deleted file mode 100644 index cfb7713..0000000 --- a/demo/minitest.md +++ /dev/null @@ -1,94 +0,0 @@ -# Minitap - -Given a Minitest Test: - - class ExampleTestCase < Minitest::Test - def test_error - raise - end - - def test_failing - assert_equal('1', '2') - end - - def test_passing - sleep 1 - assert_equal('1', '1') - end - end - -Running it with the TAP-Y format should work without error. - -The resulting document stream should exhibit the following -characteristics. - -There should be six sections. - - @stream.size #=> 6 - -The first should be a `suite` with a count of `3`. - - @stream.first['type'] #=> 'suite' - @stream.first['count'] #=> 3 - -The second should be `case` entry. - - @stream[1]['type'] #=> 'case' - @stream[1]['label'] #=> 'ExampleTestCase' - @stream[1]['level'] #=> 0 - -The next three documents are the unit tests, which can occur in any order. -There's one that should have a status of `pass`, another of `fail` and the -third of `error`. - - passing_test = @stream.find{ |d| d['type'] == 'test' && d['status'] == 'pass' } - failing_test = @stream.find{ |d| d['type'] == 'test' && d['status'] == 'fail' } - erring_test = @stream.find{ |d| d['type'] == 'test' && d['status'] == 'error' } - -The passing test should have the following charactersitics. - - passing_test['label'] #=> 'test_passing' - -The failing test should - - failing_test['label'] #=> "test_failing" - failing_test['exception']['class'] #=> "Minitest::Assertion" - failing_test['exception']['file'] #=> "test.rb" - failing_test['exception']['line'] #=> 10 - failing_test['exception']['source'] #=> "assert_equal('1', '2')" - -The failing test should also not have any mention of minitap in the -backtrace. - - failing_test['exception']['backtrace'].each do |e| - /minitap/.refute.match(e) - end - -The erring test should - - erring_test['label'] #=> 'test_error' - erring_test['exception']['class'] #=> 'RuntimeError' - erring_test['exception']['file'] #=> 'test.rb' - erring_test['exception']['line'] #=> 6 - erring_test['exception']['source'] #=> 'raise' - -The erring test should also not have any mention of minitap in the -backtrace. - - erring_test['exception']['backtrace'].each do |e| - /minitap/.refute.match(e) - end - -The last should a `final` document. - - @stream.last['type'] #=> 'final' - -And it should have the following counts. - - @stream.last['counts']['total'] #=> 3 - @stream.last['counts']['error'] #=> 1 - @stream.last['counts']['fail'] #=> 1 - @stream.last['counts']['pass'] #=> 1 - @stream.last['counts']['omit'] #=> 0 - @stream.last['counts']['todo'] #=> 0 - diff --git a/lib/minitap.rb b/lib/minitap.rb index 6972325..b1c902e 100644 --- a/lib/minitap.rb +++ b/lib/minitap.rb @@ -1,11 +1,91 @@ -#gem "minitest", "~> 5.0" - require 'minitest' -require 'minitest/reporter_api' -require 'minitap/minitest5' +require 'minitap/version' +require 'minitap/reporter' +# Minitap makes Minitest report in TAP-Y or TAP-J, the formats that +# Tapout reads. It is a Minitest plugin. +# +# Choose the format on the command line, with `--tapy` or `--tapj`, or +# in a test helper: +# +# require 'minitest/autorun' +# require 'minitap' +# +# Minitap.tapy! +# module Minitap - TapY = Minitest::TapY - TapJ = Minitest::TapJ -end + # The reporter for each format, by the format's name. + FORMATS = { 'tapy' => TapY, 'tapj' => TapJ } + + @format = nil + @registered = false + + class << self + + # The format chosen in code, 'tapy' or 'tapj', or nil. A `--tapy` + # or `--tapj` option on the command line takes precedence over it. + attr_reader :format + + # Choose the format: :tapy, :tapj, or nil for Minitest's own report. + def format=(name) + name = name.to_s.downcase.delete('-_') unless name.nil? + unless name.nil? || FORMATS.key?(name) + raise ArgumentError, "unknown format #{name.inspect}, use :tapy or :tapj" + end + @format = name + end + + # Report in TAP-Y. + def tapy! + self.format = :tapy + end + + # Report in TAP-J. + def tapj! + self.format = :tapj + end + + # Called by Minitest to add this plugin's command line options. + def minitest_plugin_options(opts, options) + opts.on '--tapy', 'Report in TAP-Y, for Tapout.' do + options[:minitap] = 'tapy' + end + opts.on '--tapj', 'Report in TAP-J, for Tapout.' do + options[:minitap] = 'tapj' + end + end + + # Called by Minitest as a run starts. If a format was chosen, its + # reporter takes the place of Minitest's own reporters, whose + # output would corrupt the stream. + def minitest_plugin_init(options) + format = options[:minitap] || self.format + return unless format + + composite = Minitest.reporter + return if composite.reporters.any? { |r| Reporter === r } + + composite.reporters.clear + composite << FORMATS.fetch(format.to_s).new(options[:io], options) + end + + # Has Minitap been registered with Minitest as a plugin module? + def registered? + @registered + end + + # Register with Minitest. Minitest 5.24 and newer take a module. + # Older versions find `minitest/minitap_plugin.rb` on their own. + def register + return if registered? + return unless Minitest.respond_to?(:register_plugin) + Minitest.register_plugin(self) + @registered = true + end + + end + + register + +end diff --git a/lib/minitap/autorun.rb b/lib/minitap/autorun.rb index 948c486..897e75d 100644 --- a/lib/minitap/autorun.rb +++ b/lib/minitap/autorun.rb @@ -1,8 +1,7 @@ +# Run the tests when the program exits, reporting in TAP-Y unless +# another format has been chosen. + require 'minitest/autorun' require 'minitap' -# Default it TapY. -#Minitest.reporter = Minitest::TapJ -Minitest.reporter = Minitest::TapY - - +Minitap.tapy! unless Minitap.format diff --git a/lib/minitap/ignore_callers.rb b/lib/minitap/ignore_callers.rb deleted file mode 100644 index 95800f8..0000000 --- a/lib/minitap/ignore_callers.rb +++ /dev/null @@ -1,5 +0,0 @@ -ignore = /(lib|bin)#{Regexp.escape(File::SEPARATOR)}minitap/ - -$RUBY_IGNORE_CALLERS = [] unless defined?($RUBY_IGNORE_CALLERS) -$RUBY_IGNORE_CALLERS << ignore - diff --git a/lib/minitap/minitest5.rb b/lib/minitap/minitest5.rb deleted file mode 100644 index 045a822..0000000 --- a/lib/minitap/minitest5.rb +++ /dev/null @@ -1,885 +0,0 @@ -# MiniTest adaptor for tapout. - -# Have to make sure the latest version of minitest is used. -begin; gem 'minitest'; rescue; end - -#require 'minitest/unit' -require 'minitap/ignore_callers' -require 'stringio' - -# Becuase of some wierdness in MiniTest -#debug, $DEBUG = $DEBUG, false -#require 'minitest/unit' -#$DEBUG = debug - -module Minitest - - ## - # Base class for TapY and TapJ runners. - # - class Minitap < StatisticsReporter #Reporter - - # TAP-Y/J Revision - REVISION = 4 - - # Backtrace patterns to be omitted. - IGNORE_CALLERS = $RUBY_IGNORE_CALLERS - - # Test results. - #attr_reader :test_results - - attr_reader :test_cases - attr_reader :test_count - - attr_accessor :suite_start_time - attr_accessor :case_start_time - attr_accessor :test_start_time - - # Initialize new Minitap Minitest reporter. - def initialize(options = {}) - io = options.delete(:io) || $stdout - - super(io, options) - - # since tapout uses a unix pipe, we don't want any buffering - io.sync = true - - #@_stdout = StringIO.new - #@_stderr = StringIO.new - - #@test_results = {} - #self.assertion_count = 0 - - @_source_cache = {} - end - - # - # Minitest's initial hook ran just before testing begins. - # - def start - super - - @test_cases = Runnable.runnables - - capture_io - - #@_stdout, @_stderr = capture_io do - # super_result = super(suite, type) - #end - - before_suite(@test_cases) - end - - # - # Process a test result. - # - def record(minitest_result) - super(minitest_result) - - result = TestResult.new(minitest_result) - - #if exception #&& ENV['minitap_debug'] - # STDERR.puts exception - # STDERR.puts exception.backtrace.join("\n") - #end - - #@test_results[suite] ||= {} - #@test_results[suite][test.to_sym] = record - - case_change = false - - if @previous_case != result.test_case - case_change = true - before_case(result.test_case) - end - - #before_test(result) - case result.type - when :skip - test_skip(result) - when :pass - test_pass(result) - when :fail - test_fail(result) - when :err - test_err(result) - end - after_test(result) - - if case_change - after_case(result.test_case) - end - - @previous_case = result.test_case - end - - # - # Minitest's finalization hook. - # - def report - super - - uncapture_io - - after_suite() - end - - # - # Intermediary Callbacks - # - - # - def before_suite(test_cases) - @suite_start_time = Time.now - count_tests!(test_cases) - tapout_before_suite() - end - - def after_suite() #(test_cases) - tapout_after_suite() - end - - def before_case(test_case) - @case_start_time = Time.now - tapout_before_case(test_case) - end - - def after_case(test_case) - tapout_after_case(test_case) - end - - def before_test(result) - @test_start_time = Time.now - tapout_before_test(result) - end - - def after_test(result) - tapout_after_test(result) - end - - def test_skip(result) - tapout_test_skip(result) - end - - def test_pass(result) - tapout_test_pass(result) - end - - def test_fail(result) - tapout_test_failure(result) - end - - def test_err(result) - tapout_test_error(result) - end - -=begin - def _run_suites(suites, type) - #output.puts "# Run options: #{@help}" - - @suites_start_time = Time.now - count_tests!(suites, type) - trigger_callback(:before_suites, suites, type) - super(suites, type) - ensure - trigger_callback(:after_suites, suites, type) - end - - def _run_suite(suite, type) - # The only reason this is here is b/c MiniTest wil try to run - # base classes like `MiniTest::Spec`. So to prevent that, - # if there are no tests to run, we don't bother to process - # the "suite" at all. - @_suite_tests = suite.send("#{type}_methods") - return [0,0] if @_suite_tests.empty? - - begin - @suite_start_time = Time.now - trigger_callback(:before_suite, suite) - - super_result = nil - @_stdout, @_stderr = capture_io do - super_result = super(suite, type) - end - super_result - ensure - trigger_callback(:after_suite, suite) - end - end - - def before_test(suite, test) - @test_start_time = Time.now - trigger_callback(:before_test, suite, test) - end - - def after_test(suite, test) - #runners = @test_recorder[suite, test.to_sym] - #records = @test_results[suite][test.to_sym] - record = @test_results[suite][test.to_sym] - - #records.each do |record| - # trigger_callback(record.result, suite, test.to_sym, record) - #end - - trigger_callback(record.result, suite, test.to_sym, record) - - #trigger_callback(:after_test, suite, test.to_sym) - end -=end - - # Stub out the three IO methods used by the built-in reporter. - def p(*args) - args.each{ |a| io.print(a.inspect); puts } - end - - def puts(*args) - io.puts(*args) - end - - def print(*args) - io.print(*args) - end - - #def status(io = output); end - - private - - # - def filtered_tests(test_case) #suite, type - filter = options[:filter] || '/./' - filter = Regexp.new($1) if filter =~ /\/(.*)\// - test_case.runnable_methods.grep(filter) - end - -=begin - # - def add_test_result(suite, test, test_runner) - self.report[suite] ||= {} - self.report[suite][test.to_sym] = test_runner - - self.assertion_count += test_runner.assertions - - case test_runner.result - when :skip then self.skips += 1 - when :failure then self.failures += 1 - when :error then self.errors += 1 - end - end -=end - - def count_tests!(test_cases) - filter = options[:filter] || '/./' - filter = Regexp.new $1 if filter =~ /\/(.*)\// - - @test_count = test_cases.inject(0) do |acc, test_case| - acc + test_case.runnable_methods.grep(filter).length - end - end - - # - # Tapout Records - # - - # - def tapout_before_suite() - doc = { - 'type' => 'suite', - 'start' => self.suite_start_time.strftime('%Y-%m-%d %H:%M:%S'), - 'count' => self.test_count, - 'seed' => self.options[:seed], - 'rev' => REVISION - } - return doc - end - - # - def tapout_after_suite() - doc = { - 'type' => 'final', - 'time' => Time.now - self.suite_start_time, - 'counts' => { - 'total' => self.test_count, - 'pass' => self.test_count - self.failures - self.errors - self.skips, - 'fail' => self.failures, - 'error' => self.errors, - 'omit' => self.skips, - 'todo' => 0 # TODO: does minitest support pending tests? - } - } - return doc - end - - # - def tapout_before_case(test_case) - doc = { - 'type' => 'case', - 'subtype' => '', - 'label' => "#{test_case}", - 'level' => 0 - } - - record_stdcom(doc) - - return doc - end - - # - def tapout_after_case(test_case) - end - - # - def tapout_before_test(result) - end - - # - def tapout_after_test(result) - end - - # TAP record for pass. - # - # Returns [Hash]. - def tapout_test_pass(result) #suite, test, test_runner - doc = { - 'type' => 'test', - 'subtype' => '', - 'status' => 'pass', - #'setup': foo instance - 'label' => "#{result.label}", - #'expected' => 2 - #'returned' => 2 - #'file' => 'test/test_foo.rb' - #'line': 45 - #'source': ok 1, 2 - #'snippet': - # - 44: ok 0,0 - # - 45: ok 1,2 - # - 46: ok 2,4 - #'coverage': - # file: lib/foo.rb - # line: 11..13 - # code: Foo#* - 'time' => Time.now - self.suite_start_time - } - - record_stdcom(doc) - - #stdout, stderr = @_stdout, @_stderr - #doc['stdout'] = stdout unless stdout.empty? - #doc['stderr'] = stderr unless stderr.empty? - - return doc - end - - # TAP record for skip. - # - # Returns [Hash]. - def tapout_test_skip(result) #suite, test, test_runner - e = result.exception - e_file, e_line = location(result.exception) - r_file = e_file.sub(Dir.pwd+'/', '') - - doc = { - 'type' => 'test', - 'subtype' => '', - 'status' => 'skip', - 'label' => "#{result.label}", - #'setup' => "foo instance", - #'expected' => 2, - #'returned' => 1, - #'file' => test/test_foo.rb - #'line' => 45 - #'source' => ok 1, 2 - #'snippet' => - # - 44: ok 0,0 - # - 45: ok 1,2 - # - 46: ok 2,4 - #'coverage' => - # 'file' => lib/foo.rb - # 'line' => 11..13 - # 'code' => Foo#* - 'exception' => { - 'message' => clean_message(e.message), - 'class' => e.class.name, - 'file' => r_file, - 'line' => e_line, - 'source' => source(e_file)[e_line-1].strip, - 'snippet' => code_snippet(e_file, e_line), - 'backtrace' => filter_backtrace(e.backtrace) - }, - 'time' => Time.now - self.suite_start_time - } - return doc - end - - # TAP record for failure. - # - # Returns [Hash]. - def tapout_test_failure(result) - e = result.exception - e_file, e_line = location(result.exception) - r_file = e_file.sub(Dir.pwd+'/', '') - - doc = { - 'type' => 'test', - 'subtype' => '', - 'status' => 'fail', - 'label' => "#{result.label}", - #'setup' => "foo instance", - #'expected' => 2, - #'returned' => 1, - #'file' => test/test_foo.rb - #'line' => 45 - #'source' => ok 1, 2 - #'snippet' => - # - 44: ok 0,0 - # - 45: ok 1,2 - # - 46: ok 2,4 - #'coverage' => - # 'file' => lib/foo.rb - # 'line' => 11..13 - # 'code' => Foo#* - 'exception' => { - 'message' => clean_message(e.message), - 'class' => e.class.name, - 'file' => r_file, - 'line' => e_line, - 'source' => source(e_file)[e_line-1].strip, - 'snippet' => code_snippet(e_file, e_line), - 'backtrace' => filter_backtrace(e.backtrace) - }, - 'time' => Time.now - self.suite_start_time # result.time - } - - record_stdcom(doc) - - #stdout, stderr = @_stdout, @_stderr - #doc['stdout'] = stdout unless stdout.empty? - #doc['stderr'] = stderr unless stderr.empty? - - return doc - end - - # TAP record for error. - # - # Returns [Hash]. - def tapout_test_error(result) - e = result.exception - e_file, e_line = location(e) - r_file = e_file.sub(Dir.pwd+'/', '') - - doc = { - 'type' => 'test', - 'subtype' => '', - 'status' => 'error', - 'label' => "#{result.label}", - #'setup' => "foo instance", - #'expected' => 2, - #'returned' => 1, - #'file' => test/test_foo.rb - #'line' => 45 - #'source' => ok 1, 2 - #'snippet' => - # - 44: ok 0,0 - # - 45: ok 1,2 - # - 46: ok 2,4 - #'coverage' => - # 'file' => lib/foo.rb - # 'line' => 11..13 - # 'code' => Foo#* - 'exception' => { - 'message' => clean_message(e.error.message), - 'class' => e.error.class.name, - 'file' => r_file, - 'line' => e_line, - 'source' => source(e_file)[e_line-1].strip, - 'snippet' => code_snippet(e_file, e_line), - 'backtrace' => filter_backtrace(e.backtrace) - }, - 'time' => Time.now - self.suite_start_time # result.time - } - - record_stdcom(doc) - - #stdout, stderr = @_stdout, @_stderr - #doc['stdout'] = stdout unless stdout.empty? - #doc['stderr'] = stderr unless stderr.empty? - - return doc - end - - # --------------------------------------------------------------------- - - # - # - # - def record_stdcom(doc) - begin - doc['stdout'] = $stdout.string unless $stdout.length == 0 #empty? - doc['stderr'] = $stderr.string unless $stderr.length == 0 #empty? - $stdout.close; $stderr.close - $stdout, $stderr = StringIO.new, StringIO.new - #end - rescue => err - uncapture_io - raise err - end - end - - # - #def filter_backtrace(backtrace) - # trace = backtrace - # trace = clean_backtrace(trace) - # trace = MiniTest::filter_backtrace(trace) - # trace - #end - - # Clean the backtrace of any reference to test framework itself. - def filter_backtrace(backtrace) - ## remove backtraces that match any pattern in IGNORE_CALLERS - trace = backtrace.reject{|b| IGNORE_CALLERS.any?{|i| i=~b}} - ## remove `:in ...` portion of backtraces - trace = trace.map do |bt| - i = bt.index(':in') - i ? bt[0...i] : bt - end - ## now apply MiniTest's own filter (note: doesn't work if done first, why?) - trace = Minitest::filter_backtrace(trace) - ## if the backtrace is empty now then revert to the original - trace = backtrace if trace.empty? - ## simplify paths to be relative to current workding diectory - trace = trace.map{ |bt| bt.sub(Dir.pwd+File::SEPARATOR,'') } - return trace - end - - # Returns a String of source code. - def code_snippet(file, line) - s = [] - if File.file?(file) - source = source(file) - radius = 2 # TODO: make customizable (number of surrounding lines to show) - region = [line - radius, 1].max .. - [line + radius, source.length].min - - s = region.map do |n| - {n => source[n-1].chomp} - end - end - return s - end - - # Cache source file text. This is only used if the TAP-Y stream - # doesn not provide a snippet and the test file is locatable. - def source(file) - @_source_cache[file] ||= ( - File.readlines(file) - ) - end - - # Parse source location from caller, caller[0] or an Exception object. - def parse_source_location(caller) - case caller - when Exception - trace = caller.backtrace.reject{ |bt| bt =~ INTERNALS } - caller = trace.first - when Array - caller = caller.first - end - caller =~ /(.+?):(\d+(?=:|\z))/ or return "" - source_file, source_line = $1, $2.to_i - return source_file, source_line - end - - # Get location of exception. - def location e # :nodoc: - last_before_assertion = "" - e.backtrace.reverse_each do |s| - break if s =~ /in .(assert|refute|flunk|pass|fail|raise|must|wont)/ - last_before_assertion = s - end - file, line = last_before_assertion.sub(/:in .*$/, '').split(':') - line = line.to_i if line - return file, line - end - - # - def clean_message(message) - message.strip #.gsub(/\s*\n\s*/, "\n") - end - - # - #def capture_io - # ostdout, ostderr = $stdout, $stderr - # cstdout, cstderr = StringIO.new, StringIO.new - # $stdout, $stderr = cstdout, cstderr - # - # yield - # - # return cstdout.string.chomp("\n"), cstderr.string.chomp("\n") - #ensure - # $stdout = ostdout - # $stderr = ostderr - #end - - # - def capture_io - @_stdout, @_stderr = $stdout, $stderr - $stdout, $stderr = StringIO.new, StringIO.new - end - - # - def uncapture_io - $stdout, $stderr = @_stdout, @_stderr - end - - end - - # - # TestResult delegtes to Minitest's own test result object. - # - class TestResult - # Create new TestResult instance. - # - # result - MiniTest's test result object. - # - def initialize(result) - @result = result - end - - def test_case - @result.class - end - alias :testcase :test_case - - # Name of the test. - def name - @result.name - end - alias :test :name - - # - def label - if spec? - name.sub(/^test_\d+_/, '').gsub('_', ' ') - else - name - end - end - - # Is this a Minitest::Spec? - # - # Returns [Boolean]. - def spec? - @is_spec ||= ( - Minitest.const_defined?(:Spec) && @result.class < Minitest::Spec - #@result.class.methods.include?(:it) || @result.class.methods.include?('it') - ) - end - - # Number of assertions made by test. - # - # Returns [Integer]. - def assertions - @result.assertions - end - - # - def time - @result.time - end - - # - def exception - @result.failure - end - - # Result type. - def type - case exception - when UnexpectedError - :err - when Skip - :skip - when Assertion - :fail - when nil - :pass - else - :err - end - end - end - -=begin - # Runner for individual MiniTest tests. - # - # You *should not* create instances of this class directly. Instances of - # {SuiteRunner} will create these and send them to the reporters. - # - # Based upon Ryan Davis of Seattle.rb's MiniTest (MIT License). - # - # @see https://github.com/seattlerb/minitest MiniTest - class TestRunner - attr_reader :suite, :test, :assertions, :result, :exception - attr_reader :stdout, :stderr - - def initialize(suite, test) - @suite = suite - @test = test - @assertions = 0 - end - - def run - suite_instance = suite.new(test) - test_result = nil - @stdout, @stderr = capture_io do - test_result = suite_instance.run(self) - end - @result, @exception = fix_result(test_result) - @assertions = suite_instance._assertions - end - - def puke(suite, test, exception) - case exception - when MiniTest::Skip then [:skip, exception] - when MiniTest::Assertion then [:failure, exception] - else [:error, exception] - end - end - - def record(suite, method, assertions, time, error) - end - - private - - # - def fix_result(result) - result == '.' ? [:pass, nil] : result - end - - # - def capture_io - ostdout, ostderr = $stdout, $stderr - cstdout, cstderr = StringIO.new, StringIO.new - $stdout, $stderr = cstdout, cstderr - - yield - - return cstdout.string.chomp("\n"), cstderr.string.chomp("\n") - ensure - $stdout = ostdout - $stderr = ostderr - end - end -=end - -=begin - ## - # Around advice. - # - module AroundTestHooks - def self.before_test(instance) - if before_test = (MiniTest::Unit.runner.method(:before_test) rescue nil) - before_test.call(instance.class, instance.__name__) - end - end - - def self.after_test(instance) - # MiniTest < 4.1.0 sends #record after all teardown hooks, so don't call - # #after_test here. - if MiniTest::Unit::VERSION > "4.1.0" - if after_test = (MiniTest::Unit.runner.method(:after_test) rescue nil) - after_test.call(instance.class, instance.__name__) - end - end - end - - def before_setup - AroundTestHooks.before_test(self) - super - end - - def after_teardown - super - AroundTestHooks.after_test(self) - end - end - - class Unit::TestCase - include AroundTestHooks - end -=end - - ## - # TAP-Y adapater. - # - class TapY < Minitap - def initialize(options={}) - require 'yaml' unless respond_to?(:to_yaml) - super(options) - end - - def tapout_before_suite() - wp super().to_yaml - end - def tapout_before_case(test_case) - wp super(test_case).to_yaml - end - def tapout_test_pass(result) - wp super(result).to_yaml - end - def tapout_test_skip(result) - wp super(result).to_yaml - end - def tapout_test_failure(result) - wp super(result).to_yaml - end - def tapout_test_error(result) - wp super(result).to_yaml - end - def tapout_after_suite() - wp super().to_yaml - wp "..." - end - - def wp(str) - io.puts(str) - end - end - - ## - # TAP-J adapater. - # - class TapJ < Minitap - def initialize(options={}) - require 'json' unless respond_to?(:to_json) - super(options) - end - - def tapout_before_suite() - wp super().to_json - end - def tapout_before_case(test_case) - wp super(test_case).to_json - end - def tapout_test_pass(result) - wp super(result).to_json - end - def tapout_test_skip(result) - wp super(result).to_json - end - def tapout_test_failure(result) - wp super(result).to_json - end - def tapout_test_error(result) - wp super(result).to_json - end - def tapout_after_suite() - wp super().to_json - end - - def wp(str) - io.puts(str) - end - end - -end diff --git a/lib/minitap/reporter.rb b/lib/minitap/reporter.rb new file mode 100644 index 0000000..74b809c --- /dev/null +++ b/lib/minitap/reporter.rb @@ -0,0 +1,294 @@ +require 'minitest' +require 'stringio' + +module Minitap + + # Base class of the TAP-Y and TAP-J reporters. It turns Minitest's + # results into the records of a TAP-Y/J stream; the subclasses write + # them out. + # + # While tests run, `$stdout` and `$stderr` are captured, so that + # what a test prints becomes part of its record instead of breaking + # the stream. + class Reporter < Minitest::StatisticsReporter + + # TAP-Y/J revision. + REVISION = 4 + + # Number of lines of source to show on each side of a failure. + SNIPPET_RADIUS = 2 + + # Where Minitap's own code lives, to keep it out of backtraces. + LIB_DIRECTORY = File.expand_path('..', __dir__) + File::SEPARATOR + + def initialize(io = $stdout, options = {}) + super + # Tapout reads from a pipe, so nothing should wait in a buffer. + io.sync = true if io.respond_to?(:sync=) + @source_cache = {} + @current_case = nil + end + + # Minitest calls this just before the tests run. + def start + super + @suite_start = Time.now + capture_io + emit suite_record + end + + # Minitest calls this with the result of each test. + def record(result) + super + test_case = case_name(result) + if test_case != @current_case + @current_case = test_case + emit case_record(test_case) + end + emit test_record(result) + end + + # Minitest calls this when all tests have run. + def report + super + release_io + emit final_record + finish + end + + private + + # Write a record to the stream. Subclasses define this. + def emit(record) + raise NotImplementedError + end + + # Write whatever ends the stream. + def finish + end + + # + def suite_record + { + 'type' => 'suite', + 'start' => @suite_start.strftime('%Y-%m-%d %H:%M:%S'), + 'count' => test_count, + 'seed' => options[:seed], + 'rev' => REVISION + } + end + + # + def case_record(test_case) + { + 'type' => 'case', + 'label' => test_case.to_s, + 'level' => 0 + } + end + + # + def test_record(result) + failure = result.failure + + record = { + 'type' => 'test', + 'status' => status(failure), + 'label' => label(result) + } + record['exception'] = exception_record(failure) if failure + + stdout, stderr = captured_output + record['stdout'] = stdout unless stdout.empty? + record['stderr'] = stderr unless stderr.empty? + + record['time'] = Time.now - @suite_start + record + end + + # + def final_record + { + 'type' => 'final', + 'time' => Time.now - @suite_start, + 'counts' => { + 'total' => count, + 'pass' => count - failures - errors - skips, + 'fail' => failures, + 'error' => errors, + 'omit' => skips, + 'todo' => 0 + } + } + end + + # TAP-Y/J calls a skipped test omitted. + def status(failure) + case failure + when nil then 'pass' + when Minitest::UnexpectedError then 'error' + when Minitest::Skip then 'omit' + else 'fail' + end + end + + # The name of the test. Minitest::Spec names a test + # `test_0001_does something`; the label is the part that was written. + def label(result) + result.name.to_s.sub(/\Atest_\d{4}_/, '') + end + + # The name of the class the test belongs to. + def case_name(result) + result.respond_to?(:klass) ? result.klass.to_s : result.class.name + end + + # + def exception_record(failure) + error = actual_error(failure) + backtrace = clean_backtrace(failure.backtrace || error.backtrace) + file, line = location(backtrace) + + record = { 'message' => error.message.to_s.strip, 'class' => error.class.name } + + if file + record['file'] = file + record['line'] = line + if lines = source(file) + record['source'] = lines[line - 1].to_s.strip + record['snippet'] = snippet(lines, line) + end + end + + record['backtrace'] = backtrace + record + end + + # Minitest wraps an error raised by a test in an UnexpectedError. + def actual_error(failure) + return failure unless Minitest::UnexpectedError === failure + failure.respond_to?(:error) ? failure.error : failure.exception + end + + # The backtrace without the test framework, without the method + # names, and with paths relative to the working directory. + def clean_backtrace(backtrace) + trace = Minitest.filter_backtrace(Array(backtrace)) + trace = trace.reject { |line| line.start_with?(LIB_DIRECTORY) } + trace.map do |line| + line.sub(/:in .*\z/m, '').sub(Dir.pwd + File::SEPARATOR, '') + end + end + + # File and line number of the first line of a backtrace. + def location(backtrace) + md = /\A(.+?):(\d+)\z/.match(backtrace.first.to_s) + md ? [md[1], md[2].to_i] : [nil, nil] + end + + # The lines of a source file, or nil if it can't be read. + def source(file) + return @source_cache[file] if @source_cache.key?(file) + @source_cache[file] = File.file?(file) ? File.readlines(file) : nil + end + + # The lines around a line of source, as a list of number => text. + def snippet(lines, line) + first = [line - SNIPPET_RADIUS, 1].max + last = [line + SNIPPET_RADIUS, lines.size].min + (first..last).map { |n| { n => lines[n - 1].chomp } } + end + + # How many tests are about to run. + # + # Asking a class for its tests shuffles them, which draws on Ruby's + # random numbers. So they are seeded again afterwards, and the tests + # run in the order they would have without Minitap. + def test_count + total = Minitest::Runnable.runnables.inject(0) do |sum, runnable| + sum + selected_methods(runnable).size + end + srand options[:seed] if options[:seed] + total + end + + # The tests of a class that Minitest's name options select. The + # option is `:include` in Minitest 6 and `:filter` before. + def selected_methods(runnable) + methods = runnable.runnable_methods + wanted = name_pattern(options[:include] || options[:filter]) + spurned = name_pattern(options[:exclude]) + methods = methods.select { |m| wanted === m || wanted === "#{runnable}##{m}" } if wanted + methods = methods.reject { |m| spurned === m || spurned === "#{runnable}##{m}" } if spurned + methods + rescue NotImplementedError + [] + end + + # A name option written `/like this/` is a regular expression. + def name_pattern(pattern) + String === pattern && pattern =~ %r{/(.*)/} ? Regexp.new($1) : pattern + end + + # + def capture_io + @real_stdout, @real_stderr = $stdout, $stderr + @stdout, @stderr = StringIO.new, StringIO.new + $stdout, $stderr = @stdout, @stderr + end + + # + def release_io + $stdout = @real_stdout if $stdout.equal?(@stdout) + $stderr = @real_stderr if $stderr.equal?(@stderr) + end + + # What has been printed since the last record, as two strings. + def captured_output + [@stdout, @stderr].map do |capture| + text = capture.string.dup + capture.truncate(0) + capture.rewind + text + end + end + + end + + # Reports in TAP-Y, a stream of YAML documents. + class TapY < Reporter + + def initialize(io = $stdout, options = {}) + require 'yaml' + super + end + + private + + def emit(record) + io.puts record.to_yaml + end + + def finish + io.puts '...' + end + + end + + # Reports in TAP-J, a JSON document on each line. + class TapJ < Reporter + + def initialize(io = $stdout, options = {}) + require 'json' + super + end + + private + + def emit(record) + io.puts JSON.generate(record) + end + + end + +end diff --git a/lib/minitap/version.rb b/lib/minitap/version.rb new file mode 100644 index 0000000..ba701d1 --- /dev/null +++ b/lib/minitap/version.rb @@ -0,0 +1,3 @@ +module Minitap + VERSION = '0.6.0' +end diff --git a/lib/minitest/minitap_plugin.rb b/lib/minitest/minitap_plugin.rb index 2202821..19f0d73 100644 --- a/lib/minitest/minitap_plugin.rb +++ b/lib/minitest/minitap_plugin.rb @@ -1,40 +1,20 @@ -module Minitest +# Minitest finds this file by its name. Minitest 5 loads it on its own +# when the gem is installed; `Minitest.load :minitap` loads it too. +# +# Requiring `minitap` registers the plugin as a module where Minitest +# supports that (5.24 and newer). The methods below are for older +# versions, which only know plugins by name. - # - def self.plugin_minitap_options(opts, options) - opts.on "--tapy", "Use TapY reporter." do - options[:minitap] = 'tapy' - end +require 'minitap' - opts.on "--tapj", "Use TapJ reporter." do - options[:minitap] = 'tapj' - end +module Minitest - # DEPRECATED Thanks to minitest-reporter-api gem. - #unless options[:minitap] - # if defined?(Minitest::TapY) && self.reporter == Minitest::TapY - # options[:minitap] = 'tapy' - # elsif defined?(Minitest::TapJ) && self.reporter == Minitest::TapJ - # options[:minitap] = 'tapj' - # end - #end + def self.plugin_minitap_options(opts, options) + Minitap.minitest_plugin_options(opts, options) unless Minitap.registered? end - # def self.plugin_minitap_init(options) - if options[:minitap] - require 'minitap/minitest5' - - self.reporter.reporters.clear - - case options[:minitap] || ENV['rpt'] - when 'tapj' - self.reporter << TapJ.new(options) - when 'tapy' - self.reporter << TapY.new(options) - end - end + Minitap.minitest_plugin_init(options) unless Minitap.registered? end end - diff --git a/minitap.gemspec b/minitap.gemspec new file mode 100644 index 0000000..a9ec860 --- /dev/null +++ b/minitap.gemspec @@ -0,0 +1,39 @@ +require_relative 'lib/minitap/version' + +Gem::Specification.new do |s| + s.name = 'minitap' + s.version = Minitap::VERSION + s.summary = 'TAP-Y/J reporters for Minitest' + s.description = 'Minitap is a Minitest plugin that reports test results in TAP-Y ' \ + 'or TAP-J, for Tapout to render in any of its formats.' + + s.authors = ['Trans'] + s.email = ['transfire@gmail.com'] + s.homepage = 'https://github.com/rubyworks/minitap' + s.license = 'BSD-2-Clause' + + s.metadata = { + 'homepage_uri' => s.homepage, + 'source_code_uri' => 'https://github.com/rubyworks/minitap', + 'bug_tracker_uri' => 'https://github.com/rubyworks/minitap/issues', + 'changelog_uri' => 'https://github.com/rubyworks/minitap/blob/master/HISTORY.md', + 'documentation_uri' => 'https://rubydoc.info/gems/minitap' + } + + s.required_ruby_version = '>= 2.7' + + s.files = Dir[ + 'lib/**/*.rb', 'demo/**/*', + '.yardopts', 'README.md', 'HISTORY.md', 'LICENSE.txt', 'NOTICE.md' + ] + s.require_paths = ['lib'] + s.extra_rdoc_files = ['HISTORY.md', 'README.md', 'LICENSE.txt', 'NOTICE.md'] + + s.add_dependency 'minitest', '>= 5.11', '< 7' + s.add_dependency 'tapout', '>= 0.5' + s.add_dependency 'json' + + s.add_development_dependency 'rake', '>= 13' + s.add_development_dependency 'qed', '>= 2.9' + s.add_development_dependency 'ae', '>= 1.8' +end diff --git a/var/authors b/var/authors deleted file mode 100644 index 11e7d54..0000000 --- a/var/authors +++ /dev/null @@ -1,2 +0,0 @@ ---- -- trans diff --git a/var/copyrights b/var/copyrights deleted file mode 100644 index 7a0c449..0000000 --- a/var/copyrights +++ /dev/null @@ -1,2 +0,0 @@ ---- -- 2011 Rubyworks (BSD-2-Clause) diff --git a/var/description b/var/description deleted file mode 100644 index d04bf43..0000000 --- a/var/description +++ /dev/null @@ -1 +0,0 @@ -MiniTap provides a MiniTest TAP-Y/J report format suitable for use with TAPOUT. diff --git a/var/name b/var/name deleted file mode 100644 index 190bd1e..0000000 --- a/var/name +++ /dev/null @@ -1 +0,0 @@ -minitap \ No newline at end of file diff --git a/var/organization b/var/organization deleted file mode 100644 index 5568880..0000000 --- a/var/organization +++ /dev/null @@ -1 +0,0 @@ -rubyworks diff --git a/var/repositories b/var/repositories deleted file mode 100644 index 77af6aa..0000000 --- a/var/repositories +++ /dev/null @@ -1,2 +0,0 @@ ---- -upstream: git://github.com/rubyworks/minitap.git diff --git a/var/requirements b/var/requirements deleted file mode 100644 index e5fbbcc..0000000 --- a/var/requirements +++ /dev/null @@ -1,8 +0,0 @@ ---- -- tapout 0.3.0+ -- minitest 5.0~ -- minitest-reporter-api 0.0.2+ -- qed (test) -- ae (test) -- ergo (build) - diff --git a/var/resources b/var/resources deleted file mode 100644 index 5e3f4cb..0000000 --- a/var/resources +++ /dev/null @@ -1,7 +0,0 @@ ---- -home: http://rubyworks.github.com/minitap -docs: http://rubydoc.info/gems/minitap -code: http://github.com/rubyworks/minitap -bugs: http://github.com/rubyworks/minitap/issues -mail: http://groups.google.com/group/rubyworks-mailinglist - diff --git a/var/summary b/var/summary deleted file mode 100644 index be00c5c..0000000 --- a/var/summary +++ /dev/null @@ -1 +0,0 @@ -TAP-Y/J reporters for MiniTest \ No newline at end of file diff --git a/var/title b/var/title deleted file mode 100644 index 32c03ca..0000000 --- a/var/title +++ /dev/null @@ -1 +0,0 @@ -MiniTap \ No newline at end of file diff --git a/var/version b/var/version deleted file mode 100644 index be14282..0000000 --- a/var/version +++ /dev/null @@ -1 +0,0 @@ -0.5.3 diff --git a/work/minitest4/Gemfile b/work/minitest4/Gemfile deleted file mode 100644 index d281984..0000000 --- a/work/minitest4/Gemfile +++ /dev/null @@ -1,10 +0,0 @@ -source "https://rubygems.org" - -gem "minitest", "~> 4.0" - -group "test" do - gem "tapout", ">= 0.3.0" - gem "qed" - gem "ae" -end - diff --git a/work/minitest4/applique/ae.rb b/work/minitest4/applique/ae.rb deleted file mode 100644 index 84ae3d2..0000000 --- a/work/minitest4/applique/ae.rb +++ /dev/null @@ -1 +0,0 @@ -require 'ae' diff --git a/work/minitest4/applique/cli.rb b/work/minitest4/applique/cli.rb deleted file mode 100644 index e72fd76..0000000 --- a/work/minitest4/applique/cli.rb +++ /dev/null @@ -1,43 +0,0 @@ -require 'tapout' - -When 'Given a MiniTest testcase' do |text| - @test = text -end - -When 'Running it with the (((.*?))) format' do |type| - File.open('test.rb', 'w'){ |f| - f << test_helper(type) + "\n\n" + @test - } - - @out = `ruby -I../../lib test.rb` - - #@stream = YAML.load_documents(@out) # b/c of bug in Ruby 1.8 - @stream = ( - s = [] - YAML.load_documents(@out){ |d| s << d } - s - ) -end - -#When '(((\w+))) reporter should run without error' do |format| -# $stdin = StringIO.new(@tapy) -# $stdout = StringIO.new(out = '') -# -# TapOut.cli(format) -#end - -def test_helper(type) - if type == 'TAP-Y' then - %Q{ - require 'minitap' - MiniTest::Unit.runner = MiniTest::TapY.new - require 'minitest/autorun' - } - else - %Q{ - require 'minitap' - MiniTest::Unit.runner = MiniTest::TapJ.new - require 'minitest/autorun' - } - end -end diff --git a/work/minitest4/fixtures/tapy.yml b/work/minitest4/fixtures/tapy.yml deleted file mode 100644 index c116e8c..0000000 --- a/work/minitest4/fixtures/tapy.yml +++ /dev/null @@ -1,78 +0,0 @@ ---- -type: suite -start: '2011-10-06 18:48:08' -count: 3 -seed: 36440 -rev: 2 ---- -type: case -subtype: '' -label: ExampleTestCase -level: 0 ---- -type: test -subtype: '' -status: error -label: test_error -exception: - message: ! 'RuntimeError:' - file: example.rb - line: 10 - snippet: - - 8: '' - - 9: ! ' def test_error' - - 10: ! ' raise' - - 11: ! ' end' - - 12: '' - backtrace: - - example.rb:10 -time: 0.001054606 ---- -type: test -subtype: '' -status: fail -label: test_failing -exception: - message: ! "Expected: \"1\"\n Actual: \"2\"" - file: example.rb - line: 14 - snippet: - - 12: '' - - 13: ! ' def test_failing' - - 14: ! ' assert_equal(''1'', ''2'')' - - 15: ! ' end' - - 16: '' - backtrace: - - example.rb:14 - - /home/trans/com/programs/rubyworks/minitap/lib/minitap.rb:456 - - /home/trans/com/programs/rubyworks/minitap/lib/minitap.rb:103 - - /home/trans/com/programs/rubyworks/minitap/lib/minitap.rb:88 - - /home/trans/com/programs/rubyworks/minitap/lib/minitap.rb:88 - - /home/trans/com/programs/rubyworks/minitap/lib/minitap.rb:88 - - /home/trans/com/programs/rubyworks/minitap/lib/minitap.rb:73 - - /home/trans/com/programs/rubyworks/minitap/lib/minitap.rb:73 - - /home/trans/com/programs/rubyworks/minitap/lib/minitap.rb:73 - - /home/trans/com/programs/rubyworks/minitap/lib/minitap.rb:146 - - /home/trans/com/programs/rubyworks/minitap/lib/minitap.rb:72 - - /home/trans/com/programs/rubyworks/minitap/lib/minitap.rb:48 - - /home/trans/com/programs/rubyworks/minitap/lib/minitap.rb:47 - - /home/trans/com/programs/rubyworks/minitap/lib/minitap.rb:47 -time: 0.046170916 ---- -type: test -subtype: '' -status: pass -label: test_passing -time: 1.04997403 ---- -type: tally -time: 1.000800203 -counts: - total: 3 - pass: 1 - fail: 1 - error: 1 - omit: 0 - todo: 0 -... - diff --git a/work/minitest4/minitest.md b/work/minitest4/minitest.md deleted file mode 100644 index e3561ba..0000000 --- a/work/minitest4/minitest.md +++ /dev/null @@ -1,94 +0,0 @@ -# Minitap - -Given a Minitest testcase: - - class ExampleTestCase < MiniTest::Unit::TestCase - def test_error - raise - end - - def test_failing - assert_equal('1', '2') - end - - def test_passing - sleep 1 - assert_equal('1', '1') - end - end - -Running it with the TAP-Y format should work without error. - -The resulting document stream should exhibit the following -characteristics. - -There should be six sections. - - @stream.size #=> 6 - -The first should be a `suite` with a count of `3`. - - @stream.first['type'] #=> 'suite' - @stream.first['count'] #=> 3 - -The second should be `case` entry. - - @stream[1]['type'] #=> 'case' - @stream[1]['label'] #=> 'ExampleTestCase' - @stream[1]['level'] #=> 0 - -The next three documents are the unit tests, which can occur in any order. -There's one that should have a status of `pass`, another of `fail` and the -third of `error`. - - passing_test = @stream.find{ |d| d['type'] == 'test' && d['status'] == 'pass' } - failing_test = @stream.find{ |d| d['type'] == 'test' && d['status'] == 'fail' } - erring_test = @stream.find{ |d| d['type'] == 'test' && d['status'] == 'error' } - -The passing test should have the following charactersitics. - - passing_test['label'] #=> 'test_passing' - -The failing test should - - failing_test['label'] #=> "test_failing" - failing_test['exception']['class'] #=> "MiniTest::Assertion" - failing_test['exception']['file'] #=> "test.rb" - failing_test['exception']['line'] #=> 13 - failing_test['exception']['source'] #=> "assert_equal('1', '2')" - -The failing test should also not have any mention of minitap in the -backtrace. - - failing_test['exception']['backtrace'].each do |e| - /minitap/.refute.match(e) - end - -The erring test should - - erring_test['label'] #=> 'test_error' - erring_test['exception']['class'] #=> 'RuntimeError' - erring_test['exception']['file'] #=> 'test.rb' - erring_test['exception']['line'] #=> 9 - erring_test['exception']['source'] #=> 'raise' - -The erring test should also not have any mention of minitap in the -backtrace. - - erring_test['exception']['backtrace'].each do |e| - /minitap/.refute.match(e) - end - -The last should a `final` document. - - @stream.last['type'] #=> 'final' - -And it should have the following counts. - - @stream.last['counts']['total'] #=> 3 - @stream.last['counts']['error'] #=> 1 - @stream.last['counts']['fail'] #=> 1 - @stream.last['counts']['pass'] #=> 1 - @stream.last['counts']['omit'] #=> 0 - @stream.last['counts']['todo'] #=> 0 - diff --git a/work/test_example.rb b/work/test_example.rb deleted file mode 100644 index 6debc98..0000000 --- a/work/test_example.rb +++ /dev/null @@ -1,39 +0,0 @@ -require 'minitest/autorun' - -#require 'minitap' -#MiniTest::Unit.runner = MiniTest::TapJ.new - -#require "minitest/reporters" -#MiniTest::Reporters.use! MiniTest::Reporters::SpecReporter.new - -#require 'active_support/core_ext' # why do i have to require this? - -class TestThis < Minitest::Test - - def method1 - puts "this will break tapout because of malformed output" - true - end - - def method2 - puts "this will also break tapout because of malformed output" - true - end - - def test_broken1 - assert method1 - end - - def test_broken2 - assert method2 - end - - def test_fine - assert true - end - - def test_not_fine - assert false - end - -end