[
  {
    "path": ".github/dependabot.yml",
    "content": "version: 2\nupdates:\n  - package-ecosystem: github-actions\n    directory: \"/\"\n    schedule:\n      interval: \"weekly\"\n"
  },
  {
    "path": ".github/workflows/ci.yml",
    "content": "name: CI\non: [push, pull_request]\npermissions:\n  actions: none\n  checks: write\n  contents: read\n  deployments: none\n  issues: none\n  packages: none\n  pull-requests: none\n  repository-projects: none\n  security-events: none\n  statuses: write\njobs:\n  build:\n    name: ruby-${{ matrix.ruby_version }}\n    runs-on: ubuntu-latest\n    strategy:\n      fail-fast: false\n      matrix:\n        ruby_version:\n          - \"2.6\"\n          - \"2.7\"\n          - \"3.0\"\n          - \"3.1\"\n          - \"3.2\"\n          - \"3.3\"\n    steps:\n      - uses: actions/checkout@v4\n      - uses: ruby/setup-ruby@v1\n        with:\n          ruby-version: ${{ matrix.ruby_version }}\n          bundler-cache: true\n      - run: bundle exec rake\n"
  },
  {
    "path": ".gitignore",
    "content": "/*.gem\n/.bundle\n/.ruby-version\n/Gemfile.lock\n/coverage\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "## Contributing\n\n[fork]: https://github.com/github/scientist/fork\n[pr]: https://github.com/github/scientist/compare\n\nHi there! We're thrilled that you'd like to contribute to this project. Your help is essential for keeping it great.\n\nContributions to this project are [released](https://help.github.com/articles/github-terms-of-service/#6-contributions-under-repository-license) to the public under the [project's open source license](LICENSE.txt).\n\n## Submitting a pull request\n\n0. [Fork][fork] and clone the repository\n1. Create a new branch: `git checkout -b my-branch-name`\n2. Make your change, push to your fork and [submit a pull request][pr]\n3. Pat your self on the back and wait for your pull request to be reviewed and merged.\n\nHere are a few things you can do that will increase the likelihood of your pull request being accepted:\n\n- Keep your change as focused as possible. If there are multiple changes you would like to make that are not dependent upon each other, consider submitting them as separate pull requests.\n- Write a [good commit message](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html).\n\n## Resources\n\n- [How to Contribute to Open Source](https://opensource.guide/how-to-contribute/)\n- [Using Pull Requests](https://help.github.com/articles/about-pull-requests/)\n- [GitHub Help](https://help.github.com)\n"
  },
  {
    "path": "Gemfile",
    "content": "source \"https://rubygems.org\"\n\ngemspec\n"
  },
  {
    "path": "LICENSE.txt",
    "content": "Copyright 2013, 2014 GitHub, Inc.\n\nMIT License\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\nLIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\nOF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\nWITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "# Scientist!\n\nA Ruby library for carefully refactoring critical paths. [![Build Status](https://github.com/github/scientist/actions/workflows/ci.yml/badge.svg)](https://github.com/github/scientist/actions/workflows/ci.yml)\n\n## How do I science?\n\nLet's pretend you're changing the way you handle permissions in a large web app. Tests can help guide your refactoring, but you really want to compare the current and refactored behaviors under load.\n\n```ruby\nrequire \"scientist\"\n\nclass MyWidget\n  def allows?(user)\n    experiment = Scientist::Default.new \"widget-permissions\"\n    experiment.use { model.check_user(user).valid? } # old way\n    experiment.try { user.can?(:read, model) } # new way\n\n    experiment.run\n  end\nend\n```\n\nWrap a `use` block around the code's original behavior, and wrap `try` around the new behavior. `experiment.run` will always return whatever the `use` block returns, but it does a bunch of stuff behind the scenes:\n\n* It decides whether or not to run the `try` block,\n* Randomizes the order in which `use` and `try` blocks are run,\n* Measures the wall time and cpu time of all behaviors in seconds,\n* Compares the result of `try` to the result of `use`,\n* Swallow and record exceptions raised in the `try` block when overriding `raised`, and\n* Publishes all this information.\n\nThe `use` block is called the **control**. The `try` block is called the **candidate**.\n\nCreating an experiment is wordy, but when you include the `Scientist` module, the `science` helper will instantiate an experiment and call `run` for you:\n\n```ruby\nrequire \"scientist\"\n\nclass MyWidget\n  include Scientist\n\n  def allows?(user)\n    science \"widget-permissions\" do |experiment|\n      experiment.use { model.check_user(user).valid? } # old way\n      experiment.try { user.can?(:read, model) } # new way\n    end # returns the control value\n  end\nend\n```\n\nIf you don't declare any `try` blocks, none of the Scientist machinery is invoked and the control value is always returned.\n\n## Making science useful\n\nThe examples above will run, but they're not really *doing* anything. The `try` blocks don't run yet and none of the results get published. Replace the default experiment implementation to control execution and reporting:\n\n```ruby\nrequire \"scientist/experiment\"\n\nclass MyExperiment\n  include Scientist::Experiment\n\n  attr_accessor :name\n\n  def initialize(name)\n    @name = name\n  end\n\n  def enabled?\n    # see \"Ramping up experiments\" below\n    true\n  end\n\n  def raised(operation, error)\n    # see \"In a Scientist callback\" below\n    p \"Operation '#{operation}' failed with error '#{error.inspect}'\"\n    super # will re-raise\n  end\n\n  def publish(result)\n    # see \"Publishing results\" below\n    p result\n  end\nend\n```\n\nWhen `Scientist::Experiment` is included in a class, it automatically sets it as the default implementation via `Scientist::Experiment.set_default`. This `set_default` call is skipped if you include `Scientist::Experiment` in a module.\n\nNow calls to the `science` helper will load instances of `MyExperiment`.\n\n### Controlling comparison\n\nScientist compares control and candidate values using `==`. To override this behavior, use `compare` to define how to compare observed values instead:\n\n```ruby\nclass MyWidget\n  include Scientist\n\n  def users\n    science \"users\" do |e|\n      e.use { User.all }         # returns User instances\n      e.try { UserService.list } # returns UserService::User instances\n\n      e.compare do |control, candidate|\n        control.map(&:login) == candidate.map(&:login)\n      end\n    end\n  end\nend\n```\n\nIf either the control block or candidate block raises an error, Scientist compares the two observations' classes and messages using `==`. To override this behavior, use `compare_errors` to define how to compare observed errors instead:\n\n```ruby\nclass MyWidget\n  include Scientist\n\n  def slug_from_login(login)\n    science \"slug_from_login\" do |e|\n      e.use { User.slug_from_login login }         # returns String instance or ArgumentError\n      e.try { UserService.slug_from_login login }  # returns String instance or ArgumentError\n\n      compare_error_message_and_class = -> (control, candidate) do\n        control.class == candidate.class &&\n        control.message == candidate.message\n      end\n\n      compare_argument_errors = -> (control, candidate) do\n        control.class == ArgumentError &&\n        candidate.class == ArgumentError &&\n        control.message.start_with?(\"Input has invalid characters\") &&\n        candidate.message.start_with?(\"Invalid characters in input\")\n      end\n\n      e.compare_errors do |control, candidate|\n        compare_error_message_and_class.call(control, candidate) ||\n        compare_argument_errors.call(control, candidate)\n      end\n    end\n  end\nend\n```\n\n### Adding context\n\nResults aren't very useful without some way to identify them. Use the `context` method to add to or retrieve the context for an experiment:\n\n```ruby\nscience \"widget-permissions\" do |e|\n  e.context :user => user\n\n  e.use { model.check_user(user).valid? }\n  e.try { user.can?(:read, model) }\nend\n```\n\n`context` takes a Symbol-keyed Hash of extra data. The data is available in `Experiment#publish` via the `context` method. If you're using the `science` helper a lot in a class, you can provide a default context:\n\n```ruby\nclass MyWidget\n  include Scientist\n\n  def allows?(user)\n    science \"widget-permissions\" do |e|\n      e.context :user => user\n\n      e.use { model.check_user(user).valid? }\n      e.try { user.can?(:read, model) }\n    end\n  end\n\n  def destroy\n    science \"widget-destruction\" do |e|\n      e.use { old_scary_destroy }\n      e.try { new_safe_destroy }\n    end\n  end\n\n  def default_scientist_context\n    { :widget => self }\n  end\nend\n```\n\nThe `widget-permissions` and `widget-destruction` experiments will both have a `:widget` key in their contexts.\n\n### Expensive setup\n\nIf an experiment requires expensive setup that should only occur when the experiment is going to be run, define it with the `before_run` method:\n\n```ruby\n# Code under test modifies this in-place. We want to copy it for the\n# candidate code, but only when needed:\nvalue_for_original_code = big_object\nvalue_for_new_code      = nil\n\nscience \"expensive-but-worthwhile\" do |e|\n  e.before_run do\n    value_for_new_code = big_object.deep_copy\n  end\n  e.use { original_code(value_for_original_code) }\n  e.try { new_code(value_for_new_code) }\nend\n```\n\n### Keeping it clean\n\nSometimes you don't want to store the full value for later analysis. For example, an experiment may return `User` instances, but when researching a mismatch, all you care about is the logins. You can define how to clean these values in an experiment:\n\n```ruby\nclass MyWidget\n  include Scientist\n\n  def users\n    science \"users\" do |e|\n      e.use { User.all }\n      e.try { UserService.list }\n\n      e.clean do |value|\n        value.map(&:login).sort\n      end\n    end\n  end\nend\n```\n\nAnd this cleaned value is available in observations in the final published result:\n\n```ruby\nclass MyExperiment\n  include Scientist::Experiment\n\n  # ...\n\n  def publish(result)\n    result.control.value         # [<User alice>, <User bob>, <User carol>]\n    result.control.cleaned_value # [\"alice\", \"bob\", \"carol\"]\n  end\nend\n```\n\nNote that the `#clean` method will discard the previous cleaner block if you call it again.  If for some reason you need to access the currently configured cleaner block, `Scientist::Experiment#cleaner` will return the block without further ado.  _(This probably won't come up in normal usage, but comes in handy if you're writing, say, a custom experiment runner that provides default cleaners.)_\n\nThe `#clean` method will not be used for comparison of the results, so in the following example it is not possible to remove the `#compare` method without the experiment failing:\n\n```ruby\ndef user_ids\n  science \"user_ids\" do\n    e.use { [1,2,3] }\n    e.try { [1,3,2] }\n    e.clean { |value| value.sort }\n    e.compare { |a, b| a.sort == b.sort }\n  end\nend\n```\n\n### Ignoring mismatches\n\nDuring the early stages of an experiment, it's possible that some of your code will always generate a mismatch for reasons you know and understand but haven't yet fixed. Instead of these known cases always showing up as mismatches in your metrics or analysis, you can tell an experiment whether or not to ignore a mismatch using the `ignore` method. You may include more than one block if needed:\n\n```ruby\ndef admin?(user)\n  science \"widget-permissions\" do |e|\n    e.use { model.check_user(user).admin? }\n    e.try { user.can?(:admin, model) }\n\n    e.ignore { user.staff? } # user is staff, always an admin in the new system\n    e.ignore do |control, candidate|\n      # new system doesn't handle unconfirmed users yet:\n      control && !candidate && !user.confirmed_email?\n    end\n  end\nend\n```\n\nThe ignore blocks are only called if the *values* don't match. Unless a `compare_errors` comparator is defined, two cases are considered mismatches: a) one observation raising an exception and the other not, b) observations raising exceptions with different classes or messages.\n\n### Enabling/disabling experiments\n\nSometimes you don't want an experiment to run. Say, disabling a new codepath for anyone who isn't staff. You can disable an experiment by setting a `run_if` block. If this returns `false`, the experiment will merely return the control value. Otherwise, it defers to the experiment's configured `enabled?` method.\n\n```ruby\nclass DashboardController\n  include Scientist\n\n  def dashboard_items\n    science \"dashboard-items\" do |e|\n      # only run this experiment for staff members\n      e.run_if { current_user.staff? }\n      # ...\n  end\nend\n```\n\n### Ramping up experiments\n\nAs a scientist, you know it's always important to be able to turn your experiment off, lest it run amok and result in villagers with pitchforks on your doorstep. In order to control whether or not an experiment is enabled, you must include the `enabled?` method in your `Scientist::Experiment` implementation.\n\n```ruby\nclass MyExperiment\n  include Scientist::Experiment\n\n  attr_accessor :name, :percent_enabled\n\n  def initialize(name)\n    @name = name\n    @percent_enabled = 100\n  end\n\n  def enabled?\n    percent_enabled > 0 && rand(100) < percent_enabled\n  end\n\n  # ...\n\nend\n```\n\nThis code will be invoked for every method with an experiment every time, so be sensitive about its performance. For example, you can store an experiment in the database but wrap it in various levels of caching such as memcache or per-request thread-locals.\n\n### Publishing results\n\nWhat good is science if you can't publish your results?\n\nYou must implement the `publish(result)` method, and can publish data however you like. For example, timing data can be sent to graphite, and mismatches can be placed in a capped collection in redis for debugging later.\n\nThe `publish` method is given a `Scientist::Result` instance with its associated `Scientist::Observation`s:\n\n```ruby\nclass MyExperiment\n  include Scientist::Experiment\n\n  # ...\n\n  def publish(result)\n\n    # Wall time\n    # Store the timing for the control value,\n    $statsd.timing \"science.#{name}.control\", result.control.duration\n    # for the candidate (only the first, see \"Breaking the rules\" below,\n    $statsd.timing \"science.#{name}.candidate\", result.candidates.first.duration\n\n    # CPU time\n    # Store the timing for the control value,\n    $statsd.timing \"science.cpu.#{name}.control\", result.control.cpu_time\n    # for the candidate (only the first, see \"Breaking the rules\" below,\n    $statsd.timing \"science.cpu.#{name}.candidate\", result.candidates.first.cpu_time\n\n    # and counts for match/ignore/mismatch:\n    if result.matched?\n      $statsd.increment \"science.#{name}.matched\"\n    elsif result.ignored?\n      $statsd.increment \"science.#{name}.ignored\"\n    else\n      $statsd.increment \"science.#{name}.mismatched\"\n      # Finally, store mismatches in redis so they can be retrieved and examined\n      # later on, for debugging and research.\n      store_mismatch_data(result)\n    end\n  end\n\n  def store_mismatch_data(result)\n    payload = {\n      :name            => name,\n      :context         => context,\n      :control         => observation_payload(result.control),\n      :candidate       => observation_payload(result.candidates.first),\n      :execution_order => result.observations.map(&:name)\n    }\n\n    key = \"science.#{name}.mismatch\"\n    $redis.lpush key, payload\n    $redis.ltrim key, 0, 1000\n  end\n\n  def observation_payload(observation)\n    if observation.raised?\n      {\n        :exception => observation.exception.class,\n        :message   => observation.exception.message,\n        :backtrace => observation.exception.backtrace\n      }\n    else\n      {\n        # see \"Keeping it clean\" above\n        :value => observation.cleaned_value\n      }\n    end\n  end\nend\n```\n\n### Testing\n\nWhen running your test suite, it's helpful to know that the experimental results always match. To help with testing, Scientist defines a `raise_on_mismatches` class attribute when you include `Scientist::Experiment`. Only do this in your test suite!\n\nTo raise on mismatches:\n\n```ruby\nclass MyExperiment\n  include Scientist::Experiment\n  # ... implementation\nend\n\nMyExperiment.raise_on_mismatches = true\n```\n\nScientist will raise a `Scientist::Experiment::MismatchError` exception if any observations don't match.\n\n#### Custom mismatch errors\n\nTo instruct Scientist to raise a custom error instead of the default `Scientist::Experiment::MismatchError`:\n\n```ruby\nclass CustomMismatchError < Scientist::Experiment::MismatchError\n  def to_s\n    message = \"There was a mismatch! Here's the diff:\"\n\n    diffs = result.candidates.map do |candidate|\n      Diff.new(result.control, candidate)\n    end.join(\"\\n\")\n\n    \"#{message}\\n#{diffs}\"\n  end\nend\n```\n\n```ruby\nscience \"widget-permissions\" do |e|\n  e.use { Report.find(id) }\n  e.try { ReportService.new.fetch(id) }\n\n  e.raise_with CustomMismatchError\nend\n```\n\nThis allows for pre-processing on mismatch error exception messages.\n\n### Handling errors\n\n#### In candidate code\n\nScientist rescues and tracks _all_ exceptions raised in a `try` or `use` block, including some where rescuing may cause unexpected behavior (like `SystemExit` or `ScriptError`). To rescue a more restrictive set of exceptions, modify the `RESCUES` list:\n\n```ruby\n# default is [Exception]\nScientist::Observation::RESCUES.replace [StandardError]\n```\n\n**Timeout ⏲️**: If you're introducing a candidate that could possibly timeout, use caution. ⚠️ While Scientist rescues all exceptions that occur in the candidate block, it *does not* protect you from timeouts, as doing so would be complicated. It would likely require running the candidate code in a background job and tracking the time of a request. We feel the cost of this complexity would outweigh the benefit, so make sure that your code doesn't cause timeouts. This risk can be reduced by running the experiment on a low percentage so that users can (most likely) bypass the experiment by refreshing the page if they hit a timeout. See [Ramping up experiments](#ramping-up-experiments) below for how details on how to set the percentage for your experiment.\n\n#### In a Scientist callback\n\nIf an exception is raised within any of Scientist's internal helpers, like `publish`, `compare`, or `clean`, the `raised` method is called with the symbol name of the internal operation that failed and the exception that was raised. The default behavior of `Scientist::Default` is to simply re-raise the exception. Since this halts the experiment entirely, it's often a better idea to handle this error and continue so the experiment as a whole isn't canceled entirely:\n\n```ruby\nclass MyExperiment\n  include Scientist::Experiment\n\n  # ...\n\n  def raised(operation, error)\n    InternalErrorTracker.track! \"science failure in #{name}: #{operation}\", error\n  end\nend\n```\n\nThe operations that may be handled here are:\n\n* `:clean` - an exception is raised in a `clean` block\n* `:compare` - an exception is raised in a `compare` block\n* `:enabled` - an exception is raised in the `enabled?` method\n* `:ignore` - an exception is raised in an `ignore` block\n* `:publish` - an exception is raised in the `publish` method\n* `:run_if` - an exception is raised in a `run_if` block\n\n### Designing an experiment\n\nBecause `enabled?` and `run_if` determine when a candidate runs, it's impossible to guarantee that it will run every time. For this reason, Scientist is only safe for wrapping methods that aren't changing data.\n\nWhen using Scientist, we've found it most useful to modify both the existing and new systems simultaneously anywhere writes happen, and verify the results at read time with `science`. `raise_on_mismatches` has also been useful to ensure that the correct data was written during tests, and reviewing published mismatches has helped us find any situations we overlooked with our production data at runtime. When writing to and reading from two systems, it's also useful to write some data reconciliation scripts to verify and clean up production data alongside any running experiments.\n\n#### Noise and error rates\n\nKeep in mind that Scientist's `try` and `use` blocks run sequentially in random order. As such, any data upon which your code depends may change before the second block is invoked, potentially yielding a mismatch between the candidate and control return values. To calibrate your expectations with respect to [false negatives](https://en.wikipedia.org/wiki/Type_I_and_type_II_errors) arising from systemic conditions external to your proposed changes, consider starting with an experiment in which both the `try` and `use` blocks invoke the control method. Then proceed with introducing a candidate.\n\n### Finishing an experiment\n\nAs your candidate behavior converges on the controls, you'll start thinking about removing an experiment and using the new behavior.\n\n* If there are any ignore blocks, the candidate behavior is *guaranteed* to be different. If this is unacceptable, you'll need to remove the ignore blocks and resolve any ongoing mismatches in behavior until the observations match perfectly every time.\n* When removing a read-behavior experiment, it's a good idea to keep any write-side duplication between an old and new system in place until well after the new behavior has been in production, in case you need to roll back.\n\n## Breaking the rules\n\nSometimes scientists just gotta do weird stuff. We understand.\n\n### Ignoring results entirely\n\nScience is useful even when all you care about is the timing data or even whether or not a new code path blew up. If you have the ability to incrementally control how often an experiment runs via your `enabled?` method, you can use it to silently and carefully test new code paths and ignore the results altogether. You can do this by setting `ignore { true }`, or for greater efficiency, `compare { true }`.\n\nThis will still log mismatches if any exceptions are raised, but will disregard the values entirely.\n\n### Trying more than one thing\n\nIt's not usually a good idea to try more than one alternative simultaneously. Behavior isn't guaranteed to be isolated and reporting + visualization get quite a bit harder. Still, it's sometimes useful.\n\nTo try more than one alternative at once, add names to some `try` blocks:\n\n```ruby\nrequire \"scientist\"\n\nclass MyWidget\n  include Scientist\n\n  def allows?(user)\n    science \"widget-permissions\" do |e|\n      e.use { model.check_user(user).valid? } # old way\n\n      e.try(\"api\") { user.can?(:read, model) } # new service API\n      e.try(\"raw-sql\") { user.can_sql?(:read, model) } # raw query\n    end\n  end\nend\n```\n\nWhen the experiment runs, all candidate behaviors are tested and each candidate observation is compared with the control in turn.\n\n### No control, just candidates\n\nDefine the candidates with named `try` blocks, omit a `use`, and pass a candidate name to `run`:\n\n```ruby\nexperiment = MyExperiment.new(\"various-ways\") do |e|\n  e.try(\"first-way\")  { ... }\n  e.try(\"second-way\") { ... }\nend\n\nexperiment.run(\"second-way\")\n```\n\nThe `science` helper also knows this trick:\n\n```ruby\nscience \"various-ways\", run: \"first-way\" do |e|\n  e.try(\"first-way\")  { ... }\n  e.try(\"second-way\") { ... }\nend\n```\n\n#### Providing fake timing data\n\nIf you're writing tests that depend on specific timing values, you can provide canned durations using the `fabricate_durations_for_testing_purposes` method, and Scientist will report these in `Scientist::Observation#duration` and `Scientist::Observation#cpu_time` instead of the actual execution times.\n\n```ruby\nscience \"absolutely-nothing-suspicious-happening-here\" do |e|\n  e.use { ... } # \"control\"\n  e.try { ... } # \"candidate\"\n  e.fabricate_durations_for_testing_purposes({\n    \"control\" => { \"duration\" => 1.0, \"cpu_time\" => 0.9 },\n    \"candidate\" => { \"duration\" => 0.5, \"cpu_time\" => 0.4 }\n  })\nend\n```\n\n`fabricate_durations_for_testing_purposes` takes a Hash of duration & cpu_time values, keyed by behavior names.  (By default, Scientist uses `\"control\"` and `\"candidate\"`, but if you override these as shown in [Trying more than one thing](#trying-more-than-one-thing) or [No control, just candidates](#no-control-just-candidates), use matching names here.)  If a name is not provided, the actual execution time will be reported instead.\n\nWe should mention these durations will be used both for the `duration` field and the `cpu_time` field.\n\n_Like `Scientist::Experiment#cleaner`, this probably won't come up in normal usage.  It's here to make it easier to test code that extends Scientist._\n\n### Without including Scientist\n\nIf you need to use Scientist in a place where you aren't able to include the Scientist module, you can call `Scientist.run`:\n\n```ruby\nScientist.run \"widget-permissions\" do |e|\n  e.use { model.check_user(user).valid? }\n  e.try { user.can?(:read, model) }\nend\n```\n\n## Hacking\n\nBe on a Unixy box. Make sure a modern Bundler is available. `script/test` runs the unit tests. All development dependencies are installed automatically. Scientist requires Ruby 2.3 or newer.\n\n## Wrappers\n\n- [RealGeeks/lab_tech](https://github.com/RealGeeks/lab_tech) is a Rails engine for using this library by controlling, storing, and analyzing experiment results with ActiveRecord.\n\n## Alternatives\n\n- [daylerees/scientist](https://github.com/daylerees/scientist) (PHP)\n- [scientistproject/scientist.net](https://github.com/scientistproject/Scientist.net) (.NET)\n- [joealcorn/laboratory](https://github.com/joealcorn/laboratory) (Python)\n- [rawls238/Scientist4J](https://github.com/rawls238/Scientist4J) (Java)\n- [tomiaijo/scientist](https://github.com/tomiaijo/scientist) (C++)\n- [trello/scientist](https://github.com/trello/scientist) (node.js)\n- [ziyasal/scientist.js](https://github.com/ziyasal/scientist.js) (node.js, ES6)\n- [TrueWill/tzientist](https://github.com/TrueWill/tzientist) (node.js, TypeScript)\n- [TrueWill/paleontologist](https://github.com/TrueWill/paleontologist) (Deno, TypeScript)\n- [yeller/laboratory](https://github.com/yeller/laboratory) (Clojure)\n- [lancew/Scientist](https://github.com/lancew/Scientist) (Perl 5)\n- [lancew/ScientistP6](https://github.com/lancew/ScientistP6) (Perl 6)\n- [MadcapJake/Test-Lab](https://github.com/MadcapJake/Test-Lab) (Perl 6)\n- [cwbriones/scientist](https://github.com/cwbriones/scientist) (Elixir)\n- [calavera/go-scientist](https://github.com/calavera/go-scientist) (Go)\n- [jelmersnoeck/experiment](https://github.com/jelmersnoeck/experiment) (Go)\n- [spoptchev/scientist](https://github.com/spoptchev/scientist) (Kotlin / Java)\n- [junkpiano/scientist](https://github.com/junkpiano/scientist) (Swift)\n- [serverless scientist](http://serverlessscientist.com/) (AWS Lambda)\n- [fightmegg/scientist](https://github.com/fightmegg/scientist) (TypeScript, Browser / Node.js)\n- [MisterSpex/misterspex-scientist](https://github.com/MisterSpex/misterspex-scientist) (Java, no dependencies)\n\n## Maintainers\n\n[@jbarnette](https://github.com/jbarnette),\n[@jesseplusplus](https://github.com/jesseplusplus),\n[@rick](https://github.com/rick),\nand [@zerowidth](https://github.com/zerowidth)\n"
  },
  {
    "path": "Rakefile",
    "content": "require \"rake/testtask\"\n\ntask default: \"test\"\n\nRake::TestTask.new do |t|\n  t.test_files = FileList['test/test_helper.rb', 'test/**/*_test.rb']\nend\n"
  },
  {
    "path": "doc/changelog.md",
    "content": "# Changes\n\n## v1.6.5 (16 December 2024)\n\n- New: measure CPU time alongside wall time for experiments #275\n\n## v1.6.4 (5 April 2023)\n\n- New: GitHub Actions for CI #171\n- New: add ruby 3.1 support #175\n- Fix: `compare_errors` in docs #178\n- Fix: remove outdated travis configs #179\n- Fix: typos #191\n- New: add support for `after_run` blocks #211\n\n## v1.6.3 (9 December 2021)\n\n- Fix: improve marshaling implementation #169\n\n## v1.6.2 (4 November 2021)\n\n- New: make `MismatchError` marshalable #168\n\n## v1.6.1 (22 October 2021)\n\n- Fix: moving supported ruby versions from <=2.3 to >=2.6 #150\n- Fix: update docs to explain timeout handling #159\n- New: add support for comparing errors #77\n\n## v1.6.0 (8 March 2021)\n\n- Fix: clarify unit for observations #124\n- New: enable support for truffleruby #143\n- Fix: don't default experiment when included in a module #144\n\n## v1.5.0 (8 September 2020)\n\n- Fix: clearer explanation of exception handling #110\n- Fix: remove unused attribute from `Scientist::Observation` #119\n- New: Added internal extension point for generating experinet results #121\n- New: Add `Scientist::Experiment.register` helper #104\n\n## v1.4.0 (20 September 2019)\n\n- New: Make `MismatchError` a base `Exception` #107\n\n## v1.3.0 (2 April 2019)\n\n- New: Drop support for ruby <2.3\n- Fix: Build new strings instead of modifying frozen ones\n- New: Add an accessor for the configured clean block\n- New: Add a hook to use fabricated durations instead of actual timing data.\n\n## v1.2.0 (5 July 2018)\n\n- New: Use monotonic clock for duration calculations\n- New: Drop support for ruby <2.1 to support monotonic clock\n- New: Run CI on Ruby 2.5\n\n## v1.1.2 (9 May 2018)\n\n- New: Add `raise_with` option to allow for custom mismatch errors to be raised\n\n## v1.1.1 (6 February 2018)\n\n- Fix: default experiment no longer runs all `try` paths\n- New: Add `Scientist.run` module method for running experiments when an included module isn't available\n- New: Add [Noise and error rates](https://github.com/github/scientist#noise-and-error-rates) to `README.md`\n\n## v1.1.0 (29 August 2017)\n\n- New: [Specify which exception types to rescue](https://github.com/github/scientist#in-candidate-code)\n- New: List [alternative implementations](https://github.com/github/scientist#alternatives) in `README.md`\n- New: Code coverage via [coveralls.io](https://coveralls.io/github/github/scientist)\n- New: Run CI on Ruby 2.3 and 2.4\n- Fix: `README` typos, examples, and lies\n- Fix: `false` results are now passed to the cleaner\n"
  },
  {
    "path": "lib/scientist/default.rb",
    "content": "require \"scientist/experiment\"\n\n# A null experiment.\nclass Scientist::Default\n  include Scientist::Experiment\n\n  attr_reader :name\n\n  def initialize(name)\n    @name = name\n  end\n\n  # Don't run experiments.\n  def enabled?\n    false\n  end\n\n  # Don't publish anything.\n  def publish(result)\n  end\nend\n"
  },
  {
    "path": "lib/scientist/errors.rb",
    "content": "module Scientist\n\n  # Smoking in the bathroom and/or sassing.\n  class BadBehavior < StandardError\n    attr_reader :experiment\n    attr_reader :name\n\n    def initialize(experiment, name, message)\n      @experiment = experiment\n      @name = name\n\n      super message\n    end\n  end\n\n  class BehaviorMissing < BadBehavior\n    def initialize(experiment, name)\n      super experiment, name,\n        \"#{experiment.name} missing #{name} behavior\"\n    end\n  end\n\n  class BehaviorNotUnique < BadBehavior\n    def initialize(experiment, name)\n      super experiment, name,\n        \"#{experiment.name} already has #{name} behavior\"\n    end\n  end\n\n  class NoValue < StandardError\n    attr_reader :observation\n\n    def initialize(observation)\n      @observation = observation\n      super \"#{observation.name} didn't return a value\"\n    end\n  end\nend\n"
  },
  {
    "path": "lib/scientist/experiment.rb",
    "content": "# This mixin provides shared behavior for experiments. Includers must implement\n# `enabled?` and `publish(result)`.\n#\n# Override Scientist::Experiment.new to set your own class which includes and\n# implements Scientist::Experiment's interface.\nmodule Scientist::Experiment\n\n  # Whether to raise when the control and candidate mismatch.\n  # If this is nil, raise_on_mismatches class attribute is used instead.\n  attr_accessor :raise_on_mismatches\n\n  def self.included(base)\n    self.set_default(base) if base.instance_of?(Class)\n    base.extend RaiseOnMismatch\n  end\n\n  # Instantiate a new experiment (using the class given to the .set_default method).\n  def self.new(name)\n    (@experiment_klass || Scientist::Default).new(name)\n  end\n\n  # Configure Scientist to use the given class for all future experiments\n  # (must implement the Scientist::Experiment interface).\n  #\n  # Called automatically when new experiments are defined.\n  def self.set_default(klass)\n    @experiment_klass = klass\n  end\n\n  # A mismatch, raised when raise_on_mismatches is enabled.\n  class MismatchError < Exception\n    attr_reader :name, :result\n\n    def initialize(name, result)\n      @name   = name\n      @result = result\n      super \"experiment '#{name}' observations mismatched\"\n    end\n\n    # The default formatting is nearly unreadable, so make it useful.\n    #\n    # The assumption here is that errors raised in a test environment are\n    # printed out as strings, rather than using #inspect.\n    def to_s\n      super + \":\\n\" +\n      format_observation(result.control) + \"\\n\" +\n      result.candidates.map { |candidate| format_observation(candidate) }.join(\"\\n\") +\n      \"\\n\"\n    end\n\n    def format_observation(observation)\n      observation.name + \":\\n\" +\n      if observation.raised?\n        lines = observation.exception.backtrace.map { |line| \"    #{line}\" }.join(\"\\n\")\n        \"  #{observation.exception.inspect}\" + \"\\n\" + lines\n      else\n        \"  #{observation.cleaned_value.inspect}\"\n      end\n    end\n  end\n\n  module RaiseOnMismatch\n    # Set this flag to raise on experiment mismatches.\n    #\n    # This causes all science mismatches to raise a MismatchError. This is\n    # intended for test environments and should not be enabled in a production\n    # environment.\n    #\n    # bool - true/false - whether to raise when the control and candidate mismatch.\n    def raise_on_mismatches=(bool)\n      @raise_on_mismatches = bool\n    end\n\n    # Whether or not to raise a mismatch error when a mismatch occurs.\n    def raise_on_mismatches?\n      @raise_on_mismatches\n    end\n  end\n\n  # Define a block of code to run before an experiment begins, if the experiment\n  # is enabled.\n  #\n  # The block takes no arguments.\n  #\n  # Returns the configured block.\n  def before_run(&block)\n    @_scientist_before_run = block\n  end\n\n  # Define a block of code to run after an experiment completes, if the experiment\n  # is enabled.\n  #\n  # The block takes one argument, the Scientist::Result containing experiment results.\n  #\n  # Returns the configured block.\n  def after_run(&block)\n    @_scientist_after_run = block\n  end\n\n  # A Hash of behavior blocks, keyed by String name. Register behavior blocks\n  # with the `try` and `use` methods.\n  def behaviors\n    @_scientist_behaviors ||= {}\n  end\n\n  # A block to clean an observed value for publishing or storing.\n  #\n  # The block takes one argument, the observed value which will be cleaned.\n  #\n  # Returns the configured block.\n  def clean(&block)\n    @_scientist_cleaner = block\n  end\n\n  # Accessor for the clean block, if one is available.\n  #\n  # Returns the configured block, or nil.\n  def cleaner\n    @_scientist_cleaner\n  end\n\n  # Internal: Clean a value with the configured clean block, or return the value\n  # if no clean block is configured.\n  #\n  # Rescues and reports exceptions in the clean block if they occur.\n  def clean_value(value)\n    if @_scientist_cleaner\n      @_scientist_cleaner.call value\n    else\n      value\n    end\n  rescue StandardError => ex\n    raised :clean, ex\n    value\n  end\n\n  # A block which compares two experimental values.\n  #\n  # The block must take two arguments, the control value and a candidate value,\n  # and return true or false.\n  #\n  # Returns the block.\n  def compare(*args, &block)\n    @_scientist_comparator = block\n  end\n\n  # A block which compares two experimental errors.\n  #\n  # The block must take two arguments, the control Error and a candidate Error,\n  # and return true or false.\n  #\n  # Returns the block.\n  def compare_errors(*args, &block)\n    @_scientist_error_comparator = block\n  end\n\n  # A Symbol-keyed Hash of extra experiment data.\n  def context(context = nil)\n    @_scientist_context ||= {}\n    @_scientist_context.merge!(context) unless context.nil?\n    @_scientist_context\n  end\n\n  # Configure this experiment to ignore an observation with the given block.\n  #\n  # The block takes two arguments, the control observation and the candidate\n  # observation which didn't match the control. If the block returns true, the\n  # mismatch is disregarded.\n  #\n  # This can be called more than once with different blocks to use.\n  def ignore(&block)\n    @_scientist_ignores ||= []\n    @_scientist_ignores << block\n  end\n\n  # Internal: ignore a mismatched observation?\n  #\n  # Iterates through the configured ignore blocks and calls each of them with\n  # the given control and mismatched candidate observations.\n  #\n  # Returns true or false.\n  def ignore_mismatched_observation?(control, candidate)\n    return false unless @_scientist_ignores\n    @_scientist_ignores.any? do |ignore|\n      begin\n        ignore.call control.value, candidate.value\n      rescue StandardError => ex\n        raised :ignore, ex\n        false\n      end\n    end\n  end\n\n  # The String name of this experiment. Default is \"experiment\". See\n  # Scientist::Default for an example of how to override this default.\n  def name\n    \"experiment\"\n  end\n\n  # Internal: compare two observations, using the configured compare and compare_errors lambdas if present.\n  def observations_are_equivalent?(a, b)\n    a.equivalent_to? b, @_scientist_comparator, @_scientist_error_comparator\n  rescue StandardError => ex\n    raised :compare, ex\n    false\n  end\n\n  def raise_with(exception)\n    @_scientist_custom_mismatch_error = exception\n  end\n\n  # Called when an exception is raised while running an internal operation,\n  # like :publish. Override this method to track these exceptions. The\n  # default implementation re-raises the exception.\n  def raised(operation, error)\n    raise error\n  end\n\n  # Internal: Run all the behaviors for this experiment, observing each and\n  # publishing the results. Return the result of the named behavior, default\n  # \"control\".\n  def run(name = nil)\n    behaviors.freeze\n    context.freeze\n\n    name = (name || \"control\").to_s\n    block = behaviors[name]\n\n    if block.nil?\n      raise Scientist::BehaviorMissing.new(self, name)\n    end\n\n    unless should_experiment_run?\n      return block.call\n    end\n\n    if @_scientist_before_run\n      @_scientist_before_run.call\n    end\n\n    result = generate_result(name)\n\n    if @_scientist_after_run\n      @_scientist_after_run.call(result)\n    end\n\n    begin\n      publish(result)\n    rescue StandardError => ex\n      raised :publish, ex\n    end\n\n    if raise_on_mismatches? && result.mismatched?\n      if @_scientist_custom_mismatch_error\n        raise @_scientist_custom_mismatch_error.new(self.name, result)\n      else\n        raise MismatchError.new(self.name, result)\n      end\n    end\n\n    control = result.control\n    raise control.exception if control.raised?\n    control.value\n  end\n\n  # Define a block that determines whether or not the experiment should run.\n  def run_if(&block)\n    @_scientist_run_if_block = block\n  end\n\n  # Internal: does a run_if block allow the experiment to run?\n  #\n  # Rescues and reports exceptions in a run_if block if they occur.\n  def run_if_block_allows?\n    (@_scientist_run_if_block ? @_scientist_run_if_block.call : true)\n  rescue StandardError => ex\n    raised :run_if, ex\n    return false\n  end\n\n  # Internal: determine whether or not an experiment should run.\n  #\n  # Rescues and reports exceptions in the enabled method if they occur.\n  def should_experiment_run?\n    behaviors.size > 1 && enabled? && run_if_block_allows?\n  rescue StandardError => ex\n    raised :enabled, ex\n    return false\n  end\n\n  # Register a named behavior for this experiment, default \"candidate\".\n  def try(name = nil, &block)\n    name = (name || \"candidate\").to_s\n\n    if behaviors.include?(name)\n      raise Scientist::BehaviorNotUnique.new(self, name)\n    end\n\n    behaviors[name] = block\n  end\n\n  # Register the control behavior for this experiment.\n  def use(&block)\n    try \"control\", &block\n  end\n\n  # Whether or not to raise a mismatch error when a mismatch occurs.\n  def raise_on_mismatches?\n    if raise_on_mismatches.nil?\n      self.class.raise_on_mismatches?\n    else\n      !!raise_on_mismatches\n    end\n  end\n\n  # Provide predefined durations to use instead of actual timing data.\n  # This is here solely as a convenience for developers of libraries that extend Scientist.\n  def fabricate_durations_for_testing_purposes(fabricated_durations = {})\n    @_scientist_fabricated_durations = fabricated_durations\n  end\n\n  # Internal: Generate the observations and create the result from those and the control.\n  def generate_result(name)\n    observations = []\n\n    behaviors.keys.shuffle.each do |key|\n      block = behaviors[key]\n      fabricated_duration = @_scientist_fabricated_durations && @_scientist_fabricated_durations[key]\n      observations << Scientist::Observation.new(key, self, fabricated_duration: fabricated_duration, &block)\n    end\n\n    control = observations.detect { |o| o.name == name }\n    Scientist::Result.new(self, observations, control)\n  end\n\n  private\n\n  # In order to support marshaling, we have to make the procs marshalable. Some\n  # CI providers attempt to marshal Scientist mismatch errors so that they can\n  # be sent out to different places (logs, etc.) The mismatch errors contain\n  # code from the experiment. This code contains procs. These procs prevent the\n  # error from being marshaled. To fix this, we simple exclude the procs from\n  # the data that we marshal.\n  def marshal_dump\n    [@name, @result, @raise_on_mismatches]\n  end\n\n  def marshal_load(array)\n    @name, @result, @raise_on_mismatches = array\n  end\nend\n"
  },
  {
    "path": "lib/scientist/observation.rb",
    "content": "# What happened when this named behavior was executed? Immutable.\nclass Scientist::Observation\n\n  # An Array of Exception types to rescue when initializing an observation.\n  # NOTE: This Array will change to `[StandardError]` in the next major release.\n  RESCUES = [Exception]\n\n  # The experiment this observation is for\n  attr_reader :experiment\n\n  # The String name of the behavior.\n  attr_reader :name\n\n  # The value returned, if any.\n  attr_reader :value\n\n  # The raised exception, if any.\n  attr_reader :exception\n\n  # The Float seconds elapsed.\n  attr_reader :duration\n\n  # The Float CPU time elapsed, in seconds\n  attr_reader :cpu_time\n\n  def initialize(name, experiment, fabricated_duration: nil, &block)\n    @name       = name\n    @experiment = experiment\n\n    start_wall_time, start_cpu_time = capture_times unless fabricated_duration\n\n    begin\n      @value = block.call\n    rescue *RESCUES => e\n      @exception = e\n    end\n\n    if fabricated_duration.is_a?(Hash)\n      @duration = fabricated_duration[\"duration\"]\n      @cpu_time = fabricated_duration[\"cpu_time\"]\n    elsif fabricated_duration\n      @duration = fabricated_duration\n      @cpu_time = 0.0 # setting a default value\n    else\n      end_wall_time, end_cpu_time = capture_times\n      @duration = end_wall_time - start_wall_time\n      @cpu_time = end_cpu_time - start_cpu_time\n    end\n\n    freeze\n  end\n\n  # Return a cleaned value suitable for publishing. Uses the experiment's\n  # defined cleaner block to clean the observed value.\n  def cleaned_value\n    experiment.clean_value value unless value.nil?\n  end\n\n  # Is this observation equivalent to another?\n  #\n  # other            - the other Observation in question\n  # comparator       - an optional comparison proc. This observation's value and the\n  #                    other observation's value are passed to this to determine\n  #                    their equivalency. Proc should return true/false.\n  # error_comparator - an optional comparison proc. This observation's Error and the\n  #                    other observation's Error are passed to this to determine\n  #                    their equivalency. Proc should return true/false.\n  #\n  # Returns true if:\n  #\n  # * The values of the observation are equal (using `==`)\n  # * The values of the observations are equal according to a comparison\n  #   proc, if given\n  # * The exceptions raised by the observations are equal according to the\n  #   error comparison proc, if given.\n  # * Both observations raised an exception with the same class and message.\n  #\n  # Returns false otherwise.\n  def equivalent_to?(other, comparator=nil, error_comparator=nil)\n    return false unless other.is_a?(Scientist::Observation)\n\n    if raised? || other.raised?\n      if error_comparator\n        return error_comparator.call(exception, other.exception)\n      else\n        return other.exception.class == exception.class &&\n          other.exception.message == exception.message\n      end\n    end\n\n    if comparator\n      comparator.call(value, other.value)\n    else\n      value == other.value\n    end\n  end\n\n  def hash\n    [value, exception, self.class].compact.map(&:hash).inject(:^)\n  end\n\n  def raised?\n    !exception.nil?\n  end\n\n  private\n\n  def capture_times\n    [\n      Process.clock_gettime(Process::CLOCK_MONOTONIC, :float_second),\n      Process.clock_gettime(Process::CLOCK_PROCESS_CPUTIME_ID, :float_second)\n    ]\n  end\nend\n"
  },
  {
    "path": "lib/scientist/result.rb",
    "content": "# The immutable result of running an experiment.\nclass Scientist::Result\n\n  # An Array of candidate Observations.\n  attr_reader :candidates\n\n  # The control Observation to which the rest are compared.\n  attr_reader :control\n\n  # An Experiment.\n  attr_reader :experiment\n\n  # An Array of observations which didn't match the control, but were ignored.\n  attr_reader :ignored\n\n  # An Array of observations which didn't match the control.\n  attr_reader :mismatched\n\n  # An Array of Observations in execution order.\n  attr_reader :observations\n\n  # Internal: Create a new result.\n  #\n  # experiment    - the Experiment this result is for\n  # observations: - an Array of Observations, in execution order\n  # control:      - the control Observation\n  #\n  def initialize(experiment, observations = [], control = nil)\n    @experiment   = experiment\n    @observations = observations\n    @control      = control\n    @candidates   = observations - [control]\n    evaluate_candidates\n\n    freeze\n  end\n\n  # Public: the experiment's context\n  def context\n    experiment.context\n  end\n\n  # Public: the name of the experiment\n  def experiment_name\n    experiment.name\n  end\n\n  # Public: was the result a match between all behaviors?\n  def matched?\n    mismatched.empty? && !ignored?\n  end\n\n  # Public: were there mismatches in the behaviors?\n  def mismatched?\n    mismatched.any?\n  end\n\n  # Public: were there any ignored mismatches?\n  def ignored?\n    ignored.any?\n  end\n\n  # Internal: evaluate the candidates to find mismatched and ignored results\n  #\n  # Sets @ignored and @mismatched with the ignored and mismatched candidates.\n  def evaluate_candidates\n    mismatched = candidates.reject do |candidate|\n      experiment.observations_are_equivalent?(control, candidate)\n    end\n\n    @ignored = mismatched.select do |candidate|\n      experiment.ignore_mismatched_observation? control, candidate\n    end\n\n    @mismatched = mismatched - @ignored\n  end\nend\n"
  },
  {
    "path": "lib/scientist/version.rb",
    "content": "module Scientist\n  VERSION = '1.6.5'\nend\n"
  },
  {
    "path": "lib/scientist.rb",
    "content": "# Include this module into any class which requires science experiments in its\n# methods. Provides the `science` and `default_scientist_context` methods for\n# defining and running experiments.\n#\n# If you need to run science on class methods, extend this module instead.\n#\n# If including or extending this module are not an option, call\n# `Scientist.run`.\nmodule Scientist\n  # Define and run a science experiment.\n  #\n  # name - a String name for this experiment.\n  # opts - optional hash with the the named test to run instead of \"control\",\n  #        :run is the only valid key.\n  #\n  # Yields an object which implements the Scientist::Experiment interface.\n  # See `Scientist::Experiment.new` for how this is defined.\n  #\n  # Returns the calculated value of the control experiment, or raises if an\n  # exception was raised.\n  def self.run(name, opts = {})\n    experiment = Experiment.new(name)\n\n    yield experiment\n\n    test = opts[:run] if opts\n    experiment.run(test)\n  end\n\n  # Define and run a science experiment.\n  #\n  # name - a String name for this experiment.\n  # opts - optional hash with the the named test to run instead of \"control\",\n  #        :run is the only valid key.\n  #\n  # Yields an object which implements the Scientist::Experiment interface.\n  # See `Scientist::Experiment.new` for how this is defined. The context from\n  # the `default_scientist_context` method will be applied to the experiment.\n  #\n  # Returns the calculated value of the control experiment, or raises if an\n  # exception was raised.\n  def science(name, opts = {})\n    Scientist.run(name, opts) do |experiment|\n      experiment.context(default_scientist_context)\n\n      yield experiment\n    end\n  end\n\n  # Public: the default context data for an experiment created and run via the\n  # `science` helper method. Override this in any class that includes Scientist\n  # to define your own behavior.\n  #\n  # Returns a Hash.\n  def default_scientist_context\n    {}\n  end\nend\n\nrequire \"scientist/default\"\nrequire \"scientist/errors\"\nrequire \"scientist/experiment\"\nrequire \"scientist/observation\"\nrequire \"scientist/result\"\nrequire \"scientist/version\"\n"
  },
  {
    "path": "scientist.gemspec",
    "content": "$: << \"lib\" and require \"scientist/version\"\n\nGem::Specification.new do |gem|\n  gem.name          = \"scientist\"\n  gem.description   = \"A Ruby library for carefully refactoring critical paths\"\n  gem.version       = Scientist::VERSION\n  gem.authors       = [\"GitHub Open Source\", \"John Barnette\", \"Rick Bradley\", \"Jesse Toth\", \"Nathan Witmer\"]\n  gem.email         = [\"opensource+scientist@github.com\", \"jbarnette@github.com\", \"rick@rickbradley.com\", \"jesseplusplus@github.com\",\"zerowidth@github.com\"]\n  gem.summary       = \"Carefully test, measure, and track refactored code.\"\n  gem.homepage      = \"https://github.com/github/scientist\"\n  gem.license       = \"MIT\"\n\n  gem.required_ruby_version = '>= 2.3'\n\n  gem.files         = `git ls-files`.split($/)\n  gem.executables   = []\n  gem.test_files    = gem.files.grep(/^test/)\n  gem.require_paths = [\"lib\"]\n\n  gem.add_development_dependency \"minitest\", \"~> 5.8\"\n  gem.add_development_dependency \"rake\"\nend\n"
  },
  {
    "path": "script/bootstrap",
    "content": "#!/bin/sh\n# Ensure local dependencies are available.\n\nset -e\n\ncd $(dirname \"$0\")/..\nrm -f .bundle/config\n\nbundle install --path .bundle --quiet \"$@\"\n"
  },
  {
    "path": "script/release",
    "content": "#!/bin/sh\n# Tag and push a release.\n\nset -e\n\n# Make sure we're in the project root.\n\ncd $(dirname \"$0\")/..\n\n# Build a new gem archive.\n\nrm -rf scientist-*.gem\ngem build -q scientist.gemspec\n\n# Make sure we're on the main branch.\n\n(git branch --no-color | grep -q '* main') || {\n  echo \"Only release from the main branch.\"\n  exit 1\n}\n\n# Figure out what version we're releasing.\n\ntag=v`ls scientist-*.gem | sed 's/^scientist-\\(.*\\)\\.gem$/\\1/'`\n\n# Make sure we haven't released this version before.\n\ngit fetch -t origin\n\n(git tag -l | grep -q \"$tag\") && {\n  echo \"Whoops, there's already a '${tag}' tag.\"\n  exit 1\n}\n\n# Tag it and bag it.\n\ngem push scientist-*.gem && git tag \"$tag\" &&\n  git push origin main && git push origin \"$tag\"\n"
  },
  {
    "path": "script/test",
    "content": "#!/bin/sh\n# Run the unit tests.\n\nset -e\n\ncd $(dirname \"$0\")/..\n  script/bootstrap && bundle exec rake test\n"
  },
  {
    "path": "test/scientist/default_test.rb",
    "content": "describe Scientist::Default do\n  before do\n    @ex = Scientist::Default.new \"default\"\n  end\n\n  it \"is always disabled\" do\n    refute @ex.enabled?\n  end\n\n  it \"noops publish\" do\n    assert_nil @ex.publish(\"data\")\n  end\n\n  it \"is an experiment\" do\n    assert Scientist::Default < Scientist::Experiment\n  end\n\n  it \"reraises when an internal action raises\" do\n     assert_raises RuntimeError do\n       @ex.raised :publish, RuntimeError.new(\"kaboom\")\n     end\n  end\nend\n"
  },
  {
    "path": "test/scientist/experiment_test.rb",
    "content": "describe Scientist::Experiment do\n  class Fake\n    include Scientist::Experiment\n\n    # Undo auto-config magic / preserve default behavior of Scientist::Experiment.new\n    Scientist::Experiment.set_default(nil)\n\n    def initialize(*args)\n    end\n\n    def enabled?\n      true\n    end\n\n    attr_reader :published_result\n\n    def exceptions\n      @exceptions ||= []\n    end\n\n    def raised(op, exception)\n      exceptions << [op, exception]\n    end\n\n    def publish(result)\n      @published_result = result\n    end\n  end\n\n  before do\n    @ex = Fake.new\n  end\n\n  it \"sets the default on inclusion\" do\n    klass = Class.new do\n      include Scientist::Experiment\n\n      def initialize(name)\n      end\n    end\n\n    assert_kind_of klass, Scientist::Experiment.new(\"hello\")\n\n    Scientist::Experiment.set_default(nil)\n  end\n\n  it \"doesn't set the default on inclusion when it's a module\" do\n    Module.new { include Scientist::Experiment }\n    assert_kind_of Scientist::Default, Scientist::Experiment.new(\"hello\")\n  end\n\n  it \"has a default implementation\" do\n    ex = Scientist::Experiment.new(\"hello\")\n    assert_kind_of Scientist::Default, ex\n    assert_equal \"hello\", ex.name\n  end\n\n  it \"provides a static default name\" do\n    assert_equal \"experiment\", Fake.new.name\n  end\n\n  it \"requires includers to implement enabled?\" do\n    obj = Object.new\n    obj.extend Scientist::Experiment\n\n    assert_raises NoMethodError do\n      obj.enabled?\n    end\n  end\n\n  it \"requires includers to implement publish\" do\n    obj = Object.new\n    obj.extend Scientist::Experiment\n\n    assert_raises NoMethodError do\n      obj.publish(\"result\")\n    end\n  end\n\n  it \"can't be run without a control behavior\" do\n    e = assert_raises Scientist::BehaviorMissing do\n      @ex.run\n    end\n\n    assert_equal \"control\", e.name\n  end\n\n  it \"is a straight pass-through with only a control behavior\" do\n    @ex.use { \"control\" }\n    assert_equal \"control\", @ex.run\n  end\n\n  it \"runs other behaviors but always returns the control\" do\n    @ex.use { \"control\" }\n    @ex.try { \"candidate\" }\n\n    assert_equal \"control\", @ex.run\n  end\n\n  it \"complains about duplicate behavior names\" do\n    @ex.use { \"control\" }\n\n    e = assert_raises Scientist::BehaviorNotUnique do\n      @ex.use { \"control-again\" }\n    end\n\n    assert_equal @ex, e.experiment\n    assert_equal \"control\", e.name\n  end\n\n  it \"swallows exceptions raised by candidate behaviors\" do\n    @ex.use { \"control\" }\n    @ex.try { raise \"candidate\" }\n\n    assert_equal \"control\", @ex.run\n  end\n\n  it \"passes through exceptions raised by the control behavior\" do\n    @ex.use { raise \"control\" }\n    @ex.try { \"candidate\" }\n\n    exception = assert_raises RuntimeError do\n      @ex.run\n    end\n\n    assert_equal \"control\", exception.message\n  end\n\n  it \"shuffles behaviors before running\" do\n    last = nil\n    runs = []\n\n    @ex.use { last = \"control\" }\n    @ex.try { last = \"candidate\" }\n\n    10000.times do\n      @ex.run\n      runs << last\n    end\n\n    assert runs.uniq.size > 1\n  end\n\n  it \"re-raises exceptions raised during publish by default\" do\n    ex = Scientist::Experiment.new(\"hello\")\n    assert_kind_of Scientist::Default, ex\n\n    def ex.enabled?\n      true\n    end\n\n    def ex.publish(result)\n      raise \"boomtown\"\n    end\n\n    ex.use { \"control\" }\n    ex.try { \"candidate\" }\n\n    exception = assert_raises RuntimeError do\n      ex.run\n    end\n\n    assert_equal \"boomtown\", exception.message\n  end\n\n  it \"reports publishing errors\" do\n    def @ex.publish(result)\n      raise \"boomtown\"\n    end\n\n    @ex.use { \"control\" }\n    @ex.try { \"candidate\" }\n\n    assert_equal \"control\", @ex.run\n\n    op, exception = @ex.exceptions.pop\n\n    assert_equal :publish, op\n    assert_equal \"boomtown\", exception.message\n  end\n\n  it \"publishes results\" do\n    @ex.use { 1 }\n    @ex.try { 1 }\n    assert_equal 1, @ex.run\n    assert @ex.published_result\n  end\n\n  it \"does not publish results when there is only a control value\" do\n    @ex.use { 1 }\n    assert_equal 1, @ex.run\n    assert_nil @ex.published_result\n  end\n\n  it \"compares results with a comparator block if provided\" do\n    @ex.compare { |a, b| a == b.to_s }\n    @ex.use { \"1\" }\n    @ex.try { 1 }\n\n    assert_equal \"1\", @ex.run\n    assert @ex.published_result.matched?\n  end\n\n  it \"compares errors with an error comparator block if provided\" do\n    @ex.compare_errors { |a, b| a.class == b.class }\n    @ex.use { raise \"foo\" }\n    @ex.try { raise \"bar\" }\n\n    resulting_error = assert_raises RuntimeError do\n      @ex.run\n    end\n    assert_equal \"foo\", resulting_error.message\n    assert @ex.published_result.matched?\n  end\n\n  it \"knows how to compare two experiments\" do\n    a = Scientist::Observation.new(@ex, \"a\") { 1 }\n    b = Scientist::Observation.new(@ex, \"b\") { 2 }\n\n    assert @ex.observations_are_equivalent?(a, a)\n    refute @ex.observations_are_equivalent?(a, b)\n  end\n\n  it \"uses a compare block to determine if observations are equivalent\" do\n    a = Scientist::Observation.new(@ex, \"a\") { \"1\" }\n    b = Scientist::Observation.new(@ex, \"b\") { 1 }\n    @ex.compare { |x, y| x == y.to_s }\n    assert @ex.observations_are_equivalent?(a, b)\n  end\n\n  it \"reports errors in a compare block\" do\n    @ex.compare { raise \"boomtown\" }\n    @ex.use { \"control\" }\n    @ex.try { \"candidate\" }\n\n    assert_equal \"control\", @ex.run\n\n    op, exception = @ex.exceptions.pop\n\n    assert_equal :compare, op\n    assert_equal \"boomtown\", exception.message\n  end\n\n  it \"reports errors in the enabled? method\" do\n    def @ex.enabled?\n      raise \"kaboom\"\n    end\n\n    @ex.use { \"control\" }\n    @ex.try { \"candidate\" }\n    assert_equal \"control\", @ex.run\n\n    op, exception = @ex.exceptions.pop\n\n    assert_equal :enabled, op\n    assert_equal \"kaboom\", exception.message\n  end\n\n  it \"reports errors in a run_if block\" do\n    @ex.run_if { raise \"kaboom\" }\n    @ex.use { \"control\" }\n    @ex.try { \"candidate\" }\n    assert_equal \"control\", @ex.run\n\n    op, exception = @ex.exceptions.pop\n\n    assert_equal :run_if, op\n    assert_equal \"kaboom\", exception.message\n  end\n\n  it \"returns the given value when no clean block is configured\" do\n    assert_equal 10, @ex.clean_value(10)\n  end\n\n  it \"provides the clean block when asked for it, in case subclasses wish to override and provide defaults\" do\n    assert_nil @ex.cleaner\n    cleaner = ->(value) { value.upcase }\n    @ex.clean(&cleaner)\n    assert_equal cleaner, @ex.cleaner\n  end\n\n  it \"calls the configured clean block with a value when configured\" do\n    @ex.clean do |value|\n      value.upcase\n    end\n\n    assert_equal \"TEST\", @ex.clean_value(\"test\")\n  end\n\n  it \"reports an error and returns the original value when an error is raised in a clean block\" do\n    @ex.clean { |value| raise \"kaboom\" }\n\n    @ex.use { \"control\" }\n    @ex.try { \"candidate\" }\n    assert_equal \"control\", @ex.run\n\n    assert_equal \"control\", @ex.published_result.control.cleaned_value\n\n    op, exception = @ex.exceptions.pop\n\n    assert_equal :clean, op\n    assert_equal \"kaboom\", exception.message\n  end\n\n  describe \"#raise_with\" do\n    it \"raises custom error if provided\" do\n      CustomError = Class.new(Scientist::Experiment::MismatchError)\n\n      @ex.use { 1 }\n      @ex.try { 2 }\n      @ex.raise_with(CustomError)\n      @ex.raise_on_mismatches = true\n\n      assert_raises(CustomError) { @ex.run }\n    end\n  end\n\n  describe \"#run_if\" do\n    it \"does not run the experiment if the given block returns false\" do\n      candidate_ran = false\n      run_check_ran = false\n\n      @ex.use { 1 }\n      @ex.try { candidate_ran = true; 1 }\n\n      @ex.run_if { run_check_ran = true; false }\n\n      @ex.run\n\n      assert run_check_ran\n      refute candidate_ran\n    end\n\n    it \"runs the experiment if the given block returns true\" do\n      candidate_ran = false\n      run_check_ran = false\n\n      @ex.use { true }\n      @ex.try { candidate_ran = true }\n\n      @ex.run_if { run_check_ran = true }\n\n      @ex.run\n\n      assert run_check_ran\n      assert candidate_ran\n    end\n  end\n\n  describe \"#ignore_mismatched_observation?\" do\n    before do\n      @a = Scientist::Observation.new(@ex, \"a\") { 1 }\n      @b = Scientist::Observation.new(@ex, \"b\") { 2 }\n    end\n\n    it \"does not ignore an observation if no ignores are configured\" do\n      refute @ex.ignore_mismatched_observation?(@a, @b)\n    end\n\n    it \"calls a configured ignore block with the given observed values\" do\n      called = false\n      @ex.ignore do |a, b|\n        called = true\n        assert_equal @a.value, a\n        assert_equal @b.value, b\n        true\n      end\n\n      assert @ex.ignore_mismatched_observation?(@a, @b)\n      assert called\n    end\n\n    it \"calls multiple ignore blocks to see if any match\" do\n      called_one = called_two = called_three = false\n      @ex.ignore { |a, b| called_one   = true; false }\n      @ex.ignore { |a, b| called_two   = true; false }\n      @ex.ignore { |a, b| called_three = true; false }\n      refute @ex.ignore_mismatched_observation?(@a, @b)\n      assert called_one\n      assert called_two\n      assert called_three\n    end\n\n    it \"only calls ignore blocks until one matches\" do\n      called_one = called_two = called_three = false\n      @ex.ignore { |a, b| called_one   = true; false }\n      @ex.ignore { |a, b| called_two   = true; true  }\n      @ex.ignore { |a, b| called_three = true; false }\n      assert @ex.ignore_mismatched_observation?(@a, @b)\n      assert called_one\n      assert called_two\n      refute called_three\n    end\n\n    it \"reports exceptions raised in an ignore block and returns false\" do\n      def @ex.exceptions\n        @exceptions ||= []\n      end\n\n      def @ex.raised(op, exception)\n        exceptions << [op, exception]\n      end\n\n      @ex.ignore { raise \"kaboom\" }\n\n      refute @ex.ignore_mismatched_observation?(@a, @b)\n\n      op, exception = @ex.exceptions.pop\n      assert_equal :ignore, op\n      assert_equal \"kaboom\", exception.message\n    end\n\n    it \"skips ignore blocks that raise and tests any remaining blocks if an exception is swallowed\" do\n      def @ex.exceptions\n        @exceptions ||= []\n      end\n\n      # this swallows the exception rather than re-raising\n      def @ex.raised(op, exception)\n        exceptions << [op, exception]\n      end\n\n      @ex.ignore { raise \"kaboom\" }\n      @ex.ignore { true }\n\n      assert @ex.ignore_mismatched_observation?(@a, @b)\n      assert_equal 1, @ex.exceptions.size\n    end\n  end\n\n  describe \"raising on mismatches\" do\n    before do\n      @old_raise_on_mismatches = Fake.raise_on_mismatches?\n    end\n\n    after do\n      Fake.raise_on_mismatches = @old_raise_on_mismatches\n    end\n\n    it \"raises when there is a mismatch if raise on mismatches is enabled\" do\n      Fake.raise_on_mismatches = true\n      @ex.use { \"fine\" }\n      @ex.try { \"not fine\" }\n\n      assert_raises(Scientist::Experiment::MismatchError) { @ex.run }\n    end\n\n    it \"cleans values when raising on observation mismatch\" do\n      Fake.raise_on_mismatches = true\n      @ex.use { \"fine\" }\n      @ex.try { \"not fine\" }\n      @ex.clean { \"So Clean\" }\n\n      err = assert_raises(Scientist::Experiment::MismatchError) { @ex.run }\n      assert_match /So Clean/, err.message\n    end\n\n    it \"doesn't raise when there is a mismatch if raise on mismatches is disabled\" do\n      Fake.raise_on_mismatches = false\n      @ex.use { \"fine\" }\n      @ex.try { \"not fine\" }\n\n      assert_equal \"fine\", @ex.run\n    end\n\n    it \"raises a mismatch error if the control raises and candidate doesn't\" do\n      Fake.raise_on_mismatches = true\n      @ex.use { raise \"control\" }\n      @ex.try { \"candidate\" }\n      assert_raises(Scientist::Experiment::MismatchError) { @ex.run }\n    end\n\n    it \"raises a mismatch error if the candidate raises and the control doesn't\" do\n      Fake.raise_on_mismatches = true\n      @ex.use { \"control\" }\n      @ex.try { raise \"candidate\" }\n      assert_raises(Scientist::Experiment::MismatchError) { @ex.run }\n    end\n\n    it \"allows MismatchError to bubble up through bare rescues\" do\n      Fake.raise_on_mismatches = true\n      @ex.use { \"control\" }\n      @ex.try { \"candidate\" }\n      runner = -> {\n        begin\n          @ex.run\n        rescue\n          # StandardError handled\n        end\n      }\n      assert_raises(Scientist::Experiment::MismatchError) { runner.call }\n    end\n\n    it \"can be marshaled\" do\n      Fake.raise_on_mismatches = true\n      @ex.before_run { \"some block\" }\n      @ex.clean { \"some block\" }\n      @ex.compare_errors { \"some block\" }\n      @ex.ignore { false }\n      @ex.run_if { \"some block\" }\n      @ex.try { \"candidate\" }\n      @ex.use { \"control\" }\n      @ex.compare { |control, candidate| control == candidate }\n\n      mismatch = nil\n      begin\n        @ex.run\n      rescue Scientist::Experiment::MismatchError => e\n        mismatch = e\n      end\n\n      assert_kind_of(String, Marshal.dump(mismatch))\n    end\n\n    it \"can be marshal loaded\" do\n      assert_kind_of(Fake, Marshal.load(Marshal.dump(@ex)))\n    end\n\n    describe \"#raise_on_mismatches?\" do\n      it \"raises when there is a mismatch if the experiment instance's raise on mismatches is enabled\" do\n        Fake.raise_on_mismatches = false\n        @ex.raise_on_mismatches = true\n        @ex.use { \"fine\" }\n        @ex.try { \"not fine\" }\n\n        assert_raises(Scientist::Experiment::MismatchError) { @ex.run }\n      end\n\n      it \"doesn't raise when there is a mismatch if the experiment instance's raise on mismatches is disabled\" do\n        Fake.raise_on_mismatches = true\n        @ex.raise_on_mismatches = false\n        @ex.use { \"fine\" }\n        @ex.try { \"not fine\" }\n\n        assert_equal \"fine\", @ex.run\n      end\n\n      it \"respects the raise_on_mismatches class attribute by default\" do\n        Fake.raise_on_mismatches = false\n        @ex.use { \"fine\" }\n        @ex.try { \"not fine\" }\n\n        assert_equal \"fine\", @ex.run\n\n        Fake.raise_on_mismatches = true\n\n        assert_raises(Scientist::Experiment::MismatchError) { @ex.run }\n      end\n    end\n\n    describe \"MismatchError\" do\n      before do\n        Fake.raise_on_mismatches = true\n        @ex.use { :foo }\n        @ex.try { :bar }\n        begin\n          @ex.run\n        rescue Scientist::Experiment::MismatchError => e\n          @mismatch = e\n        end\n        assert @mismatch\n      end\n\n      it \"has the name of the experiment\" do\n        assert_equal @ex.name, @mismatch.name\n      end\n\n      it \"includes the experiments' results\" do\n        assert_equal @ex.published_result, @mismatch.result\n      end\n\n      it \"formats nicely as a string\" do\n        assert_equal <<-STR, @mismatch.to_s\nexperiment 'experiment' observations mismatched:\ncontrol:\n  :foo\ncandidate:\n  :bar\n        STR\n      end\n\n      it \"includes the backtrace when an observation raises\" do\n        mismatch = nil\n        ex = Fake.new\n        ex.use { \"value\" }\n        ex.try { raise \"error\" }\n\n        begin\n          ex.run\n        rescue Scientist::Experiment::MismatchError => e\n          mismatch = e\n        end\n\n        # Should look like this:\n        # experiment 'experiment' observations mismatched:\n        # control:\n        #   \"value\"\n        # candidate:\n        #   #<RuntimeError: error>\n        #     test/scientist/experiment_test.rb:447:in `block (5 levels) in <top (required)>'\n        # ... (more backtrace)\n        lines = mismatch.to_s.split(\"\\n\")\n        assert_equal \"control:\", lines[1]\n        assert_equal \"  \\\"value\\\"\", lines[2]\n        assert_equal \"candidate:\", lines[3]\n        assert_equal \"  #<RuntimeError: error>\", lines[4]\n        assert_match %r(test/scientist/experiment_test.rb:\\d+:in `block), lines[5]\n      end\n    end\n  end\n\n  describe \"before run block\" do\n    it \"runs when an experiment is enabled\" do\n      control_ok = candidate_ok = false\n      before = false\n      @ex.before_run { before = true }\n      @ex.use { control_ok = before }\n      @ex.try { candidate_ok = before }\n\n      @ex.run\n\n      assert before, \"before_run should have run\"\n      assert control_ok, \"control should have run after before_run\"\n      assert candidate_ok, \"candidate should have run after before_run\"\n    end\n\n    it \"does not run when an experiment is disabled\" do\n      before = false\n\n      def @ex.enabled?\n        false\n      end\n      @ex.before_run { before = true }\n      @ex.use { \"value\" }\n      @ex.try { \"value\" }\n      @ex.run\n\n      refute before, \"before_run should not have run\"\n    end\n  end\n\n  describe \"after run block\" do\n    it \"runs when an experiment is enabled\" do\n      control_ok = candidate_ok = false\n      after_result = nil\n      @ex.after_run { |result| after_result = result }\n      @ex.use { control_ok = after_result.nil? }\n      @ex.try { candidate_ok = after_result.nil? }\n\n      @ex.run\n\n      assert after_result, \"after_run should have run\"\n      assert after_result.matched?, \"after_run should be called with the result\"\n      assert control_ok, \"control should have run before after_run\"\n      assert candidate_ok, \"candidate should have run before after_run\"\n    end\n\n    it \"does not run when an experiment is disabled\" do\n      after_result = nil\n\n      def @ex.enabled?\n        false\n      end\n      @ex.after_run { |result| after_result = result }\n      @ex.use { \"value\" }\n      @ex.try { \"value\" }\n      @ex.run\n\n      refute after_result, \"after_run should not have run\"\n    end\n  end\n\n  describe \"testing hooks for extending code\" do\n    it \"allows a user to provide fabricated durations for testing purposes (old version)\" do\n      @ex.use { true }\n      @ex.try { true }\n      @ex.fabricate_durations_for_testing_purposes( \"control\" => 0.5, \"candidate\" => 1.0 )\n\n      @ex.run\n\n      cont = @ex.published_result.control\n      cand = @ex.published_result.candidates.first\n      assert_in_delta 0.5, cont.duration, 0.01\n      assert_in_delta 1.0, cand.duration, 0.01\n    end\n\n    it \"allows a user to provide fabricated durations for testing purposes (new version)\" do\n      @ex.use { true }\n      @ex.try { true }\n      @ex.fabricate_durations_for_testing_purposes({\n        \"control\" => { \"duration\" => 0.5, \"cpu_time\" => 0.4 },\n        \"candidate\" => { \"duration\" => 1.0, \"cpu_time\" => 0.9 }\n      })\n      @ex.run\n\n      cont = @ex.published_result.control\n      cand = @ex.published_result.candidates.first\n\n      # Wall Time\n      assert_in_delta 0.5, cont.duration, 0.01\n      assert_in_delta 1.0, cand.duration, 0.01\n\n      # CPU Time\n      assert_equal 0.4, cont.cpu_time\n      assert_equal 0.9, cand.cpu_time\n    end\n\n    it \"returns actual durations if fabricated ones are omitted for some blocks (old version)\" do\n      @ex.use { true }\n      @ex.try { sleep 0.1; true }\n      @ex.fabricate_durations_for_testing_purposes( \"control\" => 0.5 )\n\n      @ex.run\n\n      cont = @ex.published_result.control\n      cand = @ex.published_result.candidates.first\n      assert_in_delta 0.5, cont.duration, 0.01\n      assert_in_delta 0.1, cand.duration, 0.01\n    end\n\n    it \"returns actual durations if fabricated ones are omitted for some blocks (new version)\" do\n      @ex.use { true }\n      @ex.try do\n        start_time = Time.now\n        while Time.now - start_time < 0.1\n          # Perform some CPU-intensive work\n          (1..1000).each { |i| i * i }\n        end\n        true\n      end\n      @ex.fabricate_durations_for_testing_purposes({ \"control\" => { \"duration\" => 0.5, \"cpu_time\" => 0.4 }})\n      @ex.run\n\n      cont = @ex.published_result.control\n      cand = @ex.published_result.candidates.first\n\n      # Fabricated durations\n      assert_in_delta 0.5, cont.duration, 0.01\n      assert_in_delta 0.4, cont.cpu_time, 0.01\n\n      # Measured durations\n      assert_in_delta 0.1, cand.duration, 0.01\n      assert_in_delta 0.1, cand.cpu_time, 0.01\n    end\n  end\nend\n"
  },
  {
    "path": "test/scientist/observation_test.rb",
    "content": "describe Scientist::Observation do\n\n  before do\n    @experiment = Scientist::Experiment.new \"test\"\n  end\n\n  it \"observes and records the execution of a block\" do\n    ob = Scientist::Observation.new(\"test\", @experiment) do\n      start_time = Time.now\n      while Time.now - start_time < 0.1\n        # Perform some CPU-intensive work\n        (1..1000).each { |i| i * i }\n      end\n      \"ret\"\n    end\n\n    assert_equal \"ret\", ob.value\n    refute ob.raised?\n    assert_in_delta 0.1, ob.duration, 0.01\n    assert_in_delta 0.1, ob.cpu_time, 0.01\n  end\n\n  it \"stashes exceptions\" do\n    ob = Scientist::Observation.new(\"test\", @experiment) do\n      raise \"exception\"\n    end\n\n    assert ob.raised?\n    assert_equal \"exception\", ob.exception.message\n    assert_nil ob.value\n  end\n\n  describe \"::RESCUES\" do\n    before do\n      @original = Scientist::Observation::RESCUES.dup\n    end\n\n    after do\n      Scientist::Observation::RESCUES.replace(@original)\n    end\n\n    it \"includes all exception types by default\" do\n      ob = Scientist::Observation.new(\"test\", @experiment) do\n        raise Exception.new(\"not a StandardError\")\n      end\n\n      assert ob.raised?\n      assert_instance_of Exception, ob.exception\n    end\n\n    it \"can customize rescued types\" do\n      Scientist::Observation::RESCUES.replace [StandardError]\n\n      ex = assert_raises Exception do\n        Scientist::Observation.new(\"test\", @experiment) do\n          raise Exception.new(\"not a StandardError\")\n        end\n      end\n\n      assert_equal \"not a StandardError\", ex.message\n    end\n  end\n\n  it \"compares values\" do\n    a = Scientist::Observation.new(\"test\", @experiment) { 1 }\n    b = Scientist::Observation.new(\"test\", @experiment) { 1 }\n\n    assert a.equivalent_to?(b)\n\n    x = Scientist::Observation.new(\"test\", @experiment) { 1 }\n    y = Scientist::Observation.new(\"test\", @experiment) { 2 }\n\n    refute x.equivalent_to?(y)\n  end\n\n  it \"compares exception messages\" do\n    a = Scientist::Observation.new(\"test\", @experiment) { raise \"error\" }\n    b = Scientist::Observation.new(\"test\", @experiment) { raise \"error\" }\n\n    assert a.equivalent_to?(b)\n\n    x = Scientist::Observation.new(\"test\", @experiment) { raise \"error\" }\n    y = Scientist::Observation.new(\"test\", @experiment) { raise \"ERROR\" }\n\n    refute x.equivalent_to?(y)\n  end\n\n  FirstError = Class.new(StandardError)\n  SecondError = Class.new(StandardError)\n\n  it \"compares exception classes\" do\n    x = Scientist::Observation.new(\"test\", @experiment) { raise FirstError, \"error\" }\n    y = Scientist::Observation.new(\"test\", @experiment) { raise SecondError, \"error\" }\n    z = Scientist::Observation.new(\"test\", @experiment) { raise FirstError, \"error\" }\n\n    assert x.equivalent_to?(z)\n    refute x.equivalent_to?(y)\n  end\n\n  it \"compares values using a comparator proc\" do\n    a = Scientist::Observation.new(\"test\", @experiment) { 1 }\n    b = Scientist::Observation.new(\"test\", @experiment) { \"1\" }\n\n    refute a.equivalent_to?(b)\n\n    compare_on_string = -> (x, y) { x.to_s == y.to_s }\n\n    assert a.equivalent_to?(b, compare_on_string)\n\n    yielded = []\n    compare_appends = -> (x, y) do\n      yielded << x\n      yielded << y\n      true\n    end\n    a.equivalent_to?(b, compare_appends)\n\n    assert_equal [a.value, b.value], yielded\n  end\n\n  it \"compares exceptions using an error comparator proc\" do\n    x = Scientist::Observation.new(\"test\", @experiment) { raise FirstError, \"error\" }\n    y = Scientist::Observation.new(\"test\", @experiment) { raise SecondError, \"error\" }\n    z = Scientist::Observation.new(\"test\", @experiment) { raise FirstError, \"ERROR\" }\n\n    refute x.equivalent_to?(z)\n    refute x.equivalent_to?(y)\n\n    compare_on_class = -> (error, other_error) {\n      error.class == other_error.class\n    }\n    compare_on_message = -> (error, other_error) {\n      error.message == other_error.message\n    }\n\n    assert x.equivalent_to?(z, nil, compare_on_class)\n    assert x.equivalent_to?(y, nil, compare_on_message)\n  end\n\n  describe \"#cleaned_value\" do\n    it \"returns the observation's value by default\" do\n      a = Scientist::Observation.new(\"test\", @experiment) { 1 }\n      assert_equal 1, a.cleaned_value\n    end\n\n    it \"uses the experiment's clean block to clean a value when configured\" do\n      @experiment.clean { |value| value.upcase }\n      a = Scientist::Observation.new(\"test\", @experiment) { \"test\" }\n      assert_equal \"TEST\", a.cleaned_value\n    end\n\n    it \"doesn't clean nil values\" do\n      @experiment.clean { |value| \"foo\" }\n      a = Scientist::Observation.new(\"test\", @experiment) { nil }\n      assert_nil a.cleaned_value\n    end\n\n    it \"returns false boolean values\" do\n      a = Scientist::Observation.new(\"test\", @experiment) { false }\n      assert_equal false, a.cleaned_value\n    end\n\n    it \"cleans false values\" do\n      @experiment.clean { |value| value.to_s.upcase }\n      a = Scientist::Observation.new(\"test\", @experiment) { false }\n      assert_equal \"FALSE\", a.cleaned_value\n    end\n  end\n\nend\n"
  },
  {
    "path": "test/scientist/result_test.rb",
    "content": "describe Scientist::Result do\n  before do\n    @experiment = Scientist::Experiment.new \"experiment\"\n  end\n\n  it \"is immutable\" do\n    control = Scientist::Observation.new(\"control\", @experiment)\n    candidate = Scientist::Observation.new(\"candidate\", @experiment)\n\n    result = Scientist::Result.new @experiment, [control, candidate], control\n    assert result.frozen?\n  end\n\n  it \"evaluates its observations\" do\n    a = Scientist::Observation.new(\"a\", @experiment) { 1 }\n    b = Scientist::Observation.new(\"b\", @experiment) { 1 }\n\n    assert a.equivalent_to?(b)\n\n    result = Scientist::Result.new @experiment, [a, b], a\n    assert result.matched?\n    refute result.mismatched?\n    assert_equal [], result.mismatched\n\n    x = Scientist::Observation.new(\"x\", @experiment) { 1 }\n    y = Scientist::Observation.new(\"y\", @experiment) { 2 }\n    z = Scientist::Observation.new(\"z\", @experiment) { 3 }\n\n    result = Scientist::Result.new @experiment, [x, y, z], x\n    refute result.matched?\n    assert result.mismatched?\n    assert_equal [y, z], result.mismatched\n  end\n\n  it \"has no mismatches if there is only a control observation\" do\n    a = Scientist::Observation.new(\"a\", @experiment) { 1 }\n    result = Scientist::Result.new @experiment, [a], a\n    assert result.matched?\n  end\n\n  it \"evaluates observations using the experiment's compare block\" do\n    a = Scientist::Observation.new(\"a\", @experiment) { \"1\" }\n    b = Scientist::Observation.new(\"b\", @experiment) { 1 }\n\n    @experiment.compare { |x, y| x == y.to_s }\n\n    result = Scientist::Result.new @experiment, [a, b], a\n\n    assert result.matched?, result.mismatched\n  end\n\n  it \"does not ignore any mismatches when nothing's ignored\" do\n    x = Scientist::Observation.new(\"x\", @experiment) { 1 }\n    y = Scientist::Observation.new(\"y\", @experiment) { 2 }\n\n    result = Scientist::Result.new @experiment, [x, y], x\n\n    assert result.mismatched?\n    refute result.ignored?\n  end\n\n  it \"uses the experiment's ignore block to ignore mismatched observations\" do\n    x = Scientist::Observation.new(\"x\", @experiment) { 1 }\n    y = Scientist::Observation.new(\"y\", @experiment) { 2 }\n    called = false\n    @experiment.ignore { called = true }\n\n    result = Scientist::Result.new @experiment, [x, y], x\n\n    refute result.mismatched?\n    refute result.matched?\n    assert result.ignored?\n    assert_equal [], result.mismatched\n    assert_equal [y], result.ignored\n    assert called\n  end\n\n  it \"partitions observations into mismatched and ignored when applicable\" do\n    x = Scientist::Observation.new(\"x\", @experiment) { :x }\n    y = Scientist::Observation.new(\"y\", @experiment) { :y }\n    z = Scientist::Observation.new(\"z\", @experiment) { :z }\n\n    @experiment.ignore { |control, candidate| candidate == :y }\n\n    result = Scientist::Result.new @experiment, [x, y, z], x\n\n    assert result.mismatched?\n    assert result.ignored?\n    assert_equal [y], result.ignored\n    assert_equal [z], result.mismatched\n  end\n\n  it \"knows the experiment's name\" do\n    a = Scientist::Observation.new(\"a\", @experiment) { 1 }\n    b = Scientist::Observation.new(\"b\", @experiment) { 1 }\n    result = Scientist::Result.new @experiment, [a, b], a\n\n    assert_equal @experiment.name, result.experiment_name\n  end\n\n  it \"has the context from an experiment\" do\n    @experiment.context :foo => :bar\n    a = Scientist::Observation.new(\"a\", @experiment) { 1 }\n    b = Scientist::Observation.new(\"b\", @experiment) { 1 }\n    result = Scientist::Result.new @experiment, [a, b], a\n\n    assert_equal({:foo => :bar}, result.context)\n  end\n\nend\n"
  },
  {
    "path": "test/scientist_test.rb",
    "content": "describe Scientist do\n  it \"has a version or whatever\" do\n    assert Scientist::VERSION\n  end\n\n  it \"provides a helper to instantiate and run experiments\" do\n    obj = Object.new\n    obj.extend(Scientist)\n\n    r = obj.science \"test\" do |e|\n      e.use { :control }\n      e.try { :candidate }\n    end\n\n    assert_equal :control, r\n  end\n\n  it \"provides a module method to instantiate and run experiments\" do\n    r = Scientist.run \"test\" do |e|\n      e.use { :control }\n      e.try { :candidate }\n    end\n\n    assert_equal :control, r\n  end\n\n  it \"provides an empty default_scientist_context\" do\n    obj = Object.new\n    obj.extend(Scientist)\n\n    assert_equal Hash.new, obj.default_scientist_context\n  end\n\n  it \"respects default_scientist_context\" do\n    obj = Object.new\n    obj.extend(Scientist)\n\n    def obj.default_scientist_context\n      { :default => true }\n    end\n\n    experiment = nil\n\n    obj.science \"test\" do |e|\n      experiment = e\n      e.context :inline => true\n      e.use { }\n    end\n\n    refute_nil experiment\n    assert_equal true, experiment.context[:default]\n    assert_equal true, experiment.context[:inline]\n  end\n\n  it \"runs the named test instead of the control\" do\n    obj = Object.new\n    obj.extend(Scientist)\n\n    behaviors_executed = []\n\n    result = obj.science \"test\", run: \"first-way\" do |e|\n      e.try(\"first-way\") { behaviors_executed << \"first-way\" ; true }\n      e.try(\"second-way\") { behaviors_executed << \"second-way\" ; true }\n    end\n\n    assert_equal true, result\n    assert_equal [ \"first-way\" ], behaviors_executed\n  end\n\n  it \"runs control when there is a nil named test\" do\n    obj = Object.new\n    obj.extend(Scientist)\n\n    behaviors_executed = []\n\n    result = obj.science \"test\", nil do |e|\n      e.use { behaviors_executed << \"control\" ; true }\n      e.try(\"second-way\") { behaviors_executed << \"second-way\" ; true }\n    end\n\n    assert_equal true, result\n    assert_equal [ \"control\" ], behaviors_executed\n  end\nend\n"
  },
  {
    "path": "test/test_helper.rb",
    "content": "require \"minitest/autorun\"\n\n$LOAD_PATH.unshift(File.expand_path(File.join(__dir__, \"../lib\")))\nrequire \"scientist\"\n"
  }
]