minitest-markdown 0.0.1.pre → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 6836d7576d3a208628f401e2660fac20d4288faf95c6513e76dd20a2a402fed2
4
- data.tar.gz: 4f38166f7ff54f9a74391daafe8e698a7f0aabc57cf7a3797f292b3b8d85d524
3
+ metadata.gz: 497033589078efbc020edf7c16075dc2c72af705ef81b947ef9e3f9532abdae3
4
+ data.tar.gz: c2919ce835a3dd9326cf66efdabd6fa2a739459cb236b3ac4b4dd5d1102784e1
5
5
  SHA512:
6
- metadata.gz: 393bc3aff42df19c5cfd10c2edddb64242798765d30aed3185e44be621547e0ed93f495113cca4082e388ab20f2da213f4f5ad4411b17f6117b1421c531d066a
7
- data.tar.gz: a30d096c73f2064311cb2d729305fe5cc1d00cca871575fb75783d8046d28f5fc325d92882ccb886834358ed6a586f36eb397439829fba22f4d875c2f6e61998
6
+ metadata.gz: 152b82cbb368756281c6da8523de466e35a4a546c748282769282bfcf5cf799b66e8ba380246dda6e4c700589d2fbe5708d0d150de21c201b1d76254029721ee
7
+ data.tar.gz: bc042b387c85a1e1a57372a825064b54665fe1e541933b1e74d3c2932ee765477b334c4bbb7d2272fac6bfb5fbbfe6df0c2c1a6c7202ff1e2544a8cf8f2c6a99
data/CHANGELOG.md CHANGED
@@ -1,5 +1,38 @@
1
1
  ## [Unreleased]
2
2
 
3
+ ## [0.0.1] - 2025-05-22
4
+
5
+ - Fix bug with Minitest::Hooks method definitions
6
+
7
+ ## [0.0.0] - 2025-05-10
8
+
9
+ - Fix bug in TestCodeBlock error message
10
+ - Add binding to Kernel.eval fixes #1
11
+ - pass kwargs to stub methods in StubProc
12
+
13
+ ## [0.2.2.pre] - 2025-05-08
14
+
15
+ - Improve magic comment & hook comment parsing
16
+ - Fix bug with empty sting after magic comment
17
+ - Fix bug in config if Bundler undefined
18
+
19
+ ## [0.2.1.pre] - 2025-05-07
20
+
21
+ - Fix issue with require in eval
22
+ - Fix bug in StubChain where instance was mutated after #call
23
+
24
+ ## [0.2.0.pre] - 2025-05-06
25
+
26
+ - Add ability to pass any number of stubs to a test code block
27
+
28
+ ### Breaking changes
29
+ - StubChain class replaces Stubb module see https://gitlab.com/matzfan/minitest-markdown#stubbing
30
+
31
+ ## [0.1.0.pre] - 2025-05-01
32
+
33
+ - Add ability to pass stubs to test class
34
+ - Add dependency; minitest-stub_any_instance
35
+
3
36
  ## [0.0.1.pre] - 2025-04-24
4
37
 
5
38
  - Bump minitest dep to >= 5.25.2
data/README.md CHANGED
@@ -5,10 +5,11 @@
5
5
 
6
6
  ## \_why?
7
7
 
8
- Document your Gem's usage, examples etc. with fully testable code! Better still, use your README as a BDD aid and specify functionaility in your README/wiki code blocks *before* you write your code!!
8
+ Document your Gem's usage, examples etc. with fully testable code! Better still, use your README as a BDD aid and specify functionality in your README/wiki code blocks *before* you write your code!!
9
9
 
10
10
  ## Installation
11
11
 
12
+
12
13
  Add the gem to the application's Gemfile:
13
14
 
14
15
  ```bash
@@ -21,6 +22,17 @@ If bundler is not being used to manage dependencies, install the gem by executin
21
22
  gem install minitest-markdown
22
23
  ```
23
24
 
25
+ ## Configuration
26
+
27
+ No configuration is required if you use Bundler. If not, set your `project_root` path using the setter method:
28
+ ```ruby
29
+ @config = Minitest::Markdown.config
30
+ # => instance_of Configuration
31
+
32
+ Configuration.instance_methods(false)
33
+ # => includes :project_root=
34
+ ```
35
+
24
36
  ## Usage
25
37
 
26
38
  ### In your test class
@@ -29,17 +41,24 @@ To test the Ruby blocks in your README file, create file `test_readme.rb` (for e
29
41
  ```ruby
30
42
  require 'minitest/autorun' # or in your test_helper
31
43
  require 'minitest/markdown' # ditto
44
+ require 'minitest/hooks/test' # optional, see 'State' section below
45
+
46
+ class ReadmeTest < Minitest::Test # or your own subclass of Minitest::Test
47
+ include Minitest::Hooks # optional, see 'State' section below
32
48
 
33
- class ReadmeTest < MyTest # your own subclass of Minitest::Test
34
49
  Markdown.generate_markdown_tests(self)
35
50
  end
36
- # => nil
51
+ # => truthy
37
52
  ```
38
53
  To test Ruby blocks in another Markdown file, create another test file and pass the path to your Markdown file using the `:path` keyword arg i.e. `Markdown.generate_markdown_tests(self, path: '/path/to/your/markdown/file.md')`
39
54
 
40
55
  ### In your Markdown - magic comments become assertions
41
56
 
42
- Each Markdown file is represented by a single test class and each Ruby block in a file becomes a test method with zero or more assertions. The syntax used is `# => ` followed by an assertion keyword. Keywords may be one of the [Minitest "assert_" assertions](https://docs.seattlerb.org/minitest/Minitest/Assertions.html) less the "assert_" prefix (refutations are not implemented at this time). If the keyword is omitted, the default assertion; `assert_equal` is used. The actual value passed to the assertion is the result of the evaluation of the Ruby code above each magic comment. The following block (a single test) includes 3 assertions:
57
+ Each Markdown file is represented by a single test class and each Ruby block* in a file becomes a test method with zero or more assertions. Test methods are named according to their index; `test_block0`, `test_block1` etc.
58
+
59
+ \*Any 'state' blocks are excluded from indexing - see State section below
60
+
61
+ The syntax used for assertions is `# => ` followed by an assertion keyword. Keywords may be any one of the [Minitest "assert_" assertions](https://docs.seattlerb.org/minitest/Minitest/Assertions.html) less the "assert_" prefix (refutations are not implemented at this time). If the keyword is omitted, the default assertion; `assert_equal` is used. The actual value passed to the assertion is the result of the evaluation of the Ruby code above each magic comment. The following block (a single test) includes 6 assertions:
43
62
  ```ruby
44
63
  File.read 'test/fixtures/klass.rb'
45
64
  # => "class Klass\n def hello\n 'Hello Markdown!'\n end\nend"
@@ -53,12 +72,15 @@ Klass.new # inline comments are also ignored
53
72
  # The assertion and expected value are:-
54
73
  # => instance_of Klass
55
74
 
56
- # No keywword here, so the default assertion is used (assert_equal)
75
+ # No keyword here, so the default assertion is used (assert_equal)
57
76
  Klass.new.hello
58
77
  # => 'Hello Markdown!'
59
78
 
60
79
  Klass.hello
61
80
  # => raises NoMethodError
81
+
82
+ self
83
+ # => instance_of Markdown::TestClass
62
84
  ```
63
85
  Plain old `assert` has been aliased as `assert_truthy`, so when expecting a truthy value you should do this:
64
86
  ```ruby
@@ -72,7 +94,7 @@ For convenience, the assertion `assert_includes` has also been aliased so that i
72
94
  2
73
95
  # => included_in [1, 2, 3]
74
96
  ```
75
- Everything on the magic comment line after the keyword, or `# => `, if one is omitted, is evaluated as Ruby code. Note: **inline comments are NOT ALLOWED on magic comment lines**. Where an assertion takes multiple positional args, these are simply separated by commas. Note that the assertion keyword itself is **not an argument**. The syntax is as follows:
97
+ Everything on the magic comment line after the assertion keyword, or `# => ` if one is omitted, is evaluated as Ruby code. Note: **inline comments are NOT ALLOWED on magic comment lines**. Where an assertion takes multiple positional args, these are simply separated by commas. Note that the assertion keyword itself is **not an argument**. The syntax is as follows:
76
98
  ```ruby
77
99
  22/7.0
78
100
  # => in_delta Math::PI, 0.01
@@ -82,36 +104,103 @@ To skip a test, use `skip`, as you would in a regular test:
82
104
  "some code which you don't want to test yet"
83
105
  # => skip 'give a reason for the skip here'
84
106
  ```
107
+ Test failures will look like this - note the method name `test_block10` in this example:
108
+ ```
109
+ Minitest::Markdown::ReadmeTest#test_block10 [lib/minitest/markdown/test_class.rb:118]:
110
+ Expected: 42
111
+ Actual: 0
112
+ ```
85
113
 
86
114
  ### State
87
115
 
88
- Minitest's `setup` and `teardown` methods are generated by using the appropriate comment on the first line of a code block. Magic comments are ignored in such blocks, as these are not tests. E.g.
116
+ Instance vars are shared across test methods within a class, but as Minitest's default is to run tests in random order you may want to use a setup block in order to ensure a stored value is available to all test blocks (tests) in the Markdown file test class (see below):
117
+ ```ruby
118
+ @instance_var
119
+ # => 7
120
+
121
+ @before_all_instance_var # see hook methods below
122
+ # => 'foo'
123
+ ```
124
+ Minitest's `setup` and `teardown` methods are generated by using the appropriate comment on the first line of a code block. Assertion magic comments are ignored in such blocks, as these are not tests. E.g.
125
+
89
126
  ```ruby
90
127
  # setup
91
128
 
92
- @instance_var = 42
129
+ # do some setup task - or:-
130
+ @instance_var = 7 # now available in all test method blocks, including the one above
131
+ # => IGNORED
93
132
  ```
94
- The instance var set is now available to all test blocks (tests) in the Markdown file.
95
133
  ```ruby
96
- @instance_var
97
- # => 42
134
+ # teardown
135
+
136
+ # do some teardown task
98
137
  ```
99
- The hook methods defined in the [minitest-hooks](https://github.com/jeremyevans/minitest-hooks?tab=readme-ov-file#in-tests-minitesttest-) extension (`before_all`, `after_all`, `around` & `around_all`)are also available in this way if `minitest-hooks` is installed and `Minitest::Hooks` is included in your test class.
138
+ The hook methods defined in the [minitest-hooks](https://github.com/jeremyevans/minitest-hooks?tab=readme-ov-file#in-tests-minitesttest-) extension (`before_all`, `after_all`, `around` & `around_all`)are also available in this way if `minitest-hooks` is installed and `Minitest::Hooks` is included in your markdown test class. See the 'In your test class' section above for an example. You can now do this:
100
139
 
140
+ ```ruby
141
+ # before_all
142
+ @before_all_instance_var = 'foo'
143
+ ```
101
144
 
102
- Everything in the code blocks above runs as test code. [minitest-proveit](https://github.com/seattlerb/minitest-proveit) would complain otherwise ;-)
145
+ Everything in the Ruby code blocks above and below here runs as test code. [minitest-proveit](https://github.com/seattlerb/minitest-proveit) would complain otherwise ;-)
103
146
 
104
- ## Configuration
147
+ ### Mocks
105
148
 
106
- No configuation is required if you use Bundler. If not, set your `project_root` path using the setter method:
149
+ Mocks use the "mock" keyword for [assert_mock](https://docs.seattlerb.org/minitest/Minitest/Assertions.html#method-i-assert_mock) in place of the equivalent `mock.verify`:
107
150
  ```ruby
108
- @config = Markdown.config
109
- # => instance_of Configuration
151
+ @mymock = Minitest::Mock.new
152
+ @mymock.expect(:puts, nil, ['Hello World!'])
110
153
 
111
- Configuration.instance_methods(false)
112
- # => includes :project_root=
154
+ @mymock.puts 'Hello World!'
155
+ # => mock @mymock
156
+ ```
157
+
158
+ ### Stubbing
159
+
160
+ It is possible to pass stubs to the generated tests. This is done using the stubs keyword. Hash keys represent the index of the test code block. **Important: any 'state' blocks are ignored for test code block indexing**. The hash value must be an instance of `Minitest::StubChain` which holds a proc for each stub in the chain. For convenience `StubChain.stubproc` returns a suitable stub proc object which is called around the relevant test code. Zero or more of these reusable procs can be used to instantiate a StubChain object:
161
+ ```ruby
162
+ class MarkdownTest < Minitest::Test
163
+ set_stubs_new = Minitest::StubChain.stubproc(Set, :new, []) # returns a proc which stubs Set.new to return an empty array
164
+ array_stubs_size = Minitest::StubChain.stubproc(Array, :size, 42, any_instance: true) # uses the bundled minitest-stub_any_instance gem
165
+
166
+ stub_chain = Minitest::StubChain.new([set_stubs_new]) # initialized with zero or more stub procs
167
+ stub_chain.stubs << array_stubs_size # add another like this if need be
168
+
169
+ stubs = {}
170
+ stubs[10] = stub_chain
171
+ stubs[11] = stub_chain # StubChain instances themselves may be reused
172
+
173
+ Markdown.generate_markdown_tests(self, stubs: stubs)
174
+ end
175
+ # => truthy
176
+ ```
177
+ The 2 stubs in the `StubChain` instance above are demonstrated in the following example:
178
+ ```ruby
179
+ # This is test_block10
180
+ Set.new([1, 'c', :s]).size
181
+ # => 42
182
+
183
+ # Because we added `stubs[10] = stub_chain` above, this is exactly equivalent to:
184
+ #
185
+ # def test_block10
186
+ # Set.stub(:new, []) do
187
+ # Array.stub_any_instance(:size, 42) do
188
+ # assert_equal 42, Set.new([1, 'c', :s]).size
189
+ # end
190
+ # end
191
+ # end
192
+ ```
193
+ Example showing the reuse of a StubChain:
194
+ ```ruby
195
+ # This is test_block11
196
+ Set.new.size
197
+ # => 42
113
198
  ```
114
199
 
200
+ ### Errors
201
+
202
+ All errors subclass `Markdown::Error`
203
+
115
204
  ## Development
116
205
 
117
206
  After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
@@ -120,7 +209,7 @@ To install this gem onto your local machine, run `bundle exec rake install`. To
120
209
 
121
210
  ## Contributing
122
211
 
123
- Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/minitest-markdown. Please checkout a suitably named branch before submitting a PR.
212
+ Bug reports and pull requests are welcome on GitLab at https://gitlab.com/matzfan/minitest-markdown. Please checkout a suitably named branch before submitting a PR.
124
213
 
125
214
  ## License
126
215
 
@@ -2,29 +2,32 @@
2
2
 
3
3
  require 'pathname'
4
4
 
5
- require_relative 'error'
5
+ require_relative 'errors'
6
6
 
7
7
  module Minitest
8
8
  module Markdown
9
9
  # configuration for gem
10
10
  class Configuration
11
- attr_accessor :project_root, :prove_it
11
+ PROJECT_ROOT_UNDETERMINED = "Project root can't be determined, set with 'Markdown.config.project_root = /path'"
12
+
13
+ attr_writer :project_root
14
+ attr_accessor :prove_it
12
15
 
13
16
  def initialize
14
- @project_root = determine_project_root
17
+ @project_root = self.class.determine_project_root
15
18
  @prove_it = true
16
19
  end
17
20
 
18
- def readme_path
19
- project_root.join 'README.md'
21
+ def self.determine_project_root
22
+ Bundler.root if defined? Bundler
20
23
  end
21
24
 
22
- private
23
-
24
- def determine_project_root
25
- return Bundler.root if defined? Bundler
25
+ def project_root
26
+ @project_root || (raise Error, PROJECT_ROOT_UNDETERMINED)
27
+ end
26
28
 
27
- raise Error::MarkdownError, "Project root can't be determined, set with 'Config.project_root = /root/path'"
29
+ def readme_path
30
+ project_root.join 'README.md'
28
31
  end
29
32
  end
30
33
  end
@@ -2,8 +2,6 @@
2
2
 
3
3
  module Minitest
4
4
  module Markdown
5
- module Error
6
- class MarkdownError < StandardError; end
7
- end
5
+ class Error < StandardError; end
8
6
  end
9
7
  end
@@ -1,39 +1,47 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require 'minifyrb' # DEP
3
+ require 'minifyrb'
4
4
 
5
5
  require_relative '../assertions_extensions' # for assert_truthy
6
- require_relative '../markdown/error'
6
+ require_relative '../markdown/errors'
7
7
 
8
8
  module Minitest
9
9
  module Markdown
10
- # A Ruby code block reprenting test code, with 0 or more assertions
11
- class TestCodeBlock
12
- ASSERT_ = 'assert_'
13
- ASSERT_REGEXP = /\A#{ASSERT_}/
14
- SKIP = { skip: :skip }.freeze
10
+ # A Ruby code block representing test code, with 0 or more assertions or a 'state' block
11
+ class RubyCodeBlock
12
+ ASSERT_ = 'assert_'
13
+ ASSERT_REGEXP = /\A#{ASSERT_}/
14
+ SKIP = { skip: :skip }.freeze
15
15
  DEFAULT_ASSERTION = :assert_equal
16
16
 
17
- ASSERTION_KEYS = %i[ruby assertion test_args].freeze
17
+ ASSERTION_KEYS = %i[ruby assertion test_args].freeze
18
+ STATE_BLOCK_TYPES = %i[setup teardown before_all after_all around around_all].freeze
18
19
 
19
- MAGIC_COMMENT_DELIMITER = '# => '
20
- MAGIC_COMMENT_REGEXP = /^#{MAGIC_COMMENT_DELIMITER}.*$/
21
- MAGIC_COMMENT_SCAN_REGEXP = /^#{MAGIC_COMMENT_DELIMITER}(.*)$/ # strips delimiter prefix
20
+ MAGIC_COMMENT_REGEXP = /^\s*#\s*=>.*$/
21
+ MAGIC_COMMENT_SCAN_REGEXP = /^\s*#\s*=>\s*(.*)$/ # strips delimiter prefix
22
+
23
+ MISSING_ASSERTION_OR_VALUE = "Magic comment missing assertion or value. Something must follow '# =>'"
22
24
 
23
25
  attr_reader :fenced_block_str
24
26
 
25
27
  def self.asserts
26
- Assertions.instance_methods.grep(ASSERT_REGEXP) - [:assert_send] # deprecated
28
+ @asserts ||= Assertions.instance_methods.grep(ASSERT_REGEXP) - [:assert_send] # deprecated
27
29
  end
28
30
 
29
31
  def self.assertions_map
30
- asserts.inject({}) { |memo, m| memo.merge(m.to_s.split(ASSERT_)[1..].join.to_sym => m) }.merge(SKIP)
32
+ @assertions_map ||= asserts.inject(SKIP) { |memo, m| memo.merge(m.to_s.split(ASSERT_)[1..].join.to_sym => m) }
31
33
  end
32
34
 
33
35
  def initialize(fenced_block_str)
34
36
  @fenced_block_str = fenced_block_str
35
37
  end
36
38
 
39
+ def type
40
+ STATE_BLOCK_TYPES.each { |type| return type if fenced_block_str.lines.first&.match?(/^\s*#\s*#{type}\s*\n$/) }
41
+
42
+ :test
43
+ end
44
+
37
45
  def assertions
38
46
  assertions_arr.map { |arr| Hash[*ASSERTION_KEYS.zip(arr).flatten] }
39
47
  end
@@ -45,6 +53,8 @@ module Minitest
45
53
  end
46
54
 
47
55
  def parse(magic_comment_string)
56
+ raise ArgumentError, MISSING_ASSERTION_OR_VALUE if magic_comment_string.strip.empty?
57
+
48
58
  assertion = parse_assertion(magic_comment_string)
49
59
  return [DEFAULT_ASSERTION, "[#{magic_comment_string}]"] if assertion.nil?
50
60
  return [assertion, '[]'] if magic_comment_string.split.size == 1
@@ -53,7 +63,7 @@ module Minitest
53
63
  end
54
64
 
55
65
  def parse_assertion(str)
56
- self.class.assertions_map[str.split.first.to_sym]
66
+ self.class.assertions_map[str.split.first.to_sym] # 'nil' => :assert_nil, but 'nil?' => nil
57
67
  end
58
68
 
59
69
  def magic_comments
@@ -64,7 +74,7 @@ module Minitest
64
74
  @fenced_block_str.split(MAGIC_COMMENT_REGEXP).map do |str|
65
75
  Minifyrb::Minifier.new(str).minify.strip
66
76
  rescue SyntaxError
67
- raise Error::MarkdownError, "Syntax error in:\n\n#{str}"
77
+ raise Error, "Syntax error in:\n\n#{str}"
68
78
  end
69
79
  end
70
80
  end
@@ -1,75 +1,88 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require_relative '../assertions_extensions'
4
- require_relative 'test_code_block'
4
+ require_relative 'ruby_code_block'
5
+
6
+ $LOAD_PATH << '.' # fix #2
5
7
 
6
8
  module Minitest
7
9
  module Markdown
8
- # knows how to build a markdown test
10
+ # knows how to build a markdown test class, test methods and 'state' methods
9
11
  class TestClass
10
- FENCED_BLOCK_REGEXP = /^```ruby\n(.*?)\n```/m # TODO: use Lexer/RDoc::Parser? which can deal with md comments
11
- HOOK_METHODS = %i[before_all after_all around around_all].freeze # minitest-hooks extension
12
- NON_TEST_METHODS = %i[setup teardown].freeze
12
+ FENCED_BLOCK_REGEXP = /^```ruby\n(.*?)\n```/m
13
+
14
+ BAD_KLASS = 'TestClass must be instantiated with Minitest::Test or subclass thereof'
15
+ BAD_PATH = 'Path does not exist, is not readable or is not a Markdown file:'
16
+ MD = '.md'
17
+
18
+ HOOK_METHODS_BEFORE = %i[before_all].freeze
19
+ HOOK_METHODS_AFTER = %i[after_all around around_all].freeze
13
20
 
14
21
  attr_reader :klass, :path
15
22
 
16
23
  def initialize(klass, path: nil)
17
- @klass = klass
18
- @config = Markdown.config
19
- @path = path || @config.readme_path
20
- @ruby_blocks = parse_ruby_blocks
24
+ @klass = validate_class klass
25
+ @path = validate_path path
26
+ @state_methods_defined = []
21
27
  end
22
28
 
23
- def define_methods
24
- define_non_test_methods
25
- @ruby_blocks.each_with_index { |block, i| define_test_method(block, i) }
26
- nil
29
+ def define_methods(stubs: {})
30
+ i = 0
31
+ parse_ruby_blocks.each do |block|
32
+ next define_non_test_method(block) unless block.type == :test
33
+
34
+ define_test_method(block, i, stub_chain: stubs[i])
35
+ i += 1
36
+ end
27
37
  end
28
38
 
29
39
  private
30
40
 
31
- def parse_ruby_blocks
32
- File.new(path).read.scan(FENCED_BLOCK_REGEXP).flatten.map { |str| TestCodeBlock.new(str) }
41
+ def validate_class(klass)
42
+ raise ArgumentError, BAD_KLASS unless klass.respond_to?(:ancestors) && klass.ancestors.include?(Minitest::Test)
43
+
44
+ klass
33
45
  end
34
46
 
35
- def define_non_test_methods
36
- recognized_non_test_methods.each { |name| define_non_test_method(name, parse_non_test_method_block(name)) }
47
+ def validate_path(pth)
48
+ return Markdown.config.readme_path if pth.nil?
49
+ raise ArgumentError, "#{BAD_PATH} #{pth}" unless File.exist?(pth) && File.file?(pth) && File.extname(pth) == MD
50
+
51
+ pth
37
52
  end
38
53
 
39
- def recognized_non_test_methods
40
- Minitest.const_defined?(:Hooks) ? NON_TEST_METHODS + HOOK_METHODS : NON_TEST_METHODS
54
+ def parse_ruby_blocks
55
+ File.new(path).read.scan(FENCED_BLOCK_REGEXP).flatten.map { |str| RubyCodeBlock.new(str) }
41
56
  end
42
57
 
43
- def define_non_test_method(type, block)
44
- return unless block
58
+ def define_non_test_method(block)
59
+ type = block.type
60
+ raise Error, "State method: #{type} is already defined" if @state_methods_defined.include? type
45
61
 
46
62
  bind = binding
47
63
  klass.define_method(type) do
48
- super() if type == :before_all
49
- bind.eval(block)
50
- super() if %i[after_all around around_all].include? type
64
+ super() if HOOK_METHODS_BEFORE.include? type
65
+ bind.eval(block.fenced_block_str)
66
+ super() if HOOK_METHODS_AFTER.include? type
51
67
  end
68
+ @state_methods_defined << type
52
69
  end
53
70
 
54
- def parse_non_test_method_block(type)
55
- blocks = @ruby_blocks.map.select { |blk| blk.fenced_block_str.lines.first == "# #{type}\n" }
56
- return if blocks.empty?
57
- raise Error::MarkdownError, "Multiple #{type} blocks are not allowed" if blocks.size > 1
58
-
59
- @ruby_blocks.delete(blocks.first).fenced_block_str # hook method blocks can't be test methods
60
- end
61
-
62
- def define_test_method(block, meth_index)
71
+ def define_test_method(block, meth_index, stub_chain:)
72
+ stub_chain ||= StubChain.new
63
73
  instance = self # scope
64
74
  klass.define_method(:"test_block#{meth_index}") do
65
- block.assertions.each { |assertion_hash| instance.send(:evaluation_assertions, assertion_hash, binding) }
75
+ test_code_proc = proc do
76
+ block.assertions.each { |assertion_hash| instance.send(:evaluation_assertions, assertion_hash, binding) }
77
+ end
78
+ stub_chain.call(test_code_proc)
66
79
  end
67
80
  end
68
81
 
69
82
  def evaluation_assertions(assertion_hash, bind)
70
- ruby, assertion, args = TestCodeBlock::ASSERTION_KEYS.map { |key| assertion_hash[key] } # order dep
83
+ ruby, assertion, args = RubyCodeBlock::ASSERTION_KEYS.map { |key| assertion_hash[key] } # order dep
71
84
 
72
- lmbda = -> { eval(ruby) } # rubocop:disable Security/Eval
85
+ lmbda = -> { kernel_eval(ruby) }
73
86
  return unless assertion
74
87
  return eval_with_block(bind, assertion, lmbda, args) if Assertions::WITH_BLOCK_EVAL.include? assertion
75
88
 
@@ -79,20 +92,27 @@ module Minitest
79
92
  def eval_with_block(bind, assertion, actual, args)
80
93
  return bind.receiver.send(assertion, &actual) if args.empty?
81
94
 
82
- bind.receiver.send(assertion, *eval(args), &actual) # rubocop:disable Security/Eval
95
+ bind.receiver.send(assertion, *kernel_eval(args), &actual)
83
96
  end
84
97
 
85
98
  def eval_without_block(bind, assertion, lmbda, args)
86
99
  actual = lmbda.call
87
100
  return bind.receiver.send(assertion, actual) if args == '[]'
88
101
 
89
- expected, *rest = eval(args) # rubocop:disable Security/Eval
102
+ expected, *rest = kernel_eval(args)
90
103
  expected, actual = actual, expected if Assertions::EXPECTED_ACTUAL_REVERSED.include? assertion
91
104
  kwargs = rest.last.is_a?(Hash) ? rest.last : nil
92
105
  return bind.receiver.send(assertion, expected, actual, *rest) unless kwargs
93
106
 
94
107
  bind.receiver.send(assertion, expected, actual, *rest, **kwargs) # assert_respond_to takes a kwarg..
95
108
  end
109
+
110
+ def kernel_eval(str)
111
+ bind = binding
112
+ bind.eval str
113
+ rescue SyntaxError
114
+ raise ArgumentError, "Invalid test code, failed to parse #{str}"
115
+ end
96
116
  end
97
117
  end
98
118
  end
@@ -2,6 +2,6 @@
2
2
 
3
3
  module Minitest
4
4
  module Markdown
5
- VERSION = '0.0.1.pre'
5
+ VERSION = '0.0.1'
6
6
  end
7
7
  end
@@ -1,13 +1,18 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require 'minitest/stub_any_instance'
4
+
5
+ require_relative 'stub_chain'
3
6
  require_relative 'markdown/configuration'
4
- require_relative 'markdown/error'
7
+ require_relative 'markdown/errors'
5
8
  require_relative 'markdown/version'
6
9
  require_relative 'markdown/test_class'
7
10
 
8
11
  module Minitest
9
12
  # namespace
10
13
  module Markdown
14
+ ARG_ERR = 'stubs keyword takes a hash. Keys are integers and values are StubChain instances'
15
+
11
16
  class << self
12
17
  def config
13
18
  @config ||= Configuration.new
@@ -17,8 +22,12 @@ module Minitest
17
22
  yield config
18
23
  end
19
24
 
20
- def generate_markdown_tests(klass, path: nil)
21
- TestClass.new(klass, path: path).define_methods
25
+ def generate_markdown_tests(klass, path: nil, stubs: {})
26
+ raise ArgumentError, ARG_ERR unless stubs.is_a? Hash
27
+ raise ArgumentError, ARG_ERR unless stubs.keys.all? { |o| o.instance_of? Integer }
28
+ raise ArgumentError, ARG_ERR unless stubs.values.all? { |o| o.instance_of? StubChain }
29
+
30
+ TestClass.new(klass, path: path).define_methods(stubs: stubs)
22
31
  end
23
32
  end
24
33
  end
@@ -0,0 +1,41 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Minitest
4
+ # respresentaion of zero or more stub blocks around one or more test assertions
5
+ class StubChain
6
+ NOT_CALLABLE_ERR = 'StubChain#call takes a callable argument'
7
+ MUST_NOT_CALL_A_BLOCK_ERR = 'StubChain#call takes a callable argument which must not call a block'
8
+
9
+ attr_reader :stubs
10
+
11
+ def initialize(stubs = [])
12
+ @stubs = *stubs
13
+ end
14
+
15
+ def self.stubproc(klass, *args, any_instance: false, **kwargs)
16
+ return proc { |&blk| klass.stub(*args, **kwargs) { blk.call } } unless any_instance
17
+
18
+ proc { |&blk| klass.stub_any_instance(*args, **kwargs) { blk.call } }
19
+ end
20
+
21
+ def call(test_code_proc)
22
+ validate(test_code_proc)
23
+ call_recursive [*stubs, test_code_proc]
24
+ end
25
+
26
+ private
27
+
28
+ def validate(test_code_proc)
29
+ raise ArgumentError, NOT_CALLABLE_ERR unless test_code_proc.respond_to?(:call)
30
+
31
+ test_code_proc
32
+ end
33
+
34
+ def call_recursive(call_chain)
35
+ prok = call_chain.shift
36
+ return prok.call if call_chain.empty?
37
+
38
+ prok.call { call_recursive(call_chain) }
39
+ end
40
+ end
41
+ end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: minitest-markdown
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.0.1.pre
4
+ version: 0.0.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - MatzFan
@@ -49,6 +49,20 @@ dependencies:
49
49
  - - ">="
50
50
  - !ruby/object:Gem::Version
51
51
  version: 5.25.2
52
+ - !ruby/object:Gem::Dependency
53
+ name: minitest-stub_any_instance
54
+ requirement: !ruby/object:Gem::Requirement
55
+ requirements:
56
+ - - "~>"
57
+ - !ruby/object:Gem::Version
58
+ version: '1.0'
59
+ type: :runtime
60
+ prerelease: false
61
+ version_requirements: !ruby/object:Gem::Requirement
62
+ requirements:
63
+ - - "~>"
64
+ - !ruby/object:Gem::Version
65
+ version: '1.0'
52
66
  description: Generates tests for Ruby code blocks in any Markdown file.
53
67
  executables: []
54
68
  extensions: []
@@ -63,10 +77,11 @@ files:
63
77
  - lib/minitest/assertions_extensions.rb
64
78
  - lib/minitest/markdown.rb
65
79
  - lib/minitest/markdown/configuration.rb
66
- - lib/minitest/markdown/error.rb
80
+ - lib/minitest/markdown/errors.rb
81
+ - lib/minitest/markdown/ruby_code_block.rb
67
82
  - lib/minitest/markdown/test_class.rb
68
- - lib/minitest/markdown/test_code_block.rb
69
83
  - lib/minitest/markdown/version.rb
84
+ - lib/minitest/stub_chain.rb
70
85
  - sig/minitest/markdown.rbs
71
86
  homepage: https://gitlab.com/matzfan/minitest-markdown
72
87
  licenses:
@@ -89,7 +104,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
89
104
  - !ruby/object:Gem::Version
90
105
  version: '0'
91
106
  requirements: []
92
- rubygems_version: 3.6.7
107
+ rubygems_version: 3.7.0.dev
93
108
  specification_version: 4
94
109
  summary: Turn your README.md Ruby code blocks into testable code.
95
110
  test_files: []