mocha-1.3.0/0000755000004100000410000000000013155337745012647 5ustar www-datawww-datamocha-1.3.0/Rakefile0000644000004100000410000001122413155337744014313 0ustar www-datawww-datarequire "bundler" Bundler::GemHelper.install_tasks require "bundler/setup" MOCHA_DOCS_HOST = ENV['MOCHA_DOCS_HOST'] || 'gofreerange.com' require 'rake/testtask' desc "Run all tests" task 'default' => ['test', 'test:performance'] desc "Run tests" task 'test' do if test_library = ENV['MOCHA_RUN_INTEGRATION_TESTS'] Rake::Task["test:integration:#{test_library}"].invoke else Rake::Task['test:units'].invoke Rake::Task['test:acceptance'].invoke end end namespace 'test' do unit_tests = FileList['test/unit/**/*_test.rb'] all_acceptance_tests = FileList['test/acceptance/*_test.rb'] ruby186_incompatible_acceptance_tests = FileList['test/acceptance/stub_class_method_defined_on_*_test.rb'] + FileList['test/acceptance/stub_instance_method_defined_on_*_test.rb'] ruby186_compatible_acceptance_tests = all_acceptance_tests - ruby186_incompatible_acceptance_tests desc "Run unit tests" Rake::TestTask.new('units') do |t| t.libs << 'test' t.test_files = unit_tests t.verbose = true t.warning = true end desc "Run acceptance tests" Rake::TestTask.new('acceptance') do |t| t.libs << 'test' if defined?(RUBY_VERSION) && (RUBY_VERSION >= "1.8.7") t.test_files = all_acceptance_tests else t.test_files = ruby186_compatible_acceptance_tests end t.verbose = true t.warning = true end namespace 'integration' do desc "Run MiniTest integration tests (intended to be run in its own process)" Rake::TestTask.new('minitest') do |t| t.libs << 'test' t.test_files = FileList['test/integration/mini_test_test.rb'] t.verbose = true t.warning = true end desc "Run Test::Unit integration tests (intended to be run in its own process)" Rake::TestTask.new('test-unit') do |t| t.libs << 'test' t.test_files = FileList['test/integration/test_unit_test.rb'] t.verbose = true t.warning = true end end # require 'rcov/rcovtask' # Rcov::RcovTask.new('coverage') do |t| # t.libs << 'test' # t.test_files = unit_tests + acceptance_tests # t.verbose = true # t.warning = true # t.rcov_opts << '--sort coverage' # t.rcov_opts << '--xref' # end desc "Run performance tests" task 'performance' do require File.join(File.dirname(__FILE__), 'test', 'acceptance', 'stubba_example_test') require File.join(File.dirname(__FILE__), 'test', 'acceptance', 'mocha_example_test') iterations = 1000 puts "\nBenchmarking with #{iterations} iterations..." [MochaExampleTest, StubbaExampleTest].each do |test_case| puts "#{test_case}: #{benchmark_test_case(test_case, iterations)} seconds." end end end def benchmark_test_case(klass, iterations) require 'benchmark' require 'mocha/detection/mini_test' if defined?(MiniTest) minitest_version = Gem::Version.new(Mocha::Detection::MiniTest.version) if Gem::Requirement.new('>= 5.0.0').satisfied_by?(minitest_version) result = Benchmark.realtime { iterations.times { |i| klass.run(MiniTest::CompositeReporter.new) } } MiniTest::Runnable.runnables.delete(klass) result else MiniTest::Unit.output = StringIO.new Benchmark.realtime { iterations.times { |i| MiniTest::Unit.new.run([klass]) } } end else load 'test/unit/ui/console/testrunner.rb' unless defined?(Test::Unit::UI::Console::TestRunner) unless $silent_option begin load 'test/unit/ui/console/outputlevel.rb' unless defined?(Test::Unit::UI::Console::OutputLevel::SILENT) $silent_option = { :output_level => Test::Unit::UI::Console::OutputLevel::SILENT } rescue LoadError $silent_option = Test::Unit::UI::SILENT end end Benchmark.realtime { iterations.times { Test::Unit::UI::Console::TestRunner.run(klass, $silent_option) } } end end if ENV["MOCHA_GENERATE_DOCS"] require 'yard' desc 'Remove generated documentation' task 'clobber_yardoc' do `rm -rf ./doc` end task 'docs_environment' do unless ENV['GOOGLE_ANALYTICS_WEB_PROPERTY_ID'] puts "\nWarning: GOOGLE_ANALYTICS_WEB_PROPERTY_ID was not defined\n\n" end end desc 'Generate documentation' YARD::Rake::YardocTask.new('yardoc' => 'docs_environment') do |task| task.options = ["--title", "Mocha #{Mocha::VERSION}"] end desc "Generate documentation" task 'generate_docs' => ['clobber_yardoc', 'yardoc'] desc "Publish docs to #{MOCHA_DOCS_HOST}/docs/mocha" task 'publish_docs' => 'generate_docs' do path = "/home/freerange/docs/mocha" system %{ssh #{MOCHA_DOCS_HOST} "sudo rm -fr #{path} && mkdir -p #{path}" && scp -r doc/* #{MOCHA_DOCS_HOST}:#{path}} end end task 'release' => 'default' do Rake::Task['publish_docs'].invoke end mocha-1.3.0/.gemtest0000644000004100000410000000000013155337744014305 0ustar www-datawww-datamocha-1.3.0/bin/0000755000004100000410000000000013155337744013416 5ustar www-datawww-datamocha-1.3.0/bin/build-matrix0000755000004100000410000000325713155337744015754 0ustar www-datawww-data#!/usr/bin/env ruby require 'yaml' def execute(*commands) commands.each do |command| system(command) unless $?.success? message = [ "Executing shell command failed.", " Command: #{command}", " Status: #{$?.exitstatus}" ].join("\n") raise message end end end def reset_bundle execute( "rm -rf .bundle/gems", "rm -rf gemfiles/.bundle/gems", "rm -f *.lock", "rm -f gemfiles/*.lock" ) end def with_rbenv(command) %{export PATH="$HOME/.rbenv/bin:$PATH"; eval "$(rbenv init -)"; #{command}} end def run(ruby_version, gemfile, task = "test") ENV["RBENV_VERSION"] = ruby_version ENV["BUNDLE_GEMFILE"] = gemfile ENV["MOCHA_OPTIONS"] = "debug" reset_bundle execute( with_rbenv("bundle install --gemfile=#{gemfile}"), with_rbenv("bundle exec rake #{task}"), ) end travis_config = YAML.load(File.read('.travis.yml')) build_configs = travis_config['matrix']['include'] travis_config['rvm'].each do |ruby_version| travis_config['gemfile'].each do |gemfile| travis_config['env'].each do |env| build_configs << { 'rvm' => ruby_version, 'gemfile' => gemfile, 'env' => env } end end end build_configs.each do |config| ruby_version = config['rvm'] gemfile = config['gemfile'] environment_variables = Hash[*config['env'].split.flat_map { |e| e.split('=') }] original_environment_variables = {} begin environment_variables.each do |k, v| original_environment_variables[k] = ENV[k] ENV[k] = v end p [ruby_version, gemfile, environment_variables] run(ruby_version, gemfile) ensure original_environment_variables.each do |k, v| ENV[k] = v end end end mocha-1.3.0/Gemfile0000644000004100000410000000004713155337744014142 0ustar www-datawww-datasource 'https://rubygems.org' gemspec mocha-1.3.0/RELEASE.md0000644000004100000410000012304313155337744014253 0ustar www-datawww-data# Release Notes ## 1.3.0 * Ensure all tests run individually - thanks to @chrisroos (#267) * Update Travis CI build status badge to show master branch status (#264) * Correct RSpec section of the README - thanks to @myronmarston (0cc039c8) * Fix pretty printing of quotes in `String#mocha_inspect` (#215 & #223) * Add release instructions to README - thanks to @chrisroos (70a5febd & 3c664df7) * Require at least Ruby v1.8.7 in gemspec - thanks to @knappe (3e20be8e) * Remove redundant InstanceMethod#method_exists? - thanks to @chrisroos (8f58eddf) * Reduce risk of hitting bug 12832 in Ruby v2.3 - thanks to @chrisroos (#277 & eca7560c) * Fix JRuby build - thanks to @headius (jruby/jruby#4250) & @chrisroos (#274) * Add latest stable version of JRuby to Travis CI build matrix (#288) * Fix Ruby v1.8.7 builds on Travis CI (928b5a40 & 460dce5b) * Deprecate passing block to mock object constructor (#290) * Add a known issue to README for Ruby bug 12876 (#276) * Add Ruby 2.4 and ruby-head to Travis CI build matrix - thanks to @junaruga (#297) * Fix `Mocha::ParameterMatchers#includes` for `Array` values - thanks to @timcraft (#302) * Use faster container-based virtual environments for Travis CI builds (#305) * Rename `Mocha::ParameterMatchers::QueryStringMatches` to `QueryString` (#306) * Handle blank parameter value for query string matcher - thanks to @weynsee (#303 & #304) * Rename `Mocha::ParameterMatchers::QueryString` -> `EquivalentUri` (#307) * Use `do ... end` instead of `{ ... }` in acceptance tests - thanks to @chrisroos (#294) ## 1.2.1 * Fixed #272. Workaround Ruby bug 12832 which caused interpreter to hang. See https://bugs.ruby-lang.org/issues/12832. Thanks to @chrisroos & @petems (6f1c8b9b, #273). ## 1.2.0 * Always use prepended module to stub class & instance methods for Ruby v2+ - thanks to @grosser & @chrisroos (43d56671, #244) * Always use prepended module to stub AnyInstance methods in Ruby v2+ - thanks to @chrisroos (#262) * Always set visibility of stub method to match stubbed method on included module - thanks to @grosser & @chrisroos (e87c03b0, #248) * Always set visibility to stub method to match stubbed method on superclass - thanks to @chrisroos (38d902ad) * Allow stubbing of method to which any instance responds (#200) * Allow `includes` matcher to take matcher arguments - thanks to @lazyatom (#217) * Avoid exception in older version of Rubygems - thanks to @chrisroos (78d930a7) * Add licenses to gemspec as requested by @coreyhaines (#201) * Fix typo in README - thanks to @jaredbeck (6119460d) * Added section about using Mocha with RSpec & Rails to README (#221) * Fix documentation for Mocha::API#stub method - thanks to @raeno (599b1dcd) * Added backers and sponsors from OpenCollective - thanks to @piamancini (#253) * Fix typo in docs for equals - thanks to @alexcoco (#254) * Add known issue for Ruby v1.8 to README - thanks to @chrisroos (2c642096) ## 1.1.0 * Set visibility of any instance stub method. * Stub methods with a prepended method if there are other prepended methods. Thanks to @mrsimo. * Improve docs for `Mock#responds_like` & `#responds_like_instance_of`. * Use GitHub convention for instructions on contributing to Mocha. * Fix typos in docs. Thanks to @10io ## 1.0.0 ### External changes * Assume 'mocha' has been required when requiring 'mocha/setup'. * Provide shortcuts for integrating with specific test library i.e. `require 'mocha/test_unit'` or `require 'mocha/mini_test'` as alternatives to `require 'mocha/setup'`. * Do not automatically try to integrate with test libraries. Since the automatic test library integration functionality requires the test library to be loaded and this doesn't usually happen until *after* the bundle is loaded, it makes things simpler if we use `require 'mocha/setup'` to explicitly setup Mocha when we know the test library has been loaded. Fixes #146 & #155. * Consider stubs on superclasses if none exist on primary receiver. Largely based on changes suggested by @ccutrer in #145. Note: this may break existing tests which rely on the old behaviour. Stubbing a superclass method and then invoking that method on a child class would previously cause an unexpected invocation error. By searching up through the inheritance hierarchy for each of the delegate mock objects, we can provide more intuitive behaviour. Instead of an unexpected invocation error, invoking the method on the child class will cause the stubbed method on the superclass to be used. * Avoid recursion when constructing unexpected invocation message. Fixes #168. * Add explanation of method dispatch. Heavily based on the relevant jMock v1 documentation. Fixes #172. * Make class_eval line number more accurate. This sets the line number as the line number of the `def` statement. Closes #169. * Allow nesting of `responds_with` parameter matcher. Closes #166. * Define `Mocha` module before it's referenced. The test helper defines a class `TestCase` within the `Mocha` module. When running the tests inside the bundle, the `Mocha` module happens to be defined at this point. However when running the tests outside the bundle, it is not defined and so an exception is raised: `uninitialized constant Mocha (NameError)`. Fixes #163. * Document lack of thread-safety. Fixes #154. * Document how to use the build-matrix script. Fixes #160. * Stubbing non-public method should use same visibility. This will probably break some existing tests that were somehow relying on the stubbed method being public while the original method was protected or private. Fixes #150. ### Internal changes * Use lastest Rubygems in Travis CI builds. * Run the standard test suite against Ruby 2.1.0 in the build matrix. * Run integration tests against Ruby 2.0.0 with latest Test::Unit gem in the build matrix. * Test::Unit is not available in Ruby v1.9.3 standard library, so remove it from the build matrix. * Force use of Test::Unit runner, etc in relevant integration tests. Prior to this, I don't think we were really testing the Mocha integration with Test::Unit much, because, although `TestUnitTest` was a subclass of `Test::Unit::TestCase`, the important test case instances are the temporary ones built by `TestRunner#run_as_test` et al. Prior to this change, these would only have used Test::Unit where MiniTest was not available *at all* i.e. only in early versions of Ruby and when the MiniTest gem was not loaded. * Reset environment variables between build matrix builds. * Only activate integration with relevant test library for each of the integration tests. * Include standard build combinations from Travis CI config i.e. builds using standard library versions of test libraries. * Fix `build-matrix.rb` script. Also use `.travis.yml` to decide what combinations to run. This means we can now simulate the Travis CI build locally and avoid duplication. Fixes #157. * Remove Ruby version map from build matrix script. I'm using the `rbenv-aliases` plugin to alias minor versions to the relevant patch version. ## 0.14.0 * Official support for MiniTest v5. All tests now pass on the continuous integration build. ## 0.14.0.alpha * Add speculative support for Minitest v5. Due to incompatibilities it has not yet been possible to run the Mocha test suite against Minitest v5. However, @zenspider (author of Minitest) provided the patch and he has tested it against Rails v4. Fixes #156. Thanks to @zenspider. * Documentation updates. ## 0.13.3 * Allow `Mocha::ParameterMatchers#includes` to accept multiple items. Thanks to @simao. * Allow stubbing of *private* `Kernel` methods. Fixes #134. Thanks to @camski for reporting. * Avoid a warning when `test/unit/version` is required by other libraries in the same project. Fixes #140. Thanks to @tmiller. * Make auto-activation of Test::Unit integration more resilient. This change is specifically to cope with the nasty re-defining of classes that is done by the `minitest-spec-rails` gem. Fixes #143. Thanks to @tubaxenor for reporting. * Safer restoration of stubbed method visibility. Fixes #141. Thanks to @tmm1. * Ensure `Mockery` instance gets reset even if exception raised. Fixes #144. * Adapt Mocha acceptance tests to cope with changes in output from latest (v4.6.2) of MiniTest. * Updates to README about Rails compatibility. ## 0.13.2 * Stubbing of methods re-declared with different visibilty. Fixes #109. * Add `Mock#responds_like_instance_of`. Fixes #119. * Make `Expectation#inspect` less verbose and more useful. Fixes #122. * Make unit tests more robust to changes in environment. Fixes #121. * Update README in an attempt to head Rails-related issues off at the pass. * Add a Gem Badge to provide a link to Mocha on Rubygems. * Make documentation example consistent with other examples. ## 0.13.1 * Fix #97 - `Mocha::ParameterMatchers#has_entry` does not work with an Array as the entry's value. Thanks to @ngokli. * Allow deprecation `:debug` mode to be switched on from `MOCHA_OPTIONS` environment variable. ## 0.13.0 * Major overhaul of MiniTest & Test::Unit integration. Mocha now integrates with later versions of the two test libraries using documented hooks rather than monkey-patching. This should mean that Mocha will integrate with new versions of either library without the need to release a new version of Mocha each time, which was clearly bad and unsustainable. Many thanks to @tenderlove, @zenspider & @kou for their help, suggestions & patience. * Temporarily deprecated `require 'mocha'`. Use `require 'mocha/setup'` instead. The plan is that eventually `require 'mocha'` will *not* automatically integrate with either of the two test libraries as it does at the moment, and you'll need to explicitly & separately trigger the integration. I think this will provide a lot more flexibility and will hopefully do away with the need for the `require: false` option in the `Gemfile` which has always confused people. * Deprecated `require 'mocha_standalone'` and `require 'mocha/standalone'`. Use `require 'mocha/api` instead. * Although these are not part of Mocha's public API, I thought I should mention that the MiniTest and Test::Unit assertion counter classes have been combined into a single class `Mocha::Integration::AssertionCounter`. * Extracted Mocha::Hooks module from Mocha::API and added documentation for test library authors. * Improvements to documentation. Much of it has been combined into the README file. * Fix #101 - Mock#respond_to? doesn't work with a string argument - thanks to @urbanautomaton. * Fix #105 - Travis link in README - thanks to @cknadler. * Various improvements to automated testing of integration with test libraries. * Make deprecation warnings more prominent. ## 0.12.7 * Officially support minitest v4.1.0 (still monkey-patching). ## 0.12.6 * Fixes #103. ## 0.12.5 * Officially support minitest v3.5.0 (still monkey-patching). ## 0.12.4 * Officially support minitest v3.4.0 & test-unit v2.5.2 (still monkey-patching). ## 0.12.3 * Revert rename of undocumented internal module since it turns out Rails/ActiveSupport is relying on its existence. ## 0.12.2 * Officially support minitest v3.3.0 (still monkey-patching) ## 0.12.1 * Deprecation warning (instead of fail fast) if neither Test::Unit nor MiniTest is loaded. Fixes #88. * Remove deprecated access to `Mocha::Standalone`. * Remove the deprecated file `stubba.rb`. * Officially support test-unit v2.5.1 (still monkey-patching). * Improve the API acceptance test. ## 0.12.0 * Fail fast if neither Test::Unit nor MiniTest is loaded. Fixes #40. * Officially support MiniTest up to v3.2.0 (still monkey-patching). * Officially support test-unit v2.5.0 (still monkey-patching). * Do not monkey-patch Test::Unit or MiniTest unless we *know* it's ok. * Add acceptance tests to demonstrate using a block as a custom parameter matcher. * Update Travis CI build status image to use the new build under the freerange account. ## 0.11.4 * Homepage has moved to http://gofreerange.com/mocha/docs. ## 0.11.3 * Fix for #78 i.e. alias Object#method as Object#_method, not Object#__method__ which already exists as another Ruby method. ## 0.11.2 * Rails has a Request class which defines its own #method method. This broke the new mechanism for stubbing a method. This release includes a slightly modified version of fix #77 provided by @sikachu. See https://github.com/rails/rails/pull/5907 for further info. ## 0.11.1 * In Ruby 1.8.7 methods accepting a block parameter were incorrectly restored without the block parameter after being stubbed. Fix for #76. ## 0.11.0 * Store original method when stubbing rather than using alias_method. This fixes #41, #47, #74 and all tests now pass on both Ruby 1.8.7 and 1.9.3. * Attempting to stub a method on a frozen object should fail fast. See #68. * Prevent stubbing a method on nil by default. See #68. * Generate documentation using YARD instead of Rdoc - removes dependency on Coderay. * Publish documentation on Github pages instead of Rubyforge - uses rake task written by @tomafro. * Remove agiledox which has outlived it's usefulness. * Removed trailing whitespace throughout codebase. * Add documentation for Mock#unstub. * Improve documentation for ObjectMethods. * Provide a way to run multiple tests within a single acceptance test method. ## 0.10.5 * Fix for issue #66 (hopefully without regressing on issue #63) - Mocha::Mock has Mocha::Mockery as a dependency. Stop trying to pretend otherwise. Thanks to @kennyj for reporting. * Fix a bunch of warnings in Ruby 1.9. There are still the 6 test failures mentioned in issue #41 which I suspect are due to the introspection gem not being Ruby 1.9-compatible. * Add links to README for source code & issue tracker. * Fix for issue #67 - Make the travis-ci badge visible in the README. Thanks to Diego Plentz for pull request. * Fix for issue #70 - Rename Mock#expectations to Mock#__expectations__ to avoid conflicts. Thanks to Jeremy Stephens for pull request. ## 0.10.4 * Fix for issue #65 - expectations not being verified in subsequent tests. * Fix for issue #63 - require Mocha::Mockery at Mocha::Mock class load time and not on invocation of Mock#method_missing. * Fix for issue #45 - raise ArgumentError if Mocha::ParameterMatchers#has_entry is given Hash with wrong number of entries. * Make global variable name more obscure to avoid clashes with other libraries. * Move travis-ci-related gemfiles into their own directory. ## 0.10.3 * Fix for issue #57. Gem::Requirement#=~ was only added in rubygems v1.8.0, but Object#=~ means the result of various monkey-patching checks is always false/nil for earlier versions of rubygems. However, the method it aliases #satisfied_by? has existed since Gem::Dependency was extracted from Gem::Version in rubygems v0.9.4.4, so it's much safer to use that. Thanks to fguillen for reporting and helping with diagnosis. ## 0.10.2 * Merge pull request #53. Unstubbing a method should not remove expectations for other stubbed methods. Fixes #52. Thanks to saikat. ## 0.10.1 * Merge pull request #51. Use Gem::Requirement & Gem::Version for version comparison. Fixes issue #50. Thanks to meineerde. * Fixed typo in rdoc for Mocha::ObjectMethods. * Improve README as suggested in issue #46. Explain that Mocha must be loaded after test libraries and how to achieve this using Bundler. * Merge pull request #43 - nobody expects the spanish inquisition! Thanks to cairo140. * Fix for issue #39 - improve documentation for Expectation#multiple_yields. * Fix for issue #38 where a subtle change in test-unit v2.3.0 had been missed - only visible in verbose mode. * Support for MiniTest up to v2.6.2 has been verified. * Add explicit development dependency on coderay for generating syntax-highlighted code examples. ## 0.10.0 * Add Expectation#throws to allow a stubbed method to use Kernel#throw. * Updates for versions of Test::Unit up to and including v2.3.3 (including patch by Jens Fahnenbruck). * Updates for versions of MiniTest up to and including v2.5.1. * Since the singleton method added by Mocha masks the underlying instance method, there's no need to move it out the way and then back again. This fixes Github issue #20, because the original method is left unchanged - https://github.com/floehopper/mocha/issues/20 (thanks to Nick Lewis). * Handle stubbing of a singleton method, leaving the original method unchanged after the test. * When stubbing an instance method that was originally defined as a singleton method, the original method should still exist after the test. * Fixed mis-print in Mocha::ObjectMethods#unstub documentation (patch by Gleb Pomykalov). * Improved test coverage around stubbing of methods defined in different ways - this makes use of the newly extracted introspection gem (although this means some tests are now failing in Ruby v1.9.2). * Added configuration for Travis continuous integration. * Make the gemspec the canonical reference and stop generating it from the Rakefile. * Use the built-in Bundler rake tasks for packaging the gem. * Use the "release" rake task provided by Bundler instead of using the Rake::XForge::Release functionality. * Extract Object#__metaclass__ into a new metaclass gem. * Run rake tasks without `bundle exec`. * Avoid deprecation warning for rdoc rake task. * Remove the `use_test_unit_gem` MOCHA_OPTION which hasn't worked since we switched to bundler - we can now run the tests specifying a different Gemfile instead. * Use multiple Gemfiles seems to run Travis CI builds against multiple version of test-unit & minitest. ## 0.9.12 * Make Mocha's tests pass under Ruby 1.9.2 i.e. using MiniTest. One of the main issues was that we were not parsing stacktraces on MiniTest errors comprehensively enough. * Avoid 'circular require considered harmful' warning when running Mocha's tests in Ruby 1.9.2 * Make performance tests work on Ruby 1.9.2 i.e. using MiniTest. * Declare rake as a *development* dependency with newer versions of Rubygems since it's only needed to carry out developer-related tasks. ## 0.9.11 * Added explicit support for minitest v1.5.0 to v2.0.2. * Make testable by rubygems-test. * Update links to my blog and make other links consistent. * Added a URI parameter matcher that ignores the order of query parameters so that tests can be independent of undefined hash ordering (patch by Paul Battley). * Include unexpected invocation in failure message and change the language slightly to make the failure message less confusing. See http://floehopper.lighthouseapp.com/projects/22289/tickets/52. * No need to create regular expression every time the BacktraceFilter#filtered method is called. See http://floehopper.lighthouseapp.com/projects/22289-mocha/tickets/66. ## 0.9.10 * Added Mocha::ObjectMethods#unstub method - https://github.com/floehopper/mocha/issues#issue/6 * Inherit Mocha::ExpectationError from Exception instead of StandardError to reduce the chances of a test passing by accident - thanks to James Sanders (jsanders) - https://github.com/floehopper/mocha/issues#issue/15 * Fixed bug - GitHub README page to link correctly to code examples - https://github.com/floehopper/mocha/issues/closed#issue/11 * Fixed bug - PASSTHROUGH_EXCEPTIONS are defined on MiniTest::Unit::TestCase not in Mocha - thanks to Brian Troutwine (blt) - https://github.com/floehopper/mocha/issues/closed#issue/14 ## 0.9.9 * Avoid loading bits of the test-unit gem by accident. This is an attempt at a fix for the problem that James Adam reported [1]. By using 'load' instead of 'require' to detect the version of Test::Unit, we can avoid rubygems trying to load bits of the test-unit gem when it's not wanted. [1] http://floehopper.lighthouseapp.com/projects/22289-mocha/tickets/50#ticket-50-13 * Fix exception when running rake without test-unit gem. When test-unit gem >=v2.0.0 was installed but the "use_test_unit_gem" MOCHA_OPTIONS was not specified, a "comparison of Fixnum with Hash failed" exception was being raised when running the performance tests. This was because bits of the test-unit gem were being loaded accidentally and a Hash was being incorrectly supplied to the TestRunner.run method. * Explicitly require rubygems for running tests via rake using test-unit gem. * Handle newer versions of test-unit gem (v2.0.2 to v2.0.9) * Handle newer versions of minitest gem (v1.4.0 to v1.6.0) * Added warnings about monkey-patching test-unit and minitest to aid debugging. These are enabled by including "debug" in the MOCHA_OPTIONS environment variable. This is now a comma-separated list, so that we can specify multiple options e.g. MOCHA_OPTIONS=debug,use_test_unit_gem * Eloy Duran (alloy) made the unit tests run on 1.9.2dev r25249. * Eloy Duran (alloy) also improved some MiniTest TestResult code I'd written and got the acceptance tests running on Ruby 1.9 HEAD. There are still 4 failures because for some reason the backtrace line numbers are off by one. And the minitest_test test case does not run when the whole suite is run with MiniTest. These issues still need investigation. * Fixed some acceptance tests to run in Ruby 1.9.2 - it's no longer possible to subvert the protection of a method by calling it via Object#send. * Fixed "test:performance" rake task so it runs in Ruby 1.9.2. * Fix test incorrectly failing under Rubinius 1.0. This test imposed too many constraints. It appears that Object#inspect legitimately calls Object#object_id in Rubinius. But we're only interested in what 'id' methods Mocha::ObjectMethods#mocha_inspect calls. By stubbing Object#inspect we can relax the constraints imposed by the test. * Luke Redpath (lukeredpath) added new shorthand "any" and "all" composite parameter matchers using "&" and "|". This provides an alternative syntax for expecting any or all matchers to pass, e.g. foo.expects(:bar).with(equals(1) | equals(2)). * Improved documentation for Expectation#raises. A number of people have suggested an extension to the API to cope with custom exceptions that have extra constructor parameters. However, since the arguments supplied to Expectation#raises are just passed on to Kernel#raise, it's possible to pass in an instance of an exception. Thus no change to the API is required, but it does seem worthwhile pointing this out in the docs. * Corrected RDoc example for Expectation#never thanks to Red David (reddavis). * Improved RDoc including a change suggested by Rohit Arondekar (rohit). * Updated gemspec as requested by Sam Woodard (shwoodard). ## 0.9.8 * Fixed bug "NameError raised when using Mocha as a Rails plug-in" - http://floehopper.lighthouseapp.com/projects/22289/tickets/53. Since 0.9.6 the Rails plugin has been broken. See bug report for details. You will need to explicitly load Mocha *after* the test framework has been loaded, e.g. by adding "require 'mocha'" at the bottom of test/test_helper.rb. * Make Mocha::ParameterMatchers#regexp_matches, #includes, #has_value, #has_key more robust. Thanks to Sander Hartlage. * Allow passing a block to Mocha::Configuration methods to only change configuration for the duration of the block. Thanks to Dan Manges. * Fixed bug "doc generation fails in 0.9.7 gem" - http://floehopper.lighthouseapp.com/projects/22289/tickets/51. * Remove rdoc template incorporating google analytics from source control. The file just needs to exist locally and be ignored by source control. This should stop the warning showing up on e.g. RunCodeRun build results. ## 0.9.7 * Although I had provided a deprecation warning for people using Mocha::Standalone, I had assumed people wouldn't be explicitly loading the mocha/standalone.rb file. It turns out this assumption was incorrect at least in the case of Rspec. This is now fixed. ## 0.9.6 * Version 2.0.1 of the test-unit gem introduced a private 'run_test' method on TestCase which clashed with the public TestRunner#run_test method. So this latter method has been renamed to 'run_as_test'. * Stop requiring rubygems - this should be an environmental choice for the user. http://gist.github.com/54177 - describes why requiring rubygems in your library code is a bad idea. * It seems like overkill to vendorize coderay and meta_project when they're only needed to generate the examples for documentation and for publishing files on RubyForge. So I'm removing them and installing them locally as gems when I need them. * Added support for 'test-unit' gem (version >= 2.0). Note that as with other versions of Test::Unit I'm completely replacing the TestCase#run method. Unfortunately in version 2.0.0 this method differs slightly from the same method in version 2.0.1 & 2.0.2, so we have to provide different implementations to ensure that the internal working of Test::Unit are not compromised by Mocha. Note also that unless the 'test-unit' gem is loaded, requiring 'test/unit' leads to a mixture of stdlib and gem classes being loaded causing errors. To avoid a dependency on rubygems, the gem is loaded only if MOCHA_OPTIONS is set to 'use_test_unit_gem' - this option is only intended for use in running Mocha's own tests. It might be worthwhile to create a shim gem like minitest_tu_shim to allow the test-unit gem to completely replace the stdlib, but that's a job for another day. The changes in the Rakefile are to make the default task run with the 'test-unit' gem (version >= 2.0). * Renamed Mocha::Standalone to Mocha::API to better reflect its purpose. Added a deprecation warning for those who are referencing Mocha::Standalone. * Fix exception raised by HasEntry#matches? if first param is not a Hash (thanks to Taylor Barstow). * Ken Collins reported [1] that Mocha is always loading MiniTest if it is available and loading it causes some Rails/ActionPack tests to break. I've removed the loading of MiniTest, but this now means the user has to ensure that if they want to use MiniTest in conjunction with Mocha, he must load MiniTest before loading Mocha. [1] http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/2060 * Implemented Bacon integration (thanks to Ubiratan Pires Alberton), but this was then removed after deciding only to maintain integration with Test::Unit and MiniTest which are both Ruby standard libraries. See mailing list for details. * Don't monkey-patch MiniTest if it's already been monkey-patched by Mocha. * Fixed bug: MiniTest integration was counting ExpectationErrors as errors not failures. http://floehopper.lighthouseapp.com/projects/22289-mocha/tickets/41. * Fixed bug: Some Bacon tests were failing in Ruby 1.9.1. http://floehopper.lighthouseapp.com/projects/22289-mocha/tickets/43. * Chad Humphries pointed out that in Ruby 1.9.1, if you are not using Test::Unit or MiniTest, Mocha will attempt to load and monkey-patch Test::Unit. Mocha will now only monkey-patch Test::Unit and/or MiniTest if they have already been loaded. MiniTest tests will now run in both Ruby 1.8.6 (with MiniTest gem) and in Ruby 1.9.1 (with MiniTest std lib). See Ligthouse ticket - http://floehopper.lighthouseapp.com/projects/22289/tickets/49. * Made Mocha compatible with minitest 1.4.0 and above (thanks to Denis Defreyne). ## 0.9.5 * Fixed Lighthouse bug #32 - stub_everything should mean mock responds to anything. * Added Expectation#twice to improve readability. Thanks to pull request from Celestino Gomes. * In Ruby 1.9.1, requiring 'test/unit' loads a thin wrapper around MiniTest and Test::Unit::TestCase ends up inheriting from MiniTest::Unit::TestCase. So we need to avoid including the Mocha modules more than once to avoid nasty consequences. Thanks to Matthias Hennemeyer for help with this. * Ruby 1.9 includes rake, but not rake/contrib. For the moment I've moved the sshpublisher require into the only rake task that needs it, so that I can at least run the tests in Ruby 1.9. It looks like I will need to build a rake/contrib gem or similar to get this working properly - http://intertwingly.net/blog/2008/01/07/Rake-Contrib-for-1-9 ## 0.9.4 * Added mocha.gemspec file generated with Chad Woolley's new rake task, so that a floehopper-mocha gem will get built on GitHub. * Add rake task to update mocha.gemspec with unique version, which will cause gem to be auto-built on github * As Tobias Crawley correctly pointed out in feature request #23055 "stubs(with_hash) not working with existing object" [1], following the principle of least surprise, it should be possible to call ObjectMethods#expects & ObjectMethods#stubs with a Hash of method_names vs return_values like you can with Mock#expects & Mock#stubs. I've also updated & improved the docs to reflect the changes. [1] http://rubyforge.org/tracker/index.php?func=detail&aid=23055&group_id=1917&atid=7480 * Removed deprecated gem autorequire. ## 0.9.3 * Added support for MiniTest thanks to Jeff Smick. * Fixed a possible bug with some of the non-default Configuration options relating to the argument to Object#respond_to? * As per Jay Fields recommendations [1] and with further impetus from a talk at Ruby Manor, any methods added to core classes are now added by including a module. This means that Mocha is a better citizen of the Ruby world and it's behaviour is more easily extended. [1] http://blog.jayfields.com/2008/07/ruby-underuse-of-modules.html & http://blog.jayfields.com/2008/07/ruby-redefine-method-behavior.html * Removed deprecated gem autorequire. ## 0.9.2 * Improved documentation to address [#22530] 'Mock methods with multiple return values not possible?' * respond_with parameter matcher was not available in tests. * Patch [#22630] Fix for a bug in running Rails tests with Ruby 1.8.7. Array#flatten was being called which in turn was checking whether each element responded to #to_ary. This check was using the two parameter version of #respond_to?, but Mock was only defining a one parameter version. ## 0.9.1 * Fixed bug #21465 - expects & stubs should support method names as strings (as well as symbols) or fail fast. Convert all expectation method names to a symbol in case they were supplied as a string. * By removing Mock#unexpected_method_called we reduce the number of methods vulnerable to the problem that surfaced in bug #21563. * Fix bug #21563 - stubbing 'verified?' method is unsafe. Instance method names on the Mock class should be more obscure. * Performance improvement. StubbaExampleTest goes twice as fast on my local machine. * Added primitive performance test to default rake task. * Fix format of case statements which don't work in Ruby 1.9 and make others consistent. * There is no point in running (potentially expensive) checks if configuration is set to allow such checks to fail. This is a relatively quick fix in response to Chris McGrath's performance problems. * Fix for bug #21161 - 'uninitialized constant Deprecation in stubba.rb'. * It's more readable to talk about 'once' and 'twice' rather than '1 time' and '2 times'. * Fix bug #20883 - never should raise when called to prevent follow up errors. Fail fast when there are no matching invokable expectations and handle the stub_everything case sensibly. This might not be entirely backwards compatible, but I think the benefits outweigh the risks. The most likely change is that a test that was already failing will now fail faster, which doesn't seem so awful. ## 0.9.0 * Configurable warnings or errors * when a method on a non-public method is stubbed * when a method on a non-existent method is stubbed * when a method on a non-mock object is stubbed * when a method is stubbed unnecessarily (i.e. the stubbed method is not called during the test) * Improved error messages * User-friendly list of unsatisfied expectations, satisfied expectations and state machines. * Improved readability of cardinality description. * Display sensible failure message for any_instance expectations e.g. "#.bar - expected calls: 1, actual calls: 0" * Parameter matchers * New to this release * optionally (allows matching of optional parameters if available) * yaml_equivalent (allows matching of YAML that represents the specified object) * responds_with (tests the quack not the duck) * Nesting of parameter matchers is now supported. * Optional block passed into mock initializer is evaluated in the context of the new mock instance and can be used as a shortcut to set up expectations. * Added JMock-style sequences for constraining the order of expected invocations. See Standalone#sequence and Expectation#in_sequence. * Added JMock-style states for constraining the order of expected invocations. See Standalone#states, Expectation#then, Expectation#when and StateMachine. * Compatibility with versions of Ruby * Compatibility with Ruby v1.9. All test errors and warnings fixed. * Nasty fix so that TestCaseAdaptor works consistently with earlier versions of Test::Unit as well as more recent versions. * Added platform to gem specification to avoid bug in rubygems 0.9.5 - see http://www.dcmanges.com/blog/rubygems-0-9-5-platform-bug and http://rubygems.org/read/chapter/20#platform. * Make ExpectationRaiser deal with subclasses of Interrupt which seem to need a message supplied in the raise statement in Ruby 1.8.6 (but not 1.8.4 or 1.9). Not sure this is really Mocha's responsibility. * Added deprecation warning in stubba.rb which is no longer needed and will be removed. * Supply positioning information to evals to improve any error messages. See http://ola-bini.blogspot.com/2008/01/ruby-antipattern-using-eval-without.html * Bug fixes * 18914 in revision 296 - http://rubyforge.org/tracker/index.php?func=detail&aid=18914&group_id=1917&atid=7477 * 18917 in revision 295 - http://rubyforge.org/tracker/index.php?func=detail&aid=18917&group_id=1917&atid=7477 * 18336 in revision 287 - http://rubyforge.org/tracker/index.php?func=detail&aid=18336&group_id=1917&atid=7477 * 17835 in revision 255 - http://rubyforge.org/tracker/index.php?func=detail&aid=17835&group_id=1917&atid=7477 * 17412 in revision 242 - http://rubyforge.org/tracker/index.php?func=detail&aid=17412&group_id=1917&atid=7477 * 15977 in revision 198 - http://rubyforge.org/tracker/index.php?func=detail&aid=15977&group_id=1917&atid=7477 * 11885 in revision 156 - http://rubyforge.org/tracker/index.php?func=detail&aid=11885&group_id=1917&atid=7477 ## 0.5.5 - Renamed Matches parameter matcher to RegexpMatches for clarity. - Added noframes tag to rdoc index to assist Google. ## 0.5.4 - Added matches parameter matcher for matching regular expressions. ## 0.5.3 - Attempt to fix packaging problems by switching to newer version (1.15.1) of gnutar and setting COPY_EXTENDED_ATTRIBUTES_DISABLE environment variable. - Removed unused ExpectationSequenceError exception. - Added instance_of and kind_of parameter matchers. - Added Google Webmaster meta tag to rdoc template header. - Put Google Webmaster meta tag in the right header i.e. the one for the index page. ## 0.5.2 - Fix bug 11885 - "never doesn't work with stub_everything" submitted by Alexander Lang. In fixing this bug, also fixed undiscoverd bug where expected & actual invocation counts were being incorrectly reported which seems to have been introduced when fixes were added for invocation dispatch (see MockedMethodDispatchAcceptanceTest). - Previously when an expectation did not allow more invocations, it was treated as not matching. Now we prefer matching expectations which allow more invocations, but still match expectations which cannot allow more invocations. I think this may be overcomplicating things, but let's see how it goes. ## 0.5.1 - Fixed bug #11583 "Mocha 0.5.0 throwing unexpected warnings". Also switched on ruby warning for all rake test tasks. Fixed majority of warnings, but some left to fix. ## 0.5.0 - Parameter Matchers - I’ve added a few Hamcrest-style parameter matchers which are designed to be used inside Expectation#with. The following matchers are currently available: anything(), includes(), has_key(), has_value(), has_entry(), all_of() & any_of(). More to follow soon. The idea is eventually to get rid of the nasty parameter_block option on Expectation#with. object = mock() object.expects(:method).with(has_key('key_1')) object.method('key_1' => 1, 'key_2' => 2) # no verification error raised object = mock() object.expects(:method).with(has_key('key_1')) object.method('key_2' => 2) # verification error raised, because method was not called with Hash containing key: 'key_1' - Values Returned and Exceptions Raised on Consecutive Invocations - Allow multiple calls to Expectation#returns and Expectation#raises to build up a sequence of responses to invocations on the mock. Added syntactic sugar method Expectation#then to allow more readable expectations. object = mock() object.stubs(:method).returns(1, 2).then.raises(Exception).then.returns(4) object.method # => 1 object.method # => 2 object.method # => raises exception of class Exception object.method # => 4 - Yields on Consecutive Invocations - Allow multiple calls to yields on single expectation to allow yield parameters to be specified for consecutive invocations. object = mock() object.stubs(:method).yields(1, 2).then.yields(3) object.method { |*values| p values } # => [1, 2] object.method { |*values| p values } # => [3] - Multiple Yields on Single Invocation - Added Expectation#multiple_yields to allow a mocked or stubbed method to yield multiple times for a single invocation. object = mock() object.stubs(:method).multiple_yields([1, 2], [3]) object.method { |*values| p values } # => [1, 2] # => [3] - Invocation Dispatch - Expectations were already being matched in reverse order i.e. the most recently defined one was being found first. This is still the case, but we now stop matching an expectation when its maximum number of expected invocations is reached. c.f. JMock v1. A stub will never stop matching by default. Hopefully this means we can soon get rid of the need to pass a Proc to Expectation#returns. object = mock() object.stubs(:method).returns(2) object.expects(:method).once.returns(1) object.method # => 1 object.method # => 2 object.method # => 2 # no verification error raised # The following should still work... Time.stubs(:now).returns(Time.parse('Mon Jan 01 00:00:00 UTC 2007')) Time.now # => Mon Jan 01 00:00:00 UTC 2007 Time.stubs(:now).returns(Time.parse('Thu Feb 01 00:00:00 UTC 2007')) Time.now # => Thu Feb 01 00:00:00 UTC 2007 - Deprecate passing an instance of Proc to Expectation#returns. - Explicitly include all Rakefile dependencies in project. - Fixed old Stubba example. - Fix so that it is possible for a stubbed method to raise an Interrupt exception without a message in Ruby 1.8.6 - Added responds_like and quacks_like. - Capture standard object methods before Mocha adds any. - Added Expectation#once method to make interface less surprising. - Use Rake::TestTask to run tests. Created three separate tasks to run unit, integration & acceptance tests. Split inspect_test into one file per TestCase. Deleted superfluous all_tests file. - Fiddled with mocha_inspect and tests to give more sensible results on x86 platform. - Fixed bug #7834 "infinite_range.rb makes incorrect assumption about to_f" logged by James Moore. ## 0.4.0 - Allow naming of mocks (patch from Chris Roos). - Specify multiple return values for consecutive calls. - Improved consistency of expectation error messages. - Allow mocking of Object instance methods e.g. kind_of?, type. - Provide aliased versions of #expects and #stubs to allow mocking of these methods. - Added at_least, at_most, at_most_once methods to expectation. - Allow expects and stubs to take a hash of method and return values. - Eliminate warning: "instance variable @yield not initialized" (patch from Xavier Shay). - Restore instance methods on partial mocks (patch from Chris Roos). - Allow stubbing of a method with non-word characters in its name (patch from Paul Battley). - Removed coupling to Test::Unit. - Allow specified exception instance to be raised (patch from Chris Roos). - Make mock object_id appear in hex like normal Ruby inspect (patch from Paul Battley). - Fix path to object.rb in rdoc rake task (patch from Tomas Pospisek). - Reverse order in which expectations are matched, so that last expectation is matched first. This allows e.g. a call to #stubs to be effectively overridden by a call to #expects (patch from Tobias Lutke). - Stubba & SmartTestCase modules incorporated into Mocha module so only need to require 'mocha' - no longer need to require 'stubba'. - AutoMocha removed. ## 0.3.3 - Quick bug fix to restore instance methods on partial mocks (for Kevin Clark). ## 0.3.2 - Examples added. ## 0.3.1 - Dual licensing with MIT license added. ## 0.3.0 * Rails plugin. * Auto-verify for expectations on concrete classes. * Include each expectation verification in the test result assertion count. * Filter out noise from assertion backtraces. * Point assertion backtrace to line where failing expectation was created. * New yields method for expectations. * Create stubs which stub all method calls. * Mocks now respond_to? expected methods. ## 0.2.1 * Rename MochaAcceptanceTest::Rover#move method to avoid conflict with Rake (in Ruby 1.8.4 only?) ## 0.2.0 * Small change to SetupAndTeardown#teardown_stubs suggested by Luke Redpath (http://www.lukeredpath.co.uk) to allow use of Stubba with RSpec (http://rspec.rubyforge.org). * Reorganized directory structure and extracted addition of setup and teardown methods into SmartTestCase mini-library. * Addition of auto-verify for Mocha (but not Stubba). This means there is more significance in the choice of expects or stubs in that any expects on a mock will automatically get verified. So instead of... wotsit = Mocha.new wotsit.expects(:thingummy).with(5).returns(10) doobrey = Doobrey.new(wotsit) doobrey.hoojamaflip wotsit.verify you need to do... wotsit = mock() wotsit.expects(:thingummy).with(5).returns(10) doobrey = Doobrey.new(wotsit) doobrey.hoojamaflip # no need to verify There are also shortcuts as follows... instead of... wotsit = Mocha.new wotsit.expects(:thingummy).returns(10) wotsit.expects(:summat).returns(25) you can have... wotsit = mock(:thingummy => 5, :summat => 25) and instead of... wotsit = Mocha.new wotsit.stubs(:thingummy).returns(10) wotsit.stubs(:summat).returns(25) you can have... wotsit = stub(:thingummy => 5, :summat => 25) ## 0.1.2 * Minor tweaks ## 0.1.1 * Initial release. mocha-1.3.0/yard-templates/0000755000004100000410000000000013155337745015602 5ustar www-datawww-datamocha-1.3.0/yard-templates/default/0000755000004100000410000000000013155337745017226 5ustar www-datawww-datamocha-1.3.0/yard-templates/default/layout/0000755000004100000410000000000013155337745020543 5ustar www-datawww-datamocha-1.3.0/yard-templates/default/layout/html/0000755000004100000410000000000013155337745021507 5ustar www-datawww-datamocha-1.3.0/yard-templates/default/layout/html/setup.rb0000644000004100000410000000016313155337745023174 0ustar www-datawww-datadef init super if ENV['GOOGLE_ANALYTICS_WEB_PROPERTY_ID'] sections[:layout] << :google_analytics end end mocha-1.3.0/yard-templates/default/layout/html/google_analytics.erb0000644000004100000410000000102713155337745025524 0ustar www-datawww-data mocha-1.3.0/lib/0000755000004100000410000000000013155337744013414 5ustar www-datawww-datamocha-1.3.0/lib/mocha.rb0000644000004100000410000000003013155337744015021 0ustar www-datawww-datarequire 'mocha/version' mocha-1.3.0/lib/mocha_standalone.rb0000644000004100000410000000025213155337744017237 0ustar www-datawww-datarequire 'mocha/api' require 'mocha/deprecation' Mocha::Deprecation.warning("`require 'mocha_standalone'` has been deprecated. Please use `require 'mocha/api' instead.") mocha-1.3.0/lib/mocha/0000755000004100000410000000000013155337744014503 5ustar www-datawww-datamocha-1.3.0/lib/mocha/standalone.rb0000644000004100000410000000025213155337744017157 0ustar www-datawww-datarequire 'mocha/api' require 'mocha/deprecation' Mocha::Deprecation.warning("`require 'mocha/standalone'` has been deprecated. Please use `require 'mocha/api' instead.") mocha-1.3.0/lib/mocha/any_instance_method.rb0000644000004100000410000000367613155337744021057 0ustar www-datawww-datarequire 'mocha/ruby_version' require 'mocha/class_method' module Mocha class AnyInstanceMethod < ClassMethod def mock stubbee.any_instance.mocha end def reset_mocha stubbee.any_instance.reset_mocha end def hide_original_method if @original_visibility = method_visibility(method) begin if RUBY_V2_PLUS @definition_target = PrependedModule.new stubbee.__send__ :prepend, @definition_target else @original_method = stubbee.instance_method(method) if @original_method && @original_method.owner == stubbee stubbee.send(:remove_method, method) end end rescue NameError # deal with nasties like ActiveRecord::Associations::AssociationProxy end end end def define_new_method definition_target.class_eval(<<-CODE, __FILE__, __LINE__ + 1) def #{method}(*args, &block) self.class.any_instance.mocha.method_missing(:#{method}, *args, &block) end CODE if @original_visibility Module.instance_method(@original_visibility).bind(definition_target).call(method) end end def remove_new_method definition_target.send(:remove_method, method) end def restore_original_method unless RUBY_V2_PLUS if @original_method && @original_method.owner == stubbee stubbee.send(:define_method, method, @original_method) Module.instance_method(@original_visibility).bind(stubbee).call(method) end end end def method_visibility(method) (stubbee.public_instance_methods(true).include?(method) && :public) || (stubbee.protected_instance_methods(true).include?(method) && :protected) || (stubbee.private_instance_methods(true).include?(method) && :private) end private def definition_target @definition_target ||= stubbee end end end mocha-1.3.0/lib/mocha/single_return_value.rb0000644000004100000410000000025113155337744021102 0ustar www-datawww-datarequire 'mocha/is_a' module Mocha class SingleReturnValue def initialize(value) @value = value end def evaluate @value end end end mocha-1.3.0/lib/mocha/parameter_matchers.rb0000644000004100000410000000207213155337744020677 0ustar www-datawww-datamodule Mocha # Used as parameters for {Expectation#with} to restrict the parameter values which will match the expectation. Can be nested. module ParameterMatchers; end end require 'mocha/parameter_matchers/object' require 'mocha/parameter_matchers/all_of' require 'mocha/parameter_matchers/any_of' require 'mocha/parameter_matchers/any_parameters' require 'mocha/parameter_matchers/anything' require 'mocha/parameter_matchers/equals' require 'mocha/parameter_matchers/has_entry' require 'mocha/parameter_matchers/has_entries' require 'mocha/parameter_matchers/has_key' require 'mocha/parameter_matchers/has_value' require 'mocha/parameter_matchers/includes' require 'mocha/parameter_matchers/instance_of' require 'mocha/parameter_matchers/is_a' require 'mocha/parameter_matchers/kind_of' require 'mocha/parameter_matchers/not' require 'mocha/parameter_matchers/optionally' require 'mocha/parameter_matchers/regexp_matches' require 'mocha/parameter_matchers/responds_with' require 'mocha/parameter_matchers/yaml_equivalent' require 'mocha/parameter_matchers/equivalent_uri' mocha-1.3.0/lib/mocha/is_a.rb0000644000004100000410000000012313155337744015737 0ustar www-datawww-dataclass Object # :stopdoc: alias_method :__is_a__, :is_a? # :startdoc: end mocha-1.3.0/lib/mocha/unexpected_invocation.rb0000644000004100000410000000126113155337744021425 0ustar www-datawww-datamodule Mocha # Exception raised when an unexpected method is invoked class UnexpectedInvocation # @private def initialize(mock, symbol, *arguments) @mock, @symbol, @arguments = mock, symbol, arguments end # @private def full_description method_matcher = MethodMatcher.new(@symbol) parameters_matcher = ParametersMatcher.new(@arguments) method_signature = "#{@mock.mocha_inspect}.#{method_matcher.mocha_inspect}#{parameters_matcher.mocha_inspect}" "unexpected invocation: #{method_signature}\n" end # @private def short_description "unexpected invocation: #{@symbol}(#{@arguments.join(', ')})" end end end mocha-1.3.0/lib/mocha/configuration.rb0000644000004100000410000000545213155337744017705 0ustar www-datawww-datamodule Mocha # Configuration settings. class Configuration DEFAULTS = { :stubbing_method_unnecessarily => :allow, :stubbing_method_on_non_mock_object => :allow, :stubbing_non_existent_method => :allow, :stubbing_non_public_method => :allow, :stubbing_method_on_nil => :prevent, } class << self # Allow the specified +action+. # # @param [Symbol] action one of +:stubbing_method_unnecessarily+, +:stubbing_method_on_non_mock_object+, +:stubbing_non_existent_method+, +:stubbing_non_public_method+, +:stubbing_method_on_nil+. # @yield optional block during which the configuration change will be changed before being returned to its original value at the end of the block. def allow(action, &block) change_config action, :allow, &block end # @private def allow?(action) configuration[action] == :allow end # Warn if the specified +action+ is attempted. # # @param [Symbol] action one of +:stubbing_method_unnecessarily+, +:stubbing_method_on_non_mock_object+, +:stubbing_non_existent_method+, +:stubbing_non_public_method+, +:stubbing_method_on_nil+. # @yield optional block during which the configuration change will be changed before being returned to its original value at the end of the block. def warn_when(action, &block) change_config action, :warn, &block end # @private def warn_when?(action) configuration[action] == :warn end # Raise a {StubbingError} if if the specified +action+ is attempted. # # @param [Symbol] action one of +:stubbing_method_unnecessarily+, +:stubbing_method_on_non_mock_object+, +:stubbing_non_existent_method+, +:stubbing_non_public_method+, +:stubbing_method_on_nil+. # @yield optional block during which the configuration change will be changed before being returned to its original value at the end of the block. def prevent(action, &block) change_config action, :prevent, &block end # @private def prevent?(action) configuration[action] == :prevent end # @private def reset_configuration @configuration = nil end private # @private def configuration @configuration ||= DEFAULTS.dup end # @private def change_config(action, new_value, &block) if block_given? temporarily_change_config action, new_value, &block else configuration[action] = new_value end end # @private def temporarily_change_config(action, new_value, &block) original_value = configuration[action] configuration[action] = new_value yield ensure configuration[action] = original_value end end end end mocha-1.3.0/lib/mocha/class_methods.rb0000644000004100000410000000360113155337744017660 0ustar www-datawww-datarequire 'mocha/mockery' require 'mocha/class_method' require 'mocha/any_instance_method' module Mocha # Methods added to all classes to allow mocking and stubbing on real (i.e. non-mock) objects. module ClassMethods # @private def stubba_method Mocha::ClassMethod end # @private class AnyInstance def initialize(klass) @stubba_object = klass end def mocha @mocha ||= Mocha::Mockery.instance.mock_impersonating_any_instance_of(@stubba_object) end def stubba_method Mocha::AnyInstanceMethod end def stubba_object @stubba_object end def method_exists?(method, include_public_methods = true) if include_public_methods return true if @stubba_object.public_instance_methods(include_superclass_methods = true).include?(method) return true if @stubba_object.allocate.respond_to?(method.to_sym) end return true if @stubba_object.protected_instance_methods(include_superclass_methods = true).include?(method) return true if @stubba_object.private_instance_methods(include_superclass_methods = true).include?(method) return false end end # @return [Mock] a mock object which will detect calls to any instance of this class. # @raise [StubbingError] if attempting to stub method which is not allowed. # # @example Return false to invocation of +Product#save+ for any instance of +Product+. # Product.any_instance.stubs(:save).returns(false) # product_1 = Product.new # assert_equal false, product_1.save # product_2 = Product.new # assert_equal false, product_2.save def any_instance if frozen? raise StubbingError.new("can't stub method on frozen object: #{mocha_inspect}.any_instance", caller) end @any_instance ||= AnyInstance.new(self) end end end mocha-1.3.0/lib/mocha/expectation_error_factory.rb0000644000004100000410000000270313155337744022315 0ustar www-datawww-datarequire 'mocha/backtrace_filter' require 'mocha/expectation_error' module Mocha # This factory determines what class of exception should be raised when Mocha detects a test failure. # # This class should only be used by authors of test libraries and not by typical "users" of Mocha. # # For example, it is used by +Mocha::Integration::MiniTest::Adapter+ in order to have Mocha raise a +MiniTest::Assertion+ which can then be sensibly handled by +MiniTest::Unit::TestCase+. # # @see Mocha::Integration::MiniTest::Adapter class ExpectationErrorFactory class << self # @!attribute exception_class # Determines what class of exception should be raised when Mocha detects a test failure. # # This attribute may be set by authors of test libraries in order to have Mocha raise exceptions of a specific class when there is an unexpected invocation or an unsatisfied expectation. # # By default a +Mocha::ExpectationError+ will be raised. # # @return [Exception] class of exception to be raised when an expectation error occurs # @see Mocha::ExpectationError attr_accessor :exception_class # @private def build(message = nil, backtrace = []) exception = exception_class.new(message) filter = BacktraceFilter.new exception.set_backtrace(filter.filtered(backtrace)) exception end end self.exception_class = ExpectationError end end mocha-1.3.0/lib/mocha/deprecation.rb0000644000004100000410000000067113155337744017331 0ustar www-datawww-datarequire 'mocha/debug' module Mocha class Deprecation class << self attr_accessor :mode, :messages def warning(message) @messages << message $stderr.puts "\n*** Mocha deprecation warning: #{message}\n\n" unless mode == :disabled $stderr.puts caller.join("\n ") if mode == :debug end end self.mode = Debug::OPTIONS['debug'] ? :debug : :enabled self.messages = [] end end mocha-1.3.0/lib/mocha/expectation.rb0000644000004100000410000006063713155337744017367 0ustar www-datawww-datarequire 'mocha/method_matcher' require 'mocha/parameters_matcher' require 'mocha/expectation_error' require 'mocha/return_values' require 'mocha/exception_raiser' require 'mocha/thrower' require 'mocha/yield_parameters' require 'mocha/is_a' require 'mocha/in_state_ordering_constraint' require 'mocha/change_state_side_effect' require 'mocha/cardinality' module Mocha # Methods on expectations returned from {Mock#expects}, {Mock#stubs}, {ObjectMethods#expects} and {ObjectMethods#stubs}. class Expectation # Modifies expectation so that the number of calls to the expected method must be within a specific +range+. # # @param [Range,Integer] range specifies the allowable range in the number of expected invocations. # @return [Expectation] the same expectation, thereby allowing invocations of other {Expectation} methods to be chained. # # @example Specifying a specific number of expected invocations. # object = mock() # object.expects(:expected_method).times(3) # 3.times { object.expected_method } # # => verify succeeds # # object = mock() # object.expects(:expected_method).times(3) # 2.times { object.expected_method } # # => verify fails # # @example Specifying a range in the number of expected invocations. # object = mock() # object.expects(:expected_method).times(2..4) # 3.times { object.expected_method } # # => verify succeeds # # object = mock() # object.expects(:expected_method).times(2..4) # object.expected_method # # => verify fails def times(range) @cardinality = Cardinality.times(range) self end # Modifies expectation so that the expected method must be called exactly twice. # # @return [Expectation] the same expectation, thereby allowing invocations of other {Expectation} methods to be chained. # # @example Expected method must be invoked exactly twice. # object = mock() # object.expects(:expected_method).twice # object.expected_method # object.expected_method # # => verify succeeds # # object = mock() # object.expects(:expected_method).twice # object.expected_method # object.expected_method # object.expected_method # => unexpected invocation # # object = mock() # object.expects(:expected_method).twice # object.expected_method # # => verify fails def twice @cardinality = Cardinality.exactly(2) self end # Modifies expectation so that the expected method must be called exactly once. # # Note that this is the default behaviour for an expectation, but you may wish to use it for clarity/emphasis. # # @return [Expectation] the same expectation, thereby allowing invocations of other {Expectation} methods to be chained. # # @example Expected method must be invoked exactly once. # object = mock() # object.expects(:expected_method).once # object.expected_method # # => verify succeeds # # object = mock() # object.expects(:expected_method).once # object.expected_method # object.expected_method # => unexpected invocation # # object = mock() # object.expects(:expected_method).once # # => verify fails def once @cardinality = Cardinality.exactly(1) self end # Modifies expectation so that the expected method must never be called. # # @return [Expectation] the same expectation, thereby allowing invocations of other {Expectation} methods to be chained. # # @example Expected method must never be called. # object = mock() # object.expects(:expected_method).never # object.expected_method # => unexpected invocation # # object = mock() # object.expects(:expected_method).never # # => verify succeeds def never @cardinality = Cardinality.exactly(0) self end # Modifies expectation so that the expected method must be called at least a +minimum_number_of_times+. # # @param [Integer] minimum_number_of_times minimum number of expected invocations. # @return [Expectation] the same expectation, thereby allowing invocations of other {Expectation} methods to be chained. # # @example Expected method must be called at least twice. # object = mock() # object.expects(:expected_method).at_least(2) # 3.times { object.expected_method } # # => verify succeeds # # object = mock() # object.expects(:expected_method).at_least(2) # object.expected_method # # => verify fails def at_least(minimum_number_of_times) @cardinality = Cardinality.at_least(minimum_number_of_times) self end # Modifies expectation so that the expected method must be called at least once. # # @return [Expectation] the same expectation, thereby allowing invocations of other {Expectation} methods to be chained. # # @example Expected method must be called at least once. # object = mock() # object.expects(:expected_method).at_least_once # object.expected_method # # => verify succeeds # # object = mock() # object.expects(:expected_method).at_least_once # # => verify fails def at_least_once at_least(1) self end # Modifies expectation so that the expected method must be called at most a +maximum_number_of_times+. # # @param [Integer] maximum_number_of_times maximum number of expected invocations. # @return [Expectation] the same expectation, thereby allowing invocations of other {Expectation} methods to be chained. # # @example Expected method must be called at most twice. # object = mock() # object.expects(:expected_method).at_most(2) # 2.times { object.expected_method } # # => verify succeeds # # object = mock() # object.expects(:expected_method).at_most(2) # 3.times { object.expected_method } # => unexpected invocation def at_most(maximum_number_of_times) @cardinality = Cardinality.at_most(maximum_number_of_times) self end # Modifies expectation so that the expected method must be called at most once. # # @return [Expectation] the same expectation, thereby allowing invocations of other {Expectation} methods to be chained. # # @example Expected method must be called at most once. # object = mock() # object.expects(:expected_method).at_most_once # object.expected_method # # => verify succeeds # # object = mock() # object.expects(:expected_method).at_most_once # 2.times { object.expected_method } # => unexpected invocation def at_most_once() at_most(1) self end # Modifies expectation so that the expected method must be called with +expected_parameters+. # # May be used with parameter matchers in {ParameterMatchers}. # # @param [*Array] expected_parameters parameters expected. # @yield optional block specifying custom matching. # @yieldparam [*Array] actual_parameters parameters with which expected method was invoked. # @yieldreturn [Boolean] +true+ if +actual_parameters+ are acceptable. # @return [Expectation] the same expectation, thereby allowing invocations of other {Expectation} methods to be chained. # # @example Expected method must be called with expected parameters. # object = mock() # object.expects(:expected_method).with(:param1, :param2) # object.expected_method(:param1, :param2) # # => verify succeeds # # object = mock() # object.expects(:expected_method).with(:param1, :param2) # object.expected_method(:param3) # # => verify fails # # @example Expected method must be called with a value divisible by 4. # object = mock() # object.expects(:expected_method).with() { |value| value % 4 == 0 } # object.expected_method(16) # # => verify succeeds # # object = mock() # object.expects(:expected_method).with() { |value| value % 4 == 0 } # object.expected_method(17) # # => verify fails def with(*expected_parameters, &matching_block) @parameters_matcher = ParametersMatcher.new(expected_parameters, &matching_block) self end # Modifies expectation so that when the expected method is called, it yields with the specified +parameters+. # # May be called multiple times on the same expectation for consecutive invocations. # # @param [*Array] parameters parameters to be yielded. # @return [Expectation] the same expectation, thereby allowing invocations of other {Expectation} methods to be chained. # @see #then # # @example Yield parameters when expected method is invoked. # object = mock() # object.expects(:expected_method).yields('result') # yielded_value = nil # object.expected_method { |value| yielded_value = value } # yielded_value # => 'result' # # @example Yield different parameters on different invocations of the expected method. # object = mock() # object.stubs(:expected_method).yields(1).then.yields(2) # yielded_values_from_first_invocation = [] # yielded_values_from_second_invocation = [] # object.expected_method { |value| yielded_values_from_first_invocation << value } # first invocation # object.expected_method { |value| yielded_values_from_second_invocation << value } # second invocation # yielded_values_from_first_invocation # => [1] # yielded_values_from_second_invocation # => [2] def yields(*parameters) @yield_parameters.add(*parameters) self end # Modifies expectation so that when the expected method is called, it yields multiple times per invocation with the specified +parameter_groups+. # # @param [*Array] parameter_groups each element of +parameter_groups+ should iself be an +Array+ representing the parameters to be passed to the block for a single yield. # @return [Expectation] the same expectation, thereby allowing invocations of other {Expectation} methods to be chained. # @see #then # # @example When the +expected_method+ is called, the stub will invoke the block twice, the first time it passes +'result_1'+, +'result_2'+ as the parameters, and the second time it passes 'result_3' as the parameters. # object = mock() # object.expects(:expected_method).multiple_yields(['result_1', 'result_2'], ['result_3']) # yielded_values = [] # object.expected_method { |*values| yielded_values << values } # yielded_values # => [['result_1', 'result_2'], ['result_3]] # # @example Yield different groups of parameters on different invocations of the expected method. # object = mock() # object.stubs(:expected_method).multiple_yields([1, 2], [3]).then.multiple_yields([4], [5, 6]) # yielded_values_from_first_invocation = [] # yielded_values_from_second_invocation = [] # object.expected_method { |*values| yielded_values_from_first_invocation << values } # first invocation # object.expected_method { |*values| yielded_values_from_second_invocation << values } # second invocation # yielded_values_from_first_invocation # => [[1, 2], [3]] # yielded_values_from_second_invocation # => [[4], [5, 6]] def multiple_yields(*parameter_groups) @yield_parameters.multiple_add(*parameter_groups) self end # Modifies expectation so that when the expected method is called, it returns the specified +value+. # # @return [Expectation] the same expectation, thereby allowing invocations of other {Expectation} methods to be chained. # @see #then # # @overload def returns(value) # @param [Object] value value to return on invocation of expected method. # @overload def returns(*values) # @param [*Array] values values to return on consecutive invocations of expected method. # # @example Return the same value on every invocation. # object = mock() # object.stubs(:stubbed_method).returns('result') # object.stubbed_method # => 'result' # object.stubbed_method # => 'result' # # @example Return a different value on consecutive invocations. # object = mock() # object.stubs(:stubbed_method).returns(1, 2) # object.stubbed_method # => 1 # object.stubbed_method # => 2 # # @example Alternative way to return a different value on consecutive invocations. # object = mock() # object.stubs(:expected_method).returns(1, 2).then.returns(3) # object.expected_method # => 1 # object.expected_method # => 2 # object.expected_method # => 3 # # @example May be called in conjunction with {#raises} on the same expectation. # object = mock() # object.stubs(:expected_method).returns(1, 2).then.raises(Exception) # object.expected_method # => 1 # object.expected_method # => 2 # object.expected_method # => raises exception of class Exception1 # # @example Note that in Ruby a method returning multiple values is exactly equivalent to a method returning an +Array+ of those values. # object = mock() # object.stubs(:expected_method).returns([1, 2]) # x, y = object.expected_method # x # => 1 # y # => 2 def returns(*values) @return_values += ReturnValues.build(*values) self end # Modifies expectation so that when the expected method is called, it raises the specified +exception+ with the specified +message+ i.e. calls +Kernel#raise(exception, message)+. # # @param [Class,Exception,String,#exception] exception exception to be raised or message to be passed to RuntimeError. # @param [String] message exception message. # @return [Expectation] the same expectation, thereby allowing invocations of other {Expectation} methods to be chained. # # @see Kernel#raise # @see #then # # @overload def raises # @overload def raises(exception) # @overload def raises(exception, message) # # @example Raise specified exception if expected method is invoked. # object = stub() # object.stubs(:expected_method).raises(Exception, 'message') # object.expected_method # => raises exception of class Exception and with message 'message' # # @example Raise custom exception with extra constructor parameters by passing in an instance of the exception. # object = stub() # object.stubs(:expected_method).raises(MyException.new('message', 1, 2, 3)) # object.expected_method # => raises the specified instance of MyException # # @example Raise different exceptions on consecutive invocations of the expected method. # object = stub() # object.stubs(:expected_method).raises(Exception1).then.raises(Exception2) # object.expected_method # => raises exception of class Exception1 # object.expected_method # => raises exception of class Exception2 # # @example Raise an exception on first invocation of expected method and then return values on subsequent invocations. # object = stub() # object.stubs(:expected_method).raises(Exception).then.returns(2, 3) # object.expected_method # => raises exception of class Exception1 # object.expected_method # => 2 # object.expected_method # => 3 def raises(exception = RuntimeError, message = nil) @return_values += ReturnValues.new(ExceptionRaiser.new(exception, message)) self end # Modifies expectation so that when the expected method is called, it throws the specified +tag+ with the specific return value +object+ i.e. calls +Kernel#throw(tag, object)+. # # @param [Symbol,String] tag tag to throw to transfer control to the active catch block. # @param [Object] object return value for the catch block. # @return [Expectation] the same expectation, thereby allowing invocations of other {Expectation} methods to be chained. # # @see Kernel#throw # @see #then # # @overload def throw(tag) # @overload def throw(tag, object) # # @example Throw tag when expected method is invoked. # object = stub() # object.stubs(:expected_method).throws(:done) # object.expected_method # => throws tag :done # # @example Throw tag with return value +object+ c.f. +Kernel#throw+. # object = stub() # object.stubs(:expected_method).throws(:done, 'result') # object.expected_method # => throws tag :done and causes catch block to return 'result' # # @example Throw different tags on consecutive invocations of the expected method. # object = stub() # object.stubs(:expected_method).throws(:done).then.throws(:continue) # object.expected_method # => throws :done # object.expected_method # => throws :continue # # @example Throw tag on first invocation of expected method and then return values for subsequent invocations. # object = stub() # object.stubs(:expected_method).throws(:done).then.returns(2, 3) # object.expected_method # => throws :done # object.expected_method # => 2 # object.expected_method # => 3 def throws(tag, object = nil) @return_values += ReturnValues.new(Thrower.new(tag, object)) self end # @overload def then # Used as syntactic sugar to improve readability. It has no effect on state of the expectation. # @overload def then(state_machine.is(state_name)) # Used to change the +state_machine+ to the state specified by +state_name+ when the expected invocation occurs. # @param [StateMachine::State] state_machine.is(state_name) provides a mechanism to change the +state_machine+ into the state specified by +state_name+ when the expected method is invoked. # # @see API#states # @see StateMachine # @see #when # # @return [Expectation] the same expectation, thereby allowing invocations of other {Expectation} methods to be chained. # # @example Using {#then} as syntactic sugar when specifying values to be returned and exceptions to be raised on consecutive invocations of the expected method. # object = mock() # object.stubs(:expected_method).returns(1, 2).then.raises(Exception).then.returns(4) # object.expected_method # => 1 # object.expected_method # => 2 # object.expected_method # => raises exception of class Exception # object.expected_method # => 4 # # @example Using {#then} to change the +state+ of a +state_machine+ on the invocation of an expected method. # power = states('power').starts_as('off') # # radio = mock('radio') # radio.expects(:switch_on).then(power.is('on')) # radio.expects(:select_channel).with('BBC Radio 4').when(power.is('on')) # radio.expects(:adjust_volume).with(+5).when(power.is('on')) # radio.expects(:select_channel).with('BBC World Service').when(power.is('on')) # radio.expects(:adjust_volume).with(-5).when(power.is('on')) # radio.expects(:switch_off).then(power.is('off')) def then(*parameters) if parameters.length == 1 state = parameters.first add_side_effect(ChangeStateSideEffect.new(state)) end self end # Constrains the expectation to occur only when the +state_machine+ is in the state specified by +state_name+. # # @param [StateMachine::StatePredicate] state_machine.is(state_name) provides a mechanism to determine whether the +state_machine+ is in the state specified by +state_name+ when the expected method is invoked. # @return [Expectation] the same expectation, thereby allowing invocations of other {Expectation} methods to be chained. # # @see API#states # @see StateMachine # @see #then # # @example Using {#when} to only allow invocation of methods when "power" state machine is in the "on" state. # power = states('power').starts_as('off') # # radio = mock('radio') # radio.expects(:switch_on).then(power.is('on')) # radio.expects(:select_channel).with('BBC Radio 4').when(power.is('on')) # radio.expects(:adjust_volume).with(+5).when(power.is('on')) # radio.expects(:select_channel).with('BBC World Service').when(power.is('on')) # radio.expects(:adjust_volume).with(-5).when(power.is('on')) # radio.expects(:switch_off).then(power.is('off')) def when(state_predicate) add_ordering_constraint(InStateOrderingConstraint.new(state_predicate)) self end # Constrains the expectation so that it must be invoked at the current point in the +sequence+. # # To expect a sequence of invocations, write the expectations in order and add the +in_sequence(sequence)+ clause to each one. # # Expectations in a +sequence+ can have any invocation count. # # If an expectation in a sequence is stubbed, rather than expected, it can be skipped in the +sequence+. # # An expected method can appear in multiple sequences. # # @param [*Array] sequences sequences in which expected method should appear. # @return [Expectation] the same expectation, thereby allowing invocations of other {Expectation} methods to be chained. # # @see API#sequence # # @example Ensure methods are invoked in a specified order. # breakfast = sequence('breakfast') # # egg = mock('egg') # egg.expects(:crack).in_sequence(breakfast) # egg.expects(:fry).in_sequence(breakfast) # egg.expects(:eat).in_sequence(breakfast) def in_sequence(*sequences) sequences.each { |sequence| add_in_sequence_ordering_constraint(sequence) } self end # @private attr_reader :backtrace # @private def initialize(mock, expected_method_name, backtrace = nil) @mock = mock @method_matcher = MethodMatcher.new(expected_method_name.to_sym) @parameters_matcher = ParametersMatcher.new @ordering_constraints = [] @side_effects = [] @cardinality, @invocation_count = Cardinality.exactly(1), 0 @return_values = ReturnValues.new @yield_parameters = YieldParameters.new @backtrace = backtrace || caller end # @private def add_ordering_constraint(ordering_constraint) @ordering_constraints << ordering_constraint end # @private def add_in_sequence_ordering_constraint(sequence) sequence.constrain_as_next_in_sequence(self) end # @private def add_side_effect(side_effect) @side_effects << side_effect end # @private def perform_side_effects @side_effects.each { |side_effect| side_effect.perform } end # @private def in_correct_order? @ordering_constraints.all? { |ordering_constraint| ordering_constraint.allows_invocation_now? } end # @private def matches_method?(method_name) @method_matcher.match?(method_name) end # @private def match?(actual_method_name, *actual_parameters) @method_matcher.match?(actual_method_name) && @parameters_matcher.match?(actual_parameters) && in_correct_order? end # @private def invocations_allowed? @cardinality.invocations_allowed?(@invocation_count) end # @private def satisfied? @cardinality.satisfied?(@invocation_count) end # @private def invoke @invocation_count += 1 perform_side_effects() if block_given? then @yield_parameters.next_invocation.each do |yield_parameters| yield(*yield_parameters) end end @return_values.next end # @private def verified?(assertion_counter = nil) assertion_counter.increment if assertion_counter && @cardinality.needs_verifying? @cardinality.verified?(@invocation_count) end # @private def used? @cardinality.used?(@invocation_count) end # @private def inspect address = __id__ * 2 address += 0x100000000 if address < 0 "#" end # @private def mocha_inspect message = "#{@cardinality.mocha_inspect}, " message << case @invocation_count when 0 then "not yet invoked" when 1 then "invoked once" when 2 then "invoked twice" else "invoked #{@invocation_count} times" end message << ": " message << method_signature message << "; #{@ordering_constraints.map { |oc| oc.mocha_inspect }.join("; ")}" unless @ordering_constraints.empty? message end # @private def method_signature "#{@mock.mocha_inspect}.#{@method_matcher.mocha_inspect}#{@parameters_matcher.mocha_inspect}" end end end mocha-1.3.0/lib/mocha/integration.rb0000644000004100000410000000104713155337744017355 0ustar www-datawww-datarequire 'mocha/deprecation' require 'mocha/integration/test_unit' require 'mocha/integration/mini_test' module Mocha module Integration def self.activate if [Integration::TestUnit, Integration::MiniTest].map(&:activate).none? Deprecation.warning("Test::Unit or MiniTest must be loaded *before* `require 'mocha/setup'`.") Deprecation.warning("If you're integrating with a test library other than Test::Unit or MiniTest, you should use `require 'mocha/api'` instead of `require 'mocha/setup'`.") end end end end mocha-1.3.0/lib/mocha/expectation_error.rb0000644000004100000410000000050413155337744020563 0ustar www-datawww-datamodule Mocha # Default exception class raised when an unexpected invocation or an unsatisfied expectation occurs. # # Authors of test libraries may use +Mocha::ExpectationErrorFactory+ to have Mocha raise a different exception. # # @see Mocha::ExpectationErrorFactory class ExpectationError < Exception; end end mocha-1.3.0/lib/mocha/multiple_yields.rb0000644000004100000410000000044013155337744020232 0ustar www-datawww-datamodule Mocha class MultipleYields attr_reader :parameter_groups def initialize(*parameter_groups) @parameter_groups = parameter_groups end def each @parameter_groups.each do |parameter_group| yield(parameter_group) end end end end mocha-1.3.0/lib/mocha/backtrace_filter.rb0000644000004100000410000000057113155337744020317 0ustar www-datawww-datamodule Mocha class BacktraceFilter LIB_DIRECTORY = File.expand_path(File.join(File.dirname(__FILE__), "..")) + File::SEPARATOR def initialize(lib_directory = LIB_DIRECTORY) @path_pattern = Regexp.new(lib_directory) end def filtered(backtrace) backtrace.reject { |location| @path_pattern.match(File.expand_path(location)) } end end end mocha-1.3.0/lib/mocha/module_method.rb0000644000004100000410000000054613155337744017662 0ustar www-datawww-datarequire 'mocha/class_method' module Mocha class ModuleMethod < ClassMethod def method_exists?(method) return true if stubbee.public_methods(false).include?(method) return true if stubbee.protected_methods(false).include?(method) return true if stubbee.private_methods(false).include?(method) return false end end end mocha-1.3.0/lib/mocha/parameters_matcher.rb0000644000004100000410000000171313155337744020700 0ustar www-datawww-datarequire 'mocha/inspect' require 'mocha/parameter_matchers' module Mocha class ParametersMatcher def initialize(expected_parameters = [ParameterMatchers::AnyParameters.new], &matching_block) @expected_parameters, @matching_block = expected_parameters, matching_block end def match?(actual_parameters = []) if @matching_block return @matching_block.call(*actual_parameters) else return parameters_match?(actual_parameters) end end def parameters_match?(actual_parameters) matchers.all? { |matcher| matcher.matches?(actual_parameters) } && (actual_parameters.length == 0) end def mocha_inspect signature = matchers.mocha_inspect signature = signature.gsub(/^\[|\]$/, '') signature = signature.gsub(/^\{|\}$/, '') if matchers.length == 1 "(#{signature})" end def matchers @expected_parameters.map { |parameter| parameter.to_matcher } end end end mocha-1.3.0/lib/mocha/test_unit.rb0000644000004100000410000000011513155337744017043 0ustar www-datawww-datarequire "mocha/integration/test_unit" Mocha::Integration::TestUnit.activate mocha-1.3.0/lib/mocha/no_yields.rb0000644000004100000410000000010213155337744017006 0ustar www-datawww-datamodule Mocha class NoYields def each end end end mocha-1.3.0/lib/mocha/in_state_ordering_constraint.rb0000644000004100000410000000044713155337744023000 0ustar www-datawww-datamodule Mocha class InStateOrderingConstraint def initialize(state_predicate) @state_predicate = state_predicate end def allows_invocation_now? @state_predicate.active? end def mocha_inspect "when #{@state_predicate.mocha_inspect}" end end end mocha-1.3.0/lib/mocha/logger.rb0000644000004100000410000000023413155337744016306 0ustar www-datawww-datamodule Mocha class Logger def initialize(io) @io = io end def warn(message) @io.puts "WARNING: #{message}" end end end mocha-1.3.0/lib/mocha/debug.rb0000644000004100000410000000036613155337744016123 0ustar www-datawww-datamodule Mocha module Debug OPTIONS = (ENV['MOCHA_OPTIONS'] || '').split(',').inject({}) do |hash, key| hash[key] = true; hash end.freeze def self.puts(message) $stderr.puts(message) if OPTIONS['debug'] end end end mocha-1.3.0/lib/mocha/thrower.rb0000644000004100000410000000025713155337744016526 0ustar www-datawww-datamodule Mocha class Thrower def initialize(tag, object = nil) @tag, @object = tag, object end def evaluate throw @tag, @object end end end mocha-1.3.0/lib/mocha/yield_parameters.rb0000644000004100000410000000112013155337744020353 0ustar www-datawww-datarequire 'mocha/no_yields' require 'mocha/single_yield' require 'mocha/multiple_yields' module Mocha class YieldParameters def initialize @parameter_groups = [] end def next_invocation case @parameter_groups.length when 0 then NoYields.new when 1 then @parameter_groups.first else @parameter_groups.shift end end def add(*parameters) @parameter_groups << SingleYield.new(*parameters) end def multiple_add(*parameter_groups) @parameter_groups << MultipleYields.new(*parameter_groups) end end end mocha-1.3.0/lib/mocha/detection/0000755000004100000410000000000013155337744016461 5ustar www-datawww-datamocha-1.3.0/lib/mocha/detection/test_unit.rb0000644000004100000410000000133013155337744021021 0ustar www-datawww-datamodule Mocha module Detection module TestUnit def self.testcase if defined?(::Test::Unit::TestCase) && !(defined?(::MiniTest::Unit::TestCase) && (::Test::Unit::TestCase < ::MiniTest::Unit::TestCase)) && !(defined?(::MiniTest::Spec) && (::Test::Unit::TestCase < ::MiniTest::Spec)) ::Test::Unit::TestCase else nil end end def self.version version = '1.0.0' if testcase begin require 'test/unit/version' rescue LoadError end if defined?(::Test::Unit::VERSION) version = ::Test::Unit::VERSION end end version end end end end mocha-1.3.0/lib/mocha/detection/mini_test.rb0000644000004100000410000000102213155337744020774 0ustar www-datawww-datamodule Mocha module Detection module MiniTest def self.testcase if defined?(::Minitest::Test) ::Minitest::Test elsif defined?(::MiniTest::Unit::TestCase) ::MiniTest::Unit::TestCase else nil end end def self.version if defined?(::MiniTest::Unit::VERSION) ::MiniTest::Unit::VERSION elsif defined?(::Minitest::VERSION) ::Minitest::VERSION else '0.0.0' end end end end end mocha-1.3.0/lib/mocha/mock.rb0000644000004100000410000003361413155337744015770 0ustar www-datawww-datarequire 'metaclass' require 'mocha/expectation' require 'mocha/expectation_list' require 'mocha/names' require 'mocha/receivers' require 'mocha/method_matcher' require 'mocha/parameters_matcher' require 'mocha/unexpected_invocation' require 'mocha/argument_iterator' require 'mocha/expectation_error_factory' require 'mocha/deprecation' module Mocha # Traditional mock object. # # All methods return an {Expectation} which can be further modified by # methods on {Expectation}. # # Stubs and expectations are basically the same thing. A stub is just an # expectation of zero or more invocations. The {#stubs} method is syntactic # sugar to make the intent of the test more explicit. # # When a method is invoked on a mock object, the mock object searches through # its expectations from newest to oldest to find one that matches the # invocation. After the invocation, the matching expectation might stop # matching further invocations. For example, an +expects(:foo).once+ # expectation only matches once and will be ignored on future invocations # while an +expects(:foo).at_least_once+ expectation will always be matched # against invocations. # # This scheme allows you to: # # - Set up default stubs in your the +setup+ method of your test class and # override some of those stubs in individual tests. # - Set up different +once+ expectations for the same method with different # action per invocation. However, it's better to use the # {Expectation#returns} method with multiple arguments to do this, as # described below. # # However, there are some possible "gotchas" caused by this scheme: # # - if you create an expectation and then a stub for the same method, the # stub will always override the expectation and the expectation will never # be met. # - if you create a stub and then an expectation for the same method, the # expectation will match, and when it stops matching the stub will be used # instead, possibly masking test failures. # - if you create different expectations for the same method, they will be # invoked in the opposite order than that in which they were specified, # rather than the same order. # # The best thing to do is not set up multiple expectations and stubs for the # same method with exactly the same matchers. Instead, use the # {Expectation#returns} method with multiple arguments to create multiple # actions for a method. You can also chain multiple calls to # {Expectation#returns} and {Expectation#raises} (along with syntactic sugar # {Expectation#then} if desired). # # @example # object = mock() # object.stubs(:expected_method).returns(1, 2).then.raises(Exception) # object.expected_method # => 1 # object.expected_method # => 2 # object.expected_method # => raises exception of class Exception1 # # If you want to specify more complex ordering or order invocations across # different mock objects, use the {Expectation#in_sequence} method to # explicitly define a total or partial ordering of invocations. class Mock # Adds an expectation that the specified method must be called exactly once with any parameters. # # @param [Symbol,String] method_name name of expected method # @param [Hash] expected_methods_vs_return_values expected method name symbols as keys and corresponding return values as values - these expectations are setup as if {#expects} were called multiple times. # # @overload def expects(method_name) # @overload def expects(expected_methods_vs_return_values) # @return [Expectation] last-built expectation which can be further modified by methods on {Expectation}. # # @example Expected method invoked once so no error raised # object = mock() # object.expects(:expected_method) # object.expected_method # # @example Expected method not invoked so error raised # object = mock() # object.expects(:expected_method) # # error raised when test completes, because expected_method not called exactly once # # @example Expected method invoked twice so error raised # object = mock() # object.expects(:expected_method) # object.expected_method # object.expected_method # => error raised when expected method invoked second time # # @example Setup multiple expectations using +expected_methods_vs_return_values+. # object = mock() # object.expects(:expected_method_one => :result_one, :expected_method_two => :result_two) # # # is exactly equivalent to # # object = mock() # object.expects(:expected_method_one).returns(:result_one) # object.expects(:expected_method_two).returns(:result_two) def expects(method_name_or_hash, backtrace = nil) iterator = ArgumentIterator.new(method_name_or_hash) iterator.each { |*args| method_name = args.shift ensure_method_not_already_defined(method_name) expectation = Expectation.new(self, method_name, backtrace) expectation.returns(args.shift) if args.length > 0 @expectations.add(expectation) } end # Adds an expectation that the specified method may be called any number of times with any parameters. # # @param [Symbol,String] method_name name of stubbed method # @param [Hash] stubbed_methods_vs_return_values stubbed method name symbols as keys and corresponding return values as values - these stubbed methods are setup as if {#stubs} were called multiple times. # # @overload def stubs(method_name) # @overload def stubs(stubbed_methods_vs_return_values) # @return [Expectation] last-built expectation which can be further modified by methods on {Expectation}. # # @example No error raised however many times stubbed method is invoked # object = mock() # object.stubs(:stubbed_method) # object.stubbed_method # object.stubbed_method # # no error raised # # @example Setup multiple expectations using +stubbed_methods_vs_return_values+. # object = mock() # object.stubs(:stubbed_method_one => :result_one, :stubbed_method_two => :result_two) # # # is exactly equivalent to # # object = mock() # object.stubs(:stubbed_method_one).returns(:result_one) # object.stubs(:stubbed_method_two).returns(:result_two) def stubs(method_name_or_hash, backtrace = nil) iterator = ArgumentIterator.new(method_name_or_hash) iterator.each { |*args| method_name = args.shift ensure_method_not_already_defined(method_name) expectation = Expectation.new(self, method_name, backtrace) expectation.at_least(0) expectation.returns(args.shift) if args.length > 0 @expectations.add(expectation) } end # Removes the specified stubbed method (added by calls to {#expects} or {#stubs}) and all expectations associated with it. # # @param [Symbol] method_name name of method to unstub. # # @example Invoking an unstubbed method causes error to be raised # object = mock('mock') do # object.stubs(:stubbed_method).returns(:result_one) # object.stubbed_method # => :result_one # object.unstub(:stubbed_method) # object.stubbed_method # => unexpected invocation: #.stubbed_method() def unstub(method_name) @expectations.remove_all_matching_method(method_name) end # Constrains the {Mock} instance so that it can only expect or stub methods to which +responder+ responds. The constraint is only applied at method invocation time. # # A +NoMethodError+ will be raised if the +responder+ does not +#respond_to?+ a method invocation (even if the method has been expected or stubbed). # # The {Mock} instance will delegate its +#respond_to?+ method to the +responder+. # # Note that the methods on +responder+ are never actually invoked. # # @param [Object, #respond_to?] responder an object used to determine whether {Mock} instance should +#respond_to?+ to an invocation. # @return [Mock] the same {Mock} instance, thereby allowing invocations of other {Mock} methods to be chained. # @see #responds_like_instance_of # # @example Normal mocking # sheep = mock('sheep') # sheep.expects(:chew) # sheep.expects(:foo) # sheep.respond_to?(:chew) # => true # sheep.respond_to?(:foo) # => true # sheep.chew # sheep.foo # # no error raised # # @example Using {#responds_like} with an instance method # class Sheep # def chew(grass); end # end # # sheep = mock('sheep') # sheep.responds_like(Sheep.new) # sheep.expects(:chew) # sheep.expects(:foo) # sheep.respond_to?(:chew) # => true # sheep.respond_to?(:foo) # => false # sheep.chew # sheep.foo # => raises NoMethodError exception # # @example Using {#responds_like} with a class method # class Sheep # def self.number_of_legs; end # end # # sheep_class = mock('sheep_class') # sheep_class.responds_like(Sheep) # sheep_class.stubs(:number_of_legs).returns(4) # sheep_class.expects(:foo) # sheep_class.respond_to?(:number_of_legs) # => true # sheep_class.respond_to?(:foo) # => false # sheep_class.number_of_legs # => 4 # sheep_class.foo # => raises NoMethodError exception def responds_like(responder) @responder = responder self end # Constrains the {Mock} instance so that it can only expect or stub methods to which an instance of the +responder_class+ responds. The constraint is only applied at method invocation time. Note that the responder instance is instantiated using +Class#allocate+. # # A +NoMethodError+ will be raised if the responder instance does not +#respond_to?+ a method invocation (even if the method has been expected or stubbed). # # The {Mock} instance will delegate its +#respond_to?+ method to the responder instance. # # Note that the methods on the responder instance are never actually invoked. # # @param [Class] responder_class a class used to determine whether {Mock} instance should +#respond_to?+ to an invocation. # @return [Mock] the same {Mock} instance, thereby allowing invocations of other {Mock} methods to be chained. # @see #responds_like # # @example Using {#responds_like_instance_of} # class Sheep # def initialize # raise "some awkward code we don't want to call" # end # def chew(grass); end # end # # sheep = mock('sheep') # sheep.responds_like_instance_of(Sheep) # sheep.expects(:chew) # sheep.expects(:foo) # sheep.respond_to?(:chew) # => true # sheep.respond_to?(:foo) # => false # sheep.chew # sheep.foo # => raises NoMethodError exception def responds_like_instance_of(responder_class) responds_like(responder_class.allocate) end # @private def initialize(mockery, name = nil, receiver = nil, &block) @mockery = mockery @name = name || DefaultName.new(self) @receiver = receiver || DefaultReceiver.new(self) @expectations = ExpectationList.new @everything_stubbed = false @responder = nil @unexpected_invocation = nil if block Deprecation.warning('Passing a block is deprecated. Use Object#tap or define stubs/expectations with an explicit receiver instead.') instance_eval(&block) end end # @private attr_reader :everything_stubbed alias_method :__expects__, :expects alias_method :__stubs__, :stubs alias_method :quacks_like, :responds_like alias_method :quacks_like_instance_of, :responds_like_instance_of # @private def __expectations__ @expectations end # @private def stub_everything @everything_stubbed = true end # @private def all_expectations @receiver.mocks.inject(ExpectationList.new) { |e, m| e + m.__expectations__ } end # @private def method_missing(symbol, *arguments, &block) if @responder and not @responder.respond_to?(symbol) raise NoMethodError, "undefined method `#{symbol}' for #{self.mocha_inspect} which responds like #{@responder.mocha_inspect}" end if matching_expectation_allowing_invocation = all_expectations.match_allowing_invocation(symbol, *arguments) matching_expectation_allowing_invocation.invoke(&block) else if (matching_expectation = all_expectations.match(symbol, *arguments)) || (!matching_expectation && !@everything_stubbed) if @unexpected_invocation.nil? @unexpected_invocation = UnexpectedInvocation.new(self, symbol, *arguments) matching_expectation.invoke(&block) if matching_expectation message = @unexpected_invocation.full_description message << @mockery.mocha_inspect else message = @unexpected_invocation.short_description end raise ExpectationErrorFactory.build(message, caller) end end end # @private def respond_to?(symbol, include_private = false) if @responder then if @responder.method(:respond_to?).arity > 1 @responder.respond_to?(symbol, include_private) else @responder.respond_to?(symbol) end else @everything_stubbed || all_expectations.matches_method?(symbol) end end # @private def __verified__?(assertion_counter = nil) @expectations.verified?(assertion_counter) end # @private def mocha_inspect @name.mocha_inspect end # @private def inspect mocha_inspect end # @private def ensure_method_not_already_defined(method_name) self.__metaclass__.send(:undef_method, method_name) if self.__metaclass__.method_defined?(method_name) || self.__metaclass__.private_method_defined?(method_name) end # @private def any_expectations? @expectations.any? end end end mocha-1.3.0/lib/mocha/api.rb0000644000004100000410000002034513155337744015605 0ustar www-datawww-datarequire 'mocha/parameter_matchers' require 'mocha/hooks' require 'mocha/mockery' require 'mocha/sequence' require 'mocha/object_methods' require 'mocha/module_methods' require 'mocha/class_methods' module Mocha # Methods added to +Test::Unit::TestCase+, +MiniTest::Unit::TestCase+ or equivalent. module API include ParameterMatchers include Hooks # @private def self.included(mod) Object.send(:include, Mocha::ObjectMethods) Module.send(:include, Mocha::ModuleMethods) Class.send(:include, Mocha::ClassMethods) end # Builds a new mock object # # @param [String] name identifies mock object in error messages. # @param [Hash] expected_methods_vs_return_values expected method name symbols as keys and corresponding return values as values - these expectations are setup as if {Mock#expects} were called multiple times. # @yield optional block to be evaluated in the context of the mock object instance, giving an alternative way to setup stubbed methods. # @yield note that the block is evaulated by calling Mock#instance_eval and so things like instance variables declared in the test will not be available within the block. # @yield deprecated: use Object#tap or define stubs/expectations with an explicit receiver instead. # @return [Mock] a new mock object # # @overload def mock(name, &block) # @overload def mock(expected_methods_vs_return_values = {}, &block) # @overload def mock(name, expected_methods_vs_return_values = {}, &block) # # @example Using expected_methods_vs_return_values Hash to setup expectations. # def test_motor_starts_and_stops # motor = mock('motor', :start => true, :stop => true) # assert motor.start # assert motor.stop # # an error will be raised unless both Motor#start and Motor#stop have been called # end # @example Using the optional block to setup expectations & stubbed methods [deprecated]. # def test_motor_starts_and_stops # motor = mock('motor') do # expects(:start).with(100.rpm).returns(true) # stubs(:stop).returns(true) # end # assert motor.start(100.rpm) # assert motor.stop # # an error will only be raised if Motor#start(100.rpm) has not been called # end def mock(*arguments, &block) name = arguments.shift if arguments.first.is_a?(String) expectations = arguments.shift || {} mock = name ? Mockery.instance.named_mock(name, &block) : Mockery.instance.unnamed_mock(&block) mock.expects(expectations) mock end # Builds a new mock object # # @param [String] name identifies mock object in error messages. # @param [Hash] stubbed_methods_vs_return_values stubbed method name symbols as keys and corresponding return values as values - these stubbed methods are setup as if {Mock#stubs} were called multiple times. # @yield optional block to be evaluated in the context of the mock object instance, giving an alternative way to setup stubbed methods. # @yield note that the block is evaulated by calling Mock#instance_eval and so things like instance variables declared in the test will not be available within the block. # @yield deprecated: use Object#tap or define stubs/expectations with an explicit receiver instead. # @return [Mock] a new mock object # # @overload def stub(name, &block) # @overload def stub(stubbed_methods_vs_return_values = {}, &block) # @overload def stub(name, stubbed_methods_vs_return_values = {}, &block) # # @example Using stubbed_methods_vs_return_values Hash to setup stubbed methods. # def test_motor_starts_and_stops # motor = stub('motor', :start => true, :stop => true) # assert motor.start # assert motor.stop # # an error will not be raised even if either Motor#start or Motor#stop has not been called # end # # @example Using the optional block to setup expectations & stubbed methods [deprecated]. # def test_motor_starts_and_stops # motor = stub('motor') do # expects(:start).with(100.rpm).returns(true) # stubs(:stop).returns(true) # end # assert motor.start(100.rpm) # assert motor.stop # # an error will only be raised if Motor#start(100.rpm) has not been called # end def stub(*arguments, &block) name = arguments.shift if arguments.first.is_a?(String) expectations = arguments.shift || {} stub = name ? Mockery.instance.named_mock(name, &block) : Mockery.instance.unnamed_mock(&block) stub.stubs(expectations) stub end # Builds a mock object that accepts calls to any method. By default it will return +nil+ for any method call. # # @param [String] name identifies mock object in error messages. # @param [Hash] stubbed_methods_vs_return_values stubbed method name symbols as keys and corresponding return values as values - these stubbed methods are setup as if {Mock#stubs} were called multiple times. # @yield optional block to be evaluated in the context of the mock object instance, giving an alternative way to setup stubbed methods. # @yield note that the block is evaulated by calling Mock#instance_eval and so things like instance variables declared in the test will not be available within the block. # @yield deprecated: use Object#tap or define stubs/expectations with an explicit receiver instead. # @return [Mock] a new mock object # # @overload def stub_everything(name, &block) # @overload def stub_everything(stubbed_methods_vs_return_values = {}, &block) # @overload def stub_everything(name, stubbed_methods_vs_return_values = {}, &block) # # @example Ignore invocations of irrelevant methods. # def test_motor_stops # motor = stub_everything('motor', :stop => true) # assert_nil motor.irrelevant_method_1 # => no error raised # assert_nil motor.irrelevant_method_2 # => no error raised # assert motor.stop # end def stub_everything(*arguments, &block) name = arguments.shift if arguments.first.is_a?(String) expectations = arguments.shift || {} stub = name ? Mockery.instance.named_mock(name, &block) : Mockery.instance.unnamed_mock(&block) stub.stub_everything stub.stubs(expectations) stub end # Builds a new sequence which can be used to constrain the order in which expectations can occur. # # Specify that an expected invocation must occur within a named {Sequence} by using {Expectation#in_sequence}. # # @return [Sequence] a new sequence # # @see Expectation#in_sequence # # @example Ensure methods on egg are invoked in correct order. # breakfast = sequence('breakfast') # # egg = mock('egg') do # expects(:crack).in_sequence(breakfast) # expects(:fry).in_sequence(breakfast) # expects(:eat).in_sequence(breakfast) # end def sequence(name) Sequence.new(name) end # Builds a new state machine which can be used to constrain the order in which expectations can occur. # # Specify the initial state of the state machine by using {StateMachine#starts_as}. # # Specify that an expected invocation should change the state of the state machine by using {Expectation#then}. # # Specify that an expected invocation should be constrained to occur within a particular +state+ by using {Expectation#when}. # # A test can contain multiple state machines. # # @return [StateMachine] a new state machine # # @see Expectation#then # @see Expectation#when # @see StateMachine # @example Constrain expected invocations to occur in particular states. # power = states('power').starts_as('off') # # radio = mock('radio') do # expects(:switch_on).then(power.is('on')) # expects(:select_channel).with('BBC Radio 4').when(power.is('on')) # expects(:adjust_volume).with(+5).when(power.is('on')) # expects(:select_channel).with('BBC World Service').when(power.is('on')) # expects(:adjust_volume).with(-5).when(power.is('on')) # expects(:switch_off).then(power.is('off')) # end def states(name) Mockery.instance.new_state_machine(name) end end end mocha-1.3.0/lib/mocha/exception_raiser.rb0000644000004100000410000000052013155337744020370 0ustar www-datawww-datamodule Mocha class ExceptionRaiser def initialize(exception, message) @exception, @message = exception, message end def evaluate raise @exception, @exception.to_s if @exception.is_a?(Module) && (@exception < Interrupt) raise @exception, @message if @message raise @exception end end end mocha-1.3.0/lib/mocha/object_methods.rb0000644000004100000410000001560113155337744020024 0ustar www-datawww-datarequire 'mocha/mockery' require 'mocha/instance_method' require 'mocha/argument_iterator' require 'mocha/expectation_error_factory' module Mocha # Methods added to all objects to allow mocking and stubbing on real (i.e. non-mock) objects. # # Both {#expects} and {#stubs} return an {Expectation} which can be further modified by methods on {Expectation}. module ObjectMethods # @private alias_method :_method, :method # @private def mocha @mocha ||= Mocha::Mockery.instance.mock_impersonating(self) end # @private def reset_mocha @mocha = nil end # @private def stubba_method Mocha::InstanceMethod end # @private def stubba_object self end # Adds an expectation that the specified method must be called exactly once with any parameters. # # The original implementation of the method is replaced during the test and then restored at the end of the test. The temporary replacement method has the same visibility as the original method. # # @param [Symbol,String] method_name name of expected method # @param [Hash] expected_methods_vs_return_values expected method name symbols as keys and corresponding return values as values - these expectations are setup as if {#expects} were called multiple times. # # @overload def expects(method_name) # @overload def expects(expected_methods_vs_return_values) # @return [Expectation] last-built expectation which can be further modified by methods on {Expectation}. # @raise [StubbingError] if attempting to stub method which is not allowed. # # @example Setting up an expectation on a non-mock object. # product = Product.new # product.expects(:save).returns(true) # assert_equal true, product.save # # @example Setting up multiple expectations on a non-mock object. # product = Product.new # product.expects(:valid? => true, :save => true) # # # exactly equivalent to # # product = Product.new # product.expects(:valid?).returns(true) # product.expects(:save).returns(true) # # @see Mock#expects def expects(expected_methods_vs_return_values) if expected_methods_vs_return_values.to_s =~ /the[^a-z]*spanish[^a-z]*inquisition/i raise ExpectationErrorFactory.build('NOBODY EXPECTS THE SPANISH INQUISITION!') end if frozen? raise StubbingError.new("can't stub method on frozen object: #{mocha_inspect}", caller) end expectation = nil mockery = Mocha::Mockery.instance iterator = ArgumentIterator.new(expected_methods_vs_return_values) iterator.each { |*args| method_name = args.shift mockery.on_stubbing(self, method_name) method = stubba_method.new(stubba_object, method_name) mockery.stubba.stub(method) expectation = mocha.expects(method_name, caller) expectation.returns(args.shift) if args.length > 0 } expectation end # Adds an expectation that the specified method may be called any number of times with any parameters. # # The original implementation of the method is replaced during the test and then restored at the end of the test. The temporary replacement method has the same visibility as the original method. # # @param [Symbol,String] method_name name of stubbed method # @param [Hash] stubbed_methods_vs_return_values stubbed method name symbols as keys and corresponding return values as values - these stubbed methods are setup as if {#stubs} were called multiple times. # # @overload def stubs(method_name) # @overload def stubs(stubbed_methods_vs_return_values) # @return [Expectation] last-built expectation which can be further modified by methods on {Expectation}. # @raise [StubbingError] if attempting to stub method which is not allowed. # # @example Setting up a stubbed methods on a non-mock object. # product = Product.new # product.stubs(:save).returns(true) # assert_equal true, product.save # # @example Setting up multiple stubbed methods on a non-mock object. # product = Product.new # product.stubs(:valid? => true, :save => true) # # # exactly equivalent to # # product = Product.new # product.stubs(:valid?).returns(true) # product.stubs(:save).returns(true) # # @see Mock#stubs def stubs(stubbed_methods_vs_return_values) if frozen? raise StubbingError.new("can't stub method on frozen object: #{mocha_inspect}", caller) end expectation = nil mockery = Mocha::Mockery.instance iterator = ArgumentIterator.new(stubbed_methods_vs_return_values) iterator.each { |*args| method_name = args.shift mockery.on_stubbing(self, method_name) method = stubba_method.new(stubba_object, method_name) mockery.stubba.stub(method) expectation = mocha.stubs(method_name, caller) expectation.returns(args.shift) if args.length > 0 } expectation end # Removes the specified stubbed methods (added by calls to {#expects} or {#stubs}) and all expectations associated with them. # # Restores the original behaviour of the methods before they were stubbed. This is normally done automatically at the end of each test, but in some circumstances you may want to do it *before* the end of the test. # # WARNING: If you {#unstub} a method which still has unsatisfied expectations, you may be removing the only way those expectations can be satisfied. Use {#unstub} with care. # # @param [Array] method_names names of methods to unstub. # # @example Stubbing and unstubbing a method on a real (non-mock) object. # multiplier = Multiplier.new # multiplier.double(2) # => 4 # multiplier.stubs(:double).raises # new behaviour defined # multiplier.double(2) # => raises exception # multiplier.unstub(:double) # original behaviour restored # multiplier.double(2) # => 4 # # @example Unstubbing multiple methods on a real (non-mock) object. # multiplier.unstub(:double, :triple) # # # exactly equivalent to # # multiplier.unstub(:double) # multiplier.unstub(:triple) def unstub(*method_names) mockery = Mocha::Mockery.instance method_names.each do |method_name| method = stubba_method.new(stubba_object, method_name) mockery.stubba.unstub(method) end end # @private def method_exists?(method, include_public_methods = true) if include_public_methods return true if public_methods(include_superclass_methods = true).include?(method) return true if respond_to?(method.to_sym) end return true if protected_methods(include_superclass_methods = true).include?(method) return true if private_methods(include_superclass_methods = true).include?(method) return false end end end mocha-1.3.0/lib/mocha/version.rb0000644000004100000410000000004513155337744016514 0ustar www-datawww-datamodule Mocha VERSION = "1.3.0" end mocha-1.3.0/lib/mocha/change_state_side_effect.rb0000644000004100000410000000034313155337744021775 0ustar www-datawww-datamodule Mocha class ChangeStateSideEffect def initialize(state) @state = state end def perform @state.activate end def mocha_inspect "then #{@state.mocha_inspect}" end end end mocha-1.3.0/lib/mocha/single_yield.rb0000644000004100000410000000030313155337744017473 0ustar www-datawww-datamodule Mocha class SingleYield attr_reader :parameters def initialize(*parameters) @parameters = parameters end def each yield(@parameters) end end end mocha-1.3.0/lib/mocha/inspect.rb0000644000004100000410000000162413155337744016500 0ustar www-datawww-datarequire 'date' module Mocha module ObjectMethods def mocha_inspect address = self.__id__ * 2 address += 0x100000000 if address < 0 inspect =~ /#" : inspect end end module ArrayMethods def mocha_inspect "[#{collect { |member| member.mocha_inspect }.join(', ')}]" end end module HashMethods def mocha_inspect "{#{collect { |key, value| "#{key.mocha_inspect} => #{value.mocha_inspect}" }.join(', ')}}" end end module TimeMethods def mocha_inspect "#{inspect} (#{to_f} secs)" end end module DateMethods def mocha_inspect to_s end end end class Object include Mocha::ObjectMethods end class Array include Mocha::ArrayMethods end class Hash include Mocha::HashMethods end class Time include Mocha::TimeMethods end class Date include Mocha::DateMethods end mocha-1.3.0/lib/mocha/mockery.rb0000644000004100000410000001376313155337744016513 0ustar www-datawww-datarequire 'mocha/ruby_version' require 'mocha/central' require 'mocha/mock' require 'mocha/names' require 'mocha/receivers' require 'mocha/state_machine' require 'mocha/logger' require 'mocha/configuration' require 'mocha/stubbing_error' require 'mocha/expectation_error_factory' module Mocha class Mockery class << self def instance @instance ||= new end def verify(*args) instance.verify(*args) end def teardown instance.teardown end def reset_instance @instance = nil end end def named_mock(name, &block) add_mock(Mock.new(self, Name.new(name), &block)) end def unnamed_mock(&block) add_mock(Mock.new(self, &block)) end def mock_impersonating(object, &block) add_mock(Mock.new(self, ImpersonatingName.new(object), ObjectReceiver.new(object), &block)) end def mock_impersonating_any_instance_of(klass, &block) add_mock(Mock.new(self, ImpersonatingAnyInstanceName.new(klass), AnyInstanceReceiver.new(klass), &block)) end def new_state_machine(name) add_state_machine(StateMachine.new(name)) end def verify(assertion_counter = nil) unless mocks.all? { |mock| mock.__verified__?(assertion_counter) } message = "not all expectations were satisfied\n#{mocha_inspect}" if unsatisfied_expectations.empty? backtrace = caller else backtrace = unsatisfied_expectations[0].backtrace end raise ExpectationErrorFactory.build(message, backtrace) end expectations.each do |e| unless Mocha::Configuration.allow?(:stubbing_method_unnecessarily) unless e.used? on_stubbing_method_unnecessarily(e) end end end end def teardown stubba.unstub_all reset end def stubba @stubba ||= Central.new end def mocks @mocks ||= [] end def state_machines @state_machines ||= [] end def mocha_inspect message = "" message << "unsatisfied expectations:\n- #{unsatisfied_expectations.map { |e| e.mocha_inspect }.join("\n- ")}\n" unless unsatisfied_expectations.empty? message << "satisfied expectations:\n- #{satisfied_expectations.map { |e| e.mocha_inspect }.join("\n- ")}\n" unless satisfied_expectations.empty? message << "states:\n- #{state_machines.map { |sm| sm.mocha_inspect }.join("\n- ")}" unless state_machines.empty? message end def on_stubbing(object, method) method = PRE_RUBY_V19 ? method.to_s : method.to_sym unless Mocha::Configuration.allow?(:stubbing_non_existent_method) unless object.method_exists?(method, include_public_methods = true) on_stubbing_non_existent_method(object, method) end end unless Mocha::Configuration.allow?(:stubbing_non_public_method) if object.method_exists?(method, include_public_methods = false) on_stubbing_non_public_method(object, method) end end unless Mocha::Configuration.allow?(:stubbing_method_on_nil) if object.nil? on_stubbing_method_on_nil(object, method) end end unless Mocha::Configuration.allow?(:stubbing_method_on_non_mock_object) on_stubbing_method_on_non_mock_object(object, method) end end def on_stubbing_non_existent_method(object, method) if Mocha::Configuration.prevent?(:stubbing_non_existent_method) raise StubbingError.new("stubbing non-existent method: #{object.mocha_inspect}.#{method}", caller) end if Mocha::Configuration.warn_when?(:stubbing_non_existent_method) logger.warn "stubbing non-existent method: #{object.mocha_inspect}.#{method}" end end def on_stubbing_non_public_method(object, method) if Mocha::Configuration.prevent?(:stubbing_non_public_method) raise StubbingError.new("stubbing non-public method: #{object.mocha_inspect}.#{method}", caller) end if Mocha::Configuration.warn_when?(:stubbing_non_public_method) logger.warn "stubbing non-public method: #{object.mocha_inspect}.#{method}" end end def on_stubbing_method_on_nil(object, method) if Mocha::Configuration.prevent?(:stubbing_method_on_nil) raise StubbingError.new("stubbing method on nil: #{object.mocha_inspect}.#{method}", caller) end if Mocha::Configuration.warn_when?(:stubbing_method_on_nil) logger.warn "stubbing method on nil: #{object.mocha_inspect}.#{method}" end end def on_stubbing_method_on_non_mock_object(object, method) if Mocha::Configuration.prevent?(:stubbing_method_on_non_mock_object) raise StubbingError.new("stubbing method on non-mock object: #{object.mocha_inspect}.#{method}", caller) end if Mocha::Configuration.warn_when?(:stubbing_method_on_non_mock_object) logger.warn "stubbing method on non-mock object: #{object.mocha_inspect}.#{method}" end end def on_stubbing_method_unnecessarily(expectation) if Mocha::Configuration.prevent?(:stubbing_method_unnecessarily) raise StubbingError.new("stubbing method unnecessarily: #{expectation.method_signature}", expectation.backtrace) end if Mocha::Configuration.warn_when?(:stubbing_method_unnecessarily) logger.warn "stubbing method unnecessarily: #{expectation.method_signature}" end end attr_writer :logger def logger @logger ||= Logger.new($stderr) end private def expectations mocks.map { |mock| mock.__expectations__.to_a }.flatten end def unsatisfied_expectations expectations.reject { |e| e.verified? } end def satisfied_expectations expectations.select { |e| e.verified? } end def add_mock(mock) mocks << mock mock end def add_state_machine(state_machine) state_machines << state_machine state_machine end def reset @stubba = nil @mocks = nil @state_machines = nil end end end mocha-1.3.0/lib/mocha/instance_method.rb0000644000004100000410000000013413155337744020172 0ustar www-datawww-datarequire 'mocha/class_method' module Mocha class InstanceMethod < ClassMethod end end mocha-1.3.0/lib/mocha/integration/0000755000004100000410000000000013155337744017026 5ustar www-datawww-datamocha-1.3.0/lib/mocha/integration/assertion_counter.rb0000644000004100000410000000032713155337744023123 0ustar www-datawww-datamodule Mocha module Integration class AssertionCounter def initialize(test_case) @test_case = test_case end def increment @test_case.assert(true) end end end end mocha-1.3.0/lib/mocha/integration/test_unit/0000755000004100000410000000000013155337744021044 5ustar www-datawww-datamocha-1.3.0/lib/mocha/integration/test_unit/gem_version_200.rb0000644000004100000410000000333613155337744024274 0ustar www-datawww-datarequire 'mocha/integration/assertion_counter' require 'mocha/integration/monkey_patcher' require 'mocha/expectation_error' module Mocha module Integration module TestUnit module GemVersion200 def self.applicable_to?(test_unit_version, ruby_version = nil) Gem::Requirement.new('2.0.0').satisfied_by?(test_unit_version) end def self.description "monkey patch for Test::Unit gem v2.0.0" end def self.included(mod) MonkeyPatcher.apply(mod, RunMethodPatch) end module RunMethodPatch def run(result) assertion_counter = AssertionCounter.new(self) begin @_result = result yield(Test::Unit::TestCase::STARTED, name) begin begin run_setup __send__(@method_name) mocha_verify(assertion_counter) rescue Mocha::ExpectationError => e add_failure(e.message, e.backtrace) rescue Exception @interrupted = true raise unless handle_exception($!) ensure begin run_teardown rescue Mocha::ExpectationError => e add_failure(e.message, e.backtrace) rescue Exception raise unless handle_exception($!) end end ensure mocha_teardown end result.add_run yield(Test::Unit::TestCase::FINISHED, name) ensure @_result = nil end end end end end end end mocha-1.3.0/lib/mocha/integration/test_unit/ruby_version_186_and_above.rb0000644000004100000410000000376613155337744026527 0ustar www-datawww-datarequire 'mocha/integration/assertion_counter' require 'mocha/integration/monkey_patcher' require 'mocha/expectation_error' module Mocha module Integration module TestUnit module RubyVersion186AndAbove def self.applicable_to?(test_unit_version, ruby_version) Gem::Requirement.new('<= 1.2.3').satisfied_by?(test_unit_version) && Gem::Requirement.new('>= 1.8.6').satisfied_by?(ruby_version) end def self.description "monkey patch for standard library Test::Unit in Ruby >= v1.8.6" end def self.included(mod) MonkeyPatcher.apply(mod, RunMethodPatch) end module RunMethodPatch def run(result) assertion_counter = AssertionCounter.new(self) yield(Test::Unit::TestCase::STARTED, name) @_result = result begin begin setup __send__(@method_name) mocha_verify(assertion_counter) rescue Mocha::ExpectationError => e add_failure(e.message, e.backtrace) rescue Test::Unit::AssertionFailedError => e add_failure(e.message, e.backtrace) rescue Exception raise if Test::Unit::TestCase::PASSTHROUGH_EXCEPTIONS.include? $!.class add_error($!) ensure begin teardown rescue Mocha::ExpectationError => e add_failure(e.message, e.backtrace) rescue Test::Unit::AssertionFailedError => e add_failure(e.message, e.backtrace) rescue Exception raise if Test::Unit::TestCase::PASSTHROUGH_EXCEPTIONS.include? $!.class add_error($!) end end ensure mocha_teardown end result.add_run yield(Test::Unit::TestCase::FINISHED, name) end end end end end end mocha-1.3.0/lib/mocha/integration/test_unit/gem_version_201_to_202.rb0000644000004100000410000000336513155337744025364 0ustar www-datawww-datarequire 'mocha/integration/assertion_counter' require 'mocha/integration/monkey_patcher' require 'mocha/expectation_error' module Mocha module Integration module TestUnit module GemVersion201To202 def self.applicable_to?(test_unit_version, ruby_version = nil) Gem::Requirement.new('>= 2.0.1', '<= 2.0.2').satisfied_by?(test_unit_version) end def self.description "monkey patch for Test::Unit gem >= v2.0.1 and <= v2.0.2" end def self.included(mod) MonkeyPatcher.apply(mod, RunMethodPatch) end module RunMethodPatch def run(result) assertion_counter = AssertionCounter.new(self) begin @_result = result yield(Test::Unit::TestCase::STARTED, name) begin begin run_setup run_test mocha_verify(assertion_counter) rescue Mocha::ExpectationError => e add_failure(e.message, e.backtrace) rescue Exception @interrupted = true raise unless handle_exception($!) ensure begin run_teardown rescue Mocha::ExpectationError => e add_failure(e.message, e.backtrace) rescue Exception raise unless handle_exception($!) end end ensure mocha_teardown end result.add_run yield(Test::Unit::TestCase::FINISHED, name) ensure @_result = nil end end end end end end end mocha-1.3.0/lib/mocha/integration/test_unit/gem_version_230_to_250.rb0000644000004100000410000000405413155337744025365 0ustar www-datawww-datarequire 'mocha/integration/assertion_counter' require 'mocha/integration/monkey_patcher' require 'mocha/expectation_error' module Mocha module Integration module TestUnit module GemVersion230To250 def self.applicable_to?(test_unit_version, ruby_version = nil) Gem::Requirement.new('>= 2.3.0', '<= 2.5.0').satisfied_by?(test_unit_version) end def self.description "monkey patch for Test::Unit gem >= v2.3.0 and <= v2.5.0" end def self.included(mod) MonkeyPatcher.apply(mod, RunMethodPatch) end module RunMethodPatch def run(result) assertion_counter = AssertionCounter.new(self) begin @internal_data.test_started @_result = result yield(Test::Unit::TestCase::STARTED, name) yield(Test::Unit::TestCase::STARTED_OBJECT, self) begin begin run_setup run_test run_cleanup mocha_verify(assertion_counter) add_pass rescue Mocha::ExpectationError => e add_failure(e.message, e.backtrace) rescue Exception @internal_data.interrupted raise unless handle_exception($!) ensure begin run_teardown rescue Mocha::ExpectationError => e add_failure(e.message, e.backtrace) rescue Exception raise unless handle_exception($!) end end ensure mocha_teardown end @internal_data.test_finished result.add_run yield(Test::Unit::TestCase::FINISHED, name) yield(Test::Unit::TestCase::FINISHED_OBJECT, self) ensure # @_result = nil # For test-spec's after_all :< end end end end end end end mocha-1.3.0/lib/mocha/integration/test_unit/nothing.rb0000644000004100000410000000061713155337744023043 0ustar www-datawww-datamodule Mocha module Integration module TestUnit module Nothing def self.applicable_to?(test_unit_version, ruby_version = nil) true end def self.description "nothing (no Test::Unit integration available)" end def self.included(mod) raise "No Test::Unit integration available" end end end end end mocha-1.3.0/lib/mocha/integration/test_unit/ruby_version_185_and_below.rb0000644000004100000410000000353313155337744026532 0ustar www-datawww-datarequire 'mocha/integration/assertion_counter' require 'mocha/integration/monkey_patcher' require 'mocha/expectation_error' module Mocha module Integration module TestUnit module RubyVersion185AndBelow def self.applicable_to?(test_unit_version, ruby_version) Gem::Requirement.new('<= 1.2.3').satisfied_by?(test_unit_version) && Gem::Requirement.new('<= 1.8.5').satisfied_by?(ruby_version) end def self.description "monkey patch for standard library in Ruby <= v1.8.5" end def self.included(mod) MonkeyPatcher.apply(mod, RunMethodPatch) end module RunMethodPatch def run(result) assertion_counter = AssertionCounter.new(self) yield(Test::Unit::TestCase::STARTED, name) @_result = result begin begin setup __send__(@method_name) mocha_verify(assertion_counter) rescue Mocha::ExpectationError => e add_failure(e.message, e.backtrace) rescue Test::Unit::AssertionFailedError => e add_failure(e.message, e.backtrace) rescue StandardError, ScriptError add_error($!) ensure begin teardown rescue Mocha::ExpectationError => e add_failure(e.message, e.backtrace) rescue Test::Unit::AssertionFailedError => e add_failure(e.message, e.backtrace) rescue StandardError, ScriptError add_error($!) end end ensure mocha_teardown end result.add_run yield(Test::Unit::TestCase::FINISHED, name) end end end end end end mocha-1.3.0/lib/mocha/integration/test_unit/adapter.rb0000644000004100000410000000247613155337744023022 0ustar www-datawww-datarequire 'mocha/api' require 'mocha/integration/assertion_counter' require 'mocha/expectation_error' module Mocha module Integration module TestUnit # Integrates Mocha into recent versions of Test::Unit. # # See the source code for an example of how to integrate Mocha into a test library. module Adapter include Mocha::API # @private def self.applicable_to?(test_unit_version, ruby_version = nil) Gem::Requirement.new('>= 2.5.1').satisfied_by?(test_unit_version) end # @private def self.description "adapter for Test::Unit gem >= v2.5.1" end # @private def self.included(mod) mod.setup :mocha_setup, :before => :prepend mod.exception_handler(:handle_mocha_expectation_error) mod.cleanup :after => :append do assertion_counter = Integration::AssertionCounter.new(self) mocha_verify(assertion_counter) end mod.teardown :mocha_teardown, :after => :append end private # @private def handle_mocha_expectation_error(e) return false unless e.is_a?(Mocha::ExpectationError) problem_occurred add_failure(e.message, e.backtrace) true end end end end end mocha-1.3.0/lib/mocha/integration/test_unit/gem_version_203_to_220.rb0000644000004100000410000000342613155337744025364 0ustar www-datawww-datarequire 'mocha/integration/assertion_counter' require 'mocha/integration/monkey_patcher' require 'mocha/expectation_error' module Mocha module Integration module TestUnit module GemVersion203To220 def self.applicable_to?(test_unit_version, ruby_version = nil) Gem::Requirement.new('>= 2.0.3', '<= 2.2.0').satisfied_by?(test_unit_version) end def self.description "monkey patch for Test::Unit gem >= v2.0.3 and <= v2.2.0" end def self.included(mod) MonkeyPatcher.apply(mod, RunMethodPatch) end module RunMethodPatch def run(result) assertion_counter = AssertionCounter.new(self) begin @_result = result yield(Test::Unit::TestCase::STARTED, name) begin begin run_setup run_test mocha_verify(assertion_counter) rescue Mocha::ExpectationError => e add_failure(e.message, e.backtrace) rescue Exception @interrupted = true raise unless handle_exception($!) ensure begin run_teardown rescue Mocha::ExpectationError => e add_failure(e.message, e.backtrace) rescue Exception raise unless handle_exception($!) end end ensure mocha_teardown end result.add_run yield(Test::Unit::TestCase::FINISHED, name) ensure # @_result = nil # For test-spec's after_all :< end end end end end end end mocha-1.3.0/lib/mocha/integration/test_unit.rb0000644000004100000410000000304513155337744021373 0ustar www-datawww-datarequire 'mocha/debug' require 'mocha/detection/test_unit' require 'mocha/integration/test_unit/nothing' require 'mocha/integration/test_unit/ruby_version_185_and_below' require 'mocha/integration/test_unit/ruby_version_186_and_above' require 'mocha/integration/test_unit/gem_version_200' require 'mocha/integration/test_unit/gem_version_201_to_202' require 'mocha/integration/test_unit/gem_version_203_to_220' require 'mocha/integration/test_unit/gem_version_230_to_250' require 'mocha/integration/test_unit/adapter' module Mocha module Integration module TestUnit def self.activate return false unless Detection::TestUnit.testcase test_unit_version = Gem::Version.new(Detection::TestUnit.version) ruby_version = Gem::Version.new(RUBY_VERSION.dup) Debug.puts "Detected Ruby version: #{ruby_version}" Debug.puts "Detected Test::Unit version: #{test_unit_version}" integration_module = [ TestUnit::Adapter, TestUnit::GemVersion230To250, TestUnit::GemVersion203To220, TestUnit::GemVersion201To202, TestUnit::GemVersion200, TestUnit::RubyVersion186AndAbove, TestUnit::RubyVersion185AndBelow, TestUnit::Nothing ].detect { |m| m.applicable_to?(test_unit_version, ruby_version) } unless ::Test::Unit::TestCase < integration_module Debug.puts "Applying #{integration_module.description}" ::Test::Unit::TestCase.send(:include, integration_module) end true end end end end mocha-1.3.0/lib/mocha/integration/monkey_patcher.rb0000644000004100000410000000137713155337744022373 0ustar www-datawww-datarequire 'mocha/api' module Mocha module Integration module MonkeyPatcher def self.apply(mod, run_method_patch) if mod < Mocha::API Debug.puts "Mocha::API already included in #{mod}" else mod.send(:include, Mocha::API) end if mod.method_defined?(:run_before_mocha) Debug.puts "#{mod}#run_before_mocha method already defined" else if mod.method_defined?(:run) mod.send(:alias_method, :run_before_mocha, :run) mod.send(:remove_method, :run) mod.send(:include, run_method_patch) else raise "Unable to monkey-patch #{mod}, because it does not define a `#run` method" end end end end end end mocha-1.3.0/lib/mocha/integration/mini_test/0000755000004100000410000000000013155337744021021 5ustar www-datawww-datamocha-1.3.0/lib/mocha/integration/mini_test/version_230_to_2101.rb0000644000004100000410000000422013155337744024562 0ustar www-datawww-datarequire 'mocha/integration/assertion_counter' require 'mocha/integration/monkey_patcher' require 'mocha/integration/mini_test/exception_translation' module Mocha module Integration module MiniTest module Version230To2101 def self.applicable_to?(mini_test_version) Gem::Requirement.new('>= 2.3.0', '<= 2.10.1').satisfied_by?(mini_test_version) end def self.description "monkey patch for MiniTest gem >= v2.3.0 <= v2.10.1" end def self.included(mod) MonkeyPatcher.apply(mod, RunMethodPatch) end module RunMethodPatch def run runner trap 'INFO' do time = runner.start_time ? Time.now - runner.start_time : 0 warn "%s#%s %.2fs" % [self.class, self.__name__, time] runner.status $stderr end if ::MiniTest::Unit::TestCase::SUPPORTS_INFO_SIGNAL assertion_counter = AssertionCounter.new(self) result = "" begin begin @passed = nil self.setup self.run_setup_hooks self.__send__ self.__name__ mocha_verify(assertion_counter) result = "." unless io? @passed = true rescue *::MiniTest::Unit::TestCase::PASSTHROUGH_EXCEPTIONS raise rescue Exception => e @passed = false result = runner.puke self.class, self.__name__, Mocha::Integration::MiniTest.translate(e) ensure begin self.run_teardown_hooks self.teardown rescue *::MiniTest::Unit::TestCase::PASSTHROUGH_EXCEPTIONS raise rescue Exception => e result = runner.puke self.class, self.__name__, Mocha::Integration::MiniTest.translate(e) end trap 'INFO', 'DEFAULT' if ::MiniTest::Unit::TestCase::SUPPORTS_INFO_SIGNAL end ensure mocha_teardown end result end end end end end end mocha-1.3.0/lib/mocha/integration/mini_test/exception_translation.rb0000644000004100000410000000062013155337744025760 0ustar www-datawww-datarequire 'mocha/expectation_error' module Mocha module Integration module MiniTest def self.translate(exception) return exception unless exception.kind_of?(::Mocha::ExpectationError) translated_exception = ::MiniTest::Assertion.new(exception.message) translated_exception.set_backtrace(exception.backtrace) translated_exception end end end end mocha-1.3.0/lib/mocha/integration/mini_test/version_13.rb0000644000004100000410000000271013155337744023336 0ustar www-datawww-datarequire 'mocha/integration/assertion_counter' require 'mocha/integration/monkey_patcher' require 'mocha/integration/mini_test/exception_translation' module Mocha module Integration module MiniTest module Version13 def self.applicable_to?(mini_test_version) Gem::Requirement.new('>= 1.3.0', '<= 1.3.1').satisfied_by?(mini_test_version) end def self.description "monkey patch for MiniTest gem v1.3" end def self.included(mod) MonkeyPatcher.apply(mod, RunMethodPatch) end module RunMethodPatch def run runner assertion_counter = AssertionCounter.new(self) result = '.' begin begin @passed = nil self.setup self.__send__ self.name mocha_verify(assertion_counter) @passed = true rescue Exception => e @passed = false result = runner.puke(self.class, self.name, Mocha::Integration::MiniTest.translate(e)) ensure begin self.teardown rescue Exception => e result = runner.puke(self.class, self.name, Mocha::Integration::MiniTest.translate(e)) end end ensure mocha_teardown end result end end end end end end mocha-1.3.0/lib/mocha/integration/mini_test/version_201_to_222.rb0000644000004100000410000000407613155337744024513 0ustar www-datawww-datarequire 'mocha/integration/assertion_counter' require 'mocha/integration/monkey_patcher' require 'mocha/integration/mini_test/exception_translation' module Mocha module Integration module MiniTest module Version201To222 def self.applicable_to?(mini_test_version) Gem::Requirement.new('>= 2.0.1', '<= 2.2.2').satisfied_by?(mini_test_version) end def self.description "monkey patch for MiniTest gem >= v2.0.1 <= v2.2.2" end def self.included(mod) MonkeyPatcher.apply(mod, RunMethodPatch) end module RunMethodPatch def run runner trap 'INFO' do time = runner.start_time ? Time.now - runner.start_time : 0 warn "%s#%s %.2fs" % [self.class, self.__name__, time] runner.status $stderr end if ::MiniTest::Unit::TestCase::SUPPORTS_INFO_SIGNAL assertion_counter = AssertionCounter.new(self) result = "" begin begin @passed = nil self.setup self.__send__ self.__name__ mocha_verify(assertion_counter) result = "." unless io? @passed = true rescue *::MiniTest::Unit::TestCase::PASSTHROUGH_EXCEPTIONS raise rescue Exception => e @passed = false result = runner.puke self.class, self.__name__, Mocha::Integration::MiniTest.translate(e) ensure begin self.teardown rescue *::MiniTest::Unit::TestCase::PASSTHROUGH_EXCEPTIONS raise rescue Exception => e result = runner.puke self.class, self.__name__, Mocha::Integration::MiniTest.translate(e) end trap 'INFO', 'DEFAULT' if ::MiniTest::Unit::TestCase::SUPPORTS_INFO_SIGNAL end ensure mocha_teardown end result end end end end end end mocha-1.3.0/lib/mocha/integration/mini_test/version_2110_to_2111.rb0000644000004100000410000000436713155337744024656 0ustar www-datawww-datarequire 'mocha/integration/assertion_counter' require 'mocha/integration/monkey_patcher' require 'mocha/integration/mini_test/exception_translation' module Mocha module Integration module MiniTest module Version2110To2111 def self.applicable_to?(mini_test_version) Gem::Requirement.new('>= 2.11.0', '<= 2.11.1').satisfied_by?(mini_test_version) end def self.description "monkey patch for MiniTest gem >= v2.11.0 <= v2.11.1" end def self.included(mod) MonkeyPatcher.apply(mod, RunMethodPatch) end module RunMethodPatch def run runner trap 'INFO' do time = runner.start_time ? Time.now - runner.start_time : 0 warn "%s#%s %.2fs" % [self.class, self.__name__, time] runner.status $stderr end if ::MiniTest::Unit::TestCase::SUPPORTS_INFO_SIGNAL assertion_counter = AssertionCounter.new(self) result = "" begin begin @passed = nil self.before_setup self.setup self.after_setup self.run_test self.__name__ mocha_verify(assertion_counter) result = "." unless io? @passed = true rescue *::MiniTest::Unit::TestCase::PASSTHROUGH_EXCEPTIONS raise rescue Exception => e @passed = false result = runner.puke self.class, self.__name__, Mocha::Integration::MiniTest.translate(e) ensure %w{ before_teardown teardown after_teardown }.each do |hook| begin self.send hook rescue *::MiniTest::Unit::TestCase::PASSTHROUGH_EXCEPTIONS raise rescue Exception => e result = runner.puke self.class, self.__name__, Mocha::Integration::MiniTest.translate(e) end end trap 'INFO', 'DEFAULT' if ::MiniTest::Unit::TestCase::SUPPORTS_INFO_SIGNAL end ensure mocha_teardown end result end end end end end end mocha-1.3.0/lib/mocha/integration/mini_test/version_2112_to_320.rb0000644000004100000410000000462113155337744024571 0ustar www-datawww-datarequire 'mocha/integration/assertion_counter' require 'mocha/integration/monkey_patcher' require 'mocha/integration/mini_test/exception_translation' module Mocha module Integration module MiniTest module Version2112To320 def self.applicable_to?(mini_test_version) Gem::Requirement.new('>= 2.11.2', '<= 3.2.0').satisfied_by?(mini_test_version) end def self.description "monkey patch for MiniTest gem >= v2.11.2 <= v3.2.0" end def self.included(mod) MonkeyPatcher.apply(mod, RunMethodPatch) end module RunMethodPatch def run runner trap "INFO" do runner.report.each_with_index do |msg, i| warn "\n%3d) %s" % [i + 1, msg] end warn '' time = runner.start_time ? Time.now - runner.start_time : 0 warn "Current Test: %s#%s %.2fs" % [self.class, self.__name__, time] runner.status $stderr end if ::MiniTest::Unit::TestCase::SUPPORTS_INFO_SIGNAL assertion_counter = AssertionCounter.new(self) result = "" begin begin @passed = nil self.before_setup self.setup self.after_setup self.run_test self.__name__ mocha_verify(assertion_counter) result = "." unless io? @passed = true rescue *::MiniTest::Unit::TestCase::PASSTHROUGH_EXCEPTIONS raise rescue Exception => e @passed = false result = runner.puke self.class, self.__name__, Mocha::Integration::MiniTest.translate(e) ensure %w{ before_teardown teardown after_teardown }.each do |hook| begin self.send hook rescue *::MiniTest::Unit::TestCase::PASSTHROUGH_EXCEPTIONS raise rescue Exception => e result = runner.puke self.class, self.__name__, Mocha::Integration::MiniTest.translate(e) end end trap 'INFO', 'DEFAULT' if ::MiniTest::Unit::TestCase::SUPPORTS_INFO_SIGNAL end ensure mocha_teardown end result end end end end end end mocha-1.3.0/lib/mocha/integration/mini_test/version_140.rb0000644000004100000410000000271013155337744023417 0ustar www-datawww-datarequire 'mocha/integration/assertion_counter' require 'mocha/integration/monkey_patcher' require 'mocha/integration/mini_test/exception_translation' module Mocha module Integration module MiniTest module Version140 def self.applicable_to?(mini_test_version) Gem::Requirement.new('1.4.0').satisfied_by?(mini_test_version) end def self.description "monkey patch for MiniTest gem v1.4.0" end def self.included(mod) MonkeyPatcher.apply(mod, RunMethodPatch) end module RunMethodPatch def run runner assertion_counter = AssertionCounter.new(self) result = '.' begin begin @passed = nil self.setup self.__send__ self.__name__ mocha_verify(assertion_counter) @passed = true rescue Exception => e @passed = false result = runner.puke(self.class, self.__name__, Mocha::Integration::MiniTest.translate(e)) ensure begin self.teardown rescue Exception => e result = runner.puke(self.class, self.__name__, Mocha::Integration::MiniTest.translate(e)) end end ensure mocha_teardown end result end end end end end end mocha-1.3.0/lib/mocha/integration/mini_test/nothing.rb0000644000004100000410000000061313155337744023014 0ustar www-datawww-datamodule Mocha module Integration module MiniTest module Nothing def self.applicable_to?(test_unit_version, ruby_version = nil) true end def self.description "nothing (no MiniTest integration available)" end def self.included(mod) raise "No MiniTest integration available" end end end end end mocha-1.3.0/lib/mocha/integration/mini_test/version_142_to_172.rb0000644000004100000410000000377513155337744024530 0ustar www-datawww-datarequire 'mocha/integration/assertion_counter' require 'mocha/integration/monkey_patcher' require 'mocha/integration/mini_test/exception_translation' module Mocha module Integration module MiniTest module Version142To172 def self.applicable_to?(mini_test_version) Gem::Requirement.new('>= 1.4.2', '<= 1.7.2').satisfied_by?(mini_test_version) end def self.description "monkey patch for MiniTest gem >= v1.4.2 and <= v1.7.2" end def self.included(mod) MonkeyPatcher.apply(mod, RunMethodPatch) end module RunMethodPatch def run runner trap 'INFO' do warn '%s#%s %.2fs' % [self.class, self.__name__, (Time.now - runner.start_time)] runner.status $stderr end if ::MiniTest::Unit::TestCase::SUPPORTS_INFO_SIGNAL assertion_counter = AssertionCounter.new(self) result = '.' begin begin @passed = nil self.setup self.__send__ self.__name__ mocha_verify(assertion_counter) @passed = true rescue *::MiniTest::Unit::TestCase::PASSTHROUGH_EXCEPTIONS raise rescue Exception => e @passed = false result = runner.puke(self.class, self.__name__, Mocha::Integration::MiniTest.translate(e)) ensure begin self.teardown rescue *::MiniTest::Unit::TestCase::PASSTHROUGH_EXCEPTIONS raise rescue Exception => e result = runner.puke(self.class, self.__name__, Mocha::Integration::MiniTest.translate(e)) end trap 'INFO', 'DEFAULT' if ::MiniTest::Unit::TestCase::SUPPORTS_INFO_SIGNAL end ensure mocha_teardown end result end end end end end end mocha-1.3.0/lib/mocha/integration/mini_test/adapter.rb0000644000004100000410000000232713155337744022772 0ustar www-datawww-datarequire 'mocha/api' require 'mocha/integration/assertion_counter' require 'mocha/expectation_error_factory' module Mocha module Integration module MiniTest # Integrates Mocha into recent versions of MiniTest. # # See the source code for an example of how to integrate Mocha into a test library. module Adapter include Mocha::API # @private def self.applicable_to?(mini_test_version) Gem::Requirement.new('>= 3.3.0').satisfied_by?(mini_test_version) end # @private def self.description "adapter for MiniTest gem >= v3.3.0" end # @private def self.included(mod) Mocha::ExpectationErrorFactory.exception_class = ::MiniTest::Assertion end # @private def before_setup mocha_setup super end # @private def before_teardown return unless passed? assertion_counter = Integration::AssertionCounter.new(self) mocha_verify(assertion_counter) ensure super end # @private def after_teardown super mocha_teardown end end end end end mocha-1.3.0/lib/mocha/integration/mini_test/version_200.rb0000644000004100000410000000400513155337744023413 0ustar www-datawww-datarequire 'mocha/integration/assertion_counter' require 'mocha/integration/monkey_patcher' require 'mocha/integration/mini_test/exception_translation' module Mocha module Integration module MiniTest module Version200 def self.applicable_to?(mini_test_version) Gem::Requirement.new('2.0.0').satisfied_by?(mini_test_version) end def self.description "monkey patch for MiniTest gem v2.0.0" end def self.included(mod) MonkeyPatcher.apply(mod, RunMethodPatch) end module RunMethodPatch def run runner trap 'INFO' do time = Time.now - runner.start_time warn "%s#%s %.2fs" % [self.class, self.__name__, time] runner.status $stderr end if ::MiniTest::Unit::TestCase::SUPPORTS_INFO_SIGNAL assertion_counter = AssertionCounter.new(self) result = "" begin begin @passed = nil self.setup self.__send__ self.__name__ mocha_verify(assertion_counter) result = "." unless io? @passed = true rescue *::MiniTest::Unit::TestCase::PASSTHROUGH_EXCEPTIONS raise rescue Exception => e @passed = false result = runner.puke self.class, self.__name__, Mocha::Integration::MiniTest.translate(e) ensure begin self.teardown rescue *::MiniTest::Unit::TestCase::PASSTHROUGH_EXCEPTIONS raise rescue Exception => e result = runner.puke self.class, self.__name__, Mocha::Integration::MiniTest.translate(e) end trap 'INFO', 'DEFAULT' if ::MiniTest::Unit::TestCase::SUPPORTS_INFO_SIGNAL end ensure mocha_teardown end result end end end end end end mocha-1.3.0/lib/mocha/integration/mini_test/version_141.rb0000644000004100000410000000356013155337744023424 0ustar www-datawww-datarequire 'mocha/integration/assertion_counter' require 'mocha/integration/monkey_patcher' require 'mocha/integration/mini_test/exception_translation' module Mocha module Integration module MiniTest module Version141 def self.applicable_to?(mini_test_version) Gem::Requirement.new('1.4.1').satisfied_by?(mini_test_version) end def self.description "monkey patch for MiniTest gem v1.4.1" end def self.included(mod) MonkeyPatcher.apply(mod, RunMethodPatch) end module RunMethodPatch def run runner trap 'INFO' do warn '%s#%s %.2fs' % [self.class, self.__name__, (Time.now - runner.start_time)] runner.status $stderr end assertion_counter = AssertionCounter.new(self) result = '.' begin begin @passed = nil self.setup self.__send__ self.__name__ mocha_verify(assertion_counter) @passed = true rescue *::MiniTest::Unit::TestCase::PASSTHROUGH_EXCEPTIONS raise rescue Exception => e @passed = false result = runner.puke(self.class, self.__name__, Mocha::Integration::MiniTest.translate(e)) ensure begin self.teardown rescue *::MiniTest::Unit::TestCase::PASSTHROUGH_EXCEPTIONS raise rescue Exception => e result = runner.puke(self.class, self.__name__, Mocha::Integration::MiniTest.translate(e)) end trap 'INFO', 'DEFAULT' end ensure mocha_teardown end result end end end end end end mocha-1.3.0/lib/mocha/integration/mini_test.rb0000644000004100000410000000315713155337744021354 0ustar www-datawww-datarequire 'mocha/debug' require 'mocha/detection/mini_test' require 'mocha/integration/mini_test/nothing' require 'mocha/integration/mini_test/version_13' require 'mocha/integration/mini_test/version_140' require 'mocha/integration/mini_test/version_141' require 'mocha/integration/mini_test/version_142_to_172' require 'mocha/integration/mini_test/version_200' require 'mocha/integration/mini_test/version_201_to_222' require 'mocha/integration/mini_test/version_230_to_2101' require 'mocha/integration/mini_test/version_2110_to_2111' require 'mocha/integration/mini_test/version_2112_to_320' require 'mocha/integration/mini_test/adapter' module Mocha module Integration module MiniTest def self.activate return false unless Detection::MiniTest.testcase mini_test_version = Gem::Version.new(Detection::MiniTest.version) Debug.puts "Detected MiniTest version: #{mini_test_version}" integration_module = [ MiniTest::Adapter, MiniTest::Version2112To320, MiniTest::Version2110To2111, MiniTest::Version230To2101, MiniTest::Version201To222, MiniTest::Version200, MiniTest::Version142To172, MiniTest::Version141, MiniTest::Version140, MiniTest::Version13, MiniTest::Nothing ].detect { |m| m.applicable_to?(mini_test_version) } target = Detection::MiniTest.testcase unless target < integration_module Debug.puts "Applying #{integration_module.description}" target.send(:include, integration_module) end true end end end end mocha-1.3.0/lib/mocha/pretty_parameters.rb0000644000004100000410000000100313155337744020574 0ustar www-datawww-datarequire 'mocha/inspect' module Mocha class PrettyParameters def initialize(params) @params = params @params_string = params.mocha_inspect end def pretty remove_outer_array_braces! remove_outer_hash_braces! @params_string end def remove_outer_array_braces! @params_string = @params_string.gsub(/^\[|\]$/, '') end def remove_outer_hash_braces! @params_string = @params_string.gsub(/^\{|\}$/, '') if @params.length == 1 end end end mocha-1.3.0/lib/mocha/argument_iterator.rb0000644000004100000410000000053313155337744020564 0ustar www-datawww-datamodule Mocha class ArgumentIterator def initialize(argument) @argument = argument end def each(&block) if @argument.is_a?(Hash) then @argument.each do |method_name, return_value| block.call(method_name, return_value) end else block.call(@argument) end end end end mocha-1.3.0/lib/mocha/expectation_list.rb0000644000004100000410000000243513155337744020412 0ustar www-datawww-datamodule Mocha class ExpectationList def initialize(expectations = []) @expectations = expectations end def add(expectation) @expectations.unshift(expectation) expectation end def remove_all_matching_method(method_name) @expectations.reject! { |expectation| expectation.matches_method?(method_name) } end def matches_method?(method_name) @expectations.any? { |expectation| expectation.matches_method?(method_name) } end def match(method_name, *arguments) matching_expectations(method_name, *arguments).first end def match_allowing_invocation(method_name, *arguments) matching_expectations(method_name, *arguments).detect { |e| e.invocations_allowed? } end def verified?(assertion_counter = nil) @expectations.all? { |expectation| expectation.verified?(assertion_counter) } end def to_a @expectations end def to_set @expectations.to_set end def length @expectations.length end def any? @expectations.any? end def +(other) self.class.new(self.to_a + other.to_a) end private def matching_expectations(method_name, *arguments) @expectations.select { |e| e.match?(method_name, *arguments) } end end end mocha-1.3.0/lib/mocha/return_values.rb0000644000004100000410000000077313155337744017735 0ustar www-datawww-datarequire 'mocha/single_return_value' module Mocha class ReturnValues def self.build(*values) new(*values.map { |value| SingleReturnValue.new(value) }) end attr_accessor :values def initialize(*values) @values = values end def next case @values.length when 0 then nil when 1 then @values.first.evaluate else @values.shift.evaluate end end def +(other) self.class.new(*(@values + other.values)) end end end mocha-1.3.0/lib/mocha/receivers.rb0000644000004100000410000000126113155337744017017 0ustar www-datawww-datamodule Mocha class ObjectReceiver def initialize(object) @object = object end def mocks object, mocks = @object, [] while object do mocks << object.mocha object = object.is_a?(Class) ? object.superclass : nil end mocks end end class AnyInstanceReceiver def initialize(klass) @klass = klass end def mocks klass, mocks = @klass, [] while klass do mocks << klass.any_instance.mocha klass = klass.superclass end mocks end end class DefaultReceiver def initialize(mock) @mock = mock end def mocks [@mock] end end end mocha-1.3.0/lib/mocha/parameter_matchers/0000755000004100000410000000000013155337744020351 5ustar www-datawww-datamocha-1.3.0/lib/mocha/parameter_matchers/instance_of.rb0000644000004100000410000000244713155337744023175 0ustar www-datawww-datarequire 'mocha/parameter_matchers/base' module Mocha module ParameterMatchers # Matches any object that is an instance of +klass+ # # @param [Class] klass expected class. # @return [InstanceOf] parameter matcher. # # @see Expectation#with # @see Kernel#instance_of? # # @example Actual parameter is an instance of +String+. # object = mock() # object.expects(:method_1).with(instance_of(String)) # object.method_1('string') # # no error raised # # @example Actual parameter is not an instance of +String+. # object = mock() # object.expects(:method_1).with(instance_of(String)) # object.method_1(99) # # error raised, because method_1 was not called with an instance of String def instance_of(klass) InstanceOf.new(klass) end # Parameter matcher which matches when actual parameter is an instance of the specified class. class InstanceOf < Base # @private def initialize(klass) @klass = klass end # @private def matches?(available_parameters) parameter = available_parameters.shift parameter.instance_of?(@klass) end # @private def mocha_inspect "instance_of(#{@klass.mocha_inspect})" end end end end mocha-1.3.0/lib/mocha/parameter_matchers/kind_of.rb0000644000004100000410000000235613155337744022315 0ustar www-datawww-datarequire 'mocha/parameter_matchers/base' module Mocha module ParameterMatchers # Matches any +Object+ that is a kind of +klass+. # # @param [Class] klass expected class. # @return [KindOf] parameter matcher. # # @see Expectation#with # @see Kernel#kind_of? # # @example Actual parameter is a kind of +Integer+. # object = mock() # object.expects(:method_1).with(kind_of(Integer)) # object.method_1(99) # # no error raised # # @example Actual parameter is not a kind of +Integer+. # object = mock() # object.expects(:method_1).with(kind_of(Integer)) # object.method_1('string') # # error raised, because method_1 was not called with a kind of Integer def kind_of(klass) KindOf.new(klass) end # Parameter matcher which matches when actual parameter is a kind of specified class. class KindOf < Base # @private def initialize(klass) @klass = klass end # @private def matches?(available_parameters) parameter = available_parameters.shift parameter.kind_of?(@klass) end # @private def mocha_inspect "kind_of(#{@klass.mocha_inspect})" end end end end mocha-1.3.0/lib/mocha/parameter_matchers/includes.rb0000644000004100000410000000676113155337744022516 0ustar www-datawww-datarequire 'mocha/parameter_matchers/all_of' require 'mocha/parameter_matchers/base' module Mocha module ParameterMatchers # Matches any object that responds with +true+ to +include?(item)+ # for all items. # # @param [*Array] items expected items. # @return [Includes] parameter matcher. # # @see Expectation#with # # @example Actual parameter includes all items. # object = mock() # object.expects(:method_1).with(includes('foo', 'bar')) # object.method_1(['foo', 'bar', 'baz']) # # no error raised # # @example Actual parameter does not include all items. # object.method_1(['foo', 'baz']) # # error raised, because ['foo', 'baz'] does not include 'bar'. # # @example Actual parameter includes item which matches nested matcher. # object = mock() # object.expects(:method_1).with(includes(has_key(:key))) # object.method_1(['foo', 'bar', {:key => 'baz'}]) # # no error raised # # @example Actual parameter does not include item matching nested matcher. # object.method_1(['foo', 'bar', {:other_key => 'baz'}]) # # error raised, because no element matches `has_key(:key)` matcher # # @example Actual parameter is a String including substring. # object = mock() # object.expects(:method_1).with(includes('bar')) # object.method_1('foobarbaz') # # no error raised # # @example Actual parameter is a String not including substring. # object.method_1('foobaz') # # error raised, because 'foobaz' does not include 'bar' # # @example Actual parameter is a Hash including the given key. # object = mock() # object.expects(:method_1).with(includes(:bar)) # object.method_1({:foo => 1, :bar => 2}) # # no error raised # # @example Actual parameter is a Hash without the given key. # object.method_1({:foo => 1, :baz => 2}) # # error raised, because hash does not include key 'bar' # # @example Actual parameter is a Hash with a key matching the given matcher. # object = mock() # object.expects(:method_1).with(includes(regexp_matches(/ar/))) # object.method_1({'foo' => 1, 'bar' => 2}) # # no error raised # # @example Actual parameter is a Hash no key matching the given matcher. # object.method_1({'foo' => 1, 'baz' => 3}) # # error raised, because hash does not include a key matching /ar/ def includes(*items) Includes.new(*items) end # Parameter matcher which matches when actual parameter includes expected values. class Includes < Base # @private def initialize(*items) @items = items end # @private def matches?(available_parameters) parameter = available_parameters.shift return false unless parameter.respond_to?(:include?) if @items.size == 1 if parameter.respond_to?(:any?) && !parameter.is_a?(String) parameter = parameter.keys if parameter.is_a?(Hash) return parameter.any? { |p| @items.first.to_matcher.matches?([p]) } else return parameter.include?(@items.first) end else includes_matchers = @items.map { |item| Includes.new(item) } AllOf.new(*includes_matchers).matches?([parameter]) end end # @private def mocha_inspect item_descriptions = @items.map(&:mocha_inspect) "includes(#{item_descriptions.join(', ')})" end end end end mocha-1.3.0/lib/mocha/parameter_matchers/is_a.rb0000644000004100000410000000225113155337744021611 0ustar www-datawww-datarequire 'mocha/parameter_matchers/base' module Mocha module ParameterMatchers # Matches any object that is a +klass+. # # @param [Class] klass expected class. # @return [IsA] parameter matcher. # # @see Expectation#with # @see Kernel#is_a? # # @example Actual parameter is a +Integer+. # object = mock() # object.expects(:method_1).with(is_a(Integer)) # object.method_1(99) # # no error raised # # @example Actual parameter is not a +Integer+. # object = mock() # object.expects(:method_1).with(is_a(Integer)) # object.method_1('string') # # error raised, because method_1 was not called with an Integer def is_a(klass) IsA.new(klass) end # Parameter matcher which matches when actual parameter is a specific class. class IsA < Base # @private def initialize(klass) @klass = klass end # @private def matches?(available_parameters) parameter = available_parameters.shift parameter.is_a?(@klass) end # @private def mocha_inspect "is_a(#{@klass.mocha_inspect})" end end end end mocha-1.3.0/lib/mocha/parameter_matchers/has_entries.rb0000644000004100000410000000313613155337744023205 0ustar www-datawww-datarequire 'mocha/parameter_matchers/base' require 'mocha/parameter_matchers/all_of' require 'mocha/parameter_matchers/has_entry' module Mocha module ParameterMatchers # Matches +Hash+ containing all +entries+. # # @param [Hash] entries expected +Hash+ entries. # @return [HasEntries] parameter matcher. # # @see Expectation#with # # @example Actual parameter contains all expected entries. # object = mock() # object.expects(:method_1).with(has_entries('key_1' => 1, 'key_2' => 2)) # object.method_1('key_1' => 1, 'key_2' => 2, 'key_3' => 3) # # no error raised # # @example Actual parameter does not contain all expected entries. # object = mock() # object.expects(:method_1).with(has_entries('key_1' => 1, 'key_2' => 2)) # object.method_1('key_1' => 1, 'key_2' => 99) # # error raised, because method_1 was not called with Hash containing entries: 'key_1' => 1, 'key_2' => 2 def has_entries(entries) HasEntries.new(entries) end # Parameter matcher which matches when actual parameter contains all expected +Hash+ entries. class HasEntries < Base # @private def initialize(entries) @entries = entries end # @private def matches?(available_parameters) parameter = available_parameters.shift has_entry_matchers = @entries.map { |key, value| HasEntry.new(key, value) } AllOf.new(*has_entry_matchers).matches?([parameter]) end # @private def mocha_inspect "has_entries(#{@entries.mocha_inspect})" end end end end mocha-1.3.0/lib/mocha/parameter_matchers/anything.rb0000644000004100000410000000141213155337744022515 0ustar www-datawww-datarequire 'mocha/parameter_matchers/base' module Mocha module ParameterMatchers # Matches any object. # # @return [Anything] parameter matcher. # # @see Expectation#with # # @example Any object will match. # object = mock() # object.expects(:method_1).with(anything) # object.method_1('foo') # object.method_1(789) # object.method_1(:bar) # # no error raised def anything Anything.new end # Parameter matcher which always matches a single parameter. class Anything < Base # @private def matches?(available_parameters) available_parameters.shift return true end # @private def mocha_inspect "anything" end end end end mocha-1.3.0/lib/mocha/parameter_matchers/equals.rb0000644000004100000410000000230013155337744022163 0ustar www-datawww-datarequire 'mocha/parameter_matchers/base' module Mocha module ParameterMatchers # Matches any +Object+ equalling +value+. # # @param [Object] value expected value. # @return [Equals] parameter matcher. # # @see Expectation#with # @see Object#== # # @example Actual parameter equals expected parameter. # object = mock() # object.expects(:method_1).with(equals(2)) # object.method_1(2) # # no error raised # # @example Actual parameter does not equal expected parameter. # object = mock() # object.expects(:method_1).with(equals(2)) # object.method_1(3) # # error raised, because method_1 was not called with an +Object+ that equals 2 def equals(value) Equals.new(value) end # Parameter matcher which matches when actual parameter equals expected value. class Equals < Base # @private def initialize(value) @value = value end # @private def matches?(available_parameters) parameter = available_parameters.shift parameter == @value end # @private def mocha_inspect @value.mocha_inspect end end end end mocha-1.3.0/lib/mocha/parameter_matchers/regexp_matches.rb0000644000004100000410000000262513155337744023701 0ustar www-datawww-datarequire 'mocha/parameter_matchers/base' module Mocha module ParameterMatchers # Matches any object that matches +regexp+. # # @param [Regexp] regexp regular expression to match. # @return [RegexpMatches] parameter matcher. # # @see Expectation#with # # @example Actual parameter is matched by specified regular expression. # object = mock() # object.expects(:method_1).with(regexp_matches(/e/)) # object.method_1('hello') # # no error raised # # @example Actual parameter is not matched by specified regular expression. # object = mock() # object.expects(:method_1).with(regexp_matches(/a/)) # object.method_1('hello') # # error raised, because method_1 was not called with a parameter that matched the # # regular expression def regexp_matches(regexp) RegexpMatches.new(regexp) end # Parameter matcher which matches if specified regular expression matches actual paramter. class RegexpMatches < Base # @private def initialize(regexp) @regexp = regexp end # @private def matches?(available_parameters) parameter = available_parameters.shift return false unless parameter.respond_to?(:=~) parameter =~ @regexp end # @private def mocha_inspect "regexp_matches(#{@regexp.mocha_inspect})" end end end end mocha-1.3.0/lib/mocha/parameter_matchers/has_entry.rb0000644000004100000410000000624613155337744022702 0ustar www-datawww-datarequire 'mocha/parameter_matchers/base' module Mocha module ParameterMatchers # Matches +Hash+ containing entry with +key+ and +value+. # # @overload def has_entry(key, value) # @param [Object] key key for entry. # @param [Object] value value for entry. # @overload def has_entry(single_entry_hash) # @param [Hash] single_entry_hash +Hash+ with single entry. # @raise [ArgumentError] if +single_entry_hash+ does not contain exactly one entry. # # @return [HasEntry] parameter matcher. # # @see Expectation#with # # @example Actual parameter contains expected entry supplied as key and value. # object = mock() # object.expects(:method_1).with(has_entry('key_1', 1)) # object.method_1('key_1' => 1, 'key_2' => 2) # # no error raised # # @example Actual parameter contains expected entry supplied as +Hash+ entry. # object = mock() # object.expects(:method_1).with(has_entry('key_1' => 1)) # object.method_1('key_1' => 1, 'key_2' => 2) # # no error raised # # @example Actual parameter does not contain expected entry supplied as key and value. # object = mock() # object.expects(:method_1).with(has_entry('key_1', 1)) # object.method_1('key_1' => 2, 'key_2' => 1) # # error raised, because method_1 was not called with Hash containing entry: 'key_1' => 1 # # @example Actual parameter does not contain expected entry supplied as +Hash+ entry. # # object = mock() # object.expects(:method_1).with(has_entry('key_1' => 1)) # object.method_1('key_1' => 2, 'key_2' => 1) # # error raised, because method_1 was not called with Hash containing entry: 'key_1' => 1 def has_entry(*options) case options.length when 1 case options[0] when Hash case options[0].length when 0 raise ArgumentError.new("Argument has no entries.") when 1 key, value = options[0].first else raise ArgumentError.new("Argument has multiple entries. Use Mocha::ParameterMatchers#has_entries instead.") end else raise ArgumentError.new("Argument is not a Hash.") end when 2 key, value = options else raise ArgumentError.new("Too many arguments; use either a single argument (must be a Hash) or two arguments (a key and a value).") end HasEntry.new(key, value) end # Parameter matcher which matches when actual parameter contains expected +Hash+ entry. class HasEntry < Base # @private def initialize(key, value) @key, @value = key, value end # @private def matches?(available_parameters) parameter = available_parameters.shift return false unless parameter.respond_to?(:keys) && parameter.respond_to?(:[]) matching_keys = parameter.keys.select { |key| @key.to_matcher.matches?([key]) } matching_keys.any? { |key| @value.to_matcher.matches?([parameter[key]]) } end # @private def mocha_inspect "has_entry(#{@key.mocha_inspect} => #{@value.mocha_inspect})" end end end end mocha-1.3.0/lib/mocha/parameter_matchers/any_of.rb0000644000004100000410000000270613155337744022156 0ustar www-datawww-datarequire 'mocha/parameter_matchers/base' module Mocha module ParameterMatchers # Matches if any +matchers+ match. # # @param [*Array] parameter_matchers parameter matchers. # @return [AnyOf] parameter matcher. # # @see Expectation#with # # @example One parameter matcher matches. # object = mock() # object.expects(:method_1).with(any_of(1, 3)) # object.method_1(1) # # no error raised # # @example The other parameter matcher matches. # object = mock() # object.expects(:method_1).with(any_of(1, 3)) # object.method_1(3) # # no error raised # # @example Neither parameter matcher matches. # object = mock() # object.expects(:method_1).with(any_of(1, 3)) # object.method_1(2) # # error raised, because method_1 was not called with 1 or 3 def any_of(*matchers) AnyOf.new(*matchers) end # Parameter matcher which combines a number of other matchers using a logical OR. class AnyOf < Base # @private def initialize(*matchers) @matchers = matchers end # @private def matches?(available_parameters) parameter = available_parameters.shift @matchers.any? { |matcher| matcher.to_matcher.matches?([parameter]) } end # @private def mocha_inspect "any_of(#{@matchers.map { |matcher| matcher.mocha_inspect }.join(", ") })" end end end end mocha-1.3.0/lib/mocha/parameter_matchers/equivalent_uri.rb0000644000004100000410000000357613155337744023745 0ustar www-datawww-datarequire 'mocha/deprecation' require 'mocha/parameter_matchers/base' require 'uri' require 'cgi' module Mocha module ParameterMatchers # Matches a URI without regard to the ordering of parameters in the query string. # # @param [String] uri URI to match. # @return [EquivalentUri] parameter matcher. # # @see Expectation#with # # @example Actual URI is equivalent. # object = mock() # object.expects(:method_1).with(equivalent_uri('http://example.com/foo?a=1&b=2)) # object.method_1('http://example.com/foo?b=2&a=1') # # no error raised # # @example Actual URI is not equivalent. # object = mock() # object.expects(:method_1).with(equivalent_uri('http://example.com/foo?a=1&b=2)) # object.method_1('http://example.com/foo?a=1&b=3') # # error raised, because the query parameters were different def equivalent_uri(uri) EquivalentUri.new(uri) end # @deprecated Use {#equivalent_uri} instead. def has_equivalent_query_string(uri) Mocha::Deprecation.warning("`has_equivalent_query_string` is deprecated. Please use `equivalent_uri` instead.") equivalent_uri(uri) end # Parameter matcher which matches URIs with equivalent query strings. class EquivalentUri < Base # @private def initialize(uri) @uri = URI.parse(uri) end # @private def matches?(available_parameters) actual = explode(URI.parse(available_parameters.shift)) expected = explode(@uri) actual == expected end # @private def mocha_inspect "equivalent_uri(#{@uri.mocha_inspect})" end private # @private def explode(uri) query_hash = CGI.parse(uri.query || '') URI::Generic::COMPONENT.inject({}){ |h, k| h.merge(k => uri.__send__(k)) }.merge(:query => query_hash) end end end end mocha-1.3.0/lib/mocha/parameter_matchers/responds_with.rb0000644000004100000410000000315013155337744023565 0ustar www-datawww-datarequire 'mocha/parameter_matchers/base' require 'yaml' module Mocha module ParameterMatchers # Matches any object that responds to +message+ with +result+. To put it another way, it tests the quack, not the duck. # # @param [Symbol] message method to invoke. # @param [Object] result expected result of sending +message+. # @return [RespondsWith] parameter matcher. # # @see Expectation#with # # @example Actual parameter responds with "FOO" when :upcase is invoked. # object = mock() # object.expects(:method_1).with(responds_with(:upcase, "FOO")) # object.method_1("foo") # # no error raised, because "foo".upcase == "FOO" # # @example Actual parameter does not respond with "FOO" when :upcase is invoked. # object = mock() # object.expects(:method_1).with(responds_with(:upcase, "BAR")) # object.method_1("foo") # # error raised, because "foo".upcase != "BAR" def responds_with(message, result) RespondsWith.new(message, result) end # Parameter matcher which matches if actual parameter returns expected result when specified method is invoked. class RespondsWith < Base # @private def initialize(message, result) @message, @result = message, result end # @private def matches?(available_parameters) parameter = available_parameters.shift @result.to_matcher.matches?( [parameter.__send__(@message)] ) end # @private def mocha_inspect "responds_with(#{@message.mocha_inspect}, #{@result.mocha_inspect})" end end end end mocha-1.3.0/lib/mocha/parameter_matchers/has_key.rb0000644000004100000410000000253313155337744022324 0ustar www-datawww-datarequire 'mocha/parameter_matchers/base' module Mocha module ParameterMatchers # Matches +Hash+ containing +key+. # # @param [Object] key expected key. # @return [HasKey] parameter matcher. # # @see Expectation#with # # @example Actual parameter contains entry with expected key. # object = mock() # object.expects(:method_1).with(has_key('key_1')) # object.method_1('key_1' => 1, 'key_2' => 2) # # no error raised # # @example Actual parameter does not contain entry with expected key. # object = mock() # object.expects(:method_1).with(has_key('key_1')) # object.method_1('key_2' => 2) # # error raised, because method_1 was not called with Hash containing key: 'key_1' def has_key(key) HasKey.new(key) end # Parameter matcher which matches when actual parameter contains +Hash+ entry with expected key. class HasKey < Base # @private def initialize(key) @key = key end # @private def matches?(available_parameters) parameter = available_parameters.shift return false unless parameter.respond_to?(:keys) parameter.keys.any? { |key| @key.to_matcher.matches?([key]) } end # @private def mocha_inspect "has_key(#{@key.mocha_inspect})" end end end end mocha-1.3.0/lib/mocha/parameter_matchers/object.rb0000644000004100000410000000036213155337744022145 0ustar www-datawww-datarequire 'mocha/parameter_matchers/equals' module Mocha module ObjectMethods # @private def to_matcher Mocha::ParameterMatchers::Equals.new(self) end end end # @private class Object include Mocha::ObjectMethods end mocha-1.3.0/lib/mocha/parameter_matchers/yaml_equivalent.rb0000644000004100000410000000263413155337744024102 0ustar www-datawww-datarequire 'mocha/parameter_matchers/base' require 'yaml' module Mocha module ParameterMatchers # Matches any YAML that represents the specified +object+ # # @param [Object] object object whose YAML to compare. # @return [YamlEquivalent] parameter matcher. # # @see Expectation#with # # @example Actual parameter is YAML equivalent of specified +object+. # object = mock() # object.expects(:method_1).with(yaml_equivalent(1, 2, 3)) # object.method_1("--- \n- 1\n- 2\n- 3\n") # # no error raised # # @example Actual parameter is not YAML equivalent of specified +object+. # object = mock() # object.expects(:method_1).with(yaml_equivalent(1, 2, 3)) # object.method_1("--- \n- 1\n- 2\n") # # error raised, because method_1 was not called with YAML representing the specified Array def yaml_equivalent(object) YamlEquivalent.new(object) end # Parameter matcher which matches if actual parameter is YAML equivalent of specified object. class YamlEquivalent < Base # @private def initialize(object) @object = object end # @private def matches?(available_parameters) parameter = available_parameters.shift @object == YAML.load(parameter) end # @private def mocha_inspect "yaml_equivalent(#{@object.mocha_inspect})" end end end end mocha-1.3.0/lib/mocha/parameter_matchers/has_value.rb0000644000004100000410000000257313155337744022654 0ustar www-datawww-datarequire 'mocha/parameter_matchers/base' module Mocha module ParameterMatchers # Matches +Hash+ containing +value+. # # @param [Object] value expected value. # @return [HasValue] parameter matcher. # # @see Expectation#with # # @example Actual parameter contains entry with expected value. # object = mock() # object.expects(:method_1).with(has_value(1)) # object.method_1('key_1' => 1, 'key_2' => 2) # # no error raised # # @example Actual parameter does not contain entry with expected value. # object = mock() # object.expects(:method_1).with(has_value(1)) # object.method_1('key_2' => 2) # # error raised, because method_1 was not called with Hash containing value: 1 def has_value(value) HasValue.new(value) end # Parameter matcher which matches when actual parameter contains +Hash+ entry with expected value. class HasValue < Base # @private def initialize(value) @value = value end # @private def matches?(available_parameters) parameter = available_parameters.shift return false unless parameter.respond_to?(:values) parameter.values.any? { |value| @value.to_matcher.matches?([value]) } end # @private def mocha_inspect "has_value(#{@value.mocha_inspect})" end end end end mocha-1.3.0/lib/mocha/parameter_matchers/optionally.rb0000644000004100000410000000413613155337744023074 0ustar www-datawww-datamodule Mocha module ParameterMatchers # Matches optional parameters if available. # # @param [*Array] matchers matchers for optional parameters. # @return [Optionally] parameter matcher. # # @see Expectation#with # # @example Only the two required parameters are supplied and they both match their expected value. # object = mock() # object.expects(:method_1).with(1, 2, optionally(3, 4)) # object.method_1(1, 2) # # no error raised # # @example Both required parameters and one of the optional parameters are supplied and they all match their expected value. # object = mock() # object.expects(:method_1).with(1, 2, optionally(3, 4)) # object.method_1(1, 2, 3) # # no error raised # # @example Both required parameters and both of the optional parameters are supplied and they all match their expected value. # object = mock() # object.expects(:method_1).with(1, 2, optionally(3, 4)) # object.method_1(1, 2, 3, 4) # # no error raised # # @example One of the actual optional parameters does not match the expected value. # object = mock() # object.expects(:method_1).with(1, 2, optionally(3, 4)) # object.method_1(1, 2, 3, 5) # # error raised, because optional parameters did not match def optionally(*matchers) Optionally.new(*matchers) end # Parameter matcher which allows optional parameters to be specified. class Optionally < Base # @private def initialize(*parameters) @matchers = parameters.map { |parameter| parameter.to_matcher } end # @private def matches?(available_parameters) index = 0 while (available_parameters.length > 0) && (index < @matchers.length) do matcher = @matchers[index] return false unless matcher.matches?(available_parameters) index += 1 end return true end # @private def mocha_inspect "optionally(#{@matchers.map { |matcher| matcher.mocha_inspect }.join(", ") })" end end end end mocha-1.3.0/lib/mocha/parameter_matchers/any_parameters.rb0000644000004100000410000000202513155337744023707 0ustar www-datawww-datarequire 'mocha/parameter_matchers/base' module Mocha module ParameterMatchers # Matches any parameters. This is used as the default for a newly built expectation. # # @return [AnyParameters] parameter matcher. # # @see Expectation#with # # @example Any parameters will match. # object = mock() # object.expects(:method_1).with(any_parameters) # object.method_1(1, 2, 3, 4) # # no error raised # # object = mock() # object.expects(:method_1).with(any_parameters) # object.method_1(5, 6, 7, 8, 9, 0) # # no error raised def any_parameters AnyParameters.new end # Parameter matcher which always matches whatever the parameters. class AnyParameters < Base # @private def matches?(available_parameters) while available_parameters.length > 0 do available_parameters.shift end return true end # @private def mocha_inspect "any_parameters" end end end end mocha-1.3.0/lib/mocha/parameter_matchers/base.rb0000644000004100000410000000457313155337744021621 0ustar www-datawww-datamodule Mocha module ParameterMatchers # @abstract Subclass and implement +#matches?+ and +#mocha_inspect+ to define a custom matcher. Also add a suitably named instance method to {ParameterMatchers} to build an instance of the new matcher c.f. {#equals}. class Base # @private def to_matcher self end # A shorthand way of combining two matchers when both must match. # # Returns a new {AllOf} parameter matcher combining two matchers using a logical AND. # # This shorthand will not work with an implicit equals match. Instead, an explicit {Equals} matcher should be used. # # @param [Base] matcher parameter matcher. # @return [AllOf] parameter matcher. # # @see Expectation#with # # @example Alternative ways to combine matchers with a logical AND. # object = mock() # object.expects(:run).with(all_of(has_key(:foo), has_key(:bar))) # object.run(:foo => 'foovalue', :bar => 'barvalue') # # # is exactly equivalent to # # object.expects(:run).with(has_key(:foo) & has_key(:bar)) # object.run(:foo => 'foovalue', :bar => 'barvalue) def &(matcher) AllOf.new(self, matcher) end # A shorthand way of combining two matchers when at least one must match. # # Returns a new +AnyOf+ parameter matcher combining two matchers using a logical OR. # # This shorthand will not work with an implicit equals match. Instead, an explicit {Equals} matcher should be used. # # @param [Base] matcher parameter matcher. # @return [AnyOf] parameter matcher. # # @see Expectation#with # # @example Alternative ways to combine matchers with a logical OR. # object = mock() # object.expects(:run).with(any_of(has_key(:foo), has_key(:bar))) # object.run(:foo => 'foovalue') # # # is exactly equivalent to # # object.expects(:run).with(has_key(:foo) | has_key(:bar)) # object.run(:foo => 'foovalue') # # @example Using an explicit {Equals} matcher in combination with {#|}. # object.expects(:run).with(equals(1) | equals(2)) # object.run(1) # passes # object.run(2) # passes # object.run(3) # fails def |(matcher) AnyOf.new(self, matcher) end end end end mocha-1.3.0/lib/mocha/parameter_matchers/all_of.rb0000644000004100000410000000253113155337744022133 0ustar www-datawww-datarequire 'mocha/parameter_matchers/base' module Mocha module ParameterMatchers # Matches if all +matchers+ match. # # @param [*Array] parameter_matchers parameter matchers. # @return [AllOf] parameter matcher. # # @see Expectation#with # # @example All parameter matchers match. # object = mock() # object.expects(:method_1).with(all_of(includes(1), includes(3))) # object.method_1([1, 3]) # # no error raised # # @example One of the parameter matchers does not match. # object = mock() # object.expects(:method_1).with(all_of(includes(1), includes(3))) # object.method_1([1, 2]) # # error raised, because method_1 was not called with object including 1 and 3 def all_of(*matchers) AllOf.new(*matchers) end # Parameter matcher which combines a number of other matchers using a logical AND. class AllOf < Base # @private def initialize(*matchers) @matchers = matchers end # @private def matches?(available_parameters) parameter = available_parameters.shift @matchers.all? { |matcher| matcher.to_matcher.matches?([parameter]) } end # @private def mocha_inspect "all_of(#{@matchers.map { |matcher| matcher.mocha_inspect }.join(", ") })" end end end end mocha-1.3.0/lib/mocha/parameter_matchers/not.rb0000644000004100000410000000240013155337744021472 0ustar www-datawww-datarequire 'mocha/parameter_matchers/base' module Mocha module ParameterMatchers # Matches if +matcher+ does *not* match. # # @param [Base] matcher matcher whose logic to invert. # @return [Not] parameter matcher. # # @see Expectation#with # # @example Actual parameter does not include the value +1+. # object = mock() # object.expects(:method_1).with(Not(includes(1))) # object.method_1([0, 2, 3]) # # no error raised # # @example Actual parameter does include the value +1+. # object = mock() # object.expects(:method_1).with(Not(includes(1))) # object.method_1([0, 1, 2, 3]) # # error raised, because method_1 was not called with object not including 1 def Not(matcher) Not.new(matcher) end # Parameter matcher which inverts the logic of the specified matcher using a logical NOT operation. class Not < Base # @private def initialize(matcher) @matcher = matcher end # @private def matches?(available_parameters) parameter = available_parameters.shift !@matcher.matches?([parameter]) end # @private def mocha_inspect "Not(#{@matcher.mocha_inspect})" end end end end mocha-1.3.0/lib/mocha/setup.rb0000644000004100000410000000016113155337744016166 0ustar www-datawww-datarequire 'mocha/integration' module Mocha def self.activate Integration.activate end end Mocha.activate mocha-1.3.0/lib/mocha/sequence.rb0000644000004100000410000000201613155337744016637 0ustar www-datawww-datamodule Mocha # Used to constrain the order in which expectations can occur. # # @see API#sequence # @see Expectation#in_sequence class Sequence # @private class InSequenceOrderingConstraint def initialize(sequence, index) @sequence, @index = sequence, index end def allows_invocation_now? @sequence.satisfied_to_index?(@index) end def mocha_inspect "in sequence #{@sequence.mocha_inspect}" end end # @private def initialize(name) @name = name @expectations = [] end # @private def constrain_as_next_in_sequence(expectation) index = @expectations.length @expectations << expectation expectation.add_ordering_constraint(InSequenceOrderingConstraint.new(self, index)) end # @private def satisfied_to_index?(index) @expectations[0...index].all? { |expectation| expectation.satisfied? } end # @private def mocha_inspect "#{@name.mocha_inspect}" end end end mocha-1.3.0/lib/mocha/module_methods.rb0000644000004100000410000000022613155337744020040 0ustar www-datawww-datarequire 'mocha/module_method' module Mocha # @private module ModuleMethods def stubba_method Mocha::ModuleMethod end end end mocha-1.3.0/lib/mocha/central.rb0000644000004100000410000000110313155337744016453 0ustar www-datawww-datamodule Mocha class Central attr_accessor :stubba_methods def initialize self.stubba_methods = [] end def stub(method) unless stubba_methods.detect { |m| m.matches?(method) } method.stub stubba_methods.push(method) end end def unstub(method) if existing = stubba_methods.detect { |m| m.matches?(method) } existing.unstub stubba_methods.delete(existing) end end def unstub_all while stubba_methods.any? do unstub(stubba_methods.first) end end end end mocha-1.3.0/lib/mocha/hooks.rb0000644000004100000410000000366113155337744016161 0ustar www-datawww-datarequire 'mocha/mockery' module Mocha # Integration hooks for test library authors. # # The methods in this module should be called from test libraries wishing to integrate with Mocha. # # This module is provided as part of the +Mocha::API+ module and is therefore part of the public API, but should only be used by authors of test libraries and not by typical "users" of Mocha. # # Integration with Test::Unit and MiniTest are provided as part of Mocha, because they are (or were once) part of the Ruby standard library. Integration with other test libraries is not provided as *part* of Mocha, but is supported by means of the methods in this module. # # See the code in the +Adapter+ modules for examples of how to use the methods in this module. +Mocha::ExpectationErrorFactory+ may be used if you want +Mocha+ to raise a different type of exception. # # @see Mocha::Integration::TestUnit::Adapter # @see Mocha::Integration::MiniTest::Adapter # @see Mocha::ExpectationErrorFactory # @see Mocha::API module Hooks # Prepares Mocha before a test (only for use by authors of test libraries). # # This method should be called before each individual test starts (including before any "setup" code). def mocha_setup end # Verifies that all mock expectations have been met (only for use by authors of test libraries). # # This is equivalent to a series of "assertions". # # This method should be called at the end of each individual test, before it has been determined whether or not the test has passed. def mocha_verify(assertion_counter = nil) Mockery.verify(assertion_counter) end # Resets Mocha after a test (only for use by authors of test libraries). # # This method should be called after each individual test has finished (including after any "teardown" code). def mocha_teardown Mockery.teardown ensure Mockery.reset_instance end end end mocha-1.3.0/lib/mocha/ruby_version.rb0000644000004100000410000000025413155337744017557 0ustar www-datawww-datamodule Mocha PRE_RUBY_V19 = Gem::Version.new(RUBY_VERSION.dup) < Gem::Version.new('1.9') RUBY_V2_PLUS = Gem::Version.new(RUBY_VERSION.dup) >= Gem::Version.new('2') end mocha-1.3.0/lib/mocha/names.rb0000644000004100000410000000130013155337744016125 0ustar www-datawww-datamodule Mocha class ImpersonatingName def initialize(object) @object = object end def mocha_inspect @object.mocha_inspect end end class ImpersonatingAnyInstanceName def initialize(klass) @klass = klass end def mocha_inspect "#" end end class Name def initialize(name) @name = name end def mocha_inspect "#" end end class DefaultName def initialize(mock) @mock = mock end def mocha_inspect address = @mock.__id__ * 2 address += 0x100000000 if address < 0 "#" end end end mocha-1.3.0/lib/mocha/stubbing_error.rb0000644000004100000410000000057613155337744020066 0ustar www-datawww-datarequire 'mocha/backtrace_filter' module Mocha # Exception raised when stubbing a particular method is not allowed. # # @see Configuration.prevent class StubbingError < StandardError # @private def initialize(message = nil, backtrace = []) super(message) filter = BacktraceFilter.new set_backtrace(filter.filtered(backtrace)) end end end mocha-1.3.0/lib/mocha/class_method.rb0000644000004100000410000000600513155337744017476 0ustar www-datawww-datarequire 'mocha/ruby_version' require 'metaclass' module Mocha class ClassMethod PrependedModule = Class.new(Module) attr_reader :stubbee, :method def initialize(stubbee, method) @stubbee = stubbee @original_method, @original_visibility = nil, nil @method = PRE_RUBY_V19 ? method.to_s : method.to_sym end def stub hide_original_method define_new_method end def unstub remove_new_method restore_original_method mock.unstub(method.to_sym) unless mock.any_expectations? reset_mocha end end def mock stubbee.mocha end def reset_mocha stubbee.reset_mocha end def hide_original_method if @original_visibility = method_visibility(method) begin if RUBY_V2_PLUS @definition_target = PrependedModule.new stubbee.__metaclass__.__send__ :prepend, @definition_target else @original_method = stubbee._method(method) if @original_method && @original_method.owner == stubbee.__metaclass__ stubbee.__metaclass__.send(:remove_method, method) end end rescue NameError # deal with nasties like ActiveRecord::Associations::AssociationProxy end end end def define_new_method definition_target.class_eval(<<-CODE, __FILE__, __LINE__ + 1) def #{method}(*args, &block) mocha.method_missing(:#{method}, *args, &block) end CODE if @original_visibility Module.instance_method(@original_visibility).bind(definition_target).call(method) end end def remove_new_method definition_target.send(:remove_method, method) end def restore_original_method unless RUBY_V2_PLUS if @original_method && @original_method.owner == stubbee.__metaclass__ if PRE_RUBY_V19 original_method = @original_method stubbee.__metaclass__.send(:define_method, method) do |*args, &block| original_method.call(*args, &block) end else stubbee.__metaclass__.send(:define_method, method, @original_method) end end if @original_visibility Module.instance_method(@original_visibility).bind(stubbee.__metaclass__).call(method) end end end def matches?(other) return false unless (other.class == self.class) (stubbee.object_id == other.stubbee.object_id) and (method == other.method) end alias_method :==, :eql? def to_s "#{stubbee}.#{method}" end def method_visibility(method) symbol = method.to_sym metaclass = stubbee.__metaclass__ (metaclass.public_method_defined?(symbol) && :public) || (metaclass.protected_method_defined?(symbol) && :protected) || (metaclass.private_method_defined?(symbol) && :private) end private def definition_target @definition_target ||= stubbee.__metaclass__ end end end mocha-1.3.0/lib/mocha/method_matcher.rb0000644000004100000410000000054113155337744020013 0ustar www-datawww-datamodule Mocha class MethodMatcher attr_reader :expected_method_name def initialize(expected_method_name) @expected_method_name = expected_method_name end def match?(actual_method_name) @expected_method_name == actual_method_name.to_sym end def mocha_inspect "#{@expected_method_name}" end end end mocha-1.3.0/lib/mocha/mini_test.rb0000644000004100000410000000011513155337744017020 0ustar www-datawww-datarequire "mocha/integration/mini_test" Mocha::Integration::MiniTest.activate mocha-1.3.0/lib/mocha/state_machine.rb0000644000004100000410000000553713155337744017646 0ustar www-datawww-datamodule Mocha # A state machine that is used to constrain the order of invocations. # An invocation can be constrained to occur when a state {#is}, or {#is_not}, active. class StateMachine # Provides a mechanism to change the state of a {StateMachine} at some point in the future. class State # @private def initialize(state_machine, state) @state_machine, @state = state_machine, state end # @private def activate @state_machine.current_state = @state end # @private def active? @state_machine.current_state == @state end # @private def mocha_inspect "#{@state_machine.name} is #{@state.mocha_inspect}" end end # Provides the ability to determine whether a {StateMachine} is in a specified state at some point in the future. class StatePredicate # @private def initialize(state_machine, state) @state_machine, @state = state_machine, state end # @private def active? @state_machine.current_state != @state end # @private def mocha_inspect "#{@state_machine.name} is not #{@state.mocha_inspect}" end end # @private attr_reader :name # @private attr_accessor :current_state # @private def initialize(name) @name = name @current_state = nil end # Put the {StateMachine} into the state specified by +initial_state_name+. # # @param [String] initial_state_name name of initial state # @return [StateMachine] state machine, thereby allowing invocations of other {StateMachine} methods to be chained. def starts_as(initial_state_name) become(initial_state_name) self end # Put the {StateMachine} into the +next_state_name+. # # @param [String] next_state_name name of new state def become(next_state_name) @current_state = next_state_name end # Provides a mechanism to change the {StateMachine} into the state specified by +state_name+ at some point in the future. # # Or provides a mechanism to determine whether the {StateMachine} is in the state specified by +state_name+ at some point in the future. # # @param [String] state_name name of new state # @return [State] state which, when activated, will change the {StateMachine} into the state with the specified +state_name+. def is(state_name) State.new(self, state_name) end # Provides a mechanism to determine whether the {StateMachine} is not in the state specified by +state_name+ at some point in the future. def is_not(state_name) StatePredicate.new(self, state_name) end # @private def mocha_inspect if @current_state "#{@name} is #{@current_state.mocha_inspect}" else "#{@name} has no current state" end end end end mocha-1.3.0/lib/mocha/cardinality.rb0000644000004100000410000000365213155337744017341 0ustar www-datawww-datamodule Mocha class Cardinality INFINITY = 1 / 0.0 class << self def exactly(count) new(count, count) end def at_least(count) new(count, INFINITY) end def at_most(count) new(0, count) end def times(range_or_count) case range_or_count when Range then new(range_or_count.first, range_or_count.last) else new(range_or_count, range_or_count) end end end def initialize(required, maximum) @required, @maximum = required, maximum end def invocations_allowed?(invocation_count) invocation_count < maximum end def satisfied?(invocations_so_far) invocations_so_far >= required end def needs_verifying? !allowed_any_number_of_times? end def verified?(invocation_count) (invocation_count >= required) && (invocation_count <= maximum) end def allowed_any_number_of_times? required == 0 && infinite?(maximum) end def used?(invocation_count) (invocation_count > 0) || (maximum == 0) end def mocha_inspect if allowed_any_number_of_times? "allowed any number of times" else if required == 0 && maximum == 0 "expected never" elsif required == maximum "expected exactly #{times(required)}" elsif infinite?(maximum) "expected at least #{times(required)}" elsif required == 0 "expected at most #{times(maximum)}" else "expected between #{required} and #{times(maximum)}" end end end protected attr_reader :required, :maximum def times(number) case number when 0 then "no times" when 1 then "once" when 2 then "twice" else "#{number} times" end end def infinite?(number) number.respond_to?(:infinite?) && number.infinite? end end end mocha-1.3.0/gemfiles/0000755000004100000410000000000013155337744014441 5ustar www-datawww-datamocha-1.3.0/gemfiles/Gemfile.minitest.2.11.00000644000004100000410000000015213155337744020303 0ustar www-datawww-datasource 'https://rubygems.org' gemspec :path=>"../" group :development do gem "minitest", "2.11.0" end mocha-1.3.0/gemfiles/Gemfile.test-unit.2.0.10000644000004100000410000000015213155337744020322 0ustar www-datawww-datasource 'https://rubygems.org' gemspec :path=>"../" group :development do gem "test-unit", "2.0.1" end mocha-1.3.0/gemfiles/Gemfile.minitest.2.3.00000644000004100000410000000015113155337744020223 0ustar www-datawww-datasource 'https://rubygems.org' gemspec :path=>"../" group :development do gem "minitest", "2.3.0" end mocha-1.3.0/gemfiles/Gemfile.minitest.1.3.00000644000004100000410000000015113155337744020222 0ustar www-datawww-datasource 'https://rubygems.org' gemspec :path=>"../" group :development do gem "minitest", "1.3.0" end mocha-1.3.0/gemfiles/Gemfile.minitest.1.4.10000644000004100000410000000015113155337744020224 0ustar www-datawww-datasource 'https://rubygems.org' gemspec :path=>"../" group :development do gem "minitest", "1.4.1" end mocha-1.3.0/gemfiles/Gemfile.minitest.2.0.00000644000004100000410000000015113155337744020220 0ustar www-datawww-datasource 'https://rubygems.org' gemspec :path=>"../" group :development do gem "minitest", "2.0.0" end mocha-1.3.0/gemfiles/Gemfile.minitest.1.4.00000644000004100000410000000015113155337744020223 0ustar www-datawww-datasource 'https://rubygems.org' gemspec :path=>"../" group :development do gem "minitest", "1.4.0" end mocha-1.3.0/gemfiles/Gemfile.test-unit.2.0.00000644000004100000410000000015213155337744020321 0ustar www-datawww-datasource 'https://rubygems.org' gemspec :path=>"../" group :development do gem "test-unit", "2.0.0" end mocha-1.3.0/gemfiles/Gemfile.test-unit.2.0.30000644000004100000410000000015213155337744020324 0ustar www-datawww-datasource 'https://rubygems.org' gemspec :path=>"../" group :development do gem "test-unit", "2.0.3" end mocha-1.3.0/gemfiles/Gemfile.minitest.1.4.20000644000004100000410000000015113155337744020225 0ustar www-datawww-datasource 'https://rubygems.org' gemspec :path=>"../" group :development do gem "minitest", "1.4.2" end mocha-1.3.0/gemfiles/Gemfile.minitest.latest0000644000004100000410000000014013155337744021055 0ustar www-datawww-datasource 'https://rubygems.org' gemspec :path=>"../" group :development do gem "minitest" end mocha-1.3.0/gemfiles/Gemfile.minitest.2.11.20000644000004100000410000000015213155337744020305 0ustar www-datawww-datasource 'https://rubygems.org' gemspec :path=>"../" group :development do gem "minitest", "2.11.2" end mocha-1.3.0/gemfiles/Gemfile.test-unit.latest0000644000004100000410000000024613155337744021164 0ustar www-datawww-datasource 'https://rubygems.org' gemspec :path=>"../" group :development do if RUBY_VERSION < '1.9' gem "test-unit", "~> 2" else gem "test-unit" end end mocha-1.3.0/gemfiles/Gemfile.minitest.2.0.10000644000004100000410000000015113155337744020221 0ustar www-datawww-datasource 'https://rubygems.org' gemspec :path=>"../" group :development do gem "minitest", "2.0.1" end mocha-1.3.0/test/0000755000004100000410000000000013155337744013625 5ustar www-datawww-datamocha-1.3.0/test/method_definer.rb0000644000004100000410000000113613155337744017127 0ustar www-datawww-datarequire 'metaclass' module Mocha module ObjectMethods def define_instance_method(method_symbol, &block) __metaclass__.send(:define_method, method_symbol, block) end def replace_instance_method(method_symbol, &block) raise "Cannot replace #{method_symbol} as #{self} does not respond to it." unless self.respond_to?(method_symbol) define_instance_method(method_symbol, &block) end def define_instance_accessor(*symbols) symbols.each { |symbol| __metaclass__.send(:attr_accessor, symbol) } end end end class Object include Mocha::ObjectMethods end mocha-1.3.0/test/test_unit_result.rb0000644000004100000410000000077013155337744017572 0ustar www-datawww-datarequire 'test/unit/testresult' class TestUnitResult def self.build_test_result test_result = Test::Unit::TestResult.new class << test_result attr_reader :failures, :errors def failure_messages failures.map { |failure| failure.message } end def failure_message_lines failure_messages.map { |message| message.split("\n") }.flatten end def error_messages errors.map { |error| error.message } end end test_result end end mocha-1.3.0/test/mini_test_result.rb0000644000004100000410000000470113155337744017545 0ustar www-datawww-datarequire 'stringio' require 'minitest/unit' class MiniTestResult minitest_version = Gem::Version.new(::MiniTest::Unit::VERSION) if Gem::Requirement.new('<= 4.6.1').satisfied_by?(minitest_version) FAILURE_PATTERN = %r{(Failure)\:\n([^\(]+)\(([^\)]+)\) \[([^\]]+)\]\:\n(.*)\n}m ERROR_PATTERN = %r{(Error)\:\n([^\(]+)\(([^\)]+)\)\:\n(.+?)\n}m PATTERN_INDICES = { :method => 2, :testcase => 3 } else FAILURE_PATTERN = %r{(Failure)\:\n.([^#]+)\#([^ ]+) \[([^\]]+)\]\:\n(.*)\n}m ERROR_PATTERN = %r{(Error)\:\n.([^#]+)\#([^ ]+)\:\n(.+?)\n}m PATTERN_INDICES = { :method => 3, :testcase => 2 } end def self.parse_failure(raw) matches = FAILURE_PATTERN.match(raw) return nil unless matches Failure.new(matches[PATTERN_INDICES[:method]], matches[PATTERN_INDICES[:testcase]], [matches[4]], matches[5]) end def self.parse_error(raw) matches = ERROR_PATTERN.match(raw) return nil unless matches backtrace = raw.gsub(ERROR_PATTERN, '').split("\n").map(&:strip) Error.new(matches[PATTERN_INDICES[:method]], matches[PATTERN_INDICES[:testcase]], matches[4], backtrace) end class Failure attr_reader :method, :test_case, :location, :message def initialize(method, test_case, location, message) @method, @test_case, @location, @message = method, test_case, location, message end end class Error class Exception attr_reader :message, :backtrace def initialize(message, location) @message, @backtrace = message, location end end attr_reader :method, :test_case, :exception def initialize(method, test_case, message, backtrace) @method, @test_case, @exception = method, test_case, Exception.new(message, backtrace) end end def initialize(runner, tests) @runner, @tests = runner, tests end def failure_count @runner.failures end def assertion_count @tests.inject(0) { |total, test| total + test._assertions } end def error_count @runner.errors end def passed? @tests.all?(&:passed?) end def failures @runner.report.map { |puked| MiniTestResult.parse_failure(puked) }.compact end def errors @runner.report.map { |puked| MiniTestResult.parse_error(puked) }.compact end def failure_messages failures.map(&:message) end def failure_message_lines failure_messages.map { |message| message.split("\n") }.flatten end def error_messages errors.map { |e| e.exception.message } end end mocha-1.3.0/test/simple_counter.rb0000644000004100000410000000017513155337744017205 0ustar www-datawww-dataclass SimpleCounter attr_reader :count def initialize @count = 0 end def increment @count += 1 end end mocha-1.3.0/test/test_helper.rb0000644000004100000410000000305013155337744016466 0ustar www-datawww-dataunless defined?(STANDARD_OBJECT_PUBLIC_INSTANCE_METHODS) STANDARD_OBJECT_PUBLIC_INSTANCE_METHODS = Object.instance_methods + Object.private_instance_methods end $:.unshift File.expand_path(File.join(File.dirname(__FILE__), "..", "lib")) $:.unshift File.expand_path(File.join(File.dirname(__FILE__))) $:.unshift File.expand_path(File.join(File.dirname(__FILE__), 'unit')) $:.unshift File.expand_path(File.join(File.dirname(__FILE__), 'unit', 'parameter_matchers')) $:.unshift File.expand_path(File.join(File.dirname(__FILE__), 'acceptance')) require 'mocha/detection/mini_test' begin require 'minitest' rescue LoadError end begin require 'minitest/unit' rescue LoadError end module Mocha; end if (minitest_testcase = Mocha::Detection::MiniTest.testcase) && (ENV['MOCHA_RUN_INTEGRATION_TESTS'] != 'test-unit') begin require 'minitest/autorun' rescue LoadError MiniTest::Unit.autorun end class Mocha::TestCase < minitest_testcase def assert_nothing_raised(exception = StandardError) yield rescue exception => e flunk "Unexpected exception raised: #{e}" end alias_method :assert_not_nil, :refute_nil alias_method :assert_raise, :assert_raises alias_method :assert_not_same, :refute_same alias_method :assert_no_match, :refute_match end else require 'test/unit' class Mocha::TestCase < Test::Unit::TestCase def test_dummy # Some versions (?) of Test::Unit try to run this base class as a test case # and it fails because it has no test methods, so I'm adding a dummy test. end end end mocha-1.3.0/test/test_runner.rb0000644000004100000410000000357113155337744016530 0ustar www-datawww-datarequire 'assertions' require 'mocha/detection/mini_test' module TestRunner def run_as_test(&block) run_as_tests(:test_me => block) end def run_as_tests(methods = {}) base_class = Mocha::TestCase test_class = Class.new(base_class) do include Assertions methods.each do |(method_name, proc)| define_method(method_name, proc) end end tests = methods.keys.select { |m| m.to_s[/^test/] }.map { |m| test_class.new(m) } if Mocha::Detection::MiniTest.testcase && (ENV['MOCHA_RUN_INTEGRATION_TESTS'] != 'test-unit') minitest_version = Gem::Version.new(Mocha::Detection::MiniTest.version) if Gem::Requirement.new('>= 5.0.0').satisfied_by?(minitest_version) require File.expand_path('../minitest_result', __FILE__) tests.each do |test| test.run end Minitest::Runnable.runnables.delete(test_class) test_result = MinitestResult.new(tests) elsif Gem::Requirement.new('> 0.0.0', '< 5.0.0').satisfied_by?(minitest_version) require File.expand_path('../mini_test_result', __FILE__) runner = MiniTest::Unit.new tests.each do |test| test.run(runner) end test_result = MiniTestResult.new(runner, tests) end else require File.expand_path('../test_unit_result', __FILE__) test_result = TestUnitResult.build_test_result tests.each do |test| test.run(test_result) {} end end test_result end def assert_passed(test_result) flunk "Test failed unexpectedly with message: #{test_result.failures}" if test_result.failure_count > 0 flunk "Test failed unexpectedly with message: #{test_result.errors.map(&:exception)}" if test_result.error_count > 0 end def assert_failed(test_result) flunk "Test passed unexpectedly" unless test_result.failure_count + test_result.error_count > 0 end end mocha-1.3.0/test/minitest_result.rb0000644000004100000410000000163613155337744017412 0ustar www-datawww-datarequire 'forwardable' class MinitestResult class Failure extend Forwardable def_delegators :@failure, :message, :backtrace def initialize(failure) @failure = failure end def location Minitest.filter_backtrace(backtrace) end end def initialize(tests) @tests = tests end def failures @tests.map(&:failures).flatten.select { |r| r.instance_of?(Minitest::Assertion) }.map { |f| Failure.new(f) } end def failure_count failures.length end def failure_message_lines failures.map { |f| f.message.split("\n") }.flatten end def errors @tests.map(&:failures).flatten.select { |r| r.instance_of?(Minitest::UnexpectedError) } end def error_count errors.length end def error_messages errors.map { |e| e.message.split("\n") }.flatten end def assertion_count @tests.inject(0) { |total, test| total + test.assertions } end end mocha-1.3.0/test/integration/0000755000004100000410000000000013155337744016150 5ustar www-datawww-datamocha-1.3.0/test/integration/shared_tests.rb0000644000004100000410000001367113155337744021175 0ustar www-datawww-datarequire 'test_runner' require 'execution_point' module SharedTests include TestRunner def test_assertion_satisfied test_result = run_as_test do assert true end assert_passed(test_result) end def test_assertion_unsatisfied execution_point = nil test_result = run_as_test do execution_point = ExecutionPoint.current; flunk end assert_failed(test_result) failure = test_result.failures.first assert_equal execution_point, ExecutionPoint.new(failure.location) end def test_mock_object_unexpected_invocation execution_point = nil test_result = run_as_test do mock = mock("not expecting invocation") execution_point = ExecutionPoint.current; mock.unexpected end assert_failed(test_result) failure = test_result.failures.first assert_equal execution_point, ExecutionPoint.new(failure.location) assert_equal ["unexpected invocation: #.unexpected()"], test_result.failure_message_lines end def test_mock_object_explicitly_unexpected_invocation execution_point = nil test_result = run_as_test do mock = mock("not expecting invocation") mock.expects(:unexpected).never execution_point = ExecutionPoint.current; mock.unexpected end assert_failed(test_result) failure = test_result.failures.first assert_equal execution_point, ExecutionPoint.new(failure.location) assert_equal [ "unexpected invocation: #.unexpected()", "unsatisfied expectations:", "- expected never, invoked once: #.unexpected(any_parameters)" ], test_result.failure_message_lines end def test_mock_object_unsatisfied_expectation execution_point = nil test_result = run_as_test do mock = mock("expecting invocation") execution_point = ExecutionPoint.current; mock.expects(:expected) end assert_failed(test_result) failure = test_result.failures.first assert_equal execution_point, ExecutionPoint.new(failure.location) assert_equal [ "not all expectations were satisfied", "unsatisfied expectations:", "- expected exactly once, not yet invoked: #.expected(any_parameters)" ], test_result.failure_message_lines end def test_mock_object_unexpected_invocation_in_setup execution_point = nil test_result = run_as_tests( :setup => lambda { mock = mock("not expecting invocation") execution_point = ExecutionPoint.current; mock.unexpected }, :test_me => lambda { assert true } ) assert_failed(test_result) failure = test_result.failures.first assert_equal execution_point, ExecutionPoint.new(failure.location) assert_equal ["unexpected invocation: #.unexpected()"], test_result.failure_message_lines end def test_mock_object_unsatisfied_expectation_in_setup execution_point = nil test_result = run_as_tests( :setup => lambda { mock = mock("expecting invocation") execution_point = ExecutionPoint.current; mock.expects(:expected) }, :test_me => lambda { assert true } ) assert_failed(test_result) failure = test_result.failures.first assert_equal execution_point, ExecutionPoint.new(failure.location) assert_equal [ "not all expectations were satisfied", "unsatisfied expectations:", "- expected exactly once, not yet invoked: #.expected(any_parameters)" ], test_result.failure_message_lines end def test_mock_object_unexpected_invocation_in_teardown execution_point = nil test_result = run_as_tests( :test_me => lambda { assert true }, :teardown => lambda { mock = mock("not expecting invocation") execution_point = ExecutionPoint.current; mock.unexpected } ) assert_failed(test_result) failure = test_result.failures.first assert_equal execution_point, ExecutionPoint.new(failure.location) assert_equal ["unexpected invocation: #.unexpected()"], test_result.failure_message_lines end def test_real_object_explicitly_unexpected_invocation execution_point = nil object = Object.new test_result = run_as_test do object.expects(:unexpected).never execution_point = ExecutionPoint.current; object.unexpected end assert_failed(test_result) failure = test_result.failures.first assert_equal execution_point, ExecutionPoint.new(failure.location) assert_equal [ "unexpected invocation: #{object.mocha_inspect}.unexpected()", "unsatisfied expectations:", "- expected never, invoked once: #{object.mocha_inspect}.unexpected(any_parameters)" ], test_result.failure_message_lines end def test_real_object_unsatisfied_expectation execution_point = nil object = Object.new test_result = run_as_test do execution_point = ExecutionPoint.current; object.expects(:expected) end assert_failed(test_result) failure = test_result.failures.first assert_equal execution_point, ExecutionPoint.new(failure.location) assert_equal [ "not all expectations were satisfied", "unsatisfied expectations:", "- expected exactly once, not yet invoked: #{object.mocha_inspect}.expected(any_parameters)" ], test_result.failure_message_lines end def test_real_object_expectation_does_not_leak_into_subsequent_test execution_point = nil klass = Class.new test_result = run_as_tests( :test_1 => lambda { klass.expects(:foo) klass.foo }, :test_2 => lambda { execution_point = ExecutionPoint.current; klass.foo } ) assert_failed(test_result) exception = test_result.errors.first.exception assert_equal execution_point, ExecutionPoint.new(exception.backtrace) assert_match %r{undefined method `foo'}, exception.message end end mocha-1.3.0/test/integration/test_unit_test.rb0000644000004100000410000000026613155337744021556 0ustar www-datawww-datarequire File.expand_path('../../test_helper', __FILE__) require "mocha/test_unit" require "integration/shared_tests" class TestUnitTest < Mocha::TestCase include SharedTests end mocha-1.3.0/test/integration/mini_test_test.rb0000644000004100000410000000026613155337744021533 0ustar www-datawww-datarequire File.expand_path('../../test_helper', __FILE__) require "mocha/mini_test" require "integration/shared_tests" class MiniTestTest < Mocha::TestCase include SharedTests end mocha-1.3.0/test/execution_point.rb0000644000004100000410000000131613155337744017367 0ustar www-datawww-dataclass ExecutionPoint attr_reader :backtrace def self.current new(caller) end def initialize(backtrace) @backtrace = backtrace end def first_relevant_line_of_backtrace @backtrace && (@backtrace.reject { |l| /\Aorg\/jruby\//.match(l) }.first || 'unknown:0') end def file_name /\A(.*?):\d+/.match(first_relevant_line_of_backtrace)[1] end def line_number Integer(/\A.*?:(\d+)/.match(first_relevant_line_of_backtrace)[1]) end def ==(other) return false unless other.is_a?(ExecutionPoint) (file_name == other.file_name) and (line_number == other.line_number) end def to_s "file: #{file_name}; line: #{line_number}" end def inspect to_s end end mocha-1.3.0/test/deprecation_disabler.rb0000644000004100000410000000046213155337744020316 0ustar www-datawww-datarequire 'mocha/deprecation' module DeprecationDisabler def disable_deprecations original_mode = Mocha::Deprecation.mode Mocha::Deprecation.mode = :disabled begin yield ensure Mocha::Deprecation.mode = original_mode end end module_function :disable_deprecations end mocha-1.3.0/test/assertions.rb0000644000004100000410000000046013155337744016344 0ustar www-datawww-datarequire 'mocha/ruby_version' module Assertions def assert_method_visibility(object, method_name, visiblity) method_key = Mocha::PRE_RUBY_V19 ? method_name.to_s : method_name.to_sym assert object.send("#{visiblity}_methods").include?(method_key), "#{method_name} is not #{visiblity}" end end mocha-1.3.0/test/unit/0000755000004100000410000000000013155337745014605 5ustar www-datawww-datamocha-1.3.0/test/unit/cardinality_test.rb0000644000004100000410000000433213155337744020475 0ustar www-datawww-datarequire File.expand_path('../../test_helper', __FILE__) require 'mocha/cardinality' class CardinalityTest < Mocha::TestCase include Mocha def test_should_allow_invocations_if_invocation_count_has_not_yet_reached_maximum cardinality = Cardinality.new(2, 3) assert cardinality.invocations_allowed?(0) assert cardinality.invocations_allowed?(1) assert cardinality.invocations_allowed?(2) assert !cardinality.invocations_allowed?(3) end def test_should_be_satisfied_if_invocations_so_far_have_reached_required_threshold cardinality = Cardinality.new(2, 3) assert !cardinality.satisfied?(0) assert !cardinality.satisfied?(1) assert cardinality.satisfied?(2) assert cardinality.satisfied?(3) end def test_should_describe_cardinality assert_equal 'allowed any number of times', Cardinality.at_least(0).mocha_inspect assert_equal 'expected at most once', Cardinality.at_most(1).mocha_inspect assert_equal 'expected at most twice', Cardinality.at_most(2).mocha_inspect assert_equal 'expected at most 3 times', Cardinality.at_most(3).mocha_inspect assert_equal 'expected at least once', Cardinality.at_least(1).mocha_inspect assert_equal 'expected at least twice', Cardinality.at_least(2).mocha_inspect assert_equal 'expected at least 3 times', Cardinality.at_least(3).mocha_inspect assert_equal 'expected never', Cardinality.exactly(0).mocha_inspect assert_equal 'expected exactly once', Cardinality.exactly(1).mocha_inspect assert_equal 'expected exactly twice', Cardinality.exactly(2).mocha_inspect assert_equal 'expected exactly 3 times', Cardinality.times(3).mocha_inspect assert_equal 'expected between 2 and 4 times', Cardinality.times(2..4).mocha_inspect assert_equal 'expected between 1 and 3 times', Cardinality.times(1..3).mocha_inspect end def test_should_need_verifying assert Cardinality.exactly(2).needs_verifying? assert Cardinality.at_least(3).needs_verifying? assert Cardinality.at_most(2).needs_verifying? assert Cardinality.times(4).needs_verifying? assert Cardinality.times(2..4).needs_verifying? end def test_should_not_need_verifying assert_equal false, Cardinality.at_least(0).needs_verifying? end end mocha-1.3.0/test/unit/multiple_yields_test.rb0000644000004100000410000000072313155337744021376 0ustar www-datawww-datarequire File.expand_path('../../test_helper', __FILE__) require 'mocha/multiple_yields' class MultipleYieldsTest < Mocha::TestCase include Mocha def test_should_provide_parameters_for_multiple_yields_in_single_invocation parameter_group = MultipleYields.new([1, 2, 3], [4, 5]) parameter_groups = [] parameter_group.each do |parameters| parameter_groups << parameters end assert_equal [[1, 2, 3], [4, 5]], parameter_groups end end mocha-1.3.0/test/unit/method_matcher_test.rb0000644000004100000410000000160513155337744021155 0ustar www-datawww-datarequire File.expand_path('../../test_helper', __FILE__) require 'mocha/method_matcher' class MethodMatcherTest < Mocha::TestCase include Mocha def test_should_match_if_actual_method_name_is_same_as_expected_method_name method_matcher = MethodMatcher.new(:method_name) assert method_matcher.match?(:method_name) end def test_should_match_if_actual_method_name_is_expected_method_name_as_string method_matcher = MethodMatcher.new(:method_name) assert method_matcher.match?('method_name') end def test_should_not_match_if_actual_method_name_is_not_same_as_expected_method_name method_matcher = MethodMatcher.new(:method_name) assert !method_matcher.match?(:different_method_name) end def test_should_describe_what_method_is_expected method_matcher = MethodMatcher.new(:method_name) assert_equal "method_name", method_matcher.mocha_inspect end end mocha-1.3.0/test/unit/return_values_test.rb0000644000004100000410000000364413155337745021076 0ustar www-datawww-datarequire File.expand_path('../../test_helper', __FILE__) require 'mocha/return_values' class ReturnValuesTest < Mocha::TestCase include Mocha def test_should_return_nil values = ReturnValues.new assert_nil values.next end def test_should_keep_returning_nil values = ReturnValues.new values.next assert_nil values.next assert_nil values.next end def test_should_return_evaluated_single_return_value values = ReturnValues.new(SingleReturnValue.new('value')) assert_equal 'value', values.next end def test_should_keep_returning_evaluated_single_return_value values = ReturnValues.new(SingleReturnValue.new('value')) values.next assert_equal 'value', values.next assert_equal 'value', values.next end def test_should_return_consecutive_evaluated_single_return_values values = ReturnValues.new(SingleReturnValue.new('value_1'), SingleReturnValue.new('value_2')) assert_equal 'value_1', values.next assert_equal 'value_2', values.next end def test_should_keep_returning_last_of_consecutive_evaluated_single_return_values values = ReturnValues.new(SingleReturnValue.new('value_1'), SingleReturnValue.new('value_2')) values.next values.next assert_equal 'value_2', values.next assert_equal 'value_2', values.next end def test_should_build_single_return_values_for_each_values values = ReturnValues.build('value_1', 'value_2', 'value_3').values assert_equal 'value_1', values[0].evaluate assert_equal 'value_2', values[1].evaluate assert_equal 'value_3', values[2].evaluate end def test_should_combine_two_sets_of_return_values values_1 = ReturnValues.build('value_1') values_2 = ReturnValues.build('value_2a', 'value_2b') values = (values_1 + values_2).values assert_equal 'value_1', values[0].evaluate assert_equal 'value_2a', values[1].evaluate assert_equal 'value_2b', values[2].evaluate end end mocha-1.3.0/test/unit/any_instance_method_test.rb0000644000004100000410000001030013155337744022175 0ustar www-datawww-datarequire File.expand_path('../../test_helper', __FILE__) require 'method_definer' require 'mocha/mock' require 'mocha/any_instance_method' class AnyInstanceMethodTest < Mocha::TestCase include Mocha unless RUBY_V2_PLUS def test_should_hide_original_method klass = Class.new { def method_x; end } method = AnyInstanceMethod.new(klass, :method_x) method.hide_original_method assert_equal false, klass.method_defined?(:method_x) end end def test_should_not_raise_error_hiding_method_that_isnt_defined klass = Class.new method = AnyInstanceMethod.new(klass, :method_x) assert_nothing_raised { method.hide_original_method } end def test_should_define_a_new_method klass = Class.new { def method_x; end } method = AnyInstanceMethod.new(klass, :method_x) mocha = build_mock mocha.expects(:method_x).with(:param1, :param2).returns(:result) any_instance = Object.new any_instance.define_instance_method(:mocha) { mocha } klass.define_instance_method(:any_instance) { any_instance } method.hide_original_method method.define_new_method instance = klass.new result = instance.method_x(:param1, :param2) assert_equal :result, result assert mocha.__verified__? end def test_should_restore_original_method klass = Class.new { def method_x; :original_result; end } method = AnyInstanceMethod.new(klass, :method_x) method.hide_original_method method.define_new_method method.remove_new_method method.restore_original_method instance = klass.new assert instance.respond_to?(:method_x) assert_equal :original_result, instance.method_x end def test_should_not_restore_original_method_if_none_was_defined_in_first_place klass = Class.new { def method_x; :new_result; end } method = AnyInstanceMethod.new(klass, :method_x) method.restore_original_method instance = klass.new assert_equal :new_result, instance.method_x end def test_should_call_remove_new_method klass = Class.new { def method_x; end } any_instance = build_mock any_instance_mocha = build_mock any_instance.stubs(:mocha).returns(any_instance_mocha) klass.define_instance_method(:any_instance) { any_instance } method = AnyInstanceMethod.new(klass, :method_x) method.replace_instance_method(:restore_original_method) { } method.replace_instance_method(:reset_mocha) { } method.define_instance_accessor(:remove_called) method.replace_instance_method(:remove_new_method) { self.remove_called = true } method.unstub assert method.remove_called end def test_should_call_restore_original_method klass = Class.new { def method_x; end } any_instance = build_mock any_instance_mocha = build_mock any_instance.stubs(:mocha).returns(any_instance_mocha) klass.define_instance_method(:any_instance) { any_instance } method = AnyInstanceMethod.new(klass, :method_x) method.replace_instance_method(:remove_new_method) { } method.replace_instance_method(:reset_mocha) { } method.define_instance_accessor(:restore_called) method.replace_instance_method(:restore_original_method) { self.restore_called = true } method.unstub assert method.restore_called end def test_should_call_mock_unstub klass = Class.new { def method_x; end } method = AnyInstanceMethod.new(klass, :method_x) method.replace_instance_method(:remove_new_method) { } method.replace_instance_method(:restore_original_method) { } mocha = Class.new { class << self; attr_accessor :unstub_method; end; def self.unstub(method); self.unstub_method = method; end; } mocha.define_instance_method(:any_expectations?) { true } method.replace_instance_method(:mock) { mocha } method.unstub assert_equal mocha.unstub_method, :method_x end def test_should_return_any_instance_mocha_for_stubbee mocha = Object.new any_instance = Object.new any_instance.define_instance_method(:mocha) { mocha } stubbee = Class.new stubbee.define_instance_method(:any_instance) { any_instance } method = AnyInstanceMethod.new(stubbee, :method_name) assert_equal stubbee.any_instance.mocha, method.mock end private def build_mock Mock.new(nil) end end mocha-1.3.0/test/unit/object_inspect_test.rb0000644000004100000410000000244413155337744021167 0ustar www-datawww-datarequire File.expand_path('../../test_helper', __FILE__) require 'mocha/ruby_version' require 'mocha/inspect' require 'method_definer' class ObjectInspectTest < Mocha::TestCase def test_should_return_default_string_representation_of_object_not_including_instance_variables object = Object.new class << object attr_accessor :attribute end object.attribute = 'instance_variable' assert_match Regexp.new("^#$"), object.mocha_inspect assert_no_match(/instance_variable/, object.mocha_inspect) end def test_should_return_customized_string_representation_of_object object = Object.new class << object define_method(:inspect) { 'custom_inspect' } end assert_equal 'custom_inspect', object.mocha_inspect end def test_should_use_underscored_id_instead_of_object_id_or_id_so_that_they_can_be_stubbed calls = [] object = Object.new object.replace_instance_method(:id) { calls << :id; return 1 } if Mocha::PRE_RUBY_V19 object.replace_instance_method(:object_id) { calls << :object_id; return 1 } object.replace_instance_method(:__id__) { calls << :__id__; return 1 } object.replace_instance_method(:inspect) { "object-description" } object.mocha_inspect assert_equal [:__id__], calls.uniq end end mocha-1.3.0/test/unit/expectation_list_test.rb0000644000004100000410000000704713155337744021556 0ustar www-datawww-datarequire File.expand_path('../../test_helper', __FILE__) require 'mocha/expectation_list' require 'mocha/expectation' require 'set' require 'method_definer' class ExpectationListTest < Mocha::TestCase include Mocha def test_should_return_added_expectation expectation_list = ExpectationList.new expectation = Expectation.new(nil, :my_method) assert_same expectation, expectation_list.add(expectation) end def test_should_find_matching_expectation expectation_list = ExpectationList.new expectation1 = Expectation.new(nil, :my_method).with(:argument1, :argument2) expectation2 = Expectation.new(nil, :my_method).with(:argument3, :argument4) expectation_list.add(expectation1) expectation_list.add(expectation2) assert_same expectation1, expectation_list.match(:my_method, :argument1, :argument2) end def test_should_remove_all_expectations_matching_method_name expectation_list = ExpectationList.new expectation1 = Expectation.new(nil, :method_one).with(:argument1, :argument2) expectation2 = Expectation.new(nil, :method_one).with(:argument3, :argument4) expectation3 = Expectation.new(nil, :method_two) expectation_list.add(expectation1) expectation_list.add(expectation2) expectation_list.add(expectation3) expectation_list.remove_all_matching_method(:method_one) assert_nil expectation_list.match(:method_one, :argument1, :argument2) assert_nil expectation_list.match(:method_one, :argument3, :argument4) assert_same expectation3, expectation_list.match(:method_two) end def test_should_find_most_recent_matching_expectation expectation_list = ExpectationList.new expectation1 = Expectation.new(nil, :my_method).with(:argument1, :argument2) expectation2 = Expectation.new(nil, :my_method).with(:argument1, :argument2) expectation_list.add(expectation1) expectation_list.add(expectation2) assert_same expectation2, expectation_list.match(:my_method, :argument1, :argument2) end def test_should_find_matching_expectation_allowing_invocation expectation_list = ExpectationList.new expectation1 = Expectation.new(nil, :my_method).with(:argument1, :argument2) expectation2 = Expectation.new(nil, :my_method).with(:argument3, :argument4) expectation1.define_instance_method(:invocations_allowed?) { true } expectation2.define_instance_method(:invocations_allowed?) { true } expectation_list.add(expectation1) expectation_list.add(expectation2) assert_same expectation1, expectation_list.match_allowing_invocation(:my_method, :argument1, :argument2) end def test_should_find_most_recent_matching_expectation_allowing_invocation expectation_list = ExpectationList.new expectation1 = Expectation.new(nil, :my_method) expectation2 = Expectation.new(nil, :my_method) expectation1.define_instance_method(:invocations_allowed?) { true } expectation2.define_instance_method(:invocations_allowed?) { false } expectation_list.add(expectation1) expectation_list.add(expectation2) assert_same expectation1, expectation_list.match_allowing_invocation(:my_method) end def test_should_combine_two_expectation_lists_into_one expectation_list1 = ExpectationList.new expectation_list2 = ExpectationList.new expectation1 = Expectation.new(nil, :my_method) expectation2 = Expectation.new(nil, :my_method) expectation_list1.add(expectation1) expectation_list2.add(expectation2) expectation_list = expectation_list1 + expectation_list2 assert_equal [expectation1, expectation2], expectation_list.to_a end end mocha-1.3.0/test/unit/parameters_matcher_test.rb0000644000004100000410000001142013155337745022035 0ustar www-datawww-datarequire File.expand_path('../../test_helper', __FILE__) require 'mocha/parameters_matcher' class ParametersMatcherTest < Mocha::TestCase include Mocha def test_should_match_any_actual_parameters_if_no_expected_parameters_specified parameters_matcher = ParametersMatcher.new assert parameters_matcher.match?([1, 2, 3]) end def test_should_match_if_actual_parameters_are_same_as_expected_parameters parameters_matcher = ParametersMatcher.new([4, 5, 6]) assert parameters_matcher.match?([4, 5, 6]) end def test_should_not_match_if_actual_parameters_are_different_from_expected_parameters parameters_matcher = ParametersMatcher.new([4, 5, 6]) assert !parameters_matcher.match?([1, 2, 3]) end def test_should_not_match_if_there_are_less_actual_parameters_than_expected_parameters parameters_matcher = ParametersMatcher.new([4, 5, 6]) assert !parameters_matcher.match?([4, 5]) end def test_should_not_match_if_there_are_more_actual_parameters_than_expected_parameters parameters_matcher = ParametersMatcher.new([4, 5]) assert !parameters_matcher.match?([4, 5, 6]) end def test_should_not_match_if_not_all_required_parameters_are_supplied optionals = ParameterMatchers::Optionally.new(6, 7) parameters_matcher = ParametersMatcher.new([4, 5, optionals]) assert !parameters_matcher.match?([4]) end def test_should_match_if_all_required_parameters_match_and_no_optional_parameters_are_supplied optionals = ParameterMatchers::Optionally.new(6, 7) parameters_matcher = ParametersMatcher.new([4, 5, optionals]) assert parameters_matcher.match?([4, 5]) end def test_should_match_if_all_required_and_optional_parameters_match_and_some_optional_parameters_are_supplied optionals = ParameterMatchers::Optionally.new(6, 7) parameters_matcher = ParametersMatcher.new([4, 5, optionals]) assert parameters_matcher.match?([4, 5, 6]) end def test_should_match_if_all_required_and_optional_parameters_match_and_all_optional_parameters_are_supplied optionals = ParameterMatchers::Optionally.new(6, 7) parameters_matcher = ParametersMatcher.new([4, 5, optionals]) assert parameters_matcher.match?([4, 5, 6, 7]) end def test_should_not_match_if_all_required_and_optional_parameters_match_but_too_many_optional_parameters_are_supplied optionals = ParameterMatchers::Optionally.new(6, 7) parameters_matcher = ParametersMatcher.new([4, 5, optionals]) assert !parameters_matcher.match?([4, 5, 6, 7, 8]) end def test_should_not_match_if_all_required_parameters_match_but_some_optional_parameters_do_not_match optionals = ParameterMatchers::Optionally.new(6, 7) parameters_matcher = ParametersMatcher.new([4, 5, optionals]) assert !parameters_matcher.match?([4, 5, 6, 0]) end def test_should_not_match_if_some_required_parameters_do_not_match_although_all_optional_parameters_do_match optionals = ParameterMatchers::Optionally.new(6, 7) parameters_matcher = ParametersMatcher.new([4, 5, optionals]) assert !parameters_matcher.match?([4, 0, 6]) end def test_should_not_match_if_all_required_parameters_match_but_no_optional_parameters_match optionals = ParameterMatchers::Optionally.new(6, 7) parameters_matcher = ParametersMatcher.new([4, 5, optionals]) assert !parameters_matcher.match?([4, 5, 0, 0]) end def test_should_match_if_actual_parameters_satisfy_matching_block parameters_matcher = ParametersMatcher.new { |x, y| x + y == 3 } assert parameters_matcher.match?([1, 2]) end def test_should_not_match_if_actual_parameters_do_not_satisfy_matching_block parameters_matcher = ParametersMatcher.new { |x, y| x + y == 3 } assert !parameters_matcher.match?([2, 3]) end def test_should_remove_outer_array_braces params = [1, 2, [3, 4]] parameters_matcher = ParametersMatcher.new(params) assert_equal '(1, 2, [3, 4])', parameters_matcher.mocha_inspect end def test_should_display_numeric_arguments_as_is params = [1, 2, 3] parameters_matcher = ParametersMatcher.new(params) assert_equal '(1, 2, 3)', parameters_matcher.mocha_inspect end def test_should_remove_curly_braces_if_hash_is_only_argument params = [{:a => 1, :z => 2}] parameters_matcher = ParametersMatcher.new(params) assert_nil parameters_matcher.mocha_inspect.index('{') assert_nil parameters_matcher.mocha_inspect.index('}') end def test_should_not_remove_curly_braces_if_hash_is_not_the_only_argument params = [1, {:a => 1}] parameters_matcher = ParametersMatcher.new(params) assert_equal '(1, {:a => 1})', parameters_matcher.mocha_inspect end def test_should_indicate_that_matcher_will_match_any_actual_parameters parameters_matcher = ParametersMatcher.new assert_equal '(any_parameters)', parameters_matcher.mocha_inspect end end mocha-1.3.0/test/unit/class_method_test.rb0000644000004100000410000001663713155337744020652 0ustar www-datawww-datarequire File.expand_path('../../test_helper', __FILE__) require 'method_definer' require 'mocha/mock' require 'mocha/class_method' class ClassMethodTest < Mocha::TestCase include Mocha unless RUBY_V2_PLUS def test_should_hide_original_method klass = Class.new { def self.method_x; end } klass.__metaclass__.send(:alias_method, :_method, :method) method = ClassMethod.new(klass, :method_x) method.hide_original_method assert_equal false, klass.respond_to?(:method_x) end end def test_should_not_raise_error_hiding_method_that_isnt_defined klass = Class.new method = ClassMethod.new(klass, :method_x) assert_nothing_raised { method.hide_original_method } end def test_should_not_raise_error_hiding_method_in_class_that_implements_method_called_method klass = Class.new { def self.method; end } method = ClassMethod.new(klass, :method) assert_nothing_raised { method.hide_original_method } end def test_should_define_a_new_method_which_should_call_mocha_method_missing klass = Class.new { def self.method_x; end } mocha = build_mock klass.define_instance_method(:mocha) { mocha } mocha.expects(:method_x).with(:param1, :param2).returns(:result) method = ClassMethod.new(klass, :method_x) method.hide_original_method method.define_new_method result = klass.method_x(:param1, :param2) assert_equal :result, result assert mocha.__verified__? end def test_should_remove_new_method klass = Class.new { def self.method_x; end } method = ClassMethod.new(klass, :method_x) method.remove_new_method assert_equal false, klass.respond_to?(:method_x) end def test_should_restore_original_method klass = Class.new { def self.method_x; :original_result; end } klass.__metaclass__.send(:alias_method, :_method, :method) method = ClassMethod.new(klass, :method_x) method.hide_original_method method.define_new_method method.remove_new_method method.restore_original_method assert klass.respond_to?(:method_x) assert_equal :original_result, klass.method_x end def test_should_restore_original_method_accepting_a_block_parameter klass = Class.new { def self.method_x(&block); block.call if block_given? ; end } klass.__metaclass__.send(:alias_method, :_method, :method) method = ClassMethod.new(klass, :method_x) method.hide_original_method method.define_new_method method.remove_new_method method.restore_original_method block_called = false klass.method_x { block_called = true } assert block_called end def test_should_not_restore_original_method_if_none_was_defined_in_first_place klass = Class.new { def self.method_x; :new_result; end } method = ClassMethod.new(klass, :method_x) method.restore_original_method assert_equal :new_result, klass.method_x end def test_should_call_hide_original_method klass = Class.new { def self.method_x; end } method = ClassMethod.new(klass, :method_x) method.hide_original_method method.define_instance_accessor(:hide_called) method.replace_instance_method(:hide_original_method) { self.hide_called = true } method.stub assert method.hide_called end def test_should_call_define_new_method klass = Class.new { def self.method_x; end } method = ClassMethod.new(klass, :method_x) method.define_instance_accessor(:define_called) method.replace_instance_method(:define_new_method) { self.define_called = true } method.stub assert method.define_called end def test_should_call_remove_new_method klass = Class.new { def self.method_x; end } method = ClassMethod.new(klass, :method_x) mocha = build_mock klass.define_instance_method(:mocha) { mocha } method.replace_instance_method(:reset_mocha) { } method.define_instance_accessor(:remove_called) method.replace_instance_method(:remove_new_method) { self.remove_called = true } method.unstub assert method.remove_called end def test_should_call_restore_original_method klass = Class.new { def self.method_x; end } mocha = build_mock klass.define_instance_method(:mocha) { mocha } method = ClassMethod.new(klass, :method_x) method.replace_instance_method(:reset_mocha) { } method.define_instance_accessor(:restore_called) method.replace_instance_method(:restore_original_method) { self.restore_called = true } method.unstub assert method.restore_called end def test_should_call_mocha_unstub klass = Class.new { def self.method_x; end } method = ClassMethod.new(klass, :method_x) method.replace_instance_method(:restore_original_method) { } mocha = Class.new { class << self; attr_accessor :unstub_method; end; def self.unstub(method); self.unstub_method = method; end; } mocha.define_instance_method(:any_expectations?) { true } method.replace_instance_method(:mock) { mocha } method.unstub assert_equal mocha.unstub_method, :method_x end def test_should_call_stubbee_reset_mocha_if_no_expectations_remaining klass = Class.new { def self.method_x; end } method = ClassMethod.new(klass, :method_x) method.replace_instance_method(:remove_new_method) { } method.replace_instance_method(:restore_original_method) { } mocha = Class.new mocha.define_instance_method(:unstub) { |method_name| } mocha.define_instance_method(:any_expectations?) { false } method.replace_instance_method(:mock) { mocha } stubbee = Class.new { attr_accessor :reset_mocha_called; def reset_mocha; self.reset_mocha_called = true; end; }.new method.replace_instance_method(:stubbee) { stubbee } method.unstub assert stubbee.reset_mocha_called end def test_should_return_mock_for_stubbee mocha = Object.new stubbee = Object.new stubbee.define_instance_accessor(:mocha) { mocha } stubbee.mocha = nil method = ClassMethod.new(stubbee, :method_name) assert_equal stubbee.mocha, method.mock end def test_should_not_match_if_other_object_has_a_different_class class_method = ClassMethod.new(Object.new, :method) other_object = Object.new assert !class_method.matches?(other_object) end def test_should_not_match_if_other_class_method_has_different_stubbee stubbee_1 = Object.new stubbee_2 = Object.new class_method_1 = ClassMethod.new(stubbee_1, :method) class_method_2 = ClassMethod.new(stubbee_2, :method) assert !class_method_1.matches?(class_method_2) end def test_should_not_match_if_other_class_method_has_different_method stubbee = Object.new class_method_1 = ClassMethod.new(stubbee, :method_1) class_method_2 = ClassMethod.new(stubbee, :method_2) assert !class_method_1.matches?(class_method_2) end def test_should_match_if_other_class_method_has_same_stubbee_and_same_method_so_no_attempt_is_made_to_stub_a_method_twice stubbee = Object.new class_method_1 = ClassMethod.new(stubbee, :method) class_method_2 = ClassMethod.new(stubbee, :method) assert class_method_1.matches?(class_method_2) end def test_should_match_if_other_class_method_has_same_stubbee_and_same_method_but_stubbee_equal_method_lies_like_active_record_association_proxy stubbee = Class.new do def equal?(other); false; end end.new class_method_1 = ClassMethod.new(stubbee, :method) class_method_2 = ClassMethod.new(stubbee, :method) assert class_method_1.matches?(class_method_2) end private def build_mock Mock.new(nil) end end mocha-1.3.0/test/unit/state_machine_test.rb0000644000004100000410000000606613155337745021005 0ustar www-datawww-datarequire File.expand_path('../../test_helper', __FILE__) require 'mocha/state_machine' class StateMachineTest < Mocha::TestCase include Mocha def test_should_initially_be_in_no_state state_machine = StateMachine.new('name') any_state.each do |state| assert !state_machine.is(state).active? assert state_machine.is_not(state).active? end end def test_should_be_able_to_enter_a_state state_machine = StateMachine.new('name') state = 'A' other_states = any_state.reject { |s| s == state } state_machine.is(state).activate assert state_machine.is(state).active? assert !state_machine.is_not(state).active? other_states.each do |s| assert !state_machine.is(s).active? assert state_machine.is_not(s).active? end end def test_should_be_able_to_change_state state_machine = StateMachine.new('name') state = 'B' other_states = any_state.reject { |s| s == state } state_machine.is('A').activate state_machine.is(state).activate assert state_machine.is(state).active? assert !state_machine.is_not(state).active? other_states.each do |s| assert !state_machine.is(s).active? assert state_machine.is_not(s).active? end end def test_should_be_put_into_an_initial_state state_machine = StateMachine.new('name') initial_state = 'A' other_states = any_state.reject { |s| s == initial_state } state_machine.starts_as(initial_state) assert state_machine.is(initial_state).active? assert !state_machine.is_not(initial_state).active? other_states.each do |state| assert !state_machine.is(state).active? assert state_machine.is_not(state).active? end end def test_should_be_put_into_a_new_state next_state = 'B' other_states = any_state.reject { |s| s == next_state } state_machine = StateMachine.new('name').starts_as('A') state_machine.become(next_state) assert state_machine.is(next_state).active? assert !state_machine.is_not(next_state).active? other_states.each do |state| assert !state_machine.is(state).active? assert state_machine.is_not(state).active? end end def test_should_describe_itself_as_name_and_current_state state_machine = StateMachine.new('state_machine_name') assert_equal 'state_machine_name has no current state', state_machine.mocha_inspect inspectable_state = Class.new { define_method(:mocha_inspect) { "'inspectable_state'" } }.new state_machine.is(inspectable_state).activate assert_equal "state_machine_name is 'inspectable_state'", state_machine.mocha_inspect end def test_should_have_self_describing_states state_machine = StateMachine.new('state_machine_name') inspectable_state = Class.new { define_method(:mocha_inspect) { "'inspectable_state'" } }.new assert_equal "state_machine_name is 'inspectable_state'", state_machine.is(inspectable_state).mocha_inspect assert_equal "state_machine_name is not 'inspectable_state'", state_machine.is_not(inspectable_state).mocha_inspect end def any_state %w(A B C D) end end mocha-1.3.0/test/unit/central_test.rb0000644000004100000410000000434513155337744017626 0ustar www-datawww-datarequire File.expand_path('../../test_helper', __FILE__) require 'mocha/central' require 'mocha/mock' require 'method_definer' class CentralTest < Mocha::TestCase include Mocha def test_should_start_with_empty_stubba_methods stubba = Central.new assert_equal [], stubba.stubba_methods end def test_should_stub_method_if_not_already_stubbed method = build_mock method.expects(:stub) stubba = Central.new stubba.stub(method) assert method.__verified__? end def test_should_not_stub_method_if_already_stubbed method = build_mock method.stubs(:matches?).returns(true) method.expects(:stub).times(0) stubba = Central.new stubba.stubba_methods = [method] stubba.stub(method) assert method.__verified__? end def test_should_record_method method = build_mock method.expects(:stub) stubba = Central.new stubba.stub(method) assert_equal [method], stubba.stubba_methods end def test_should_unstub_specified_method stubba = Central.new method_1 = build_mock method_1.stubs(:matches?).returns(false) method_2 = build_mock method_2.stubs(:matches?).returns(true) method_2.expects(:unstub) stubba.stubba_methods = [method_1, method_2] stubba.unstub(method_2) assert_equal [method_1], stubba.stubba_methods assert method_2.__verified__? end def test_should_not_unstub_specified_method_if_not_already_stubbed stubba = Central.new method_1 = build_mock method_1.stubs(:matches?).returns(false) method_2 = build_mock method_2.expects(:unstub).never stubba.stubba_methods = [method_1] stubba.unstub(method_2) assert_equal [method_1], stubba.stubba_methods assert method_2.__verified__? end def test_should_unstub_all_methods stubba = Central.new method_1 = build_mock method_1.stubs(:matches?).returns(true) method_1.expects(:unstub) method_2 = build_mock method_2.stubs(:matches?).returns(true) method_2.expects(:unstub) stubba.stubba_methods = [method_1, method_2] stubba.unstub_all assert_equal [], stubba.stubba_methods assert method_1.__verified__? assert method_2.__verified__? end private def build_mock Mock.new(nil) end end mocha-1.3.0/test/unit/string_inspect_test.rb0000644000004100000410000000040313155337745021221 0ustar www-datawww-datarequire File.expand_path('../../test_helper', __FILE__) require 'mocha/inspect' class StringInspectTest < Mocha::TestCase def test_should_use_default_inspect_method string = "my_string" assert_equal %{"my_string"}, string.mocha_inspect end end mocha-1.3.0/test/unit/date_time_inspect_test.rb0000644000004100000410000000103613155337744021650 0ustar www-datawww-datarequire File.expand_path('../../test_helper', __FILE__) require 'mocha/inspect' class DateTimeInspectTest < Mocha::TestCase def test_should_use_include_date_in_seconds time = Time.now assert_equal "#{time.inspect} (#{time.to_f} secs)", time.mocha_inspect end def test_should_use_to_s_for_date date = Date.new(2006, 1, 1) assert_equal date.to_s, date.mocha_inspect end def test_should_use_to_s_for_datetime datetime = DateTime.new(2006, 1, 1) assert_equal datetime.to_s, datetime.mocha_inspect end end mocha-1.3.0/test/unit/in_state_ordering_constraint_test.rb0000644000004100000410000000202413155337744024131 0ustar www-datawww-datarequire File.expand_path('../../test_helper', __FILE__) require 'mocha/in_state_ordering_constraint' class InStateOrderingConstraintTest < Mocha::TestCase include Mocha class FakeStatePredicate attr_writer :active, :description def active? @active end def mocha_inspect @description end end def test_should_allow_invocation_when_state_is_active state_predicate = FakeStatePredicate.new ordering_constraint = InStateOrderingConstraint.new(state_predicate) state_predicate.active = true assert ordering_constraint.allows_invocation_now? state_predicate.active = false assert !ordering_constraint.allows_invocation_now? end def test_should_describe_itself_in_terms_of_the_state_predicates_description state_predicate = FakeStatePredicate.new ordering_constraint = InStateOrderingConstraint.new(state_predicate) state_predicate.description = 'the-state-predicate' assert_equal 'when the-state-predicate', ordering_constraint.mocha_inspect end end mocha-1.3.0/test/unit/change_state_side_effect_test.rb0000644000004100000410000000141513155337744023136 0ustar www-datawww-datarequire File.expand_path('../../test_helper', __FILE__) require 'mocha/change_state_side_effect' class ChangeStateSideEffectTest < Mocha::TestCase include Mocha class FakeState attr_reader :active attr_writer :description def activate @active = true end def mocha_inspect @description end end def test_should_activate_the_given_state state = FakeState.new side_effect = ChangeStateSideEffect.new(state) side_effect.perform assert state.active end def test_should_describe_itself_in_terms_of_the_activated_state state = FakeState.new state.description = 'the-new-state' side_effect = ChangeStateSideEffect.new(state) assert_equal 'then the-new-state', side_effect.mocha_inspect end end mocha-1.3.0/test/unit/hash_inspect_test.rb0000644000004100000410000000061513155337744020642 0ustar www-datawww-datarequire File.expand_path('../../test_helper', __FILE__) require 'mocha/inspect' class HashInspectTest < Mocha::TestCase def test_should_keep_spacing_between_key_value hash = {:a => true} assert_equal '{:a => true}', hash.mocha_inspect end def test_should_use_mocha_inspect_on_each_item hash = {:a => 'mocha'} assert_equal %{{:a => "mocha"}}, hash.mocha_inspect end end mocha-1.3.0/test/unit/hooks_test.rb0000644000004100000410000000125313155337744017314 0ustar www-datawww-datarequire File.expand_path('../../test_helper', __FILE__) require 'mocha/hooks' class HooksTest < Mocha::TestCase class Mocha::Mockery class << self attr_writer :instance end end class FakeMockery def verify(*args) end def teardown raise "exception within Mockery#teardown" end end def test_ensure_mockery_instance_is_reset_even_when_an_exception_is_raised_in_mockery_teardown fake_test_case = Object.new.extend(Mocha::Hooks) original_mockery = FakeMockery.new Mocha::Mockery.instance = original_mockery fake_test_case.mocha_teardown rescue nil assert_not_same Mocha::Mockery.instance, original_mockery end end mocha-1.3.0/test/unit/exception_raiser_test.rb0000644000004100000410000000275513155337744021544 0ustar www-datawww-datarequire File.expand_path('../../test_helper', __FILE__) require 'mocha/exception_raiser' require 'timeout' class ExceptionRaiserTest < Mocha::TestCase include Mocha def test_should_raise_exception_with_specified_class_and_default_message exception_class = Class.new(StandardError) raiser = ExceptionRaiser.new(exception_class, nil) exception = assert_raises(exception_class) { raiser.evaluate } assert_equal exception_class.to_s, exception.message end def test_should_raise_exception_with_specified_class_and_message exception_class = Class.new(StandardError) raiser = ExceptionRaiser.new(exception_class, 'message') exception = assert_raises(exception_class) { raiser.evaluate } assert_equal 'message', exception.message end def test_should_raise_exception_instance exception_class = Class.new(StandardError) raiser = ExceptionRaiser.new(exception_class.new('message'), nil) exception = assert_raises(exception_class) { raiser.evaluate } assert_equal 'message', exception.message end def test_should_raise_interrupt_exception_with_default_message_so_it_works_in_ruby_1_8_6 raiser = ExceptionRaiser.new(Interrupt, nil) assert_raises(Interrupt) { raiser.evaluate } end def test_should_raise_subclass_of_interrupt_exception_with_default_message_so_it_works_in_ruby_1_8_6 exception_class = Class.new(Interrupt) raiser = ExceptionRaiser.new(exception_class, nil) assert_raises(exception_class) { raiser.evaluate } end end mocha-1.3.0/test/unit/receivers_test.rb0000644000004100000410000000327713155337745020171 0ustar www-datawww-datarequire File.expand_path('../../test_helper', __FILE__) require 'mocha/receivers' class ObjectReceiverTest < Mocha::TestCase include Mocha class FakeObject < Struct.new(:mocha) def is_a?(klass) false end end class FakeClass < Struct.new(:superclass, :mocha) def is_a?(klass) klass == Class end end def test_mocks_returns_mock_for_object object = FakeObject.new(:mocha) receiver = ObjectReceiver.new(object) assert_equal [:mocha], receiver.mocks end def test_mocks_returns_mocks_for_class_and_its_superclasses grandparent = FakeClass.new(nil, :grandparent_mocha) parent = FakeClass.new(grandparent, :parent_mocha) klass = FakeClass.new(parent, :mocha) receiver = ObjectReceiver.new(klass) assert_equal [:mocha, :parent_mocha, :grandparent_mocha], receiver.mocks end end class AnyInstanceReceiverTest < Mocha::TestCase include Mocha class FakeAnyInstanceClass attr_reader :superclass def initialize(superclass, mocha) @superclass, @mocha = superclass, mocha end def any_instance Struct.new(:mocha).new(@mocha) end end def test_mocks_returns_mocks_for_class_and_its_superclasses grandparent = FakeAnyInstanceClass.new(nil, :grandparent_mocha) parent = FakeAnyInstanceClass.new(grandparent, :parent_mocha) klass = FakeAnyInstanceClass.new(parent, :mocha) receiver = AnyInstanceReceiver.new(klass) assert_equal [:mocha, :parent_mocha, :grandparent_mocha], receiver.mocks end end class DefaultReceiverTest < Mocha::TestCase include Mocha def test_mocks_returns_mock mock = :mocha receiver = DefaultReceiver.new(mock) assert_equal [:mocha], receiver.mocks end end mocha-1.3.0/test/unit/yield_parameters_test.rb0000644000004100000410000000717413155337745021533 0ustar www-datawww-datarequire File.expand_path('../../test_helper', __FILE__) require 'mocha/yield_parameters' require 'mocha/no_yields' require 'mocha/single_yield' require 'mocha/multiple_yields' class YieldParametersTest < Mocha::TestCase include Mocha def test_should_return_null_yield_parameter_group_by_default yield_parameters = YieldParameters.new assert yield_parameters.next_invocation.is_a?(NoYields) end def test_should_return_single_yield_parameter_group yield_parameters = YieldParameters.new yield_parameters.add(1, 2, 3) parameter_group = yield_parameters.next_invocation assert parameter_group.is_a?(SingleYield) assert_equal [1, 2, 3], parameter_group.parameters end def test_should_keep_returning_single_yield_parameter_group yield_parameters = YieldParameters.new yield_parameters.add(1, 2, 3) yield_parameters.next_invocation parameter_group = yield_parameters.next_invocation assert parameter_group.is_a?(SingleYield) assert_equal [1, 2, 3], parameter_group.parameters parameter_group = yield_parameters.next_invocation assert parameter_group.is_a?(SingleYield) assert_equal [1, 2, 3], parameter_group.parameters end def test_should_return_consecutive_single_yield_parameter_groups yield_parameters = YieldParameters.new yield_parameters.add(1, 2, 3) yield_parameters.add(4, 5) parameter_group = yield_parameters.next_invocation assert parameter_group.is_a?(SingleYield) assert_equal [1, 2, 3], parameter_group.parameters parameter_group = yield_parameters.next_invocation assert parameter_group.is_a?(SingleYield) assert_equal [4, 5], parameter_group.parameters end def test_should_return_multiple_yield_parameter_group yield_parameters = YieldParameters.new yield_parameters.multiple_add([1, 2, 3], [4, 5]) parameter_group = yield_parameters.next_invocation assert parameter_group.is_a?(MultipleYields) assert_equal [[1, 2, 3], [4, 5]], parameter_group.parameter_groups end def test_should_keep_returning_multiple_yield_parameter_group yield_parameters = YieldParameters.new yield_parameters.multiple_add([1, 2, 3], [4, 5]) yield_parameters.next_invocation parameter_group = yield_parameters.next_invocation assert parameter_group.is_a?(MultipleYields) assert_equal [[1, 2, 3], [4, 5]], parameter_group.parameter_groups parameter_group = yield_parameters.next_invocation assert parameter_group.is_a?(MultipleYields) assert_equal [[1, 2, 3], [4, 5]], parameter_group.parameter_groups end def test_should_return_consecutive_multiple_yield_parameter_groups yield_parameters = YieldParameters.new yield_parameters.multiple_add([1, 2, 3], [4, 5]) yield_parameters.multiple_add([6, 7], [8, 9, 0]) parameter_group = yield_parameters.next_invocation assert parameter_group.is_a?(MultipleYields) assert_equal [[1, 2, 3], [4, 5]], parameter_group.parameter_groups parameter_group = yield_parameters.next_invocation assert parameter_group.is_a?(MultipleYields) assert_equal [[6, 7], [8, 9, 0]], parameter_group.parameter_groups end def test_should_return_consecutive_single_and_multiple_yield_parameter_groups yield_parameters = YieldParameters.new yield_parameters.add(1, 2, 3) yield_parameters.multiple_add([4, 5, 6], [7, 8]) parameter_group = yield_parameters.next_invocation assert parameter_group.is_a?(SingleYield) assert_equal [1, 2, 3], parameter_group.parameters parameter_group = yield_parameters.next_invocation assert parameter_group.is_a?(MultipleYields) assert_equal [[4, 5, 6], [7, 8]], parameter_group.parameter_groups end end mocha-1.3.0/test/unit/module_methods_test.rb0000644000004100000410000000073413155337744021204 0ustar www-datawww-datarequire File.expand_path('../../test_helper', __FILE__) require 'mocha/module_methods' require 'mocha/object_methods' class ModuleMethodsTest < Mocha::TestCase def setup @module = Module.new.extend(Mocha::ModuleMethods, Mocha::ObjectMethods) end def test_should_use_stubba_module_method_for_module assert_equal Mocha::ModuleMethod, @module.stubba_method end def test_should_stub_self_for_module assert_equal @module, @module.stubba_object end end mocha-1.3.0/test/unit/class_methods_test.rb0000644000004100000410000000215513155337744021023 0ustar www-datawww-datarequire File.expand_path('../../test_helper', __FILE__) require 'mocha/class_methods' require 'mocha/object_methods' class ClassMethodsTest < Mocha::TestCase def setup @klass = Class.new.extend(Mocha::ClassMethods, Mocha::ObjectMethods) end def test_should_build_any_instance_object any_instance = @klass.any_instance assert_not_nil any_instance assert any_instance.is_a?(Mocha::ClassMethods::AnyInstance) end def test_should_return_same_any_instance_object any_instance_1 = @klass.any_instance any_instance_2 = @klass.any_instance assert_equal any_instance_1, any_instance_2 end def test_should_use_stubba_class_method_for_class assert_equal Mocha::ClassMethod, @klass.stubba_method end def test_should_use_stubba_class_method_for_any_instance assert_equal Mocha::AnyInstanceMethod, @klass.any_instance.stubba_method end def test_should_stub_self_for_class assert_equal @klass, @klass.stubba_object end def test_should_stub_relevant_class_for_any_instance any_instance = @klass.any_instance assert_equal @klass, any_instance.stubba_object end end mocha-1.3.0/test/unit/sequence_test.rb0000644000004100000410000000725513155337745020012 0ustar www-datawww-datarequire File.expand_path('../../test_helper', __FILE__) require 'mocha/sequence' require 'mocha/expectation' class SequenceTest < Mocha::TestCase include Mocha class FakeExpectation attr_reader :ordering_constraints def initialize(satisfied = false) @satisfied = satisfied @ordering_constraints = [] end def add_ordering_constraint(ordering_constraint) @ordering_constraints << ordering_constraint end def satisfied? @satisfied end end def test_should_be_satisfied_if_no_expectations_added sequence = Sequence.new('name') assert sequence.satisfied_to_index?(0) end def test_should_be_satisfied_if_one_unsatisfied_expectations_added_but_it_is_not_included_by_index sequence = Sequence.new('name') expectation = FakeExpectation.new(false) sequence.constrain_as_next_in_sequence(expectation) assert sequence.satisfied_to_index?(0) end def test_should_not_be_satisfied_if_one_unsatisfied_expectations_added_and_it_is_included_by_index sequence = Sequence.new('name') expectation = FakeExpectation.new(false) sequence.constrain_as_next_in_sequence(expectation) assert !sequence.satisfied_to_index?(1) end def test_should_be_satisfied_if_one_satisfied_expectations_added_and_it_is_included_by_index sequence = Sequence.new('name') expectation = FakeExpectation.new(true) sequence.constrain_as_next_in_sequence(expectation) assert sequence.satisfied_to_index?(1) end def test_should_not_be_satisfied_if_one_satisfied_and_one_unsatisfied_expectation_added_and_both_are_included_by_index sequence = Sequence.new('name') expectation_one = FakeExpectation.new(true) expectation_two = FakeExpectation.new(false) sequence.constrain_as_next_in_sequence(expectation_one) sequence.constrain_as_next_in_sequence(expectation_two) assert !sequence.satisfied_to_index?(2) end def test_should_be_satisfied_if_two_satisfied_expectations_added_and_both_are_included_by_index sequence = Sequence.new('name') expectation_one = FakeExpectation.new(true) expectation_two = FakeExpectation.new(true) sequence.constrain_as_next_in_sequence(expectation_one) sequence.constrain_as_next_in_sequence(expectation_two) assert sequence.satisfied_to_index?(2) end def test_should_add_ordering_constraint_to_expectation sequence = Sequence.new('name') expectation = FakeExpectation.new sequence.constrain_as_next_in_sequence(expectation) assert_equal 1, expectation.ordering_constraints.length end def test_should_not_allow_invocation_of_second_method_when_first_n_sequence_has_not_been_invoked sequence = Sequence.new('name') expectation_one = FakeExpectation.new(false) expectation_two = FakeExpectation.new(false) sequence.constrain_as_next_in_sequence(expectation_one) sequence.constrain_as_next_in_sequence(expectation_two) assert !expectation_two.ordering_constraints[0].allows_invocation_now? end def test_should_allow_invocation_of_second_method_when_first_in_sequence_has_been_invoked sequence = Sequence.new('name') expectation_one = FakeExpectation.new(true) expectation_two = FakeExpectation.new(false) sequence.constrain_as_next_in_sequence(expectation_one) sequence.constrain_as_next_in_sequence(expectation_two) assert expectation_two.ordering_constraints[0].allows_invocation_now? end def test_should_describe_ordering_constraint_as_being_part_of_named_sequence sequence = Sequence.new('wibble') expectation = FakeExpectation.new sequence.constrain_as_next_in_sequence(expectation) assert_equal %{in sequence "wibble"}, expectation.ordering_constraints[0].mocha_inspect end end mocha-1.3.0/test/unit/configuration_test.rb0000644000004100000410000000255213155337744021043 0ustar www-datawww-datarequire File.expand_path('../../test_helper', __FILE__) require "mocha/configuration" class ConfigurationTest < Mocha::TestCase def test_allow_temporarily_changes_config_when_given_block Mocha::Configuration.warn_when(:stubbing_method_unnecessarily) yielded = false Mocha::Configuration.allow(:stubbing_method_unnecessarily) do yielded = true assert Mocha::Configuration.allow?(:stubbing_method_unnecessarily) end assert yielded assert Mocha::Configuration.warn_when?(:stubbing_method_unnecessarily) end def test_prevent_temporarily_changes_config_when_given_block Mocha::Configuration.allow(:stubbing_method_unnecessarily) yielded = false Mocha::Configuration.prevent(:stubbing_method_unnecessarily) do yielded = true assert Mocha::Configuration.prevent?(:stubbing_method_unnecessarily) end assert yielded assert Mocha::Configuration.allow?(:stubbing_method_unnecessarily) end def test_warn_when_temporarily_changes_config_when_given_block Mocha::Configuration.allow(:stubbing_method_unnecessarily) yielded = false Mocha::Configuration.warn_when(:stubbing_method_unnecessarily) do yielded = true assert Mocha::Configuration.warn_when?(:stubbing_method_unnecessarily) end assert yielded assert Mocha::Configuration.allow?(:stubbing_method_unnecessarily) end end mocha-1.3.0/test/unit/expectation_test.rb0000644000004100000410000004133613155337744020522 0ustar www-datawww-datarequire File.expand_path('../../test_helper', __FILE__) require 'method_definer' require 'mocha/expectation' require 'mocha/sequence' require 'execution_point' require 'simple_counter' class ExpectationTest < Mocha::TestCase include Mocha def new_expectation Expectation.new(nil, :expected_method) end def test_should_match_calls_to_same_method_with_any_parameters assert new_expectation.match?(:expected_method, 1, 2, 3) end def test_should_match_calls_to_same_method_with_exactly_zero_parameters expectation = new_expectation.with() assert expectation.match?(:expected_method) end def test_should_not_match_calls_to_same_method_with_more_than_zero_parameters expectation = new_expectation.with() assert !expectation.match?(:expected_method, 1, 2, 3) end def test_should_match_calls_to_same_method_with_expected_parameter_values expectation = new_expectation.with(1, 2, 3) assert expectation.match?(:expected_method, 1, 2, 3) end def test_should_match_calls_to_same_method_with_parameters_constrained_as_expected expectation = new_expectation.with() {|x, y, z| x + y == z} assert expectation.match?(:expected_method, 1, 2, 3) end def test_should_not_match_calls_to_different_method_with_parameters_constrained_as_expected expectation = new_expectation.with() {|x, y, z| x + y == z} assert !expectation.match?(:different_method, 1, 2, 3) end def test_should_not_match_calls_to_different_methods_with_no_parameters assert !new_expectation.match?(:unexpected_method) end def test_should_not_match_calls_to_same_method_with_too_few_parameters expectation = new_expectation.with(1, 2, 3) assert !expectation.match?(:unexpected_method, 1, 2) end def test_should_not_match_calls_to_same_method_with_too_many_parameters expectation = new_expectation.with(1, 2) assert !expectation.match?(:unexpected_method, 1, 2, 3) end def test_should_not_match_calls_to_same_method_with_unexpected_parameter_values expectation = new_expectation.with(1, 2, 3) assert !expectation.match?(:unexpected_method, 1, 0, 3) end def test_should_not_match_calls_to_same_method_with_parameters_not_constrained_as_expected expectation = new_expectation.with() {|x, y, z| x + y == z} assert !expectation.match?(:expected_method, 1, 0, 3) end def test_should_allow_invocations_until_expected_invocation_count_is_one_and_actual_invocation_count_would_be_two expectation = new_expectation.times(1) assert expectation.invocations_allowed? expectation.invoke assert !expectation.invocations_allowed? end def test_should_allow_invocations_until_expected_invocation_count_is_two_and_actual_invocation_count_would_be_three expectation = new_expectation.times(2) assert expectation.invocations_allowed? expectation.invoke assert expectation.invocations_allowed? expectation.invoke assert !expectation.invocations_allowed? end def test_should_allow_invocations_until_expected_invocation_count_is_a_range_from_two_to_three_and_actual_invocation_count_would_be_four expectation = new_expectation.times(2..3) assert expectation.invocations_allowed? expectation.invoke assert expectation.invocations_allowed? expectation.invoke assert expectation.invocations_allowed? expectation.invoke assert !expectation.invocations_allowed? end def test_should_store_provided_backtrace backtrace = Object.new expectation = Expectation.new(nil, :expected_method, backtrace) assert_equal backtrace, expectation.backtrace end def test_should_default_backtrace_to_caller execution_point = ExecutionPoint.current; expectation = Expectation.new(nil, :expected_method) assert_equal execution_point, ExecutionPoint.new(expectation.backtrace) end def test_should_not_yield yielded = false new_expectation.invoke() { yielded = true } assert_equal false, yielded end def test_should_yield_no_parameters expectation = new_expectation().yields() yielded_parameters = nil expectation.invoke() { |*parameters| yielded_parameters = parameters } assert_equal Array.new, yielded_parameters end def test_should_yield_with_specified_parameters expectation = new_expectation().yields(1, 2, 3) yielded_parameters = nil expectation.invoke() { |*parameters| yielded_parameters = parameters } assert_equal [1, 2, 3], yielded_parameters end def test_should_yield_different_parameters_on_consecutive_invocations expectation = new_expectation().yields(1, 2, 3).yields(4, 5) yielded_parameters = [] expectation.invoke() { |*parameters| yielded_parameters << parameters } expectation.invoke() { |*parameters| yielded_parameters << parameters } assert_equal [[1, 2, 3], [4, 5]], yielded_parameters end def test_should_yield_multiple_times_for_single_invocation expectation = new_expectation().multiple_yields([1, 2, 3], [4, 5]) yielded_parameters = [] expectation.invoke() { |*parameters| yielded_parameters << parameters } assert_equal [[1, 2, 3], [4, 5]], yielded_parameters end def test_should_yield_multiple_times_for_first_invocation_and_once_for_second_invocation expectation = new_expectation().multiple_yields([1, 2, 3], [4, 5]).then.yields(6, 7) yielded_parameters = [] expectation.invoke() { |*parameters| yielded_parameters << parameters } expectation.invoke() { |*parameters| yielded_parameters << parameters } assert_equal [[1, 2, 3], [4, 5], [6, 7]], yielded_parameters end def test_should_return_specified_value expectation = new_expectation.returns(99) assert_equal 99, expectation.invoke end def test_should_return_same_specified_value_multiple_times expectation = new_expectation.returns(99) assert_equal 99, expectation.invoke assert_equal 99, expectation.invoke end def test_should_return_specified_values_on_consecutive_calls expectation = new_expectation.returns(99, 100, 101) assert_equal 99, expectation.invoke assert_equal 100, expectation.invoke assert_equal 101, expectation.invoke end def test_should_return_specified_values_on_consecutive_calls_even_if_values_are_modified values = [99, 100, 101] expectation = new_expectation.returns(*values) values.shift assert_equal 99, expectation.invoke assert_equal 100, expectation.invoke assert_equal 101, expectation.invoke end def test_should_return_nil_by_default assert_nil new_expectation.invoke end def test_should_return_nil_if_no_value_specified expectation = new_expectation.returns() assert_nil expectation.invoke end def test_should_raise_runtime_exception expectation = new_expectation.raises assert_raise(RuntimeError) { expectation.invoke } end def test_should_raise_custom_exception exception = Class.new(Exception) expectation = new_expectation.raises(exception) assert_raise(exception) { expectation.invoke } end def test_should_raise_same_instance_of_custom_exception exception_klass = Class.new(StandardError) expected_exception = exception_klass.new expectation = new_expectation.raises(expected_exception) actual_exception = assert_raise(exception_klass) { expectation.invoke } assert_same expected_exception, actual_exception end def test_should_use_the_default_exception_message expectation = new_expectation.raises(Exception) exception = assert_raise(Exception) { expectation.invoke } assert_equal Exception.new.message, exception.message end def test_should_raise_custom_exception_with_message exception_msg = "exception message" expectation = new_expectation.raises(Exception, exception_msg) exception = assert_raise(Exception) { expectation.invoke } assert_equal exception_msg, exception.message end def test_should_return_values_then_raise_exception expectation = new_expectation.returns(1, 2).then.raises() assert_equal 1, expectation.invoke assert_equal 2, expectation.invoke assert_raise(RuntimeError) { expectation.invoke } end def test_should_raise_exception_then_return_values expectation = new_expectation.raises().then.returns(1, 2) assert_raise(RuntimeError) { expectation.invoke } assert_equal 1, expectation.invoke assert_equal 2, expectation.invoke end def test_should_verify_successfully_if_expected_call_was_made expectation = new_expectation expectation.invoke assert expectation.verified? end def test_should_not_verify_successfully_if_call_expected_once_but_invoked_twice expectation = new_expectation.once expectation.invoke expectation.invoke assert !expectation.verified? end def test_should_not_verify_successfully_if_call_expected_once_but_not_invoked expectation = new_expectation.once assert !expectation.verified? end def test_should_verify_successfully_if_call_expected_once_and_invoked_once expectation = new_expectation.once expectation.invoke assert expectation.verified? end def test_should_not_verify_successfully_if_call_expected_twice_and_invoked_three_times expectation = new_expectation.twice expectation.invoke expectation.invoke expectation.invoke assert !expectation.verified? end def test_should_not_verify_successfully_if_call_expected_twice_but_invoked_once expectation = new_expectation.twice expectation.invoke assert !expectation.verified? end def test_should_verify_successfully_if_call_expected_twice_and_invoked_twice expectation = new_expectation.twice expectation.invoke expectation.invoke assert expectation.verified? end def test_should_verify_successfully_if_expected_call_was_made_at_least_once expectation = new_expectation.at_least_once 3.times {expectation.invoke} assert expectation.verified? end def test_should_not_verify_successfully_if_expected_call_was_not_made_at_least_once expectation = new_expectation.with(1, 2, 3).at_least_once assert !expectation.verified? assert_match(/expected at least once, not yet invoked/i, expectation.mocha_inspect) end def test_should_verify_successfully_if_expected_call_was_made_expected_number_of_times expectation = new_expectation.times(2) 2.times {expectation.invoke} assert expectation.verified? end def test_should_not_verify_successfully_if_expected_call_was_made_too_few_times expectation = new_expectation.times(2) 1.times {expectation.invoke} assert !expectation.verified? assert_match(/expected exactly twice, invoked once/i, expectation.mocha_inspect) end def test_should_not_verify_successfully_if_expected_call_was_made_too_many_times expectation = new_expectation.times(2) 3.times {expectation.invoke} assert !expectation.verified? end def test_should_increment_assertion_counter_for_expectation_because_it_does_need_verifyng expectation = new_expectation expectation.invoke assertion_counter = SimpleCounter.new expectation.verified?(assertion_counter) assert_equal 1, assertion_counter.count end def test_should_not_increment_assertion_counter_for_stub_because_it_does_not_need_verifying stub = Expectation.new(nil, :expected_method).at_least(0) assertion_counter = SimpleCounter.new stub.verified?(assertion_counter) assert_equal 0, assertion_counter.count end def test_should_store_backtrace_from_point_where_expectation_was_created execution_point = ExecutionPoint.current; expectation = Expectation.new(nil, :expected_method) assert_equal execution_point, ExecutionPoint.new(expectation.backtrace) end class FakeMock def initialize(name) @name = name end def mocha_inspect @name end end def test_should_raise_error_with_message_indicating_which_method_was_expected_to_be_called_on_which_mock_object_with_which_parameters_and_in_what_sequences mock = FakeMock.new('mock') sequence_one = Sequence.new('one') sequence_two = Sequence.new('two') expectation = Expectation.new(mock, :expected_method).with(1, 2, {'a' => true}, {:b => false}, [1, 2, 3]).in_sequence(sequence_one, sequence_two) assert !expectation.verified? assert_match %{mock.expected_method(1, 2, {"a" => true}, {:b => false}, [1, 2, 3]); in sequence "one"; in sequence "two"}, expectation.mocha_inspect end class FakeConstraint def initialize(allows_invocation_now) @allows_invocation_now = allows_invocation_now end def allows_invocation_now? @allows_invocation_now end end def test_should_be_in_correct_order_if_all_ordering_constraints_allow_invocation_now constraint_one = FakeConstraint.new(allows_invocation_now = true) constraint_two = FakeConstraint.new(allows_invocation_now = true) expectation = Expectation.new(nil, :method_one) expectation.add_ordering_constraint(constraint_one) expectation.add_ordering_constraint(constraint_two) assert expectation.in_correct_order? end def test_should_not_be_in_correct_order_if_one_ordering_constraint_does_not_allow_invocation_now constraint_one = FakeConstraint.new(allows_invocation_now = true) constraint_two = FakeConstraint.new(allows_invocation_now = false) expectation = Expectation.new(nil, :method_one) expectation.add_ordering_constraint(constraint_one) expectation.add_ordering_constraint(constraint_two) assert !expectation.in_correct_order? end def test_should_match_if_all_ordering_constraints_allow_invocation_now constraint_one = FakeConstraint.new(allows_invocation_now = true) constraint_two = FakeConstraint.new(allows_invocation_now = true) expectation = Expectation.new(nil, :method_one) expectation.add_ordering_constraint(constraint_one) expectation.add_ordering_constraint(constraint_two) assert expectation.match?(:method_one) end def test_should_not_match_if_one_ordering_constraints_does_not_allow_invocation_now constraint_one = FakeConstraint.new(allows_invocation_now = true) constraint_two = FakeConstraint.new(allows_invocation_now = false) expectation = Expectation.new(nil, :method_one) expectation.add_ordering_constraint(constraint_one) expectation.add_ordering_constraint(constraint_two) assert !expectation.match?(:method_one) end def test_should_not_be_satisfied_when_required_invocation_has_not_been_made expectation = Expectation.new(nil, :method_one).times(1) assert !expectation.satisfied? end def test_should_be_satisfied_when_required_invocation_has_been_made expectation = Expectation.new(nil, :method_one).times(1) expectation.invoke assert expectation.satisfied? end def test_should_not_be_satisfied_when_minimum_number_of_invocations_has_not_been_made expectation = Expectation.new(nil, :method_one).at_least(2) expectation.invoke assert !expectation.satisfied? end def test_should_be_satisfied_when_minimum_number_of_invocations_has_been_made expectation = Expectation.new(nil, :method_one).at_least(2) 2.times { expectation.invoke } assert expectation.satisfied? end class FakeSequence attr_reader :expectations def initialize @expectations = [] end def constrain_as_next_in_sequence(expectation) @expectations << expectation end end def test_should_tell_sequences_to_constrain_expectation_as_next_in_sequence sequence_one = FakeSequence.new sequence_two = FakeSequence.new expectation = Expectation.new(nil, :method_one) assert_equal expectation, expectation.in_sequence(sequence_one, sequence_two) assert_equal [expectation], sequence_one.expectations assert_equal [expectation], sequence_two.expectations end class FakeState def initialize @active = false end def activate @active = true end def active? @active end end def test_should_change_state_when_expectation_is_invoked state = FakeState.new expectation = Expectation.new(nil, :method_one) expectation.then(state) expectation.invoke assert state.active? end def test_should_match_when_state_is_active state = FakeState.new expectation = Expectation.new(nil, :method_one) expectation.when(state) assert !expectation.match?(:method_one) state.activate assert expectation.match?(:method_one) end def test_should_include_default_representation_of_object_in_inspect object = Object.new class << object define_method(:inspect) { 'mock' } end expectation = Expectation.new(object, :method_one) assert_match Regexp.new("^#$"), expectation.inspect end def test_should_include_output_of_mocha_inspect_in_inspect object = Object.new class << object define_method(:inspect) { 'mock' } end expectation = Expectation.new(object, :method_one) assert expectation.inspect.include?(expectation.mocha_inspect) end end mocha-1.3.0/test/unit/mock_test.rb0000644000004100000410000002436113155337744017127 0ustar www-datawww-datarequire File.expand_path('../../test_helper', __FILE__) require 'mocha/ruby_version' require 'mocha/mock' require 'mocha/expectation_error_factory' require 'set' require 'simple_counter' class MockTest < Mocha::TestCase include Mocha def test_should_set_single_expectation mock = build_mock mock.expects(:method1).returns(1) assert_nothing_raised(ExpectationErrorFactory.exception_class) do assert_equal 1, mock.method1 end end def test_should_build_and_store_expectations mock = build_mock expectation = mock.expects(:method1) assert_not_nil expectation assert_equal [expectation], mock.__expectations__.to_a end def test_should_not_stub_everything_by_default mock = build_mock assert_equal false, mock.everything_stubbed end def test_should_stub_everything mock = build_mock mock.stub_everything assert_equal true, mock.everything_stubbed end def test_should_be_able_to_extend_mock_object_with_module mock = build_mock assert_nothing_raised(ExpectationErrorFactory.exception_class) { mock.extend(Module.new) } end def test_should_be_equal mock = build_mock assert_equal true, mock.eql?(mock) end if PRE_RUBY_V19 OBJECT_METHODS = STANDARD_OBJECT_PUBLIC_INSTANCE_METHODS.reject { |m| m =~ /^__.*__$/ || ["method_missing", "singleton_method_undefined", "initialize"].include?(m)} else OBJECT_METHODS = STANDARD_OBJECT_PUBLIC_INSTANCE_METHODS.reject { |m| m =~ /^__.*__$/ || [:object_id, :method_missing, :singleton_method_undefined, :initialize, :String, :singleton_method_added].include?(m) } end def test_should_be_able_to_mock_standard_object_methods mock = build_mock OBJECT_METHODS.each { |method| mock.__expects__(method.to_sym).returns(method) } OBJECT_METHODS.each { |method| assert_equal method, mock.__send__(method.to_sym) } assert mock.__verified__? end def test_should_be_able_to_stub_standard_object_methods mock = build_mock OBJECT_METHODS.each { |method| mock.__stubs__(method.to_sym).returns(method) } OBJECT_METHODS.each { |method| assert_equal method, mock.__send__(method.to_sym) } end def test_should_create_and_add_expectations mock = build_mock expectation1 = mock.expects(:method1) expectation2 = mock.expects(:method2) assert_equal [expectation1, expectation2].to_set, mock.__expectations__.to_set end def test_should_pass_backtrace_into_expectation mock = build_mock backtrace = Object.new expectation = mock.expects(:method1, backtrace) assert_equal backtrace, expectation.backtrace end def test_should_pass_backtrace_into_stub mock = build_mock backtrace = Object.new stub = mock.stubs(:method1, backtrace) assert_equal backtrace, stub.backtrace end def test_should_create_and_add_stubs mock = build_mock stub1 = mock.stubs(:method1) stub2 = mock.stubs(:method2) assert_equal [stub1, stub2].to_set, mock.__expectations__.to_set end def test_should_invoke_expectation_and_return_result mock = build_mock mock.expects(:my_method).returns(:result) result = mock.my_method assert_equal :result, result end def test_should_not_raise_error_if_stubbing_everything mock = build_mock mock.stub_everything result = nil assert_nothing_raised(ExpectationErrorFactory.exception_class) do result = mock.unexpected_method end assert_nil result end def test_should_raise_assertion_error_for_unexpected_method_call mock = build_mock error = assert_raise(ExpectationErrorFactory.exception_class) do mock.unexpected_method_called(:my_method, :argument1, :argument2) end assert_match(/unexpected invocation/, error.message) assert_match(/my_method/, error.message) assert_match(/argument1/, error.message) assert_match(/argument2/, error.message) end def test_should_not_verify_successfully_because_not_all_expectations_have_been_satisfied mock = build_mock mock.expects(:method1) mock.expects(:method2) mock.method1 assert !mock.__verified__? end def test_should_increment_assertion_counter_for_every_verified_expectation mock = build_mock mock.expects(:method1) mock.method1 mock.expects(:method2) mock.method2 assertion_counter = SimpleCounter.new mock.__verified__?(assertion_counter) assert_equal 2, assertion_counter.count end def test_should_yield_supplied_parameters_to_block mock = build_mock parameters_for_yield = [1, 2, 3] mock.expects(:method1).yields(*parameters_for_yield) yielded_parameters = nil mock.method1() { |*parameters| yielded_parameters = parameters } assert_equal parameters_for_yield, yielded_parameters end def test_should_set_up_multiple_expectations_with_return_values mock = build_mock mock.expects(:method1 => :result1, :method2 => :result2) assert_equal :result1, mock.method1 assert_equal :result2, mock.method2 end def test_should_set_up_multiple_stubs_with_return_values mock = build_mock mock.stubs(:method1 => :result1, :method2 => :result2) assert_equal :result1, mock.method1 assert_equal :result2, mock.method2 end def test_should_keep_returning_specified_value_for_stubs mock = build_mock mock.stubs(:method1).returns(1) assert_equal 1, mock.method1 assert_equal 1, mock.method1 end def test_should_keep_returning_specified_value_for_expects mock = build_mock mock.expects(:method1).times(2).returns(1) assert_equal 1, mock.method1 assert_equal 1, mock.method1 end def test_should_match_most_recent_call_to_expects mock = build_mock mock.expects(:method1).returns(0) mock.expects(:method1).returns(1) assert_equal 1, mock.method1 end def test_should_match_most_recent_call_to_stubs mock = build_mock mock.stubs(:method1).returns(0) mock.stubs(:method1).returns(1) assert_equal 1, mock.method1 end def test_should_match_most_recent_call_to_stubs_or_expects mock = build_mock mock.stubs(:method1).returns(0) mock.expects(:method1).returns(1) assert_equal 1, mock.method1 end def test_should_match_most_recent_call_to_expects_or_stubs mock = build_mock mock.expects(:method1).returns(0) mock.stubs(:method1).returns(1) assert_equal 1, mock.method1 end def test_should_respond_to_expected_method mock = build_mock mock.expects(:method1) assert_equal true, mock.respond_to?(:method1) end def test_should_respond_to_expected_method_as_string mock = build_mock mock.expects(:method1) assert_equal true, mock.respond_to?('method1') end def test_should_not_respond_to_unexpected_method mock = build_mock assert_equal false, mock.respond_to?(:method1) end def test_should_respond_to_methods_which_the_responder_does_responds_to instance = Class.new do define_method(:respond_to?) { |symbol| true } end.new mock = build_mock mock.responds_like(instance) assert_equal true, mock.respond_to?(:invoked_method) end def test_should_not_respond_to_methods_which_the_responder_does_not_responds_to instance = Class.new do define_method(:respond_to?) { |symbol| false } end.new mock = build_mock mock.responds_like(instance) assert_equal false, mock.respond_to?(:invoked_method) end def test_should_respond_to_methods_which_the_responder_instance_does_responds_to klass = Class.new do define_method(:respond_to?) { |symbol| true } end mock = build_mock mock.responds_like_instance_of(klass) assert_equal true, mock.respond_to?(:invoked_method) end def test_should_not_respond_to_methods_which_the_responder_instance_does_not_responds_to klass = Class.new do define_method(:respond_to?) { |symbol| false } end mock = build_mock mock.responds_like_instance_of(klass) assert_equal false, mock.respond_to?(:invoked_method) end def test_respond_like_should_return_itself_to_allow_method_chaining mock = build_mock assert_same mock.responds_like(Object.new), mock end def test_respond_like_instance_of_should_return_itself_to_allow_method_chaining mock = build_mock assert_same mock.responds_like_instance_of(Object), mock end def test_should_not_raise_no_method_error_if_mock_is_not_restricted_to_respond_like_a_responder mock = build_mock mock.stubs(:invoked_method) assert_nothing_raised(NoMethodError) { mock.invoked_method } end def test_should_not_raise_no_method_error_if_responder_does_respond_to_invoked_method instance = Class.new do define_method(:respond_to?) { |symbol| true } end.new mock = build_mock mock.responds_like(instance) mock.stubs(:invoked_method) assert_nothing_raised(NoMethodError) { mock.invoked_method } end def test_should_raise_no_method_error_if_responder_does_not_respond_to_invoked_method instance = Class.new do define_method(:respond_to?) { |symbol| false } define_method(:mocha_inspect) { 'mocha_inspect' } end.new mock = build_mock mock.responds_like(instance) mock.stubs(:invoked_method) assert_raises(NoMethodError) { mock.invoked_method } end def test_should_raise_no_method_error_with_message_indicating_that_mock_is_constrained_to_respond_like_responder instance = Class.new do define_method(:respond_to?) { |symbol| false } define_method(:mocha_inspect) { 'mocha_inspect' } end.new mock = build_mock mock.responds_like(instance) mock.stubs(:invoked_method) begin mock.invoked_method rescue NoMethodError => e assert_match(/which responds like mocha_inspect/, e.message) end end def test_should_handle_respond_to_with_private_methods_param_without_error mock = build_mock assert_nothing_raised { mock.respond_to?(:object_id, false) } end def test_should_respond_to_any_method_if_stubbing_everything mock = build_mock mock.stub_everything assert mock.respond_to?(:abc) assert mock.respond_to?(:xyz) end def test_should_remove_expectation_for_unstubbed_method mock = build_mock mock.expects(:method1) mock.unstub(:method1) e = assert_raises(ExpectationErrorFactory.exception_class) { mock.method1 } assert_match(/unexpected invocation/, e.message) end private def build_mock Mock.new(nil) end end mocha-1.3.0/test/unit/parameter_matchers/0000755000004100000410000000000013155337745020453 5ustar www-datawww-datamocha-1.3.0/test/unit/parameter_matchers/has_value_test.rb0000644000004100000410000000335213155337745024011 0ustar www-datawww-datarequire File.expand_path('../../../test_helper', __FILE__) require 'mocha/parameter_matchers/has_value' require 'mocha/parameter_matchers/object' require 'mocha/parameter_matchers/equals' require 'mocha/inspect' class HasValueTest < Mocha::TestCase include Mocha::ParameterMatchers def test_should_match_hash_including_specified_value matcher = has_value('value_1') assert matcher.matches?([{ :key_1 => 'value_1', :key_2 => 'value_2' }]) end def test_should_not_match_hash_not_including_specified_value matcher = has_value('value_1') assert !matcher.matches?([{ :key_2 => 'value_2' }]) end def test_should_describe_matcher matcher = has_value('value_1') assert_equal %{has_value("value_1")}, matcher.mocha_inspect end def test_should_match_hash_including_specified_value_with_nested_value_matcher matcher = has_value(equals('value_1')) assert matcher.matches?([{ :key_1 => 'value_1', :key_2 => 'value_2' }]) end def test_should_not_match_hash_not_including_specified_value_with_nested_value_matcher matcher = has_value(equals('value_1')) assert !matcher.matches?([{ :key_2 => 'value_2' }]) end def test_should_not_raise_error_on_empty_arguments matcher = has_value('value_1') assert_nothing_raised { matcher.matches?([]) } end def test_should_not_match_empty_arguments matcher = has_value('value_1') assert !matcher.matches?([]) end def test_should_not_raise_error_on_argument_that_does_not_respond_to_values matcher = has_value('value_1') assert_nothing_raised { matcher.matches?(['value_1']) } end def test_should_not_match_on_argument_that_does_not_respond_to_values matcher = has_value('value_1') assert !matcher.matches?(['value_1']) end end mocha-1.3.0/test/unit/parameter_matchers/equals_test.rb0000644000004100000410000000106513155337745023333 0ustar www-datawww-datarequire File.expand_path('../../../test_helper', __FILE__) require 'mocha/parameter_matchers/equals' require 'mocha/inspect' class EqualsTest < Mocha::TestCase include Mocha::ParameterMatchers def test_should_match_object_that_equals_value matcher = equals('x') assert matcher.matches?(['x']) end def test_should_not_match_object_that_does_not_equal_value matcher = equals('x') assert !matcher.matches?(['y']) end def test_should_describe_matcher matcher = equals('x') assert_equal %{"x"}, matcher.mocha_inspect end end mocha-1.3.0/test/unit/parameter_matchers/has_entries_test.rb0000644000004100000410000000425613155337745024352 0ustar www-datawww-datarequire File.expand_path('../../../test_helper', __FILE__) require 'mocha/parameter_matchers/has_entries' require 'mocha/parameter_matchers/object' require 'mocha/inspect' class HasEntriesTest < Mocha::TestCase include Mocha::ParameterMatchers def test_should_match_hash_including_specified_entries matcher = has_entries(:key_1 => 'value_1', :key_2 => 'value_2') assert matcher.matches?([{ :key_1 => 'value_1', :key_2 => 'value_2', :key_3 => 'value_3' }]) end def test_should_not_match_hash_not_including_specified_entries matcher = has_entries(:key_1 => 'value_2', :key_2 => 'value_2', :key_3 => 'value_3') assert !matcher.matches?([{ :key_1 => 'value_1', :key_2 => 'value_2' }]) end def test_should_describe_matcher matcher = has_entries(:key_1 => 'value_1', :key_2 => 'value_2') description = matcher.mocha_inspect matches = /has_entries\((.*)\)/.match(description) assert_not_nil matches[0] entries = eval(matches[1], binding, __FILE__, __LINE__) assert_equal 'value_1', entries[:key_1] assert_equal 'value_2', entries[:key_2] end def test_should_match_hash_including_specified_entries_with_nested_key_matchers matcher = has_entries(equals(:key_1) => 'value_1', equals(:key_2) => 'value_2') assert matcher.matches?([{ :key_1 => 'value_1', :key_2 => 'value_2', :key_3 => 'value_3' }]) end def test_should_not_match_hash_not_including_specified_entries_with_nested_key_matchers matcher = has_entries(equals(:key_1) => 'value_2', equals(:key_2) => 'value_2', equals(:key_3) => 'value_3') assert !matcher.matches?([{ :key_1 => 'value_1', :key_2 => 'value_2' }]) end def test_should_match_hash_including_specified_entries_with_nested_value_matchers matcher = has_entries(:key_1 => equals('value_1'), :key_2 => equals('value_2')) assert matcher.matches?([{ :key_1 => 'value_1', :key_2 => 'value_2', :key_3 => 'value_3' }]) end def test_should_not_match_hash_not_including_specified_entries_with_nested_value_matchers matcher = has_entries(:key_1 => equals('value_2'), :key_2 => equals('value_2'), :key_3 => equals('value_3')) assert !matcher.matches?([{ :key_1 => 'value_1', :key_2 => 'value_2' }]) end end mocha-1.3.0/test/unit/parameter_matchers/includes_test.rb0000644000004100000410000000632513155337745023653 0ustar www-datawww-datarequire File.expand_path('../../../test_helper', __FILE__) require 'mocha/parameter_matchers/includes' require 'mocha/parameter_matchers/object' require 'mocha/parameter_matchers/has_key' require 'mocha/parameter_matchers/regexp_matches' require 'mocha/inspect' class IncludesTest < Mocha::TestCase include Mocha::ParameterMatchers def test_should_match_object_including_value matcher = includes(:x) assert matcher.matches?([[:x, :y, :z]]) end def test_should_match_object_including_array_value matcher = includes([:x]) assert matcher.matches?([[[:x], [:y], [:z]]]) end def test_should_match_object_including_all_values matcher = includes(:x, :y, :z) assert matcher.matches?([[:x, :y, :z]]) end def test_should_not_match_object_that_does_not_include_value matcher = includes(:not_included) assert !matcher.matches?([[:x, :y, :z]]) end def test_should_not_match_object_that_does_not_include_any_one_value matcher = includes(:x, :y, :z, :not_included) assert !matcher.matches?([[:x, :y, :z]]) end def test_should_describe_matcher_with_one_item matcher = includes(:x) assert_equal "includes(:x)", matcher.mocha_inspect end def test_should_describe_matcher_with_multiple_items matcher = includes(:x, :y, :z) assert_equal "includes(:x, :y, :z)", matcher.mocha_inspect end def test_should_not_raise_error_on_emtpy_arguments matcher = includes(:x) assert_nothing_raised { matcher.matches?([]) } end def test_should_not_match_on_empty_arguments matcher = includes(:x) assert !matcher.matches?([]) end def test_should_not_raise_error_on_argument_that_does_not_respond_to_include matcher = includes(:x) assert_nothing_raised { matcher.matches?([:x]) } end def test_should_not_match_on_argument_that_does_not_respond_to_include matcher = includes(:x) assert !matcher.matches?([:x]) end def test_should_match_object_including_value_which_matches_nested_matcher matcher = includes(has_key(:key)) assert matcher.matches?([[:non_matching_element, {:key => 'value'}]]) end def test_should_not_match_object_which_doesnt_include_value_that_matches_nested_matcher matcher = includes(has_key(:key)) assert !matcher.matches?([[:non_matching_element, {:other_key => 'other-value'}]]) end def test_should_match_string_argument_containing_substring matcher = includes('bar') assert matcher.matches?(['foobarbaz']) end def test_should_not_match_string_argument_without_substring matcher = includes('bar') assert !matcher.matches?(['foobaz']) end def test_should_match_hash_argument_containing_given_key matcher = includes(:key) assert matcher.matches?([{:thing => 1, :key => 2}]) end def test_should_not_match_hash_argument_missing_given_key matcher = includes(:key) assert !matcher.matches?([{:thing => 1, :other => :key}]) end def test_should_match_hash_when_nested_matcher_matches_key matcher = includes(regexp_matches(/ar/)) assert matcher.matches?([{'foo' => 1, 'bar' => 2}]) end def test_should_not_match_hash_when_nested_matcher_doesn_not_match_key matcher = includes(regexp_matches(/az/)) assert !matcher.matches?([{'foo' => 1, 'bar' => 2}]) end end mocha-1.3.0/test/unit/parameter_matchers/has_key_test.rb0000644000004100000410000000306513155337745023466 0ustar www-datawww-datarequire File.expand_path('../../../test_helper', __FILE__) require 'mocha/parameter_matchers/has_key' require 'mocha/parameter_matchers/object' require 'mocha/inspect' class HasKeyTest < Mocha::TestCase include Mocha::ParameterMatchers def test_should_match_hash_including_specified_key matcher = has_key(:key_1) assert matcher.matches?([{ :key_1 => 1, :key_2 => 2 }]) end def test_should_not_match_hash_not_including_specified_key matcher = has_key(:key_1) assert !matcher.matches?([{ :key_2 => 2 }]) end def test_should_describe_matcher matcher = has_key(:key) assert_equal 'has_key(:key)', matcher.mocha_inspect end def test_should_match_hash_including_specified_key_with_nested_key_matcher matcher = has_key(equals(:key_1)) assert matcher.matches?([{ :key_1 => 1, :key_2 => 2 }]) end def test_should_not_match_hash_not_including_specified_key_with_nested_key_matcher matcher = has_key(equals(:key_1)) assert !matcher.matches?([{ :key_2 => 2 }]) end def test_should_not_raise_error_on_empty_arguments matcher = has_key(:key) assert_nothing_raised { matcher.matches?([]) } end def test_should_not_match_on_empty_arguments matcher = has_key(:key) assert !matcher.matches?([]) end def test_should_not_raise_error_on_argument_that_does_not_respond_to_keys matcher = has_key(:key) assert_nothing_raised { matcher.matches?([:key]) } end def test_should_not_match_on_argument_that_does_not_respond_to_keys matcher = has_key(:key) assert !matcher.matches?([:key]) end end mocha-1.3.0/test/unit/parameter_matchers/yaml_equivalent_test.rb0000644000004100000410000000132413155337745025236 0ustar www-datawww-datarequire File.expand_path('../../../test_helper', __FILE__) require 'mocha/parameter_matchers/yaml_equivalent' require 'mocha/inspect' class YamlEquivalentTest < Mocha::TestCase include Mocha::ParameterMatchers def test_should_match_parameter_matching_yaml_representation_of_object matcher = yaml_equivalent([1, 2, 3]) assert matcher.matches?(["--- \n- 1\n- 2\n- 3\n"]) end def test_should_not_match_parameter_matching_yaml_representation_of_object matcher = yaml_equivalent([1, 2, 3]) assert !matcher.matches?(["--- \n- 4\n- 5\n"]) end def test_should_describe_matcher matcher = yaml_equivalent([1, 2, 3]) assert_equal "yaml_equivalent([1, 2, 3])", matcher.mocha_inspect end end mocha-1.3.0/test/unit/parameter_matchers/stub_matcher.rb0000644000004100000410000000054113155337745023460 0ustar www-datawww-datamodule Stub class Matcher attr_accessor :value def initialize(matches) @matches = matches end def matches?(available_parameters) value = available_parameters.shift @value = value @matches end def mocha_inspect "matcher(#{@matches})" end def to_matcher self end end end mocha-1.3.0/test/unit/parameter_matchers/all_of_test.rb0000644000004100000410000000154113155337744023273 0ustar www-datawww-datarequire File.expand_path('../../../test_helper', __FILE__) require 'mocha/parameter_matchers/all_of' require 'mocha/inspect' require 'stub_matcher' class AllOfTest < Mocha::TestCase include Mocha::ParameterMatchers def test_should_match_if_all_matchers_match matcher = all_of(Stub::Matcher.new(true), Stub::Matcher.new(true), Stub::Matcher.new(true)) assert matcher.matches?(['any_old_value']) end def test_should_not_match_if_any_matcher_does_not_match matcher = all_of(Stub::Matcher.new(true), Stub::Matcher.new(false), Stub::Matcher.new(true)) assert !matcher.matches?(['any_old_value']) end def test_should_describe_matcher matcher = all_of(Stub::Matcher.new(true), Stub::Matcher.new(false), Stub::Matcher.new(true)) assert_equal 'all_of(matcher(true), matcher(false), matcher(true))', matcher.mocha_inspect end end mocha-1.3.0/test/unit/parameter_matchers/equivalent_uri_test.rb0000644000004100000410000000337013155337745025076 0ustar www-datawww-datarequire File.expand_path('../../../test_helper', __FILE__) require 'deprecation_disabler' require 'mocha/parameter_matchers/equivalent_uri' class EquivalentUriMatchesTest < Mocha::TestCase include Mocha::ParameterMatchers include DeprecationDisabler def test_should_match_identical_uri matcher = equivalent_uri('http://example.com/foo?a=1&b=2') assert matcher.matches?(['http://example.com/foo?a=1&b=2']) end def test_should_support_legacy_matcher_method disable_deprecations do matcher = has_equivalent_query_string('http://example.com/foo?a=1&b=2') assert matcher.matches?(['http://example.com/foo?a=1&b=2']) end end def test_should_match_uri_with_rearranged_query_string matcher = equivalent_uri('http://example.com/foo?b=2&a=1') assert matcher.matches?(['http://example.com/foo?a=1&b=2']) end def test_should_not_match_uri_with_different_query_string matcher = equivalent_uri('http://example.com/foo?a=1') assert !matcher.matches?(['http://example.com/foo?a=1&b=2']) end def test_should_not_match_uri_when_no_query_string_expected matcher = equivalent_uri('http://example.com/foo') assert !matcher.matches?(['http://example.com/foo?a=1&b=2']) end def test_should_not_match_uri_with_different_domain matcher = equivalent_uri('http://a.example.com/foo?a=1&b=2') assert !matcher.matches?(['http://b.example.com/foo?a=1&b=2']) end def test_should_match_uri_without_scheme_and_domain matcher = equivalent_uri('/foo?a=1&b=2') assert matcher.matches?(['/foo?a=1&b=2']) end def test_should_match_uri_with_query_string_containing_blank_value matcher = equivalent_uri('http://example.com/foo?a=&b=2') assert matcher.matches?(['http://example.com/foo?a=&b=2']) end end mocha-1.3.0/test/unit/parameter_matchers/not_test.rb0000644000004100000410000000122613155337745022640 0ustar www-datawww-datarequire File.expand_path('../../../test_helper', __FILE__) require 'mocha/parameter_matchers/not' require 'mocha/inspect' require 'stub_matcher' class NotTest < Mocha::TestCase include Mocha::ParameterMatchers def test_should_match_if_matcher_does_not_match matcher = Not(Stub::Matcher.new(false)) assert matcher.matches?(['any_old_value']) end def test_should_not_match_if_matcher_does_match matcher = Not(Stub::Matcher.new(true)) assert !matcher.matches?(['any_old_value']) end def test_should_describe_matcher matcher = Not(Stub::Matcher.new(true)) assert_equal 'Not(matcher(true))', matcher.mocha_inspect end end mocha-1.3.0/test/unit/parameter_matchers/responds_with_test.rb0000644000004100000410000000173613155337745024736 0ustar www-datawww-datarequire File.expand_path('../../../test_helper', __FILE__) require 'mocha/parameter_matchers/responds_with' require 'mocha/parameter_matchers/object' require 'mocha/inspect' class RespondsWithTest < Mocha::TestCase include Mocha::ParameterMatchers def test_should_match_parameter_responding_with_expected_value matcher = responds_with(:upcase, 'FOO') assert matcher.matches?(['foo']) end def test_should_not_match_parameter_responding_with_unexpected_value matcher = responds_with(:upcase, 'FOO') assert !matcher.matches?(['bar']) end def test_should_match_parameter_responding_with_nested_responds_with_matcher matcher = responds_with(:foo, responds_with(:bar, 'baz')) object = Class.new { def foo; Class.new { def bar; 'baz'; end }.new; end }.new assert matcher.matches?([object]) end def test_should_describe_matcher matcher = responds_with(:foo, :bar) assert_equal 'responds_with(:foo, :bar)', matcher.mocha_inspect end end mocha-1.3.0/test/unit/parameter_matchers/is_a_test.rb0000644000004100000410000000111713155337745022752 0ustar www-datawww-datarequire File.expand_path('../../../test_helper', __FILE__) require 'mocha/parameter_matchers/is_a' require 'mocha/inspect' class IsATest < Mocha::TestCase include Mocha::ParameterMatchers def test_should_match_object_that_is_a_specified_class matcher = is_a(Integer) assert matcher.matches?([99]) end def test_should_not_match_object_that_is_not_a_specified_class matcher = is_a(Integer) assert !matcher.matches?(['string']) end def test_should_describe_matcher matcher = is_a(Integer) assert_equal "is_a(Integer)", matcher.mocha_inspect end end mocha-1.3.0/test/unit/parameter_matchers/any_of_test.rb0000644000004100000410000000153613155337744023316 0ustar www-datawww-datarequire File.expand_path('../../../test_helper', __FILE__) require 'mocha/parameter_matchers/any_of' require 'mocha/inspect' require 'stub_matcher' class AnyOfTest < Mocha::TestCase include Mocha::ParameterMatchers def test_should_match_if_any_matchers_match matcher = any_of(Stub::Matcher.new(false), Stub::Matcher.new(true), Stub::Matcher.new(false)) assert matcher.matches?(['any_old_value']) end def test_should_not_match_if_no_matchers_match matcher = any_of(Stub::Matcher.new(false), Stub::Matcher.new(false), Stub::Matcher.new(false)) assert !matcher.matches?(['any_old_value']) end def test_should_describe_matcher matcher = any_of(Stub::Matcher.new(false), Stub::Matcher.new(true), Stub::Matcher.new(false)) assert_equal 'any_of(matcher(false), matcher(true), matcher(false))', matcher.mocha_inspect end end mocha-1.3.0/test/unit/parameter_matchers/kind_of_test.rb0000644000004100000410000000116113155337745023447 0ustar www-datawww-datarequire File.expand_path('../../../test_helper', __FILE__) require 'mocha/parameter_matchers/kind_of' require 'mocha/inspect' class KindOfTest < Mocha::TestCase include Mocha::ParameterMatchers def test_should_match_object_that_is_a_kind_of_specified_class matcher = kind_of(Integer) assert matcher.matches?([99]) end def test_should_not_match_object_that_is_not_a_kind_of_specified_class matcher = kind_of(Integer) assert !matcher.matches?(['string']) end def test_should_describe_matcher matcher = kind_of(Integer) assert_equal "kind_of(Integer)", matcher.mocha_inspect end end mocha-1.3.0/test/unit/parameter_matchers/anything_test.rb0000644000004100000410000000073013155337744023657 0ustar www-datawww-datarequire File.expand_path('../../../test_helper', __FILE__) require 'mocha/parameter_matchers/anything' require 'mocha/inspect' class AnythingTest < Mocha::TestCase include Mocha::ParameterMatchers def test_should_match_anything matcher = anything assert matcher.matches?([:something]) assert matcher.matches?([{'x' => 'y'}]) end def test_should_describe_matcher matcher = anything assert_equal "anything", matcher.mocha_inspect end end mocha-1.3.0/test/unit/parameter_matchers/has_entry_test.rb0000644000004100000410000001117713155337745024042 0ustar www-datawww-datarequire File.expand_path('../../../test_helper', __FILE__) require 'mocha/parameter_matchers/has_entry' require 'mocha/parameter_matchers/object' require 'mocha/parameter_matchers/equals' require 'mocha/inspect' class HasEntryTest < Mocha::TestCase include Mocha::ParameterMatchers def test_should_match_hash_including_specified_key_value_pair matcher = has_entry(:key_1, 'value_1') assert matcher.matches?([{ :key_1 => 'value_1', :key_2 => 'value_2' }]) end def test_should_not_match_hash_not_including_specified_key_value_pair matcher = has_entry(:key_1, 'value_2') assert !matcher.matches?([{ :key_1 => 'value_1', :key_2 => 'value_2' }]) end def test_should_match_hash_including_specified_entry matcher = has_entry(:key_1 => 'value_1') assert matcher.matches?([{ :key_1 => 'value_1', :key_2 => 'value_2' }]) end def test_should_not_match_hash_not_including_specified_entry matcher = has_entry(:key_1 => 'value_2') assert !matcher.matches?([{ :key_1 => 'value_1', :key_2 => 'value_2' }]) end def test_should_describe_matcher_with_key_value_pair matcher = has_entry(:key_1, 'value_1') assert_equal %{has_entry(:key_1 => "value_1")}, matcher.mocha_inspect end def test_should_describe_matcher_with_entry matcher = has_entry(:key_1 => 'value_1') assert_equal %{has_entry(:key_1 => "value_1")}, matcher.mocha_inspect end def test_should_match_hash_including_specified_entry_with_nested_key_matcher matcher = has_entry(equals(:key_1) => 'value_1') assert matcher.matches?([{ :key_1 => 'value_1', :key_2 => 'value_2' }]) end def test_should_match_hash_including_specified_entry_with_nested_value_matcher matcher = has_entry(:key_1 => equals('value_1')) assert matcher.matches?([{ :key_1 => 'value_1', :key_2 => 'value_2' }]) end def test_should_not_match_hash_not_including_specified_entry_with_nested_key_matcher matcher = has_entry(equals(:key_1) => 'value_2') assert !matcher.matches?([{ :key_1 => 'value_1', :key_2 => 'value_2' }]) end def test_should_not_match_hash_not_including_specified_entry_with_nested_value_matcher matcher = has_entry(:key_1 => equals('value_2')) assert !matcher.matches?([{ :key_1 => 'value_1', :key_2 => 'value_2' }]) end def test_should_not_match_object_that_doesnt_respond_to_keys matcher = has_entry(:key_1 => equals('value_2')) object = Class.new do def [](key) 'value_2' end end.new assert !matcher.matches?([object]) end def test_should_not_match_object_that_doesnt_respond_to_square_bracket matcher = has_entry(:key_1 => equals('value_2')) object = Class.new do def keys [:key_1] end end.new assert !matcher.matches?([object]) end def test_should_raise_argument_error_if_single_argument_is_not_a_hash e = assert_raises(ArgumentError) do has_entry(Array.new) end assert_equal "Argument is not a Hash.", e.message end def test_should_raise_argument_error_if_no_entries_are_supplied e = assert_raises(ArgumentError) do has_entry({}) end assert_equal "Argument has no entries.", e.message end def test_should_raise_argument_error_if_multiple_entries_are_supplied e = assert_raises(ArgumentError) do has_entry(:key_1 => 'value_1', :key_2 => 'value_2') end assert_equal "Argument has multiple entries. Use Mocha::ParameterMatchers#has_entries instead.", e.message end def test_should_raise_argument_error_if_more_than_two_arguments_are_supplied e = assert_raises(ArgumentError) do has_entry(1, 2, 3) end assert_equal "Too many arguments; use either a single argument (must be a Hash) or two arguments (a key and a value).", e.message end def test_should_match_array_as_key matcher = has_entry([:key_1, :key_2] => 'value_1') assert matcher.matches?([{[:key_1, :key_2] => 'value_1', :key_3 => 'value_2'}]) end def test_should_match_array_as_value matcher = has_entry(:key_1 => ['value_1', 'value_2']) assert matcher.matches?([{:key_1 => ['value_1', 'value_2']}]) end def test_should_match_hash_as_value_and_key matcher = has_entry({{:key_1 => 'value_1', :key_2 => 'value_2'} => {:key_3 => 'value_3', :key_4 => 'value_4'}}) assert matcher.matches?([{{:key_1 => 'value_1', :key_2 => 'value_2'} => {:key_3 => 'value_3', :key_4 => 'value_4'}, :key_5 => 'value_5'}]) end def test_should_match_matcher_as_value_and_key matcher = has_entry({has_entry(:key_1 => 'value_1') => has_entry(:key_3 => 'value_3')}) assert matcher.matches?([{{:key_1 => 'value_1', :key_2 => 'value_2'} => {:key_3 => 'value_3', :key_4 => 'value_4'}, :key_5 => 'value_5'}]) end end mocha-1.3.0/test/unit/parameter_matchers/instance_of_test.rb0000644000004100000410000000121713155337745024330 0ustar www-datawww-datarequire File.expand_path('../../../test_helper', __FILE__) require 'mocha/parameter_matchers/instance_of' require 'mocha/inspect' class InstanceOfTest < Mocha::TestCase include Mocha::ParameterMatchers def test_should_match_object_that_is_an_instance_of_specified_class matcher = instance_of(String) assert matcher.matches?(['string']) end def test_should_not_match_object_that_is_not_an_instance_of_specified_class matcher = instance_of(String) assert !matcher.matches?([99]) end def test_should_describe_matcher matcher = instance_of(String) assert_equal "instance_of(String)", matcher.mocha_inspect end end mocha-1.3.0/test/unit/parameter_matchers/regexp_matches_test.rb0000644000004100000410000000266613155337745025047 0ustar www-datawww-datarequire File.expand_path('../../../test_helper', __FILE__) require 'mocha/parameter_matchers/regexp_matches' require 'mocha/inspect' class RegexpMatchesTest < Mocha::TestCase include Mocha::ParameterMatchers def test_should_match_parameter_matching_regular_expression matcher = regexp_matches(/oo/) assert matcher.matches?(['foo']) end def test_should_not_match_parameter_not_matching_regular_expression matcher = regexp_matches(/oo/) assert !matcher.matches?(['bar']) end def test_should_describe_matcher matcher = regexp_matches(/oo/) assert_equal "regexp_matches(/oo/)", matcher.mocha_inspect end def test_should_not_raise_error_on_empty_arguments matcher = regexp_matches(/oo/) assert_nothing_raised { matcher.matches?([]) } end def test_should_not_match_on_empty_arguments matcher = regexp_matches(/oo/) assert !matcher.matches?([]) end def test_should_not_raise_error_on_argument_that_does_not_respond_to_equals_tilde object_not_responding_to_equals_tilde = Class.new { undef =~ }.new matcher = regexp_matches(/oo/) assert_nothing_raised { matcher.matches?([object_not_responding_to_equals_tilde]) } end def test_should_not_match_on_argument_that_does_not_respond_to_equals_tilde object_not_responding_to_equals_tilde = Class.new { undef =~ }.new matcher = regexp_matches(/oo/) assert !matcher.matches?([object_not_responding_to_equals_tilde]) end end mocha-1.3.0/test/unit/mockery_test.rb0000644000004100000410000001146213155337744017645 0ustar www-datawww-datarequire File.expand_path('../../test_helper', __FILE__) require 'mocha/mockery' require 'mocha/state_machine' require 'mocha/expectation_error_factory' require 'deprecation_disabler' class MockeryTest < Mocha::TestCase include Mocha include DeprecationDisabler def test_should_build_instance_of_mockery mockery = Mockery.instance assert_not_nil mockery assert_kind_of Mockery, mockery end def test_should_cache_instance_of_mockery mockery_1 = Mockery.instance mockery_2 = Mockery.instance assert_same mockery_1, mockery_2 end def test_should_expire_mockery_instance_cache mockery_1 = Mockery.instance Mockery.reset_instance mockery_2 = Mockery.instance assert_not_same mockery_1, mockery_2 end def test_should_raise_expectation_error_because_not_all_expectations_are_satisfied mockery = Mockery.new disable_deprecations do mock_1 = mockery.named_mock('mock-1') { expects(:method_1) } mock_2 = mockery.named_mock('mock-2') { expects(:method_2) } 1.times { mock_1.method_1 } 0.times { mock_2.method_2 } end assert_raises(ExpectationErrorFactory.exception_class) { mockery.verify } end def test_should_reset_list_of_mocks_on_teardown mockery = Mockery.new disable_deprecations do mockery.unnamed_mock { expects(:my_method) } end mockery.teardown assert_nothing_raised(ExpectationErrorFactory.exception_class) { mockery.verify } end def test_should_build_instance_of_stubba_on_instantiation mockery = Mockery.new assert_not_nil mockery.stubba assert_kind_of Central, mockery.stubba end def test_should_build_new_instance_of_stubba_on_teardown mockery = Mockery.new stubba_1 = mockery.stubba mockery.teardown stubba_2 = mockery.stubba assert_not_same stubba_1, stubba_2 end def test_should_build_and_store_new_state_machine mockery = Mockery.new mockery.new_state_machine('state-machine-name') assert_equal 1, mockery.state_machines.length assert_kind_of StateMachine, mockery.state_machines[0] end def test_should_reset_list_of_state_machines_on_teardown mockery = Mockery.new mockery.new_state_machine('state-machine-name') mockery.teardown assert_equal 0, mockery.state_machines.length end class FakeMethod def stub; end def unstub; end def matches?(other); true; end end def test_should_unstub_all_methods_on_teardown mockery = Mockery.new stubba = mockery.stubba stubba.stub(FakeMethod.new) mockery.teardown assert stubba.stubba_methods.empty? end def test_should_display_object_id_for_mocha_inspect_if_mock_has_no_name mockery = Mockery.new mock = mockery.unnamed_mock assert_match Regexp.new("^#$"), mock.mocha_inspect end def test_should_display_object_id_for_inspect_if_mock_has_no_name mockery = Mockery.new mock = mockery.unnamed_mock assert_match Regexp.new("^#$"), mock.inspect end def test_should_display_name_for_mocha_inspect_if_mock_has_string_name mockery = Mockery.new mock = mockery.named_mock('named_mock') assert_equal "#", mock.mocha_inspect end def test_should_display_name_for_mocha_inspect_if_mock_has_symbol_name mockery = Mockery.new mock = mockery.named_mock(:named_mock) assert_equal "#", mock.mocha_inspect end def test_should_display_name_for_inspect_if_mock_has_string_name mockery = Mockery.new mock = mockery.named_mock('named_mock') assert_equal "#", mock.inspect end def test_should_display_name_for_inspect_if_mock_has_symbol_name mockery = Mockery.new mock = mockery.named_mock(:named_mock) assert_equal "#", mock.inspect end def test_should_display_impersonated_object_for_mocha_inspect mockery = Mockery.new instance = Object.new mock = mockery.mock_impersonating(instance) assert_equal "#{instance.mocha_inspect}", mock.mocha_inspect end def test_should_display_impersonated_object_for_inspect mockery = Mockery.new instance = Object.new mock = mockery.mock_impersonating(instance) assert_equal "#{instance.mocha_inspect}", mock.inspect end class FakeClass; end def test_should_display_any_instance_prefix_followed_by_class_whose_instances_are_being_impersonated_for_mocha_inspect mockery = Mockery.new mock = mockery.mock_impersonating_any_instance_of(FakeClass) assert_equal "#", mock.mocha_inspect end def test_should_display_any_instance_prefix_followed_by_class_whose_instances_are_being_impersonated_for_inspect mockery = Mockery.new mock = mockery.mock_impersonating_any_instance_of(FakeClass) assert_equal "#", mock.inspect end end mocha-1.3.0/test/unit/object_methods_test.rb0000644000004100000410000000232013155337744021156 0ustar www-datawww-datarequire File.expand_path('../../test_helper', __FILE__) require 'mocha/object_methods' require 'mocha/mock' require 'mocha/expectation_error_factory' class ObjectMethodsTest < Mocha::TestCase def setup @object = Object.new.extend(Mocha::ObjectMethods) end def test_should_build_mocha_referring_to_self mocha = @object.mocha assert_not_nil mocha assert mocha.is_a?(Mocha::Mock) assert_equal @object.mocha_inspect, mocha.mocha_inspect end def test_should_reuse_existing_mocha mocha_1 = @object.mocha mocha_2 = @object.mocha assert_equal mocha_1, mocha_2 end def test_should_reset_mocha assert_nil @object.reset_mocha end def test_should_use_stubba_instance_method_for_object assert_equal Mocha::InstanceMethod, Object.new.stubba_method end def test_should_stub_self_for_object assert_equal @object, @object.stubba_object end def test_nobody_expects_the_spanish_inquisition assert_raise(Mocha::ExpectationErrorFactory.exception_class) { @object.expects(:the_spanish_inquisition) } end def test_should_alias_object_method klass = Class.new { def self.method_x; end } assert_equal klass._method(:method_x), klass.method(:method_x) end end mocha-1.3.0/test/unit/thrower_test.rb0000644000004100000410000000070313155337745017663 0ustar www-datawww-datarequire File.expand_path('../../test_helper', __FILE__) require 'mocha/thrower' class ThrowerTest < Mocha::TestCase include Mocha def test_should_throw_tag thrower = Thrower.new(:tag) assert_throws(:tag) { thrower.evaluate } end def test_should_throw_tag_with_return_value thrower = Thrower.new(:tag, 'return-value') return_value = catch(:tag) { thrower.evaluate } assert_equal 'return-value', return_value end end mocha-1.3.0/test/unit/single_return_value_test.rb0000644000004100000410000000043413155337745022246 0ustar www-datawww-datarequire File.expand_path('../../test_helper', __FILE__) require 'mocha/single_return_value' class SingleReturnValueTest < Mocha::TestCase include Mocha def test_should_return_value value = SingleReturnValue.new('value') assert_equal 'value', value.evaluate end end mocha-1.3.0/test/unit/array_inspect_test.rb0000644000004100000410000000057013155337744021035 0ustar www-datawww-datarequire File.expand_path('../../test_helper', __FILE__) require 'mocha/inspect' class ArrayInspectTest < Mocha::TestCase def test_should_use_inspect array = [1, 2] assert_equal array.inspect, array.mocha_inspect end def test_should_use_mocha_inspect_on_each_item array = [1, 2, "chris"] assert_equal %{[1, 2, "chris"]}, array.mocha_inspect end end mocha-1.3.0/test/unit/no_yields_test.rb0000644000004100000410000000062713155337744020162 0ustar www-datawww-datarequire File.expand_path('../../test_helper', __FILE__) require 'mocha/no_yields' class NoYieldsTest < Mocha::TestCase include Mocha def test_should_provide_parameters_for_no_yields_in_single_invocation parameter_group = NoYields.new parameter_groups = [] parameter_group.each do |parameters| parameter_groups << parameters end assert_equal [], parameter_groups end end mocha-1.3.0/test/unit/backtrace_filter_test.rb0000644000004100000410000000116213155337744021454 0ustar www-datawww-datarequire File.expand_path('../../test_helper', __FILE__) require 'mocha/backtrace_filter' class BacktraceFilterTest < Mocha::TestCase include Mocha def test_should_exclude_mocha_locations_from_backtrace mocha_lib = "/username/workspace/mocha_wibble/lib/" backtrace = [ mocha_lib + 'exclude/me/1', mocha_lib + 'exclude/me/2', '/keep/me', mocha_lib + 'exclude/me/3'] filter = BacktraceFilter.new(mocha_lib) assert_equal ['/keep/me'], filter.filtered(backtrace) end def test_should_determine_path_for_mocha_lib_directory assert_match Regexp.new("/lib/$"), BacktraceFilter::LIB_DIRECTORY end end mocha-1.3.0/test/unit/single_yield_test.rb0000644000004100000410000000066513155337745020647 0ustar www-datawww-datarequire File.expand_path('../../test_helper', __FILE__) require 'mocha/single_yield' class SingleYieldTest < Mocha::TestCase include Mocha def test_should_provide_parameters_for_single_yield_in_single_invocation parameter_group = SingleYield.new(1, 2, 3) parameter_groups = [] parameter_group.each do |parameters| parameter_groups << parameters end assert_equal [[1, 2, 3]], parameter_groups end end mocha-1.3.0/test/acceptance/0000755000004100000410000000000013155337744015713 5ustar www-datawww-datamocha-1.3.0/test/acceptance/unexpected_invocation_test.rb0000644000004100000410000000121113155337744023667 0ustar www-datawww-datarequire File.expand_path('../acceptance_test_helper', __FILE__) require 'mocha/setup' class UnexpectedInvocationTest < Mocha::TestCase include AcceptanceTest def setup setup_acceptance_test end def teardown teardown_acceptance_test end def test_avoid_recursion_when_unexpected_invocation_exception_message_depends_on_uninspectable_object test_result = run_as_test do instance = Class.new.new instance.expects(:inspect).never instance.inspect(1, 2, 'foo') end assert_failed(test_result) assert_equal "unexpected invocation: inspect(1, 2, foo)", test_result.failure_message_lines[0] end endmocha-1.3.0/test/acceptance/stubbing_non_existent_any_instance_method_test.rb0000644000004100000410000001126213155337744030006 0ustar www-datawww-datarequire File.expand_path('../acceptance_test_helper', __FILE__) require 'mocha/setup' class StubbingNonExistentAnyInstanceMethodTest < Mocha::TestCase include AcceptanceTest def setup setup_acceptance_test end def teardown teardown_acceptance_test end def test_should_allow_stubbing_non_existent_any_instance_method Mocha::Configuration.allow(:stubbing_non_existent_method) klass = Class.new test_result = run_as_test do klass.any_instance.stubs(:non_existent_method) end assert !@logger.warnings.include?("stubbing non-existent method: #{klass.any_instance.mocha_inspect}.non_existent_method") assert_passed(test_result) end def test_should_warn_when_stubbing_non_existent_any_instance_method Mocha::Configuration.warn_when(:stubbing_non_existent_method) klass = Class.new test_result = run_as_test do klass.any_instance.stubs(:non_existent_method) end assert_passed(test_result) assert @logger.warnings.include?("stubbing non-existent method: #{klass.any_instance.mocha_inspect}.non_existent_method") end def test_should_prevent_stubbing_non_existent_any_instance_method Mocha::Configuration.prevent(:stubbing_non_existent_method) klass = Class.new test_result = run_as_test do klass.any_instance.stubs(:non_existent_method) end assert_failed(test_result) assert test_result.error_messages.include?("Mocha::StubbingError: stubbing non-existent method: #{klass.any_instance.mocha_inspect}.non_existent_method") end def test_should_default_to_allow_stubbing_non_existent_any_instance_method klass = Class.new test_result = run_as_test do klass.any_instance.stubs(:non_existent_method) end assert !@logger.warnings.include?("stubbing non-existent method: #{klass.any_instance.mocha_inspect}.non_existent_method") assert_passed(test_result) end def test_should_allow_stubbing_existing_public_any_instance_method Mocha::Configuration.prevent(:stubbing_non_existent_method) klass = Class.new do def existing_public_method; end public :existing_public_method end test_result = run_as_test do klass.any_instance.stubs(:existing_public_method) end assert_passed(test_result) end def test_should_allow_stubbing_method_to_which_any_instance_responds Mocha::Configuration.prevent(:stubbing_non_existent_method) klass = Class.new do def respond_to?(method, include_private = false) (method == :method_to_which_instance_responds) end end test_result = run_as_test do klass.any_instance.stubs(:method_to_which_instance_responds) end assert_passed(test_result) end def test_should_allow_stubbing_existing_protected_any_instance_method Mocha::Configuration.prevent(:stubbing_non_existent_method) klass = Class.new do def existing_protected_method; end protected :existing_protected_method end test_result = run_as_test do klass.any_instance.stubs(:existing_protected_method) end assert_passed(test_result) end def test_should_allow_stubbing_existing_private_any_instance_method Mocha::Configuration.prevent(:stubbing_non_existent_method) klass = Class.new do def existing_private_method; end private :existing_private_method end test_result = run_as_test do klass.any_instance.stubs(:existing_private_method) end assert_passed(test_result) end def test_should_allow_stubbing_existing_public_any_instance_superclass_method Mocha::Configuration.prevent(:stubbing_non_existent_method) superklass = Class.new do def existing_public_method; end public :existing_public_method end klass = Class.new(superklass) test_result = run_as_test do klass.any_instance.stubs(:existing_public_method) end assert_passed(test_result) end def test_should_allow_stubbing_existing_protected_any_instance_superclass_method Mocha::Configuration.prevent(:stubbing_non_existent_method) superklass = Class.new do def existing_protected_method; end protected :existing_protected_method end klass = Class.new(superklass) test_result = run_as_test do klass.any_instance.stubs(:existing_protected_method) end assert_passed(test_result) end def test_should_allow_stubbing_existing_private_any_instance_superclass_method Mocha::Configuration.prevent(:stubbing_non_existent_method) superklass = Class.new do def existing_private_method; end private :existing_private_method end klass = Class.new(superklass) test_result = run_as_test do klass.any_instance.stubs(:existing_private_method) end assert_passed(test_result) end end mocha-1.3.0/test/acceptance/bug_21465_test.rb0000644000004100000410000000122413155337744020614 0ustar www-datawww-datarequire File.expand_path('../acceptance_test_helper', __FILE__) require 'mocha/setup' class Bug21465Test < Mocha::TestCase include AcceptanceTest def setup setup_acceptance_test end def teardown teardown_acceptance_test end def test_should_allow_expected_method_name_to_be_a_string test_result = run_as_test do mock = mock() mock.expects('wibble') mock.wibble end assert_passed(test_result) end def test_should_allow_stubbed_method_name_to_be_a_string test_result = run_as_test do mock = mock() mock.stubs('wibble') mock.wibble end assert_passed(test_result) end end mocha-1.3.0/test/acceptance/stub_instance_method_defined_on_kernel_module_test.rb0000644000004100000410000000433613155337744030565 0ustar www-datawww-datarequire File.expand_path('../acceptance_test_helper', __FILE__) require 'mocha/setup' class StubInstanceMethodDefinedOnKernelModuleTest < Mocha::TestCase include AcceptanceTest def setup setup_acceptance_test end def teardown teardown_acceptance_test end def test_should_stub_public_method_and_leave_it_unchanged_after_test Kernel.module_eval do def my_instance_method :original_return_value end public :my_instance_method end instance = Class.new.new assert_snapshot_unchanged(instance) do test_result = run_as_test do instance.stubs(:my_instance_method).returns(:new_return_value) assert_equal :new_return_value, instance.my_instance_method end assert_passed(test_result) end assert_equal :original_return_value, instance.my_instance_method ensure Kernel.module_eval { remove_method :my_instance_method } end def test_should_stub_protected_method_and_leave_it_unchanged_after_test Kernel.module_eval do def my_instance_method :original_return_value end protected :my_instance_method end instance = Class.new.new assert_snapshot_unchanged(instance) do test_result = run_as_test do instance.stubs(:my_instance_method).returns(:new_return_value) assert_equal :new_return_value, instance.send(:my_instance_method) end assert_passed(test_result) end assert_equal :original_return_value, instance.send(:my_instance_method) ensure Kernel.module_eval { remove_method :my_instance_method } end def test_should_stub_private_method_and_leave_it_unchanged_after_test Kernel.module_eval do def my_instance_method :original_return_value end private :my_instance_method end instance = Class.new.new assert_snapshot_unchanged(instance) do test_result = run_as_test do instance.stubs(:my_instance_method).returns(:new_return_value) assert_equal :new_return_value, instance.send(:my_instance_method) end assert_passed(test_result) end assert_equal :original_return_value, instance.send(:my_instance_method) ensure Kernel.module_eval { remove_method :my_instance_method } end end mocha-1.3.0/test/acceptance/stubba_example_test.rb0000644000004100000410000000435613155337744022302 0ustar www-datawww-datarequire File.expand_path('../../test_helper', __FILE__) require 'mocha/setup' class Widget def model 'original_model' end class << self def find(options) [] end def create(attributes) Widget.new end end end module Thingy def self.wotsit :hoojamaflip end end class StubbaExampleTest < Mocha::TestCase def test_should_stub_instance_method widget = Widget.new widget.expects(:model).returns('different_model') assert_equal 'different_model', widget.model end def test_should_stub_module_method should_stub_module_method end def test_should_stub_module_method_again should_stub_module_method end def test_should_stub_class_method should_stub_class_method end def test_should_stub_class_method_again should_stub_class_method end def test_should_stub_instance_method_on_any_instance_of_a_class should_stub_instance_method_on_any_instance_of_a_class end def test_should_stub_instance_method_on_any_instance_of_a_class_again should_stub_instance_method_on_any_instance_of_a_class end def test_should_stub_two_different_class_methods should_stub_two_different_class_methods end def test_should_stub_two_different_class_methods_again should_stub_two_different_class_methods end private def should_stub_module_method Thingy.expects(:wotsit).returns(:dooda) assert_equal :dooda, Thingy.wotsit end def should_stub_class_method widgets = [Widget.new] Widget.expects(:find).with(:all).returns(widgets) assert_equal widgets, Widget.find(:all) end def should_stub_two_different_class_methods found_widgets = [Widget.new] created_widget = Widget.new Widget.expects(:find).with(:all).returns(found_widgets) Widget.expects(:create).with(:model => 'wombat').returns(created_widget) assert_equal found_widgets, Widget.find(:all) assert_equal created_widget, Widget.create(:model => 'wombat') end def should_stub_instance_method_on_any_instance_of_a_class Widget.any_instance.expects(:model).at_least_once.returns('another_model') widget_1 = Widget.new widget_2 = Widget.new assert_equal 'another_model', widget_1.model assert_equal 'another_model', widget_2.model end end mocha-1.3.0/test/acceptance/mocha_example_test.rb0000644000004100000410000000512513155337744022104 0ustar www-datawww-datarequire File.expand_path('../../test_helper', __FILE__) require 'mocha/setup' class MochaExampleTest < Mocha::TestCase class Rover def initialize(left_track, right_track, steps_per_metre, steps_per_degree) @left_track, @right_track, @steps_per_metre, @steps_per_degree = left_track, right_track, steps_per_metre, steps_per_degree end def forward(metres) @left_track.step(metres * @steps_per_metre) @right_track.step(metres * @steps_per_metre) wait end def backward(metres) forward(-metres) end def left(degrees) @left_track.step(-degrees * @steps_per_degree) @right_track.step(+degrees * @steps_per_degree) wait end def right(degrees) left(-degrees) end def wait while (@left_track.moving? or @right_track.moving?); end end end def test_should_step_both_tracks_forward_ten_steps left_track = mock('left_track') right_track = mock('right_track') steps_per_metre = 5 rover = Rover.new(left_track, right_track, steps_per_metre, nil) left_track.expects(:step).with(10) right_track.expects(:step).with(10) left_track.stubs(:moving?).returns(false) right_track.stubs(:moving?).returns(false) rover.forward(2) end def test_should_step_both_tracks_backward_ten_steps left_track = mock('left_track') right_track = mock('right_track') steps_per_metre = 5 rover = Rover.new(left_track, right_track, steps_per_metre, nil) left_track.expects(:step).with(-10) right_track.expects(:step).with(-10) left_track.stubs(:moving?).returns(false) right_track.stubs(:moving?).returns(false) rover.backward(2) end def test_should_step_left_track_forwards_five_steps_and_right_track_backwards_five_steps left_track = mock('left_track') right_track = mock('right_track') steps_per_degree = 5.0 / 90.0 rover = Rover.new(left_track, right_track, nil, steps_per_degree) left_track.expects(:step).with(+5) right_track.expects(:step).with(-5) left_track.stubs(:moving?).returns(false) right_track.stubs(:moving?).returns(false) rover.right(90) end def test_should_step_left_track_backwards_five_steps_and_right_track_forwards_five_steps left_track = mock('left_track') right_track = mock('right_track') steps_per_degree = 5.0 / 90.0 rover = Rover.new(left_track, right_track, nil, steps_per_degree) left_track.expects(:step).with(-5) right_track.expects(:step).with(+5) left_track.stubs(:moving?).returns(false) right_track.stubs(:moving?).returns(false) rover.left(90) end end mocha-1.3.0/test/acceptance/bug_21563_test.rb0000644000004100000410000000074513155337744020622 0ustar www-datawww-datarequire File.expand_path('../acceptance_test_helper', __FILE__) require 'mocha/setup' class Bug21563Test < Mocha::TestCase include AcceptanceTest def setup setup_acceptance_test end def teardown teardown_acceptance_test end def test_should_allow_stubbing_of_verified_method test_result = run_as_test do object = Object.new object.stubs(:verified?).returns(false) assert !object.verified? end assert_passed(test_result) end end mocha-1.3.0/test/acceptance/return_value_test.rb0000644000004100000410000000246213155337744022016 0ustar www-datawww-datarequire File.expand_path('../acceptance_test_helper', __FILE__) require 'mocha/setup' class ReturnValueTest < Mocha::TestCase include AcceptanceTest def setup setup_acceptance_test end def teardown teardown_acceptance_test end def test_should_build_mock_and_explicitly_add_an_expectation_with_a_return_value test_result = run_as_test do foo = mock('foo') foo.expects(:bar).returns('bar') assert_equal 'bar', foo.bar end assert_passed(test_result) end def test_should_build_mock_incorporating_two_expectations_with_return_values test_result = run_as_test do foo = mock('foo', :bar => 'bar', :baz => 'baz') assert_equal 'bar', foo.bar assert_equal 'baz', foo.baz end assert_passed(test_result) end def test_should_build_stub_and_explicitly_add_an_expectation_with_a_return_value test_result = run_as_test do foo = stub('foo') foo.stubs(:bar).returns('bar') assert_equal 'bar', foo.bar end assert_passed(test_result) end def test_should_build_stub_incorporating_two_expectations_with_return_values test_result = run_as_test do foo = stub('foo', :bar => 'bar', :baz => 'baz') assert_equal 'bar', foo.bar assert_equal 'baz', foo.baz end assert_passed(test_result) end end mocha-1.3.0/test/acceptance/optional_parameters_test.rb0000644000004100000410000000371113155337744023351 0ustar www-datawww-datarequire File.expand_path('../acceptance_test_helper', __FILE__) require 'mocha/setup' class OptionalParameterMatcherTest < Mocha::TestCase include AcceptanceTest def setup setup_acceptance_test end def teardown teardown_acceptance_test end def test_should_pass_if_all_required_parameters_match_and_no_optional_parameters_are_supplied test_result = run_as_test do mock = mock() mock.expects(:method).with(1, 2, optionally(3, 4)) mock.method(1, 2) end assert_passed(test_result) end def test_should_pass_if_all_required_and_optional_parameters_match_and_some_optional_parameters_are_supplied test_result = run_as_test do mock = mock() mock.expects(:method).with(1, 2, optionally(3, 4)) mock.method(1, 2, 3) end assert_passed(test_result) end def test_should_pass_if_all_required_and_optional_parameters_match_and_all_optional_parameters_are_supplied test_result = run_as_test do mock = mock() mock.expects(:method).with(1, 2, optionally(3, 4)) mock.method(1, 2, 3, 4) end assert_passed(test_result) end def test_should_fail_if_all_required_and_optional_parameters_match_but_too_many_optional_parameters_are_supplied test_result = run_as_test do mock = mock() mock.expects(:method).with(1, 2, optionally(3, 4)) mock.method(1, 2, 3, 4, 5) end assert_failed(test_result) end def test_should_fail_if_all_required_parameters_match_but_some_optional_parameters_do_not_match test_result = run_as_test do mock = mock() mock.expects(:method).with(1, 2, optionally(3, 4)) mock.method(1, 2, 4) end assert_failed(test_result) end def test_should_fail_if_all_required_parameters_match_but_no_optional_parameters_match test_result = run_as_test do mock = mock() mock.expects(:method).with(1, 2, optionally(3, 4)) mock.method(1, 2, 4, 5) end assert_failed(test_result) end end mocha-1.3.0/test/acceptance/bug_18914_test.rb0000644000004100000410000000131313155337744020620 0ustar www-datawww-datarequire File.expand_path('../acceptance_test_helper', __FILE__) require 'mocha/setup' class Bug18914Test < Mocha::TestCase include AcceptanceTest def setup setup_acceptance_test end def teardown teardown_acceptance_test end class AlwaysEql def my_method true end def ==(o) true end def eql?(o) true end end def test_should_not_allow_stubbing_of_non_mock_instance_disrupted_by_legitimate_overriding_of_eql_method always_eql_1 = AlwaysEql.new always_eql_1.stubs(:my_method).returns(false) always_eql_2 = AlwaysEql.new always_eql_2.stubs(:my_method).returns(false) assert_equal false, always_eql_2.my_method end end mocha-1.3.0/test/acceptance/stub_instance_method_defined_on_active_record_association_proxy_test.rb0000644000004100000410000000613013155337744034400 0ustar www-datawww-datarequire File.expand_path('../acceptance_test_helper', __FILE__) require 'mocha/setup' class StubInstanceMethodDefinedOnActiveRecordAssociationProxyTest < Mocha::TestCase include AcceptanceTest def setup setup_acceptance_test end def teardown teardown_acceptance_test end def test_should_be_able_to_stub_method_if_ruby18_public_methods_include_method_but_method_does_not_exist ruby18_instance = Class.new do def public_methods(include_superclass = true) ['my_instance_method'] end end.new test_result = run_as_test do ruby18_instance.stubs(:my_instance_method).returns(:new_return_value) assert_equal :new_return_value, ruby18_instance.my_instance_method end assert_passed(test_result) end def test_should_be_able_to_stub_method_if_ruby19_public_methods_include_method_but_method_does_not_exist ruby19_instance = Class.new do def public_methods(include_superclass = true) [:my_instance_method] end end.new test_result = run_as_test do ruby19_instance.stubs(:my_instance_method).returns(:new_return_value) assert_equal :new_return_value, ruby19_instance.my_instance_method end assert_passed(test_result) end def test_should_be_able_to_stub_method_if_ruby18_protected_methods_include_method_but_method_does_not_exist ruby18_instance = Class.new do def protected_methods(include_superclass = true) ['my_instance_method'] end end.new test_result = run_as_test do ruby18_instance.stubs(:my_instance_method).returns(:new_return_value) assert_equal :new_return_value, ruby18_instance.my_instance_method end assert_passed(test_result) end def test_should_be_able_to_stub_method_if_ruby19_protected_methods_include_method_but_method_does_not_exist ruby19_instance = Class.new do def protected_methods(include_superclass = true) [:my_instance_method] end end.new test_result = run_as_test do ruby19_instance.stubs(:my_instance_method).returns(:new_return_value) assert_equal :new_return_value, ruby19_instance.my_instance_method end assert_passed(test_result) end def test_should_be_able_to_stub_method_if_ruby18_private_methods_include_method_but_method_does_not_exist ruby18_instance = Class.new do def private_methods(include_superclass = true) ['my_instance_method'] end end.new test_result = run_as_test do ruby18_instance.stubs(:my_instance_method).returns(:new_return_value) assert_equal :new_return_value, ruby18_instance.my_instance_method end assert_passed(test_result) end def test_should_be_able_to_stub_method_if_ruby19_private_methods_include_method_but_method_does_not_exist ruby19_instance = Class.new do def private_methods(include_superclass = true) [:my_instance_method] end end.new test_result = run_as_test do ruby19_instance.stubs(:my_instance_method).returns(:new_return_value) assert_equal :new_return_value, ruby19_instance.my_instance_method end assert_passed(test_result) end end mocha-1.3.0/test/acceptance/stubbing_non_existent_class_method_test.rb0000644000004100000410000001116613155337744026443 0ustar www-datawww-datarequire File.expand_path('../acceptance_test_helper', __FILE__) require 'mocha/setup' class StubbingNonExistentClassMethodTest < Mocha::TestCase include AcceptanceTest def setup setup_acceptance_test end def teardown teardown_acceptance_test end def test_should_allow_stubbing_non_existent_class_method Mocha::Configuration.allow(:stubbing_non_existent_method) klass = Class.new test_result = run_as_test do klass.stubs(:non_existent_method) end assert !@logger.warnings.include?("stubbing non-existent method: #{klass.mocha_inspect}.non_existent_method") assert_passed(test_result) end def test_should_warn_when_stubbing_non_existent_class_method Mocha::Configuration.warn_when(:stubbing_non_existent_method) klass = Class.new test_result = run_as_test do klass.stubs(:non_existent_method) end assert_passed(test_result) assert @logger.warnings.include?("stubbing non-existent method: #{klass.mocha_inspect}.non_existent_method") end def test_should_prevent_stubbing_non_existent_class_method Mocha::Configuration.prevent(:stubbing_non_existent_method) klass = Class.new test_result = run_as_test do klass.stubs(:non_existent_method) end assert_failed(test_result) assert test_result.error_messages.include?("Mocha::StubbingError: stubbing non-existent method: #{klass.mocha_inspect}.non_existent_method") end def test_should_default_to_allow_stubbing_non_existent_class_method klass = Class.new test_result = run_as_test do klass.stubs(:non_existent_method) end assert !@logger.warnings.include?("stubbing non-existent method: #{klass.mocha_inspect}.non_existent_method") assert_passed(test_result) end def test_should_allow_stubbing_existing_public_class_method Mocha::Configuration.prevent(:stubbing_non_existent_method) klass = Class.new do class << self def existing_public_method; end public :existing_public_method end end test_result = run_as_test do klass.stubs(:existing_public_method) end assert_passed(test_result) end def test_should_allow_stubbing_method_to_which_class_responds Mocha::Configuration.prevent(:stubbing_non_existent_method) klass = Class.new do class << self def respond_to?(method, include_private = false) (method == :method_to_which_class_responds) end end end test_result = run_as_test do klass.stubs(:method_to_which_class_responds) end assert_passed(test_result) end def test_should_allow_stubbing_existing_protected_class_method Mocha::Configuration.prevent(:stubbing_non_existent_method) klass = Class.new do class << self def existing_protected_method; end protected :existing_protected_method end end test_result = run_as_test do klass.stubs(:existing_protected_method) end assert_passed(test_result) end def test_should_allow_stubbing_existing_private_class_method Mocha::Configuration.prevent(:stubbing_non_existent_method) klass = Class.new do class << self def existing_private_method; end private :existing_private_method end end test_result = run_as_test do klass.stubs(:existing_private_method) end assert_passed(test_result) end def test_should_allow_stubbing_existing_public_superclass_method Mocha::Configuration.prevent(:stubbing_non_existent_method) superklass = Class.new do class << self def existing_public_method; end public :existing_public_method end end klass = Class.new(superklass) test_result = run_as_test do klass.stubs(:existing_public_method) end assert_passed(test_result) end def test_should_allow_stubbing_existing_protected_superclass_method Mocha::Configuration.prevent(:stubbing_non_existent_method) superklass = Class.new do class << self def existing_protected_method; end protected :existing_protected_method end end klass = Class.new(superklass) test_result = run_as_test do klass.stubs(:existing_protected_method) end assert_passed(test_result) end def test_should_allow_stubbing_existing_private_superclass_method Mocha::Configuration.prevent(:stubbing_non_existent_method) superklass = Class.new do class << self def existing_private_method; end protected :existing_private_method end end klass = Class.new(superklass) test_result = run_as_test do klass.stubs(:existing_private_method) end assert_passed(test_result) end end mocha-1.3.0/test/acceptance/prepend_test.rb0000644000004100000410000000364313155337744020742 0ustar www-datawww-datarequire File.expand_path('../acceptance_test_helper', __FILE__) require 'mocha/setup' require 'mocha/ruby_version' class PrependTest < Mocha::TestCase include AcceptanceTest def setup setup_acceptance_test end def teardown teardown_acceptance_test end if Mocha::RUBY_V2_PLUS module Mod1 def my_method super + " World" end end module Mod2 def my_method super + " Wide" end end class Klass1 prepend Mod1 prepend Mod2 def my_method "Hello" end end class Klass2 class << self prepend Mod1 prepend Mod2 def my_method "Hello" end end end def test_stubbing_any_instance_with_multiple_prepended_methods assert_snapshot_unchanged(Klass1) do test_result = run_as_test do Klass1.any_instance.stubs(:my_method).returns("Bye World") assert_equal "Bye World", Klass1.new.my_method end assert_passed(test_result) end assert_equal "Hello World Wide", Klass1.new.my_method end def test_stubbing_instance_with_multiple_prepended_methods object = Klass1.new assert_snapshot_unchanged(object) do test_result = run_as_test do object.stubs(:my_method).returns("Bye World") assert_equal "Bye World", object.my_method assert_equal "Hello World Wide", Klass1.new.my_method end assert_passed(test_result) end assert_equal "Hello World Wide", object.my_method end def test_stubbing_a_prepended_class_method assert_snapshot_unchanged(Klass2) do test_result = run_as_test do Klass2.stubs(:my_method).returns("Bye World") assert_equal "Bye World", Klass2.my_method end assert_passed(test_result) end assert_equal "Hello World Wide", Klass2.my_method end end end mocha-1.3.0/test/acceptance/stub_instance_method_defined_on_object_class_test.rb0000644000004100000410000000432713155337744030373 0ustar www-datawww-datarequire File.expand_path('../acceptance_test_helper', __FILE__) require 'mocha/setup' class StubInstanceMethodDefinedOnObjectClassTest < Mocha::TestCase include AcceptanceTest def setup setup_acceptance_test end def teardown teardown_acceptance_test end def test_should_stub_public_method_and_leave_it_unchanged_after_test Object.class_eval do def my_instance_method :original_return_value end public :my_instance_method end instance = Class.new.new assert_snapshot_unchanged(instance) do test_result = run_as_test do instance.stubs(:my_instance_method).returns(:new_return_value) assert_equal :new_return_value, instance.my_instance_method end assert_passed(test_result) end assert_equal :original_return_value, instance.my_instance_method ensure Object.class_eval { remove_method :my_instance_method } end def test_should_stub_protected_method_and_leave_it_unchanged_after_test Object.class_eval do def my_instance_method :original_return_value end protected :my_instance_method end instance = Class.new.new assert_snapshot_unchanged(instance) do test_result = run_as_test do instance.stubs(:my_instance_method).returns(:new_return_value) assert_equal :new_return_value, instance.send(:my_instance_method) end assert_passed(test_result) end assert_equal :original_return_value, instance.send(:my_instance_method) ensure Object.class_eval { remove_method :my_instance_method } end def test_should_stub_private_method_and_leave_it_unchanged_after_test Object.class_eval do def my_instance_method :original_return_value end private :my_instance_method end instance = Class.new.new assert_snapshot_unchanged(instance) do test_result = run_as_test do instance.stubs(:my_instance_method).returns(:new_return_value) assert_equal :new_return_value, instance.send(:my_instance_method) end assert_passed(test_result) end assert_equal :original_return_value, instance.send(:my_instance_method) ensure Object.class_eval { remove_method :my_instance_method } end end mocha-1.3.0/test/acceptance/stub_class_method_defined_on_module_test.rb0000644000004100000410000000375313155337744026530 0ustar www-datawww-datarequire File.expand_path('../acceptance_test_helper', __FILE__) require 'mocha/setup' class StubClassMethodDefinedOnModuleTest < Mocha::TestCase include AcceptanceTest def setup setup_acceptance_test end def teardown teardown_acceptance_test end def test_should_stub_public_method_and_leave_it_unchanged_after_test mod = Module.new do def my_class_method :original_return_value end public :my_class_method end klass = Class.new do extend mod end assert_snapshot_unchanged(klass) do test_result = run_as_test do klass.stubs(:my_class_method).returns(:new_return_value) assert_equal :new_return_value, klass.my_class_method end assert_passed(test_result) end assert_equal :original_return_value, klass.my_class_method end def test_should_stub_protected_method_and_leave_it_unchanged_after_test mod = Module.new do def my_class_method :original_return_value end protected :my_class_method end klass = Class.new do extend mod end assert_snapshot_unchanged(klass) do test_result = run_as_test do klass.stubs(:my_class_method).returns(:new_return_value) assert_equal :new_return_value, klass.send(:my_class_method) end assert_passed(test_result) end assert_equal :original_return_value, klass.send(:my_class_method) end def test_should_stub_private_method_and_leave_it_unchanged_after_test mod = Module.new do def my_class_method :original_return_value end private :my_class_method end klass = Class.new do extend mod end assert_snapshot_unchanged(klass) do test_result = run_as_test do klass.stubs(:my_class_method).returns(:new_return_value) assert_equal :new_return_value, klass.send(:my_class_method) end assert_passed(test_result) end assert_equal :original_return_value, klass.send(:my_class_method) end end mocha-1.3.0/test/acceptance/stub_any_instance_method_defined_on_superclass_test.rb0000644000004100000410000000162213155337744030766 0ustar www-datawww-datarequire File.expand_path('../acceptance_test_helper', __FILE__) require 'mocha/setup' class StubAnyInstanceMethodDefinedOnSuperclassTest < Mocha::TestCase include AcceptanceTest def setup setup_acceptance_test end def teardown teardown_acceptance_test end def test_should_stub_method_and_leave_it_unchanged_after_test superklass = Class.new do def my_superclass_method :original_return_value end public :my_superclass_method end klass = Class.new(superklass) instance = klass.new assert_snapshot_unchanged(instance) do test_result = run_as_test do superklass.any_instance.stubs(:my_superclass_method).returns(:new_return_value) assert_equal :new_return_value, instance.my_superclass_method end assert_passed(test_result) end assert_equal :original_return_value, instance.my_superclass_method end endmocha-1.3.0/test/acceptance/stubbing_same_class_method_on_parent_and_child_classes_test.rb0000644000004100000410000000143413155337744032417 0ustar www-datawww-datarequire File.expand_path('../acceptance_test_helper', __FILE__) require 'mocha/setup' class StubbingSameClassMethodOnParentAndChildClassTest < Mocha::TestCase include AcceptanceTest def setup setup_acceptance_test end def teardown teardown_acceptance_test end def test_stubbing_same_method_on_parent_and_child_classes parent_class = Class.new do def self.foo "Parent.foo" end end child_class = Class.new(parent_class) test_result = run_as_tests( :test_1 => lambda { parent_class.stubs(:foo).returns("stubbed Parent.foo") child_class.stubs(:foo).returns("stubbed Child.foo") }, :test_2 => lambda { parent_class.foo child_class.foo } ) assert_passed(test_result) end end mocha-1.3.0/test/acceptance/acceptance_test_helper.rb0000644000004100000410000000136213155337744022726 0ustar www-datawww-datarequire File.expand_path('../../test_helper', __FILE__) require 'test_runner' require 'mocha/configuration' require 'introspection' module AcceptanceTest class FakeLogger attr_reader :warnings def initialize @warnings = [] end def warn(message) @warnings << message end end attr_reader :logger include TestRunner def setup_acceptance_test Mocha::Configuration.reset_configuration @logger = FakeLogger.new mockery = Mocha::Mockery.instance @original_logger = mockery.logger mockery.logger = @logger end def teardown_acceptance_test Mocha::Configuration.reset_configuration Mocha::Mockery.instance.logger = @original_logger end include Introspection::Assertions end mocha-1.3.0/test/acceptance/expectations_on_multiple_methods_test.rb0000644000004100000410000000266513155337744026150 0ustar www-datawww-datarequire File.expand_path('../acceptance_test_helper', __FILE__) require 'mocha/setup' class ExpectationsOnMultipleMethodsTest < Mocha::TestCase include AcceptanceTest def setup setup_acceptance_test end def teardown teardown_acceptance_test end def test_should_expect_calls_to_multiple_methods instance = Class.new do def my_instance_method_1 :original_return_value_1 end def my_instance_method_2 :original_return_value_2 end end.new test_result = run_as_test do instance.expects( :my_instance_method_1 => :new_return_value_1, :my_instance_method_2 => :new_return_value_2 ) assert_equal :new_return_value_1, instance.my_instance_method_1 assert_equal :new_return_value_2, instance.my_instance_method_2 end assert_passed(test_result) end def test_should_stub_calls_to_multiple_methods instance = Class.new do def my_instance_method_1 :original_return_value_1 end def my_instance_method_2 :original_return_value_2 end end.new test_result = run_as_test do instance.stubs( :my_instance_method_1 => :new_return_value_1, :my_instance_method_2 => :new_return_value_2 ) assert_equal :new_return_value_1, instance.my_instance_method_1 assert_equal :new_return_value_2, instance.my_instance_method_2 end assert_passed(test_result) end end mocha-1.3.0/test/acceptance/stub_class_method_defined_on_superclass_test.rb0000644000004100000410000000632713155337744027427 0ustar www-datawww-datarequire File.expand_path('../acceptance_test_helper', __FILE__) require 'mocha/setup' class StubClassMethodDefinedOnSuperclassTest < Mocha::TestCase include AcceptanceTest def setup setup_acceptance_test end def teardown teardown_acceptance_test end def test_should_stub_public_method_on_child_class_and_leave_it_unchanged_after_test superklass = Class.new do class << self def my_class_method :original_return_value end public :my_class_method end end klass = Class.new(superklass) assert_snapshot_unchanged(klass) do test_result = run_as_test do klass.stubs(:my_class_method).returns(:new_return_value) assert_equal :new_return_value, klass.my_class_method end assert_passed(test_result) end assert_equal :original_return_value, klass.my_class_method end def test_should_stub_protected_method_on_child_class_and_leave_it_unchanged_after_test superklass = Class.new do class << self def my_class_method :original_return_value end protected :my_class_method end end klass = Class.new(superklass) assert_snapshot_unchanged(klass) do test_result = run_as_test do klass.stubs(:my_class_method).returns(:new_return_value) assert_equal :new_return_value, klass.send(:my_class_method) end assert_passed(test_result) end assert_equal :original_return_value, klass.send(:my_class_method) end def test_should_stub_private_method_on_child_class_and_leave_it_unchanged_after_test superklass = Class.new do class << self def my_class_method :original_return_value end private :my_class_method end end klass = Class.new(superklass) assert_snapshot_unchanged(klass) do test_result = run_as_test do klass.stubs(:my_class_method).returns(:new_return_value) assert_equal :new_return_value, klass.send(:my_class_method) end assert_passed(test_result) end assert_equal :original_return_value, klass.send(:my_class_method) end def test_should_stub_method_on_superclass_and_leave_it_unchanged_after_test superklass = Class.new do class << self def my_class_method :original_return_value end public :my_class_method end end klass = Class.new(superklass) assert_snapshot_unchanged(klass) do test_result = run_as_test do superklass.stubs(:my_class_method).returns(:new_return_value) assert_equal :new_return_value, klass.my_class_method end assert_passed(test_result) end assert_equal :original_return_value, klass.my_class_method end def test_stub_on_earliest_receiver_should_take_priority superklass = Class.new do class << self def my_class_method :original_return_value end end end klass = Class.new(superklass) test_result = run_as_test do klass.stubs(:my_class_method).returns(:klass_return_value) superklass.stubs(:my_class_method).returns(:superklass_return_value) assert_equal :klass_return_value, klass.my_class_method end assert_passed(test_result) end end mocha-1.3.0/test/acceptance/stub_instance_method_defined_on_superclass_test.rb0000644000004100000410000000421613155337744030121 0ustar www-datawww-datarequire File.expand_path('../acceptance_test_helper', __FILE__) require 'mocha/setup' class StubInstanceMethodDefinedOnSuperclassTest < Mocha::TestCase include AcceptanceTest def setup setup_acceptance_test end def teardown teardown_acceptance_test end def test_should_stub_public_method_and_leave_it_unchanged_after_test superklass = Class.new do def my_superclass_method :original_return_value end public :my_superclass_method end klass = Class.new(superklass) instance = klass.new assert_snapshot_unchanged(instance) do test_result = run_as_test do instance.stubs(:my_superclass_method).returns(:new_return_value) assert_equal :new_return_value, instance.my_superclass_method end assert_passed(test_result) end assert_equal :original_return_value, instance.my_superclass_method end def test_should_stub_protected_method_and_leave_it_unchanged_after_test superklass = Class.new do def my_superclass_method :original_return_value end protected :my_superclass_method end klass = Class.new(superklass) instance = klass.new assert_snapshot_unchanged(instance) do test_result = run_as_test do instance.stubs(:my_superclass_method).returns(:new_return_value) assert_equal :new_return_value, instance.send(:my_superclass_method) end assert_passed(test_result) end assert_equal :original_return_value, instance.send(:my_superclass_method) end def test_should_stub_private_method_and_leave_it_unchanged_after_test superklass = Class.new do def my_superclass_method :original_return_value end private :my_superclass_method end klass = Class.new(superklass) instance = klass.new assert_snapshot_unchanged(instance) do test_result = run_as_test do instance.stubs(:my_superclass_method).returns(:new_return_value) assert_equal :new_return_value, instance.send(:my_superclass_method) end assert_passed(test_result) end assert_equal :original_return_value, instance.send(:my_superclass_method) end end mocha-1.3.0/test/acceptance/parameter_matcher_test.rb0000644000004100000410000002163313155337744022767 0ustar www-datawww-datarequire File.expand_path('../acceptance_test_helper', __FILE__) require 'mocha/setup' class ParameterMatcherTest < Mocha::TestCase include AcceptanceTest def setup setup_acceptance_test end def teardown teardown_acceptance_test end def test_should_match_hash_parameter_with_specified_key test_result = run_as_test do mock = mock() mock.expects(:method).with(has_key(:key_1)) mock.method(:key_1 => 'value_1', :key_2 => 'value_2') end assert_passed(test_result) end def test_should_not_match_hash_parameter_with_specified_key test_result = run_as_test do mock = mock() mock.expects(:method).with(has_key(:key_1)) mock.method(:key_2 => 'value_2') end assert_failed(test_result) end def test_should_match_hash_parameter_with_specified_value test_result = run_as_test do mock = mock() mock.expects(:method).with(has_value('value_1')) mock.method(:key_1 => 'value_1', :key_2 => 'value_2') end assert_passed(test_result) end def test_should_not_match_hash_parameter_with_specified_value test_result = run_as_test do mock = mock() mock.expects(:method).with(has_value('value_1')) mock.method(:key_2 => 'value_2') end assert_failed(test_result) end def test_should_match_hash_parameter_with_specified_key_value_pair test_result = run_as_test do mock = mock() mock.expects(:method).with(has_entry(:key_1, 'value_1')) mock.method(:key_1 => 'value_1', :key_2 => 'value_2') end assert_passed(test_result) end def test_should_not_match_hash_parameter_with_specified_key_value_pair test_result = run_as_test do mock = mock() mock.expects(:method).with(has_entry(:key_1, 'value_2')) mock.method(:key_1 => 'value_1', :key_2 => 'value_2') end assert_failed(test_result) end def test_should_match_hash_parameter_with_specified_hash_entry test_result = run_as_test do mock = mock() mock.expects(:method).with(has_entry(:key_1 => 'value_1')) mock.method(:key_1 => 'value_1', :key_2 => 'value_2') end assert_passed(test_result) end def test_should_not_match_hash_parameter_with_specified_hash_entry test_result = run_as_test do mock = mock() mock.expects(:method).with(has_entry(:key_1 => 'value_2')) mock.method(:key_1 => 'value_1', :key_2 => 'value_2') end assert_failed(test_result) end def test_should_match_hash_parameter_with_specified_entries test_result = run_as_test do mock = mock() mock.expects(:method).with(has_entries(:key_1 => 'value_1', :key_2 => 'value_2')) mock.method(:key_1 => 'value_1', :key_2 => 'value_2', :key_3 => 'value_3') end assert_passed(test_result) end def test_should_not_match_hash_parameter_with_specified_entries test_result = run_as_test do mock = mock() mock.expects(:method).with(has_entries(:key_1 => 'value_1', :key_2 => 'value_2')) mock.method(:key_1 => 'value_1', :key_2 => 'value_3') end assert_failed(test_result) end def test_should_match_parameter_that_matches_regular_expression test_result = run_as_test do mock = mock() mock.expects(:method).with(regexp_matches(/meter/)) mock.method('this parameter should match') end assert_passed(test_result) end def test_should_not_match_parameter_that_does_not_match_regular_expression test_result = run_as_test do mock = mock() mock.expects(:method).with(regexp_matches(/something different/)) mock.method('this parameter should not match') end assert_failed(test_result) end def test_should_match_hash_parameter_with_specified_entries_using_nested_matchers test_result = run_as_test do mock = mock() mock.expects(:method).with(has_entries(:key_1 => regexp_matches(/value_1/), kind_of(Symbol) => 'value_2')) mock.method(:key_1 => 'value_1', :key_2 => 'value_2', :key_3 => 'value_3') end assert_passed(test_result) end def test_should_not_match_hash_parameter_with_specified_entries_using_nested_matchers test_result = run_as_test do mock = mock() mock.expects(:method).with(has_entries(:key_1 => regexp_matches(/value_1/), kind_of(String) => 'value_2')) mock.method(:key_1 => 'value_2', :key_2 => 'value_3') end assert_failed(test_result) end def test_should_match_parameter_that_matches_any_value test_result = run_as_test do mock = mock() mock.expects(:method).with(any_of('value_1', 'value_2')).times(2) mock.method('value_1') mock.method('value_2') end assert_passed(test_result) end def test_should_not_match_parameter_that_does_not_match_any_value test_result = run_as_test do mock = mock() mock.expects(:method).with(any_of('value_1', 'value_2')) mock.method('value_3') end assert_failed(test_result) end def test_should_match_parameter_that_matches_any_of_the_given_matchers test_result = run_as_test do mock = mock() mock.expects(:method).with(has_key(:foo) | has_key(:bar)).times(2) mock.method(:foo => 'fooval') mock.method(:bar => 'barval') end assert_passed(test_result) end def test_should_not_match_parameter_that_does_not_match_any_of_the_given_matchers test_result = run_as_test do mock = mock() mock.expects(:method).with(has_key(:foo) | has_key(:bar)) mock.method(:baz => 'bazval') end assert_failed(test_result) end def test_should_match_parameter_that_matches_all_values test_result = run_as_test do mock = mock() mock.expects(:method).with(all_of('value_1', 'value_1')) mock.method('value_1') end assert_passed(test_result) end def test_should_not_match_parameter_that_does_not_match_all_values test_result = run_as_test do mock = mock() mock.expects(:method).with(all_of('value_1', 'value_2')) mock.method('value_1') end assert_failed(test_result) end def test_should_match_parameter_that_matches_all_matchers test_result = run_as_test do mock = mock() mock.expects(:method).with(has_key(:foo) & has_key(:bar)) mock.method(:foo => 'fooval', :bar => 'barval') end assert_passed(test_result) end def test_should_not_match_parameter_that_does_not_match_all_matchers test_result = run_as_test do mock = mock() mock.expects(:method).with(has_key(:foo) & has_key(:bar)) mock.method(:foo => 'fooval', :baz => 'bazval') end assert_failed(test_result) end def test_should_match_parameter_that_responds_with_specified_value klass = Class.new do def quack 'quack' end end duck = klass.new test_result = run_as_test do mock = mock() mock.expects(:method).with(responds_with(:quack, 'quack')) mock.method(duck) end assert_passed(test_result) end def test_should_not_match_parameter_that_does_not_respond_with_specified_value klass = Class.new do def quack 'woof' end end duck = klass.new test_result = run_as_test do mock = mock() mock.expects(:method).with(responds_with(:quack, 'quack')) mock.method(duck) end assert_failed(test_result) end def test_should_match_parameter_that_is_equivalent_uri test_result = run_as_test do mock = mock() mock.expects(:method).with(equivalent_uri('http://example.com/foo?b=2&a=1')) mock.method('http://example.com/foo?a=1&b=2') end assert_passed(test_result) end def test_should_not_match_parameter_that_is_not_equivalent test_result = run_as_test do mock = mock() mock.expects(:method).with(equivalent_uri('http://example.com/foo?a=1')) mock.method('http://example.com/foo?a=1&b=2') end assert_failed(test_result) end def test_should_match_parameter_when_value_is_divisible_by_four test_result = run_as_test do mock = mock() mock.expects(:method).with { |actual_value| actual_value % 4 == 0 } mock.method(8) end assert_passed(test_result) end def test_should_not_match_parameter_when_value_is_not_divisible_by_four test_result = run_as_test do mock = mock() mock.expects(:method).with { |actual_value| actual_value % 4 == 0 } mock.method(9) end assert_failed(test_result) end def test_should_match_parameters_when_values_add_up_to_ten test_result = run_as_test do mock = mock() matcher = lambda { |*values| values.inject(0) { |sum, n| sum + n } == 10 } mock.expects(:method).with(&matcher) mock.method(1, 2, 3, 4) end assert_passed(test_result) end def test_should_not_match_parameters_when_values_do_not_add_up_to_ten test_result = run_as_test do mock = mock() matcher = lambda { |*values| values.inject(0) { |sum, n| sum + n } == 10 } mock.expects(:method).with(&matcher) mock.method(1, 2, 3, 4, 5) end assert_failed(test_result) end end mocha-1.3.0/test/acceptance/mocked_methods_dispatch_test.rb0000644000004100000410000000412713155337744024147 0ustar www-datawww-datarequire File.expand_path('../acceptance_test_helper', __FILE__) require 'mocha/setup' class MockedMethodDispatchTest < Mocha::TestCase include AcceptanceTest def setup setup_acceptance_test end def teardown teardown_acceptance_test end def test_should_find_latest_matching_expectation test_result = run_as_test do mock = mock() mock.stubs(:method).returns(1) mock.stubs(:method).returns(2) assert_equal 2, mock.method assert_equal 2, mock.method assert_equal 2, mock.method end assert_passed(test_result) end def test_should_find_latest_expectation_which_has_not_stopped_matching test_result = run_as_test do mock = mock() mock.stubs(:method).returns(1) mock.stubs(:method).once.returns(2) assert_equal 2, mock.method assert_equal 1, mock.method assert_equal 1, mock.method end assert_passed(test_result) end def test_should_keep_finding_later_stub_and_so_never_satisfy_earlier_expectation test_result = run_as_test do mock = mock() mock.expects(:method).returns(1) mock.stubs(:method).returns(2) assert_equal 2, mock.method assert_equal 2, mock.method assert_equal 2, mock.method end assert_failed(test_result) end def test_should_find_later_expectation_until_it_stops_matching_then_find_earlier_stub test_result = run_as_test do mock = mock() mock.stubs(:method).returns(1) mock.expects(:method).returns(2) assert_equal 2, mock.method assert_equal 1, mock.method assert_equal 1, mock.method end assert_passed(test_result) end def test_should_find_latest_expectation_with_range_of_expected_invocation_count_which_has_not_stopped_matching test_result = run_as_test do mock = mock() mock.stubs(:method).returns(1) mock.stubs(:method).times(2..3).returns(2) assert_equal 2, mock.method assert_equal 2, mock.method assert_equal 2, mock.method assert_equal 1, mock.method assert_equal 1, mock.method end assert_passed(test_result) end end mocha-1.3.0/test/acceptance/stub_class_method_defined_on_class_test.rb0000644000004100000410000000440313155337744026341 0ustar www-datawww-datarequire File.expand_path('../acceptance_test_helper', __FILE__) require 'mocha/setup' class StubClassMethodDefinedOnClassTest < Mocha::TestCase include AcceptanceTest def setup setup_acceptance_test end def teardown teardown_acceptance_test end def test_should_stub_public_method_and_leave_it_unchanged_after_test klass = Class.new do class << self def my_class_method :original_return_value end public :my_class_method def self.public(*args); end end end assert_snapshot_unchanged(klass) do test_result = run_as_test do klass.stubs(:my_class_method).returns(:new_return_value) assert_method_visibility klass, :my_class_method, :public assert_equal :new_return_value, klass.my_class_method end assert_passed(test_result) end assert_equal :original_return_value, klass.my_class_method end def test_should_stub_protected_method_and_leave_it_unchanged_after_test klass = Class.new do class << self def my_class_method :original_return_value end protected :my_class_method def self.protected(*args); end end end assert_snapshot_unchanged(klass) do test_result = run_as_test do klass.stubs(:my_class_method).returns(:new_return_value) assert_method_visibility klass, :my_class_method, :protected assert_equal :new_return_value, klass.send(:my_class_method) end assert_passed(test_result) end assert_equal :original_return_value, klass.send(:my_class_method) end def test_should_stub_private_method_and_leave_it_unchanged_after_test klass = Class.new do class << self def my_class_method :original_return_value end private :my_class_method def self.private(*args); end end end assert_snapshot_unchanged(klass) do test_result = run_as_test do klass.stubs(:my_class_method).returns(:new_return_value) assert_method_visibility klass, :my_class_method, :private assert_equal :new_return_value, klass.send(:my_class_method) end assert_passed(test_result) end assert_equal :original_return_value, klass.send(:my_class_method) end end mocha-1.3.0/test/acceptance/failure_messages_test.rb0000644000004100000410000000345213155337744022621 0ustar www-datawww-datarequire File.expand_path('../acceptance_test_helper', __FILE__) require 'mocha/setup' class FailureMessagesTest < Mocha::TestCase OBJECT_ADDRESS_PATTERN = '0x[0-9A-Fa-f]{1,12}' include AcceptanceTest def setup setup_acceptance_test end def teardown teardown_acceptance_test end class Foo; end def test_should_display_class_name_when_expectation_was_on_class test_result = run_as_test do Foo.expects(:bar) end assert_match Regexp.new('FailureMessagesTest::Foo'), test_result.failures[0].message end def test_should_display_class_name_and_address_when_expectation_was_on_instance test_result = run_as_test do Foo.new.expects(:bar) end assert_match Regexp.new("#"), test_result.failures[0].message end def test_should_display_class_name_and_any_instance_prefix_when_expectation_was_on_any_instance test_result = run_as_test do Foo.any_instance.expects(:bar) end assert_match Regexp.new('#'), test_result.failures[0].message end def test_should_display_mock_name_when_expectation_was_on_named_mock test_result = run_as_test do foo = mock('foo') foo.expects(:bar) end assert_match Regexp.new('#'), test_result.failures[0].message end def test_should_display_mock_address_when_expectation_was_on_unnamed_mock test_result = run_as_test do foo = mock() foo.expects(:bar) end assert_match Regexp.new("#"), test_result.failures[0].message end def test_should_display_string_when_expectation_was_on_string test_result = run_as_test do 'Foo'.expects(:bar) end assert_match Regexp.new(%{"Foo"}), test_result.failures[0].message end end mocha-1.3.0/test/acceptance/stub_instance_method_defined_on_module_test.rb0000644000004100000410000000441713155337744027225 0ustar www-datawww-datarequire File.expand_path('../acceptance_test_helper', __FILE__) require 'mocha/setup' class StubInstanceMethodDefinedOnModuleTest < Mocha::TestCase include AcceptanceTest def setup setup_acceptance_test end def teardown teardown_acceptance_test end def test_should_stub_public_method_and_leave_it_unchanged_after_test mod = Module.new do def my_module_method :original_return_value end public :my_module_method end instance = Class.new do include mod end.new assert_snapshot_unchanged(instance) do test_result = run_as_test do instance.stubs(:my_module_method).returns(:new_return_value) assert_method_visibility instance, :my_module_method, :public assert_equal :new_return_value, instance.my_module_method end assert_passed(test_result) end assert_equal :original_return_value, instance.my_module_method end def test_should_stub_protected_method_and_leave_it_unchanged_after_test mod = Module.new do def my_module_method :original_return_value end protected :my_module_method end instance = Class.new do include mod end.new assert_snapshot_unchanged(instance) do test_result = run_as_test do instance.stubs(:my_module_method).returns(:new_return_value) assert_method_visibility instance, :my_module_method, :protected assert_equal :new_return_value, instance.send(:my_module_method) end assert_passed(test_result) end assert_equal :original_return_value, instance.send(:my_module_method) end def test_should_stub_private_method_and_leave_it_unchanged_after_test mod = Module.new do def my_module_method :original_return_value end private :my_module_method end instance = Class.new do include mod end.new assert_snapshot_unchanged(instance) do test_result = run_as_test do instance.stubs(:my_module_method).returns(:new_return_value) assert_method_visibility instance, :my_module_method, :private assert_equal :new_return_value, instance.send(:my_module_method) end assert_passed(test_result) end assert_equal :original_return_value, instance.send(:my_module_method) end end mocha-1.3.0/test/acceptance/stub_instance_method_defined_on_class_and_aliased_test.rb0000644000004100000410000000416213155337744031346 0ustar www-datawww-datarequire File.expand_path('../acceptance_test_helper', __FILE__) require 'mocha/setup' class StubInstanceMethodDefinedOnClassAndAliasedTest < Mocha::TestCase include AcceptanceTest def setup setup_acceptance_test end def teardown teardown_acceptance_test end def test_should_stub_public_method_and_leave_it_unchanged_after_test instance = Class.new do def my_instance_method :original_return_value end public :my_instance_method alias_method :my_aliased_method, :my_instance_method end.new assert_snapshot_unchanged(instance) do test_result = run_as_test do instance.stubs(:my_aliased_method).returns(:new_return_value) assert_equal :new_return_value, instance.my_aliased_method end assert_passed(test_result) end assert_equal :original_return_value, instance.my_aliased_method end def test_should_stub_protected_method_and_leave_it_unchanged_after_test instance = Class.new do def my_instance_method :original_return_value end protected :my_instance_method alias_method :my_aliased_method, :my_instance_method end.new assert_snapshot_unchanged(instance) do test_result = run_as_test do instance.stubs(:my_aliased_method).returns(:new_return_value) assert_equal :new_return_value, instance.send(:my_aliased_method) end assert_passed(test_result) end assert_equal :original_return_value, instance.send(:my_aliased_method) end def test_should_stub_private_method_and_leave_it_unchanged_after_test instance = Class.new do def my_instance_method :original_return_value end private :my_instance_method alias_method :my_aliased_method, :my_instance_method end.new assert_snapshot_unchanged(instance) do test_result = run_as_test do instance.stubs(:my_aliased_method).returns(:new_return_value) assert_equal :new_return_value, instance.send(:my_aliased_method) end assert_passed(test_result) end assert_equal :original_return_value, instance.send(:my_aliased_method) end end mocha-1.3.0/test/acceptance/stubbing_non_public_class_method_test.rb0000644000004100000410000001130313155337744026047 0ustar www-datawww-datarequire File.expand_path('../acceptance_test_helper', __FILE__) require 'mocha/setup' class StubbingNonPublicClassMethodTest < Mocha::TestCase include AcceptanceTest def setup setup_acceptance_test end def teardown teardown_acceptance_test end def test_should_allow_stubbing_private_class_method Mocha::Configuration.allow(:stubbing_non_public_method) klass = Class.new do class << self def private_method; end private :private_method end end test_result = run_as_test do klass.stubs(:private_method) end assert_passed(test_result) assert !@logger.warnings.include?("stubbing non-public method: #{klass.mocha_inspect}.private_method") end def test_should_allow_stubbing_protected_class_method Mocha::Configuration.allow(:stubbing_non_public_method) klass = Class.new do class << self def protected_method; end protected :protected_method end end test_result = run_as_test do klass.stubs(:protected_method) end assert_passed(test_result) assert !@logger.warnings.include?("stubbing non-public method: #{klass.mocha_inspect}.protected_method") end def test_should_warn_when_stubbing_private_class_method Mocha::Configuration.warn_when(:stubbing_non_public_method) klass = Class.new do class << self def private_method; end private :private_method end end test_result = run_as_test do klass.stubs(:private_method) end assert_passed(test_result) assert @logger.warnings.include?("stubbing non-public method: #{klass.mocha_inspect}.private_method") end def test_should_warn_when_stubbing_protected_class_method Mocha::Configuration.warn_when(:stubbing_non_public_method) klass = Class.new do class << self def protected_method; end protected :protected_method end end test_result = run_as_test do klass.stubs(:protected_method) end assert_passed(test_result) assert @logger.warnings.include?("stubbing non-public method: #{klass.mocha_inspect}.protected_method") end def test_should_prevent_stubbing_private_class_method Mocha::Configuration.prevent(:stubbing_non_public_method) klass = Class.new do class << self def private_method; end private :private_method end end test_result = run_as_test do klass.stubs(:private_method) end assert_failed(test_result) assert test_result.error_messages.include?("Mocha::StubbingError: stubbing non-public method: #{klass.mocha_inspect}.private_method") end def test_should_prevent_stubbing_protected_class_method Mocha::Configuration.prevent(:stubbing_non_public_method) klass = Class.new do class << self def protected_method; end protected :protected_method end end test_result = run_as_test do klass.stubs(:protected_method) end assert_failed(test_result) assert test_result.error_messages.include?("Mocha::StubbingError: stubbing non-public method: #{klass.mocha_inspect}.protected_method") end def test_should_default_to_allow_stubbing_private_class_method klass = Class.new do class << self def private_method; end private :private_method end end test_result = run_as_test do klass.stubs(:private_method) end assert_passed(test_result) assert !@logger.warnings.include?("stubbing non-public method: #{klass.mocha_inspect}.private_method") end def test_should_default_to_allow_stubbing_protected_class_method klass = Class.new do class << self def protected_method; end protected :protected_method end end test_result = run_as_test do klass.stubs(:protected_method) end assert_passed(test_result) assert !@logger.warnings.include?("stubbing non-public method: #{klass.mocha_inspect}.protected_method") end def test_should_allow_stubbing_public_class_method Mocha::Configuration.prevent(:stubbing_non_public_method) klass = Class.new do class << self def public_method; end public :public_method end end test_result = run_as_test do klass.stubs(:public_method) end assert_passed(test_result) end def test_should_allow_stubbing_method_to_which_class_responds Mocha::Configuration.prevent(:stubbing_non_public_method) klass = Class.new do class << self def respond_to?(method, include_private_methods = false) (method == :method_to_which_class_responds) end end end test_result = run_as_test do klass.stubs(:method_to_which_class_responds) end assert_passed(test_result) end end mocha-1.3.0/test/acceptance/issue_272_test.rb0000644000004100000410000000205413155337744021022 0ustar www-datawww-datarequire File.expand_path('../acceptance_test_helper', __FILE__) require 'mocha/setup' class Issue272Test < Mocha::TestCase include AcceptanceTest def setup setup_acceptance_test end def teardown teardown_acceptance_test end module Mod private def foo 'original-foo' end def bar 'original-bar' end end class Klass extend Mod class << self public :foo public :bar end end def test_private_methods_in_module_used_to_extend_class_and_made_public test_result = run_as_test do Klass.stubs(:foo).returns('stubbed-foo') # hangs in next line executing: # `@original_method = stubbee._method(method)` # in Mocha::ClassMethod#hide_original_method # but only in Ruby v2.3, not v2.2 Klass.stubs(:bar).returns('stubbed-bar') assert_equal 'stubbed-foo', Klass.foo assert_equal 'stubbed-bar', Klass.bar end assert_passed(test_result) assert_equal 'original-foo', Klass.foo assert_equal 'original-bar', Klass.bar end end mocha-1.3.0/test/acceptance/stubbing_non_existent_instance_method_test.rb0000644000004100000410000001120213155337744027131 0ustar www-datawww-datarequire File.expand_path('../acceptance_test_helper', __FILE__) require 'mocha/setup' class StubbingNonExistentInstanceMethodTest < Mocha::TestCase include AcceptanceTest def setup setup_acceptance_test end def teardown teardown_acceptance_test end def test_should_allow_stubbing_non_existent_instance_method Mocha::Configuration.allow(:stubbing_non_existent_method) instance = Class.new.new test_result = run_as_test do instance.stubs(:non_existent_method) end assert !@logger.warnings.include?("stubbing non-existent method: #{instance.mocha_inspect}.non_existent_method") assert_passed(test_result) end def test_should_warn_when_stubbing_non_existent_instance_method Mocha::Configuration.warn_when(:stubbing_non_existent_method) instance = Class.new.new test_result = run_as_test do instance.stubs(:non_existent_method) end assert_passed(test_result) assert @logger.warnings.include?("stubbing non-existent method: #{instance.mocha_inspect}.non_existent_method") end def test_should_prevent_stubbing_non_existent_instance_method Mocha::Configuration.prevent(:stubbing_non_existent_method) instance = Class.new.new test_result = run_as_test do instance.stubs(:non_existent_method) end assert_failed(test_result) assert test_result.error_messages.include?("Mocha::StubbingError: stubbing non-existent method: #{instance.mocha_inspect}.non_existent_method") end def test_should_default_to_allow_stubbing_non_existent_instance_method instance = Class.new.new test_result = run_as_test do instance.stubs(:non_existent_method) end assert !@logger.warnings.include?("stubbing non-existent method: #{instance.mocha_inspect}.non_existent_method") assert_passed(test_result) end def test_should_allow_stubbing_existing_public_instance_method Mocha::Configuration.prevent(:stubbing_non_existent_method) klass = Class.new do def existing_public_method; end public :existing_public_method end instance = klass.new test_result = run_as_test do instance.stubs(:existing_public_method) end assert_passed(test_result) end def test_should_allow_stubbing_method_to_which_instance_responds Mocha::Configuration.prevent(:stubbing_non_existent_method) klass = Class.new do def respond_to?(method, include_private = false) (method == :method_to_which_instance_responds) end end instance = klass.new test_result = run_as_test do instance.stubs(:method_to_which_instance_responds) end assert_passed(test_result) end def test_should_allow_stubbing_existing_protected_instance_method Mocha::Configuration.prevent(:stubbing_non_existent_method) klass = Class.new do def existing_protected_method; end protected :existing_protected_method end instance = klass.new test_result = run_as_test do instance.stubs(:existing_protected_method) end assert_passed(test_result) end def test_should_allow_stubbing_existing_private_instance_method Mocha::Configuration.prevent(:stubbing_non_existent_method) klass = Class.new do def existing_private_method; end private :existing_private_method end instance = klass.new test_result = run_as_test do instance.stubs(:existing_private_method) end assert_passed(test_result) end def test_should_allow_stubbing_existing_public_instance_superclass_method Mocha::Configuration.prevent(:stubbing_non_existent_method) superklass = Class.new do def existing_public_method; end public :existing_public_method end instance = Class.new(superklass).new test_result = run_as_test do instance.stubs(:existing_public_method) end assert_passed(test_result) end def test_should_allow_stubbing_existing_protected_instance_superclass_method Mocha::Configuration.prevent(:stubbing_non_existent_method) superklass = Class.new do def existing_protected_method; end protected :existing_protected_method end instance = Class.new(superklass).new test_result = run_as_test do instance.stubs(:existing_protected_method) end assert_passed(test_result) end def test_should_allow_stubbing_existing_private_instance_superclass_method Mocha::Configuration.prevent(:stubbing_non_existent_method) superklass = Class.new do def existing_private_method; end private :existing_private_method end instance = Class.new(superklass).new test_result = run_as_test do instance.stubs(:existing_private_method) end assert_passed(test_result) end end mocha-1.3.0/test/acceptance/partial_mocks_test.rb0000644000004100000410000000210413155337744022124 0ustar www-datawww-datarequire File.expand_path('../acceptance_test_helper', __FILE__) require 'mocha/setup' class PartialMockTest < Mocha::TestCase include AcceptanceTest def setup setup_acceptance_test end def teardown teardown_acceptance_test end def test_should_pass_if_all_expectations_are_satisfied test_result = run_as_test do partial_mock_one = "partial_mock_one" partial_mock_two = "partial_mock_two" partial_mock_one.expects(:first) partial_mock_one.expects(:second) partial_mock_two.expects(:third) partial_mock_one.first partial_mock_one.second partial_mock_two.third end assert_passed(test_result) end def test_should_fail_if_all_expectations_are_not_satisfied test_result = run_as_test do partial_mock_one = "partial_mock_one" partial_mock_two = "partial_mock_two" partial_mock_one.expects(:first) partial_mock_one.expects(:second) partial_mock_two.expects(:third) partial_mock_one.first partial_mock_two.third end assert_failed(test_result) end end mocha-1.3.0/test/acceptance/stub_instance_method_defined_on_class_test.rb0000644000004100000410000000423413155337744027042 0ustar www-datawww-datarequire File.expand_path('../acceptance_test_helper', __FILE__) require 'mocha/setup' class StubInstanceMethodDefinedOnClassTest < Mocha::TestCase include AcceptanceTest def setup setup_acceptance_test end def teardown teardown_acceptance_test end def test_should_stub_public_method_and_leave_it_unchanged_after_test instance = Class.new do def my_instance_method :original_return_value end public :my_instance_method end.new assert_snapshot_unchanged(instance) do test_result = run_as_test do instance.stubs(:my_instance_method).returns(:new_return_value) assert_method_visibility instance, :my_instance_method, :public assert_equal :new_return_value, instance.my_instance_method end assert_passed(test_result) end assert_equal :original_return_value, instance.my_instance_method end def test_should_stub_protected_method_and_leave_it_unchanged_after_test instance = Class.new do def my_instance_method :original_return_value end protected :my_instance_method end.new assert_snapshot_unchanged(instance) do test_result = run_as_test do instance.stubs(:my_instance_method).returns(:new_return_value) assert_method_visibility instance, :my_instance_method, :protected assert_equal :new_return_value, instance.send(:my_instance_method) end assert_passed(test_result) end assert_equal :original_return_value, instance.send(:my_instance_method) end def test_should_stub_private_method_and_leave_it_unchanged_after_test instance = Class.new do def my_instance_method :original_return_value end private :my_instance_method end.new assert_snapshot_unchanged(instance) do test_result = run_as_test do instance.stubs(:my_instance_method).returns(:new_return_value) assert_method_visibility instance, :my_instance_method, :private assert_equal :new_return_value, instance.send(:my_instance_method) end assert_passed(test_result) end assert_equal :original_return_value, instance.send(:my_instance_method) end end mocha-1.3.0/test/acceptance/stubbing_on_non_mock_object_test.rb0000644000004100000410000000444113155337744025024 0ustar www-datawww-datarequire File.expand_path('../acceptance_test_helper', __FILE__) require 'mocha/setup' class StubbingOnNonMockObjectTest < Mocha::TestCase include AcceptanceTest def setup setup_acceptance_test end def teardown teardown_acceptance_test end def test_should_allow_stubbing_method_on_non_mock_object Mocha::Configuration.allow(:stubbing_method_on_non_mock_object) non_mock_object = Class.new do def existing_method end end test_result = run_as_test do non_mock_object.stubs(:existing_method) end assert_passed(test_result) assert !@logger.warnings.include?("stubbing method on non-mock object: #{non_mock_object.mocha_inspect}.existing_method") end def test_should_warn_on_stubbing_method_on_non_mock_object Mocha::Configuration.warn_when(:stubbing_method_on_non_mock_object) non_mock_object = Class.new do def existing_method end end test_result = run_as_test do non_mock_object.stubs(:existing_method) end assert_passed(test_result) assert @logger.warnings.include?("stubbing method on non-mock object: #{non_mock_object.mocha_inspect}.existing_method") end def test_should_prevent_stubbing_method_on_non_mock_object Mocha::Configuration.prevent(:stubbing_method_on_non_mock_object) non_mock_object = Class.new do def existing_method end end test_result = run_as_test do non_mock_object.stubs(:existing_method) end assert_failed(test_result) assert test_result.error_messages.include?("Mocha::StubbingError: stubbing method on non-mock object: #{non_mock_object.mocha_inspect}.existing_method") end def test_should_default_to_allow_stubbing_method_on_non_mock_object non_mock_object = Class.new do def existing_method end end test_result = run_as_test do non_mock_object.stubs(:existing_method) end assert_passed(test_result) assert !@logger.warnings.include?("stubbing method on non-mock object: #{non_mock_object.mocha_inspect}.existing_method") end def test_should_allow_stubbing_method_on_mock_object Mocha::Configuration.prevent(:stubbing_method_on_non_mock_object) test_result = run_as_test do mock = mock('mock') mock.stubs(:any_method) end assert_passed(test_result) end end mocha-1.3.0/test/acceptance/states_test.rb0000644000004100000410000000307213155337744020604 0ustar www-datawww-datarequire File.expand_path('../acceptance_test_helper', __FILE__) require 'mocha/setup' class StatesTest < Mocha::TestCase include AcceptanceTest def setup setup_acceptance_test end def teardown teardown_acceptance_test end def test_should_constrain_expectations_to_occur_within_a_given_state test_result = run_as_test do mock = mock() readiness = states('readiness') mock.stubs(:first).when(readiness.is('ready')) mock.stubs(:second).then(readiness.is('ready')) mock.first end assert_failed(test_result) end def test_should_allow_expectations_to_occur_in_correct_state test_result = run_as_test do mock = mock() readiness = states('readiness') mock.stubs(:first).when(readiness.is('ready')) mock.stubs(:second).then(readiness.is('ready')) mock.second mock.first end assert_passed(test_result) end def test_should_be_able_to_start_in_a_specific_state test_result = run_as_test do mock = mock() readiness = states('readiness') mock.stubs(:first).when(readiness.is('ready')) readiness.starts_as('ready') mock.first end assert_passed(test_result) end def test_should_switch_state_when_method_raises_an_exception test_result = run_as_test do mock = mock() readiness = states('readiness') mock.expects(:first).raises().then(readiness.is('ready')) mock.expects(:second).when(readiness.is('ready')) mock.first rescue nil mock.second end assert_passed(test_result) end end mocha-1.3.0/test/acceptance/stubbing_frozen_object_test.rb0000644000004100000410000000563413155337744024035 0ustar www-datawww-datarequire File.expand_path('../acceptance_test_helper', __FILE__) require 'mocha/setup' require 'execution_point' class StubbingFrozenObjectTest < Mocha::TestCase include AcceptanceTest def setup setup_acceptance_test end def teardown teardown_acceptance_test end def test_should_fail_fast_if_attempting_to_stub_method_on_frozen_object object = Object.new object.freeze execution_point = nil test_result = run_as_test do execution_point = ExecutionPoint.current; object.stubs(:stubbed_method) end assert_failed(test_result) assert_equal 1, test_result.error_count assert_equal execution_point, ExecutionPoint.new(test_result.errors[0].exception.backtrace) end def test_should_fail_fast_if_attempting_to_expect_method_on_frozen_object object = Object.new object.freeze execution_point = nil test_result = run_as_test do execution_point = ExecutionPoint.current; object.expects(:stubbed_method) end assert_failed(test_result) assert_equal 1, test_result.error_count assert_equal execution_point, ExecutionPoint.new(test_result.errors[0].exception.backtrace) end def test_should_fail_fast_if_attempting_to_stub_method_on_frozen_class klass = Class.new klass.freeze execution_point = nil test_result = run_as_test do execution_point = ExecutionPoint.current; klass.stubs(:stubbed_method) end assert_failed(test_result) assert_equal 1, test_result.error_count assert_equal execution_point, ExecutionPoint.new(test_result.errors[0].exception.backtrace) end def test_should_fail_fast_if_attempting_to_expect_method_on_frozen_class klass = Class.new klass.freeze execution_point = nil test_result = run_as_test do execution_point = ExecutionPoint.current; klass.expects(:stubbed_method) end assert_failed(test_result) assert_equal 1, test_result.error_count assert_equal execution_point, ExecutionPoint.new(test_result.errors[0].exception.backtrace) end def test_should_fail_fast_if_attempting_to_stub_method_on_any_instance_of_frozen_class klass = Class.new klass.freeze execution_point = nil test_result = run_as_test do execution_point = ExecutionPoint.current; klass.any_instance.stubs(:stubbed_method) end assert_failed(test_result) assert_equal 1, test_result.error_count assert_equal execution_point, ExecutionPoint.new(test_result.errors[0].exception.backtrace) end def test_should_fail_fast_if_attempting_to_expect_method_on_any_instance_of_frozen_class klass = Class.new klass.freeze execution_point = nil test_result = run_as_test do execution_point = ExecutionPoint.current; klass.any_instance.expects(:stubbed_method) end assert_failed(test_result) assert_equal 1, test_result.error_count assert_equal execution_point, ExecutionPoint.new(test_result.errors[0].exception.backtrace) end end mocha-1.3.0/test/acceptance/stub_method_defined_on_module_and_aliased_test.rb0000644000004100000410000000202513155337744027636 0ustar www-datawww-datarequire File.expand_path('../acceptance_test_helper', __FILE__) require 'mocha/setup' unless Mocha::PRE_RUBY_V19 class StubMethodDefinedOnModuleAndAliasedTest < Mocha::TestCase include AcceptanceTest def setup setup_acceptance_test end def teardown teardown_acceptance_test end def test_stubbing_class_method_defined_by_aliasing_module_instance_method mod = Module.new do def module_instance_method 'module-instance-method' end end klass = Class.new do extend mod class << self alias_method :aliased_module_instance_method, :module_instance_method end end assert_snapshot_unchanged(klass) do test_result = run_as_test do klass.stubs(:aliased_module_instance_method).returns('stubbed-aliased-module-instance-method') assert_equal 'stubbed-aliased-module-instance-method', klass.aliased_module_instance_method end assert_passed(test_result) end end end end mocha-1.3.0/test/acceptance/multiple_expectations_failure_message_test.rb0000644000004100000410000000433713155337744027142 0ustar www-datawww-datarequire File.expand_path('../acceptance_test_helper', __FILE__) require 'mocha/setup' class FailureMessageTest < Mocha::TestCase include AcceptanceTest def setup setup_acceptance_test end def teardown teardown_acceptance_test end def test_should_include_unexpected_invocation_in_unsatisfied_expectation_message test_result = run_as_test do mock = mock('mock') mock.expects(:method_one).once 2.times { mock.method_one } end assert_failed(test_result) assert_equal [ "unexpected invocation: #.method_one()", "unsatisfied expectations:", "- expected exactly once, invoked twice: #.method_one(any_parameters)" ], test_result.failure_message_lines end def test_should_report_satisfied_expectations_as_well_as_unsatisfied_expectations test_result = run_as_test do mock = mock('mock') mock.expects(:method_one).once mock.expects(:method_two).twice 1.times { mock.method_one } 1.times { mock.method_two } end assert_failed(test_result) assert_equal [ "not all expectations were satisfied", "unsatisfied expectations:", "- expected exactly twice, invoked once: #.method_two(any_parameters)", "satisfied expectations:", "- expected exactly once, invoked once: #.method_one(any_parameters)" ], test_result.failure_message_lines end def test_should_report_multiple_satisfied_expectations test_result = run_as_test do mock = mock('mock') mock.expects(:method_one).once mock.expects(:method_two).twice mock.expects(:method_three).times(3) 1.times { mock.method_one } 2.times { mock.method_two } 2.times { mock.method_three } end assert_failed(test_result) assert_equal [ "not all expectations were satisfied", "unsatisfied expectations:", "- expected exactly 3 times, invoked twice: #.method_three(any_parameters)", "satisfied expectations:", "- expected exactly twice, invoked twice: #.method_two(any_parameters)", "- expected exactly once, invoked once: #.method_one(any_parameters)" ], test_result.failure_message_lines end end mocha-1.3.0/test/acceptance/stub_class_method_defined_on_active_record_association_proxy_test.rb0000644000004100000410000000667613155337744033720 0ustar www-datawww-datarequire File.expand_path('../acceptance_test_helper', __FILE__) require 'mocha/setup' class StubClassMethodDefinedOnActiveRecordAssociationProxyTest < Mocha::TestCase include AcceptanceTest def setup setup_acceptance_test end def teardown teardown_acceptance_test end def test_should_be_able_to_stub_method_if_ruby18_public_methods_include_method_but_method_does_not_actually_exist_like_active_record_association_proxy ruby18_klass = Class.new do class << self def public_methods(include_superclass = true) ['my_class_method'] end end end test_result = run_as_test do ruby18_klass.stubs(:my_class_method).returns(:new_return_value) assert_equal :new_return_value, ruby18_klass.my_class_method end assert_passed(test_result) end def test_should_be_able_to_stub_method_if_ruby19_public_methods_include_method_but_method_does_not_actually_exist_like_active_record_association_proxy ruby19_klass = Class.new do class << self def public_methods(include_superclass = true) [:my_class_method] end end end test_result = run_as_test do ruby19_klass.stubs(:my_class_method).returns(:new_return_value) assert_equal :new_return_value, ruby19_klass.my_class_method end assert_passed(test_result) end def test_should_be_able_to_stub_method_if_ruby18_protected_methods_include_method_but_method_does_not_actually_exist_like_active_record_association_proxy ruby18_klass = Class.new do class << self def protected_methods(include_superclass = true) ['my_class_method'] end end end test_result = run_as_test do ruby18_klass.stubs(:my_class_method).returns(:new_return_value) assert_equal :new_return_value, ruby18_klass.my_class_method end assert_passed(test_result) end def test_should_be_able_to_stub_method_if_ruby19_protected_methods_include_method_but_method_does_not_actually_exist_like_active_record_association_proxy ruby19_klass = Class.new do class << self def protected_methods(include_superclass = true) [:my_class_method] end end end test_result = run_as_test do ruby19_klass.stubs(:my_class_method).returns(:new_return_value) assert_equal :new_return_value, ruby19_klass.my_class_method end assert_passed(test_result) end def test_should_be_able_to_stub_method_if_ruby18_private_methods_include_method_but_method_does_not_actually_exist_like_active_record_association_proxy ruby18_klass = Class.new do class << self def private_methods(include_superclass = true) ['my_class_method'] end end end test_result = run_as_test do ruby18_klass.stubs(:my_class_method).returns(:new_return_value) assert_equal :new_return_value, ruby18_klass.my_class_method end assert_passed(test_result) end def test_should_be_able_to_stub_method_if_ruby19_private_methods_include_method_but_method_does_not_actually_exist_like_active_record_association_proxy ruby19_klass = Class.new do class << self def private_methods(include_superclass = true) [:my_class_method] end end end test_result = run_as_test do ruby19_klass.stubs(:my_class_method).returns(:new_return_value) assert_equal :new_return_value, ruby19_klass.my_class_method end assert_passed(test_result) end end mocha-1.3.0/test/acceptance/sequence_test.rb0000644000004100000410000001216613155337744021115 0ustar www-datawww-datarequire File.expand_path('../acceptance_test_helper', __FILE__) require 'mocha/setup' class SequenceTest < Mocha::TestCase include AcceptanceTest def setup setup_acceptance_test end def teardown teardown_acceptance_test end def test_should_constrain_invocations_to_occur_in_expected_order test_result = run_as_test do mock = mock() sequence = sequence('one') mock.expects(:first).in_sequence(sequence) mock.expects(:second).in_sequence(sequence) mock.second mock.first end assert_failed(test_result) end def test_should_allow_invocations_in_sequence test_result = run_as_test do mock = mock() sequence = sequence('one') mock.expects(:first).in_sequence(sequence) mock.expects(:second).in_sequence(sequence) mock.first mock.second end assert_passed(test_result) end def test_should_constrain_invocations_to_occur_in_expected_order_even_if_expected_on_different_mocks test_result = run_as_test do mock_one = mock('1') mock_two = mock('2') sequence = sequence('one') mock_one.expects(:first).in_sequence(sequence) mock_two.expects(:second).in_sequence(sequence) mock_two.second mock_one.first end assert_failed(test_result) end def test_should_allow_invocations_in_sequence_even_if_expected_on_different_mocks test_result = run_as_test do mock_one = mock('1') mock_two = mock('2') sequence = sequence('one') mock_one.expects(:first).in_sequence(sequence) mock_two.expects(:second).in_sequence(sequence) mock_one.first mock_two.second end assert_passed(test_result) end def test_should_constrain_invocations_to_occur_in_expected_order_even_if_expected_on_partial_mocks test_result = run_as_test do partial_mock_one = "1" partial_mock_two = "2" sequence = sequence('one') partial_mock_one.expects(:first).in_sequence(sequence) partial_mock_two.expects(:second).in_sequence(sequence) partial_mock_two.second partial_mock_one.first end assert_failed(test_result) end def test_should_allow_invocations_in_sequence_even_if_expected_on_partial_mocks test_result = run_as_test do partial_mock_one = "1" partial_mock_two = "2" sequence = sequence('one') partial_mock_one.expects(:first).in_sequence(sequence) partial_mock_two.expects(:second).in_sequence(sequence) partial_mock_one.first partial_mock_two.second end assert_passed(test_result) end def test_should_allow_stub_expectations_to_be_skipped_in_sequence test_result = run_as_test do mock = mock() sequence = sequence('one') mock.expects(:first).in_sequence(sequence) mock.stubs(:second).in_sequence(sequence) mock.expects(:third).in_sequence(sequence) mock.first mock.third end assert_passed(test_result) end def test_should_regard_sequences_as_independent_of_each_other test_result = run_as_test do mock = mock() sequence_one = sequence('one') sequence_two = sequence('two') mock.expects(:first).in_sequence(sequence_one) mock.expects(:second).in_sequence(sequence_one) mock.expects(:third).in_sequence(sequence_two) mock.expects(:fourth).in_sequence(sequence_two) mock.first mock.third mock.second mock.fourth end assert_passed(test_result) end def test_should_include_sequence_in_failure_message test_result = run_as_test do mock = mock() sequence = sequence('one') mock.expects(:first).in_sequence(sequence) mock.expects(:second).in_sequence(sequence) mock.second mock.first end assert_failed(test_result) assert_match Regexp.new(%{in sequence "one"}), test_result.failures.first.message end def test_should_allow_expectations_to_be_in_more_than_one_sequence test_result = run_as_test do mock = mock() sequence_one = sequence('one') sequence_two = sequence('two') mock.expects(:first).in_sequence(sequence_one) mock.expects(:second).in_sequence(sequence_two) mock.expects(:third).in_sequence(sequence_one).in_sequence(sequence_two) mock.first mock.third mock.second end assert_failed(test_result) assert_match Regexp.new(%{in sequence "one"}), test_result.failures.first.message assert_match Regexp.new(%{in sequence "two"}), test_result.failures.first.message end def test_should_have_shortcut_for_expectations_to_be_in_more_than_one_sequence test_result = run_as_test do mock = mock() sequence_one = sequence('one') sequence_two = sequence('two') mock.expects(:first).in_sequence(sequence_one) mock.expects(:second).in_sequence(sequence_two) mock.expects(:third).in_sequence(sequence_one, sequence_two) mock.first mock.third mock.second end assert_failed(test_result) assert_match Regexp.new(%{in sequence "one"}), test_result.failures.first.message assert_match Regexp.new(%{in sequence "two"}), test_result.failures.first.message end end mocha-1.3.0/test/acceptance/stubbing_nil_test.rb0000644000004100000410000000350013155337744021754 0ustar www-datawww-datarequire File.expand_path('../acceptance_test_helper', __FILE__) require 'mocha/setup' class StubbingNilTest < Mocha::TestCase include AcceptanceTest def setup setup_acceptance_test end def teardown teardown_acceptance_test end if RUBY_VERSION < '2.2.0' def test_should_allow_stubbing_method_on_nil Mocha::Configuration.allow(:stubbing_method_on_nil) test_result = run_as_test do nil.stubs(:stubbed_method) end assert_passed(test_result) assert !@logger.warnings.include?("stubbing method on nil: nil.stubbed_method") end def test_should_warn_on_stubbing_method_on_nil Mocha::Configuration.warn_when(:stubbing_method_on_nil) test_result = run_as_test do nil.stubs(:stubbed_method) end assert_passed(test_result) assert @logger.warnings.include?("stubbing method on nil: nil.stubbed_method") end def test_should_prevent_stubbing_method_on_nil Mocha::Configuration.prevent(:stubbing_method_on_nil) test_result = run_as_test do nil.stubs(:stubbed_method) end assert_failed(test_result) assert test_result.error_messages.include?("Mocha::StubbingError: stubbing method on nil: nil.stubbed_method") end def test_should_default_to_prevent_stubbing_method_on_non_mock_object test_result = run_as_test do nil.stubs(:stubbed_method) end assert_failed(test_result) assert test_result.error_messages.include?("Mocha::StubbingError: stubbing method on nil: nil.stubbed_method") end def test_should_allow_stubbing_method_on_non_nil_object Mocha::Configuration.prevent(:stubbing_method_on_nil) object = Object.new test_result = run_as_test do object.stubs(:stubbed_method) end assert_passed(test_result) end end end mocha-1.3.0/test/acceptance/stub_module_method_test.rb0000644000004100000410000001422313155337744023163 0ustar www-datawww-datarequire File.expand_path('../acceptance_test_helper', __FILE__) require 'mocha/setup' class StubModuleMethodTest < Mocha::TestCase include AcceptanceTest def setup setup_acceptance_test end def teardown teardown_acceptance_test end def test_should_stub_method_within_test mod = Module.new do def self.my_module_method :original_return_value end end test_result = run_as_test do mod.stubs(:my_module_method).returns(:new_return_value) assert_equal :new_return_value, mod.my_module_method end assert_passed(test_result) end def test_should_leave_stubbed_public_method_unchanged_after_test mod = Module.new do class << self def my_module_method :original_return_value end public :my_module_method end end run_as_test do mod.stubs(:my_module_method).returns(:new_return_value) end assert mod.public_methods(false).any? { |m| m.to_s == 'my_module_method' } assert_equal :original_return_value, mod.my_module_method end def test_should_leave_stubbed_protected_method_unchanged_after_test mod = Module.new do class << self def my_module_method :original_return_value end protected :my_module_method def my_unprotected_module_method my_module_method end end end run_as_test do mod.stubs(:my_module_method).returns(:new_return_value) end assert mod.protected_methods(false).any? { |m| m.to_s == 'my_module_method' } assert_equal :original_return_value, mod.my_unprotected_module_method end def test_should_leave_stubbed_private_method_unchanged_after_test mod = Module.new do class << self def my_module_method :original_return_value end private :my_module_method end end run_as_test do mod.stubs(:my_module_method).returns(:new_return_value) end assert mod.private_methods(false).any? { |m| m.to_s == 'my_module_method' } assert_equal :original_return_value, mod.send(:my_module_method) end def test_should_reset_expectations_after_test mod = Module.new do def self.my_module_method :original_return_value end end run_as_test do mod.stubs(:my_module_method) end assert_equal 0, mod.mocha.__expectations__.length end def test_should_be_able_to_stub_a_superclass_method supermod = Module.new do def self.my_superclass_method :original_return_value end end mod = Module.new do include supermod end test_result = run_as_test do mod.stubs(:my_superclass_method).returns(:new_return_value) assert_equal :new_return_value, mod.my_superclass_method end assert_passed(test_result) assert supermod.public_methods.any? { |m| m.to_s == 'my_superclass_method' } assert !mod.public_methods(false).any? { |m| m.to_s == 'my_superclass_method' } assert_equal :original_return_value, supermod.my_superclass_method end def test_should_be_able_to_stub_method_if_ruby18_public_methods_include_method_but_method_does_not_actually_exist_like_active_record_association_proxy ruby18_mod = Module.new do class << self def public_methods(include_superclass = true) ['my_module_method'] end end end test_result = run_as_test do ruby18_mod.stubs(:my_module_method).returns(:new_return_value) assert_equal :new_return_value, ruby18_mod.my_module_method end assert_passed(test_result) end def test_should_be_able_to_stub_method_if_ruby19_public_methods_include_method_but_method_does_not_actually_exist_like_active_record_association_proxy ruby19_mod = Module.new do class << self def public_methods(include_superclass = true) [:my_module_method] end end end test_result = run_as_test do ruby19_mod.stubs(:my_module_method).returns(:new_return_value) assert_equal :new_return_value, ruby19_mod.my_module_method end assert_passed(test_result) end def test_should_be_able_to_stub_method_if_ruby_18_protected_methods_include_method_but_method_does_not_actually_exist_like_active_record_association_proxy ruby18_mod = Module.new do class << self def protected_methods(include_superclass = true) ['my_module_method'] end end end test_result = run_as_test do ruby18_mod.stubs(:my_module_method).returns(:new_return_value) assert_equal :new_return_value, ruby18_mod.my_module_method end assert_passed(test_result) end def test_should_be_able_to_stub_method_if_ruby19_protected_methods_include_method_but_method_does_not_actually_exist_like_active_record_association_proxy ruby19_mod = Module.new do class << self def protected_methods(include_superclass = true) [:my_module_method] end end end test_result = run_as_test do ruby19_mod.stubs(:my_module_method).returns(:new_return_value) assert_equal :new_return_value, ruby19_mod.my_module_method end assert_passed(test_result) end def test_should_be_able_to_stub_method_if_ruby18_private_methods_include_method_but_method_does_not_actually_exist_like_active_record_association_proxy ruby18_mod = Module.new do class << self def private_methods(include_superclass = true) ['my_module_method'] end end end test_result = run_as_test do ruby18_mod.stubs(:my_module_method).returns(:new_return_value) assert_equal :new_return_value, ruby18_mod.my_module_method end assert_passed(test_result) end def test_should_be_able_to_stub_method_if_ruby19_private_methods_include_method_but_method_does_not_actually_exist_like_active_record_association_proxy ruby19_mod = Module.new do class << self def private_methods(include_superclass = true) [:my_module_method] end end end test_result = run_as_test do ruby19_mod.stubs(:my_module_method).returns(:new_return_value) assert_equal :new_return_value, ruby19_mod.my_module_method end assert_passed(test_result) end end mocha-1.3.0/test/acceptance/stubbing_method_accepting_block_parameter_test.rb0000644000004100000410000000262113155337744027704 0ustar www-datawww-datarequire File.expand_path('../acceptance_test_helper', __FILE__) require 'mocha/setup' class StubbingMethodAcceptingBlockParameterTest < Mocha::TestCase include AcceptanceTest def setup setup_acceptance_test end def teardown teardown_acceptance_test end def test_stubbing_class_method_accepting_block_parameter_should_restore_original_method klass = Class.new do def self.my_class_method(&block); block.call; end end test_result = run_as_test do klass.stubs(:my_class_method) end assert_passed(test_result) assert_equal :return_value, klass.my_class_method { :return_value } end def test_stubbing_instance_method_accepting_block_parameter_should_restore_original_method instance = Class.new do def my_instance_method(&block); block.call; end end.new test_result = run_as_test do instance.stubs(:my_instance_method) end assert_passed(test_result) assert_equal :return_value, instance.my_instance_method { :return_value } end def test_stubbing_any_instance_method_accepting_block_parameter_should_restore_original_method klass = Class.new do def my_instance_method(&block); block.call; end end test_result = run_as_test do klass.any_instance.stubs(:my_instance_method) end assert_passed(test_result) assert_equal :return_value, klass.new.my_instance_method { :return_value } end end mocha-1.3.0/test/acceptance/mock_test.rb0000644000004100000410000000501613155337744020232 0ustar www-datawww-datarequire File.expand_path('../acceptance_test_helper', __FILE__) require 'mocha/setup' class MockTest < Mocha::TestCase include AcceptanceTest def setup setup_acceptance_test end def teardown teardown_acceptance_test end def test_should_build_mock_and_explicitly_add_an_expectation_which_is_satisfied test_result = run_as_test do foo = mock() foo.expects(:bar) foo.bar end assert_passed(test_result) end def test_should_build_mock_and_explicitly_add_an_expectation_which_is_not_satisfied test_result = run_as_test do foo = mock() foo.expects(:bar) end assert_failed(test_result) end def test_should_build_named_mock_and_explicitly_add_an_expectation_which_is_satisfied test_result = run_as_test do foo = mock('foo') foo.expects(:bar) foo.bar end assert_passed(test_result) end def test_should_build_named_mock_and_explicitly_add_an_expectation_which_is_not_satisfied test_result = run_as_test do foo = mock('foo') foo.expects(:bar) end assert_failed(test_result) end def test_should_build_mock_incorporating_two_expectations_which_are_satisifed test_result = run_as_test do foo = mock(:bar => 'bar', :baz => 'baz') foo.bar foo.baz end assert_passed(test_result) end def test_should_build_mock_incorporating_two_expectations_the_first_of_which_is_not_satisifed test_result = run_as_test do foo = mock(:bar => 'bar', :baz => 'baz') foo.baz end assert_failed(test_result) end def test_should_build_mock_incorporating_two_expectations_the_second_of_which_is_not_satisifed test_result = run_as_test do foo = mock(:bar => 'bar', :baz => 'baz') foo.bar end assert_failed(test_result) end def test_should_build_named_mock_incorporating_two_expectations_which_are_satisifed test_result = run_as_test do foo = mock('foo', :bar => 'bar', :baz => 'baz') foo.bar foo.baz end assert_passed(test_result) end def test_should_build_named_mock_incorporating_two_expectations_the_first_of_which_is_not_satisifed test_result = run_as_test do foo = mock('foo', :bar => 'bar', :baz => 'baz') foo.baz end assert_failed(test_result) end def test_should_build_named_mock_incorporating_two_expectations_the_second_of_which_is_not_satisifed test_result = run_as_test do foo = mock('foo', :bar => 'bar', :baz => 'baz') foo.bar end assert_failed(test_result) end end mocha-1.3.0/test/acceptance/stub_everything_test.rb0000644000004100000410000000237313155337744022525 0ustar www-datawww-datarequire File.expand_path('../acceptance_test_helper', __FILE__) require 'mocha/setup' class StubEverythingTest < Mocha::TestCase include AcceptanceTest def setup setup_acceptance_test end def teardown teardown_acceptance_test end def test_should_build_stub_and_explicitly_add_an_expectation test_result = run_as_test do foo = stub_everything() foo.stubs(:bar) foo.bar foo.unexpected_invocation end assert_passed(test_result) end def test_should_build_named_stub_and_explicitly_add_an_expectation test_result = run_as_test do foo = stub_everything('foo') foo.stubs(:bar) foo.bar foo.unexpected_invocation end assert_passed(test_result) end def test_should_build_stub_incorporating_two_expectations test_result = run_as_test do foo = stub_everything(:bar => 'bar', :baz => 'baz') foo.bar foo.baz foo.unexpected_invocation end assert_passed(test_result) end def test_should_build_named_stub_incorporating_two_expectations test_result = run_as_test do foo = stub_everything('foo', :bar => 'bar', :baz => 'baz') foo.bar foo.baz foo.unexpected_invocation end assert_passed(test_result) end end mocha-1.3.0/test/acceptance/expected_invocation_count_test.rb0000644000004100000410000001610213155337744024541 0ustar www-datawww-datarequire File.expand_path('../acceptance_test_helper', __FILE__) require 'mocha/setup' class ExpectedInvocationCountTest < Mocha::TestCase include AcceptanceTest def setup setup_acceptance_test end def teardown teardown_acceptance_test end def test_should_pass_if_method_is_never_expected_and_is_never_called test_result = run_as_test do mock = mock('mock') mock.expects(:method).never 0.times { mock.method } end assert_passed(test_result) end def test_should_fail_fast_if_method_is_never_expected_but_is_called_once test_result = run_as_test do mock = mock('mock') mock.expects(:method).never 1.times { mock.method } end assert_failed(test_result) assert_equal [ "unexpected invocation: #.method()", "unsatisfied expectations:", "- expected never, invoked once: #.method(any_parameters)" ], test_result.failure_message_lines end def test_should_pass_if_method_is_expected_twice_and_is_called_twice test_result = run_as_test do mock = mock('mock') mock.expects(:method).twice 2.times { mock.method } end assert_passed(test_result) end def test_should_fail_if_method_is_expected_twice_but_is_called_once test_result = run_as_test do mock = mock('mock') mock.expects(:method).twice 1.times { mock.method } end assert_failed(test_result) assert_equal [ "not all expectations were satisfied", "unsatisfied expectations:", "- expected exactly twice, invoked once: #.method(any_parameters)" ], test_result.failure_message_lines end def test_should_fail_fast_if_method_is_expected_twice_but_is_called_three_times test_result = run_as_test do mock = mock('mock') mock.expects(:method).twice 3.times { mock.method } end assert_failed(test_result) assert_equal [ "unexpected invocation: #.method()", "unsatisfied expectations:", "- expected exactly twice, invoked 3 times: #.method(any_parameters)" ], test_result.failure_message_lines end def test_should_pass_if_method_is_expected_between_two_and_four_times_and_is_called_twice test_result = run_as_test do mock = mock('mock') mock.expects(:method).times(2..4) 2.times { mock.method } end assert_passed(test_result) end def test_should_pass_if_method_is_expected_between_two_and_four_times_and_is_called_three_times test_result = run_as_test do mock = mock('mock') mock.expects(:method).times(2..4) 3.times { mock.method } end assert_passed(test_result) end def test_should_pass_if_method_is_expected_between_two_and_four_times_and_is_called_four_times test_result = run_as_test do mock = mock('mock') mock.expects(:method).times(2..4) 4.times { mock.method } end assert_passed(test_result) end def test_should_fail_if_method_is_expected_between_two_and_four_times_and_is_called_once test_result = run_as_test do mock = mock('mock') mock.expects(:method).times(2..4) 1.times { mock.method } end assert_failed(test_result) assert_equal [ "not all expectations were satisfied", "unsatisfied expectations:", "- expected between 2 and 4 times, invoked once: #.method(any_parameters)" ], test_result.failure_message_lines end def test_should_fail_fast_if_method_is_expected_between_two_and_four_times_and_is_called_five_times test_result = run_as_test do mock = mock('mock') mock.expects(:method).times(2..4) 5.times { mock.method } end assert_failed(test_result) assert_equal [ "unexpected invocation: #.method()", "unsatisfied expectations:", "- expected between 2 and 4 times, invoked 5 times: #.method(any_parameters)" ], test_result.failure_message_lines end def test_should_pass_if_method_is_expected_at_least_once_and_is_called_once test_result = run_as_test do mock = mock('mock') mock.expects(:method).at_least_once 1.times { mock.method } end assert_passed(test_result) end def test_should_pass_if_method_is_expected_at_least_once_and_is_called_twice test_result = run_as_test do mock = mock('mock') mock.expects(:method).at_least_once 2.times { mock.method } end assert_passed(test_result) end def test_should_fail_if_method_is_expected_at_least_once_but_is_never_called test_result = run_as_test do mock = mock('mock') mock.expects(:method).at_least_once 0.times { mock.method } end assert_failed(test_result) assert_equal [ "not all expectations were satisfied", "unsatisfied expectations:", "- expected at least once, not yet invoked: #.method(any_parameters)" ], test_result.failure_message_lines end def test_should_pass_if_method_is_expected_at_most_once_and_is_never_called test_result = run_as_test do mock = mock('mock') mock.expects(:method).at_most_once 0.times { mock.method } end assert_passed(test_result) end def test_should_pass_if_method_is_expected_at_most_once_and_called_once test_result = run_as_test do mock = mock('mock') mock.expects(:method).at_most_once 1.times { mock.method } end assert_passed(test_result) end def test_should_fail_fast_if_method_is_expected_at_most_once_but_is_called_twice test_result = run_as_test do mock = mock('mock') mock.expects(:method).at_most_once 2.times { mock.method } end assert_failed(test_result) assert_equal [ "unexpected invocation: #.method()", "unsatisfied expectations:", "- expected at most once, invoked twice: #.method(any_parameters)" ], test_result.failure_message_lines end def test_should_pass_if_method_is_never_expected_and_is_never_called_even_if_everything_is_stubbed test_result = run_as_test do stub = stub_everything('stub') stub.expects(:method).never 0.times { stub.method } end assert_passed(test_result) end def test_should_fail_fast_if_method_is_never_expected_but_is_called_once_even_if_everything_is_stubbed test_result = run_as_test do stub = stub_everything('stub') stub.expects(:method).never 1.times { stub.method } end assert_failed(test_result) assert_equal [ "unexpected invocation: #.method()", "unsatisfied expectations:", "- expected never, invoked once: #.method(any_parameters)" ], test_result.failure_message_lines end def test_should_fail_fast_if_there_is_no_matching_expectation test_result = run_as_test do mock = mock('mock') mock.expects(:method).with(1) 1.times { mock.method } end assert_failed(test_result) assert_equal [ "unexpected invocation: #.method()", "unsatisfied expectations:", "- expected exactly once, not yet invoked: #.method(1)" ], test_result.failure_message_lines end end mocha-1.3.0/test/acceptance/stubbing_non_public_any_instance_method_test.rb0000644000004100000410000001036113155337744027420 0ustar www-datawww-datarequire File.expand_path('../acceptance_test_helper', __FILE__) require 'mocha/setup' class StubbingNonPublicAnyInstanceMethodTest < Mocha::TestCase include AcceptanceTest def setup setup_acceptance_test end def teardown teardown_acceptance_test end def test_should_allow_stubbing_private_any_instance_method Mocha::Configuration.allow(:stubbing_non_public_method) klass = Class.new do def private_method; end private :private_method end test_result = run_as_test do klass.any_instance.stubs(:private_method) end assert_passed(test_result) assert !@logger.warnings.include?("stubbing non-public method: #{klass.any_instance.mocha_inspect}.private_method") end def test_should_allow_stubbing_protected_any_instance_method Mocha::Configuration.allow(:stubbing_non_public_method) klass = Class.new do def protected_method; end protected :protected_method end test_result = run_as_test do klass.any_instance.stubs(:protected_method) end assert_passed(test_result) assert !@logger.warnings.include?("stubbing non-public method: #{klass.any_instance.mocha_inspect}.protected_method") end def test_should_warn_when_stubbing_private_any_instance_method Mocha::Configuration.warn_when(:stubbing_non_public_method) klass = Class.new do def private_method; end private :private_method end test_result = run_as_test do klass.any_instance.stubs(:private_method) end assert_passed(test_result) assert @logger.warnings.include?("stubbing non-public method: #{klass.any_instance.mocha_inspect}.private_method") end def test_should_warn_when_stubbing_protected_any_instance_method Mocha::Configuration.warn_when(:stubbing_non_public_method) klass = Class.new do def protected_method; end protected :protected_method end test_result = run_as_test do klass.any_instance.stubs(:protected_method) end assert_passed(test_result) assert @logger.warnings.include?("stubbing non-public method: #{klass.any_instance.mocha_inspect}.protected_method") end def test_should_prevent_stubbing_private_any_instance_method Mocha::Configuration.prevent(:stubbing_non_public_method) klass = Class.new do def private_method; end private :private_method end test_result = run_as_test do klass.any_instance.stubs(:private_method) end assert_failed(test_result) assert test_result.error_messages.include?("Mocha::StubbingError: stubbing non-public method: #{klass.any_instance.mocha_inspect}.private_method") end def test_should_prevent_stubbing_protected_any_instance_method Mocha::Configuration.prevent(:stubbing_non_public_method) klass = Class.new do def protected_method; end protected :protected_method end test_result = run_as_test do klass.any_instance.stubs(:protected_method) end assert_failed(test_result) assert test_result.error_messages.include?("Mocha::StubbingError: stubbing non-public method: #{klass.any_instance.mocha_inspect}.protected_method") end def test_should_default_to_allow_stubbing_private_any_instance_method klass = Class.new do def private_method; end private :private_method end test_result = run_as_test do klass.any_instance.stubs(:private_method) end assert_passed(test_result) assert !@logger.warnings.include?("stubbing non-public method: #{klass.any_instance.mocha_inspect}.private_method") end def test_should_default_to_allow_stubbing_protected_any_instance_method klass = Class.new do def protected_method; end protected :protected_method end test_result = run_as_test do klass.any_instance.stubs(:protected_method) end assert_passed(test_result) assert !@logger.warnings.include?("stubbing non-public method: #{klass.any_instance.mocha_inspect}.protected_method") end def test_should_allow_stubbing_public_any_instance_method Mocha::Configuration.prevent(:stubbing_non_public_method) klass = Class.new do def public_method; end public :public_method end test_result = run_as_test do klass.any_instance.stubs(:public_method) end assert_passed(test_result) end end mocha-1.3.0/test/acceptance/exception_rescue_test.rb0000644000004100000410000000300713155337744022643 0ustar www-datawww-datarequire File.expand_path('../acceptance_test_helper', __FILE__) require 'mocha/setup' class ExceptionRescueTest < Mocha::TestCase include AcceptanceTest def setup setup_acceptance_test end def teardown teardown_acceptance_test end def test_unexpected_invocation_exception_is_not_caught_by_standard_rescue test_result = run_as_test do mock = mock('mock') begin mock.some_method rescue => e flunk "should not rescue #{e.class}" end end assert_failed(test_result) assert_equal "unexpected invocation: #.some_method()", test_result.failure_message_lines[0] end def test_invocation_never_expected_exception_is_not_caught_by_standard_rescue test_result = run_as_test do mock = mock('mock') mock.expects(:some_method).never begin mock.some_method rescue => e flunk "should not rescue #{e.class}" end end assert_failed(test_result) assert_equal "unexpected invocation: #.some_method()", test_result.failure_message_lines[0] end def test_unsatisfied_expectation_exception_is_not_caught_by_standard_rescue test_result = run_as_test do mock = mock('mock') mock.expects(:some_method) end assert_failed(test_result) assert_equal [ "not all expectations were satisfied", "unsatisfied expectations:", "- expected exactly once, not yet invoked: #.some_method(any_parameters)" ], test_result.failure_message_lines end end mocha-1.3.0/test/acceptance/stubbing_non_public_instance_method_test.rb0000644000004100000410000001102013155337744026542 0ustar www-datawww-datarequire File.expand_path('../acceptance_test_helper', __FILE__) require 'mocha/setup' class StubbingNonPublicInstanceMethodTest < Mocha::TestCase include AcceptanceTest def setup setup_acceptance_test end def teardown teardown_acceptance_test end def test_should_allow_stubbing_private_instance_method Mocha::Configuration.allow(:stubbing_non_public_method) instance = Class.new do def private_method; end private :private_method end.new test_result = run_as_test do instance.stubs(:private_method) end assert_passed(test_result) assert !@logger.warnings.include?("stubbing non-public method: #{instance.mocha_inspect}.private_method") end def test_should_allow_stubbing_protected_instance_method Mocha::Configuration.allow(:stubbing_non_public_method) instance = Class.new do def protected_method; end protected :protected_method end.new test_result = run_as_test do instance.stubs(:protected_method) end assert_passed(test_result) assert !@logger.warnings.include?("stubbing non-public method: #{instance.mocha_inspect}.protected_method") end def test_should_warn_when_stubbing_private_instance_method Mocha::Configuration.warn_when(:stubbing_non_public_method) instance = Class.new do def private_method; end private :private_method end.new test_result = run_as_test do instance.stubs(:private_method) end assert_passed(test_result) assert @logger.warnings.include?("stubbing non-public method: #{instance.mocha_inspect}.private_method") end def test_should_warn_when_stubbing_protected_instance_method Mocha::Configuration.warn_when(:stubbing_non_public_method) instance = Class.new do def protected_method; end protected :protected_method end.new test_result = run_as_test do instance.stubs(:protected_method) end assert_passed(test_result) assert @logger.warnings.include?("stubbing non-public method: #{instance.mocha_inspect}.protected_method") end def test_should_prevent_stubbing_private_instance_method Mocha::Configuration.prevent(:stubbing_non_public_method) instance = Class.new do def private_method; end private :private_method end.new test_result = run_as_test do instance.stubs(:private_method) end assert_failed(test_result) assert test_result.error_messages.include?("Mocha::StubbingError: stubbing non-public method: #{instance.mocha_inspect}.private_method") end def test_should_prevent_stubbing_protected_instance_method Mocha::Configuration.prevent(:stubbing_non_public_method) instance = Class.new do def protected_method; end protected :protected_method end.new test_result = run_as_test do instance.stubs(:protected_method) end assert_failed(test_result) assert test_result.error_messages.include?("Mocha::StubbingError: stubbing non-public method: #{instance.mocha_inspect}.protected_method") end def test_should_default_to_allow_stubbing_private_instance_method instance = Class.new do def private_method; end private :private_method end.new test_result = run_as_test do instance.stubs(:private_method) end assert_passed(test_result) assert !@logger.warnings.include?("stubbing non-public method: #{instance.mocha_inspect}.private_method") end def test_should_default_to_allow_stubbing_protected_instance_method instance = Class.new do def protected_method; end protected :protected_method end.new test_result = run_as_test do instance.stubs(:protected_method) end assert_passed(test_result) assert !@logger.warnings.include?("stubbing non-public method: #{instance.mocha_inspect}.protected_method") end def test_should_allow_stubbing_public_instance_method Mocha::Configuration.prevent(:stubbing_non_public_method) instance = Class.new do def public_method; end public :public_method end.new test_result = run_as_test do instance.stubs(:public_method) end assert_passed(test_result) end def test_should_allow_stubbing_method_to_which_instance_responds Mocha::Configuration.prevent(:stubbing_non_public_method) instance = Class.new do def respond_to?(method, include_private_methods = false) (method == :method_to_which_instance_responds) end end.new test_result = run_as_test do instance.stubs(:method_to_which_instance_responds) end assert_passed(test_result) end end mocha-1.3.0/test/acceptance/stubbing_method_unnecessarily_test.rb0000644000004100000410000000376713155337744025435 0ustar www-datawww-datarequire File.expand_path('../acceptance_test_helper', __FILE__) require 'mocha/setup' class StubbingMethodUnnecessarilyTest < Mocha::TestCase include AcceptanceTest def setup setup_acceptance_test end def teardown teardown_acceptance_test end def test_should_allow_stubbing_method_unnecessarily Mocha::Configuration.allow(:stubbing_method_unnecessarily) test_result = run_as_test do mock = mock('mock') mock.stubs(:public_method) end assert_passed(test_result) assert !@logger.warnings.include?('stubbing method unnecessarily: #.public_method(any_parameters)') end def test_should_warn_when_stubbing_method_unnecessarily Mocha::Configuration.warn_when(:stubbing_method_unnecessarily) test_result = run_as_test do mock = mock('mock') mock.stubs(:public_method) end assert_passed(test_result) assert @logger.warnings.include?('stubbing method unnecessarily: #.public_method(any_parameters)') end def test_should_prevent_stubbing_method_unnecessarily Mocha::Configuration.prevent(:stubbing_method_unnecessarily) test_result = run_as_test do mock = mock('mock') mock.stubs(:public_method) end assert_failed(test_result) assert test_result.error_messages.include?('Mocha::StubbingError: stubbing method unnecessarily: #.public_method(any_parameters)') end def test_should_default_to_allow_stubbing_method_unnecessarily test_result = run_as_test do mock = mock('mock') mock.stubs(:public_method) end assert_passed(test_result) assert !@logger.warnings.include?('stubbing method unnecessarily: #.public_method(any_parameters)') end def test_should_allow_stubbing_method_when_stubbed_method_is_invoked Mocha::Configuration.prevent(:stubbing_method_unnecessarily) test_result = run_as_test do mock = mock('mock') mock.stubs(:public_method) mock.public_method end assert_passed(test_result) end end mocha-1.3.0/test/acceptance/raise_exception_test.rb0000644000004100000410000000204013155337744022454 0ustar www-datawww-datarequire File.expand_path('../acceptance_test_helper', __FILE__) require 'mocha/setup' class RaiseExceptionTest < Mocha::TestCase include AcceptanceTest def setup setup_acceptance_test end def teardown teardown_acceptance_test end def test_should_raise_exception exception_class = Class.new(StandardError) test_result = run_as_test do foo = stub('foo') foo.stubs(:bar).raises(exception_class, "my-message") exception = assert_raises(exception_class) { foo.bar } assert_equal "my-message", exception.message end assert_passed(test_result) end def test_should_raise_two_different_exceptions exception_one_class = Class.new(StandardError) exception_two_class = Class.new(StandardError) test_result = run_as_test do foo = stub('foo') foo.stubs(:bar).raises(exception_one_class).then.raises(exception_two_class) assert_raises(exception_one_class) { foo.bar } assert_raises(exception_two_class) { foo.bar } end assert_passed(test_result) end end mocha-1.3.0/test/acceptance/stubba_test_result_test.rb0000644000004100000410000000346713155337744023226 0ustar www-datawww-datarequire File.expand_path('../acceptance_test_helper', __FILE__) require 'mocha/setup' require 'execution_point' class StubbaTestResultTest < Mocha::TestCase include AcceptanceTest def setup setup_acceptance_test end def teardown teardown_acceptance_test end def test_should_include_expectation_verification_in_assertion_count test_result = run_as_test do object = Class.new do def message end end.new object.expects(:message) object.message end assert_equal 1, test_result.assertion_count end def test_should_include_assertions_in_assertion_count test_result = run_as_test do assert true end assert_equal 1, test_result.assertion_count end def test_should_not_include_stubbing_expectation_verification_in_assertion_count test_result = run_as_test do object = Class.new do def message end end.new object.stubs(:message) object.message end assert_equal 0, test_result.assertion_count end def test_should_include_expectation_verification_failure_in_failure_count test_result = run_as_test do object = Class.new do def message end end.new object.expects(:message) end assert_equal 1, test_result.failure_count end def test_should_include_assertion_failure_in_failure_count test_result = run_as_test do flunk end assert_equal 1, test_result.failure_count end def test_should_display_backtrace_indicating_line_number_where_failing_assertion_was_called execution_point = nil test_result = run_as_test do execution_point = ExecutionPoint.current; flunk end assert_equal 1, test_result.failure_count assert_equal execution_point, ExecutionPoint.new(test_result.failures[0].location) end end mocha-1.3.0/test/acceptance/unstubbing_test.rb0000644000004100000410000001324713155337744021466 0ustar www-datawww-datarequire File.expand_path('../acceptance_test_helper', __FILE__) require 'mocha/setup' class UnstubbingTest < Mocha::TestCase include AcceptanceTest def setup setup_acceptance_test end def teardown teardown_acceptance_test end def test_unstubbing_an_instance_method_should_restore_original_behaviour klass = Class.new do def my_instance_method; :original_return_value; end end test_result = run_as_test do object = klass.new object.stubs(:my_instance_method).returns(:new_return_value) object.unstub(:my_instance_method) assert_equal :original_return_value, object.my_instance_method end assert_passed(test_result) end def test_unstubbing_a_class_method_should_restore_original_behaviour klass = Class.new do def self.my_class_method; :original_return_value; end end test_result = run_as_test do klass.stubs(:my_class_method).returns(:new_return_value) klass.unstub(:my_class_method) assert_equal :original_return_value, klass.my_class_method end assert_passed(test_result) end def test_unstubbing_a_module_method_should_restore_original_behaviour mod = Module.new do def self.my_module_method; :original_return_value; end end test_result = run_as_test do mod.stubs(:my_module_method).returns(:new_return_value) mod.unstub(:my_module_method) assert_equal :original_return_value, mod.my_module_method end assert_passed(test_result) end def test_unstubbing_a_module_method_defined_like_fileutils_in_ruby_2_0_should_restore_original_behaviour mod = Module.new do def my_module_method; :original_return_value; end private :my_module_method extend self class << self public :my_module_method end end test_result = run_as_test do mod.stubs(:my_module_method).returns(:new_return_value) mod.unstub(:my_module_method) assert_equal :original_return_value, mod.my_module_method end assert_passed(test_result) end def test_unstubbing_an_any_instance_method_should_restore_original_behaviour klass = Class.new do def my_instance_method; :original_return_value; end end test_result = run_as_test do object = klass.new klass.any_instance.stubs(:my_instance_method).returns(:new_return_value) klass.any_instance.unstub(:my_instance_method) assert_equal :original_return_value, object.my_instance_method end assert_passed(test_result) end def test_unstubbing_multiple_methods_should_restore_original_behaviour klass = Class.new do def my_first_instance_method; :original_return_value; end def my_second_instance_method; :original_return_value; end end test_result = run_as_test do object = klass.new object.stubs(:my_first_instance_method).returns(:new_return_value) object.stubs(:my_second_instance_method).returns(:new_return_value) object.unstub(:my_first_instance_method, :my_second_instance_method) assert_equal :original_return_value, object.my_first_instance_method assert_equal :original_return_value, object.my_second_instance_method end assert_passed(test_result) end def test_unstubbing_a_method_multiple_times_should_restore_original_behaviour klass = Class.new do def my_instance_method; :original_return_value; end end test_result = run_as_test do object = klass.new object.stubs(:my_instance_method).returns(:new_return_value) object.unstub(:my_instance_method) object.unstub(:my_instance_method) assert_equal :original_return_value, object.my_instance_method end assert_passed(test_result) end def test_unstubbing_a_non_stubbed_method_should_do_nothing klass = Class.new do def my_instance_method; :original_return_value; end end test_result = run_as_test do object = klass.new object.unstub(:my_instance_method) assert_equal :original_return_value, object.my_instance_method end assert_passed(test_result) end def test_unstubbing_a_method_which_was_stubbed_multiple_times_should_restore_orginal_behaviour klass = Class.new do def my_instance_method; :original_return_value; end end test_result = run_as_test do object = klass.new object.stubs(:my_instance_method).with(:first).returns(:first_new_return_value) object.stubs(:my_instance_method).with(:second).returns(:second_new_return_value) object.unstub(:my_instance_method) assert_equal :original_return_value, object.my_instance_method end assert_passed(test_result) end def test_unstubbing_a_method_should_not_unstub_other_stubbed_methods klass = Class.new do def my_first_instance_method; :first_return_value; end def my_second_instance_method; :second_return_value; end end test_result = run_as_test do object = klass.new object.stubs(:my_first_instance_method).returns(:first_new_return_value) object.stubs(:my_second_instance_method).returns(:second_new_return_value) object.unstub(:my_first_instance_method) assert_equal :first_return_value, object.my_first_instance_method assert_equal :second_new_return_value, object.my_second_instance_method end assert_passed(test_result) end def test_unstubbing_a_method_should_remove_all_expectations_for_that_method klass = Class.new do def my_instance_method; :original_return_value; end end test_result = run_as_test do object = klass.new object.expects(:my_instance_method).with(:first) object.expects(:my_instance_method).with(:second) object.unstub(:my_instance_method) end assert_passed(test_result) end end mocha-1.3.0/test/acceptance/mocha_test_result_test.rb0000644000004100000410000000436013155337744023026 0ustar www-datawww-datarequire File.expand_path('../acceptance_test_helper', __FILE__) require 'mocha/setup' require 'execution_point' class MochaTestResultTest < Mocha::TestCase include AcceptanceTest def setup setup_acceptance_test end def teardown teardown_acceptance_test end def test_should_include_expectation_verification_in_assertion_count test_result = run_as_test do object = mock() object.expects(:message) object.message end assert_equal 1, test_result.assertion_count end def test_should_include_assertions_in_assertion_count test_result = run_as_test do assert true end assert_equal 1, test_result.assertion_count end def test_should_not_include_stubbing_expectation_verification_in_assertion_count test_result = run_as_test do object = mock() object.stubs(:message) object.message end assert_equal 0, test_result.assertion_count end def test_should_include_expectation_verification_failure_in_failure_count test_result = run_as_test do object = mock() object.expects(:message) end assert_equal 1, test_result.failure_count end def test_should_include_unexpected_verification_failure_in_failure_count test_result = run_as_test do object = mock() object.message end assert_equal 1, test_result.failure_count end def test_should_include_assertion_failure_in_failure_count test_result = run_as_test do flunk end assert_equal 1, test_result.failure_count end def test_should_display_backtrace_indicating_line_number_where_unexpected_method_was_called execution_point = nil test_result = run_as_test do object = mock() execution_point = ExecutionPoint.current; object.message end assert_equal 1, test_result.failure_count assert_equal execution_point, ExecutionPoint.new(test_result.failures[0].location) end def test_should_display_backtrace_indicating_line_number_where_failing_assertion_was_called execution_point = nil test_result = run_as_test do execution_point = ExecutionPoint.current; flunk end assert_equal 1, test_result.failure_count assert_equal execution_point, ExecutionPoint.new(test_result.failures[0].location) end end mocha-1.3.0/test/acceptance/issue_65_test.rb0000644000004100000410000000260313155337744020742 0ustar www-datawww-datarequire File.expand_path('../acceptance_test_helper', __FILE__) require 'mocha/setup' class Issue65Test < Mocha::TestCase include AcceptanceTest def setup setup_acceptance_test end def teardown teardown_acceptance_test end def test_expectations_on_class_methods_on_same_class_should_be_verified_in_consecutive_tests klass = Class.new do def self.foo; end def self.bar; end end test_1 = run_as_test do klass.expects(:foo) klass.foo end assert_passed(test_1) test_2 = run_as_test do klass.expects(:bar) end assert_failed(test_2) end def test_expectations_on_any_instance_methods_on_same_class_should_be_verified_in_consecutive_tests klass = Class.new do def foo; end def bar; end end test_1 = run_as_test do klass.any_instance.expects(:foo) klass.new.foo end assert_passed(test_1) test_2 = run_as_test do klass.any_instance.expects(:bar) end assert_failed(test_2) end def test_expectations_on_instance_methods_on_same_object_should_be_verified_in_consecutive_tests instance = Class.new do def foo; end def bar; end end.new test_1 = run_as_test do instance.expects(:foo) instance.foo end assert_passed(test_1) test_2 = run_as_test do instance.expects(:bar) end assert_failed(test_2) end end mocha-1.3.0/test/acceptance/mock_with_initializer_block_test.rb0000644000004100000410000000247513155337744025050 0ustar www-datawww-datarequire File.expand_path('../acceptance_test_helper', __FILE__) require 'mocha/setup' require 'deprecation_disabler' class MockWithInitializerBlockTest < Mocha::TestCase include AcceptanceTest def setup setup_acceptance_test end def teardown teardown_acceptance_test end def test_should_expect_two_method_invocations_and_receive_both_of_them test_result = run_as_test do DeprecationDisabler.disable_deprecations do mock = mock() do expects(:method_1) expects(:method_2) end mock.method_1 mock.method_2 end end assert_passed(test_result) end def test_should_expect_two_method_invocations_but_receive_only_one_of_them test_result = run_as_test do DeprecationDisabler.disable_deprecations do mock = mock() do expects(:method_1) expects(:method_2) end mock.method_1 end end assert_failed(test_result) end def test_should_stub_methods test_result = run_as_test do DeprecationDisabler.disable_deprecations do mock = mock() do stubs(:method_1).returns(1) stubs(:method_2).returns(2) end assert_equal 1, mock.method_1 assert_equal 2, mock.method_2 end end assert_passed(test_result) end end mocha-1.3.0/test/acceptance/issue_70_test.rb0000644000004100000410000000253013155337744020735 0ustar www-datawww-datarequire File.expand_path('../acceptance_test_helper', __FILE__) require 'mocha/setup' class Issue70Test < Mocha::TestCase include AcceptanceTest def setup setup_acceptance_test end def teardown teardown_acceptance_test end def test_should_stub_expectations_instance_method instance = Class.new do def expectations :original_return_value end end.new test_result = run_as_test do instance.stubs(:expectations).returns(:stubbed_return_value) assert_equal :stubbed_return_value, instance.expectations end assert_passed(test_result) end def test_should_stub_expectations_class_method klass = Class.new do def self.expectations :original_return_value end end test_result = run_as_test do klass.stubs(:expectations).returns(:stubbed_return_value) assert_equal :stubbed_return_value, klass.expectations end assert_passed(test_result) end def test_should_stub_expectations_any_instance_method klass = Class.new do def expectations :original_return_value end end instance = klass.new test_result = run_as_test do klass.any_instance.stubs(:expectations).returns(:stubbed_return_value) assert_equal :stubbed_return_value, instance.expectations end assert_passed(test_result) end end mocha-1.3.0/test/acceptance/stubbing_error_backtrace_test.rb0000644000004100000410000000443313155337744024330 0ustar www-datawww-datarequire File.expand_path('../acceptance_test_helper', __FILE__) require 'mocha/setup' require 'execution_point' class StubbingErrorBacktraceTest < Mocha::TestCase include AcceptanceTest def setup setup_acceptance_test end def teardown teardown_acceptance_test end def test_should_display_backtrace_indicating_line_number_where_attempt_to_stub_non_existent_method_was_made execution_point = nil object = Object.new Mocha::Configuration.prevent(:stubbing_non_existent_method) test_result = run_as_test do execution_point = ExecutionPoint.current; object.stubs(:non_existent_method) end assert_equal 1, test_result.error_count assert_equal execution_point, ExecutionPoint.new(test_result.errors[0].exception.backtrace) end def test_should_display_backtrace_indicating_line_number_where_attempt_to_stub_non_public_method_was_made execution_point = nil object = Class.new do def non_public_method; end private :non_public_method end.new Mocha::Configuration.prevent(:stubbing_non_public_method) test_result = run_as_test do execution_point = ExecutionPoint.current; object.stubs(:non_public_method) end assert_equal 1, test_result.error_count assert_equal execution_point, ExecutionPoint.new(test_result.errors[0].exception.backtrace) end def test_should_display_backtrace_indicating_line_number_where_attempt_to_stub_method_on_non_mock_object_was_made execution_point = nil object = Object.new Mocha::Configuration.prevent(:stubbing_method_on_non_mock_object) test_result = run_as_test do execution_point = ExecutionPoint.current; object.stubs(:any_method) end assert_equal 1, test_result.error_count assert_equal execution_point, ExecutionPoint.new(test_result.errors[0].exception.backtrace) end def test_should_display_backtrace_indicating_line_number_where_method_was_unnecessarily_stubbed execution_point = nil object = Object.new Mocha::Configuration.prevent(:stubbing_method_unnecessarily) test_result = run_as_test do execution_point = ExecutionPoint.current; object.stubs(:unused_method) end assert_equal 1, test_result.error_count assert_equal execution_point, ExecutionPoint.new(test_result.errors[0].exception.backtrace) end end mocha-1.3.0/test/acceptance/stub_instance_method_defined_on_singleton_class_test.rb0000644000004100000410000000405213155337744031122 0ustar www-datawww-datarequire File.expand_path('../acceptance_test_helper', __FILE__) require 'mocha/setup' class StubInstanceMethodDefinedOnSingletonClassTest < Mocha::TestCase include AcceptanceTest def setup setup_acceptance_test end def teardown teardown_acceptance_test end def test_should_stub_public_method_and_leave_it_unchanged_after_test instance = Class.new.new class << instance def my_singleton_method :original_return_value end public :my_singleton_method end assert_snapshot_unchanged(instance) do test_result = run_as_test do instance.stubs(:my_singleton_method).returns(:stubbed_return_value) assert_equal :stubbed_return_value, instance.my_singleton_method end assert_passed(test_result) end assert_equal :original_return_value, instance.my_singleton_method end def test_should_stub_protected_method_and_leave_it_unchanged_after_test instance = Class.new.new class << instance def my_singleton_method :original_return_value end protected :my_singleton_method end assert_snapshot_unchanged(instance) do test_result = run_as_test do instance.stubs(:my_singleton_method).returns(:stubbed_return_value) assert_equal :stubbed_return_value, instance.send(:my_singleton_method) end assert_passed(test_result) end assert_equal :original_return_value, instance.send(:my_singleton_method) end def test_should_stub_private_method_and_leave_it_unchanged_after_test instance = Class.new.new class << instance def my_singleton_method :original_return_value end private :my_singleton_method end assert_snapshot_unchanged(instance) do test_result = run_as_test do instance.stubs(:my_singleton_method).returns(:stubbed_return_value) assert_equal :stubbed_return_value, instance.send(:my_singleton_method) end assert_passed(test_result) end assert_equal :original_return_value, instance.send(:my_singleton_method) end end mocha-1.3.0/test/acceptance/throw_test.rb0000644000004100000410000000201013155337744020433 0ustar www-datawww-datarequire File.expand_path('../acceptance_test_helper', __FILE__) require 'mocha/setup' class ThrowTest < Mocha::TestCase include AcceptanceTest def setup setup_acceptance_test end def teardown teardown_acceptance_test end def test_should_throw_tag test_result = run_as_test do foo = stub('foo') foo.stubs(:bar).throws(:tag) assert_throws(:tag) { foo.bar } end assert_passed(test_result) end def test_should_throw_with_return_value test_result = run_as_test do foo = stub('foo') foo.stubs(:bar).throws(:tag, 'return-value') return_value = catch(:tag) { foo.bar } assert_equal 'return-value', return_value end assert_passed(test_result) end def test_should_throw_two_different_tags test_result = run_as_test do foo = stub('foo') foo.stubs(:bar).throws(:tag_one).then.throws(:tag_two) assert_throws(:tag_one) { foo.bar } assert_throws(:tag_two) { foo.bar } end assert_passed(test_result) end end mocha-1.3.0/test/acceptance/stub_any_instance_method_test.rb0000644000004100000410000002311013155337744024344 0ustar www-datawww-datarequire File.expand_path('../acceptance_test_helper', __FILE__) require 'mocha/setup' class StubAnyInstanceMethodTest < Mocha::TestCase include AcceptanceTest def setup setup_acceptance_test end def teardown teardown_acceptance_test end def test_should_stub_public_method_within_test klass = Class.new do def my_instance_method :original_return_value end end instance = klass.new test_result = run_as_test do klass.any_instance.stubs(:my_instance_method).returns(:new_return_value) assert_method_visibility instance, :my_instance_method, :public assert_equal :new_return_value, instance.my_instance_method end assert_passed(test_result) end def test_should_leave_stubbed_public_method_unchanged_after_test klass = Class.new do def my_instance_method :original_return_value end public :my_instance_method def self.public(*args); end end instance = klass.new run_as_test do klass.any_instance.stubs(:my_instance_method).returns(:new_return_value) end assert instance.public_methods(false).any? { |m| m.to_s == 'my_instance_method' } assert_equal :original_return_value, instance.my_instance_method end def test_should_leave_stubbed_protected_method_unchanged_after_test klass = Class.new do def my_instance_method :original_return_value end protected :my_instance_method def self.protected(*args); end def my_unprotected_instance_method my_instance_method end end instance = klass.new run_as_test do klass.any_instance.stubs(:my_instance_method).returns(:new_return_value) end assert instance.protected_methods(false).any? { |m| m.to_s == 'my_instance_method' } assert_equal :original_return_value, instance.my_unprotected_instance_method end def test_should_stub_protected_method_within_test klass = Class.new do def my_instance_method :original_return_value end protected :my_instance_method def self.protected(*args); end def my_unprotected_instance_method my_instance_method end end instance = klass.new test_result = run_as_test do klass.any_instance.stubs(:my_instance_method).returns(:new_return_value) assert_method_visibility instance, :my_instance_method, :protected end assert_passed(test_result) end def test_should_leave_stubbed_private_method_unchanged_after_test klass = Class.new do def my_instance_method :original_return_value end private :my_instance_method def self.private(*args); end end instance = klass.new run_as_test do klass.any_instance.stubs(:my_instance_method).returns(:new_return_value) end assert instance.private_methods(false).any? { |m| m.to_s == 'my_instance_method' } assert_equal :original_return_value, instance.send(:my_instance_method) end def test_should_stub_private_method_within_test klass = Class.new do def my_instance_method :original_return_value end private :my_instance_method def self.private(*args); end end instance = klass.new test_result = run_as_test do klass.any_instance.stubs(:my_instance_method).returns(:new_return_value) assert_method_visibility instance, :my_instance_method, :private end assert_passed(test_result) end def test_should_reset_expectations_after_test klass = Class.new do def my_instance_method :original_return_value end end run_as_test do klass.any_instance.stubs(:my_instance_method).returns(:new_return_value) end assert_equal 0, klass.any_instance.mocha.__expectations__.length end def test_should_be_able_to_stub_a_public_superclass_method superklass = Class.new do def my_superclass_method :original_return_value end public :my_superclass_method end klass = Class.new(superklass) instance = klass.new test_result = run_as_test do klass.any_instance.stubs(:my_superclass_method).returns(:new_return_value) assert_method_visibility instance, :my_superclass_method, :public assert_equal :new_return_value, instance.my_superclass_method end assert_passed(test_result) assert instance.public_methods(true).any? { |m| m.to_s == 'my_superclass_method' } assert !klass.public_methods(false).any? { |m| m.to_s == 'my_superclass_method' } assert_equal :original_return_value, instance.my_superclass_method end def test_should_be_able_to_stub_a_protected_superclass_method superklass = Class.new do def my_superclass_method :original_return_value end protected :my_superclass_method end klass = Class.new(superklass) instance = klass.new test_result = run_as_test do klass.any_instance.stubs(:my_superclass_method).returns(:new_return_value) assert_method_visibility instance, :my_superclass_method, :protected assert_equal :new_return_value, instance.send(:my_superclass_method) end assert_passed(test_result) assert instance.protected_methods(true).any? { |m| m.to_s == 'my_superclass_method' } assert !klass.protected_methods(false).any? { |m| m.to_s == 'my_superclass_method' } assert_equal :original_return_value, instance.send(:my_superclass_method) end def test_should_be_able_to_stub_a_private_superclass_method superklass = Class.new do def my_superclass_method :original_return_value end private :my_superclass_method end klass = Class.new(superklass) instance = klass.new test_result = run_as_test do klass.any_instance.stubs(:my_superclass_method).returns(:new_return_value) assert_method_visibility instance, :my_superclass_method, :private assert_equal :new_return_value, instance.send(:my_superclass_method) end assert_passed(test_result) assert instance.private_methods(true).any? { |m| m.to_s == 'my_superclass_method' } assert !klass.private_methods(false).any? { |m| m.to_s == 'my_superclass_method' } assert_equal :original_return_value, instance.send(:my_superclass_method) end def test_should_be_able_to_stub_method_if_ruby18_public_instance_methods_include_method_but_method_does_not_actually_exist_like_active_record_association_proxy ruby18_klass = Class.new do class << self def public_instance_methods(include_superclass = true) ['my_instance_method'] end end end test_result = run_as_test do ruby18_klass.any_instance.stubs(:my_instance_method).returns(:new_return_value) assert_equal :new_return_value, ruby18_klass.new.my_instance_method end assert_passed(test_result) end def test_should_be_able_to_stub_method_if_ruby19_public_instance_methods_include_method_but_method_does_not_actually_exist_like_active_record_association_proxy ruby19_klass = Class.new do class << self def public_instance_methods(include_superclass = true) [:my_instance_method] end end end test_result = run_as_test do ruby19_klass.any_instance.stubs(:my_instance_method).returns(:new_return_value) assert_equal :new_return_value, ruby19_klass.new.my_instance_method end assert_passed(test_result) end def test_should_be_able_to_stub_method_if_ruby18_protected_instance_methods_include_method_but_method_does_not_actually_exist_like_active_record_association_proxy ruby18_klass = Class.new do class << self def protected_instance_methods(include_superclass = true) ['my_instance_method'] end end end test_result = run_as_test do ruby18_klass.any_instance.stubs(:my_instance_method).returns(:new_return_value) assert_equal :new_return_value, ruby18_klass.new.send(:my_instance_method) end assert_passed(test_result) end def test_should_be_able_to_stub_method_if_ruby19_protected_instance_methods_include_method_but_method_does_not_actually_exist_like_active_record_association_proxy ruby19_klass = Class.new do class << self def protected_instance_methods(include_superclass = true) [:my_instance_method] end end end test_result = run_as_test do ruby19_klass.any_instance.stubs(:my_instance_method).returns(:new_return_value) assert_equal :new_return_value, ruby19_klass.new.send(:my_instance_method) end assert_passed(test_result) end def test_should_be_able_to_stub_method_if_ruby18_private_instance_methods_include_method_but_method_does_not_actually_exist_like_active_record_association_proxy ruby18_klass = Class.new do class << self def private_instance_methods(include_superclass = true) ['my_instance_method'] end end end test_result = run_as_test do ruby18_klass.any_instance.stubs(:my_instance_method).returns(:new_return_value) assert_equal :new_return_value, ruby18_klass.new.send(:my_instance_method) end assert_passed(test_result) end def test_should_be_able_to_stub_method_if_ruby19_private_instance_methods_include_method_but_method_does_not_actually_exist_like_active_record_association_proxy ruby19_klass = Class.new do class << self def private_instance_methods(include_superclass = true) [:my_instance_method] end end end test_result = run_as_test do ruby19_klass.any_instance.stubs(:my_instance_method).returns(:new_return_value) assert_equal :new_return_value, ruby19_klass.new.send(:my_instance_method) end assert_passed(test_result) end end mocha-1.3.0/test/acceptance/stub_test.rb0000644000004100000410000000210513155337744020252 0ustar www-datawww-datarequire File.expand_path('../acceptance_test_helper', __FILE__) require 'mocha/setup' class StubTest < Mocha::TestCase include AcceptanceTest def setup setup_acceptance_test end def teardown teardown_acceptance_test end def test_should_build_stub_and_explicitly_add_an_expectation test_result = run_as_test do foo = stub() foo.stubs(:bar) foo.bar end assert_passed(test_result) end def test_should_build_named_stub_and_explicitly_add_an_expectation test_result = run_as_test do foo = stub('foo') foo.stubs(:bar) foo.bar end assert_passed(test_result) end def test_should_build_stub_incorporating_two_expectations test_result = run_as_test do foo = stub(:bar => 'bar', :baz => 'baz') foo.bar foo.baz end assert_passed(test_result) end def test_should_build_named_stub_incorporating_two_expectations test_result = run_as_test do foo = stub('foo', :bar => 'bar', :baz => 'baz') foo.bar foo.baz end assert_passed(test_result) end end mocha-1.3.0/init.rb0000644000004100000410000000032213155337744014133 0ustar www-datawww-data# Mocha should no longer be loaded at plugin load time # You should explicitly load Mocha *after* Test::Unit or MiniTest have been loaded # e.g. by adding "require 'mocha'" at the bottom of test/test_helper.rb mocha-1.3.0/COPYING.md0000644000004100000410000000034313155337744014300 0ustar www-datawww-dataCopyright Revieworld Ltd. 2006 You may use, copy and redistribute this library under the same terms as [Ruby itself](http://www.ruby-lang.org/en/LICENSE.txt) or under the [MIT license](http://www.opensource.org/licenses/MIT). mocha-1.3.0/mocha.gemspec0000644000004100000410000000466113155337744015311 0ustar www-datawww-data# -*- encoding: utf-8 -*- lib = File.expand_path('../lib/', __FILE__) $LOAD_PATH.unshift lib unless $LOAD_PATH.include?(lib) require "mocha/version" Gem::Specification.new do |s| s.name = "mocha" s.version = Mocha::VERSION s.licenses = ['MIT', 'BSD-2-Clause'] s.required_ruby_version = '>= 1.8.7' s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["James Mead"] s.description = "Mocking and stubbing library with JMock/SchMock syntax, which allows mocking and stubbing of methods on real (non-mock) classes." s.email = "mocha-developer@googlegroups.com" s.files = `git ls-files`.split("\n") s.files.delete(".travis.yml") s.files.delete(".gitignore") s.homepage = "http://gofreerange.com/mocha/docs" s.require_paths = ["lib"] s.rubyforge_project = "mocha" s.summary = "Mocking and stubbing library" s.has_rdoc = "yard" s.add_dependency("metaclass", "~> 0.0.1") if s.respond_to? :specification_version then current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then if RUBY_VERSION >= '1.9.3' s.add_development_dependency("rake", ">= 0") else s.add_development_dependency("rake", "~> 10.0") end s.add_development_dependency("introspection", "~> 0.0.1") if RUBY_VERSION >= '2.2.0' s.add_development_dependency("minitest") end if ENV["MOCHA_GENERATE_DOCS"] s.add_development_dependency("yard") s.add_development_dependency("redcarpet") end else if RUBY_VERSION >= '1.9.3' s.add_development_dependency("rake", ">= 0") else s.add_development_dependency("rake", "~> 10.0") end s.add_dependency("introspection", "~> 0.0.1") if RUBY_VERSION >= '2.2.0' s.add_dependency("minitest") end if ENV["MOCHA_GENERATE_DOCS"] s.add_dependency("yard") s.add_dependency("redcarpet") end end else if RUBY_VERSION >= '1.9.3' s.add_development_dependency("rake", ">= 0") else s.add_development_dependency("rake", "~> 10.0") end s.add_dependency("introspection", "~> 0.0.1") if RUBY_VERSION >= '2.2.0' s.add_dependency("minitest") end if ENV["MOCHA_GENERATE_DOCS"] s.add_dependency("yard") s.add_dependency("redcarpet") end end end mocha-1.3.0/.yardopts0000644000004100000410000000107513155337744014517 0ustar www-datawww-data--template-path yard-templates --no-private lib/mocha/api.rb lib/mocha/hooks.rb lib/mocha/mock.rb lib/mocha/expectation.rb lib/mocha/object_methods.rb lib/mocha/class_methods.rb lib/mocha/parameter_matchers.rb lib/mocha/parameter_matchers lib/mocha/state_machine.rb lib/mocha/sequence.rb lib/mocha/configuration.rb lib/mocha/expectation_error_factory.rb lib/mocha/expectation_error.rb lib/mocha/stubbing_error.rb lib/mocha/unexpected_invocation.rb lib/mocha/integration/test_unit/adapter.rb lib/mocha/integration/mini_test/adapter.rb - RELEASE.md COPYING.md MIT-LICENSE.md mocha-1.3.0/CONTRIBUTING.md0000644000004100000410000000135613155337744015104 0ustar www-datawww-data* Pull requests are welcomed. * Fork the repository. * Make your changes in a branch. * Add tests for new behaviour. Modify/remove existing tests for changes to existing behaviour. * Run `bin/build-matrix` from the root directory and ensure all the tests pass. * This script depends on `rbenv` being installed. * You must have all the ruby versions listed in `.travis.yml` under the `rvm` key installed (currently 1.8.7, 1.9.3 & 2.0.0). * I use `rbenv-aliases` to alias the patch versions. * Note that the build matrix takes quite a while to run. * Send us a pull request from your fork/branch. * Wait for your pull request to build on [Travis CI](https://travis-ci.org/freerange/mocha). * I will not accept pull requests with failing tests. mocha-1.3.0/MIT-LICENSE.md0000644000004100000410000000204313155337744014700 0ustar www-datawww-dataCopyright (c) 2006 Revieworld Ltd. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. mocha-1.3.0/README.md0000644000004100000410000004714613155337744014141 0ustar www-datawww-data## Mocha [![Build Status](https://travis-ci.org/freerange/mocha.svg?branch=master)](https://travis-ci.org/freerange/mocha) [![Gem Version](https://badge.fury.io/rb/mocha.png)](http://badge.fury.io/rb/mocha) [![OpenCollective](https://opencollective.com/mocha/backers/badge.svg)](#backers) [![OpenCollective](https://opencollective.com/mocha/sponsors/badge.svg)](#sponsors) ### Description * A Ruby library for mocking and stubbing. * A unified, simple and readable syntax for both full & partial mocking. * Built-in support for MiniTest and Test::Unit. * Supported by many other test frameworks. ### Installation #### Gem Install the latest version of the gem with the following command... $ gem install mocha Note: If you are intending to use Mocha with Test::Unit or MiniTest, you should only setup Mocha *after* loading the relevant test library... ##### Test::Unit ```ruby require 'rubygems' gem 'mocha' require 'test/unit' require 'mocha/test_unit' ``` ##### MiniTest ```ruby require 'rubygems' gem 'mocha' require 'minitest/unit' require 'mocha/mini_test' ``` #### Bundler If you're using Bundler, include Mocha in the `Gemfile` and then setup Mocha later once you know the test library has been loaded... ##### Test::Unit ```ruby # Gemfile gem "mocha" # Elsewhere after Bundler has loaded gems e.g. after `require 'bundler/setup'` require "test/unit" require "mocha/test_unit" ``` ##### MiniTest ```ruby # Gemfile gem "mocha" # Elsewhere after Bundler has loaded gems e.g. after `require 'bundler/setup'` require "minitest/unit" require "mocha/mini_test" ``` #### Rails If you're loading Mocha using Bundler within a Rails application, you should setup Mocha manually e.g. at the bottom of your `test_helper.rb`. ##### MiniTest ```ruby # Gemfile in Rails app gem 'mocha' # At bottom of test_helper.rb (or at least after `require 'rails/test_help'`) require 'mocha/mini_test' ``` ##### RSpec RSpec includes a mocha adapter. Just tell RSpec you want to mock with `:mocha`: ```ruby # Gemfile in Rails app gem 'mocha' # Within `spec/spec_helper.rb` RSpec.configure do |config| config.mock_with :mocha end ``` Note: There is no need to use a require statement to setup Mocha; RSpec does this itself. #### Rails Plugin Install the Rails plugin... $ rails plugin install git://github.com/freerange/mocha.git Note: As of version 0.9.8, the Mocha plugin is not automatically setup at plugin load time. Instead it must be manually setup e.g. at the bottom of your `test_helper.rb`. ##### MiniTest ```ruby # At bottom of test_helper.rb (or at least after `require 'rails/test_help'`) require 'mocha/mini_test' ``` #### Known Issues * In Mocha v1.2.0 there is a scenario where stubbing a class method originally defined in a module hangs the Ruby interpreter due to [a bug in Ruby v2.3.1](https://bugs.ruby-lang.org/issues/12832). See #272. This was fixed in Mocha v1.2.1. * Since v1.1.0 Mocha has used prepended modules internally for stubbing methods. There is [an obscure Ruby bug](https://bugs.ruby-lang.org/issues/12876) in many (but not all) versions of Ruby between v2.0 & v2.3 which under certain circumstances may cause your Ruby interpreter to hang. See the Ruby bug report for more details. The bug has been fixed in Ruby v2.3.3 & v2.4.0. * Stubbing an aliased class method, where the original method is defined in a module that's used to `extend` the class doesn't work in Ruby 1.8.x. See stub_method_defined_on_module_and_aliased_test.rb for an example of this behaviour. * 0.13.x versions cause a harmless, but annoying, deprecation warning when used with Rails 3.2.0-3.2.12, 3.1.0-3.1.10 & 3.0.0-3.0.19. * 0.11.x versions don't work with Rails 3.2.13 (`TypeError: superclass mismatch for class ExpectationError`). See #115. * Versions 0.10.2, 0.10.3 & 0.11.0 of the Mocha gem were broken. Please do not use these versions. * Versions 0.9.6 & 0.9.7 of the Mocha Rails plugin were broken. Please do not use these versions. ### Usage #### Quick Start ```ruby require 'test/unit' require 'mocha/test_unit' class MiscExampleTest < Test::Unit::TestCase def test_mocking_a_class_method product = Product.new Product.expects(:find).with(1).returns(product) assert_equal product, Product.find(1) end def test_mocking_an_instance_method_on_a_real_object product = Product.new product.expects(:save).returns(true) assert product.save end def test_stubbing_instance_methods_on_real_objects prices = [stub(:pence => 1000), stub(:pence => 2000)] product = Product.new product.stubs(:prices).returns(prices) assert_equal [1000, 2000], product.prices.collect {|p| p.pence} end def test_stubbing_an_instance_method_on_all_instances_of_a_class Product.any_instance.stubs(:name).returns('stubbed_name') product = Product.new assert_equal 'stubbed_name', product.name end def test_traditional_mocking object = mock('object') object.expects(:expected_method).with(:p1, :p2).returns(:result) assert_equal :result, object.expected_method(:p1, :p2) end def test_shortcuts object = stub(:method1 => :result1, :method2 => :result2) assert_equal :result1, object.method1 assert_equal :result2, object.method2 end end ``` #### Mock Objects ```ruby class Enterprise def initialize(dilithium) @dilithium = dilithium end def go(warp_factor) warp_factor.times { @dilithium.nuke(:anti_matter) } end end require 'test/unit' require 'mocha/test_unit' class EnterpriseTest < Test::Unit::TestCase def test_should_boldly_go dilithium = mock() dilithium.expects(:nuke).with(:anti_matter).at_least_once # auto-verified at end of test enterprise = Enterprise.new(dilithium) enterprise.go(2) end end ``` #### Partial Mocking ```ruby class Order attr_accessor :shipped_on def total_cost line_items.inject(0) { |total, line_item| total + line_item.price } + shipping_cost end def total_weight line_items.inject(0) { |total, line_item| total + line_item.weight } end def shipping_cost total_weight * 5 + 10 end class << self def find_all # Database.connection.execute('select * from orders... end def number_shipped_since(date) find_all.select { |order| order.shipped_on > date }.length end def unshipped_value find_all.inject(0) { |total, order| order.shipped_on ? total : total + order.total_cost } end end end require 'test/unit' require 'mocha/test_unit' class OrderTest < Test::Unit::TestCase # illustrates stubbing instance method def test_should_calculate_shipping_cost_based_on_total_weight order = Order.new order.stubs(:total_weight).returns(10) assert_equal 60, order.shipping_cost end # illustrates stubbing class method def test_should_count_number_of_orders_shipped_after_specified_date now = Time.now; week_in_secs = 7 * 24 * 60 * 60 order_1 = Order.new; order_1.shipped_on = now - 1 * week_in_secs order_2 = Order.new; order_2.shipped_on = now - 3 * week_in_secs Order.stubs(:find_all).returns([order_1, order_2]) assert_equal 1, Order.number_shipped_since(now - 2 * week_in_secs) end # illustrates stubbing instance method for all instances of a class def test_should_calculate_value_of_unshipped_orders Order.stubs(:find_all).returns([Order.new, Order.new, Order.new]) Order.any_instance.stubs(:shipped_on).returns(nil) Order.any_instance.stubs(:total_cost).returns(10) assert_equal 30, Order.unshipped_value end end ``` ### Thread safety Mocha is currently *not* thread-safe. There are two main reasons for this: (a) in multi-threaded code Mocha exceptions may be raised in a thread other than the one which is running the test and thus a Mocha exception may not be correctly intercepted by Mocha exception handling code; and (b) partial mocking changes the state of objects in the `ObjectSpace` which is shared across all threads in the Ruby process and this access to what is effectively global state is not synchronized. ### Expectation matching / invocation order Stubs and expectations are basically the same thing. A stub is just an expectation of zero or more invocations. The `Expectation#stubs` method is syntactic sugar to make the intent of the test more explicit. When a method is invoked on a mock object, the mock object searches through its expectations from newest to oldest to find one that matches the invocation. After the invocation, the matching expectation might stop matching further invocations. See the [documentation](http://gofreerange.com/mocha/docs/Mocha/Mock.html) for `Mocha::Mock` for further details. ### Useful Links * [Official Documentation](http://gofreerange.com/mocha/docs/) * [Source Code](http://github.com/freerange/mocha) * [Mailing List](http://groups.google.com/group/mocha-developer) * [James Mead's Blog](http://jamesmead.org/blog/) * [An Introduction To Mock Objects In Ruby](http://jamesmead.org/talks/2007-07-09-introduction-to-mock-objects-in-ruby-at-lrug/) * [Mocks Aren't Stubs](http://martinfowler.com/articles/mocksArentStubs.html) * [Growing Object-Oriented Software Guided By Tests](http://www.growing-object-oriented-software.com/) * [Mock Roles Not Objects](http://www.jmock.org/oopsla2004.pdf) * [jMock](http://www.jmock.org/) ### Contributors See this [list of contributors](https://github.com/freerange/mocha/graphs/contributors). ### Backers Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/mocha#backer)] ### Sponsors Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/mocha#sponsor)] ### Translations * [Serbo-Croatian](http://science.webhostinggeeks.com/mocha) by [WHG Team](http://webhostinggeeks.com/). (may be out-of-date) ### Releasing a new version * Update the RELEASE.md file with a summary of changes * Bump the version in `lib/mocha/version.rb` * Commit & push to Github * Check Travis CI build is passing - https://travis-ci.org/freerange/mocha * Sign in to rubygems.org and find API key - https://rubygems.org/profile/edit ```bash $ curl -u james@floehopper.org https://rubygems.org/api/v1/api_key.yaml > ~/.gem/credentials; chmod 0600 ~/.gem/credentials` ``` * Sign in to Google Analytics - https://analytics.google.com/analytics/web/ * Find the web property ID for Go Free Range Ltd > Mocha Documentation (UA-45002715-2) ```bash $ MOCHA_GENERATE_DOCS=true bundle install $ MOCHA_GENERATE_DOCS=true GOOGLE_ANALYTICS_WEB_PROPERTY_ID=UA-45002715-2 rake release mocha 1.2.0 built to pkg/mocha-1.2.0.gem. Tagged v1.2.0. Pushed git commits and tags. Pushed mocha 1.2.0 to rubygems.org. [runs tests] [generates docs] [deploys docs] ``` ### History Mocha was initially harvested from projects at [Reevoo](http://www.reevoo.com/). It's syntax is heavily based on that of [jMock](http://www.jmock.org). ### License © Copyright Revieworld Ltd. 2006 You may use, copy and redistribute this library under the same terms as [Ruby itself](http://www.ruby-lang.org/en/LICENSE.txt) or under the [MIT license](http://www.opensource.org/licenses/MIT).